text:
Q: Работа с Cursor Здравствуйте. Пишу небольшое приложение – справочник грибов. Есть 3  класса – 1 MainActivity с Listview , 2 класс -  Information – будет выводить информацию о грибах в зависимости от того на какой элемент ListView кликнул пользователь, информация о каждом грибе будет браться из БД,  3 класс  - работа с Базой данных SqLite.
Вот код моей Базы данных:
  public class DataBaseHelper extends SQLiteOpenHelper implements BaseColumns {
        private SQLiteDatabase sqdb;
        private static final String DATABASE_NAME = "mushrooms.db";
        private  static final int DATABASE_VERSION = 1;
        public static final String TABLE_NAME = "mushrooms_table";
        public static final String Mushroom1 = "mushroom1";
        public static final String Mushroom2 = "mushroom2";

        private static final String SQL_CREATE_ = "create table " + TABLE_NAME +" ("
                + DataBaseHelper._ID + " integer primary key autoincrement,"
                + Mushroom1 + " text,"
                + Mushroom2 + " text" + ");";

        public DataBaseHelper(Context context) {
            super(context , DATABASE_NAME , null , DATABASE_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(SQL_CREATE_);
            db.beginTransaction();
            try {
                ContentValues cv = new ContentValues();
                cv.put(Mushroom1 , "Білий гриб - один з найбільш цінних грибів. Росте в хвойних, " +
                        "листяних і змішаних лісах, звичайно на прогалинах і " +
                        "лісових узліссях, у рідкому молодому ялиннику, " +
                        "на вологому ґрунті з червня по жовтень. " +
                        "Забарвлення шляпки в дубових лісах темно-бура," +
                        " у листяних - світло-бура, у соснових - темно-бура з фіолетовим відтінком," +
                        " у ялинових - червонясто-бура. Нижня сторона капелюшка в молодих білих грибів біла, " +
                        "з віком жовтіє і нарешті стає жовтувато-зеленою.");

                 cv.put(Mushroom2 , "Існує кілька різновидів моховиків. " +
                         "Найбільш відомі жовто-бурий і зелений моховик. " +
                         "Жовто-бурий моховик росте в соснових лісах. " +
                         "Забарвлення сухого бархатистого капелюшка жовте чи жовтувато-буре. " +
                         "Зелений чи глухий моховик росте в хвойних і листяних лісах. " +
                         "Забарвлення бархатистого капелюшка жовтувато-зеленувате чи коричнювато - зеленувате. " +
                         "Нижня сторона капелюшка і м'якоть жовтуваті. М'якоть на зламі синіє. " +
                         "Моховики використовуються для готування других блюд (найкраще жарити) і маринування. " +
                         "При сушінні моховики чорніють.");

                 sqdb.insert(TABLE_NAME , null , cv);

                 db.setTransactionSuccessful();
            }finally {
                db.endTransaction();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }

        public String getInformation(int id) {
            sqdb = this.getReadableDatabase();
            String selection = "_id = ?";
            String[] selectionArgs = new String[] {String.valueOf(id)};
            Cursor  cursor = sqdb.query(TABLE_NAME , null , selection , selectionArgs , null , null, null);

    // работа с курсором
            sqdb.close();
            cursor.close();
        }
    }

Так вот вопрос ,  видите я пишу метод  public String getInformation(int id), это метод будет вызываться во 2 классе - Information для того чтобы в зависиомсти от выбраного пункта бралась инфа из бд ,  с очередью я разобрался, теперь надо как то извлечь данные правильно?
будет ли правильно дописать в этод метод такой код:
 if(cursor != null) {
     if (cursor.moveToFirst()) {
         do {
             String mush = cursor.getString(cursor.getColumnIndex(Mushroom1));
         }while (cursor.moveToNext());
      }
  }
  return mush;

Мне нужно чтобы в зависимости от id выводило информацию. Подскажите пожалуйста как правильно тут использовать getColumnIndex.

A: Согласно структуры базы данных, при запросе по полю "_id" будет выдана только одна запись, содержащая поля "_id", "Mushroom1" и "Mushroom2".
Таким образом, функция getInformation(int id) в том варианте, в котором она сейчас написана, должна выводить только сведения из одного поля таблицы и иметь вид:
public String getInformation(int id) {
sqdb = this.getReadableDatabase();
String selection = "_id = ?";
String[] selectionArgs = new String[] {String.valueOf(id)};
Cursor  cursor = sqdb.query(TABLE_NAME , null , selection , selectionArgs , null , null, null);
if(cursor.getCount() > 0){ // Проверка на наличие данных
    cursor.moveToFirst();
    return cursor.getString(cursor.getColumnIndex(Mushroom1);
} else {
    return null;
}
cursor.close();

}
Для того, чтобы сразу получить все значения из строки таблицы стоит несколько изменить функцию:
public HashMap<String, Object> getInformation(final int id){
    HashMap<String, Object> result = new HashMap<String, Object>();
    sqdb = this.getReadableDatabase();
    String selection = "_id = ?";
    String[] selectionArgs = new String[] {String.valueOf(id)};
    Cursor  cursor = sqdb.query(TABLE_NAME , null , selection , selectionArgs , null , null, null);
    if(cursor.getCount() > 0){
        cursor.moveToFirst();
        result.put("id", cursor.getInt(cursor.getColumnIndex("_id");
        result.put("Mushroom1", cursor.getInt(cursor.getColumnIndex("Mushroom1");
        result.put("Mushroom2", cursor.getInt(cursor.getColumnIndex("Mushroom2");
    }
    cursor.close();
    retrun result;
}


text:
Q: adding pom file on svn repository maven OK, so I am using maven to try to add a pom file to a svn repository:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>my-app</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>
    <name>my-app</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
    <build>
    <plugins>
        <plugin>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>1.5</version>
            <configuration>
            </configuration>
        </plugin>
    </plugins>
</build>
<scm>
    <connection>scm:svn:URL</connection>
</scm>
<distributionManagement>
    <repository>
        <id>test</id>
        <name>new-test</name>
        <url>URL</url>
        <uniqueVersion>false</uniqueVersion>
    </repository>
</distributionManagement>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
      </dependency>
</dependencies>

That's what my pom.xml file looks like currently; of course the URL is my url and the username and pass are my actual username and password
I am very confused on the commands I should use to upload this.  If anyone could help, I would be very grateful.  Also, I am not sure if my pom.xml file is configured correctly.

A: A quick Google search reveals the documentation at the maven-scm-plugin site on apache.org here and here.
Based on my understanding of Maven and a quick scan through these documents, you should probably be doing the following:

*

*I think that you are missing a connectionType declaration in the configuration section for the plug-in.

*I'm not sure what your use case is for hanging the plug-in off of the install goal.

*Use mvn scm:add initially, to add the file(s) to your SVN workspace.

*Use mvn -Dmessage="<commit_log_here>" scm:checkin to commit the changes to SVN.

*Use mvn scm:update to pull updates from SVN.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do strings look from the compiler's point of view? In C, the compiler has a pointer to the start of the string and has an end-symbol ('\0'). If a user wants to calculate the length of the string, the compiler has to count elements of the string array until it finds '\0'.
In UCSD-strings, the compiler has the length of the string in the first symbols.
And what does the compiler think about C#-strings? Yes, from the user's point of view String is an object that has a field Length, I'm not talking about high-level stuff. I want to know deep algorithms; e.g., how does the compiler calculate the length of the string?

A: In C# the length of the string is stored in the object in a private field ([NonSerialized]private int  m_stringLength;), it doesn't have to be calculated at run-time.
The source code of String class is available online.

A: Let's execute the following code:
string s = "123";
string s2 = "234";
string s3 = s + s2;
string s4 = s2 + s3;
Console.WriteLine(s + s2);

Now let's put a breakpoint at the last line and open the memory window:

Writing s3 in the memory window we can see the 2 (s3 and s4) strings allocated one after the other with 4 bytes of size at the beginning.
Also you can see that other memory is allocated such as the strings class type token and other string class data.
The string class itself contains a member private int  m_stringLength; which contains the length of the string, this also makes string.Concat() execute super fast (by allocating the whole length at the beginning):
int totalLength = str0.Length + str1.Length + str2.Length;

String result = FastAllocateString(totalLength);
FillStringChecked(result, 0, str0);
FillStringChecked(result, str0.Length, str1);
FillStringChecked(result, str0.Length + str1.Length, str2);

What I find a little strange is that the implementation of IEnumerable<char>.Count() for string is done using the default implementation which means iterating items one by one unlike ICollection<T>s like List<T> where the IEnumerable<char>.Count() is implemented by taking its ICollection<T>.Count property.


text:
Q: Node JS TCP Proxy: Set up HTTP Tunnel using Node JS I'm trying to implement a TCP proxy in Node JS. I only have some experience with Javascript so I met a lot of problems along the way. I've done a lot of searching for this one but had no luck.
I want to implement a two-hop TCP connection for HTTPS proxy. Here is part of my code.
var net = require('net');

var server = net.createServer(function(clientSock) {

    var connected = false;

    var serverSock;

    clientSock.on('data', function(clientData) {

        if (connected) {

            // Send future messages if is connected
            serverSocet.write(clientData);

        } else {

            var host = // get from data
            var port = // get from data

            if (clientData is a CONNECT request) {

                // Create a new socket to server
                if (!serverSock) {
                    serverSock = new net.Socket();

                    serverSock.connect(port, host, function() {

                        // Send the CONNECT request (Client Hello)
                        serverSock.write(clientData);

                        connected = true;

                        clientSock.write('HTTP/1.1 200 OK\r\n');
                   });

                   serverSock.on('data', function(serverData) {
                        clientSock.write(serverData);
                   });
               }
          }
     });
 });

I used Wireshark to capture the packets sent if I visit https://www.google.com. If I don't use my proxy, the "Client Hello" message is sent in TLS v1.2. But if I use my proxy, it is sent by SSL. The server always reject my CONNECT request and send back a reset request.
I also tried the TLS API in Node JS. The server accepted my CONNECT request but always request me to start a new session after the Key Exchange. The browser will close the socket and create a new socket. But it never loaded the page...
I've spent a whole day on this single problem. I believe I can use TCP socket to implement HTTP Tunnel. Please help... Thanks a lot!!

A: Problem solved!
To make TCP socket use TLS v1.2 while dealing with HTTPS, just put this option, {allowHalfOpen: true}, as parameter when creating the sockets.
New Code would look like this:
var net = require('net');

                               // option here
var server = net.createServer({allowHalfOpen: true}, function(clientSock) {

var connected = false;

var serverSock;

clientSock.on('data', function(clientData) {

    if (connected) {

        // Send future messages if is connected
        serverSocet.write(clientData);

    } else {

        var host = // get from data
        var port = // get from data

        if (clientData is a CONNECT request) {

            // Create a new socket to server
            if (!serverSock) {

                                             // Option here
                serverSock = new net.Socket({allowHalfOpen: true});

                serverSock.connect(port, host, function() {

                    // Don't need to forward hello message from client
                    // Connect method automatically sends it for you
                    //serverSock.write(clientData);

                    connected = true;

                    clientSock.write('HTTP/1.1 200 OK\r\n');
               });

               serverSock.on('data', function(serverData) {
                    clientSock.write(serverData);
               });
           }
      }
 });


text:
Q: Optional inner join SQL I have this SQL code that does an inner join on 2 tables:
SELECT
    c.*,
    dc1.user_pemilik_nip AS lokasi1,
    dc2.user_pemilik_nip AS lokasi2
FROM
    certificate c
INNER JOIN
    data_certificate dc1 ON c.seri = dc1.certificate_seri
                         AND dc1.part_certificate_name = 'Surat Ukur'
INNER JOIN
    data_certificate dc2 ON c.seri = dc2.certificate_seri
                         AND dc2.part_certificate_name = 'BT dan STP'

As you can see, I inner join the same table twice (data_certificate to dc1 and dc2) with where/on condition is part_certificate_name, but, this sql script can't handle if 2 of condition for part_certificate_name there's only one, so seri with 1 part_certificate_name not showed, only seri with 2 part_certificate_name, how to handle that case, and btw is there simple SQL code similar with my case?

A: I think you want LEFT JOIN:
SELECT c.*, dc1.user_pemilik_nip as lokasi1, dc2.user_pemilik_nip as lokasi2
FROM certificate c LEFT JOIN
     data_certificate dc1
     ON c.seri = dc1.certificate_seri AND
        dc1.part_certificate_name = 'Surat Ukur' LEFT JOIN
     data_certificate dc2
     ON c.seri = dc2.certificate_seri AND
        dc2.part_certificate_name = 'BT dan STP'

A: If for each certificate_seri in data_certificate there is only 1 part_certificate_name, either 'Surat Ukur' or 'BT dan STP', then you need only 1 join for both cases with the operator IN in the ON clause and with CASE expressions in the SELECT list to distinguish the columns:
SELECT c.*,
       CASE WHEN dc.part_certificate_name = 'Surat Ukur' THEN dc.user_pemilik_nip AS lokasi1,
       CASE WHEN dc.part_certificate_name = 'BT dan STP' THEN dc.user_pemilik_nip AS lokasi12
FROM certificate c INNER JOIN data_certificate dc
ON c.seri = dc.certificate_seri AND dc.part_certificate_name IN ('Surat Ukur', 'BT dan STP');

If there may exist both values for each certificate_seri, then first aggregate in data_certificate and then join to certificate:
SELECT c.*, dc.lokasi1, dc.lokasi12
FROM certificate c
INNER JOIN (
  SELECT certificate_seri,
         MAX(CASE WHEN part_certificate_name = 'Surat Ukur' THEN user_pemilik_nip END) lokasi1,
         MAX(CASE WHEN part_certificate_name = 'BT dan STP' THEN user_pemilik_nip END) lokasi2
  FROM data_certificate
  WHERE part_certificate_name IN ('Surat Ukur', 'BT dan STP')
  GROUP BY certificate_seri
) dc ON c.seri = dc.certificate_seri;


text:
Q: Facebook and Whatsapp meta tag cache issue Problem Statement
I share URLs via Facebook and Whatsapp. These messaging apps tend to generate a "rich preview" in the form of a thumbnail for the link shared. Everything seems to work fine thus far
But if I change the content which my link points to then the next time I share the same link with a completely different person, the changes are not reflected! This applies to rich preview thumbnails in both Facebook and WhatsApp. The new person whom I messaged, still sees the old thumbnail that the previous user received from me.
For example, here is a snapshot of the thumbnail rendered by the messaging apps after a message with a link was sent by me to ALICE:

And here is a snapshot of another thumbnail rendered by the messaging apps after I edited the content to which my link points. I changed the name to Pro3 and price to 549 and sent a new message to BOB ... but BOB sees the same thumbnail preview as ALICE!
Not good solutions

*

*Changing the URL ever so slightly is not a solution that is a good fit for me.

*The scrape option on Facebook debugger would only work for that platform and it is not a good fit because it must be done manually, which means it cannot scale!

What I need help with
My preferred solution is to use Cache-Control and Pragma tags (as per web-standards) for disabling cache but it doesn't seem to work.
Here is my code
 '<title>' + metaData.title + '</title>' +
    '<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">\n' +
    '<meta http-equiv="Pragma" content="no-cache">\n' +
    '<meta http-equiv="Expires" content="0">\n' +
    '<meta http-equiv="refresh" content="0; url=http://my.site.com/my/products">' +
    '<meta name="description" content="' + metaData.description + '" />\n' +
    '<meta property="og:type" content="product" />\n' +
    '<meta property="og:title" content="' + metaData.title + '" />\n' +
    '<meta property="og:description" content="' + metaData.description + '" />\n' +
    '<meta property="og:image" content="' + metaData.imageUrl + '" />\n' +
    '<meta property="og:image:width" content="' + metaData.imgWidth + '"/>\n' +
    '<meta property="og:image:height" content="' + metaData.imgHeight + '" />\n' +
    '<meta property="og:image:alt" content="' + metaData.imgAlt + '"/>' +
    '<meta property="og:url" content="' + metaData.url + '" />\n' +
    '<meta name="og_site_name" property="og:site_name" content="' + metaData.domainName + '" />' +
    '<meta name="keywords" content="' + metaData.keywords + '">' +

Can someone please suggest another approach worth trying or help me fix whatever I might be doing wrong with the current approach?

A: I expect this issue is relative to the Facebook and Whatsapp CDN...
Apparently on Facebook you may use the debugger tool and force Facebook to refresh the URL it has cached. (maybe use API to force the refresh), but I did not find this option on Whatsapp ...
The best solution is one of your "Not good solutions":

Changing the URL

which force implicitly the CDN to re-cache/update the new content.

A: There is no simple solution to this. This is like controlling what someone else is doing with your URL. You want them to scrape you every time you share a URL but the sharing service would want to cache information, so that resources are saved on their end for fetching the resources
So what can you do?

*

*You can change the url when you share it. I usually add a ?_=<epochtim> to do so. This will work on your shortened url as well

*You could see of a 302 Temporary Redirect discourages the service to cache the url. So in that case you will have url http://site/r/<path> and it should cause a 302 withhttp://site/?_=`. If looking at the 302 these sites decide to scrape again, then the approach could help

There is no fool proof solution here and I don't think one can expect one

A: You don't need to add the no-cache meta tag in to your codes to control the cache method, somehow it's is bad solution related to the performance as standard (should caches what we need to cache).
In this case I think you should prevent the caches just for what you need only. You can add the versioning as timestamp at last. Something like this:
<meta property="og:image" content="' + metaData.imageUrl + '?v=' + timestamp + '" />\n
Go with this way, the file will be re-downloaded whenever your app is loaded because in understanding, the file is always new. As I said above, just add into your meta tag which you need to avoid caching.


text:
Q: Сериализацация объектов в Json У меня есть базовый класс Base, и два класса которые его расширяют Fork,Message. Так же есть класс Page, в котором содержится массив (в котором будут храниться объекты классов Fork,Message)
Возможно ли настроить сериализацию\десериализацию класса page в json?
class Base implements{
/**
 * @var string
 */
private $id;

/**
 * @return string
 */
public function getId(): string
{
    return $this->id;
}

/**
 * @param string $id
 */
public function setId(string $id): void
{
    $this->id = $id;
}

}
class Fork extends Base{
/**
 * @var string
 */
private $childrens;

/**
 * @return string
 */
public function getChildrens(): string
{
    return $this->childrens;
}

/**
 * @param string $childrens
 */
public function setChildrens(string $childrens): void
{
    $this->childrens = $childrens;
}
}

class Message extends Base{
/**
 * @var string
 */
private $inputValue;

/**
 * @return string
 */
public function getInputValue(): string
{
    return $this->inputValue;
}

/**
 * @param string $inputValue
 */
public function setInputValue(string $inputValue): void
{
    $this->inputValue = $inputValue;
}
}

class Page{

/**
 * @var Base[]
 */
private $arr = array();

/**
 * @return Base[]
 */
public function getArr(): array
{
    return $this->arr;
}

/**
 * @param Base[] $arr
 */
public function setArr(array $arr): void
{
    $this->arr = $arr;
}
}

Перешел из java, там можно настроить Jackson аннотациями, возможно и в php есть хорошая библиотека для этого дела? Спасибо за помощь.

A: Есть конечно - воспользуйтесь, например, компонентом Symfony - Serializer


text:
Q: EOL while scanning string literal even using r I am trying to define a name for a long server folder path below.  May I know why I still get "EOL while scanning string literal" error?  Many thanks.
path= (r '\\hbap.adroot.abb\HK\Finance\00210602\AMH_A2R\1KY\Drv Reengine\Python\')

A: Its not allowed to put a space between the 'r' and the string. However i suggest just doubling the backslashes to escape them like this:
path= ("\\\\hbap.adroot.abb\\HK\\Finance\\00210602\\AMH_A2R\\1KY\\Drv Reengine\\Python\\")

Alternativly, you can just leave out the backslash at the end and do this:
path= (r"\\hbap.adroot.abb\HK\Finance\00210602\AMH_A2R\1KY\Drv Reengine\Python")

All is good, as long as you escape the backslashes and dont have the string ending with a \ (except if that ending backslash is doubled)


text:
Q: Hiding GitHub token in .gitconfig I would like to store all of my dotfiles on GitHub, including .gitconfig which requires me to hide the GitHub token in the .gitconfig.
To do so I have a ".gitconfig-hidden-token" file which is the file I intend to edit and put under git that hides the token:
...
[github]
user = giuliop
token = --hidden--
...

And a shell script which I need to launch if I modify the ".gitconfig-hidden-token" file  to create the ".gitconfig" file:
cp .gitconfig .gitconfig.backup
sed 's/--hidden--/123456789/' .gitconfig-hidden-token > .gitconfig

The drawback is the need to manually launch the script everytime I modidy the file. Is there a better, fully automated way to do this?

A: I just fixed this up for myself.  The "proper" way to solve the issue is to split your gitconfig into two files, a public one with the alias/config/etc, and a private file that keeps your username and secrets. Like so...

From https://github.com/ddopson/dotfiles ...
.gitconfig:
[include]
  # For username / creds / etc
  path = ~/.gitconfig.local

[alias]
  ...

.gitconfig.local:
[user]
  user = ddopson
  name = Dave Dopson
  email = ddopson@gmail.com
  token = a123uber456secret789ceprivate000key78

[credential]
  helper = osxkeychain

.gitignore:
/.gitconfig.local

A: You can now include another file in your gitconfig. You could put your github section in that extra file. See this question: Is it possible to include a file in your .gitconfig

A: Add your .gitconfig with git add -N.
Then git add -p it, edit the hunk, replace the token with anything, and push that. No need for an extra file this way.
Addendum: on additional modifications of your file, use git add -p again, and edit the hunk so that your initial manipulation not be overwritten.

A: I made a script to update my dotfiles repo, it also redacts sensitive information such as my github token. I don't think the github token is used by GitHub anymore though, but correct me if I'm wrong.
You can view my script here.


text:
Q: Calling indices in an expression while iterating over a variable number of indices (Python) I want to iterate over a variable number of indices given by the length of a list, using the values on the list as the ranges. Further, I want to call the indices in my expression.
For example, if I have a list [2,4,5], I would want something like:
import itertools

for i0, i1, i2 in itertools.product(range(2),range(4),range(5)):
    otherlist[i0]**i0 + otherlist[i2]**i2

The closest I can get is
for [i for i in range(len(mylist))] in itertools.product(*[range(i) for i in mylist]):

But I don't know how to call the indices from here.

A: You were so close already. When you use a for statement, I find it best to
keep the target list simple and access components of the target list in
the for-loop; in this code, the tuples generated by product().
import itertools

mylist = [2,4,5]
otherlist = list(range(5))

for t in itertools.product(*[range(i) for i in mylist]):
    print(otherlist[t[0]]**t[0] + otherlist[t[2]]**t[2])
# 2
# 2
# 5
# 28
# 257
# ...


text:
Q: Setting up LDAP Connection - LDAPError Invalid Credentials I am trying to connect to via LDAP for the first time. I am just trying to simply check if a user can login. After trying to connect I am getting an invalid credentials error 49 and error code 81 server is unavailable. I am passing the right user credentials so this should be validating and I am able to connect via JXplorer.
In JXplorer I have my host as ldap.my.edu port as 389
User dn as: Uid=myuser,OU=People, DC=ua,DC=edu
then mypass.
I believe I am not properly translating this to LdapConnection and the network credential. This is my first time so any help would be very appreciated.
            const string server = "ldap.my.edu:389/OU=People,DC=my,DC=edu";
            const string domain = "ldap.my.edu";
            string password = "mypass";
            string userName = "myuser";

            try
            {
                using (var ldapConnection = new LdapConnection(server))
                {

                    var networkCredential = new NetworkCredential(userName, password, domain);
                    ldapConnection.SessionOptions.SecureSocketLayer = true;
                    ldapConnection.AuthType = AuthType.Negotiate;
                    ldapConnection.Bind(networkCredential);
                }

A: If you don't have SSL (LDAPS) enabled on this server, which looks to be the case, then you'll want to make sure you set :
ldapConnection.SessionOptions.SecureSocketLayer = false

Or, you can just not set it at all - LdapConnection will default to unsecured port 389 (LDAP) by default, if this isn't explicitly set.
An example, using the values you provided in your question, would be something like this (note that I'm applying the domain to the NetworkCredential and not the LdapConnection class itself) :
// the username and password to authenticate
const string domain = "OU=People,DC=my,DC=edu";
string password = "mypass";
string userName = "myuser";

// define your connection
LdapConnection ldapConnection = new LdapConnection("ldap.my.edu:389");

try
{
   // authenticate the username and password
   using (ldapConnection)
   {
       // pass in the network creds, and the domain.
       var networkCredential = new NetworkCredential(username, password, domain);

       // if we're using unsecured port 389, set to false. If using port 636, set this to true.
       ldapConnection.SessionOptions.SecureSocketLayer = false;

       // since this is an internal application, just accept the certificate either way
       ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };

       // to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
       ldapConnection.AuthType = AuthType.Basic;

       // authenticate the user
       ldapConnection.Bind(networkCredential);
   }
   catch (LdapException ldapException)
   {
       //Authentication failed, exception will dictate why
   }
}

A: Try port 3268 for Global Catalog


text:
Q: Setting up JCup and JFlex under Eclipse I need to configure JCup and JFlex under Eclipse somehow. I have found that:
http://itee.uq.edu.au/~comp4403/assignments/Eclipse-Setup.html?print=1
and done almost everything but I do lack build-cup.xml andbuild-flex.xml which are necessary later
Under tab Main for Buildfile browse workspace and from within your assignment 2 project select A2 and then select "build-cup.xml" and then OK

How can I do set this up? I just need the simplest way to use JCup and JFlex

A: I have had a similar assignment. However, to be honest I just used a text editor like Sublime Text 2 or Atom to manually write my Parser.cup and Scanner.jflex files in a text editor. There is simple syntax checking in both editors if you set the view to "Java". In my opinion this is the best way.
If you are adamant on using Eclipse, you can download:
http://cup-lex-eclipse.sourceforge.net/installation.html
Your question was less about installation hence my answer is a bit shorter.


text:
Q: SimpleDateFormat And Arabic Locale I want to format my date to Arabic locale but it doesn't work on my Galaxy Tab2 also doesn't work on Galaxy Note and gives me two different results.
Here is my code:
DateFormat format = new SimpleDateFormat("EEEE yyyy/MM/dd", new Locale(
            "ar"));
    String formatedDate = format.format(Calendar.getInstance().getTime());

Note that when I check for supported locales, I find that Android 4.0 on my Galaxy Tab2 does. But I didn't find any Arabic locales.
Locale[] supportedLocales = Locale.getAvailableLocales();

Is there any workaround to solve this issue or any library I can use for that?
NOTE:
On Roomed Android version (Android 4.1) from CyanogenMod, it works very well and support Arabic locales.

A: What it seems that the devices you bought has some Android builds not prepared for your region. So they remove Arabic support for some reasons (like to get small ROM).
May be better if get another device made for your region or flash new ROM that support Arabic (for MEA, Middle East Area) to your devices. But check for same Hardware version, You can break it.


text:
Q: Running Time of Algorithm - If statements inside While loop I have this example
A = 2,1,8,4,3,6 // c1, n
n = 6 // c2, n
i = 1 // c3, n
H = 2 // c4, n
inv = 0 // c5, n
while H <= n    // c6, n(n+1)/2-1
    if A[i] > A[H] && !H = n // c7, n(n-1)/2
        inv = inv + 1
        H = H + 1
    else if A[i] > A[H] && H = n // c10, n(n-1)/2
        inv = inv + 1
        i = i + 1
        H = i + 1
    else if A[i] < A[H] && !H = n // c14, n(n-1)/2
        H = H + 1
    else if A[i] < A[H] && H = n // c16, n(n-1)/2
        i = i + 1
        H = i + 1
print inv // c19, n

My question is how many n times will the code inside the if statements run in this example?

A: First, to understand this code, some assumptions must be made:

*

*The array A is 1-indexed based, i.e. the first element is accessed as A[1].

*The elements in A are unique - duplicate values are not allowed.

*The expression !H = n means H is not equal to n
The loop condition is H <= n, so let's see when this could become false.
We can see that as long as H < n, an iteration will increment H with one (either in the first if block, or in the third).
When H reaches n, i is incremented (and only then), and H becomes i+1 (in the second or last if block).
At one point i will become n, and then H will be set to i+1 again, which is the only way H can get a value that is greater than n, at which point the loop stops.
So, in other words, this loop makes i go from 1 to n, and for each of those values of i, H runs from n+1 to n.
This really means the tuple (i,H) takes all possible pairs from the range 1...n where i < H. This number of pairs is thus n(n-1)/2 (also noted C(n,2)).
In the example n = 6, so the number of pairs (iterations) is 6(6-1)/2 = 15.
The following JavaScript implementation demonstrates that a loop counter indeed reaches the count of 15:

// Must add an element at index 0, since the
// original code assumes 1-based indexing
A = [null,2,1,8,4,3,6] // c1, n
n = 6 // c2, n
i = 1 // c3, n
H = 2 // c4, n
inv = 0 // c5, n
loopCounter = 0
while (H <= n) {    // c6, n(n+1)/2-1
    loopCounter++; // count it!!
    if (A[i] > A[H] && H != n) { // c7, n(n-1)/2
        inv = inv + 1
        H = H + 1
    } else if (A[i] > A[H] && H == n) { // c10, n(n-1)/2
        inv = inv + 1
        i = i + 1
        H = i + 1
    } else if (A[i] < A[H] && H != n) { // c14, n(n-1)/2
        H = H + 1
    } else if (A[i] < A[H] && H == n) { // c16, n(n-1)/2
        i = i + 1
        H = i + 1
    }
}
console.log('inv = ', inv) // c19, n
console.log('iterations = ', loopCounter)


text:
Q: Label last set of rows in grouped dataset with Pandas EDIT: problem below given the df.assign(Flag=1 - df.duplicated(['id', 'quarter', 'lot'], keep='last')) method suggested below
 index   mkid     ordernumber quarter lotnumber1 order_xldate  Flag
441670  10176228  0108595504  2015Q2    12947-1   2015-04-09     0
441211  10176228  0108663905  2015Q2    12947-1   2015-04-29     1
450008  10176228  0108663905  2015Q2     129161   2015-04-29     1
440268  10176228  0108779992  2015Q2    12987-1   2015-05-29     0
448187  10176228  0108779992  2015Q2    12848-1   2015-05-29     1
439085  10176228  0108895691  2015Q2    12987-1   2015-06-29     1
446123  10176228  0108895691  2015Q2    12965-1   2015-06-29     1
419419  10176228  0109003405  2015Q3    12969-1   2015-07-27     1
429893  10176228  0109003405  2015Q3    12987-1   2015-07-27     1
426850  10176228  0109241988  2015Q3      13929   2015-09-15     1
384762  10176228  0109385611  2015Q4     K10127   2015-10-09     1

The Flag field is being applied to every ordernumber in the given quarter, not the last ordernumber. So, above, for 2015Q2, Flag should only hit for both lines of ordernumber 0108895691

PRIOR POST:
I currently have a dataset of sales orders in which each ordernumber is divided into lots (i.e., lot1, lot2, etc.). So, there may be various rows for each ordernumber. Other pertinent columns are account id and quarter (i.e., 2018Q2). For each given id in each given quarter, I want to apply a flag to all the lots of the last order within that given quarter using Pandas / Python. Any advice?
Currently have:
masterDF['FLAG'] = masterDF.groupby(by=['id','quarter'],as_index=False)['ordernumber'].nth(-1)
masterDF['LAST_ORDER_OF_QUARTER'] = np.where(masterDF['FLAG'].isnull(),0,1)

But that only puts a 1 on just the last row of that id/quarter/order combination, not on all rows within that given order if that ordernumber appears on more than one row.
My desired output is to have a 1 on both lots of orderB
id   |   quarter   |   ordernumber   |   lot      |    Last Order of Quarter
----------------------------------------------------------------------------
A    |   2018Q1    |   orderA        |   lot1     |     0
A    |   2018Q1    |   orderB        |   lot1     |     1
A    |   2018Q1    |   orderB        |   lot2     |     1

Instead of:
id   |   quarter   |   ordernumber   |   lot      |    Last Order of Quarter
----------------------------------------------------------------------------
A    |   2018Q1    |   orderA        |   lot1     |     0
A    |   2018Q1    |   orderB        |   lot1     |     0
A    |   2018Q1    |   orderB        |   lot2     |     1

Any advice?

A: Use duplicated
df.assign(Flag=1 - df.duplicated(['id', 'quarter', 'lot'], keep='last'))

  id quarter ordernumber   lot  Flag
0  A  2018Q1      orderA  lot1     0
1  A  2018Q1      orderB  lot1     1
2  A  2018Q1      orderB  lot2     1

Same thing
df.assign(**{'Last Order': 1 - df.duplicated(['id', 'quarter', 'lot'], keep='last')})

  id quarter ordernumber   lot  Last Order
0  A  2018Q1      orderA  lot1           0
1  A  2018Q1      orderB  lot1           1
2  A  2018Q1      orderB  lot2           1

A: Your groupby object gives a convenient table to merge back into the main. Assign "Last Order" to 1 on that table, merge it to main, and fill the NaNs with 0.
new = df.groupby(['id', 'quarter']).nth(-1)
del new['lot']
new['Last Order'] = 1
df = pd.merge(df, new, how='left').fillna(0)

This gives:
    id  quarter ordernumber lot value
0   a   2018Q1  orderA  lot1    0.0
1   a   2018Q1  orderA  lot2    0.0
2   a   2018Q1  orderB  lot1    1.0
3   b   2018Q1  orderC  lot2    0.0
4   b   2018Q1  orderD  lot1    1.0
5   b   2018Q1  orderD  lot2    1.0


text:
Q: Maven parent from dependencies I have an acceptance test module that I would like to run on Docker. To get this working, I had to copy all its parent poms, until the very last one. I would like to find out if it is possible to use a parent pom from a dependency, as in having something like:
<dependency>
    <groupId>group.id</groupId>
    <artifactId>artifact.id.parent</artifactId>
    <version>${project.version}</version>
    <type>pom</type>
</dependency>

would make Maven find the parent
<parent>
    <groupId>group.id</groupId>
    <artifactId>artifact.id.parent</artifactId>
    <version>x.x.x-SNAPSHOT</version>
</parent>

Assuming that the acceptance test module version is also x.x.x-SNAPSHOT


text:
Q: Dog bone-shaped curve: $|x|^x=|y|^y$
EDITED: Some of the questions are ansered, some aren't.
EDITED: In order not to make this post too long, I posted another post which consists of more questions.

Let $f$ be (almost) the implicit curve$$|x|^x=|y|^y$$ See the graph of the particularly interesting dog bone-shaped curve belowObviously, the graph should contains the line $x=y$.However, what I want $f$ to be, is, the graph $|x|^x=|y|^y$, without line $x=y$, but nevertheless contains the two points which the curve intersect with $x=y$. Note that the convention $0^0=1$, maybe not as usaul.Clearly $f$ is not a function.I doesn't have any idea about continuity, derivative, integral, and many other important technique, apply on an implicit curve.However, I does want to ask:
$1$) How to write $f$ in an rigorous way? (How to represents 'the intersection of the curve with $x=y$, as the line $x=y$ is originally contains in the curve?)
$2$) Is $f$ continuous?(What does it means to be a continuous implicit curve? Is it smooth?)
$3$) How can we break it down into several functions so that we can use the properties of functions?
$4$)[ANSWERED] Can we find the area (maybe not 'integral', since in definition to Riemann-integral, integral under x-axis is negative, but clearly area can't be negative) surrounding by the curve $f$? Or does it make any sense to say the area of an implicit curve? Is there a strict definition? From wikipedia, maybe we need to show that it is Jordan curve? (Thanks, Peter Heinig, in the comment.
Answer: By Barry Cipra, the integral is $3.527\dots$.
$5$) Given a straight line, at most how many points can the line intersects $f$? I believe the answer is 4, as an example, $y=-x-1$. Moreover, what if the line is in the form $y=a$,while $a\in\mathbb R$? I believe is 2. See the image below,
for some example
$6$) Where are the extrema of $f$,

*

*a) in the normal sense,

*b) when we take $x=y$ as the $x$-axis,

*c) when we take $x=-y$ as the $x$-axis?
$7$) What is the intersections of the curve with,

*

*a) $x=y$, (ANSWERED by Rahul)

*b) $x=-y$,  (ANSWERED)

If $x>0$ and $x=−y$, then we get $x^x=x^{−x}$,$x^{2x}=1$,$x=1$,$y=−1$,
and similarly for $x<0$ we get $x=−1,y=1$. This answers 7b. – Wojowu

*

*c) $x$-axis? (ANSWERED)

$8$)

*

*a) What is the circumscribed circle to the curve $f$? (I think that it may be $x^2+y^2=2$)

*b) What is the inscribed circle to the curve $f$?$\space\space\space$(I observed by trial and error that it may be $x^2+y^2=a$$\space\space\space$while $a\approx 0.27067056\approx\frac{1352}{4995}$, see the image below)

9)[ANSWERED]
Perhaps we should restrict our attention to $x^x=y^y$, consider the part of $f$ which is in the first quadrant (including positive x and y axes),see the image below, the red curve. How can we find the integral of it on [0,1](How can we write it in a more convenient form?) I observed that the integral should be $\gt 1-\frac{\pi}{4}$(See the image below) and $\lt \frac{1}{2}$, perhaps, $\frac{e}{10}$?.
Answer: By Yuriy S, the integral is $0.317\dots$.
10)Is the locus, when $f$ is rotated around the origin, the area between the two concentric circles $x^2+y^2=2$ and $x^2+y^2=\frac{2}{e^2}$? See the image and here.The equations of the graph:Using rotation matrix, as mentioned in Yuriy S's answer,Define a paremeter $a$, as the rotation degree measures in radian (clockwise),$f$, after rotation, is $$\left|x\cdot\cos a-y\sin a\right|^{x\cdot\cos a-y\sin a}=\left|x\sin a+y\cos a\right|^{x\sin a+y\cos a}$$ For$$\space x\cdot\cos a-y\sin a\neq x\sin a+y\cos a$$Of course, there are two points more.Does it helps to prove that $f$ is continuous, i.e., question 2 above?NOTE: To interpret the graph with Desmos, we need to consider two cases, namely, $\space x\cdot\cos a-y\sin a<x\sin a+y\cos a$ and $\space x\cdot\cos a-y\sin a> x\sin a+y\cos a$ respectively, see the link above.
I need really to apologize that I really doesn't have any idea to answer. I am not presently familar with implicit curve, but only a little knowledge about real analysis. However, I ask it because I think it is interesting. Moreover, it is good for an easy answer, but it is not neccesary that the answer should be very elementary, since knowing how the question can be solve by wonderful mathematical techniques is itself interesting. Welcome for any answer, even not as a complete answer to all 10 questions.
Thanks for answering my naive questions!
Sorry for a new question, but I really like to ask :)

A: Let's use polar coordinates to examine some of the aspects of the dogbone.  Writing $x=r\cos\theta$ and $y=r\sin\theta$, with $r\gt0$ and $0\le\theta\lt2\pi$ for $(x,y)\not=(0,0)$, we find
$$|x|^x=|y|^y\iff x\ln|x|=y\ln|y|\iff \cos\theta(\ln r+\ln|\cos\theta|)=\sin\theta(\ln r+\ln|\sin\theta|)\\
\iff(\cos\theta-\sin\theta)\ln r=\sin\ln|\sin\theta|-\cos\theta\ln|\cos\theta|$$
so generically we have
$$\ln r={\sin\theta\ln|\sin\theta|-\cos\theta\ln|\cos\theta|\over \cos\theta-\sin\theta}$$
or
$$r(\theta)=\left(|\sin\theta|^{\sin\theta}\over|\cos\theta|^{\cos\theta} \right)^{1/(\cos\theta-\sin\theta)}$$
This is well defined and continuous for all values of $\theta$ except when $\cos\theta=\sin\theta$, i.e., at $\theta={\pi\over4}$ and ${5\pi\over4}$. (Note, the equation $(\cos\theta-\sin\theta)\ln r=\sin\ln|\sin\theta|-\cos\theta\ln|\cos\theta|$ allows $r$ to take on any positive value when $\cos\theta=\sin\theta$, giving us all points on the line $y=x$, but we are ignoring those points, except for the ones that are on the curve.) L'Hopital allows us to fill in a value for $\ln r$ at those points. By symmetry, it suffices to look at $\theta\to\pi/4$.  We get
$$\begin{align}
\lim_{\theta\to\pi/4}{\sin\theta\ln|\sin\theta|-\cos\theta\ln|\cos\theta|\over \cos\theta-\sin\theta}
&=\lim_{\theta\to\pi/4}{(\cos\theta\ln|\sin\theta|+\cos\theta)+(\sin\theta\ln|\cos\theta|+\sin\theta)\over-\sin\theta-\cos\theta}\\
&=\ln\sqrt2-1
\end{align}$$
which tells us
$$r\left(\pi\over4\right)={\sqrt2\over e}\approx0.52026$$
as Yuriy S found.
We can also ask Wolfram Alpha to evaluate the integral for the area:
$$A=\int_0^{2\pi}{1\over2}r(\theta)^2\,d\theta=\int_0^\pi\left(|\sin\theta|^{\sin\theta}\over|\cos\theta|^{\cos\theta} \right)^{2/(\cos\theta-\sin\theta)}d\theta\approx3.52723$$

A: This is for question 9). I'm posting another answer, because my first one has become bloated enough.
To find the integral, I will use my rotated function again. It's not hard to see that the area the OP wants to find is twice the shaded area:

To write the integral explicitly, I will use the equation I obtained for $y>x$ and $y>0$:
$$2x \log y  +y \left(1+\frac{x}{y} \right) \log \left(1+\frac{x}{y} \right)- y \left(1-\frac{x}{y} \right)  \log \left(1-\frac{x}{y} \right) -x \log 2 =0$$
Let's introduce a new parameter:
$$t=\frac{x}{y}, \qquad t \in (0,1)$$
Then, we have an explicit function:
$$\log y(t)= \frac{\log 2}{2}-\frac{1}{2}\left(\frac{1}{t} +1\right) \log (1+t)+\frac{1}{2} \left( \frac{1}{t}-1 \right) \log (1-t)$$
Note that:
$$y(1)=\frac{1}{ \sqrt{2} }$$
The shaded area is given by:
$$I= \int_0^{1/ \sqrt{2}} y(x) dx - \int_0^{1/ \sqrt{2}} x dx=\int_0^{1/ \sqrt{2}} y(x) dx- \frac{1}{4}$$
It's important to note:
$$dx=d(t y)=t \frac{dy}{dt} dt+y dt= \left(t \frac{dy}{dt}+y \right) dt$$
So we have:
$$\int_0^{1/ \sqrt{2}} y(x) dx=\int_0^1 y(t) \left(t \frac{dy}{dt}+y \right) dt=\int_0^1 t y \frac{dy}{dt} dt+\int_0^1 y^2 dt$$
The first integral can be computed integrating by parts:
$$J=\int_0^1 t y \frac{dy}{dt} dt=t y^2 \big|_0^1 - \int_0^1 y(t) \left(t \frac{dy}{dt}+y \right) dt= \frac{1}{2}-J - \int_0^1 y^2 dt$$
Which means:
$$J=\frac{1}{4}-\frac{1}{2} \int_0^1 y^2 dt$$
And finally:
$$I=\frac{1}{2} \int_0^1 y^2 dt$$

$$I=\int_0^1 \exp \left(- \left(\frac{1}{t} +1\right) \log (1+t)+ \left( \frac{1}{t}-1 \right) \log (1-t) \right) dt \tag{1}$$

Wolfram Alpha computes:
$$I=0.15858185771988216006213921681874564 \dots$$
So finally the area the OP was interested in:

$$2I=0.31716371543976432\dots$$

I hope I haven't made any mistakes, but at least the OP's estimates check out as:
$$1-\frac{\pi}{4} < 2I < \frac{1}{2}$$
Update:
The value is correct, as confirmed by using Barry Cipra's polar form:
$$2I=\int_0^{\pi/4}\left(|\sin\theta|^{\sin\theta}\over|\cos\theta|^{\cos\theta} \right)^{2/(\cos\theta-\sin\theta)}d\theta$$
Update 2
A little workings with the integral (1). Using the Taylor series for the logarithm and simplifying, we get a very compact formula with the series:

$$I=\frac{1}{e^2} \int_0^1 \exp \left( \sum_{k=1}^\infty \frac{t^{2k}}{k(2k+1)} \right) dt= \\ =\frac{1}{e^2} \int_0^1 \exp \left( \frac{t^2}{3}+\frac{t^4}{10}+\frac{t^6}{21}+\frac{t^8}{36}+\frac{t^{10}}{55}+\cdots \right) dt \tag{2}$$

This gives $\frac{2}{e^2}$ (which is precisely $a^2$, i.e. the radius of the inscribed circle) as a good approximation (from below) to the area in question. The integral in (2) has a value of about $1.17$.
Here's for comparison, the area of half the inscribed circle $A_1= a^2 \frac{\pi}{2}$  and the area found here $A_2 = a^2 \int_0^1 \exp \left( \sum_{k=1}^\infty \frac{t^{2k}}{k(2k+1)} \right) dt$:

For a more complete description, alternative to the polar one, I will also add parametric form for $x>y$, which is derived in the same way from the logarithmic equation.
Now the complete parametric representation of the curve is:

$$\begin{cases} \displaystyle  x(t)= \pm  \frac{\sqrt{2}}{e}~t ~ \exp \left( \sum_{k=1}^\infty \frac{t^{2k}}{2k(2k+1)} \right) \\ \displaystyle  y(t)= \pm \frac{\sqrt{2}}{e} \exp \left( \sum_{k=1}^\infty \frac{t^{2k}}{2k(2k+1)} \right) \\ t \in (0,1) \end{cases} \tag{a}$$
$$\begin{cases} \displaystyle  x(t)= \pm \sqrt{2} \exp \left( -\sum_{k=1}^\infty \frac{t^{2k}}{2k(2k-1)} \right) \\ \displaystyle  y(t)=  \pm \sqrt{2}~ t ~ \exp \left(- \sum_{k=1}^\infty \frac{t^{2k}}{2k(2k-1)} \right) \\ t \in (0,1) \end{cases} \tag{b}$$

As you can see, it consists of $8$ pieces, for each sign in (a) and (b).
Using this representation, one can explicitly compute arclength of the curve.
Here's the Desmos link with the demonstration.
From the symmetry properties we have for the whole area (in agreement with the results of Barry Cipra and robjohn):
$$A=4 \int_0^1 \left( \frac{1}{e^2} \exp \left(\sum_{k=1}^\infty \frac{t^{2k}}{k(2k+1)} \right) + \exp \left(- \sum_{k=1}^\infty \frac{t^{2k}}{k(2k-1)} \right)\right) dt =3.52723\dots  $$

A: And by using the Rotation matrix which Yuriy S did, the rotated curve which as y=-x as the x axis,it can be descibed as
$$|\frac{1}{\sqrt2}(y+x)|^{\frac{1}{\sqrt2}(y+x)}=|\frac{1}{\sqrt2}(y-x)|^{\frac{1}{\sqrt2}(y-x)}$$
This newly rotated curve is symmetric about the x axis and the y axis, so it's extrema on the first quadrant is can be quadruplicated by symmetrically moving them.
Therefore, i will only consider when $y>0, x>0, |y|<|x|$(by the graph)
By applying logarithm, it turns to
$$(y+x)\ln(\frac{1}{\sqrt2}(y+x))=(y-x)\ln(\frac{1}{\sqrt2}(x-y))$$
$$(y+x)\ln(y+x)-\frac{1}{2}(y+x)\ln2=(y-x)\ln(x-y)-\frac{1}{2}(y-x)\ln2$$
In order to differentiate the with x, making the expression simpler,
$$y(\ln(y+x)-\ln(x-y))+x(\ln(y+x)+\ln(x-y)-\ln2)=0$$
$$\frac{dy}{dx}(\ln(y+x)-\ln(x-y))+y(\frac{1+\frac{dy}{dx}}{y+x}-\frac{-1+\frac{dy}{dx}}{y-x})+\ln(y+x)+\ln(x-y)-\ln2+x(\frac{1+\frac{dy}{dx}}{y+x}+\frac{-1+\frac{dy}{dx}}{y-x})=0$$
We are interested when $\frac{dy}{dx}=0$, so
$$\frac{y}{y+x}+\frac{y}{y-x}+\ln(y+x)+\ln(y-x)-\ln2+\frac{x}{y+x}-\frac{x}{y-x}=0$$
Therefore, $2-\ln2+\ln(x^2-y^2)=0, \ x^2-y^2=\frac{2}{e^2}$
I'm thinking about how to find the root of this...
I first thought about rotating $x^2-y^2=\frac{2}{e^2}$ and find the intersecting point with $|x|^x=|y|^y$, but this is the same thing with finding the points where $\frac{dy}{dx}=-1$ on the original curve.
If i rotate $x^2-y^2=\frac{2}{e^2}$ $\frac{\pi}{4}$ clockwise, the hyperbola changes into $$xy=-\frac{1}{e^2}$$
Therefore, we can let $$y=-\frac{1}{xe^2}$$
Since $x<0 \ and y>0$due to the graph, $$x\ln(-x)=y\ln y$$
$x\ln(-x)=\frac{1}{xe^2}(\ln(-x)+2)$
WolframAlpha computes $x\approx-0.110838771758797...$ or $-1.22101031154625...$
This value is right because the two points should be symmetric about $y=x$, and they are(using $xy=-\frac{1}{e^2}$)
Lastly, if we rotate $(-0.110838771758797, 1.22101031154625)$ again, the point is $$(-0.941759518322086, 0.785009824064019)$$
The second way was to find where $\frac{dy}{dx}=-1$, which can be calculated by:
$$(-x)^x=y^y,\ x\ln(-x)=y \ln y,\ \ln(-x)+1=\frac{dy}{dx}(\ln y+1)$$
$$\ln(-xy)=-2,\ xy=\frac{-1}{e^2}$$
This way was much easier, without needing to use the rotation matrix(although you need to find rotate the point at the end).

A: There is a point that has not been mentioned so far: The dogbone curve is only $C^1$ at its inflection points. In fact the curvature does not assume the value $0$ at these points, but tends to $\pm\infty$ when approaching such a point from either side.
Consider the inflection point ${\bf p}=(0,1)$, and put
$$x\log|x|=y\log y=: t\ .$$
Writing $y=1+u$ with $|u|\ll1$ near ${\bf p}$ we have
$$t=(1+u)\log(1+u)=u+{u^2\over2}-{u^3\over6}+\ldots=:f(u)\ ,$$
whereby $f$ is analytic in a neighborhood of  $u=0$, with $f(0)=0$ and $f'(0)=1$. It follows that $f$ has an inverse function $g$, defined in a neighborhood of $t=0$, and we have
$$u=g(t)=t-{t^2\over2}+{2t^3\over3}-\ldots\quad.$$ We then can write our dogbone curve in the neighborhood of ${\bf p}$ in the form
$$y=1+g\bigl(x\log|x|\bigr)=:h(x)\ .$$
Using the formula
$$\kappa(x)={h''(x)\over\bigl(1+h'^2(x)\bigr)^{3/2}}$$
it is then easy to verify that $\lim_{x\to\pm0}\kappa(x)=\pm\infty$.

A: There's so many questions... Let me start with a useful hint.
We can rotate the curve $45$ degrees counter clockwise to get something we can better work with.
Rotation can be done with the use of Rotation matrix, which in this case gives us simply:
$$x=\frac{1}{\sqrt{2}} (y_2+x_2) \\ y=\frac{1}{\sqrt{2}} (y_2-x_2)$$
Now we just substitute the above expressions into the equation (and forget about subscripts right after):
$$\left| \frac{1}{\sqrt{2}} (y+x) \right|^{ \frac{1}{\sqrt{2}} (y+x)}=\left| \frac{1}{\sqrt{2}} (y-x) \right|^{ \frac{1}{\sqrt{2}} (y-x)}$$
We get the following plot (with circles added later of course):

The circumscribed circle really has radius $\sqrt{2}$, as the OP guessed. It can be seen by setting $y=0$ in the above equation.
The inscribed circle is more complicated. If we set $x=0$ we get:
$$\left| \frac{y}{\sqrt{2}}\right|^{ \frac{y}{\sqrt{2}}}=\left| \frac{y}{\sqrt{2}}\right|^{ \frac{y}{\sqrt{2}}}$$
But this is true for any $y$. Remember the line $y=x$ which satisfies the original equation? That's why.
By zooming in in Desmos we see that the radius is about $$a \approx 0.52026,$$
see below for the exact value.

Now, this kind of equation is very complicated to work with. However, we can use logarithms to make it more manageable:

$$(y+x) \log \left| \frac{1}{\sqrt{2}} (y+x) \right|=(y-x) \log \left| \frac{1}{\sqrt{2}} (y-x) \right|$$

This equation describes the same curve, but now we can work with it using analytical methods (such as Taylor series, in the appropriate ranges of $x$ and $y$).
For example, setting:
$$y>0 \\ y > |x|$$
We can get rid of the absolute values and write:
$$(y+x) \left( \log y+ \log \left(1+\frac{x}{y} \right)-\frac{\log 2}{2} \right)=(y-x) \left( \log y+ \log \left(1-\frac{x}{y} \right)-\frac{\log 2}{2} \right)$$
Simplifying:
$$2x \log y  +y \left(1+\frac{x}{y} \right) \log \left(1+\frac{x}{y} \right)- y \left(1-\frac{x}{y} \right)  \log \left(1-\frac{x}{y} \right) -x \log 2 =0$$
Now, to find the non-trivial root at $x=0$ (the radius of the inscribed circle) we can add the condition $y \gg |x|$ and expand the logarithmic functions, keeping only the terms up to $x^2$:
$$2x \log y  +y \left(1+\frac{x}{y} \right) \left(\frac{x}{y}-\frac{x^2}{2y^2} \right)- y \left(1-\frac{x}{y} \right)  \left(-\frac{x}{y}-\frac{x^2}{2y^2} \right) -x \log 2 =0$$
Simplifying (and keeping only the terms up to $x^2$), we get:
$$x \left(2 \log y+2 - \log 2 \right)=0$$
As we've already seen, $x=0$ gives us trivial solution for any $y$. However, if $x \neq 0$, but is very close to it, we have also another solution:
$$2 \log y+2 - \log 2=0$$

$$y=\exp \left( \log \sqrt{2}-1 \right)=\frac{\sqrt{2}}{e}=0.52026009502 \dots$$

This our $a$, radius of the inscribed circle.

There's actually another associated circle, which looks like this:

It is completely defined by the curvature of the function around $x=0$.
Its parameters could be deduced exactly (probably) by using the definition of the curvature, but I have used an approximation. Let's keep not only quadratic, but also cubic terms in the logarithm expansion. Then we get:
$$x \left(2 \log y+2 - \log 2-\frac{x^2}{3y^2} \right)=0$$
Rearranging, we can see that (for $x \neq 0$):
$$y=\frac{\sqrt{2}}{e} \exp \left(1+ \frac{x^2}{3y^2}\right) \approx \frac{\sqrt{2}}{e} \left(1+ \frac{x^2}{3y^2}\right)$$
From the general equation of the circle for small $x$ we have:
$$y=y_0-\sqrt{R^2-x^2} \approx y_0-R \left(1- \frac{x^2}{2R^2} \right)=y_0-R+\frac{x^2}{2R}$$
In our case, $R$ is a function of $y$, but let's make another approximation and assume $y= a=\frac{\sqrt{2}}{e}$, then we have:
$$R \approx \frac{3}{e \sqrt{2}} \\ y_0 \approx \frac{5}{e \sqrt{2}}$$
The diagram above uses these values and we can see they fit very well.

I'll add more to this once I think of something else.

A: For 6a), we know that that dog-bone shaped curve has some extrema on the second and fourth quadrant, so let's differentiate that.
Clearly, this curve is symmetric about $y=x$, so I will consider only on the second quadrant, where $x<0$ and $y>0$.
$$(-x)^{x}=y^y$$ $$x\ln(-x)=y\ln y$$ $$\ln(-x)+1=\{\ln y+1\}\frac{dy}{dx}$$
we need to find where $\frac{dy}{dx}=0$, so $$\ln(-x)+1=0$$ $$x=-e^{-1}$$
I don't know how to post images, but by usng desmos, it's clear that $|x|^x=|y|^y$has its extrema on $x=-1/e, 1/e$ $\ \ $  $y^y=e^{1/e}, y\approx1.3211$(I found that with trial and error on the xy plane.)
In same way, we can know that the domain and the range of the curve(excluding y=x) is $\{-1.3211\le x \le 1.3211\},\ \{-1.3211\le y \le 1.3211\}$

A: I'm quite confused why many people just "take it for granted" that the circumscribed circle will pass $(-1, 1)$. If the slope of the tangent is close to -1(that is to say, $\frac{dy}{dx}|_{x=-1} \approx-1$),the circle might not pass $(-1,1)$, just like a chord.
I'll admit, I maybe quite preoccupied and this doesn't need to be 'proved'(or it has ben, but I couldn't notice), but I wanted to "prove" that the radius of the inscribed and circumscribed circle is what people above calculated.
So, thanks to Barry Cipra, we all know that the dog-boned curve can be presented as a following polar coordinates:$$r(\theta)=(\frac{|\sin(\theta)|^{\sin(\theta)}}{|\cos(\theta)|^{\cos(\theta)}})^{\frac{1}{\cos\theta-\sin\theta}}$$
$$\ln r(\theta)=\frac{\sin\theta \ln|\sin\theta|-\cos\theta \ln|\cos\theta|}{\cos\theta-\sin\theta}$$
For the circumscribed circle, the $\frac{\pi}{2}<\theta<\pi$
$$\frac{1}{r(\theta)}\frac{d}{d\theta}r(\theta)=\frac{\ln(\sin\theta)-\ln(-\cos\theta)}{(\cos\theta-\sin\theta)^{2}}$$
When $\theta=\frac{3}{4}\pi$, $r(\theta)$has it's maximum value because $\frac{dr(\theta)}{d\theta}=0$, and $$r(\frac{3}{4}\pi)=\sqrt2$$
In same way, for the inscribed circle, $\frac{dr(\theta)}{d\theta}=\pm\infty$ when $\theta=\frac{\pi}{4}$, so there's the local minimum point of $r(\theta)$, so the radius of the inscribed circle is $\frac{\sqrt2}{e}$

A: Parametric Representation
Let $y=ax$, then
$$
|x|^x=|ax|^{ax}
$$
and therefore,
$$
|x|=|a|^{\frac{a}{1-a}}
$$
which means that
$$
(x,y)=\pm|a|^{\frac{a}{1-a}}(1,a)
$$
For $a\not\in[-1,1]$ the transform $a\mapsto\frac1a$, maps
$$
\begin{array}{c}
a\in(1,\infty)&\pm|a|^{\frac{a}{1-a}}(1,a)&\overset{a\mapsto\frac1a}{\longmapsto}&\pm|a|^{\frac{a}{1-a}}(a,1)&a\in(0,1)\\
a\in(-\infty,-1]&\pm|a|^{\frac{a}{1-a}}(1,a)&\overset{a\mapsto\frac1a}{\longmapsto}&\mp|a|^{\frac{a}{1-a}}(a,1)&a\in[-1,0)
\end{array}
$$
Thus, we get all of the curve using $a\in[-1,1)$, with the four pieces:
$$
\bbox[5px,border:2px solid #C0A000]{
\begin{align}
\color{#C00}{+|a|^{\frac{a}{1-a}}(1,a)}\\
\color{#090}{+|a|^{\frac{a}{1-a}}(a,1)}\\
\color{#F90}{-|a|^{\frac{a}{1-a}}(1,a)}\\
\color{#00F}{-|a|^{\frac{a}{1-a}}(a,1)}
\end{align}
}
$$

The Circumscribed and Inscribed Circles
The derivative of the log of the distance from the origin is
$$
\begin{align}
\frac{\mathrm{d}}{\mathrm{d}a}\log\left(|a|^{\frac{a}{1-a}}\sqrt{1+a^2}\right)
&=\frac{\frac{1-a^2}{1+a^2}+\log|a|}{(1-a)^2}\\
&\le0
\end{align}
$$
since $\frac{1-a^2}{1+a^2}+\log|a|$ is even and increases to $0$ on $(0,1)$; that is, its derivative is $\frac1a\left(\frac{1-a^2}{1+a^2}\right)^2\ge0$. Thus, the distance from the origin decreases monotonically as $a$ goes from $-1$ to $1$. By symmetry, the maximum distance occurs at $a=-1$ and the minimum distance occurs at $a=1$.
The furthest points from the origin, where $a=-1$, are
$$
(-1,1)\text{ and }(1,-1)
$$
Taking limits, we get the closest points to the origin, where $a\to1^-$, are
$$
\left(e^{-1},e^{-1}\right)\text{ and }\left(-e^{-1},-e^{-1}\right)
$$
Thus, the radius of the circumscribed circle is
$$
\bbox[5px,border:2px solid #C0A000]{\sqrt2}
$$
and the radius of the inscribed circle is
$$
\bbox[5px,border:2px solid #C0A000]{\frac{\sqrt2}e}
$$

Area
$$
\begin{align}
&4\int_{-1}^1\frac12|a|^{\frac{a}{1-a}}(1,a)\times\left[\left(\frac{\mathrm{d}}{\mathrm{d}a}|a|^{\frac{a}{1-a}}\right)(1,a)+|a|^{\frac{a}{1-a}}(0,1)\right]\mathrm{d}a\\
&=2\int_{-1}^1|a|^{\frac{2a}{1-a}}\,\mathrm{d}a\\[6pt]
&\doteq\bbox[5px,border:2px solid #C0A000]{3.5272349603958296088}
\end{align}
$$

Length
We could avoid computing the following derivative for the area because $(1,a)\times(1,a)=0$, but we need it for the length:
$$
\frac{\mathrm{d}}{\mathrm{d}a}|a|^{\frac{a}{1-a}}
=\frac{1-a+\log|a|}{(1-a)^2}|a|^{\frac{a}{1-a}}
$$
Thus
$$
\begin{align}
\left|\,\frac{\mathrm{d}}{\mathrm{d}a}\left(|a|^{\frac{a}{1-a}}(1,a)\right)\,\right|
&=|a|^{\frac{a}{1-a}}\left|\frac{1-a+\log|a|}{(1-a)^2}(1,a)+(0,1)\right|\\
&=|a|^{\frac{a}{1-a}}\left[\left(\frac{1-a+\log|a|}{(1-a)^2}\right)^2+\left(a\frac{1-a+\log|a|}{(1-a)^2}+1\right)^2\right]^{1/2}\\
&=\frac{|a|^{\frac{a}{1-a}}}{(1-a)^2}\sqrt{(1-a+\log|a|)^2+(1-a+a\log|a|)^2}
\end{align}
$$
Therefore,
$$
4\int_{-1}^1\left|\,\frac{\mathrm{d}}{\mathrm{d}a}\left(|a|^{\frac{a}{1-a}}(1,a)\right)\,\right|\mathrm{d}a
\doteq\bbox[5px,border:2px solid #C0A000]{8.0060888731054946925}
$$

Maximum $\boldsymbol{y}$
Letting $t=-a$ where $a\lt0$, on the green curve, we wish to find the maximum, for $t\gt0$, of
$$
\log\left(t^{-\frac{t}{1+t}}\right)=-\frac{t}{1+t}\log(t)
$$
Taking the derivative, gives
$$\newcommand{\W}{\operatorname{W}}
-\frac1{(1+t)^2}\log(t)-\frac1{1+t}=0\implies t=\W\left(\frac1e\right)
$$
Thus, the maximum $y$ is
$$
\bbox[5px,border:2px solid #C0A000]{t^{-\frac{t}{1+t}}\doteq1.321099762015617457}
$$
which happens when $x=-ty$; that is, when $x$ is
$$
-t^{\frac1{1+t}}\doteq-0.36787944117144232160
$$
The other non-rotated extremal points can be found by symmetry.

A: For 7c), it is easy, let me do it by myself.
The question can be reduced to the solution of equation $0^0=1=\vert x\vert ^x$. Consider $g(x)=x^x$, defined on $\mathbb R^+$. $$0<x<1\implies g(x)<1$$and $$x>1\implies g(x)>1$$therefore$$g(x)=1\implies x=1$$, also, $$x^{-x}=1 \land x\in\mathbb R^+\implies x=1$$See the image belowTherefore, $$0^0=\vert x\vert ^x\implies x=\pm 1 \lor x=0\space (rejected)$$To conclude, the intersections of $f$ and $y=0$ are (-1,0) and (1,0).

A: Question 1
One way to answer your first question is to formulate it as an Analytic Variety. An analytic variety of a single function on the field $\mathbb{R}^2$ is defined as the set,
$$
  A(f) = \{ (x,y) \in \mathbb{R}^2 | f(x,y) = 0 \}
$$
In the case of the proposed equation,
$$
  |x|^x = |y|^y
$$
One can define a function,
$$
\begin{align}
  f : \mathbb{R}^2 \rightarrow& \mathbb{R} \\
  (x,y) \mapsto& |x|^x - |y|^y
\end{align}
$$
the line ($y=x$) would be,
$$
\begin{align}
  g : \mathbb{R}^2 \rightarrow& \mathbb{R} \\
  (x,y) \mapsto& x - y
\end{align}
$$
Since the zeros of the equation $|x|^x = |y|^y$ include the solutions of $y=x$. The intersection is written as $A(f)\cap A(g) = A(g)$. The dog bone shape alone is $(A(f) \setminus A(g)) \cup \{(1,1), (-1,-1) \}$.
Question 2
Continuity does not have the same meaning in a set, even though the resulting curves look like functions. For example, a variety could be the intersection of a plane passing through the origin and a torus. Although it is locally path-connected there would be two disjoint circles, making it, in some sense, discontinuous.
To analyse the curve differentially one needs to use Reimannian Geometry. If it is a curve in the traditional sense, then it will conform to the definition of a manifold. Your example is a Reimannian manifold of dimension $1$ because it is locally homeomorphic to $[0,1]$. The local homeomorphisms are known as charts. Barry Cipra gave,
$$
\begin{align}
  h : [0, 2\pi) \rightarrow& A(f) \\
  \theta \mapsto& r(\theta)\left( \begin{array}{c} \cos{\theta} \\ \sin{\theta} \end{array}  \right)
\end{align}
$$
where,
$$
\begin{align}
  r : [0, 2\pi) \rightarrow& \mathbb{R} \\
  \theta \mapsto& \left( \frac{|\sin{\theta}|^{\sin{\theta}}}{|\cos{\theta}|^{\cos{\theta}}} \right)^{\frac{1}{\cos{\theta} - \sin{\theta}}}
\end{align}
$$
as a homeomorphism between $[0, 2\pi)$ and $A(f)$, and so $A(f)$ is locally homeomorphic to $[0,1]$.
The manifold is called smooth if every local homeomorphism is smooth, which is also provable using the same parametrisation.


text: Q: How to create an additional terminal-based output stream? How would I create an additional file descriptor that connects to the terminal for debug messages? I'd like something just like standard out/error streams (stdout/stderr). For clarity sake, I'll call this new stream spdbg (for "special debug"). I thought about using dup() to duplicate the stdout/stderr stream, but if that stream gets redirected to a file then that means spdbg also gets redirected to the same file, which I don't want. Instead, I'd like spdbg to redirect to the terminal, just like stdout/stderr initially do. In other words, if stdout/stderr gets redirected to a file, then spdbg should still point to the terminal. However, spdbg can still be redirected to a file, if the user wishes to do so.


text:
Q: ODE Problem - how to proceed I am trying to solve this ODE:
$\dot{x}(t+x^2) = x$
...using this hint:
$\frac{dx}{dt} = \frac{1}{\frac{dt}{dx}}$.
I'm not entirely sure what this hint even means but I am guessing it has something to do with the inverse function. I would appreciate some guidance on the matter or at least an explanation of what this hint is supposed to mean.

A: Suppose that you look for $t$ as a function of $x$m then $$
\frac{dt}{dx} = \frac{t+x^2}x
= \frac tx + x
$$
whose general solution is $$
t(x) = Cx + x^2
$$
[via variation a the constant: solution of $\frac{dt}{dx} = \frac tx$ is
$t(x) = Cx$, and variation a the constant gives $xC'(x) = x$ giving $
C(x) = x $ as a particular solution].
Now solve the equation in $x(t)$.
Suppose for example an initial condition $x(0) = x_0$.
$$
0 = t(x_0) = Cx_0 + x_0^2
$$
has two solutions: $x_0 = 0$ leads to the solution, otherwise $C = -x_0$ and
$$
t = -x_0x(t) + x(t)^2
$$
that is, $$
x(t) = \frac 12 (x_0 +\sqrt{x_0^2 + 4t})
$$ (the choice is done thanks to the initial condition).

A: $\dot{x}(t+x^2) = x$
$\frac{dx}{dt}(t+x^2) = x$
$tdx+x^2{dx}= xdt$
$tdx-xdt=-x^2{dt}$
$\frac{xdt-tdx}{x^2}=dx$
$d(\frac{t}{x})=dx$
$\int d(\frac{t}{x})=\int dx$
$\frac{t}{x}=x+C$
$t=x^2+Cx$ we can write this in $x^2+Cx-t=0$ form.Then we can solve this as quadratic equation.So
$D=C^2+4t$  then  $x=\frac{-C\pm \sqrt{C^2+4t}}{2}=-\frac{C}{2} \pm$ $\sqrt{(\frac{C}{2})^2+t^2}$
Finally solution of the equation is $x=-\frac{C}{2} \pm$ $\sqrt{(\frac{C}{2})^2+t^2}$
Note. $C$ is invariable


text:
Q: error: 'sort' is not a member of 'std' I just would like to ask what does this error mean and how to fix it thanks!

error: 'sort' is not a member of 'std'

vector<int> result;
        for (auto & i : numbers)
            result.push_back(std::stoi(i));
        std::sort(result.begin(), result.end());

A: Include the algorithm header. That's why there is a error.
#include <algorithm>

A: You have to #include <algorithm>. See this.


text:
Q: cur_group_id by size rather than alphabetical order I have the following data frame:
df <- structure(list(s_do_h_patients_state = c("NC", "NC", NA, NA,
"MN", "MN", "UT", "UT", "IL", "IL"), diabetes = c(FALSE, TRUE,
FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE), n = c(24191L,
5684L, 24386L, 3820L, 18768L, 2423L, 19732L, 1313L, 15670L, 2336L
), p = c(0.809740585774059, 0.190259414225941, 0.864567822449124,
0.135432177550876, 0.88565900618187, 0.11434099381813, 0.937609883582799,
0.0623901164172012, 0.870265467066533, 0.129734532933467), N = c(29875L,
29875L, 28206L, 28206L, 21191L, 21191L, 21045L, 21045L, 18006L,
18006L)), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))

I would like to add another column enumerating the groups, such that the output would be c(1,1,2,2,3,3...).
One way to do it would be group_indices, but this orders alphabetically rather than by group size.
What's the correct way to achieve this?

A: Here is a straightforward solution to this problem
library(dplyr)
df %>% mutate(group = match(s_do_h_patients_state, unique(s_do_h_patients_state)))

Output
# A tibble: 10 x 6
   s_do_h_patients_state diabetes     n      p     N group
   <chr>                 <lgl>    <int>  <dbl> <int> <int>
 1 NC                    FALSE    24191 0.810  29875     1
 2 NC                    TRUE      5684 0.190  29875     1
 3 NA                    FALSE    24386 0.865  28206     2
 4 NA                    TRUE      3820 0.135  28206     2
 5 MN                    FALSE    18768 0.886  21191     3
 6 MN                    TRUE      2423 0.114  21191     3
 7 UT                    FALSE    19732 0.938  21045     4
 8 UT                    TRUE      1313 0.0624 21045     4
 9 IL                    FALSE    15670 0.870  18006     5
10 IL                    TRUE      2336 0.130  18006     5

Note that you can't use rleid because
> data.table::rleid(c("NC", "NC", "IL", "NC"))
[1] 1 1 2 3

A: df %>% arrange(desc(N)) %>%
mutate(id = dense_rank(desc(N)))


text:
Q: Guidance to create a catalogue app for iOS I am in the process of creating an iOS app for a catalogue app that I created for Android which you can see it here (https://play.google.com/store/apps/details?id=com.dynmk.bonbonup) or here if you don't have an Android phone (https://appetize.io/app/ctxjvzhu56fjh01dw89urmvq9g)
I want to create an iOS app that is similar to the one I did for Android using JSON files to retrieve the images and info of the product as you can see in the GridView in the Android app. I create the JSON files through a JSON editor online and then upload the files to a webhost file manager in which all images and JSON files are kept.
My experience with Xcode is not too much and I am still in the learning curve by checking the tutorials in tree house and searching through the web.
I have been reading about UICollectionView to create a GridView similar to the one I have in the Android app but my main question would be, will it work with the JSON files I have created?
Any suggestion would be appreciated,
Thanks!

A: Yea you can use JSON with Swift no problem. There is a built in tool to serialize JSON.
let parsedDict = NSJSONSerialization.JSONObjectWithData(yourJSONData, options: nil, error: &error) as NSDictionary

https://developer.apple.com/library/prerelease/mac/documentation/Foundation/Reference/NSJSONSerialization_Class/index.html#//apple_ref/occ/clm/NSJSONSerialization/JSONObjectWithData:options:error:


text:
Q: Change xfce4-settings:appearance (dpi scaling) options via terminal I want to set the dpi scaling in xfce4-settings:appearance via bash script, so that I can bind it to a key shortcut. In the official docs I can only find the method to change it via GUI. Is there a terminal command to set the dpi value?
Thanks for help!
Basti

A: I think it's what you look for
xfconf-query -c xsettings -p /Xft/DPI -s 100

You can take a look at man xfconf-query


text:
Q: Closed form of $\sum_{n=1}^{\infty} \frac{a^n}{n(n+1)}$ I have come across the series$$\sum_{n=1}^{\infty} \frac{a^n}{n(n+1)}, \quad|a|<1$$
in an intermediate step while solving a problem.
I wonder if there is a closed form for it?
I could only observe that it can be written as $\sum_{n=1}^{\infty} a^n\left(\frac{1}{n}-\frac{1}{n+1}\right)$, but the usual telescoping trick doesn't work here.
I am unaware of usable techniques. Any help is welcomed.


text:
Q: how do I use structured cues in html5 video tag texttracks? I see that a text-track file can have an entry like this:
multicell
00:01:15.200 --> 00:02:18.800
{
"title" : "Multi-celled organisms"
"description" : "Multi-celled organisms have different types of cells that perform specialized functions."
}

I'm not actually using text-track files, instead I'm using javascript to create "cues" for a texttrack object that is not in a file.  But the question is, if I play a video with a track that has structured cues like these, do any subtitles appear?
ideally, I would have the "description" field appear as subtitles, and separately I'd catch the contents of the "title" field and so something else with it.  (I could do that in an event).  Any help is appreciated.

A: I have put together a small cue-example for you.
To answer your questions:

*

*How to make a track visible
a) The track has to be a 'subtitles' or 'captions' kind.
b) The track has to be in mode 'showing'
//add a subtitle track to a video
var track = $('video').get(0).addTextTrack('subtitles', 'just a test', 'en');
//make it visible
track.mode = 'showing';

*structured Data
The Cue always has textual information and will always show the hole text. Of course you can parse a JSON string and do whatever you want with it. In case you are generating cues programatically. You won't need to add JSON. You can pass the description text directly to the cue constructor and then simply extend the resulting cue with a custom property.
function createStructuredCues(s, e, obj){
    var cue = new TextTrackCue(s, e, obj.description);
    cue.customMetaData = obj;
    return cue;
}


text:
Q: Can we use the multiplication map to prove that invertible matrices form an open subset of $M_n(R)$ Define a map  $f : M_n(R) \times M_n(R) \to M_n(R)$, by $f((A,B)) = AB$. We know that this map is continuous. Can we try to prove that invertible matrices form an open subset of $M_n(R)$ by somehow using this map. (I already know how to prove it by using the map of determinant)

A: Unfortunately we cannot. Invertible matrices would be represented by pairs (A,B) such that AB = I. Namely this set of pairs is $f^{-1}(I)$ which is a closed set in $M_n(R) \times M_n(R)$.

A: You can using the implicit function theorem.
We have ${\partial f(A,B) \over \partial A}(H) = HB$, which is invertible whenever $B$ is invertible. (The inverse map is $H \mapsto H B^{-1}$.)
Note that $f(A^{-1},A) = I$, hence the implicit function theorem tells us that there are open $U,V$ with $A \in U$, $A^{-1} \in V$ and a $C^1$ function $\phi: U \to V$ such that $f(\phi(X), X ) = I$ for $X \in U$ and
$\phi(A) = A^{-1}$.
Since $\phi(X) = X^{-1}$, and $U$ is open, we see that the set of invertible matrices is open.
(In fact, this shows that the derivative of the inverse map
is ${\partial \phi(A) \over \partial A}(H) = - A^{-1}H A^{-1}$.)
Alternative: A simpler alternative is to use the fact that $A \mapsto \det A$ is a continuous map.

A: Suppose  $A^{-1}$ exists . We have :  $A+C =A(1+A^{-1} C)$ is invertible $\iff 1+A^{-1} C$ is invertible. For brevity let $B=A^{-1} C.$ Suppose $C$ belongs to the open ball about $A$ with radius $1/(2\|A^{-1}\|).$ Then for $n\in N$ we have $\|B^n\|<2^{-n}.$ Now for $n\in N$ let $ D_n=1+\sum_1^n (-B)^n.$ Then $D_n$ converges in norm to a limit $D.$ The continuity of $f(X,Y)=X Y$ implies that $(1+B) D_n$  converges in norm to $(1+B) D.$ But $(1+B) D_n= 1-B^{-n-1}$ converges in norm to $1.$ Therefore $(1+B) D=1$ so $1+B=1+A^{-1} C$ is invertible .

A: Use $\text{det}^{-1}(\Bbb{R} \setminus {0})$ is open .


text:
Q: Screen capture video using AForge.Video.FFMPEG / AForge.Video.VFW. Frame Rate issue My WinForms .NET 4 C# application records the desktop while the user interacts with it.
It uses the AForge FFMPEG or VFW wrappers depending on the speed of the system. The capturing is done in a background thread of course.
In either case, the wrappers require the frame rate to be specified in advance. This is problematic since capturing frequency is undeterministic and easily affected by how busy the target machine is. On a good system, I get a maximum of 10 FPS.
So two issues here:

*

*How to align frames based on actual capture frame rate?

*How to increase the frame rate, perhaps by using a solution other than AForge?

The code I use is listed below for clarity:
private void ThreadWork ()
{
    int count = 0;
    string filename = "";
    RECT rect = new RECT();
    System.Drawing.Bitmap bitmap = null;
    System.Drawing.Graphics graphics = null;
    System.DateTime dateTime = System.DateTime.Now;
    System.IntPtr hWndForeground = System.IntPtr.Zero;
    AForge.Video.FFMPEG.VideoFileWriter writer = null;

    filename = @"c:\Users\Raheel Khan\Desktop\Temp\Capture.avi";
    if (System.IO.File.Exists(filename))
        System.IO.File.Delete(filename);

    writer = new AForge.Video.FFMPEG.VideoFileWriter();
    writer.Open
    (
        filename,
        System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width,
        System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height,
        10, // FPS
        AForge.Video.FFMPEG.VideoCodec.MPEG4
    );

    bitmap = new Bitmap
    (
        System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width,
        System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height,
        System.Drawing.Imaging.PixelFormat.Format24bppRgb
    );
    graphics = System.Drawing.Graphics.FromImage(bitmap);

    dateTime = System.DateTime.Now;

    while (System.DateTime.Now.Subtract(dateTime).TotalSeconds < 10) // 10 seconds.
    {
        graphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size);

        rect = new RECT();
        hWndForeground = GetForegroundWindow();
        GetWindowRect(hWndForeground, ref rect);
        graphics.DrawRectangle(Pens.Red, rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
        graphics.DrawString(count++.ToString(), this.Font, Brushes.Red, 10, 10);

        writer.WriteVideoFrame(bitmap);

        System.Threading.Thread.Sleep(10);
    }

    writer.Close();
    writer.Dispose();

    System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(filename));
}

A: You could capture the frames to a temp folder as jpegs or to a mjpeg file, and then reprocess it to an avi video file when the user desires it. This will cut down on the amount of processing you need to do 'on the fly' and free up resources - and allow your system to reach a higher and more regular frame rate.


text:
Q: odoo15 kanban view doesn't support one2many field lading_adapter_ids is a one2many field in the module.
Here is code, and all t-out show a blank.
 <t t-foreach="record.lading_adapter_ids.raw_value" t-as="o">
                                        <t t-out="o.name" />
                                         <t t-if="i % 2 != 0" >

                                        </t>
                                        <t t-set="i" t-value="1"/>

                                        <t t-out="o.district" />

                                          <t t-out="o.display_name" />

                                          <t t-out="o.eng_address" />

                                     </t>

A: Unfortunately, you can't use those fields.
The function that builds the object containing the formatted record data used in the template, sets the raw_value to a list of ids in the case of one2many and many2many fields
From kanban view documentation:

Each field has two attributes value and raw_value, the former is formattedaccording to current user parameters, the latter is the direct value from a read()(except for date and datetime fields that are formatted according to user's locale)

By default, fields are replaced by their formatted value, unless the widget attribute is specified, so you can define a new widget, like many2many_tags to change the behavior of the One2many field in kanban views.
If you look in the FieldMany2ManyTags class you will see a special attribute fieldsToFetch used to retrieve the fields used in the rendering context.
To define a new widget, kanban_address based on the value of a One2many field:

*

*You need to extend the AbstractWidget

*Set the fields to retrieve

*Define a new template

*Alter the _render function to render the newly created template.

*And finally, use the new widget in the field tag in the kanban view.

Example:
1- Kanban Widget
/** @odoo-module **/
import field_registry from 'web.field_registry';
import AbstractField from 'web.AbstractField'
import  { qweb as QWeb, _t } from 'web.core';

var FieldKanbanAddress = AbstractField.extend({
    custom_template: "kanban_address",
    supportedFieldTypes: ['one2many', 'many2many'],
    fieldsToFetch: {
        name: {type: 'char'},
        district: {type: 'char'},
        display_name: {type: 'char'},
        eng_address: {type: 'char'},
    },

    _render: function () {
        var elements = this.value ? _.pluck(this.value.data, 'data') : [];
        this.$el.html(QWeb.render(this.custom_template, {elements: elements}));
    },
});

field_registry.add('kanban.kanban_address', FieldKanbanAddress);

2- Custom template
<?xml version="1.0" encoding="UTF-8"?>
<templates id="template" xml:space="preserve">
    <t t-name="kanban_address">
        <t t-foreach="elements" t-as="o">

        </t>
    </t>
</templates>

3- widget attribute
<field name="move_raw_ids" widget="kanban_address"/>

4- Specify JS and XML files in the manifest
'assets': {
    'web.assets_backend': [

        '{MODULE_NAME}/static/src/js/kanban_address.js',
    ],
    'web.assets_qweb': [
        '{MODULE_NAME}/static/src/xml/kanban_address.xml',
    ],
},


text:
Q: Pgfplots: Weird letters on axis I am trying to plot something with pgfplots (first time using it), and for some reason there are some weird letters on the y-axis. Here is the relevant code as well as a picture:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
axis lines = center,
xlabel = $x$,
ylabel = {$f(x)$},
]
\addplot [
domain=0:0.5,
samples=1000,
color=red,
]
{sin(deg(x^-1))};
\end{axis}
\end{tikzpicture}

Any help would be much appreciated.

A: Your code does not compile correctly:
./bla2.tex:16: Missing number, treated as zero.
<to be read again>
                   i
l.16 {sin(deg(x^-1))};

The _fpt value stems from the fact that your domain ranges from 0:0.5, i.e. for the first point pgfplots would calculate 1/0. This raises the floating point exception which results in the value _fpt. Since pgfplots cannot identify this value as a number, it just puts it down.
A simple solution:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
axis lines = center,
xlabel = $x$,
ylabel = {$f(x)$},
]
\addplot [
domain=0.00001:0.5,
samples=1000,
color=red,
]
{sin(deg(x^-1))};
\end{axis}
\end{tikzpicture}


text:
Q: Associate bitbucket to Forge Laravel I can't Associate bitbucket to Forge
I got this Error
bitbucket.org SSH-2.0-OpenSSH_6.4
bitbucket.org SSH-2.0-OpenSSH_5.3
no hostkey alg
Cloning into 'mySite.com'...
Warning: Permanently added the RSA host key for IP address 'Host IP' to the list of known hosts.
Composer could not find a composer.json file in /home/forge/mySite.com
To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section
How can I get started??


text:
Q: ReactJS, Need one component to wait on the work done in another component to begin rendering So I have 3 components that are supposed to render inside a holder component. The 3rd component relies on the work done in the 2nd component, and the 2nd component relies on the work done in the 1st component. They both asynchronously read and write from a firebase firestore database, which obviously presents a problem. I'm getting issues because the 2nd component tries to access something from the database which doesn't exist yet, because the first component adds it.
This is how I have the components set up:
<React.Fragment>
  <div className="flex">
    <GroupPreferences />
    <SetupDatabase gId={groupID} />
    <Restaurants gId={groupID} user={user} history={history} />
  </div>
</React.Fragment>

The work done on the components relies on hooks, where the first component uses UseEffect() and the other two use ComponentDidMount(). I need to somehow wait for all the database work in GroupPreferences to finish before SetupDatabase begins rendering.

A: You should pass callback functions to each child component, when logic inside will be done, they should trigger that callback, so you will know that the child component is done.
If you just need to understand if components have been rendered, you can use React.ref. if Ref.current have value, components are on the screen, if ref.current doesn't have value, it's haven't rendered yet


text:
Q: NSString boundingRectWithSize:options:attributes:context: not usable in Swift? I get the error...
Could not find an overload for 'init' that accepts the supplied arguments
...when I try to use...
extension UIFont {
  func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
    NSString(string).boundingRectWithSize(CGSize(width, DBL_MAX),
                                          options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                                          attributes: [NSFontAttributeName: self],
                                          context: nil).size
  }
}

Does NSString not support this method anymore, or am I messing up on the syntax?

A: The initializers expect named arguments.
extension UIFont {
    func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: string).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin,
            attributes: [NSFontAttributeName: self],
            context: nil).size
    }
}

Note: Strings can be cast to NSStrings.
extension UIFont {
    func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
        return (string as NSString).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin,
            attributes: [NSFontAttributeName: self],
            context: nil).size
    }
}

or
extension UIFont {
    func sizeOfString (string: NSString, constrainedToWidth width: Double) -> CGSize {
        return string.boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin,
            attributes: [NSFontAttributeName: self],
            context: nil).size
    }
}

--
UPDATED
For Swift 4 syntax
extension UIFont {
    func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: string).boundingRect(
            with: CGSize(width: width, height: .greatestFiniteMagnitude),
            options: .usesLineFragmentOrigin,
            attributes: [.font: self],
            context: nil).size
    }
}

A: Alternatively you could cast it into an NSString
if let ns_str:NSString = str as NSString? {

   let sizeOfString = ns_str.boundingRectWithSize(
                                 CGSizeMake(self.titleLabel.frame.size.width, CGFloat.infinity),
                                 options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                                 attributes: [NSFontAttributeName: lbl.font],
                                 context: nil).size
}

A: Latest Swift
func sizeOfString (string: String, constrainedToHeight height: Double) -> CGSize {
    return NSString(string: string).boundingRect(with: CGSize(width: DBL_MAX, height: height),
                                                 options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                 attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 20)],
                                                 context: nil).size
}

A: Latest Swift:
import UIKit

extension UIFont {
    func sizeOfString(string: String, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: string).boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude),
                                                             options: .usesLineFragmentOrigin,
                                                             attributes: [NSFontAttributeName: self],
                                                             context: nil).size
    }
}

A: You can use objective-c bridging
let lblRegisterlinkWidth: CGFloat = lblRegisterLink.text!._bridgeToObjectiveC().boundingRectWithSize(lblRegisterLink.frame.size, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName : lblRegisterLink.font], context: nil).size.width

A: Swift 4.1 version
extension UIFont {
    func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: string).boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: self], context: nil).size
    }
}

A: Latest Swift 5:
extension UIFont {
    func size(OfString string: String, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: string).boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude),
                                                     options: .usesLineFragmentOrigin,
                                                     attributes: [.font: self],
                                                     context: nil).size
    }
}

A: Swift 5
extension String {
    func sizeOfString(maxWidth: CGFloat, font: UIFont) -> CGSize {
        let tmp = NSMutableAttributedString(string: self, attributes:[NSAttributedString.Key.font: font])
        let limitSize = CGSize(width: maxWidth, height: CGFloat(MAXFLOAT))
        let contentSize = tmp.boundingRect(with: limitSize, options: .usesLineFragmentOrigin, context: nil)
        return contentSize.size
    }
}


text:
Q: BizTalk and SalesForce integration: the query or retrieve function returns unknown type I'm integration a legacy on premise BizTalk Server with SFDC (Salesforce CRM on Demand). I'm using BizTalk 2009 with WCF custom ports. I have imported the enterprise WSDL and successfully used it to create an accounts in SFDC. The problem occurs when I try to use the retrieve (or query) function to get user details, everything is working nicely except when I try to "use" the response message.
Request:
<ns0:retrieve xmlns:ns1="urn:sobject.enterprise.soap.sforce.com" xmlns:ns0="urn:enterprise.soap.sforce.com">
    <ns0:fieldList>Name, Email</ns0:fieldList>
    <ns0:sObjectType>User</ns0:sObjectType>
    <ns0:ids>005900000023xmcAAA</ns0:ids>
</ns0:retrieve>

Receive pipeline is the standard XMLReceive.
Response message:
<retrieveResponse xmlns="urn:enterprise.soap.sforce.com">
    <result xsi:type="sf:User" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <sf:Id xmlns:sf="urn:sobject.enterprise.soap.sforce.com">005900000023xmcAAA</sf:Id>
        <sf:Email xmlns:sf="urn:sobject.enterprise.soap.sforce.com">jredwood@charteredaccountants.com.au</sf:Email>
        <sf:Name xmlns:sf="urn:sobject.enterprise.soap.sforce.com">Julian Redwood</sf:Name>
    </result>
</retrieveResponse>

Error Details:"Unable to read the stream produced by the pipeline.
 Details: The value 'sf:User' is invalid according to its schema type 'http://www.w3.org/2001/XMLSchema:QName' - 'sf' is an undeclared namespace. ".

A: Yes, that response is rather messed up.
It declares the a default name space at the root xmlns="urn:enterprise.soap.sforce.com"
It doesn't declare the sf namespace prefix at the root e.g. (xmlns:sf="urn:sobject.enterprise.soap.sforce.com").
And then for user has it as xsi:type="sf:User" where it then doesn't have the sf prefix defined for the result node.
Either it needs to declare it either in the root or at the result node level.
Option 1) If you the ESB Toolkit you could try and use the ESB Add Namespace pipeline component and add the NamspacePrefix = sf and NamspaceBase = urn:enterprise.soap.sforce.com
Option 2) Raise it as in issue with Salesforce as that is not valid.
Or both.


text:
Q: Delete particular mp3 files in a directory that has no metadata(Title,artist etc)? I want to delete particular mp3 files in a directory that has no metadata(Title, artist, etc). I tried sorting the files and then deleting it manually but it didn't work as the number of files is huge(~30K). Is there any python script to accomplish this task?

A: This example script is not completed, but I hope that good start point for you.
import os
import glob
from mutagen.easyid3 import EasyID3

mp3_files_list = glob.glob(path/to/your/mp3-files-folder/*.mp3) # example path /home/user/Downloads/mp3/*.mp3

for mp3_file in mp3_files_list:
    audio = EasyID3(mp3_file)
    if not audio['title']: # if title tag is empty
        os.remove(mp3_file)
    if not audio['artist']:
        os.remove(mp3_file)
    # etc tags check

Mutagen module documentation: https://mutagen.readthedocs.io/en/latest/


text:
Q: Beginner prime factorization I wrote a beginner program that aims to find and print the prime factors of any number:
def is_prime(n):
    if n == 3:
        return True
    elif n == 4:
        return False
    else:
        n = int(n**0.5)+1
        for i in range(2,n):
            if n % i == 0:
                return False
        return True

def prime_factors(n):
    for i in range(2,n):
        if n % i == 0:
            x = i
            primes.append(x)
            y = n / x
            return y
            break

primes = []

def main(y):
    while not is_prime(y):
        y = prime_factors(y)
    primes.append(y)
    print(primes)

Here are examples of runs of the program, which have me confused:
main(625)

[5, 5, 5, 5]

...

main(160)

[160]

...

main(6)

[6]

...

main(1007)

TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'float'

Some inputs work, and some don't. I can't figure out why. I also can't figure out how to fix that error from coming up. Please help. Thank you.

A: Your is_prime function seems to incorrectly reuse the variable n in these lines:
    n = int(n**0.5)+1
    for i in range(2,n):
        if n % i == 0:

You might consider using more descriptive names, such as factor_limit for example.

A: you have many many problems , here are some of the most noticeable ones
1.
TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'float'
is telling you that python doesnt know how to None**0.5
2. as mentioned in the other answer you are checking if the square root of n is divisble by i not if N is divisible by i
3.
def prime_factors(n):
    for i in range(2,n):
        if n % i == 0:
            x = i
            primes.append(x)
            y = n / x
            return y
            break #<--- this is totally worthless and does nothing
    #if you get here you are returning None... which breaks(see #1)
    return [1] #might fix your problem ...

there are likely some other issues as well


text:
Q: Nginx Gunicorn one ip multiple django sites in folders thanks for reading my question.
I'm trying to serve multiples Django sites on their own folders in one server without domain (only IP address) using Gunicorn and Nginx. Something like that:
20.20.20.20/demos/myapp1/ --> Django app
20.20.20.20/demos/myapp2/ --> Django app
20.20.20.20/demos/myapp3/ --> Django app

I have tested a lot of settings but I can't make it work. When i tried to load URL 20.20.20.02/demos/myapp1/ i get a 404 not found error :(
Example one site nginx conf:
upstream app1_server {
    server unix:/webapps/myapp1/run/gunicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name 20.20.20.20;

    keepalive_timeout 5;
    client_max_body_size 4G;

    location /static/ {
        alias   /webapps/myapp1/static/;
    }

    location /media/ {
        alias   /webapps/myapp1/media/;
    }

    location /demos/myapp1/ {
        try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app1_server;
    }

    # Error pages
    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /webapps/myapp1/static/;
    }
}

What is wrong with my myapp1.conf file?
For the record, if i change "location /demos/myapp1/" to "location /" my first app works, but the others apps still not working.
Thanks in advance.
Edit 1:
Checking my problem.. For now i found a solution. Rewrite rule:
location /myapp1/ {
    rewrite ^/myapp1(.*) $1 break;
    try_files $uri @proxy_to_app;
}

Is a good solution? My Django apps broken their urls :(

A: Well, reading about Nginx, i solved my problem in 4 steps:

*

*Using rewrite rule like my edit post.

*Listen each app in diferent port, like this:
server {
    listen 81;
    server_name 20.20.20.20;

    location /demos/myapp1/ {
        rewrite ^/demos/myapp1(.*) $1 break;
        try_files $uri @proxy_to_app;
    }
   ...
}

server {
     listen 82;
     server_name 20.20.20.20;
     location /demos/myapp2/ {
         rewrite ^/demos/myapp2(.*) $1 break;
         try_files $uri @proxy_to_app;
     }
    ...
}

server {
    listen 83;
    server_name 20.20.20.20;
    location /demos/myapp3/ {
        rewrite ^/demos/myapp3(.*) $1 break;
        try_files $uri @proxy_to_app;
    }
    ...
}

*Reload Nginx
sudo service nginx restart

*Test it:
http://20.20.20.20:81/myapp1/
http://20.20.20.20:82/myapp2/
http://20.20.20.20:83/myapp3/

If you have a better way to solve my problem, please let me know!


text:
Q: Is there a 40 face single polygon toroid? Solutions for 24 and 32 face single polygon toroid have been given.  Is there a solution for the next step of a 40 face single polygon toroid?
Is there a simpler single polygon toroid?
The opening on the 24 face toroid is an equilateral triangle.  The opening on the 32 face toroid is a regular square.  It seems there should be a 40 face single polygon toroid with a regular pentagonal opening.

A: A simple google search with the title of this post brings up this very post on first place and a solution with 48 triangles on the second.
--- rk