text:
Q: How can I get return value from a web-service with django/python I am posting some parameters to a web-service as follows:
requests.post("http://**.***.**.**:****/MyLogin/services/DBConnection/callLoginProcedure?inputPhoneNumber=" + phone + "&inputPassword=" + password)
The "callLoginProcedure" returns an integer value but I couldn't manage to get that value. How can I get this return value?
views.py:
def index(request):
    post = request.POST.copy()
    if post.get('login_button'):
        phone = post.get('phone_num')
        password = post.get('password')

        requests.post("http://**.***.**.**:****/MyLogin/services/DBConnection/callLoginProcedure?
            inputPhoneNumber=" + phone + "&inputPassword=" + password)
        r = request.GET.get("return", "-1")
        # if r == 1:
        #     messages.info(request, 'successful!')
        # else:
        #     messages.info(request, 'unsuccessful!')
        messages.info(request, r)
    return render(request, 'login/index.html')

urls.py:
urlpatterns = [
url(r'^$', views.index, name = 'index'),
path(r'^$', views.index, name = 'script'),

]
Edit:
My problem is solved but I get proxy error when requests.post function is called. I don't know how to solve it. The stacktrace is as follows:
    Request Method: POST
Request URL: http://localhost:8000/login/

Django Version: 2.2.3
Python Version: 3.7.3
Installed Applications:
['login',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware']

Traceback:

File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in urlopen
  603.                                                   chunked=chunked)

File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in _make_request
  344.             self._validate_conn(conn)

File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in _validate_conn
  843.             conn.connect()

File "C:\Program Files\Python37\lib\site-packages\urllib3\connection.py" in connect
  370.             ssl_context=context)

File "C:\Program Files\Python37\lib\site-packages\urllib3\util\ssl_.py" in ssl_wrap_socket
  368.     return context.wrap_socket(sock)

File "C:\Program Files\Python37\lib\ssl.py" in wrap_socket
  412.             session=session

File "C:\Program Files\Python37\lib\ssl.py" in _create
  853.                     self.do_handshake()

File "C:\Program Files\Python37\lib\ssl.py" in do_handshake
  1117.             self._sslobj.do_handshake()

During handling of the above exception ([SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)), another exception occurred:

File "C:\Program Files\Python37\lib\site-packages\requests\adapters.py" in send
  449.                     timeout=timeout

File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in urlopen
  641.                                         _stacktrace=sys.exc_info()[2])

File "C:\Program Files\Python37\lib\site-packages\urllib3\util\retry.py" in increment
  399.             raise MaxRetryError(_pool, url, error or ResponseError(cause))

During handling of the above exception (HTTPSConnectionPool(***): Max retries exceeded with url: **** (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)')))), another exception occurred:

File "C:\Program Files\Python37\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Program Files\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Program Files\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\TOLGA\Desktop\PythonWebProjects\WebLogin\login\views.py" in index
  53.         response = requests.post('{}?{}'.format(endpoint, qd.urlencode()))

File "C:\Program Files\Python37\lib\site-packages\requests\api.py" in post
  116.     return request('post', url, data=data, json=json, **kwargs)

File "C:\Program Files\Python37\lib\site-packages\requests\api.py" in request
  60.         return session.request(method=method, url=url, **kwargs)

File "C:\Program Files\Python37\lib\site-packages\requests\sessions.py" in request
  533.         resp = self.send(prep, **send_kwargs)

File "C:\Program Files\Python37\lib\site-packages\requests\sessions.py" in send
  646.         r = adapter.send(request, **kwargs)

File "C:\Program Files\Python37\lib\site-packages\requests\adapters.py" in send
  514.                 raise SSLError(e, request=request)

Exception Type: SSLError at /login/

A: First of all, I strongly suggest that you do not encode the URL yourself, but use Django's QueryDict for example, like:
from django.http import QueryDict

qd = QueryDict(mutable=True)
qd.update(inputPhoneNumber=phone, inputPassword=password)
For example:
>>> qd = QueryDict(mutable=True)
>>> qd.update(inputPhoneNumber=phone, inputPassword=password)
>>> qd.urlencode()
'inputPhoneNumber=0015550183&inputPassword=some_password'

Next, you should read out the response of the POST request, like:
from django.http import QueryDict
from json.decoder import JSONDecodeError
import requests

endpoint = 'http://68.183.75.84:8080/Calculator/services/DBConnection/callLoginProcedure'

def index(request):
    post = request.POST
    if request.POST.get('login_button'):
        qd = QueryDict(mutable=True)
        qd.update(
            inputPhoneNumber=request.POST.get('phone_num'),
            inputPassword=request.POST.get('password')
        )
        response = requests.post('{}?{}'.format(endpoint, qd.urlencode()))
        try:
            result = response.json()
        else JSONDecodeError:
            result = -1
        # ...
    return render(request, 'login/index.html')


text:
Q: Use imported package within the __del__ method I am experimenting with Telegram bots. I have created a simple class to send messages and I want it to send me a warning message when the TelegramBot object is deleted. My code is:
import requests
class TelegramBot:
    def __init__(self, token, id):
        self.token = token
        self.id = id

    def send_msg(self, msg: str):
        send_text = 'https://api.telegram.org/bot' + self.token + '/sendMessage?chat_id=' + self.id + '&parse_mode=Markdown&text=' + msg
        response = requests.get(send_text)
        return response.json()

    def __del__(self):
        self.send_msg('WARNING: TelegramBot object is being deleted')

and it works fine. The problem is within the __del__ method. Instead of sending the warning msg I am getting an error:
Exception ignored in: <function TelegramBot.__del__ at 0x7f1927c74280>
Traceback (most recent call last):
  File "check_flight_status.py", line 20, in __del__
  File "check_flight_status.py", line 16, in send_msg
  File "/usr/lib/python3/dist-packages/requests/api.py", line 75, in get
  File "/usr/lib/python3/dist-packages/requests/api.py", line 60, in request
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 533, in request
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 646, in send
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 439, in send
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 665, in urlopen
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 376, in _make_request
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 996, in _validate_conn
  File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 319, in connect
ImportError: sys.meta_path is None, Python is likely shutting down

and I believe it has to do with the fact that the requests package is being "destroyed" before the TelegramBot object.
So, how can I send a message when the object is deleted?

A: You have more way to solve your issue. The problem is in the caller side. Probably you don't delete the object of TelegramBot after usage.
I have written a representative example for you.
Code (Wrong):
import requests

class Test(object):

    def printer(self):
        print("FOO")

    def _close_con(self):
        import encodings.idna  # Sometimes it's needed for "LookupError: unknown encoding: idna" issue.
        response = requests.get('https://google.com')
        print("Status Code: {}".format(response.status_code))

    def __del__(self):
        self._close_con()

t = Test()
t.printer()
print("End of script")

Output:
>>> python3 test.py
FOO
End of script
Exception ignored in: <bound method Test.__del__ of <__main__.Test object at 0x7f7b14e5ca58>>
Traceback (most recent call last):
  File "test.py", line 15, in __del__
  File "test.py", line 10, in _close_con
ImportError: sys.meta_path is None, Python is likely shutting down

If I delete the object (t) of Test class then the Exception is fixed.
Fixed part:
t = Test()
t.printer()
print("End of script")
del t

Output:
>>> python3 test.py
FOO
End of script
Status Code: 200

Or another solution to not creating instance from the class, only call it directly. In this case the GC will do everything for you.
Fixed part:
Test().printer()
print("End of script")

Output:
>>> python3 test.py
FOO
Status Code: 200
End of script

As you can see above the object reference has been destroyed (by GC) after the usage (This is the reason why the sequence of messages is different than the other example).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Userdefinable Layout (at runtime) I'm looking for a best practise in the following scenario. This scenario has been made up just to illustrate the problem in a simplified manner.
Assuming we have the following Layout, to store an address.

Though some customers might think, the e-mail is more important than the name, and hence would like to display it before the name. Some customers might need more space for the name. Some customers cry because they don't need any phone numbers at all.
My goal: The user should be able to decide, how his form looks like.
I would like to set up a default template which should work for most customers.
I prefer not to reinvent the wheel, so is there any library which provides such functionality?
Such functionality could be (at runtime):

*

*Reorder Controls (e.g. with drag and drop)

*Store and Load UI Layout Templates

*Set Controls Visible / Invisible

*Resize Controls

If not, what would be the "best practise" to solve this?

If I had to reinvent the wheel, the most probable solution would be to create my own XML, which I would load at runtime and then set the rows and columns.
But since I'm quite new to WPF, I don't know if this was a proper solution.

At last, below is the XAML of the above example:
<Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
                <RowDefinition Height="28" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Label Grid.Row="0" Grid.Column="0" Content="Name:"/>
            <Label Grid.Row="1" Grid.Column="0" Content="E-Mail:"/>
            <Label Grid.Row="2" Grid.Column="0" Content="Phone:"/>
            <Label Grid.Row="3" Grid.Column="0" Content="Address:"/>
            <TextBox Grid.Column="1" Grid.Row="0" Margin="3" />
            <TextBox Grid.Column="1" Grid.Row="1" Margin="3" />
            <TextBox Grid.Column="1" Grid.Row="2" Margin="3" />
            <TextBox Grid.Column="1" Grid.Row="3" Margin="3" />
            <Button Grid.Column="1" Grid.Row="4" HorizontalAlignment="Right" MinWidth="80" Margin="3" Content="OK" Click="Button_Click"  />
</Grid>

A: Firstly, it is good that you ask this question before creating the application. Secondly, I think to this task dynamically creating View perfect come up DataTemplate. You should begin right away to develop your application in MVVM style, it would be more appropriate for dynamic View.
In the DataTemplate, the key role played DataTrigger. They allow depending on the value set property for an element that is in View. For example, the show / hide button, set the Height / Width, etc.
Example of DataTemplate:
<DataTemplate x:Key="MainView" DataType="{x:Type ViewModels:MainViewModel}">
    <Grid>
        <Button Name="UserButton"
                Content="Are you user?"
                Width="100"
                Height="30"
                HorizontalAlignment="Left"
                VerticalAlignment="Top"
                Command="{Binding UserButtonCommand}" />

        <Button Name="AdminButton"
                Content="Are you admin?"
                Width="100"
                Height="30"
                HorizontalAlignment="Right"
                VerticalAlignment="Top"
                Command="{Binding AdminButtonCommand}" />

        <StackPanel Name="MainViewPanel"
                    Tag="{Binding Path=MainModel.ContentType,
                                  Mode=TwoWay,
                                  UpdateSourceTrigger=PropertyChanged}">

            <TextBlock Name="TitleTextBlock"
                       Text="{Binding Path=MainModel.TitleText,
                                      Mode=TwoWay,
                                      UpdateSourceTrigger=PropertyChanged}"
                       FontSize="20"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       Visibility="Collapsed" />

            <TextBox Name="BannedTextBlock"
                     Text="{Binding Path=MainModel.BannedName,
                                    Mode=TwoWay,
                                    UpdateSourceTrigger=PropertyChanged}"
                     Visibility="Collapsed" />

            <Button Name="YesButton"
                    Content="{Binding Path=MainModel.ContentYesButton,
                                      Mode=TwoWay,
                                      UpdateSourceTrigger=PropertyChanged}"
                    Visibility="Collapsed" />

            <Button Name="NoButton"
                    Content="{Binding Path=MainModel.ContentNoButton,
                                      Mode=TwoWay,
                                      UpdateSourceTrigger=PropertyChanged}"
                    Visibility="Collapsed" />
        </StackPanel>
    </Grid>

    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding ElementName=MainViewPanel, Path=Tag}" Value="User">
            <Setter TargetName="TitleTextBlock" Property="Visibility" Value="Visible" />
            <Setter TargetName="YesButton" Property="Visibility" Value="Visible" />
        </DataTrigger>

        <DataTrigger Binding="{Binding ElementName=MainViewPanel, Path=Tag}" Value="Admin">
            <Setter TargetName="TitleTextBlock" Property="Visibility" Value="Visible" />
            <Setter TargetName="BannedTextBlock" Property="Visibility" Value="Visible" />
            <Setter TargetName="YesButton" Property="Visibility" Value="Visible" />
            <Setter TargetName="NoButton" Property="Visibility" Value="Visible" />
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

Given two buttons, one for the user and one for the administrator. If you choose the User, the content is displayed to the user, if the Admin, then for administrator. Content type specified in the Tag of StackPanel. Pay attention to the section <DataTemplate.Triggers>.
Complete example and description of an example is here (he still quite large):
Make (create) reusable dynamic Views

A: For the reordering part, you can combine Anatoliy Nikolaev's answer with a listbox and Gong Drag and Drop reorder => https://github.com/punker76/gong-wpf-dragdrop
The default layout of the listbox can easily be changed so that you don't have the selected items highlighting and so on.
You might also consider to provide two dynamic views, one for the actual form and one to edit the said form. Also at some point you will have to save the configuration for each user.


text:
Q: Use F1, F2 etc. keys to control built-in Mac features when using an external USB keyboard I use a generic external USB keyboard (specifically Amazon Basics Wired Keyboard) with my MacBook Pro. The keyboard doesn't include the fn key present on MacBook's built-in keyboard.
On the external keyboard, I wish for F1, F2 etc. keys to function just like built-in keyboards default configuration, i.e. to control Mac features like adjusting brightness, Mission Control, Launchpad etc. and not work as plain function keys.
How do I configure the external keyboard to do that? I would much prefer for a solution built into macOS rather than relying on a 3rd party app.
I am using a late 2013 15" MacBook Pro running macOS High Sierra 10.13.6.

A: The fn key isn't a modifier that's sent to the OS, it modifies the scan code that is sent.
To test this out, you can use a built in utility called xev (requires X11) to view the scan codes being sent from your mouse and keyboard.  You can also use Karabiner's Event Viewer to to obtain the key press scan codes.
What this means is that the scan code for F1 (130) will be different from the scan code of fnF1 (107).  Keep in mind that macOS allows you to "lock" the fn key to a particular behavior (have the function keys act as normal function keys or act as the "special feature keys").
This is different from other modifier keys (like Shift or Option in that both scan codes are sent (i.e. Shift A sends 64 and 8).
As for remapping a keyboard, you can use the built in utility hidutil to remap keys.  This answer here can guide you on how to do that.

*

*Apple Developer Documentation Key Table Usage

*USB.org Key Usage Table Reference (Page 53) (more in-depth source for Apple's Table)

This is a bit of a workaround for a simple keyboard, and my preference would be to just purchase a cheap keyboard with the fn key functionality built in so everything works out of the box.

A: No chance.
to use the function keys on the Mac you'll need an Apple keyboard.
I had the same problem at one of my customers Mac.
Edit: This information is wrong. Look at Allans post for the solution.


text:
Q: Enabling OverlayFS on Ubuntu 20.04 makes GNU GRUB selection pop up at boot I followed this great tutorial on how to enable overlayfs, basically just involves setting the file:
/etc/overlayroot.conf

to
overlayroot_cfgdisk="disabled"
overlayroot="tmpfs:swap=1,recurse=0"

Then rebooting. It work great, but theres some strange side effect that at boot, GNU GRUB pops up and asks me what I want to do:
GNU GRUB version 2.04
---------------------

*Ubuntu
 Advanced options for UIbuntu
 UEFI Firmware Setting

---------------------
Use up and down arrow to select which entry is highlighted.
Press enter to boot the selected OS.....

I have tried looking at my BIOS boot order settings, did not help.
If I disable OverlayFS, the request for the selection goes away.
How can I have OverlayFS without the request to select option at boot with GNU GRUB?


text:
Q: preg_replace doubt What I'm doing wrong ?
echo preg_replace('#\d{3}\d{3}\d{3}\d{2}#', '$1.$2.$3-$4', '12345678901');

Output would be this: 123.456.789-01. Isn't formating the string!!

A: <?php
echo preg_replace('#(\d{3})(\d{3})(\d{3})(\d{2})#', '$1.$2.$3-$4', '12345678901');

is correct, because dollar sign + integer refers to content in () brackets (grouping)
demo

A: You have not grouped correctly (missing brackets):
echo preg_replace('#(\d{3})(\d{3})(\d{3})(\d{2})#', '$1.$2.$3-$4', '12345678901');


text:
Q: Why is the output different in the short version of if condition when compared to its expanded version? int a = 0;
a = 7 > 2 ? printf("6") : printf("4");
printf ("%d",a);

The ouput of this block is :
61

I tried the code in its expanded form
    int a = 0  ;
    if(7>2)
    {
        printf("6");
    }
    else
    {
        printf("4");
    }
    printf("%d",a);

Here I the output was:
60

I would like to get an explanation on why the output differs.

A: The first statement assigns the return value of printf to a. printf returns the number of bytes that were written.  In this case that is 1.  In the second expanded version, a is not assigned.  Here is an actually equivalent version to the original:
int a = 0;
if(7>2)
{
    a = printf("6");
}
else
{
    a = printf("4");
}
printf("%d",a);

A: They are completely different.
To make them identical:
    int a = 0  ;
    if(7>2)
    {
        a = printf("6");
    }
    else
    {
        a = printf("4");
    }
    printf("%d",a);

A: cond?val1:val2 is the ternary operator. It is not supposed to be a control structure (like if, for or while). It is an operator. To build expression (things that have a value) rather than instruction (things that does things).
Frontier is fuzzier in C than in other languages, because instructions have a value (including void) and expression have potential side-effects.
But, well, you use cond?val1:val2 when you want to get the result. As you did, since you assigned the result to a.
And the result here is the result of printf("6"), that is 1, since printf returns the number of printed characters. Note that there is no real doubt, since even if 7 were smaller than 2, result would still have been 1. Since you print that result, it is normal to have a 1 printed after the 6.
(Just to be clear, even if I assume you know that already, what you did is print string "6" and then number 1, which is the result of 1st printf. Exactly as if you did
printf("%d",printf("6"));

which 1st prints "6", then pass the result to the outer printf to print what the inner printf returned, that is 1)
In your second code, you do nothing to change a's value, and you ignore the result of printf.

A: Your examples aren't equivalent. To be equivalent, the second one should say a=printf(... everywhere. After which a will get assigned the number of characters printed, 1.

A: The conditional operator (e1 ? e2 : e3) is not a "short version of if condition", although it has some similarities with an if ... else construct. The conditional operator yields a value (which you assign to a in your first example); an if ... else construct does not have a value.
So, your first example assigns a value to a, because it is written in the form of an assignment statement; that value is the 1 returned by the call to the printf function. To get similar behaviour in your second example, as others have said, you need to also assign the value returned by printf inside the if ... else blocks.
Alternatively, to make the first case work like the second, you can skip the assignment and use the conditional operation to determine the argument that is passed to the printf call:
int main(void)
{
    int a = 0;
    printf(7 > 2 ? "6" : "4");
    printf("%d", a);
    return 0;
}


text:
Q: Get all days and date for a given month Would like to retrieve all days and date for a given month. Have this currently which shows all the days for the current month, but how do I parse in a specified month instead?
$list=array();
for($d=1; $d<=31; $d++)
{
    $time=mktime(12, 0, 0, date('m'), $d, date('Y'));
    if (date('m', $time)==date('m'))
        $list[]=date('Y-m-d-D', $time);
}
echo "
";
print_r($list);
echo "
";

A: $days = cal_days_in_month( 0, $month, $year);

cal_days_in_month: Return the number of days in a month for a given year and calendar.
First parameter is "calendar":
0 or CAL_GREGORIAN - Gregorian Calendar
1 or CAL_JULIAN - Julian Calendar
2 or CAL_JEWISH - Jewish Calendar
3 or CAL_FRENCH - French Revolutionary Calendar
http://php.net/manual/en/function.cal-days-in-month.php
http://php.net/manual/en/function.cal-info.php

A: try this
$list=array();
$month = 12;
$year = 2014;

for($d=1; $d<=31; $d++)
{
    $time=mktime(12, 0, 0, $month, $d, $year);
    if (date('m', $time)==$month)
        $list[]=date('Y-m-d-D', $time);
}
echo "
";
print_r($list);
echo "
";

A: for object oriented users,
function getDaysInYearMonth (int $year, int $month, string $format){
  $date = DateTime::createFromFormat("Y-n", "$year-$month");

    $datesArray = array();
    for($i=1; $i<=$date->format("t"); $i++){
        $datesArray[] = DateTime::createFromFormat("Y-n-d", "$year-$month-$i")->format($format);
    }

 return $datesArray;
}

A: try this
$month = "05";
$year = "2014";

$start_date = "01-".$month."-".$year;
$start_time = strtotime($start_date);

$end_time = strtotime("+1 month", $start_time);

for($i=$start_time; $i<$end_time; $i+=86400)
{
   $list[] = date('Y-m-d-D', $i);
}

print_r($list);

See Demo

A: I'm surprised nobody mentioned PHP's built-in, no extra extensions DateTime class.
<?php
$daysInAugust2020 = (new DateTime("20200801"))->format('t');
print_r($daysInAugust2020);

You'll have to append some day to your YYYYMM string, but it's not that hard: every month has a 1st. So you can always add 01.
The trick here is the t format, which just returns the number of days in the month the date is in. If you're trying to get this month's amount of days, it's even easier. Just running the date() function creates a DateTime set to right now, so the above code becomes:
<?php
$daysInAugust2020 = date('t');
print_r($daysInAugust2020);

A: Take advantage of the relative formats.
$y_m = '2018-10'; // set year and month.

$list = array();
$d = date('d', strtotime('last day of this month', strtotime($y_m))); // get max date of current month: 28, 29, 30 or 31.

for ($i = 1; $i <= $d; $i++) {
    $list[] = $y_m . '-' . str_pad($i, 2, '0', STR_PAD_LEFT);
}

echo '
';
print_r($list);
echo '
';

A: $list=array();
$d = 13;
$year = 2019;

for($m=1; $m<=12; $m++)
{
    $time=mktime(12, 0, 0, $m, $d, $year);
    if (date('m', $time)==$m)
        $list[]=date('D-d-m-Y', $time);
    }

In this one you can put a spesific number and outpout all the days in the year that have the same number. example i wanted to outpout all the 13th days of the month. (if you want to find every Friday 13th that what you have to use)

A: This works like a charm.
Tried cal_days_in_month but didn't work.
function Get_Month_Dates($year,$month)
{
    $no_of_days = date("t",strtotime($year.'-'.$month));

    $dates = array();

    for($d=1;$d<=$no_of_days;$d++)
    {
        $day = (strlen($d)==1) ? '0'.$d : $d; // To add leading zero to the date
        $month = (strlen($month)==1) ? '0'.$month : $month; // To add leading zero to the month

        $dates[] = $year.'-'.$month.'-'.$day;
    }

    return $dates;
}

A: you may use $list[]=date('Y-M-D', $time);
Reference

A: $c_year = date("Y");
$c_month = date("m");
$no_day = cal_days_in_month(CAL_GREGORIAN, $c_month, $c_year);
for($i=1; $i<=$no_day; $i++){
     $cd[] .= $c_year.'-'.$c_month.'-'.$i;
}
$date_val = json_encode($cd)
print_r($date_val); // date array

A: This will get all date current month
$alldatethismonth = range(1, $month);
foreach($alldatethismonth as $date){
    echo date("Y-m-").$date."
";
}

And this will get all date for given month
$month = date("t", strtotime('2021-09-18'));
$alldatethismonth = range(1, $month);
foreach($alldatethismonth as $date){
    echo date("Y-m-").$date."
";
}


text:
Q: file IO and preprocessors in Windows runtime component I am new to using C#. I am creating a windows Runtime Component in C# using Visual Studio 2012.
I want to use File operations like write and read.
normal syntax of using file IO (The one where we use in normal form application) like:
String text = System.IO.File.ReadAllText(@actualOutputFileName);

doesn't seem to work. I have aslo tried using preprocessors like #ifdef. Those don't work either. Can anyone provide me link where i can read about these stuff. I have referred this link: http://msdn.microsoft.com/en-us/library/windows/apps/br230301.aspx
The closest I have come across is this piece of code that is compatible with windows store apps:
StorageFolder storageFolder = KnownFolders.PicturesLibrary;
StorageFile sampleFile = await storageFolder.GetFileAsync("id.txt");
                liveid = await FileIO.ReadTextAsync(sampleFile);

Can anyone please help me. Thanks in advance.

A: Microsoft are forcing Windows Store app developers to do all I/O asynchronously, so that the UI is not blocked by slow synchronous I/O. The synchronous I/O methods are all banned.
For System.IO.File.ReadAllText, Microsoft suggest using Windows.Storage.PathIO.ReadTextAsync.
In C#, to do conditional compilation, you use #if.


text:
Q: Using .match() in ReactJS - match is not a function? I'm trying to use match() to filter results from an array in React :
if (this.props.search) {
   tracks.filter(result => {
      return result.match(`/${this.props.search}/gi`);
   });
}

But I'm getting :
TypeError: result.match is not a function

Am I missing something really obvious here? It's been a long day :/
Example of tracks array :
0:
  active: 1
  artist: "CJ Bolland"
  date_added: "2019-01-03 05:08:10"
  date_modified: "2019-01-03 05:09:01"
  duration: "00:05:54"
  filename: "1546488490.mp3"
  id: 2
  in_playlist: false
  online: 1
  seconds: 354
  time_ago: "1 hour ago"
  title: "Sugar Is Sweeter (AVH Mix)"
  type: "track"
  user_id: 4

1:
  active: 1
  artist: "Cristoph"
  date_added: "2019-01-03 05:08:46"
  date_modified: "2019-01-03 05:10:01"
  duration: "00:06:34"
  filename: "1546488526.mp3"
  id: 3
  in_playlist: false
  online: 1
  seconds: 394
  time_ago: "1 hour ago"
  title: "Guffaz"
  type: "track"
  user_id: 3

**** EDIT ****
Here is a screen shot of what's happening after implementing Just code's solution (which is working fine here on SO, but not in React). As you can see, I'm logging 3 things, the original array, the search term and the filtered array, but the filtered array always returns empty.

A: Seems that your regex is transformed to the string and the regex is not working properly,
You can do something like this, when it comes to string interpolation regexp object is always a handy.
return result.match(new RegExp(`${search}`,'gi'));

var tracks = [{
  artist: "CJ Bolland",
  title: "Sugar Is Sweeter (AVH Mix)"
}, {
  artist: "Cristoph",
  title: "Guffaz"
}];
var search = "sug";
var filtered = tracks.filter(result => {
  return result.artist.match(new RegExp(`${search}`, 'gi')) || result.title.match(new RegExp(`${search}`, 'gi'));
});
console.log(filtered);

A: In my case, i was trying tô use match in a number. So i just used .toString() before using .match().


text:
Q: Receiving and sending email using Amazon SES I have a domain configured to send mails using Amazon SES. Both sending and receiving using normal SMTP server are working just fine. I have MX record setup as feedback-smtp.us-west-2.amazonses.com (10) and using mail from domain mail.mydomain.com. I have two e-mail addresses 'mail@mydomain.com' and 'sales@mydomain.com'.
I now need to enable receiving using Amazon SES to process emails coming on 'mail@mydomain.com' through SNS. I have verified this e-mail address and created rules to process it through SNS. The receiving documentation states that  I need to setup MX record as inbound-smtp.us-west-2.amazonaws.com which I did. I am successfully receiving incoming notifications for 'mail@mydomain.com' but mail receiving has stopped on 'sales@mydomain.com'. The mails sent on this address are bouncing.
To be specific, I need to know:
"Does enabling receiving for one e-mail address on a domain has effect on all e-mail addresses of the domain?"


text:
Q: Facebook Send URL -- linking to application I'm trying to use the Facebook Send button on an external website to link users to a specific application (an instance of "MyTab") on my client's Facebook Fan page (the link to which looks something like:
https://www.facebook.com/ClientName?sk=app_XXX

I had no trouble embedding the send button on the external website, using the following code:

<fb:send href="https://www.facebook.com/ClientName?sk=app_XXX"></fb:send>

The problem is, the URL is truncated to https://www.facebook.com/ClientName when it is successfully sent.
How can I preserve the entire link so that users are sent DIRECTLY to the application?
I've tried encoding the url using "urllib" but that didn't work.
I'm stumped!

A: This is due to OpenGraph meta tags in the URL you use are for Facebook Page, even for Page Tab they represent the page itself leading to link that differs from initial one you've provided.
You may create intermediate page that will handle redirection with javascript to Fanpage Tab Application and providing OpenGraph tags for content that will be displayed in message sent.


text:
Q: Cannot marshal 'return value': Invalid managed/unmanaged type combination I have this function in an unmanaged library and I want to call it in C#:
unsigned char __stdcall InitDev(unsigned char comport, long BaudRate)
and this is in C#
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("*.dll", CallingConvention = CallingConvention.Cdecl,CharSet =CharSet.Auto)]
public static extern byte[] InitDev(byte[] comport, [Out]long BaudRate);

but when I call this function in C# I get the following error

"Cannot marshal 'return value': Invalid managed/unmanaged type combination."

string COM = "COM3";
byte[] ptr = new byte[1];
try
{
    ptr = InitDev(Encoding.ASCII.GetBytes(COM), 9600);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

I am new to this if a little guidance is provided I will be able to resolve this issue

A: Assuming your native call is something like unsigned char* InitDef(unsigned char*, long long &baudRate) then you probably want to use IntPtr in the place of your unsigned char*. But first since it's managed/unmanaged mixing you should allocate that byte[] buffer for input and output :
byte[] pInBuffer = Encoding.ASCII.GetBytes("COM3");
// allocate unmanaged memory
IntPtr inputBuffer = Marshal.AllocHGlobal(pInBuffer.Length * sizeof(byte));
Marshal.Copy(pInBuffer, 0, inputBuffer, pInBuffer.Length);

// now your inputBuffer contains a native pointer to the `unsigned char*`
// and since your function returns a new pointer to some `unsigned char*`
// just retrieve it to IntPtr
IntPtr result = InitDev(inputBuffer, 9600);

// free your allocated memory
Marshal.FreeHGlobal(inputBuffer);

At this stage your result contains the value returned from InitDev.

new definition of InitDev function
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("*.dll", CallingConvention = CallingConvention.Cdecl,CharSet =CharSet.Auto)]
public static extern IntPtr InitDev(IntPtr comport, [Out] long BaudRate);

All of the necessary calls, you can find on this msdn page

EDIT :
Since your native call looks like this :extern unsigned char __stdcall InitDev(unsigned char comport,long BaudRate);
I'm guessing that the first parameter is just the last digit ( index ) of your "COMn" because unsigned char's lowest possible value is 0 and COM's lowest index can be 0.
Try using this snippet :
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("*.dll", CallingConvention = CallingConvention.Cdecl,CharSet =CharSet.Auto)]
public static extern byte InitDev(byte comport, long BaudRate);

And then call it like so :
byte comIdx = 3;
byte result = InitDev(comIdx, 9600);
// byte should yield correct result now


text:
Q: Pandas dataframe max in a group based on conditions on other columns I'm not sure if this question has been asked before. In a pandas dataframe I have data like
    A    B    C

1   z    0    0
2   z    1    1
3   z    2    2
4   y    0    0
5   y    1    1
6   z    2    2.5
7   z    0    0
8   z    1    0.2
9   z    2    0.8

I would like to get
    A    B    C

1   z    2    2.5
2   y    1    1
3   z    2    0.8

In the above example(from first table) z went from 0 for B and C to 2 for B and 2.5 for C respectively before going to 0 for B and C. One important property is B and C can be different however they will go to 0 at the same time. Think of it as a counter, when device is off all your counters will go back to 0. The devices in above example being y and z.
Also from the first table you can also see y went from 0 to 1 for both B and C respectively however they never went back to 0 but I still need the maximum which is 1 and 1 for B and C.
I can write some python code to loop through and do the necessary transformations but I was wondering if this is possible with some pandas magic.

A: Here's an approach that uses vectorized methods all the way through and should be pretty quick.
Add a column with value 1 when there is a 'reset' of the counter, by checking where both B & C are 0.
df['new_sample'] = (df[['B','C']] == 0).any(1).astype(int)

Then, groupby the device type, and using the cumulative sum of the new_sample column, create a counter for which trial of each device each row represents.
df['sample'] = df.groupby('A')['new_sample'].cumsum()

Finally, you can group by the device and sample number and take the maximum.
In [85]: df.groupby(['A', 'sample'], as_index=False)[['B','C']].max()
Out[85]:
   A  sample  B    C
0  y       1  1  1.0
1  z       1  2  2.5
2  z       2  2  0.8


text:
Q: How to suspend a job using the marathon API I'm trying to invoke the marathon API to suspend a job. I don't see in the API docs how to do it, but I thought that I could do it by setting instance = 0. But all that's done is cause my job to enter the "Deploying..." state (apparently forever). On the other hand, when I suspend a job using the marathon web portal, it gets suspended right away.
Does anyone know how to do this?
$.fn.suspendjob = function(id) {
$.ajax({
  type: 'PUT',
  url: 'https://mesos-head.achillesv.net/marathon/v2/apps' + id,
  headers: {
    "Authorization": "Basic " + btoa(user + ":" + pass)
  },
  data: JSON.stringify({ instances: 0}),
  contentType: "application/json; charset=utf-8",
  success: function(result) {
    appslist.length = 0;
    $('#tabs').tabs("option", "active", 1);
    $('#tabs').tabs("option", "active", 0);
  }
});

};

A: I think your solution is good (set instance = 0). I tried this solution and it worked. Please try again!

A: A small python script to achieve this (It assumes marathon is running on localhost on port 8080):
    import requests

    marathon = "http://localhost:8080/v2/apps/<app-name>"
    payload = {'instances': 0}
    r = requests.put(marathon+"?force=true", json=payload)
    #'?force=true' will be useful if an app is in deploying state
    print r.status_code, r.reason


text:
Q: VSCode connect with Remote SSH and then run command to log to another machine I want to use VSCode from Windows but I need to open a folder in a remote Linux. I can use Remote - SSH with no problems for that, but now I need to do another "jump" from the remote Linux to another remote.
But the problem is that the 2nd remote is not reached via "ssh" from inside the 1st remote (if that was the case I would use the jump server function of vscode remote ssh).
To reach that 2nd remote, I need to run 2 commands in the 1st remote:
setenv EX_VAR something
mlogin -2ndremote

With those 2 commands I go to another "machine" in a grid and there are folders that I need to open.
If I do this in a Windows Powershell terminal, it works:
ssh -t user@1stremote "setenv EX_VAR something; mlogin -2ndremote"

But I can't run a vscode GUI from that point. I tried to edit the SSH configuration file in VSCode to include "RemoteCommand" and put those 2 commands, but it doesn't work.
I also tried to put that entire line that it works on windows terminal on the dialog box that show up in VSCode when you do "Add New SSH Host" but it also doesn't work. It always just connects to the first remote and it stays there, the commands are not executed.
Thanks!


text:
Q: Ipywidgets not interacting in "while True" loop 1)This is the code snippet that I am trying to run.The main idea is that, I want the ipywidgets to be interactive, while the data is constantly being fetched from the data source. And the data is being updated at certain interval using the while loop.The objective is to plot the principal components interactively by changing the number of principal components(PC) to be considered, using the @interact function.
Also it runs perfectly fine without while loop, that is, when we are not considering the auto-update for the dataset, with the while loop. But when I include the while loop, it doesn't handle the interactive-ness of the widgets(that is, the interaction of the number of PC).
My feeling is that "while True" loop does not let the interaction of ipywidget to happen, due to some execution issue.
2) Also I looked into threading but i am unsure of how to use the fucntion which is in functools(select_data), be called using threading.Thread.
Any sort of help would be appreciated. Thanks
def data_import_date(start_date,end_date):
    end_date1=end_date.strftime('%Y-%m-%dT%H:%M:%S')
    start_date=pd.Timestamp(start_date)
    end_date=pd.Timestamp(end_date1)

    button=widgets.Button(description='Pull Data')
    button.on_click(functools.partial(select_data,rs_=[start_date,end_date]))

    vbox=widgets.VBox([button])
    display(vbox,out)

def select_data(b,rs_):
#     clear_output()
    start_date=rs_[0]
    end_date1=rs_[1]
    print("Data pulling started")

    with out:
        clear_output()
        seeq_login()
        [item1,item2]=query_seeq_for_data()
        i=0
        while True:
            end_date=end_date1.strftime('%Y-%m-%dT%H:%M:%S')
            print("Start & End date: ",start_date,end_date)
            if i==0:
                [X_data,Y_data]=pull_data(item1,item2,start_date,end_date)
            else:
                [X_data_live,Y_data_live]=pull_data(item1,item2,start_date,end_date)
                X_data=X_data.append(X_data_live)
                Y_data=Y_data.append(Y_data_live)
            print("Data pulling completed.\nNow you're ready for your analysis")

            clear_output()
            [X_train,X_test,Y_train,Y_test]=train_test(X_data,Y_data)

            [Xp_train,components,explained_variance_ratio,_,_]=apply_PCA(X_train,X_test)
            plot_PC_variance(X_data,explained_variance_ratio)
            plot_PC(X_data,components)

            time.sleep(20)
            start_date=end_date
            end_date1=end_date1+datetime.timedelta(days=1)
            i+=1

  a=interact(data_import_date,
           start_date=widgets.DatePicker(value=pd.to_datetime(start_date)),
           end_date=widgets.DatePicker(value=pd.to_datetime(end_date)))

def plot_PC(X_data,components):
    Np_comp=(1,len(X_data.columns),1)
    @interact
    def principal_components(PC1=Np_comp,PC2=Np_comp):
        fig,ax=plt.subplots(1,1,figsize=(10,10))
        plt.figure(5)
        print(PC1, PC2)

        ax.set_xlabel("Principal Component {}".format(PC1), fontsize=14)
        ax.set_ylabel("Principal Component {}".format(PC2), fontsize=14)
        ax.set_title("Principal components {0} & {1}".format(PC1,PC2), fontsize=(20))
        ax.scatter(components[:,PC1],components[:,PC2])

A: A fairly rudimentary example that shows how you can run a loop whilst polling for widget changes, but it's not really my area of expertise.
Drag the slider whilst the values are printing and you should see the printed value change to reflect current slider position.

import threading
from IPython.display import display
import ipywidgets as widgets
import time
float_val = widgets.FloatSlider()
display(float_val)

def work(progress):
    total = 10
    for i in range(total):
        time.sleep(1)
        print(float_val.value)

thread = threading.Thread(target=work, args=(progress,))

thread.start()


text:
Q: How to create an unblockable popup/popunder window or iframe? I want to automatically open website B after website A is loaded. There seem 2 options.
One is using iframe to include website B on A's website. Unfortunately, B excerts a X-Frame-Options=SAMEORIGIN policy thus cannot be iframed.
The other option is to open a new popup/popunder window to display B.  However, browsers block these popup/popunder windows.
I tried all the code found on the Internet that claim to bypass the X-Frame-Options restriction or create an unblockable popup/popunder window, but none works. The closest to success method is when a visitor moves his mouse pointer on the browser, the popup/popunder window displays(not blocked). I do not know how it is implemented.
I would like to know if a working solution exists at present.
Thanks!

A: You can't, X-Frame-Options=SAMEORIGIN exists for this exact purpose. You can ask the website owner to change the header to allow it.


text:
Q: Wasn't Rey cold on Starkiller base? Shouldn't this have impacted her somehow? Rey grew up in an environment that was desert like. For her entire life prior to the movie, she was used to a warm environment (at least daytime).

It's clearly snowing, but she is wearing the same outfit she routinely wore on a planet that was described by Star Wars wiki with a climate of "hot." We don't know how cold the base was, but it's snowing, so clearly colder.
While I might not be a Jedi-in-training, when I go to an environment that is significantly colder it affects me physically. And I live in a climate which has seasons - not having grown in a desert for 20 years.
Shouldn't Rey have been somehow physically affected by this? Or at least.. been really cold?
Inspired by this question


text:
Q: Connection pool in MongoDB with jongo I would like to use connection pool for MongoDB. I have used MongoDB with Jongo and Spring MVC framework.
Here is my spring xml code for MongoDB configuration, which is working fine.
<!-- Mongo Configuration -->
<mongo:mongo id="mongo" host="${mongodb.host}" port="${mongodb.port}">
</mongo:mongo>

<mongo:db-factory id="mongoDbFactory" mongo-ref="mongo" dbname="${mongodb.database}" username="${mongodb.username}" password="${mongodb.password}" />

I need to configure a connection pool. Can anyone guide, How to implement MongoDB connection pool with existing code?

A: Please check if the following helps
https://dzone.com/articles/multiple-mongodb-connectors-with-spring-boot
Also, a similar question seems to be asked
Connection pooling in Spring Boot and mongo db


text:
Q: gitlfs batch response: Post https://../info/lfs/objects/batch: ..proxyconnect tcp: tls: first record does not look like a TLS handshake I have a bitbucket server git repo with LFS turned on. Yesterday I activated the use of LFS for a number of file types in my local clone and pushed all changes, including .gitattributes in the repo root.
A colleague of mine pulled the changes, executed git LFS install but now finds in his clone the LFS link files instead of the real files.
Another git pull made no difference, and a git LFS pull gave him
$ git lfs pull
batch response: Post https://<bitbucket-server>/scm/<proj>/<repo>.git/info/lfs/objects/batch:
...proxyconnect tcp: tls: first record does not look like a TLS handshake
error: failed to fetch some objects from
'https://<bitbucket-server>/scm/<proj>/<repo>.git/info/lfs'

Unfortunately there is no hint on any git lfs info page what this means - and how to fix it.
Is there any way I can make git lfs work for the rest of the team?
And, just for curiosity, what is the reason for this message?
All git lfs tutorials pretend that it is easy to use git lfs, but obviously it isn't.

A: It looks like your git lfs operation is trying to use your corporate proxy server. You may have better luck if you set the no_proxy variable to ignore the <bitbucket-server> URL.
Typically it is set to something like this:
export no_proxy=127.0.0.1,localhost,.<your-domain>

But you can be explicit and set it to ignore <bitbucket-server>
export no_proxy=127.0.0.1,localhost,<bitbucket-server>

Please note the leading . before <your-domain> in that example.
Also by setting GIT_TRACE=1 you can get more hints on what the problem might be.
GIT_TRACE=1 git lfs pull

A: Sometimes the git-lfs cannot work if you set proxy in your environment, so you can try to clean all your proxy, and then it maybe work.
You can check proxy setting by the following:
env| grep -ai proxy.

A: I had the same problem, and I can fix it by

unset https_proxy.

git-lfs works with http_proxy fine. May be it's help some peoples in future! Good Luck!


text:
Q: Unity3d Select child object by touch My problem occurs when I touch the child object (it's a pillow on a sofa).
collider.transform.name always returns the parent's name. I'm trying to change the selected object color. The color change script works well except that it always returns the parent.
An example: I want to change only the pillow color on the sofa but it changes the sofa color and not the pillows. I'm new to Unity.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class objectSelect : MonoBehaviour {
    public Text tex;
    public Text tex2;
    public Transform obj1;
    public string rr;

    void Start () {
    }

    void Update () {
        Touch touch = Input.touches [0];
        Vector3 pos = touch.position;
        if (Input.touchCount > 0 && touch.phase == TouchPhase.Began) {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (pos);
            Vector3 planePoint = ray.GetPoint(0.0f);
            if (Physics.Raycast(ray,out hit))
            {
                obj1 = hit.transform;
                tex.text = obj1.transform.gameObject.GetInstanceID().ToString();
                tex2.text = hit.collider.transform.name;
                RR=obj1.transform.gameObject.GetInstanceID().ToString();
            }
        }
    }

    public string getselectedObj() {
        return obj1.transform.gameObject.GetInstanceID().ToString();
    }
    public string r() {
        return "rrrrrR";
    }
    public string RR {
        get {
            return rr;
        }
        set {
            rr = value;
        }
    }
}

A: Your pillow colliders are inside the Sofa colliders. That is why on touch, your game is finding sofa prior to pillows. Try to customize the sofa colliders. By adding more than one BoxColliders in a way so that pillows will come forward.

A: The Box Collider of the sofa contains both the pillow colliders. As a result, no ray or in fact no object can touch the pillow collider, because it is inside the sofa collider, which is why the sofa collider will always be touched first. The solution to this can be to make a compound collider for the sofa, that is make one collider for the base of the sofa, add it to the "sofa" game object, make two-three more colliders for the sofa's armrests and backrests and add them as children of the collider.

A: expected Solution!
use Mess collider rather than box collider for sofa and pillow this will solve pillow unreachable issue.
I use same solution for one of client having same scenario!
    objectSelect theScript = touchObj.GetComponent<objectSelect>();
    Renderer x = theScript.obj1.GetComponent<Renderer>();
    x.material.color = <Color you want to apply>;

touchObj  object that return reference to the object you touch ex. sofa or pillow


text:
Q: Cannot use Scrapy in Python 3.5 on Windows I have Scrapy installed through Anaconda3 with Python 3.5 in Windows 8.1. When i tried to import Scrapy, it made the following error:

File "C:...\Anaconda3\lib\site-packages\twisted\python\compat.py", line 745, in
     Version("Twisted", 15, 5, 0),
TypeError: 'module' object is not callable

What does that error mean?
I've read some pages on 2016 said that Scrapy can't be used on Windows with Python 3, but maybe there are many improvements and tricks I don't know of. Should I downgrade my Python to 2.7 to use Scrapy?


text:
Q: How to publish and consume office web add-ins only internally? We're planning to develop a series of add-ons for office, but we don't want to publish them to app store because these add-ons are only developed for our employees.
But we still want to gather our add-ons on a store.
Is it possible that we quickly build our own app store so that our employees can download add-ons conveniently? Does office has this api? I didn't find it in the document.

A: It seems that your use case scenario is Centralized Deployment via the Office 365 admin center. In this way you can publish add-ins to users, groups or an organization.


text:
Q: How to configure LVM & LUKS to autodecrypt partition? I have recently installed ubuntu server 11.04 with the full lvm encryption(installed from the setup) . I wish now to use a key file to do automatic unlock. I have tried to follow this guide http://ubuntuforums.org/showthread.php?t=837416
I generated a key with this command: sudo dd if=/dev/urandom of=/boot/grub/keyfile bs=1024 count=4
i putted it in /boot/grub because i think that it's not encrypted . When i try to add the key with this commad sudo cryptsetup luksAddKey /dev/sdX /boot/grub/keyfile
it asks me for the passphrase and when i put it nothing happen , nothing is printed to the screen ! I ignore it and continue the others steps and reboot but nothing happened and it ask for the passphrase .
Thanks for the help .

A: Improving Randy Orrison's answer, here is a small script I created, that will make system fallback to asking user for password if it fails to find the keyfile.
#!/bin/sh

ask_for_password () {
    cryptkey="Unlocking the disk $cryptsource ($crypttarget)\nEnter passphrase: "
    if [ -x /bin/plymouth ] && plymouth --ping; then
        cryptkeyscript="plymouth ask-for-password --prompt"
        cryptkey=$(printf "$cryptkey")
    else
        cryptkeyscript="/lib/cryptsetup/askpass"
    fi
    $cryptkeyscript "$cryptkey"
}

device=$(echo $1 | cut -d: -f1)
filepath=$(echo $1 | cut -d: -f2)

# Ask for password if device doesn't exist
if [ ! -b $device ]; then
    ask_for_password
    exit
fi

mkdir /tmp/auto_unlocker
mount $device /tmp/auto_unlocker

# Again ask for password if device exist but file doesn't exist
if [ ! -e /tmp/auto_unlocker$filepath ]; then
    ask_for_password
else
    cat /tmp/auto_unlocker$filepath
fi

umount /tmp/auto_unlocker

Save it and replace keyscript=/lib/cryptsetup/scripts/passdev in /etc/crypttab with the path to this file and run sudo update-initramfs -uv and you are done.

A: These instructions from howtoforge.com got me up and running with an automatically decrypting volume.
How to: Automatically Unlock LUKS Encrypted Drives With A Keyfile
Step 1: Create a random keyfile
sudo dd if=/dev/urandom of=/root/keyfile bs=1024 count=4

Step 2: Make the keyfile read-only to root
sudo chmod 0400 /root/keyfile

That will make the keyfile readable only by root. If someone get access to this keyfile, then you have a bigger problem on your computer anyway.
Alternatively chown your desired keyfile to root:root and move it into the /root folder
Step 3: Add the keyfile to LUKS
LUKS/dm_crypt enabled devices may hold up to 10 different keyfiles/passwords. So, next to having the already setup password we're going to add this keyfile as additional authorization method.
sudo cryptsetup luksAddKey /dev/sdX /root/keyfile

sdX is of course your LUKS device.
First you'll be prompted to enter an (existing) password to unlock the drive. If everything works well, you should get an output like this:
Enter any LUKS passphrase:
key slot 0 unlocked.
Command successful.

Step 4: Create a mapper
LUKS devices need to create a mapper that can then be referenced in the fstab. Open /etc/crypttab
sudo nano /etc/crypttab

and add then a line like this:
sdX_crypt      /dev/sdX  /root/keyfile  luks

or you can use the UUID of the device:
sdX_crypt      /dev/disk/by-uuid/247ad289-dbe5-4419-9965-e3cd30f0b080  /root/keyfile  luks

sdX_crypt is the name of the mapper that is being created. You can use here any name e.g. "music" or "movies" or "sfdsfawe" ....
Save and close the file by issuing ctrl-x, enter, enter. Ctrl-x closes nano but first it asks to save the file [yes = enter] and what the name shall be [same name = enter].
What we have done there actually is telling that /root/keyfile shall be used instead of password entry to unlock the drive.
Step 5: Mount the device in fstab
Now, we have an unlocked device (well, not yet but when the system is being booted up) and we just need to mount it now. Open /etc/fstab:
sudo nano /etc/fstab

and add a new entry like:
/dev/mapper/sdX_crypt  /media/sdX     ext3    defaults        0       2

Make sure you have the correct mapper name that you added in step 4. Also make sure that the mount point/folder exists. After having added it, save again the file and close it (ctrl-x, enter, enter).
Step 6: Reboot or remount
That's it. Now you can reboot and the additional devices should be auto-unlocked and mounted. You can also test it by remounting all devices:
sudo mount -a

A: I've just been through this on my new home server, it took a lot of googling and guessing, but I've got it working.  I'll attempt to reproduce the steps here.  I'm using Ubuntu Server 11.10, and started with a pretty much standard install using encrypted LVM, so I'll just relate the changes I made from there.
Setup:

*

*/dev/sda1 is my unencrypted /boot partition

*/dev/sda5 is my lvm partition which contains everything else -- root, swap, and home

*/dev/sdc1 is the partition on my USB flash drive where I'll store the keyfile

First, I created a keyfile, just in my home directory:
dd if=/dev/urandom of=keyfile bs=512 count=4

(you can use a larger blocksize or count for a larger key)
Tell cryptsetup the new key (it's the contents that are important, not the filename):
sudo cryptsetup luksAddKey /dev/sda5 keyfile

Then, I formatted my USB flash drive with ext2 and gave it a label.  I used a label, so that later I can mount it by label, and replace the USB flash drive in case something goes wrong with it.
sudo mkfs -t ext2 /dev/sdc1
sudo e2label /dev/sdc1 KEYS

(of course, your device will vary)
Now, copy the keyfile to the USB flash drive, owned by root mode 400:
mkdir KEYS
sudo mount /dev/sdc1 KEYS
sudo cp keyfile KEYS
sudo chown root KEYS/keyfile
sudo chmod 400 KEYS/keyfile

Modify /etc/crypttab.  Mine originally contained
sd5_crypt UUID=(...) none luks

which I changed to
sd5_crypt UUID=(...) /dev/disk/by-label/KEYS:/keyfile luks,keyscript=/lib/cryptsetup/scripts/passdev

Finally, update the initramfs:
sudo update-initramfs -uv

It now boots using the keyfile on the USB flash drive.  If I remove the flash drive (say, when I go on holiday) it doesn't boot and my data is secure.
If anyone knows how to get it to ask for the passphrase if the USB flash drive is missing, that would be handy as a fallback.  Hope this helps, any additions or corrections would be more than welcome!

A: @deitch
I had the same setup like @Randy Orrison and ran into the same issue as you and it turns out is a bug of systemd which tries to mount the / filesystem again as it finds the corresponding entry in /etc/crypttab.
To resolve this i just removed the entry for sda5_crypt from /etc/crypttab once the update-initramfs -uv command was ran.
Reeboot and everything works fine as intended.


text:
Q: DC Motor bridge driver L298N. Why separate the tracks after R sense resistors from GND plane? The L298N datasheet says:

The sense resistor, not of a wire wound type, must be grounded near
  the negative pole of Vs that must be near the GND pin of the I.C.

why not in common GND plane?
If I connect resistors to the common ground, how does this affect the operation of the device?
Thx.

A: The L289 datasheet Application Instructions - Suggestions, on page 7, says:

The sense resistor, not of a wire wound type, must
  be grounded near the negative pole of Vs that must
  be near the GND pin of the I.C.

This ensures that the voltage measured on the sense inputs is all due to the current on that output and not any other currents running through the ground plane causing small additional voltage lifts which would cause errors in the current control.


text:
Q: Rails 3 - Disable cache for filename in file_column plugin This is my code to obtain an UUID:
  def manage_id
    self.id = UUIDTools::UUID.random_create().to_s.upcase if self.id.blank?
  end

This works perfectly for the primary key of my object.
My problem is I want to name an uploaded file with an UUID... and I obtain the same UUID for different uploads. For example I will have an UUID and 2 minutes later with another object I will have the same UUID !
This is the class code to name my image:
:filename => "#{UUIDTools::UUID.random_create().to_s.upcase}.jpg" }

I don't understand what can be the problem when generating the UUID...
I have not the problem in development !!!
EDIT 1: the problem is not with UUID itself, it's the same with a timestamp... (and only in production)
EDIT 2: I found the problem. The setting:
config.cache_classes = true
is the problem in production mode. It is certainly keeping the UUID somewhere in memory.
I think I can't switch to false in production mode (for performance), so what is the best way to deactivate the cache for this plugin name feature ?
EDIT 3: I add the full code of my model
class Product < ActiveRecord::Base

 file_column :image, {:magick => { :versions => { "tiny" => "70x70", "small" => "160x240", "high" => "640x960" }}, :store_dir => "public/upload/wine/image", :web_root => "upload/", :filename => "#{UUIDTools::UUID.timestamp_create().to_s.upcase}.jpg" }

end

So, as I said the UUID generated is cached in production. I don't know how to force this model or maybe the plugin file_column to not be cached ?

A: The reason that it doesn't work for you because you always use pre-initialized option.
But you can try to change something to improve it. For example you can use lambda expression for calcaulationg filename ... Try something like next
file_column :image, {:magick =>
                            { :versions =>
                                { "tiny" => "70x70", "small" => "160x240", "high" => "640x960" }
                             },
                             :store_dir => "public/upload/wine/image",
                             :web_root => "upload/",
                             :filename => lambda { "#{UUIDTools::UUID.timestamp_create().to_s.upcase}.jpg"} }

and change this

Assign filename to temp image path. Update code @class TempUploadedFile store_upload method line number 219

@filename = options[:filename] || FileColumn::sanitize_filename(file.original_filename)

to
options_file_name = options[:filename].respond_to?(:call) ? options[:filename].call : options[:filename]

   @filename = options_file_name || FileColumn::sanitize_filename(file.original_filename)


text:
Q: How to deploy weblogic application as docker container completely using Dockerfile? I've a simple REST API in the weblogic application. I've to deploy the application as the docker container. But, I'm facing a problem in defining the Dockerfile.

Dockerfile

FROM store/oracle/weblogic:12.2.1.4
COPY target/app.war /u01/oracle

Above is my current Dockerfile. With the current dockerfile, I have to manually deploy the application on the weblogic server. We would like to automate the application deployment using Dockerfile and didn't get the exact examples.
Please advise.

A: This is a complex task, so it is hard to explain the whole process here.
The high-level steps that you need to execute are the followings:

*

*Start a properly configured WebLogic domain in Docker. This task involves the creation of the admin and managed servers and WL cluster, etc.

*Build the application that you wanna deploy

*Configure the database properly if you have any

*Create the WL resources like connection pool, JMS, etc manually or via WLST script

*Deploy your artifact via the WL web console or with WLST script or copy the file under the autodeploy directory

Be careful because the tasks that you executed manually will be lost if you drop your docker container.
You can find concrete examples, use cases, automated scripts that you can use and well prepared, ready for use WebLogic Docker images here: https://github.com/zappee/docker-images
If you have a concrete question, not a general one, like this, then please start a new thread.

A: Take a look at the GitHub project:
https://github.com/oracle/docker-images/tree/master/OracleWebLogic/dockerfiles


text:
Q: Random Playing Card Generator with vanilla javascript I have Five Cards for the Player and Five Cards for the Dealer
Which on click or touch it generates random card from the playing card deck.
I currently have Five different functions for a same function for each card because I have trouble making the functions into a Class that can be shared among all the cards.
This is the sample code for the function that is repeated for all the cards.
Please help me simplify my coding into One Class That can be shared for all the cards.
'''
function drawCard5() {

  var randomCard = Math.round(Math.random()* 52);
  if (randomCard === 0) {
    document.getElementById("card5").innerHTML = "A ♠";
  }

  else if (randomCard === 1) {
    document.getElementById("card5").innerHTML = "2 ♠";
  }

  else if (randomCard === 2) {
    document.getElementById("card5").innerHTML = "3 ♠";
  }

  else if (randomCard === 3) {
    document.getElementById("card5").innerHTML = "4 ♠";
  }

  else if (randomCard === 4) {
    document.getElementById("card5").innerHTML = "5 ♠";
  }

  else if (randomCard === 5) {
    document.getElementById("card5").innerHTML = "6 ♠";
  }

  else if (randomCard === 6) {
    document.getElementById("card5").innerHTML = "7 ♠";
  }

  else if (randomCard === 7) {
    document.getElementById("card5").innerHTML = "8 ♠";
  }

  else if (randomCard === 8) {
    document.getElementById("card5").innerHTML = "9 ♠";
  }

  else if (randomCard === 9) {
    document.getElementById("card5").innerHTML = "10 ♠";
  }

  else if (randomCard === 10) {
    document.getElementById("card5").innerHTML = "J ♠";
  }

  else if (randomCard === 11) {
    document.getElementById("card5").innerHTML = "Q ♠";
  }

  else if (randomCard === 12) {
    document.getElementById("card5").innerHTML = "K ♠";
  }

  else if (randomCard === 13) {
    document.getElementById("card5").innerHTML = "A ♥";
  }

  else if (randomCard === 14) {
    document.getElementById("card5").innerHTML = "2 ♥";
  }

  else if (randomCard === 15) {
    document.getElementById("card5").innerHTML = "3 ♥";
  }

  else if (randomCard === 16) {
    document.getElementById("card5").innerHTML = "4 ♥";
  }

  else if (randomCard === 17) {
    document.getElementById("card5").innerHTML = "5 ♥";
  }

  else if (randomCard === 18) {
    document.getElementById("card5").innerHTML = "6 ♥";
  }

  else if (randomCard === 19) {
    document.getElementById("card5").innerHTML = "7 ♥";
  }

  else if (randomCard === 20) {
    document.getElementById("card5").innerHTML = "8 ♥";
  }

  else if (randomCard === 21) {
    document.getElementById("card5").innerHTML = "9 ♥";
  }

  else if (randomCard === 22) {
    document.getElementById("card5").innerHTML = "10 ♥";
  }

  else if (randomCard === 23) {
    document.getElementById("card5").innerHTML = "J ♥";
  }

  else if (randomCard === 24) {
    document.getElementById("card5").innerHTML = "Q ♥";
  }

  else if (randomCard === 25) {
    document.getElementById("card5").innerHTML = "K ♥";
  }

  else if (randomCard === 26) {
    document.getElementById("card5").innerHTML = "A ♣";
  }

  else if (randomCard === 27) {
    document.getElementById("card5").innerHTML = "2 ♣";
  }

  else if (randomCard === 28) {
    document.getElementById("card5").innerHTML = "3 ♣";
  }

  else if (randomCard === 29) {
    document.getElementById("card5").innerHTML = "4 ♣";
  }

  else if (randomCard === 30) {
    document.getElementById("card5").innerHTML = "5 ♣";
  }

  else if (randomCard === 31) {
    document.getElementById("card5").innerHTML = "6 ♣";
  }

  else if (randomCard === 32) {
    document.getElementById("card5").innerHTML = "7 ♣";
  }

  else if (randomCard === 33) {
    document.getElementById("card5").innerHTML = "8 ♣";
  }

  else if (randomCard === 34) {
    document.getElementById("card5").innerHTML = "9 ♣";
  }

  else if (randomCard === 35) {
    document.getElementById("card5").innerHTML = "10 ♣";
  }

  else if (randomCard === 36) {
    document.getElementById("card5").innerHTML = "J ♣";
  }

  else if (randomCard === 37) {
    document.getElementById("card5").innerHTML = "Q ♣";
  }

  else if (randomCard === 38) {
    document.getElementById("card5").innerHTML = "K ♣";
  }

  else if (randomCard === 39) {
    document.getElementById("card5").innerHTML = "A ♦";
  }
  else if (randomCard === 40) {
    document.getElementById("card5").innerHTML = "2 ♦";
  }

  else if (randomCard === 41) {
    document.getElementById("card5").innerHTML = "3 ♦";
  }
  else if (randomCard === 42) {
    document.getElementById("card5").innerHTML = "4 ♦";
  }
  else if (randomCard === 43) {
    document.getElementById("card5").innerHTML = "5 ♦";
  }

  else if (randomCard === 44) {
    document.getElementById("card5").innerHTML = "6 ♦";
  }
  else if (randomCard === 45) {
    document.getElementById("card5").innerHTML = "7 ♦";
  }
  else if (randomCard === 46) {
    document.getElementById("card5").innerHTML = "8 ♦";
  }
  else if (randomCard === 47) {
    document.getElementById("card5").innerHTML = "9 ♦";
  }
  else if (randomCard === 48) {
    document.getElementById("card5").innerHTML = "10 ♦";
  }
  else if (randomCard === 49) {
    document.getElementById("card5").innerHTML = "J ♦";
  }
  else if (randomCard === 50) {
    document.getElementById("card5").innerHTML = "Q ♦";
  }
  else if (randomCard === 51) {
    document.getElementById("card5").innerHTML = "K ♦";
  }
  else if (randomCard === 52) {
    document.getElementById("card5").innerHTML = "JK ";
    audio2.play();
    audio3.play();
    document.getElementById("playercard").innerHTML = "Player Wins!"
    document.addEventListener("click", handler, true);
    restartGame();
  }
}

A: You can create list of card first. And then get the card by index of the list.

const createCardList = () => {
    let cardList = []
    let suits = "♠♥♣♦"
    let number = "A123456789JQK"

    for (let i=0; i<suits.length; i++) {
        for (let j=0; j<number.length; j++) {
            let card = ""
            card += suits[i] + " " + number[j]
            cardList.push(card)
        }
    }
    return cardList
}

const getCard = () => {
    let cardList = createCardList()
    let random = Math.round(Math.random() * 52);

    return cardList[random]
}

console.log(getCard())


text:
Q: Idiopathic Error C2512 I know this has been asked a million times, and I have gone through those million answers none seem to apply to my case.
I have a custom class called CFCConnections. I am trying to allocate memory to a pointer of this type here:
CFCConnections* f_pConn ;
f_pConn= new CFCConnections;

But I get the C2512 error. I have a default constructor, but it does nothing as it does not have to do anything. This was just written so that I could learn dynamic memory allocation.
The class file:
CFCConnections::CFCConnections(QObject* parent) : CResourceItem(parent)
{
    //Should I add something here? I don't want it to do anything in particular

}
CFCConnections::~CFCConnections()
{

}

All the include files are there, and the headers have been created.
I apologise in advance if this is a stupid question. I am not trying to get the community to solve my problems, I am just looking for anyone to point me in the right way.

A: SOLUTION
It was a silly oversight. The constructor was defined with a pointer as the input argument. When I tried to do f_pConn= new CFCConnections; it tried to find a constructor that took no arguments. That's why the error happened.
Changing it to f_pConn= new CFCConnections(this); fixed everything.
I hope this helps someone, that is why I did not delete the question


text:
Q: Web API : Read the image send from the app I need to read the file been send from the Ios app to the Azure web api.
I need to upload that to the blob and keep the Uri.
Can anybody suggest me the code to accept the file been send.
 /// <summary>
    ///This is to upload the image file for the user profile.
    /// </summary>
    ///<param name="userRegId"> </param>
    ///<returns></returns>
    [HttpPost]
    public Response ImageUpload(int  userRegId)
    {
        try
        {
            var response = new Response();
            if (!Request.Content.IsMimeMultipartContent())
            {
                response.status = CommonHandler.GetInvalidStatus();
            }
            else
            {

                //here i want to read the file and upload it to blob.

                string fileName =Request.Files[0].FileName;//unable to do this. Here i want to know ho to read the file
                string uniqueBlobName = string.Format("{0}/{1}", constants.pdf, fileName);
                CloudBlobClient blobStorage = cloudClasses.CreateOrGetReferenceOfBlobStorage(constants.pdf);
                CloudBlockBlob blob = cloudClasses.ClouBblockBlobPropertySetting(blobStorage, uniqueBlobName, ".pdf");
                blob.UploadFromStream(Request.Files[0].InputStream);//unable to do this.  Here i want to know ho to read the file
                response.status = CommonHandler.GetSuccessStatus();
            }
            return response;
        }
        catch (Exception ex)
        {
            _logger.LogError(Log4NetLogger.Category.Exception, "Error in : APIController.ImageUpload :>> Exception message: " + ex.Message);
            return new Response { status = CommonHandler.GetFailedStatus(ex.Message) };

        }
    }

A: Here is my code,
var streamProvider = new MultipartMemoryStreamProvider();
                Request.Content.ReadAsMultipartAsync(streamProvider);
                foreach (var content in streamProvider.Contents)
                {
                    if (content != null)
                    {
                        if (content.Headers.ContentDisposition.FileName != null)
                        {
                            var fileName =
                                content.Headers.ContentDisposition.FileName.Replace("\"", string.
                                                                                Empty);
                            Stream stream = content.ReadAsStreamAsync().Result;
                            CloudBlobContainer blobStorage = BlobHandler.GetBlobStorage("profileimage");
                            CloudBlockBlob blob = BlobHandler.BlobPropertySetting(blobStorage,
                                                                                Guid.NewGuid().ToString().ToLower() +
                                                                                fileName);
                            blob.UploadFromStream(stream);
                            response = ProfileHandler.ImageUpdate(userRegId, blob.Uri);
                        }
                    }
                }

For the blobHandler
public static CloudBlobContainer GetBlobStorage(string cloudBlobContainerName)
    {
        CloudBlobContainer container;
        try
        {
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            container = blobClient.GetContainerReference(cloudBlobContainerName); //profile
            container.CreateIfNotExist();
            var permissions = container.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            container.SetPermissions(permissions);
        }
        catch (Exception ex)
        {
            Logger.LogError(Log4NetLogger.Category.Exception, "Error in : BlobHandler.GetBlobStorage :>> Exception message: " + ex.Message);
            throw;
        }
        return container;
    }
    public static CloudBlockBlob BlobPropertySetting(CloudBlobContainer cloudBlobClientReferenceName, string blobContentName)
    {
        CloudBlockBlob blob = cloudBlobClientReferenceName.GetBlockBlobReference(blobContentName);

        //blob.Properties.ContentType = contentType;
        return blob;
    }

Hope this will help someone..

A: Yao Huang Lin wrote a blog post on how to produce a Web API file service backed by Azure blob storage. You can find it here.


text:
Q: Append lines to a file with Python3 I have the following section that I would need to append to an existing file using Python, if the section is not present there already:
Rendered file.
Sum is 3000.

The file looks like:
REQUIRES:
Enabled=False
Executables=[]

Beside the append, I would need to replace False with True and Executables=[] should turn into Executables=[.exe].
What I have been trying until now:
    with open(file, "r+") as f:
        file_content = f.read()

        if section in file_content:
            print("Section is already in file.")
        else:
            f.write(section)

        exec_to_replace = "Executables=[.exe]"
        enabled = "Enabled = True"

        if exec_to_replace not in file_content:
            to_replace = file_content.replace("Executables=[]", exec_to_replace)
            f.write(to_replace)
        else:
            print("Executable parameter already populated.")
        if enabled not in file_content:
            to_replace = file_content.replace("Enabled=False", enabled)
            f.write(to_replace )
        else:
            print("Executable already enabled.")

It looks like with the current code I get twice the section that needs to be appended. How can I do it properly?
Thank you.


text:
Q: Navigation Controller in a Tab Controller not showing back button I have a tab controller with 2 tabs "My information" and "their Information", which is just a bunch of text boxes. I want a Navigation controller at the top so I can go back, but the back button won't show up... here is my code:
Button pressed to show Form:
-(IBAction)onIncidentAidFormPressed:(id)sender {
    FormController *aidForm = [[FormController alloc] initWithNibName:@"formController" bundle:nil];
    aidForm.managedObjectContext = self.managedObjectContext;
    [self.navigationController pushViewController:aidForm animated:YES];
}

In FormController.m - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil:
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    self.title = NSLocalizedString(@"Aid Form", @"Aid Form title");
}
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIViewController *viewController1 = [[MyInformationController alloc] initWithNibName:@"MyInformationController" bundle:nil];
UIViewController *viewController2 = [[TheirInformationController alloc] initWithNibName:@"TheirInformationController" bundle:nil];
UINavigationController *navController = [[UINavigationController alloc] initWithNibName:@"navController" bundle:nil];

[navController pushViewController:viewController1 animated:YES];

self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:navController, viewController2, nil];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return self;

The tabs show up correctly, and the navigation bar is there but no back button is shown to get back.
Edit: Here are the files: IncidentAidStartViewController.h
#import <UIKit/UIKit.h>

@interface IncidentAidStartViewController : UIViewController {
    IBOutlet UIButton *incidentAidForm;
    IBOutlet UIButton *emergencyContacts;
}

-(IBAction)onIncidentAidFormPressed:(id)sender;
@property (strong, nonatomic) IncidentAidStartViewController *detailViewController;

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@end

IncidentAidStartViewController.m
#import "IncidentAidStartViewController.h"
#import "IncidentAidForm.h"
@implementation IncidentAidStartViewController

@synthesize detailViewController = _detailViewController;
@synthesize managedObjectContext = __managedObjectContext;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Incident Aid", @"Incident Aid title");
    }
    return self;
}

#pragma mark - Button handlers
-(IBAction)onIncidentAidFormPressed:(id)sender {
    IncidentAidForm *aidForm = [[IncidentAidForm alloc] initWithNibName:@"IncidentAidForm" bundle:nil];
    aidForm.managedObjectContext = self.managedObjectContext;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:nil];
    [self.navigationController pushViewController:aidForm animated:YES];

}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

IncidentAidForm.h
#import <UIKit/UIKit.h>

@interface IncidentAidForm : UIViewController <UITabBarControllerDelegate> {

}

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) UITabBarController *tabBarController;

@property (strong, nonatomic) IncidentAidForm *detailViewController;

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@end

IncidentAidForm.m
#import "IncidentAidForm.h"
#import "MyInformationController.h"
#import "TheirInformationController.h"

@implementation IncidentAidForm

@synthesize detailViewController = _detailViewController;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize window = _window;
@synthesize tabBarController = _tabBarController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Incident Aid Form", @"Incident Aid Form title");
    }
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UIViewController *viewController1 = [[MyInformationController alloc] initWithNibName:@"MyInformationController" bundle:nil];
    UIViewController *viewController2 = [[TheirInformationController alloc] initWithNibName:@"TheirInformationController" bundle:nil];
    UINavigationController *navController1 = [[UINavigationController alloc] initWithRootViewController:viewController1];
    UINavigationController *navController2 = [[UINavigationController alloc] initWithRootViewController:viewController2];

    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:navController1, navController2, nil];

    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];

    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

MyInformationController.h
#import <UIKit/UIKit.h>

@interface MyInformationController : UIViewController {

    IBOutlet UIScrollView *scrollView;
    IBOutlet UITextField *firstName;
    IBOutlet UITextField *lastName;
    IBOutlet UITextField *phoneNumber;
    IBOutlet UITextField *address;
    IBOutlet UITextField *carMake;
    IBOutlet UITextField *carModel;
    IBOutlet UITextField *carYear;
    IBOutlet UITextField *licensePlate;
    IBOutlet UITextField *insuranceCarrier;
    IBOutlet UITextField *insurancePolicy;
    IBOutlet UIButton *backgroundButton;

}

@property(nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) IBOutlet UITextField *firstName;
@property (nonatomic, retain) IBOutlet UITextField *lastName;
@property (nonatomic, retain) IBOutlet UITextField *phoneNumber;
@property (nonatomic, retain) IBOutlet UITextField *address;
@property (nonatomic, retain) IBOutlet UITextField *carMake;
@property (nonatomic, retain) IBOutlet UITextField *carModel;
@property (nonatomic, retain) IBOutlet UITextField *carYear;
@property (nonatomic, retain) IBOutlet UITextField *licensePlate;
@property (nonatomic, retain) IBOutlet UITextField *insuranceCarrier;
@property (nonatomic, retain) IBOutlet UITextField *insurancePolicy;

- (void) animateTextField: (UITextField*) textField up: (BOOL) up;
-(IBAction)hideKeyboard;
@end

MyInformationController.m
#import "MyInformationController.h"

@implementation MyInformationController

@synthesize scrollView, firstName, lastName, phoneNumber, address, carMake, carModel, carYear, licensePlate,
insuranceCarrier, insurancePolicy;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"My Information", @"My Information");
        self.tabBarItem.image = [UIImage imageNamed:@"first"];

    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;

    // Do any additional setup after loading the view, typically from a nib.
    firstName.delegate = self;
    lastName.delegate = self;
    phoneNumber.delegate = self;
    address.delegate = self;
    carMake.delegate = self;
    carModel.delegate = self;
    carYear.delegate = self;
    licensePlate.delegate = self;
    insuranceCarrier.delegate = self;
    insurancePolicy.delegate = self;

    [scrollView setContentSize:self.view.frame.size];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //[self animateTextField: textField up: YES];
    scrollView.frame = CGRectMake(0,44,320,200); //44:NavigationBar ; 200: Keyoard
    [scrollView scrollRectToVisible:textField.frame animated:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    //[self animateTextField: textField up: NO];
    if (textField.tag == 10) {
        scrollView.frame = CGRectMake(0,44,320,416); //original setup
        // [textField resignFirstResponder];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    switch (textField.tag) {
        case 1:
            [lastName becomeFirstResponder];
            break;
        case 2:
            [phoneNumber becomeFirstResponder];
            break;
        case 3:
            [address becomeFirstResponder];
            break;
        case 4:
            [carMake becomeFirstResponder];
            break;
        case 5:
            [carModel becomeFirstResponder];
            break;
        case 6:
            [carYear becomeFirstResponder];
            break;
        case 7:
            [licensePlate becomeFirstResponder];
            break;
        case 8:
            [insuranceCarrier becomeFirstResponder];
            break;
        case 9:
            [insurancePolicy becomeFirstResponder];
            break;
        case 10:
            [textField resignFirstResponder];
            break;
        default:
            break;
    }

    return TRUE;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (IBAction)hideKeyboard {
    [self.firstName resignFirstResponder];
    [self.lastName resignFirstResponder];
    [self.phoneNumber resignFirstResponder];
    [self.address resignFirstResponder];
    [self.carMake resignFirstResponder];
    [self.carModel resignFirstResponder];
    [self.carYear resignFirstResponder];
    [self.licensePlate resignFirstResponder];
    [self.insurancePolicy resignFirstResponder];
    [self.insuranceCarrier resignFirstResponder];
    scrollView.frame = CGRectMake(0,44,320,416); //original setup

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

A: So far I know this is a good way to add ur views to tabbar. So try this
UIViewController *viewController1 = [[MyInformationController alloc] initWithNibName:@"MyInformationController" bundle:nil];
UIViewController *viewController2 = [[TheirInformationController alloc] initWithNibName:@"TheirInformationController" bundle:nil];
UINavigationController *navController1 = [[UINavigationController alloc] initWithRootViewController:viewController1];
UINavigationController *navController2 = [[UINavigationController alloc] initWithRootViewController:viewController2];

self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:navController1, navController2, nil];

To add back bar item , below ine is also used.
self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;

A: Please modify your method like this
-(IBAction)onIncidentAidFormPressed:(id)sender
 {
    FormController *aidForm = [[FormController alloc] initWithNibName:@"formController" bundle:nil];
    aidForm.managedObjectContext = self.managedObjectContext;
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:nil];
    [self.navigationController pushViewController:aidForm animated:YES];

}

A: you should replace your code with the following:
UIViewController *viewController1 = [[MyInformationController alloc] initWithNibName:@"MyInformationController" bundle:nil];
UIViewController *viewController2 = [[TheirInformationController alloc] initWithNibName:@"TheirInformationController" bundle:nil];
UINavigationController *navController1 = [[[UINavigationController alloc] initWithRootViewController:viewController1] autorelease];
UINavigationController *navController2 = [[[UINavigationController alloc] initWithRootViewController:viewController2] autorelease];

self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:navController1, navController2, nil];

let me know any thing else you need........


text:
Q: How to display objects from array into HTML table enter image description hereI am working on a Shopping Cart problem and I have a table in HTML to input various objects in an Array. I want to create a "edit" button to display the specific array info back on the table.
I am working on just Visual Studio Code and Javascript. No other tools used as this is the fundamentals for my course.
So what should I code in editAdminFunc to display the objects in HTML?
Please see my code for info.

// create a flower array
var flowerArray=[];

// declare a member object
function flower(id, name, desc, price, stock, image){
    this.id = id; //id
    this.name = name; //name
    this.desc= desc; //description
    this.price = price; //price
    this.stock = stock; //quantity
    this.image = image; //image
}

function addFlower(){
    alert("addFlower function is being triggered!");
    var newFlower = new flower(
                            document.getElementById("memId").value,
                            document.getElementById("memName").value,
                            document.getElementById("memDesc").value,
                            document.getElementById("memPrice").value,
                            document.getElementById("memStock").value,
                            document.getElementById("memImage").src,
    );
  flowerArray.push(newFlower);
  console.log(flowerArray);
}

//this function is to show the flowers in list format (for admin view)
function listFlowerFunc(){
    alert("listFlowerFunc is being triggered!");

    var displayText = "
";
    displayText += "
Product ID	Name	Description	Unit Price	Stock	Image	Actions
";

    for (var i=0; i<flowerArray.length; i++){
      displayText = displayText + "
"+flowerArray[i].id+"	"+flowerArray[i].name+"	"+flowerArray[i].desc+"	"+flowerArray[i].price+"	"+flowerArray[i].stock+"	"+flowerArray[i].src+"	<button onclick =editAdminFunc()>edit</button><button onclick =deleteAdminFunc()>delete</button>
"

    }

    displayText = displayText+"
";

    document.getElementById("productlist").innerHTML = displayText;

}
//editAdminFunc
function editAdminFunc(i){
  alert("editAdminFunc() has been triggered!")
  document.getElementById("memId").value = "";  //to display array objects in the form
  document.getElementById("memName").value = "";
  document.getElementById("memDesc").value= "";
  document.getElementById("memPrice").value= "";
  document.getElementById("memStock").value= "";
  document.getElementById("memImage").src= "";
}

            <button onclick='showProductForm()'>Add Products</button> | <button id ="flowerListId" onclick="listFlowerFunc()">List Products</button>

Product ID:	<input type="text" id="memId" size="35"/>

Name:	<input type="text" id="memName" size="35"/>

Description:	<input type="text" id="memDesc" size="35"/>

Unit Price($):	<input type="text" id="memPrice" size="35"/>

Stock:	<input type="text" id="memStock" size="35"/>

Image:	<input  type="file" id="memImage"/>

&nbsp
                    <button id="clearFormBtn" onclick="clearFormFunc()">Clear</button>
                        <button id="addProdBtn" onclick="addFlower()">Add</button>
                        <button id="updateProdBtn" onclick="editHtmlTableSelected()">Update</button>

A: the right way to create an element in javascript, would be something like that

function addElement () {
  // create new "p" element
  var newP = document.createElement("p");
  // add content --  the data you want display
  var newContent = document.createTextNode("hello, how are you?");

  newP.appendChild(newContent); //add content inside the element.

  // add the element and content to DOM
  var currentDiv = document.getElementById("some");
  document.body.insertBefore(newP, currentDiv);
}
addElement();

https://developer.mozilla.org/es/docs/Web/API/Document/createElement

Now, if we adapt that information to the context of the tables, we can do it on this way to  generate the data dynamically
   arr = [
  'item 1',
  'item 2',
  'item 3',
  'item 4',
  'item 5'
         ];

function addElement () {

arr.forEach(function(el,index,array){
  let tableRef = document.getElementById('some');

  // Insert a row at the end of the table
  let newRow = tableRef.insertRow(-1);

  // Insert a cell in the row at index 0
  let newCell = newRow.insertCell(0);

  // Append a text node to the cell
  let newText = document.createTextNode(el);
  newCell.appendChild(newText);
});

}
addElement();

https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell

link to demo: Fiddle


text:
Q: Why is my form not cleared? I have made two controllers. One for adding data in the database via an API call, and a second one for sending an email. Weirdly (for now because I don't understand why) the adding functionality works fine and clears the form after the action, the second controller for sending the email doesn't clear the form and also doesn't do the console.log, it does however sends the email perfectly.
If i remove the + 'sendmail' from the emailController the form is cleared and console.log works fine also. but ofcourse the email is not send then.
I will place the pieces of codes of both controllers here. Hoping someone can help me finding out why the controller for sending the email doesnt act the way i want (and expected to).
thanks for any help.
The add review functionality
.controller('ReviewController', function ($scope, $http) {
  $scope.addReview = function () {
    $http.post(API, $scope.review)
      .success(function () {
        $scope.reviews.push($scope.review);
        $scope.review = {};
      })
      .error(function (data) {
        $scope.error = 'Posting review not successful';
        console.log(data);
      });
  };
})

the sendEmail controller
.controller('emailController', function ($scope, $http) {
  $scope.sendMail = function () {
    $http.post(API + 'sendmail', $scope.email)
      .success(function () {
        console.log('Mail send');
        $scope.email = {};
      })
      .error(function (data) {
        $scope.error = 'Posting review not successful';
        console.log(data);
        console.log('Mail not send');
      });
  };
});