List field in model?

Question: In my model, I want a field that has a list of triplets. e.g. [[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]. Is there a field that can store this data in the database?
Comment: Which database are you using?
Comment: look into this for mysqlDB:
https://stackoverflow.com/questions/58836793/is-that-possible-to-store-array-in-mysql-database-using-django-model/65814823#65814823
Answer: You can convert it into string by using JSON and store it as string.
For example,
In [3]: json.dumps([[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]])

Out[3]: '[[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]'

You can add a method into your class to convert it automatically for you.
import json

class Foobar(models.Model):
    foo = models.CharField(max_length=200)

    def set_foo(self, x):
        self.foo = json.dumps(x)

    def get_foo(self):
        return json.loads(self.foo)

If you're using Django 1.9 or above, and you use postgresql, there is a new class called JSONField, you should use it instead. Here is a link to it
There is a good talk about PostgreSQL JSONs and Arrays on youtube. Watch it, it has very good information.
Comment: In Django 1.10 and above, there's a new `ArrayField` field you can use. See answer below.
Comment: Is there a specific reason that we may use json serialization instead of a custom List field (like the second answer in this thread)? I'm having this concern performance-wise mainly but also I'd like to know if there is anything else that I should notice before choosing between these two approaches. Thanks in advance!
Comment: Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json.
Comment: json.dumps will make a full json conversion changing things like _None_ --> _null_. I don't get why to use that when you want a list->string conversion
Comment: You can use JSONField natively if you're running postgresql
Comment: Also, you will get null in a string
Comment: @Ahmed I try your solution using json loads and dumps. but when i use the function "get_foo(self)" in django template, I get an JSONDecodeError.
Comment: It means you are trying to decode a value that cannot be read by JSON. What are you trying to decode?
Answer: If you're on Django 1.10 or newer AND Postgres as your database, you can use  ArrayField. It's better to use than django-taggit or other alternatives, as it's native to the Django framework.
https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#arrayfield
from django.db import models
from django.contrib.postgres.fields import ArrayField

class ChessBoard(models.Model):
    board = ArrayField(
        ArrayField(
            models.CharField(max_length=10, blank=True),
            size=8,
        ),
        size=8,
    )

If you're on Django 3.1 or newer they've added support for JSONField with most database backends (MariaDB 10.2.7+, MySQL 5.7.8+, Oracle, PostgreSQL, and SQLite 3.9.0+). You can use this to store your Array!
https://docs.djangoproject.com/en/3.1/ref/models/fields/#jsonfield
from django.db import models

class ChessBoard(models.Model):
    list_of_pieces = models.JSONField()

Comment: Thanks! Looks like its [postgres specific](https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/#arrayfield) but a great one!
Comment: How do you use this?
from django.db import models
class ChessBoard(models.Model):
    list_of_pieces = models.JSONField()
What is next? Where are your list? Do you have any field in DB or did you created a list somewhere?
Answer: If you are using PostgreSQL, you can use ArrayField with a nested ArrayField: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/
This way, the data structure will be known to the underlying database. Also, the ORM brings special functionality for it.
Note that you will have to create a GIN index by yourself, though (see the above link, further down: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/#indexing-arrayfield).
(Edit: updated links to newest Django LTS, this feature exists at least since 1.8.)
Answer: I think it will help you.
from django.db import models
import ast

class ListField(models.TextField):
    __metaclass__ = models.SubfieldBase
    description = "Stores a python list"

    def __init__(self, *args, **kwargs):
        super(ListField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value:
            value = []

        if isinstance(value, list):
            return value

        return ast.literal_eval(value)

    def get_prep_value(self, value):
        if value is None:
            return value

        return unicode(value)

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

class ListModel(models.Model):
    test_list = ListField()

Example :
>>> ListModel.objects.create(test_list= [[1,2,3], [2,3,4,4]])
<ListModel: ListModel object>
>>> ListModel.objects.get(id=1)
<ListModel: ListModel object>
>>> o = ListModel.objects.get(id=1)
>>> o.id
1L
>>> o.test_list
[[1, 2, 3], [2, 3, 4, 4]]
>>>

Comment: I am using python 3.5 so there are couple of issues - unicode is now str and  I am getting an error ..create() takes 1 positional argument but 2 were given
Comment: I used this solution in django 1.7. Now i upgraded it to 1.9.12 But it is not working. What change should I made for make it workable in django 1.9.12
Comment: Please share error you are getting , also which version of python you are using ?
Comment: Consider using `json.loads` instead of `ast.literal_eval`, because the former is around 6 times faster.
Answer: It's quite an old topic, but since it is returned when searching for "django list field" I'll share the custom django list field code I modified to work with Python 3 and Django 2. It supports the admin interface now and not uses eval (which is a huge security breach in Prashant Gaur's code).
from django.db import models
from typing import Iterable

class ListField(models.TextField):
    """
    A custom Django field to represent lists as comma separated strings
    """

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs['token'] = self.token
        return name, path, args, kwargs

    def to_python(self, value):

        class SubList(list):
            def __init__(self, token, *args):
                self.token = token
                super().__init__(*args)

            def __str__(self):
                return self.token.join(self)

        if isinstance(value, list):
            return value
        if value is None:
            return SubList(self.token)
        return SubList(self.token, value.split(self.token))

    def from_db_value(self, value, expression, connection):
        return self.to_python(value)

    def get_prep_value(self, value):
        if not value:
            return
        assert(isinstance(value, Iterable))
        return self.token.join(value)

    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        return self.get_prep_value(value)

Comment: Thanks Heaps. I am using Django 1.11, and had to change member function to take 5 parameters "def from_db_value(self, value, expression, connection, context):"
Answer: Just use a JSON field that these third-party packages provide:

django-jsonfield
django-annoying

In this case, you don't need to care about the field value serialization - it'll happen under-the-hood.
Answer: With my current reputation I have no ability to comment, so I choose answer referencing comments for sample code in reply by Prashant Gaur (thanks, Gaur - this was helpful!) - his sample is for python2, since python3 has no unicode method.
The replacement  below for function get_prep_value(self, value): should work with Django running with python3 (I'll use this code soon - yet not tested).
Note, though, that I'm passing encoding='utf-8', errors='ignore' parameters to decode() and unicode() methods. Encoding should match your Django settings.py configuration and passing errors='ignore' is optional (and may result in silent data loss instead of exception whith misconfigured django in rare cases).

import sys

...

    def get_prep_value(self, value):
        if value is None:
            return value
        if sys.version_info[0] >= 3:
            if isinstance(out_data, type(b'')):
                return value.decode(encoding='utf-8', errors='ignore')
        else:
            if isinstance(out_data, type(b'')):
                return unicode(value, encoding='utf-8', errors='ignore')
        return str(value)
...
Answer: You can flatten the list and then store the values to a CommaSeparatedIntegerField. When you read back from the database, just group the values back into threes.
Disclaimer: according to database normalization theory, it is better not to store collections in single fields; instead you would be encouraged to store the values in those triplets in their own fields and link them via foreign keys. In the real world, though, sometimes that is too cumbersome/slow.
Comment: Note that this is deprecated as of Django 1.9 per the link in the article.
Answer: If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine library, there is a built in ListField that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.

List field in model?


Remove Ubuntu from stand-alone hard drive. Format drive

Question: I guess that I have no other choice than to add to this question, as seth saw fit to delete the question I thought I was asking as a new question. But whatever. I have a dead computer thanks to my having installed it in the first place. It will not boot either or any hard drives, and gives me the same answer
<code>Error No such device
3dddc179-e42e-4666-8ff3-00566a57908a
Entering rescue mode
</code>
grub rescue> all it does is flash the cursor nothing more from there.
My computer is useless as is. I can not load either OS, and have no idea how to fix it, short of taking it to a shop. I don't understand, how to fix it, if I can't even open it up. All i want is a straightforward answer on how to fix the problem. As this is the only means I have of contacting anybody on how to fix the problem. which I assume is in the BIOS setup. with grub. I need answers, not negative stuff like you need to use the forum more so that you have more privileges. If anybody really know how I can get my computer back to having just Windows 7 and my other hard drive formatted again so I can start over. Without ubuntu at least until I can figure out how to put the live CDs on a USB flash drive. And one then in the try mode, instead of the install mode as that is all I am given on the CD's I've got now.

I am either dumb as a rock, or I am brain dead. I have tried and tried to figure out all the in's and out's of down loading Live CD's and to boot them so I can check them out before installing. I thought I had downloaded the live CD program that would let me do that. For ubuntu, mint, and zorin. I guess that I downloaded the full version of all three.
I don't know if there are individual downloads for the Live CD programs for those OS's as well as full CDs? Anyway, I got the CD to open, their was no option to install or open live. I ended up hitting the Install. And sent it to a blank stand alone hard drive. It installed, but I am not sure how to open it. Anyway I tried to format the drive, and it says that it is now write protected.
I would really like to remove everything from that disk, starting over by trying each system, before installing one or more of them on that hard drive. It is 1.5TB. Any help you can provide is welcome. And if you can explain exactly how to download and burn the correct programs for a live CD so I can test them out. I have read page after page from Linux about all these subjects and the more I read the worse it gets. I need a simple how to that I can use for each system, without having to download fifteen different things to do this that or the other thing.
I was under the belief that Linux was easy to use. That may be once I get it on the computer. Its getting there that has confused me. Please somebody help.
Comment: If you are using Windows, have you tried using MiniTool Partition Wizard to format the drive? http://www.partitionwizard.com/free-partition-manager.html
Comment: I have two internal hard drives on this computer. Win 7 i son one, and I guess I installed ubuntu on the other. But I would like to clear and format the one with ubuntu. And download and open the Live CD or USB so I can check them out first before installing them onto the second drive. I was trying to divide that drive into thirds. But I guess I screwed that up also.
Comment: @magicgraywolf I know it's trivial, but have you tried setting the boot order to the windows drive?
Answer: I always use liveUSBs because they are far, far faster.  A liveCD likely will not give you a good experience.
This is where you can download Ubuntu.
http://www.ubuntu.com/download/desktop
This is how you can turn any flash drive into a liveUSB using the downloaded .iso.  If you need to use a CD, the link should be on this page as well.
http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-windows
Comment: Thanks for your reply. I have tried making a Live USB for all three programs, it does not to seem to be working, or I've not figured it out.


Passin args to laravel eloquent api resources constructor

Question: How I can pass args to Laravel Eloquent API Resources constructor and get it to conditional data returning on response?
What I tried:
Controller
$user = User::find(1);
return new UserResource($user, $shortData = true);

API Resource:
public function toArray($request, $shortData)
{
    if($short) {
        return $shortData;
    } else {
        return $fullData;
    }
}

Comment: *What I tried:* What was error/result?
Comment: @Tpojka No error result. This code only not worked for me. Wher set value of `$shortData` true or false in both case return full data
Answer: You have to do something like this :

Add the conditional data in your constructor (like you did). This conditional data can be null :

$user = User::find(1);
return new UserResource($user, $conditionalData);

Then in your UserResource, add the conditional data as a private attribute and add it to your constructor like this (it works as well with PHP default argument value...) :

private $conditionalData;

    public function __construct(User $resource, ?string $conditionalData)
    {
        parent::__construct($resource);
        $this->conditionalData = $conditionalData;
    }

Last thing you have to do is to use Laravel Conditional Attribute system (https://laravel.com/docs/7.x/eloquent-resources#conditional-attributes). The when method allows you to expressively define your resources without resorting to conditional statements when building the array.

public function toArray($request)
    {
        return [
            'data_1' => $this->data1,
            'data_2' => $this->data2,
            'conditional_data' => $this->when(!is_null($this->conditionalData), $this->$conditionalData)
        ];
    }

Your conditional data will be present in your response only if the attribute is not null.


Icons disappear after saving file Ubuntu 20.04 LTS

Question: ISSUE
After saving a text file, some icons and folders on the desktop disappear. When you manually refresh screen using ALT-F2, then enter "r", the icons reappear.
EXAMPLE
Open a text file
Make a change, save, then some desktop icons and files disappear
After manual refresh (ALT-F2 > "r") they all reappear
REMEDIES ATTEMPTED
sudo apt install gnome-shell-extension-desktop-icons from Ubuntu 20.04 desktop files and icons missing
sudo apt install --reinstall gnome-control-center

SYSTEM DETAILS

OS: Ubuntu 20.04 LTS
TYPE: 64-bit
GNOME VERSION: 3.36.3
Windowing System: X11

Thanks
Comment: Looks like a bug with the Desktop extension: this extension is recent and in early development
Comment: This has been reported by [Launchpad Bug #1883174](https://bugs.launchpad.net/ubuntu/+source/gnome-shell-extension-desktop-icons/+bug/1883174).
Answer: It seems there is a bug in Gnome. I found two different reports:
https://bugs.launchpad.net/ubuntu/+source/gnome-shell-extension-desktop-icons/+bug/1883174
https://bugs.launchpad.net/ubuntu/+source/gnome-shell-extension-desktop-icons/+bug/1816205
I have both symptoms here. Saving a file in desktop sometimes just flashes the icons but sometimes makes most of them to disappear - but not all of them. And I'm pretty sure the ones that stay on screen are always the same.
There was a proposed fix on 2020.12.07 but I haven't tested it. Will wait.


Discuss the continuity and differentiability

Question:
Discuss the continuity and differentiability of $f$ at zero, where
  $$f(x) = \left\{
        \begin{array}{ll}
            x^2 & \quad  \text{if} \space x \gt 0 \\
            0 & \quad \text{if}\space x \leq 0.
        \end{array}
    \right.
 $$

I am stuck here trying to figure out the approach to discussing this.
Any suggestions or pushes in the right direction are greatly appreciated
Comment: Why are you stuck on continuity at $0?$ Do you know the definition?
Answer: You have:
$$
\lim_{x \to 0^-} f(x)=\lim_{x \to 0^+} f(x)=f(0)=0
$$
so the function is continuous.
For the derivative you can find the same result since
$$
f'(x)=
\begin {cases}
2x \qquad if \; x>0\\
0 \qquad if \; x\le 0
\end{cases}
$$
so the function is derivable in $x=0$.
Note that for the second derivative the result is different.
Answer: Hint:
To show continuity you can count $\lim_{x\rightarrow 0+}f(x)$ and $\lim_{x\rightarrow 0-}f(x)$. If these two limits equal, than the function is continuos.
You also know $f'(x)$ for all $x \in (0,\infty)$ and $x \in (-\infty,0)$. So again count limits from both sides.
Answer: Remember that a function is continuous if $$\lim\limits_{x \rightarrow c} f(x) = f(c)$$ This function is therefore continuous at $x = 0$ as $$\lim\limits_{x \rightarrow 0^+} f(x) = \lim\limits_{x \rightarrow 0^-} f(x) = 0$$ However continuity does not imply differentiability (only differentiability implies continuity), so we need to examine differentiability separately.
Note the definition of differentiability,
$$\lim\limits_{x \rightarrow c} \frac{f(x) - f(c)}{x-c} = f'(c) $$
For x = 0 we need to have
$$\lim\limits_{x \rightarrow 0^+} \frac{f(x) - f(c)}{x-c} = \lim\limits_{x \rightarrow 0^-} \frac{f(x) - f(c)}{x-c} = f'(c) $$
for the function to be differentiable at 0.
We can check this by taking the derivative of both pieces of the function at x = 0 and checking if they are equivalent at that point:
$$f'(x)=\begin {cases}2x \qquad if \; x>0\\0 \qquad if \; x\le 0\end{cases}$$
Hence both derivatives are equal at x = 0 so by the definition of differentiability we can say that the function is not only continuous at x = 0 but it is also differentiable at this point.


iOS - Chat application with push notification

Question: My question is simple, is it a good idea to develop chat application using push notifications? Hence push notifications are not reliable and there is no guaranty either they would arrive or not. If it is not reliable, which technique should be used for real time chat application?
Answer: Why not?
It's definitely possible to build a chat using iOS push notifications. @Aaron points are interesting, but don't make sense in my opinion for the following reasons:

If your app sends too many push notifications (and it will if you use that as the means of "chatting") no one will use your app because it will be annoying.

The only case here is when the app is not running and even then, apple will only send the last notification if there are too many in a row. When the app is in any other state (background, foreground active & inactive, suspended), the notification can be handled silently, using content-available : 1 in your push notification. If that's a worry for you, simply use badge notifications instead of alert notifications.

The user can also disable push notifications for your app so you can't rely on that as the only means of communication.

That is wrong, that doesn't prevent notifications for being sent to the phone, they are just not being shown to the user. See here. You can therefore handle silent notifications even though the user has disabled push notifications. This is just a setting, the device will still have a device token, and the backend will still be in a position to send push notifications.
However..
It is true that some remote notifications might not be delivered and using their content is not a good idea. But that is not a big issue..
The best is to use your notification as a refresh me I got a new message kind of notification. Once you get a new notification, ask the server for new messages in this chat, and update the table. We have implemented this in one of our project and are very happy with the results so far. Some say Premature Optimization is the root of all evil, in that case, you could spend a lot of time using sockets, but you can be up and running in no time with push notifications. Optimize later.
This works great:
{
    "aps" : {
        "content-available" : 1,
        "alert" : "This is my new notification",
    }
    "conversationId": 23,
    "senderId":44
}

Comment: @divergio absolutely certain! We do it for our apps. You still have a device token even though the user chooses to disable push notifications. When the user chooses not to receive push notification, that only means that he doesn't want to physically be alerted of a push notification. You can do whatever you wish silently!
Comment: "You can therefore handle silent notifications even though the user has disabled push notifications." Are you certain about this? In my testing, disabling push notifications seems to prevent silent notifications from reaching the app.
Answer: No. It is not a good idea, for at least two reasons:

If your app sends too many push notifications (and it will if you use that as the means of "chatting") no one will use your app because it will be annoying.
The user can also disable push notifications for your app so you can't rely on that as the only means of communication.

You want a polling system of some sort with a client/channel relationship. There are lots of server systems out there that can do this for you. WebSync is one:
http://www.frozenmountain.com/websync/
Answer: Disclaimer: Recently needed to develop a chat, and used push notifications for receiving the messages, it worked flawlessly. Sockets may be a good idea, but you will have a hard time transversing NAT if that is not done for you. So I don't agree with past me on this one.
Push notifications would be great if your app needed to be awoken from the background when the user got a new message, not for the chat itself.
There is a range of technologies that could be used, the simplest one, in my opinion would be using sockets (I think it simple due to the ammount of tutorials on the subject online)
one example:
http://www.raywenderlich.com/3932/networking-tutorial-for-ios-how-to-create-a-socket-based-iphone-app-and-server
Long story short, push notifications would be a fine addition to a chat application, but just as an extra (a very good extra indeed, they are not so unreliable and you can always do some logic to detect in the client if the push arrived, like making the app resend some sort of code for every push received, and resend the push if no code was received in a given time).
Just be aware that you will need a server to make the pushes work, so if your chat app is a success, it might cost you some money...
Comment: Sockets would require the antenna to be on as long the connection is open. This would consume too much energy.


Drupal7:Prevent image from uploading by pressing other ajax button

Question: I have created a form through structure in backened
1. field_dimensions from physcial module.
2. then added image field field_image
3. through form_alter added ajax button. below mention
      $form['getquote_fs']['getquote']['get-quote-btn'] = array(
    '#type' => 'button',
    '#name' => 'estimate',
    '#button_type' => 'button',
    '#executes_submit_handler' => false,
    '#limit_validation_errors' => array(array('field_dimensions')),
    '#size' => 5,
    '#weight' => 100,
    '#default_value' => 'get estimate',
    '#maxlength' => 5,
    '#description' => t('an industry estimate of how much would I pay.'),
    '#ajax' => array(
        'callback' => 'custom_startrack_ajax_cal',
        'method' => 'replace',
        'prevent'=> 'sumbit',
     ),

  );

Now when inside the form if I browse image and press either of the other ajax button.Its directly uploading the image.How i can remove it from being uploading in folder
Answer: you can disable the behavior of buttons easily with jquery.
try one of these:
$("#your-button-id").submit(function(e){
   return false;
});

or
$("#your-button-id").submit(function(e){
    e.preventDefault();
 });


Find a recurrence for the number of ways to arrange cars in a row with $n$ parking spaces

Question: Find a recurrence for the number of ways to arrange cars in a row with $n$ parking spaces if we can use Cadillacs or Hummers or Fords. A Hummer requires two spaces, while a Cadillac or Ford requires just one space.
I know I need to use a recurrence relation model such as $$a_n=a_{n-1}-a_{n-2}$$ but I don't know how to apply the concept to to this question fully. I have done a little bit of preliminary work but I do not know if it is necessarily correct:
We can assume that$$a_1 = 2$$Since given 1 space we can put either a Cadillac or a Ford. And we can also assume that$$a_2 = 5$$Since given 2 spaces, we can put CC, CF, FC, FF, or H. But where do I go from here?
Comment: In what direction have your own efforts towards this question been?
Comment: That actually makes perfect sense. Can you please post that as an answer, @Math1000
Comment: I legitimately do not know how to apply this concept to the question, and I can't seem to find any examples like this in my text book or anywhere else online. I realize it's unconventional here to not show any work, but I am legitimately stuck at square one. I'm not expecting a solution, but maybe a hint in the correct direction to get me started.
Comment: How about small values of $n$? What if you have 2 parking spots? Or 3? Or 4?
Comment: Okay, I did some basic preliminary work for 1 or 2 parking spots. But I still don't know how to come to a recurrence model from that.
Comment: A valid parking arrangement with $n$ cars consists of either one with $n-1$ cars with an added $C$ or $F$, or $n-2$ cars with an added $H$. So the recurrence relation is
$$a_n = 2a_{n-1} + a_{n-2}. $$
Answer: To fill a parking lot with $n$ spaces, you can either:

Fill the first $n-1$ spaces and then put a Cadillac or a Ford at the end; there are $2 \cdot a_{n-1}$ ways to do this ($a_{n–1}$ ways to fill the first $n-1$ spaces, and $2$ ways to fill the last space)
Fill the first $n-2$ spaces and then put a Hummer at the end; there are $a_{n-2}$ ways to do this

Adding the two, we get
$$a_n = 2a_{n-1} + a_{n-2}$$


unistd.h is not available, How to use fork()

Question: I want to exercise some UNIX commands using C language. When I include <unistd.h> header file and when I use fork() method it gives me a compile time error: "can not include unistd.h". I check on he Internet and the fork() method is available in <unistd.h> header file only. Please help me on this.

Is now <unistd.h> is replaced with any other header file?
Even if I use "process.h", that does not have a definition for fork().
How I can use fork() method?

I have DOSBox v0.74 on my system (Windows 7, 64-bit).
Comment: Neither DOSBox nor Windows have a native `fork` function, and as neither is a Unix variant they of course doesn't have the `` header file.
Comment: Can you show your error? Can you provide more context?
Comment: Does DOSBox provide ``?  Does it document its presence?  If not, maybe try [Cygwin](http://cygwin.com/) instead; that does provide a `fork()` emulation and ``.
Answer: The DOSBox web site says it is an emulation of DOS for Unix machines, not an emulator of Unix for Windows (DOS) machines.  You need Cygwin or MinGW or something similar if you want to emulate Unix on Windows.
Answer: There is no easy way of emulating fork() on win32 or dos.
Comment: So, as I indicated in my answer, DOSBox is the wrong tool for the job of running Unix code on a Windows machine.
Comment: But this isn't Windows; it's DOS, and DOS is fundamentally incapable of performing a `fork` operation.
Comment: True, but Cygwin provides a decent approximation to `fork()` for Windows.
Comment: The host environment is Windows 7.  It can run Cygwin, which provides a decent Unix emulation on Windows.
Comment: @JonathanLeffler DOSBox is an emulator running in the host environment. The code run in the emulator does not have access to Cygwin `fork` ;-)
Comment: @JonathanLeffler, yeah, well-told!
Comment: There is no way you would want to use such a primitive, obscure function in windows anyway, where you have CreateProcess() and similar better functions, that lead to smaller executables, less RAM consumption and less obscure code.
Comment: @Lundin but in the DOS we have nothing :)
Comment: Actually, DOS or at least some libc such as Turbo C's had fork... but it had semantics like vfork(), parent would halt until child was done.
Comment: @fasked No, because DOS was not a real OS, since it didn't support multiple processes. So it _really_ doesn't make any sense whatsoever to use fork() in DOS.
Comment: @AmigableClarkKant Sounds like a real useless function. Why couldn't an if statement be used instead?
Comment: @Lundin, Useless or not, it was there. Actually, it was quite useful for calling separate binaries and then returning back to your app whence the separate program was done. But this is all incidental, the OP likely needs Cygwin or something.
Comment: @AmigableClarkKant But if there were separate binaries, it doesn't sound like a fork() as it is spec:ed in *nix, but rather as something similar to Windows' CreateProcess()?
Comment: @Lundin, it was the old fork+exec combo
Answer: You always can declare anything yourself:
    pid_t fork(void);
However, if your system don't have unistd.h, it isn't POSIX compliant (or you haven't installed headers at all).
Comment: `fork` is wrapper over a system call, and you can't fully compile the code without `fork` being resolved at link-time...
Comment: How to make is POSIX compliant?
Comment: @Rahul.G well, you can't... unless you implement all of POSIX or find a working implementation by someone else.
Comment: Ofc you have to link with libc's fork to mate it working, but still - it exactly what header files do. And... Ouch, it's DOS... That was confusing. What it have to do with unix, anyhow?


AJAX/JSON with possible Jquery event

Question: I am trying to make it so when the user clicks on the name of a person in the list, the box of data on the right side of the screen fills with the description from my JSON file.
I want to make it so that clicking any list item runs an actual AJAX request. The data returned from that request must then be used to fill the box on the right side of the page.
Any ideas or previous thread you could lead me to would be very appreciated.  I've tried many things and have not succeeded.
Can I somehow make each word on the list a clickable element? Maybe with event listener?
Thanks,
Heres my code which is is 3 separate files whis are "html file, javascript file and a json file"
<!DOCTYPE html>
<hmtl lang="en">

        <meta charset="utf-8" />
        <title>AJAX</title>
        <link rel="stylesheet" href="styles.css" type="text/css" />

</hmtl>

/* ajax.javascript file */
'use strict';

$(function() {

    let request = $.ajax({
      method: 'GET',
      url : 'people.json',
      dataType: 'json',
    });

    request.done(function(data) {
      let list = data.body.list;
      let resultBox = $('#result-box');
      let unorderedList = $('
');
      resultBox.append(unorderedList);
      console.log(data);

      for (let person of list) {
        let listItem = $('
');
        listItem.text(person.name);
        listItem.attr('data-url', person.links[0].href);
        unorderedList.append(listItem);
      }

      });

      request.fail(function(response) {
      console.log('ERROR: ' + response.statusText);

      });
    });

{
"links":[{"rel":"self","href":"http://www.philart.net/api/people.json"},{"rel":"parent","href":"http://www.philart.net/api.json"}],
"head":{"title":"People","type":"listnav"},
"body":{
"list":[
{"name":"Adam","links":[{"rel":"self","href":"http://www.philart.net/api/people/325.json"}]},
{"name":"Abigail Adams","links":[{"rel":"self","href":"http://www.philart.net/api/people/157.json"}]},
{"name":"John Adams","links":[{"rel":"self","href":"http://www.philart.net/api/people/410.json"}]},
{"name":"Samuel Adams","links":[{"rel":"self","href":"http://www.philart.net/api/people/439.json"}]},
{"name":"Lin Zexu","links":[{"rel":"self","href":"http://www.philart.net/api/people/347.json"}]},
{"name":"James A. Zimble","links":[{"rel":"self","href":"http://www.philart.net/api/people/345.json"}]},
{"name":"Doris Zimmerman","links":[{"rel":"self","href":"http://www.philart.net/api/people/171.json"}]}
]
}
}

Answer: You just need a handler like this:
let displayPersonData = (person) => {
  console.log(person)
}

Then, while rendering list of person, you add event listener like below:
for (let person of list) {
    let listItem = $('
');
    listItem.text(person.name);
    listItem.attr('data-url', person.links[0].href);
    unorderedList.append(listItem);

    listItem.on('click', () => {
      displayPersonData(person)
    });
}

You can add class to
 tags so they act like hyperlink. And customize displayPersonData to do what you want.
Answer: As Doug Nguyen stated, you will need an event handler.
let displayPersonDescription = person => {
   let html = '';
   html += person.links.reduce((a, c) => {
      //put your formating logic in here
      //i.e.
     return a + `<a href="${c.href}">${c.href}</a>`;
   }, '');

    html += person.body.art.reduce((a, c) => {
      //additional formating logic here
    }, '');
// continue this pattern for all the sections you want to include
//...
// Finally load the data into the loaded-data div
   $("#loaded-data").html(html);
}

Here is the updated section of your code to implement the handeler
for (let person of list) {

    //clear the loaded data div
    $(#loaded-data).html('');

    let listItem = $('
');
    listItem.text(person.name);
    listItem.attr('data-url', person.links[0].href);
    unorderedList.append(listItem);
    listItem.on('click', function () {
        $.ajax({
                method: 'GET',
                url: this.dataSet.url,
                dataType: 'json',
            })
            .done(displayPersonDescription(person))
            .fail(failureData => console.log(`Error: ${JSON.stringify(failureData)}`));
    });
}

AJAX/JSON with possible Jquery event


How do you prop an exterior wall to replace rotted wood?

Question: I have an exterior wall, so load bearing, that is damaged.  About a 6ft span.  It's damaged at the bottom at the foundation, but it is enough to replace the studs.
How do I prop up the roof on the exterior wall, so I can make the repair?  It is the stud, bottom plate, the whole thing.  I may be able to sister the stud, but I am not sure yet, as I have to remove more siding to get the whole picture.  Plus the wood is 50 years old, but that may be a good thing?
The home is one story, so I won't be propping up two floors or anything.  Edge of the roof at the exterior wall.
Comment: A picture will get you better answers.
Comment: This question is impossible to answer without more detail. It would take a book to cover all the possible scenarios. Please revise to include photos or a sketch.
Comment: 50 year old wood will have different dimensions compared to today's wood, at least 1/4 to 1/2 inch larger than new wood.
Comment: @crip659 Does that mean I have to replace all of it instead of a portion (sister)?
Comment: Just might need to add thin wood strapping to one edge so that it equals out.
Answer: This shouldn't be too difficult since according to your post, the top plate is OK. You'll need to get a few floor jacks and support the top plate from the foundation. You can rent them at most home stores. The jacks can be a little out of plumb to replace your bottom plate but then straighten them up. I would just replace all the studs. It will be quicker than messing around trying to sister them. Studs are cheap, you'll probably need 5.
Comment: The jacks can be that long?  That is about 8ft from bottom to top where the frame meets the roof.
Comment: They sure can. I see them all the time at construction sites and in home stores for rental.


logic if then else

Question: I have a little problem concerning logical arguments
Year    month   day
null    +       +
null    -       +
null    +       -
nonnull -       +

I have translated it into code as follows
    if($year==null)
    {
        if($day!=null && $month!=null)
        {
            return null;
        }
        elseif($month!=null || $day!=null)
        {
            return null;
        }
    }

But I tell me that it's not correct.
[UPDATE]
- means null
+ means non-null
Comment: a) what about the case where "year" is not-null ? and b) your question is not clear - you should explain how do you translate this table as its not obvious...
Comment: No idea what you're trying to accomplish here, or what's not working.  Can you elaborate on your question please?
Comment: what means your table? It seems that nulls, pluses and minuses are all inputs. What should be your output?
Answer: if($year==null || ($day!=null && $month==null))
{
    reurn null;
}

If you want to return null in your cases (for example if year is null, month and day are not null (first case)) use this code. Because if I understood your question right, when year is null you want to return null anyway, and when it's not null you want to return null only if month is null and day is not.
Answer: @mesiesta - actually you can translate all those conditions into:
if ($year==null) {
 if ($day==null && $month==null) {
    return "undefined";
 }
 else {
    return null;
}

the table doesn't "cover" a few options, one of them I showed in the code above, the other are  all the other 3 options are when year is not null

logic if then else


How to display charts in Spyder

Question: Since November 2015, plotly is Open-Source and available for python. https://plot.ly/javascript/open-source-announcement/
When trying to do some plots offline, these work in iPython Notebook (version 4.0.4)
But if I try to run them in Spyder (version 2.3.8), i just get the following output:
<IPython.core.display.HTML object>
<IPython.core.display.HTML object>

There's something wrong in my code or the iPython Terminal of Spyder still doesn't support this?
Here goes the example code (taken from https://www.reddit.com/r/IPython/comments/3tibc8/tip_on_how_to_run_plotly_examples_in_offline_mode/)
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()

trace0 = Scatter(
    x=[1, 2, 3, 4],
    y=[10, 11, 12, 13],
    mode='markers',
    marker=dict(
        size=[40, 60, 80, 100],
    )
)
data = [trace0]
layout = Layout(
    showlegend=False,
    height=600,
    width=600,
)

fig = dict( data=data, layout=layout )

iplot(fig)

Answer: If you'd like to develop your plotly figures in Spyder, perhaps because of Spyders superb variable explorer, you can easily display a non-interactive image by just running fig.show(). Note that this is for newer versions of plotly where you don't have to worry about iplot and plotly.offline.
And if you'd like display your figure in the browser as a fully interactive version, just run:
import plotly.io as pio
pio.renderers.default='browser'

Now your figure will be displayed in your default browser.
To switch back to producing your figure in Spyder, just run:
import plotly.io as pio
pio.renderers.default='svg'

You can check other options too using pio.renderers?:
Renderers configuration
-----------------------
Default renderer: 'svg'
Available rendere <...> wser', 'firefox', 'chrome', 'chromium', 'iframe',
'iframe_connected', 'sphinx_gallery']

You'll find even more details here under Setting the default renderer
Here's a detailed example
Code:
import plotly.graph_objects as go

import plotly.io as pio
#pio.renderers.default = 'svg'
pio.renderers.default = 'browser'

x = ['Product A', 'Product B', 'Product C']
y = [20, 14, 23]

fig = go.Figure(data=[go.Bar(
            x=x, y=y,
            text=y,
            textposition='auto',
        )])
fig.show()

Plot:

System info:
Python 3.7.6
Spyder 3.3.1
Plotly 3.2.0

Comment: Defaulting the output to browser saved the day for me (using Spyder 5). Thank you!
Comment: @cgage1 Glad to hear it! Spyder and Plotly is a nice combo!
Comment: Using `pio.renderers.default='svg'` triggers `Image export using the "kaleido" engine requires the kaleido package`, but otherwise this is a very helpful answer.
Answer: importing plot instead iplot (and changing the last line from iplot(fig) to plot(fig) resolved the problem, at least in python 3:
from plotly.offline import download_plotlyjs, init_notebook_mode,  plot
from plotly.graph_objs import *
init_notebook_mode()

trace0 = Scatter(
    x=[1, 2, 3, 4],
    y=[10, 11, 12, 13],
    mode='markers',
    marker=dict(
        size=[40, 60, 80, 100],
    )
)
data = [trace0]
layout = Layout(
    showlegend=False,
    height=600,
    width=600,
)

fig = dict( data=data, layout=layout )

plot(fig)

But instead you could do the following, which is slightly easier:
import plotly
import plotly.graph_objs
plotly.offline.plot({
"data": [
    plotly.graph_objs.Scatter(    x=[1, 2, 3, 4],
    y=[10, 11, 12, 13], mode='markers',
    marker=dict(
        size=[40, 60, 80, 100]))],
"layout": plotly.graph_objs.Layout(showlegend=False,
    height=600,
    width=600,
)
})

Comment: Thanks @Dominix.
Both solutions work in python 2.70 as well.
Comment: Thanks. Will try it tom first thing in the morning. Have no PC available.

How to display charts in Spyder


Wifi Connected but No Internet access

Question: I connect to the Internet on my laptop via the wifi hotspot on my phone. Currently I am able to connect to the hotspot, but unable to surf. I have tried tethering the phone to the computer, but no luck there either. I am able to connect to another (router) wifi hotspot and surf. I have tried all manner of fixes with no luck.
OK, I did the following. Pinging seems to work. The problem seems to be the same as that described here: Wifi connected but no internet. I can connect to my phone's wifi hotspot, but I get "Page Not Displayed" error messages on all browsers.
lspci -nn | grep 0280
02:00.0 Network controller [0280]: Qualcomm Atheros AR9485 Wireless Network Adapter [168c:0032] (rev 01)

ifconfig
 eno1: flags=4099  mtu 1500
         ether a0:b3:cc:76:73:e2  txqueuelen 1000  (Ethernet)
         RX packets 0  bytes 0 (0.0 B)
         RX errors 0  dropped 0  overruns 0  frame 0
         TX packets 0  bytes 0 (0.0 B)
         TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

 lo: flags=73  mtu 65536
         inet 127.0.0.1  netmask 255.0.0.0
         inet6 ::1  prefixlen 128  scopeid 0x10
         loop  txqueuelen 1000  (Local Loopback)
         RX packets 6973  bytes 450468 (450.4 KB)
         RX errors 0  dropped 0  overruns 0  frame 0
         TX packets 6973  bytes 450468 (450.4 KB)
         TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

 wlo1: flags=4163  mtu 1500
         inet 192.168.43.72  netmask 255.255.255.0  broadcast 192.168.43.255
         inet6 fe80::5aad:e67a:f02:18ee  prefixlen 64  scopeid 0x20
         ether 44:6d:57:79:25:1f  txqueuelen 1000  (Ethernet)
         RX packets 14097  bytes 6130016 (6.1 MB)
         RX errors 0  dropped 0  overruns 0  frame 0
         TX packets 16221  bytes 1895034 (1.8 MB)
         TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask       Flags   MSS Window  irtt Iface
0.0.0.0         192.168.43.1    0.0.0.0         UG        0 0          0 wlo1
169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 wlo1
192.168.43.0    0.0.0.0         255.255.255.0   U         0 0          0 wlo1
traceroute 22.214.171.124
traceroute to 220.127.116.11 (22.214.171.124), 64 hops max
  1   192.168.43.1  2.889ms  4.343ms  2.251ms
  2   *  *  *
  3   *  *  *
  4   *  *  *

dig www.google.com
; > DiG 9.11.3-1ubuntu1.1-Ubuntu > www.google.com
;; global options: +cmd
;; connection timed out; no servers could be reached

Comment: I'd suggest to take a look at this https://askubuntu.com/questions/265384/wifi-connected-but-no-internet?rq=1 and try to provide some more debug information. With the information you gave it's really hard to help
Comment: Updated as per above.
Comment: now it's clearer. Correct me if I'm wrong: you can `ping 192.168.43.1`. Then you can't `ping 126.96.36.199`. Can you `traceroute 184.108.40.206` and `dig www.google.com` and attache the result ?
Comment: Thanks. Pinging 192.168.43.1 works, but the other two commands don't work, as per above extra info.
Comment: Can you confirm the the wifi hotspot is connected to the GSM network and that you can reach the outside? Like go to visit https://www.myip.com/ and check that you have an external ip (not 192.168.43.XX)
Comment: Yes, I can surf on my phone and myip.com confirms an external IP address.
Comment: looks like there could be an issue in the return route, can you try to remove the `192.168.43.0    0.0.0.0         255.255.255.0   U         0 0          0 wlo1` via `ip r del` and check what happens?
Comment: I tried that, but had to use route del -net 192.168.43.0 netmask 255.255.255.0. (I wasn't sure how to use ip r del .) The route was deleted from the routing table, with no change to ability to connect. I also tried deleting 169.254.0.0 and that wasn't successful either.
Answer: From the debug we made I can only guess the missing thing is to setup APN type as DUN (or default, dun) on your phone. Let me know how it goes.

Wifi Connected but No Internet access


routine for an sample to make an better routine for my example

Question: i want to ask you if someone have an idea how i can make it over an for or foreach Routine easier for me, because i dont want to copy paste all the stuff for all routines
if ( $_POST['vorgang'] == 'aendern' ) {
    pd_aendern  ( $_POST['db_eintrag'] , $db_id );
}

<form action="#"  runat="server" method="POST"    enctype="multipart/form-data">

    echo '<input type="text" placeholder="'  . $vorname       . '"name="db_eintrag[pd_vorname]">
';
    echo '<input type="text" placeholder="'  . $nachname      . '"name="db_eintrag[pd_nachname]">
';
    echo '<input type="text" placeholder="'  . $geburtsjahr   . '"name="db_eintrag[pd_geburtsjahr]">
';
    ...
    ..
    .
</form>

function pd_aendern ( $db_eintrag , $db_id ) {
////////////////
//1st Routine.//
////////////////
    if (!empty(isset($db_eintrag[pd_vorname] ))) {
        $sql = "UPDATE personaldaten SET pd_vorname='$db_eintrag[pd_vorname]' WHERE pd_id='$db_id'";
        $db_erg = mysql_query( $sql );
        if ( ! $db_erg ) {
            die("Ungültige Abfrage: $sql
" . mysql_error());
        }
    }
///////////////
//2nd Routine//
///////////////
    if (!empty(isset($db_eintrag[pd_nachname] ))) {
                ...
    } else {
        echo "aaaaa";
    }
}

Any ideas how i could handle that? i want to build that part:
 $sql = "UPDATE personaldaten SET
            pd_vorname='$db_eintrag[pd_vorname],
            2nd part,
            3rd part, etc.
        ' WHERE pd_id='$db_id'";

over an for or foreach Routine to get the part for my mysql query. I tried to put that fixed stuff in 2 Arrays, but i could not get the logic for it how i have to combine that to get just the not empty inputs for it. thx for any repllies and sry for my bad english.
$array = array("pd_vorname","pd_nachname", "pd_geburtsjahr");
$array2 = array("$db_eintrag[pd_vorname]","$db_eintrag[pd_nachname]", "$db_eintrag[pd_geburtsjahr]");

Comment: why are you still using the `mysql_` library which was deprecated many years ago and removed in PHP7 due to security issues? No new code should be written using this. Your code is almost certainly vulnerable to SQL injection attacks due to the inability to use parameterised queries, and possibly other risks from using a dead codebase. I would strongly suggest migrating to `mysqli` or `PDO` as soon as possible.
Comment: As for your actual question, I don't really know what you are asking. I realise English is not easy for you but please take some time to make it clearer because it's hard to know exactly what your problem is or what you hope to do differently.
Comment: @ADyson : god damn please. i know that new Version, but i began to write all that stuff in the old Version so i could not find the time to Change it. its just lern about the Syntax and so on. thx @ all guys who attent me to Change it, but ist not nessesary for the question. but if you ment ist easy to hack the Server, please let me know how you could do that injection.? if you want i will put an honypot Server on the net and each guys of you get some Attention if you hack that old query function.
Comment: @ADyson: ok sry maybe ist a Little bit hard to understand, but i Need some Input what exactly you could not understand?
Comment: http://bobby-tables.com/ has an excellent (and humorous) example of some of the risks of your approach, and also some examples of the syntax to use for the new libraries and parameterised queries for PHP and other languages. It's not too hard to learn, and if you do it right from now on it will save you a lot of time having to re-write it later.
Comment: In terms of the question, you say you want to put some SQL into a loop "to get the part for my mysql query". Which part? And what are we looping over? Do you mean to loop the array examples you gave? It looks like _probably_ you shouldn't put the variables in quotes in array2, but without a proper example of what you want to do, and some examples of input and the expected output, it's hard to be sure. Or possibly you want to put all those values into one UPDATE statement? In which case you can do that without any kind of loop
Comment: the way with the arrays isn't wrong. You then would create one function that checks if all the values are set (and maybe verify they are valid [for geburtsdatum zB]). Another function that builds the 'set db_xy=valueForXy' and writes it to an array, which you then can include to your statement after imploding the entries.
Answer: My solution:
$array = array(pd_vorname,"pd_nachname","pd_geburtsjahr","pd_telefonnummer","pd_staatsbuerger","pd_wohnort","pd_fb");
            $zahl = count($array);

            for ($i = 0 ; $i < $zahl ; $i++) {
            $etwas = $db_eintrag[$array[$i]];
            $ar = $array[$i];
                    if (!empty($etwas)) {
                            $sql = "UPDATE personaldaten SET $ar='$etwas' WHERE pd_id='$db_id'";
                            $db_erg = mysql_query( $sql );
                                    if ( ! $db_erg ) { die("Ungültige Abfrage: $sql
" . mysql_error()); }
                    }
            }
            for ($i = 1 ; $i < 12 ; $i++) {
            $etwas = $db_eintrag["wb_wissensbereich_" . $i ];
                    if (!empty($db_eintrag["wb_wissensbereich_" . $i ] )) {
                            $sql = "UPDATE wissensbereiche SET wb_wissensbereich_$i='$etwas' WHERE wb_id_person='$db_id'";
                            $db_erg = mysql_query( $sql );
                                    if ( ! $db_erg ) { die("Ungültige Abfrage: $sql
" . mysql_error()); }
                    }
            }


Schema.org/MedicalWebPage - What is proper use for specialty identification?

Question: I am trying to add schema.org markup to a chiropractic website. My issue is how to determine which markup to use so our site will show more helpful SERPs when patients are looking for information regarding symptoms/treatment.
Our website manager has a bunch of crazy HTML and I'm plugging in the schema markup I want within existing code. Do you have to use the  tags or can the itemscope and itemtype show in
 tags?
I'd like to use this markup for the page describing prenatal chiropractic care:

<link itemprop="audience" href="http://schema.org/Patient"/>
<link itemprop="specialty" href="http://schema.org/Obstetric"/>

Is this the best way to implement the markup? I didn't see a specialty for chiropractic or I would have put it there instead of Obstetric.
Comment: Sorry, some of my question disappeared. I meant to ask Do you have to use the  tags or can the itemscope and itemtype show in

tags?
Comment: You have to use inline code markup for this (enclose it in ` characters). I edited it for you.
Comment: In HTML, the link tag has no closing slash.
Answer: You can use Google's Structured Data Testing Tool in order to validate your schema markup:
https://developers.google.com/structured-data/testing-tool/
I always work off the basis that if the actual value for a schema tag can be represented on the screen (ie not hidden in a tag), I'll show it. If I absolutely must include some data and can't display it on the screen I tend to use the meta tag, primarily as that is what I always see google use during tutorials.
To answer your question more directly; no. You can start your schema tags on whatever tags you'd like, just so long as it encompasses all of your schema markup (ie don't have an itemprop for MedicalWebPage outside of its own hierarchy).
Answer: You schema choices are valid, you can use any tag with visible information for your markup, including
, ,
,  for things that you don't want a layout change for, and even things like  for single properties.
<link> and <meta> are for things not visible on the page.  If you wanted to include more information about the patients you could use a
 rather than <link> for instance. The http://schema.org/MedicalWebPage schema gives this as a helpful example which I've shortened:

<link itemprop="audience" href="http://schema.org/Patient" />
<link itemprop="specialty" href="http://schema.org/Cardiovascular" />
<meta itemprop="lastReviewed" content="2011-09-14"/>

About High Blood Pressure

 ...

Treatment

There are many common treatments for high blood pressure, including

  beta-blocker drugs such as propanaolol.

Comment: In HTML, the link and meta tags have no closing slash.
Comment: @Rob the schema.org examples including the closing slashes on those tags
Comment: That doesn't change what I said.


Converting simple recursive method which recurses within a loop into iterative method

Question: A while back, I was working on a programming problem (CCC).  I have also come across similar questions in past contests so I decided to ask about this one.  The problem is basically this.
You are given n people and p pieces of pie.
n people are standing in a row.
You must distribute p pieces of pie amongst them. You go in order and each person must receive at least as many pieces as the person before them.  Each person must receive at least one piece of pie and no pie may be left over.
You must return the number of possible ways to distribute the pie.
I managed to create the following recursive solution but it takes too long (more than 5 seconds) for the following inputs:
120 pieces, 20 people --> 97132873
250 pieces, 130 people--> 1844349560
My solution:
import java.io.*;

public class Main
{
  int pieces, people;
  int combinations = 0;

  public void calculate (int person, int piecesLeft, int prev)
  {
    if (person == people)
    {
        if (piecesLeft == 0)
            combinations++;
    }
    else
    {
        for (int x = prev ; (x * (people - person)) <= piecesLeft ; x++)
        {
            calculate (person + 1, piecesLeft - x, x);
        }
    }
  }

  public static void main (String[] args) throws Exception
  {
    Main m = new Main ();
    BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
    //m.pieces = Integer.parseInt (in.readLine ());
    //m.people = Integer.parseInt (in.readLine ());
    m.pieces=250;
    m.people=130;
    if (m.people == m.pieces)
        System.out.println (1);
    else if (m.people == 1)
        System.out.println (1);
    else
    {
        m.calculate (0, m.pieces, 1);
        System.out.println (m.combinations);
    }
  }
}

I found the following python solution from the unofficial solutions which from what I understand, basically creates an array of already encountered values.
visited = []
def pi(n,k,min):
if visited [n][k][min] == 0:
    if n == k:
        visited[n][k][min] = 1
    elif k == 1:
        visited[n][k][min] = 1
    else:
        t = 0
        for i in range (min, (n / k)+1):
            t = t + pi(n-i, k-1, i)
        visited[n][k][min] = t
return visited[n][k][min]

file = open("j5.10.in", "r")
n = int(file.readline())
k = int(file.readline())

for i in range(n+1):
x = []
for j in range(k+1):
    t = []
    for kk in range(n+1):
        t.append (0)
    x.append(t)
visited.append(x)

print pi(n,k,1)

What I want to do is make an iterative solution out of either of these but am not sure how to do it.  From what I understand, there may not be a huge speed difference but with even larger cases, it will allow me to avoid stack overflows.
Comment: Please indent the code
Comment: How fast is the Python solution?
Comment: I believe the person who wrote it said it took 3 seconds on his machine for the largest test case.  Mine takes over 10.
Answer: The second solution is memoized ... the visited array records values which have been calculated already. A trick to convert a memoized recursion into a (sort of) iterated solution is to loop through smaller cases to fill in the memo array.  You can just throw away the results for the smaller cases (they will be stored in the memo array anyway). Then when you finally calculate the one you want, it will use the memo array right away, no extra computation.
If you really want to build up an iterative solution from the ground up, you've got to figure out what previous cases you need to store in order to build up the next case. For example, to calculate factorial, with a loop, you only need to store one value in memory. In a change-making problem with coins of denominations 1, 5, and 10 cents, you would need to save only ten previous items to construct the next one. In some cases, you need to know all previous values to construct the next. Once you know that, the memory structure should be clear, then the program logic will become clear.


click a button to save the input fields in a csv file in Tkinter

Question: I am creating a simple GUI interface with the hope of saving the input data in a csv file with Tkinker. I am done with the interface but I have challenges with the submit button to save the data. I want help so when I click the submit button, it saves the data in a csv file. Here are my codes
from tkinter import *
import csv
import os

window = Tk()

window.title("BUSINESS REGISTRATION ")

window.geometry('500x450')

# Field name
bNo = Label(window, text="BusinessNo :")
bName = Label(window, text="BusinessName :")

# Packing fileds to show on the GUI
bNo.grid(row=1, column=2)
bName.grid(row=2, column=2)

# Varibales for storing data
businessNo = StringVar
businessName = StringVar

# Creating entry fields
entry1 = Entry(window, textvariable=businessNo)
entry2 = Entry(window, textvariable=businessName)

# Packing entry fields
entry1.grid(row=1, column=3)
entry2.grid(row=2, column=3)

# creating csv file
file_exists = os.path.exists('BUSINESS REGISTRATION.csv')

with open('BUSINESS REGISTRATION.csv', 'a', encoding='UTF8') as f:
writer = csv.writer(f)
if file_exists:

    writer.writerow(businessNo)
else:
    writer.writerow(businessName)
    writer.writerow(businessNo)

# submit function
def callback():
mylabel = Label(window, )
mylabel.grid()

# Creating a submit button
submit_Button = Button(window, text="Submit", command=callback)
submit_Button.grid(row=3, column=3)

# creating a csv file

window.mainloop()

Comment: First of all, you have an indentation problems and so your posted code will not even run.  The code for creating the CSV file should be *inside* a function that gets invoked in response to a button click. Right now you do not have your code within such a function. Besides that, you have not described the actual problem you are having.
Comment: Edit your code with proper indentation.
Answer: u can use pandas then convert your data to DatFrame type then save it as csv or any other extention
import pandas as pd  #install pandas in your pc

def save_to_csv(data):
   data_to_save={'name':data[0],'age':data[1]}
   df=pd.DataFrame(data_to_save)
   df.to_csv('your path/data.csv')

data=[('messi','ronaldo','neymar'),(34,35,30)]  #this exemple of data has name and age u can put any thing
save_to_csv(data) # i call the function


"answer suggested by author" status for questions

Question: I have asked several questions that went unanswered for so long, I eventually discovered the answer through trial and error.  I don't really want to answer my own question because doing so does not seem to be correct.  I want to encourage someone to answer it (and gain the credit for the answer.)  However, I don't think it would be wrong to explain my answer in the comments, then advertise the fact that I had posted a verified method in my comments.  I'm hoping that doing this would encourage someone with similar experience to write an answer, supported by my comment, and allow me to get some closure.
Comment: Actually, someone else getting credit for work you did would be *the* wrong course of action. You did it, you write it, you collect reputation for the job well done - perfectly fair. If for some reason you don't want the reputation (for example, your friend without an account did it and you are only posting it), then you can use Community Wiki for your answer.
Answer: Answering your own questions is perfectably acceptable.  There is some additional guidance on a good question on MSE.  Just make sure your answer will benefit others reading it.


Open file from firebase in web

Question: I am developing a web app in flutter and I need to be able to view files that are in firebase cloud storage.
The problem is that it only lets me download the file and not view, how do I do that?
I tried doing this but it opens a new page and downloads the file
<code>void _openFileInBrowser() async {
    const url = 'file_url';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Impossibile aprire il link $url';
    }
  }
</code>
Answer: Since you have the file url you can do as follows:
<code>  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", fileName);
  link.setAttribute("target", "whatever_you_like");
  document.body.appendChild(link);
  link.click();
</code>

Open file from firebase in web


Strategy for achieving R-49 in old attic

Question: This is in NW Washington, climate zone 4-C. R-49 required for roof insulation.
I have a 100-year-old, partially-finished attic that I plan to gut and re-finish in the coming years into proper living space. I've gone back and forth on strategies to insulate this space both to code and for longevity.
My current plan is as follows.

1" foam board for ventilation chute (R-5)

Minimum 1" air gap under roof sheathing
https://www.finehomebuilding.com/project-guides/insulation/rigid-foam-vent-baffles

½" drywall (R-0.5)

6¼" closed-cell spray foam (R-7/in)

This gives me 1" x 5 + ½" x 0.5 + 6¼" x 7 = R-49.25
The current roof system is standard 2x6 on a 12/12 pitch. To achieve this insulation level, I'd need: 1" air gap + 1" foam board + 6¼" closed-cell foam = 8¼" rafter depth. Meaning I need to add 2¾ to the rafter depth.
An alternative thought I had was to slightly reduce the spray foam depth and add an additional 1" of foam board on top of the rafters before hanging drywall, which would reduce thermal bridging from the lumber.
Am I on the right track? Are there better/alternative solutions I could be considering? My main concern is maintaining as much interior space as possible.
Comment: R49 seems an unreasonable goal for a rafter roof. While that's a modern standard, it usually involves roof systems designed with capacity for it in mind.  If you can get to R-30 or a bit more you're in a good place, considering your relatively mild climate. Of much greater concern are air leaks elsewhere in the home.
Comment: Yes, R-30 is reasonable, but R-49 is required by the municipality.
Comment: Required when? Have they demanded that every century home be immediately upgraded? Modern codes usually don't apply to existing homes.
Comment: Modern codes do apply to new work on existing homes.
Answer: In part depending on the current shape of the roof, and in part depending on how much saving interior space is a priority, putting the insulation and ventilation space on top of the current roof (and re-roofing over that) allows for the most interior space and as much insulation as you'd care to add.
Comment: I had considered this, however the current roof is less than 5 years old and I wouldn't want to add the additional cost of an entire roofing system if I don't have to. The current interior space is quite large. I could lose a few inches, but a foot would be an unreasonable reduction.
Answer: I think you are on the right track. Like you said you will need to add some depth to the rafters. I would tweak it slightly by changing the air gap to 1.5" and adding the second layer of rigid panels on top like you suggested. You will end up using 4" of ceiling space however. I would put 2x2 furring strips perpendicular to the rafters which you can fill with 1.5" rigid foam panels. Here's a diagram:

So you R-value will be:
1" rigid foam R5, 5.5" spray foam R38.5, 1 1/2" rigid foam R5.5, 1/2" Drywall R0.5 for a total of 49.5


Pythonic-way to append path to several files in the project

Question: I am working on a python project consisting several folders and .py files.
For all files, I have to use sys.path.append to introduce my the project directory before importing files from other folders.
This makes it troublesome if I want to run the code on another PC.
I'd like to want to know if there is a better way so that I don't need to update sys.path.append in files when running on another PC?
Comment: Use `sys.path.append` with a relative path, not with an absolute path. Then you're "good to go" regardless of where you run your project from.
Comment: create an environment variable with `project-path` and use that in sys.path.append. configure the `project path`, whenever moved the project code.
Answer: You can use sys.path.append with a relative path, not with an absolute path.
Here is how I do it in one of my projects:
Create file Config.py:
import sys,os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

And import this file in each one of the other files in your project.
Note that os.path.dirname(os.path.dirname(__file__)) is just an example.
Comment: Keep in mind that `__file__` doesn't get along very well with `py2exe` (if you intend to use it at some point).


Why do natural transformations express the fact that a vector space is canonically embedded in its double-dual but not in its dual?

Question: I've been struggling for quite a while to understand why a vector space is considered to be "canonically embedded" into its double dual, but not its dual. As has been remarked in many other places, the distinction between whether an (iso-)morphism is "natural" can often seem vague and unintuitive. For me particularly, I think that part of the problem is that this sort of statement seems to run entirely counter to something I was taught early in Abstract Algebra as a Profound and Fundamental Lesson: "Isomorphic structures are exactly the same in all respects. When two things are isomorphic, all the things that can be said about one carry over verbatim to the other. There is no distinction between them." However, moving into more abstract linear algebra, a sort of about-face is being made, and now we are making the distinction of effectively saying, "My isomorphism is better than yours." In order to justify this apparent contradiction, the argument is typically made that the (iso-)morphism into the double dual does not require any "choices", while any embedding into the dual will require some "choice" to be made. However, this seems... unconvincing. So what if you can jury-rig a bilinear form out of whatever embedding/isomorphism I pick? Do we really have to pay attention to that? Again, this seems rather vague and unintuitive.
To make the argument more precise then, it is claimed that the ultimate answer lies in that Fountain of Eternal Truth - Category Theory. More specifically, it is claimed that the fact that there is a natural transformation from the identity functor on vector spaces to the double-dual functor justifies the claim that the embedding into the double-dual is "natural", while the fact that there is no such transformation between the identity and the dualizing functor shows that any such embedding into the dual is "not natural". This is elucidated beautifully in this thread. However, I claim that this is still not the final nail in the coffin of doubt. More specifically, I do not understand how natural transformations actually express the idea that a construction is (quotation marks) "natural".

How does this business with commuting diagrams make precise the idea that the embedding of a vector space into its double dual is "natural"? How does the implication that any association with the dual is "not natural" stem from a theorem saying that a certain collection of diagrams will never commute?

Another thing to note, that took me a little by surprise, is that the content of these arguments depends not only on the construction of the dual and double dual spaces, but also on this other construction called the transpose, which associates a linear map $f^*: F^* \to E^*$ to every linear map $f: E \to F$. So the fact that a map between a space and its dual is not "natural" also depends on the fact that we define an association between linear maps, that we package together with the dual operation to form the dualizing functor; however, this  association between linear maps seems rather external to the association between a vector space and its dual. This is also bothering me.
I will not deny that the transpose operation does seem like a very natural thing to pair along with the dual operation, but what does seem odd is that the intrusiveness of this transpose operation should make or break the "naturalness" of something strictly between a vector space and its dual - honestly, who ordered that? Why can't I concoct some other association between linear maps - one that's covariant, at that, and package that together with the dual space to make something that admits a natural transformation from the identity? Note however that this would also break the "theorem" that a vector space is canonically embedded in its double dual, so this sort of train of thought is a double-edged sword.
Ultimately, I feel that I don't understand natural transformations in general very well; this example is really just the biggest one that sticks out to me and the one that I care about the most. I may post another question about the general case of understanding natural transformations, depending on how well this one goes and also whether I can manage to formulate it in a manner that seems intriguing and not simply lost and confused. At any rate, I look forward to any potential answers and would greatly appreciate whatever illumination you may be able to provide.
Comment: +1 I love this question. I feel I often learn a ton from this kind of imprecise-but-aimed-at-something-you-can-feel inquiry.
Comment: @PeterFranek Corrected, thanks.
Answer: I am answering as somebody who has struggled through a related matter, as you noted in the OP. I do not think I will be able to satisfy every one of your related threads of dissatisfaction and I am not sure I will be able to satisfy any at all. On the flip side, as the question is a year old, you may have resolved it for yourself long ago.
But let's give it a whirl. I love the question.
First of all, separate from the question about how the category language speaks to (or doesn't speak to) matters, it seems to me you are not convinced that there even is a substantive difference between the isomorphism of a finite dimensional vector space to its dual and the isomorphism to its double dual, a propos of your Profound and Fundamental Lesson of Abstract Algebra -- aren't they both isomorphisms? So, before even engaging the category theory, let me speak to this:
(1) I think you will gain useful insight about the situation from studying cases where the substance of the difference between a space and its dual is felt. user254665 mentioned one such instance in her/his answer. In general, the infinite-dimensional topological vector spaces of functional analysis provide an abundant source of examples. While the dual of a finite dimensional vector space is finite-dimensional of the same dimension, and therefore isomorphic, the dual of a Banach space is typically a different Banach space. For example the dual of $L^p$ is $L^q$ with $p^{-1}+q^{-1} = 1$, which are two different Banach spaces unless $p=2$. The dual of the space of continuous, compactly supported functions on a locally compact Hausdorff space is a space of measures i.e. it is not even a space of functions!
Even in these situations where the dual is really a different animal, the original space does embed in its double dual, as usual by mapping a vector to the functional on functionals obtained by evaluation at that vector. (I will avoid controversy by not lionizing this embedding as "natural".) In many cases, the embedding is proper, i.e. the double dual is bigger than the original space. Nonetheless, there's often no obvious embedding of the original space in the (single) dual at all.
I am not a functional analyst, but a place I've encountered this substance in my own life is in the difference between a locally compact abelian group and its character group, i.e. its Pontryagin dual. Like vector spaces, this is a situation where finiteness causes a non-canonical isomorphism to the dual, and there is a canonical isomorphism to the double dual. A finite abelian group $A$ is isomorphic to its dual $\hat A$, but not an infinite group. For example, the additive group $\mathbb{Z}$ of integers and the circle group $S^1 = \{z\in\mathbb{C}^\times \mid |z| = 1\}$ are Pontryagin duals of each other, and they don't even have the same cardinality. In the finite case, where they are isomorphic, I've still "bumped into" the difference between $A$ and $\hat A$, for example in trying to understand the relationship between an action of a group $G$ of automorphisms on $A$ and the induced action of $G$ on $\hat A$, e.g. see this question.
All of this is to say that study of such examples can help convince one that the dual is really not the same as the original object, so that even when they're isomorphic it's worth keeping track of which is which. (More so than it is worth distinguishing the object from its double-dual when they are isomorphic.)
(2) How to make sense of this difference in light of your Profound and Fundamental Lesson (PaFL), that isomorphic objects are to all intents and purposes the same.
This is a question about the scope of the PaFL.
The PaFL is the right way to see things when you view the objects in isolation from their surroundings and each other. Let $A$ and $B$ be isomorphic objects (e.g. vector spaces or groups). Any specific isomorphism $\phi:A\rightarrow B$ gives you a dictionary to translate statements about the isolated object $A$ to statements about the isolated object $B$ and vice versa. For example: if $A,B$ are vector spaces, then $\phi$ carries bases to bases, so there is a perfect bijective correspondence between bases of $A$ and bases of $B$. It carries linear transformations of $A$ to linear transformations of $B$ (via $T\mapsto \phi T\phi^{-1}$) so there is a bijection between such transformations. If we think of $\phi$ as a "renaming", then we can think of $B$ as just $A$ with different names.
From this point of view, $A$ and $B$ are "the same", and any "renaming" $\phi$ works as well as any other to show this. This is the PaFL.
But. If we allow $A$ and $B$ to interact with other objects (even each other!), then distinct isomorphisms start to feel very different! For example:
Let $A = \mathbb{R}^2$, seen as a real vector space. Let $B$ be $A$'s vector space dual, i.e. the space of linear functionals $A\rightarrow \mathbb{R}$, with pointwise addition and scalar multiplication. $B$ is isomorphic to $A$ since it is also a 2-dimensional real vector space. One has a wide choice of isomorphisms: fixing a basis of $A$, one can send it to any basis of $B$. There is a 4-dimensional manifold's worth of choice.
Now along comes a linear transformation $T$ acting on $A$, say by scaling the $x$-axis by a factor of $2$. One can pick some isomorphism $\phi:A\rightarrow B$ and translate $T$ into a transformation of $B$ as above (i.e. $\phi T \phi^{-1}$). But there is another (natural??) way that $T$ acts on $B$, irrespective of any choice of $\phi$, which is to send a functional $f:A\rightarrow\mathbb{R}$ to the functional $f\circ T$. Now one can ask about any given $\phi$: does the transformation of $B$ into which it translates $T$ equal this (natural??) action of $T$ on $B$? I.e. does $\phi T \phi^{-1} (f) = f\circ T$ for all $f\in B$? A priori, some $\phi$'s may be compatible with the action of $T$ on $B$ in this respect, and some may not.
One could go further. I chose a specific $T$ at the front end of this. But one could ask if there is a $\phi$ such that $\phi T\phi^{-1}(f)$ will equal $f\circ T$ regardless of the choice of $T$. This $\phi$, if it existed, would clearly (?) be "awesome" in some way that other isomorphisms aren't.
Perhaps you respond by saying, well, why did you bring $T$, and especially its action on $B$ by $f\mapsto f\circ T$, into it? This is a perfectly legitimate question. From the point of view where you only look at $A$ and $B$ as self-contained systems, there's no reason to. But my point is that mathematical objects are often embedded in a network of other mathematical objects (such as $T$, or a wide variety of choices of $T$, and their related actions on $A$ and $B$), and when we bring these other objects and the interactions between them into it, it complicates the (overly?) simplistic picture drawn by the PaFL. Maybe some isomorphisms play better than others with the network of relationships in which $A$ and $B$ are embedded.
(3) This is a segue into the matter of categories. A natural isomorphism between two functors is not an isomorphism between two isolated objects. It is some kind of construction that works simultaneously across an entire category, in such a way that the isomorphisms all interact well with a bunch of other maps.
Thus, the way in which the categorical language translates the word "natural" is, loosely, "working simultaneously across all the objects of a whole category, in such a way that it cooperates with the other relevant maps in the category." The naturality lies in the everywhere-at-once-ness and in the fits-in-with-what-was-already-going-on-ness.
To get specific to the case. Let $\mathscr{V}$ be the category of finite dimensional $\mathbb{R}$-vector spaces.
Let's try to carry out what you proposed in the penultimate paragraph of the OP, i.e. try to reconstruct the dualizing functor as a covariant functor; call it $D$. We are already given the map on objects: it sends $V\in\operatorname{Obj}\mathscr{V}$ to its dual $V^*$. We need to design, for every $T\in \operatorname{Hom}(V,W)$, a map $D(T):V^* \rightarrow W^*$, in such a way that the identity map always gets sent to the identity map, and for any $U\xrightarrow{S} V\xrightarrow{T}W$ occurring in $\mathscr{V}$, we have $D(TS) = D(T)D(S)$.
It seems to me that this is actually possible, modulo some axiom-of-choice typed issues. If we separately chose an isomorphism $\phi_V:V\rightarrow V^*$ for each $V\in \operatorname{Obj}\mathscr{V}$, then we could send $T:V\rightarrow W$ to $D(T) = \phi_W T\phi_V^{-1}$, which maps $V^*$ to $W^*$. Furthermore, it seems to me that the maps $\phi_V:V\rightarrow V^*$ would then constitute a natural isomorphism from the identity functor to our new "dualizing functor" $D$.
I think some readers will be given pause by the fact that this construction needs some form of the axiom of choice to be carried out. (I'm out of my set-theoretic league on what's needed. It seems to me that the category at hand is not a small category; thus we need an even stronger axiom like global choice, right?) But you've indicated that the need to make choices doesn't strike you as a barrier to "naturalness," so I assume that this high degree of nonconstructiveness of the construction won't be a problem. However, I see another issue as well:
This construction loses any information related to the fact that $V^*$ is supposed to be the dual of $V$. It completely ignores the fact that the elements of $V^*$ are supposed to be functionals on $V$. We could replace $V^*$ with any other vector space of the same dimension and carry out the same construction. Thus it seems to me $D$ doesn't really send $V$ to its dual in any meaningful sense. Thus, while it uses a nonconstructive axiom (global choice?) to get past the category-theoretic insistence that a natural transformation happen "all at once across a whole category", it doesn't (honestly anyway, it seems to me) meet the second condition that it "cooperates with what was already going on."
This is where the transpose (also called the adjoint) comes in. You ask, "who ordered that?" I.e. isn't the adjoint map extrinsic to the relationship between $V$ and its dual? I contend it's actually essential. If $T:V\rightarrow W$ is a map between vector spaces, then the adjoint $T^*:W^*\rightarrow V^*$ between their duals is defined as $f\overset{T^*}{\mapsto} f\circ T$. This $T^*$ cooperates with what was already going on! I.e. it transforms the dual space in accordance with what the elements in the dual space are supposed to mean. Without a relationship like that between $T$ and $T^*$ that incorporates the fact that the elements of $V^*$ are supposed to be the contents of $\operatorname{Hom}(V,\mathbb{R})$, a functor sending $V$ to $V^*$ is only meaningfully sending it to some other vector space of the same dimension, not actually its dual.
Thus a natural isomorphism to the dual really should somehow respect the adjoint, or something like it. Otherwise, what makes the dual the dual?
Obviously the question was soft and this is a soft answer. So let me know if any of this speaks to any of the issues you outlined.
Comment: Thanks for your answer. Being in grad school now, and being swamped with homework, I probably won't have a chance to really dig through the arguments till the weekend, but I do want to make some commentary on it.
Comment: @silvascientist - looking forward to your engagement when you get a chance. I'm glad you noticed the answer and I'm anxious to know if it speaks to the issues you were articulating in the OP. (I'm also in grad school, btw; if all goes well, defending my thesis in less than a month. It's ON.)
Comment: Would you like to set up a chat room? I can imagine this conversation going on for quite a while. The comment section will start to complain.
Comment: I feel like your remark about the *scope* of the PaFL is on point. Basically, the explanation I've worked out for myself is that while, yes, a vector space and its dual may be *structurally* the same, that's not always what we really care about in mathematics. For example consider a smooth manifold. A vector field on this manifold is defined to be a section on its tangent bundle, i.e. to every point on the space we associate a vector in the tangent space *at that point*. Now, actually *all* the tangent spaces are isomorphic to each other, but it wouldn't be helpful to go about sending points..
Comment: on the manifold to random tangent spaces all over the place - we really want a point to be given a vector in the tangent space *at that point*. And there's no point (no pun intended) in going about trying to find random isomorphisms between tangent spaces just to deal with them all as the same thing.
Comment: Also, sections on the cotangent bundle are useful and interesting in Diff. Geo, they're our 1-forms. In the presence of a Riemannian metric, we can pass smoothly (pun intended) between the tangent and cotangent spaces, and this allows us to treat vector fields as forms and vice versa. This fits in with what you speak of as "everything-at-once-ness" - we have a specific isomorphism for each vector space to its dual, and we don't have to wave any global choice nonsense to get it working - we actually have *access* to each isomorphism, and this is important.
Comment: Unfortunately, I have to take off right now to an event, and I probably won't be back until 8:00 or 9:00 pm Pacific time. If you still want to chat, I'll be ready. I regret forgetting to make time for this sooner.
Comment: Sorry, just seeing this now. I don't need an extended conv., but this engagement is very gratifying. Yes, I think you are talking about exactly the same thing I am. Existence of isomorphism $\Leftrightarrow$ two objects have the same *internal* structure, but not necessarily the same relationship to anything else. I want to know if you made any sense of what I said about the adjoint map being important to the dual actually being the dual. I was struggling to articulate something there.
Comment: I did gain some appreciation for the "naturality" of the transpose when I began looking at transposes of inclusion maps. Specifically, when we have two spaces $V \subseteq W$, every functional on $W$ "obviously" also acts on $V$ just by restricting it. Now, we didn't need any notion of functoriality to intuit this, but as it turns out, this is exactly the transpose of the inclusion map! So I guess the tranpose does in fact, "cooperate with what was already going on", as you say, more than I've given it credit for.
Comment: On the other hand, this doesn't quite answer the question why having a map that "cooperates with what was already going on" is *necessary* for a collection of isomorphims to be "natural". Just to be contrarian, I could ask whether, if we had a collection of objects $A$ and their associated objects $A'$, and for each $A$, $A'$ we had a very simply defined and unartifical isomorphism, but that the isomorphisms just didn't happen to commute with all the relevant maps, why that would be some sort of stumbling block towards "naturality". I have something of a vague answer in my head why,...
Comment: but it's hard to make it precise and totally convincing. It might be helpful to see an instance where something was gained because some construction was actually "natural" in the sense of "natural transformation", where all the relevant diagrams commute, and this was actually necessary for whatever was going on.
Comment: I'm trying to make the case that the adjoint map is somehow constitutive of the dual being the dual, so that a functor can't even honestly be said to send a vec. sp. to its dual without commuting with the adjoint (or something similar). I seem to be unable to very articulate about this, but I'll mull on it and maybe later be able to say something more satisfying. I have heard people say that there is a general philosophy in category theory, codified somehow by the Yoneda lemma, that in some important way, objects are determined by their maps. I guess this is related.
Comment: Yeah, it has been on my mind the past few days that I ought to try to understand the Yoneda Lemma.  Seems relevant.
Answer: It seems to me that there are two possible meanings (close to each other).
One is that such isomorphism $**$ is defined via very simple and "expected" means. Another word commonly used for this is canonical. The definition $(v,w):=w(v)$ for $w\in V^*$ identifies $v$ with an element of $V^{**}$ and this does not depend on any additional structure on $V$, such as a metric. In this sense, it is "natural": you pair elements of $V^*$ with elements of $V$, so you can consider it the other way around as a pairing between elements of $V$ and $V^*$.
Another meaning is, as you say, the categorical. This basically says that not only can you apply $**$ to spaces but also to linear maps and the corresponding diagram commutes. That is, you can identify $f: X\to Y$ with $f^{**}: X^{**}\to Y^{**}$ (again, the identification goes via simple and expected means). As before, the functorial definition of $**$ does not depend on any additional structures such as metrics or scalar products.
These two meanings often go hand-in-hand: if something has a simple and expected definition (or a complicated one, but satisfying simple axioms), usually it can be converted into something categorical. It seems to me that if one wants to highlight the categorical meaning, (s)he uses the word natural, if one wants to highlight the simple and expected thing, (s)he often uses the word canonical.
But I'm not sure if this answers your question because I guess that you are aware of all of this.
Extension + edit: a small attempt to give some intuition of why natural transformation are "natural". Consider a finite-dimensional vector space $V$ and two its bases $\mathcal{B}_1$ and $\mathcal{B}_2$. Let $\mathcal{V}$ be a category with only one object $V$ and morphisms $Mor(V,V)$ being all linear transformations; let $\mathcal{R}$ be a category with one object $\Bbb R^n$ and morphisms being all linear transformations.
You can define two functors $F$ and $G$ from $\mathcal{V}$ to $\mathcal{R}$ that express a linear transformation as a matrix wrt. the coordinates $\mathcal{B}_1$ resp. $\mathcal{B}_2$. A natural transformation between $F$ and $G$ assigns to the object $V$ in $Obj(\mathcal{V})$ the morphism $x\mapsto C^{-1}x$ of $\Bbb R^n$ (an element of $Mor(\Bbb R^n, \Bbb R^n)$), where $C$ is the transition matrix from base $\mathcal{B}_1$ to $\mathcal{B}_2$. This morphism is just the coordinate transformation in $\Bbb R^n$.
The fact that it is a natural transformation just reflects that any linear map $f: V\to V$ (an element of $Mor(V,V)$) gives rise to the commutative diagram
\begin{array}{ccc}
\Bbb R^n & \stackrel{F(f)}{\to} & \Bbb R^n \\
\downarrow_{C^{-1}} && \downarrow_{C^{-1}} \\
\Bbb R^n & \stackrel{G(f)}{\to} & \Bbb R^n \\
\end{array}
or equivalently,
\begin{array}{ccc}
\Bbb R^n & \stackrel{M}{\to} & \Bbb R^n \\
\downarrow_{C^{-1}} && \downarrow_{C^{-1}} \\
\Bbb R^n & \stackrel{C^{-1}MC}{\to} & \Bbb R^n \\
\end{array}
where $M$ is the matrix expression of $F(f)$.
In physics, this corresponds to a change of observer: observer $\mathcal{B}_2$ will just "see" a vector $C^{-1}x$ and/or "use" the matrix $C^{-1}MC$ whenever observer $\mathcal{B}_1$ "sees" the vector $x$ and "uses" the matrix $M$. But they both see the same "real object". In this sense, the natural transformation is "natural".
Comment: @PeterFranek - Just to get clear on your construction. You are saying that $Obj(I)$ is the underlying set of $V$; ok. Then given two objects $x,y\in V$, what is $Mor(x,y)$? Is it the set of all linear transformations of $V$ that carry $x$ to $y$? (I guess what's bothering me about this is it means a single linear transformation $T$ is actually going to count as a big infinity of different morphisms, one for each pair of points $x,y$ with $Tx = y$.)
Comment: @BenBlum-Smith Thanks for pointing this out; I was confused in the comment above. The object is only one, $V$  resp. $\Bbb R^n$ and morphisms are "linear transformation"; then it makes sense I hope. But it's not such a good example as I thought before.
Comment: Ultimately, your last statement is the most on the mark. The argument with commuting diagrams is supposed to make precise the notion that the embedding "does not depend on any additional structures such as metrics or scalar products." The question is, "How?". But I do appreciate the time and effort you have shown in answering my question.
Comment: @silvascientist  I added a simple example that hopefully adds some intuition but I'm still not sure if that's what you want. I'm not sure if there is a direct connection between "not depending on additional structure" and "naturality" in the categorical sense, Maybe somebody else will formalize this, let's see..  :)
Comment: "...functors from $V$ to $\mathbb{R}^n$"... I don't understand. Are $V$ and $\mathbb{R}^n$ being considered as categories in and of themselves? With morphisms between vectors?
Comment: No. If $V$ acts on $V^*$ then it is identified with $\subseteq V^{**}$. (I meant pairing between elements, not spaces)
Comment: Oh. I had "pairing" confused with "identification".
Comment: It is as natural as "negative of a negative is positive". You see, $V^*$ acts on $V$ but then also $V$ acts on $V^*$.
Comment: @PeterFranek - thank you for the clarification, and I think it is still an illustrative example!
Answer: Consider the space $l_0$ of real sequences $(x_n)_{n\in N}$ that converge to $0,$ with $\|(x_n)_n\|=\sup_n |x_n|,$ and its dual $l_1,$ the space of absolutely summable real sequences $(y_n)_{n\in N}$ with norm $\|(y_n)_n\|=\sum_{n\in N}|y_n|<\infty.$ The space $l_0$ contains many positive sequences that are not summable,e.g if $y_n=1/n$ for each $n.$ We should expect an embedding  $E$ from $l_0 $ into $l_1$ to preserve the algebraic structure and the topological structure, in other words $E$ should be a continuous linear bijection to its image, and $E^{-1},$ acting on the image of $E$, should also be continuous.  Such an $E$ doesn't exist. As a special case of a fairly recent theorem, $l_0$ and $l_1$ are homeomorphic, but  by a non-linear mapping $F$, so the algebraic structure is not preserved by $F$.


Click to appendTo and again click undo it

Question: I have a jquery code when I click, an element [.topmenu] appendTo another element [.mainmenu] and I want to when click again, it is undone and the element goes back to first place [first place is on header .container]
But it doesn't work
$(function() {
        $(".navbar-toggle").Toggleclick(
            function(){ $(".topmenu").appendTo(".mainmenu"); },
            function(){ $(".topmenu").appendTo(".container"); },
        );
    });

Answer: There is no Toggleclick() method in jQuery.
To make this work you would need to use a single click event handler which determines the current location of .topmenu and toggles the append location accordingly, something like this:

$(function() {
  var $topmenu = $('.topmenu'),
    $mainmenu = $('.mainmenu'),
    $container = $('.container');

  $(".navbar-toggle").click(function() {
    var $target = $topmenu.parent().is('.container') ? $mainmenu : $container;
    $topmenu.appendTo($target);
  });
});
div {
  padding: 5px;
  border: 1px solid #C00;
}

<button type="button" class="navbar-toggle">Toggle</button>

  Main menu

    Top menu

  Container

Comment: can we get a condition for this code that just do while max-width:767px ?!


Navigate to a executable relative path bash

Question: So I know the basics of relative paths in Linux...

./ denote path relative to current folder
../ denotes path relative to parental folder

but what if I want to run an executable (./exeToRun) relative to a parental folder? Do I use three dots?
Example
File stucture
project
│   README.md
│   file001.txt
│
└───folder1
│   │   exeToRun
│   │   file012.txt
│   │
│   └───subfolder1
│       │   myScript.py
│       │   file112.txt
│       │   ...
│
└───folder2
    │   file021.txt
    │   file022.txt

If I wanted to call ./exeToRun executable from myScript.py, relatively, I would assume the syntax would be .../folder1/exeToRun. Two dots since it's relative to parent folder and one dot since its an executable.
Now I know this is incorrect, but I'm looking for some clarity on how to correctly achieve this functionality.
Answer: You'd use two dots (../exeToRun); there's no additional "dot since its an executable", this is just a plain path.
In the usual case of ./exeToRun, the single dot just means "in the current folder", not something about the file being executable. The reason it's needed is because if a command doesn't contain an explicit path (i.e. at least one "/"), the system will look for it in the various binaries directories in your $PATH (i.e. /bin, /usr/bin, etc); putting ./ before the executable name overrides that by explicitly saying "in the current directory..."
HOWEVER, when you use . and .. like this, they're relative to the process's current working directory, which isn't necessarily the directory your script is in. If you cd into the script's directory and run it with ./scriptname, then yes it'll be the script's directory, but if you're somewhere else and run the script by its path... then the script's working directory will be wherever you happened to be when you ran the script.
If you want to run an executable relative to the script's directory, you need to first find the script's directory, and that's not always easy (or even possible). See "How can I get the source directory of a Bash script from within the script itself?" and BashFAQ #28: How do I determine the location of my script?
Comment: Ah, I see. Thanks for clarifying this. That makes a lot more sense