text:
Q: Bind a keypress to a shell command that uses the current file in visual studio code Is there a way to create a keybinding to execute a shell command on a file?
something like:
{
    "key": "ctrl+shift+e",
    "command": "run",
    "command": "touch $file",
    "when": "editorTextFocus"
}

I don't want to use tasks as this needs to be global for the whole editor, not to a particular workspace.

A: [See my edit below - this is now much easier to do.]
I figured out a way to do what you want but it is a bit of a hack.  As you probably know it is easy to bind a task if you can create the task in .vscode/tasks.json and use something like the following:
{
  "key": "shift+escape",
  "command": "workbench.action.tasks.runTask",
  "args": "Start server and process files"
},

It is much trickier to run a script via a keybinding without a pre-existing task.  However, you can try the following which takes advantage of the       "workbench.action.terminal.runSelectedText", command.  But we need to get the script into a selection first so:
Use the macros extension (which is a little rough) so that we can tie together multiple commands.  In your user settings:
"runCommandInTerminal": [

   {
     "command": "type",
     "args": {
        "text": "node -v"
     }
  },
  {
    "command": "cursorMove",
    "args": {
       "to": "wrappedLineStart",
       "by": "wrappedLine",
       "value": 1,
       "select": true
    }
  },
  "workbench.action.terminal.runSelectedText",
  "editor.action.clipboardCutAction",
  //  "workbench.action.terminal.focus"
],

This is a general example of a setting "runCommandInTerminal" that you can then bind to any key chord you wish in keybindings.json, like
{
    "key": "ctrl+shift+e",
    "command": "macros.runCommandInTerminal"
},

Your example is a little harder because you want to access something like ${file} which you cannot do in the settings, only tasks.json and launch.json.  Fortunately, there is a command which will get the current file: "copyFilePath".  So try
"runCommandInTerminal": [

      "copyFilePath",
      {
        "command": "type",
        "args": {
          "text": "touch "
        }
      },
      "editor.action.clipboardPasteAction",
      {
      "command": "cursorMove",
        "args": {
        "to": "wrappedLineStart",
        "by": "wrappedLine",
        "value": 1,
        "select": true
        }
      },
      "workbench.action.terminal.runSelectedText",
      "editor.action.clipboardCutAction",
      // "workbench.action.terminal.focus"
],

First get the file path, then output the first part of your script command "touch".
Next append the filepath to the end of the command.
Move the cursor to select the preceding.
Run the selection in the terminal.
Cut the selection from the editor.
This can be run with your keybinding.  You will see the flash of the script being typed and cut but your editor code will be unaffected.  It is best to run it from a blank line in the editor but you can run it from the beginning of a line of unrelated code if you wish (but indentation may be lost for now).
It is hacky but seems to work.  I would love to know if there is an extension or another way to do this cleaner.

EDIT May, 2019:
Since my original answer (as @Jeff indicated) vscode has added the sendSequence command.  And the ability to use variables with that command.  So now the OP's question is much easier to accomplish:
{
  "key": "alt+x",
  "command": "workbench.action.terminal.sendSequence",
  "args": {"text": "touch ${file}"}
}

in your keybindings.json file.  See variables with a sendSequnce command.

A: with Marks answer here I could resolve my case that was run an android command with some shortcut.
After that I decided to create an guide on my GitHub, hope that helps.
GitHub: LucasMMota
Run Shell Script with Keyboard Shortcuts
In this example I set a keyboard shortcut to run android reload on my react native project.

*

*
*

*Install the macros extension to execute multiple commands.

*

*After installed go to Preferences>Settings (or cmd+,)

*

*Find Macros Configuration and use to edit in User Settings, or simply add the following in your user settings:

{
//... other configs you could have

"macros": {
    "runCommandInTerminal": [
        "editor.action.insertLineAfter", // go to new line below
        {
            "command": "type",
            "args": {
                "text": "adb shell input text \"RR\" " // exec cmd to reload android device (could be any else)
            }
        },
        // select text typed above
        {
            "command": "cursorMove",
            "args": {
                "to": "wrappedLineStart",
                "by": "wrappedLine",
                "value": 1,
                "select": true
            }
        },
        "workbench.action.terminal.runSelectedText", //run command
        "editor.action.clipboardCutAction", // remove cmd typed
        //"editor.action.deleteLines", //couldn't use. When uncommented, command doesn't work
    ],
}

}

*

*Now that we have the command set, we need to set a trigger shortcut. So go to Preferences>Keyboard Shortcuts (or cmd+k), open keybindings.json and edit like this:

{
"key": "alt+s",
"command":"macros.runCommandInTerminal"
}

*

*Save your User Settings customizations and keybindings.json, respectively

Bind file format and indenting with save shortcut
keybindings.json:
{
        "key": "cmd+s",
        "command": "macros.saveContentAndIndent",
        "when": "editorTextFocus && !editorReadonly"
    },

User Settings:
"macros": {
        "saveContentAndIndent": [
            "editor.action.formatDocument", // format
            "workbench.action.files.save", // as I used Save shorcut, I add the save bind again.
        ],
        //....
}

A: UPDATE 2:
VS Code now provides variables for integrated terminal commands. https://code.visualstudio.com/updates/v1_32#_variable-support-in-send-sequence-command
If you'd like to do more powerful tasks such as running them in the background (instead of just sending text to the current terminal) get the Command Runner or macro-commander extension
Original:
I created an extension macro-commander to solve this with a non-hacky solution. It is an improved version of the macros extension that runs the commands in order (synchronously) and lets you inject the filepath/folderpath into the command. Commands can be run in the user's VS Code terminal or a hidden background terminal.
UPDATE 1:
As of today (months later) I realized, much to my dismay, there was an existing extension that can probably do what you (and I) wanted. It is Command Runner written by edonet. If I had known about it I probably would've never made my extension.
Command Runner doesn't have as much generic possibilities (multiple commands, user input, or javascript) but it has a better UX and is probably the extension you (the reader) should try first. However, if Command Runner can't do what you're looking for, then macro-commander probably can, albeit with less elegance.
Whenever I decide to do a full update to macro-commander I'll talk with edonet and see if we can combine/add the functionality into his extension, in which case I'll update the macro-commander README to redirect to his/her extension.


text: Q: Theoretical distribution of a random variable Martin has $n$ words, and he wants to make a computer program that chooses for him $k$ words (and shows them to him), where $k \le n$, for as many times as he clicks a button until all of the words are shown at least once. Every time the words are chosen, some of them can be repeated. So, he needs to find after how many attempts all the words will be shown at least once. If the $X_{n,k}$ is the random variable that shows the number of series until all the words are shown at least once, what's the theoretical distribution of it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: грамотная проверка условия js/jquery Здравсвуйте. Подскажите как сделать грамотную проверку на наличие условия.
Есть кусочек кода который отвечает за удаление нескольких класов по тач событию.  При результате проверки ($('#popup_new_custom_kit').hasClass('popup-show')) = true
Нужно чтоб код не срабатывал, классы не удалялись
Изначальный код
function closeSelectKitTouch() {
    $(document).on('touchstart' && 'touchend', function (e) {
        var container = $(".swipe-menu");
        if (container.has(e.target).length === 0) {
            $('.wrapper ').removeClass('active-swipe-menu');
            $('#main-wrap').removeClass('active-swipe-menu');
        }
    });
}

Измененый код( так все работает как нужно)
function closeSelectKitTouch() {
    $(document).on('touchstart' && 'touchend', function (e) {
        if ($('#popup_new_custom_kit').hasClass('popup-show')) {
            // что  тут должно быть?
        }
        else {
            var container = $(".swipe-menu");
            if (container.has(e.target).length === 0) {
                $('.wrapper ').removeClass('active-swipe-menu');
                $('#main-wrap').removeClass('active-swipe-menu');
            }
        }
    });
}

Меня смущает то что у меня в действиях для if просто пусто.
Собственно в этом и вопрос можно ли так оставлять? Или что там должно быть?

A: Поставьте "!" перед условием, т.е. :
function closeSelectKitTouch() {
    $(document).on('touchstart' && 'touchend', function (e) {
        if (!$('#popup_new_custom_kit').hasClass('popup-show')) { // т.е. "если не"
            var container = $(".swipe-menu");
            if (container.has(e.target).length === 0) {
                $('.wrapper ').removeClass('active-swipe-menu');
                $('#main-wrap').removeClass('active-swipe-menu');
            }
        }
    });
}

Так же обратите внимание на конструкцию:
'touchstart' && 'touchend'

Не равна ли она true? Честно, не уверен, но есть подозрение, что это будет отрабатывать не так, как ожидается.
Несколько ивентов объявляются просто через пробел:
'touchstart touchend'


text:
Q: Reset Database in JPA Hibernate with SPRING MVC I have a requirement where i want to clear whole database tables and than move ahead.
I found below solution in hibernate with LocalSessionFactoryBean.
https://code.google.com/p/ormunit/source/browse/trunk/ormunit-hibernate/src/main/java/net/chrisrichardson/ormunit/hibernate/ResetDatabaseByRecreatingSchemaStrategy.java
But i am using JPA over Hibernate as a result i am having LocalContainerEntityManagerFactoryBean.
Can anyone guide me, how i can achieve similar solution using JPA over hibernate.
Motive is to Reset Database

A: With hibernate you could set  <property name="hbm2ddl.auto">create</property> or create-drop.
You could also use dbunit.

A: I have used

SchemaExport

to solve this issue,
LocalContainerEntityManagerFactoryBean localSessionFactoryBean = getLocalSessionFactoryBean(applicationContext);

        Configuration conf = new Ejb3Configuration().configure(
                localSessionFactoryBean.getPersistenceUnitInfo(), null)
                .getHibernateConfiguration();
        SchemaExport export = new SchemaExport(conf, localSessionFactoryBean
                .getDataSource().getConnection());
        export.create(true, true);

public LocalContainerEntityManagerFactoryBean getLocalSessionFactoryBean(
            ApplicationContext applicationContext) {

        return (LocalContainerEntityManagerFactoryBean) applicationContext
                .getBean(LocalContainerEntityManagerFactoryBean.class);
    }


text:
Q: Apple Airpods as microphone in Ubuntu 20.04 I've just acquired Apple Airpods (2nd gen) to use it as my main sound setup in Ubuntu 20.04  since I'm WFH in order to use them in Zoom meetings and so on but is not possible.
Ubuntu 20.04 is not able to detect the microphone and there's no way to use them as a microphone.
Any idea how to fix that? If they are not gonna work I'll return them since they are pretty expensive.
Thanks in advance!


text:
Q: Session State not saving value until third attempt I am currently trying to learn how to use session state but I have run into a problem that I can't figure out. What I am trying to do is have a button that when I click it, it will increase the value of my variable by 1, but my problem is that the first three times I click it my int does not increase but on the fourth click it works as intended and increases.
This is my code.
private static int Clicks = 1;

protected void Page_Load(object sender, EventArgs e)
{
    // First page load?
    if (!IsPostBack)
    {
        Session["Clicks"] = Clicks; //Clicks
    }

    Label1.Text = Convert.ToString(Session["Clicks"]);
}

protected void btnCounter_Click(object sender, EventArgs e)
{
    //UserClick.BtnClicks++;
    Session["Clicks"] = Clicks++;
}

A: You should look at the ASP.NET Page Lifecycle (see Postback Event Handling).
That btnCounter click event won't get fired until after the Page_Load event. You will probably have better results if you update the Label within your Click event.
protected void btnCounter_Click(object sender, EventArgs e)
{
    Session["Clicks"] = Clicks++;
    Label1.Text = Session["Clicks"].ToString();
}

A: Also, because you are hard setting that variable to'1', every time you click the button, it will reset to 1. You probably want to replace it with getter and setter that checks of session variable exists and, if it does, sets the value to that.


text:
Q: How to create joomla user group in joomla 2.5 I am working on my component in joomla 2.5 and i need to create user groups dynamically through my code.
As i know in 2.5 joomla is using nested sets for maintaining hierarchical structure so it may affect the whole table when we insert any new entry.
Does joomla provide any function that can be directly used to create user group ?
something in which we can specify the parent group and new group will be created under it.

A: I solved it myself
In my case i need to insert the child groups just under a particular group (mentioned as $parent_id in the code below)
// get max right from all the child under parent id
    $child_query = "SELECT max(`rgt`) FROM `#__usergroups` WHERE `id` = ".$parent_id;
$db->setQuery($child_query);
$max_rgt = $db->loadResult();

// calculate left and rgt for new entry
$new_lft = $max_rgt;
$new_rgt = $max_rgt + 1;

// update lft and rgt of all entries having lft , rgt greater than max_rgt
$upd1 = "UPDATE `#__usergroups` SET `lft` = `lft` + 2 WHERE `lft` > ".$max_rgt;
$upd2 = "UPDATE `#__usergroups` SET `rgt` = `rgt` + 2 WHERE `rgt` >= ".$max_rgt;

// insert new  child
$insert = "INSERT INTO `#__usergroups`(`parent_id`,`lft`,`rgt`,`title`) VALUES(".$matrix_parent.",".$new_lft.",".$new_rgt.",'".$title."')";

A: Even if the question is a kind of old and already accepted, I use this code to add/update/delete groups in a custom component
in order to get the required model of com_users one needs to:
JModelLegacy::addIncludePath( JPATH_ADMINISTRATOR .
                '/components/com_users/models/', 'UsersModel' );

$groupModel = JModelLegacy::getInstance( 'Group', 'UsersModel' );

before the code shown below will work.
add*/update:
$groupData = array(
    'title' => <new/old name of group here>,
    'parent_id' => <new/old id of parent group here>,
    'id' => <group id here> );

$groupModel->save( $groupData );

*if the group is newly created than the id should be 0. After the saving one can access the new id with a database query since one knows the name/title of the group
delete:
$groupModel->delete( $groupIds );

The whole code above is included in save(), delete() methods of one of my component's model.
Since Joomla stores connections between Users and Groups in a seperate Map table, no user data will be corrupted when deleting a group. Note that the delete() method takes an array of ids as argument.


text:
Q: pass object via routeActions to next route I am using react-router-redux,
Let's say I have defined url as /go-here/${routeId} and i have routeId, also data object as
 data = {
    one: 'one',
    two: 'two',
    three: 'three'
 }

using dispatch, i am routing to a new page as below,
this.props.dispatch(routeAction.push(url));

After navigating to new page, i would like to access data object, How can i do it ?

A: You can fire an action to set data in your store. Then your new page can pick up this data by simply reading this property. A good way to do this is to connect (using react-redux) your receiving component and mapStateToProps.


text:
Q: Show the following grammar is ambiguous I'm trying to identify a sentence that can produce more than one derivation tree. Also provide two different trees from the sentence
<S> = <A>
<A> = <A> + <A> | <B>
<B> = a | b | c

p.s i have a hard time figuring out the sentences

A: This looks like a problem set question, so I won't give a full answer here. However, as a hint, try showing that the string a + a + a has two different parse trees.
Hope this helps!


text:
Q: Update float array from C++ native plugin I am seeing a pretty bizarre issue while trying to pass an array from C++ to C#. I am using Marshal.Copy (specifically: https://msdn.microsoft.com/en-us/library/a53bd6cz(v=vs.110).aspx).
Problem: float array from C++ to C# is yielding a few NaN's in the resulting array.
(Note: I am working in the context of the Unity game engine)

Code
Example C++ code:
extern "C" bool UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API getSomeFloats(float** points, int* count) {
        std::vector<float> results;
        std::vector<SOME_TYPE> key_points = <SOME_POINTS>

        for (auto iter = key_points.begin(); iter < key_points.end(); iter++) {
            results.push_back(static_cast<float>(iter->pt.x));
            results.push_back(static_cast<float>(iter->pt.y));
        }

        *points = results.data();
        *count = results.size();

        //<Print results to csv here>

        return true;
}

Example C# code:
[DllImport("NativePlugin")]
private static extern bool getSomeFloats (ref IntPtr ptrResultItems, ref int resultItemsLength);

private static float[] getFloatArrayFromNative() {
        IntPtr ptrResultItems = IntPtr.Zero;
        int resultItemsLength = 0;
        bool success = getSomeFloats (ref ptrResultItems, ref resultItemsLength);
        float[] resultItems = null;
        if (success) {
            // Load the results into a managed array.
            resultItems = new float[resultItemsLength];
            Marshal.Copy (ptrResultItems
                , resultItems
                , 0
                , resultItemsLength);

            // <PRINT out resultItems to csv here>

            return resultItems;
        } else {
            Debug.Log ("Something went wrong getting some floats");
            return new float[] { -1, -2 };
        }
    }

Example Ouput:
Take the following example:
C++ output (print_out.csv):

123, 456, 789

C# output (print_out_cs.csv):

123, NaN, 789

I'm completely stumped on this one. I just don't understand why only some (roughly 7/100) floats are returning NaN. Does anyone have any advice/insight that might help?
Thanks!

A: Found few problems in your code:
1. std::vector<float> results; is declared on the stack. It will be gone by the time the function has returned.  Declare it as a pointer
std::vector<float> *results = new std::vector<float>(10);

but make sure to also declare a function that will free it on the C++ side.
2.The function parameter do not match.
Your C++:
getSomeFloats(float** points, int* count, CameraPose* pose)

Your C#:
getSomeFloats (ref IntPtr ptrResultItems, ref int resultItemsLength);

You either have to remove CameraPose* pose from the C++ side or add IntPtr pose to the C# side.
3. The use of UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API.
You don't need that. This is used when you want to use Unity's built in functions such as GL.IssuePluginEvent. You are not using it in this case.
This should do it:
#define DLLExport __declspec(dllexport)

extern "C"
{
    DLLExport void fillArrayNative(float* data, int count, int* outValue)
    {
    }
}

4.C# has a garbage collector that moves variables around in the memory. You must pin C# array if you want to modify it from C++ side. You only need to pin C# array. Another option is to allocate the array on C++ side, return it to C# copy it to a temporary variable on the C# side then delete it on the C++ side.
5.Copy the result back to the array instead of assigning it.

Recommended method:
There are just many ways to do this and some of them are extremely slow. If you want to use Marshal.Copy, you have to allocate the array on the C++ side or else you will run into some undefined behavior.
The fastest and the most efficient way to do this is to allocate the array on the C# side as a global variable. Pass the array and its length to the native side. Also pass a third parameter which C++ can use to tell C# the amount of index that has been updated or written to.
This is much more better than creating new array, copying it to C# variable then destroying it each time the function is called.
This is what you should be using:
C++:
#define DLLExport __declspec(dllexport)

extern "C"
{
    DLLExport void fillArrayNative(float* data, int count, int* outValue)
    {
        std::vector<float> results;
        for (int i = 0; i < count; i++)
        {
            //Fill the array
            data[i] = results[i];
        }
        *outValue = results.size();
    }
}

You can also use:  std::copy ( data, data+count, results.begin() ); instead of loop to copy the data too.
C#:
[DllImport("NativePlugin", CallingConvention = CallingConvention.Cdecl)]
private static extern void fillArrayNative(IntPtr data, int count, out int outValue);

public unsafe void getFillArrayNative(float[] outArray, int count, out int outValue)
{
    //Pin Memory
    fixed (float* p = outArray)
    {
        fillArrayNative((IntPtr)p, count, out outValue);
    }
}

Usage:
const int arraySize = 44500;
float[] arrayToFill = new float[arraySize];

void Start()
{
    int length = arrayToFill.Length;
    int filledAmount = 0;
    getFillArrayNative(arrayToFill, length, out filledAmount);

    //You can then loop through it with with the returned filledAmount
    for (int i = 0; i < filledAmount; i++)
    {
        //Do something with arrayToFill[i]
    }
}

This is just an example and it is faster than all other methods I've used before. Avoid doing it the way you are currently doing it with Marshal.Copy. If you still want to do it your way or use Marshal.Copy then here is the appropriate way to do it which requires allocation, copying data and de-allocating memory in each call.

A: The pointer you return in getSomeFloats is owned by results.  Before getSomeFloats returns, the vector destructor for results will free that memory.  When the C# code tries to use the pointer, you are accessing unallocated memory, which results in Undefined Behavior.  In your case most of the data hasn't been changed yet, but some of it has.  Potentially any or all of the data could have been changed (if the memory has been reused), or even a program crash (if the freed memory has been returned to the OS).


text: Q: Question about gzip compression and compress effectiveness I'm using RSA encryption between a WebSocket server and a WebSocket client. This is fine from small messages with just small amounts of info. The problem I'm running into is there's one part of my program that needs a very large message, like 1 MB in size, to be sent to the server. this means I cannot Encrypt the whole message using RSA encryption. As there's a max number of bytes that can be encrypted with the public key. So I'm opting into splitting the message into chunks and sending multiple messages and remaking the message on the other size. This requires me to chuck the message. So I'm wondering if its move effective to base64 the message before gzipping it. or should I base64 it after? As gzipping gives me a byte array, meaning I have to encode it anyway. Which path provides better performance?


text:
Q: How do I organize formulas to work with columns in google sheets Hi so I'm trying to make a spreadsheet in Google Sheets that takes two numbers and subtracts them and then does it in the next row .
So example the formula in C1 would be "subtract(A1, B1)" in the first row. But then in the next row I would like it to change to "subtract(A2, B2)" and output in C2.
(Without having to go in each C cell and change the formula of course)
So how do I do that and also how do I apply a formula to multiple cells of a row (C1,C2,C3,C4,C5, etc....)

A: Just put =MINUS(A1,B1) into C1 and then copy it and paste it in the remain rows of column C and the  spreadsheet automatically adjusts the row numbers for you.

A: @Cooper's Answer above is perfect. I'm just giving a alternative here using array formulas, because it's easy.
Put this in D2
              =ARRAYFORMULA(MINUS ( B2:B, MULTIPLY( 2.5, QUOTIENT(C2:C,15))))


text:
Q: Oracle Database docker linux VM - Laptop connection I have an Oracle database running in a Linux VM. The way i started the docker is using the following command
sudo docker run -d --name my_db --net oac_net -p 1521:1521 -P --shm-size=4G bi.docker.oraclecorp.com/database/enterprise:12.1.0.2

This is running inside a Linux VM.
[oracle@07f1d37f71c9 /]$ hostname -i
172.18.0.2

I would like to connect to this database docker from my laptop. The TNS entry in my laptop is like the following
odidocker =   (DESCRIPTION =     (ADDRESS = (PROTOCOL = TCP)(HOST = 172.18.0.2)(PORT = 1521))
(CONNECT_DATA =       (SERVER = DEDICATED)       (SERVICE_NAME = ORCL.localdomain)     )   )
PDBORCL=
(DESCRIPTION =
  (ADDRESS = (PROTOCOL = TCP)(HOST = 172.18.0.2)(PORT = 1521))
  (CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = pdborcl.localdomain)
  ))

Trying to connect using the following command
sqlplus system/welcome1@odidocker

the error we are getting is the following
ORA-12154: TNS:could not resolve the connect identifier specified

What is the mistake i am making. Could someone please help.
Thanks
Bala


text:
Q: How to run docker container with bash shell? It works with ubuntu image
wolf@linux:~$ docker run -it ubuntu /bin/bash
root@00e6296d31d8:/#

However, when I try it with different image such as vulnerables/web-dvwa, it doesn't work anymore
wolf@linux:~$ docker run -it vulnerables/web-dvwa /bin/bash
[+] Starting mysql...
[ ok ] Starting MariaDB database server: mysqld.
[+] Starting apache
[....] Starting Apache httpd web server: apache2AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
. ok
==> /var/log/apache2/access.log <==

==> /var/log/apache2/error.log <==
[Sat Apr 03 11:54:24.321232 2021] [mpm_prefork:notice] [pid 307] AH00163: Apache/2.4.25 (Debian) configured -- resuming normal operations
[Sat Apr 03 11:54:24.321280 2021] [core:notice] [pid 307] AH00094: Command line: '/usr/sbin/apache2'

==> /var/log/apache2/other_vhosts_access.log <==

id
whoami

There is no bash shell in this container
wolf@linux:~$ docker ps
CONTAINER ID   IMAGE                  COMMAND                CREATED          STATUS          PORTS     NAMES
820d3a292b2c   vulnerables/web-dvwa   "/main.sh /bin/bash"   11 seconds ago   Up 11 seconds   80/tcp    upbeat_visvesvaraya
wolf@linux:~$

A: You can attach to the container with:
 docker exec -ti 820d3a292b2c bash

or:
 docker exec -ti upbeat_visvesvaraya bash

A: That image you are trying to run i.e. vulnerables/web-dvwa contains ENTRYPOINT ["/main.sh"] which runs mysqld on startup. If you need a just a shell in that image you can override the main entry like so below ...
docker run -it --rm --entrypoint /bin/bash vulnerables/web-dvwa

OR if you want a shell on the running mysqld container, you can run it normally w/ out -it argument and then do the following to get a bash shell in the running container.
docker exec -it <container_id> /bin/bash


text:
Q: Can the calculus of variations be used to optimize to a constraint that the desired function must pass through specific intermediate points? I am wondering about this. As one may know, the "calculus of variations" is a method to solve optimization problems in which the desired object to be optimized is a function, and the optimized quantity is some functional (a function that associates a number to other functions). The most basic type of problem is one in which the function in question is suitably smooth and of the form
$$f : [a, b] \rightarrow \mathbb{R}$$
and we seek the minimization of a functional $F$ typically given by an integral:
$$F[f] = \int_{a}^{b} L\left(f(t), f'(t), f''(t), \cdots, f^{(n)}(t)\right) dt$$
subject to the constraint that the endpoint values $f(a) = f_a$ and $f(b) = f_b$ are given. Through the methods of the calculus, one can convert such a problem into a differential-equations problem - the Euler-Lagrange equations.
However, what happens if we don't necessarily want the most minimal solution, but instead want to "peg" the function at one or more intermediate points in the domain interval? That is, we want to add one or more additional constraints
$$\begin{align}f(t_1) &= f_1\\
f(t_2) &= f_2\\
&\cdots\\
f(t_N) &= f_N\end{align}$$
where $a < t_1 < t_2 < \cdots < t_N < b$. Given this, can and, if so, how can, we modify the usual Euler-Lagrange method to solve it? As a simple example (and related to what I'm trying to do with this), suppose we set the domain interval as $[a, b] := [0, 2]$, and want to minimize
$$F[f] := \int_{0}^{2} [f''(t)]^2\ dt$$
subject to the three constraints
$$f(0) = 1,\ f(1) = 2,\ f(2) = 4$$
. Note that this function will not be the absolute minimum of the functional, or even that with the two endpoints alone fixed (such functions will be linear, and the points $(0, 1)$, $(1, 2)$ and $(2, 4)$ clearly do not lie along a straight line!), as in the usual kind of problems. Rather it is a minimum that only comes about by virtue of the additional constraint. How do we do it?
The simplest thought that I had would be to just try to think about it as two minimizations on $[0, 1]$ and $[1, 2]$, seeking two functions $f_{[0, 1]}$ and $f_{[1, 2]}$ so that
$$f(x) = \begin{cases} f_{[0, 1]}(x)\ \mbox{if $x \in [0, 1]$}\\
f_{[1, 2]}(x)\ \mbox{if $x \in [1, 2]$} \end{cases}$$
and $f_{[0, 1]}(1) = f_{[1, 2]}(1) = 2$ and trying to minimize the "sub"-functionals of the original with the expected changes of bounds on the defining integral. However, that will clearly not be guaranteed to minimize the original functional, because we can get a "corner" at $x = 1$, and it will fail to be differentiable there and so we can't even compute the original functional, much less minimize it under these constraints with that solution. What, then, do you need to avoid this?

A: To get a well-defined variational problem with Euler–Lagrange equations for a functional involving the second derivative, you need boundary values for the first derivative (see Wikipedia). For a single interval, if you don't have any, you can treat them as free variables and minimize the value of the functional with respect to them.
In your case, the Euler–Lagrange equation is $f^{(4)}=0$, which is solved by all cubic polynomials. By minimizing the functional with respect to the derivatives at the boundary, you get the linear functions that you assumed to be the only solution.
For your two intervals with an intermediate point, you can minimize the function with respect to the first derivatives at all three points, but that no longer leads to a linear function because, as you note, that's not possible.
The calculation is easiest if you write $f(x)$ in each interval as the linear function connecting the endpoints of the interval plus a linear combination of cubic polynomials that are zero at the endpoints and have derivative $1$ at one endpoint and $0$ at the other. The result is a cubic Hermite spline. If we denote the linear functions between the endpoints by $l_1$ and $l_2$, then on the first interval we have
\begin{eqnarray}
f(x)&=&l_1(x)+c_0x(x-1)^2+c_1(x-1)x^2\;,\\
f''(x)&=&c_0(6x-4)+c_1(6x-2)\;,
\end{eqnarray}
with coefficients $c_0$, $c_1$ to be determined. It's convenient to use $y=x-1$ on the second interval; then on the second interval we have
\begin{eqnarray}
f(y)&=&l_2(y)+c_2y(y-1)^2+c_3(y-1)y^2\;,\\
f''(y)&=&c_2(6y-4)+c_3(6y-2)\;.
\end{eqnarray}
The condition for the continuity of the first derivative at the intermediate point is
$$
f(1)-f(0)+c_1=f(2)-f(1)+c_2\;,\tag1\label{constraint}
$$
with the differences of function values coming from the linear functions and the coefficients coming from the Hermite interpolation polynomials corresponding to the intermediate point.
The value of the functional is
$$
\int_0^2(f''(x))^2\mathrm dx=4(c_0^2+c_0c_1+c_1^2+c_2^2+c_2c_3+c_3^2)\;.
$$
Minimizing it with respect to the coefficients under the constraint \eqref{constraint} yields the equations
\begin{eqnarray}
2c_0+c_1&=&0\;,\\
c_0+2c_1&=&\lambda\;,\\
2c_2+c_3&=&-\lambda\;,\\
c_2+2c_3&=&0\;.
\end{eqnarray}
Solving the first and last equation and substituting into the second and third yields
$$
\pmatrix{c_0\\c_1\\c_2\\c_3}=\frac\lambda3\pmatrix{-1\\2\\-2\\1}\;.
$$
Then the constraint \eqref{constraint} yields
$$
\lambda=\frac34(f(2)-2f(1)+f(0))=\frac34\;,
$$
and thus
$$
\pmatrix{c_0\\c_1\\c_2\\c_3}=\frac14\pmatrix{-1\\2\\-2\\1}\;.
$$
So the minimizing function is
\begin{eqnarray}
f(x)
&=&
1+x-\frac14x(x-1)^2+\frac12(x-1)x^2
\\
&=&
\frac14\left(x^3+3x+4\right)
\end{eqnarray}
on the first interval and
\begin{eqnarray}
f(y)
&=&
2+2y-\frac12y(y-1)^2+\frac14(y-1)y^2
\\
&=&
\frac14\left(-y^3-3y^2-6y-8\right)
\end{eqnarray}
on the second interval. Here's a plot.

A: First of all we shall define the "family" of functions that you are considering.
That could be polynomials,  trigonometric polynomials, etc.
or even a wider class of functions.
Trigonometric polynomials could be interesting, because in the example you give of minimizing
$\int_{0}^{2} [f''(t)]^2\ dt$, the Parseval's theorem could simplify the computations.
However, if the points are not equally spaced, trigonometric polynomial are not easy to apply.
In general, given the values that the function has to take at $n$ points $t_1,t_2, \cdots, t_n$,
as a first step we can determine the $n-1$ degree (or lower) polynomial $p_{n-1}(t)$ passing through those points
by, e.g. a Lagrange interpolation.
That polynomial will be the "simplest" analytic function passing through the given points.
Then the polynomial
$$
q_{\,n} (t) = \left( {t - t_{\,1} } \right)\left( {t - t_{\,2} } \right) \cdots \left( {t - t_{\,n} } \right)
$$
is a polynomial that has zeros in the given points.
Therefore if we put the function to be
$$
f(t) = p_{\,n - 1} (t) + q_{\,n} (t)g(t)
$$
where $g(t)$ is any function within the class of choice, and in particular analytic. We can optimize with respect to that without
other particular restraints.
If we want to remain within the polynomials class, then we can choose to add some additional points $t_{n+1}, t_{n+2}, \cdots, t_{n+m}$,
internal to range of the previous $n$ and or external, at which additional points
we leave unspecified (variable parameters) the value of $f(t)$ . We then  construct a Lagrange polynomial $p_{n+m-1}(t)$
which takes on the wanted values on the $n$ points, and the unspecifed parametric values on the other $m$ points, and which will be those subject to optimization.
That premised, we come to the example you give.
You want to minimize the square of the second derivative
$$
I(f) = \int_0^2 {f''(t)^{\,2} dt} \quad \left| {\;f(0) = 1,\;\;f(1) = 2,\;\;f(2) = 4} \right.
$$
a) No doubt that the widest general solution is given by a pair of straight lines, with a flat $I=0$
$$
\eqalign{
  & f(x) =   \cr
  &  = \left( {1 + x} \right)\left[ {x < 1} \right] + \left( {2x} \right)\left[ {1 \le x} \right] =   \cr
  &  = \left( {1 + x} \right) + \left( {x - 1} \right)\left[ {1 \le x} \right] =   \cr
  &  = \left( {1 + x} \right) + \left( {x - 1} \right)H(x - 1) =   \cr
  &  = 2 + \left( {{3 \over 2} + {1 \over 2}{\mathop{\rm sgn}} (x - 1)} \right)\left( {x - 1} \right) \cr}
$$
where
 - $[P]$ denotes the Iverson bracket;
 - $H(x)$ is the Heaviside's step function ($H(0)=1$);
 - $sgn(x)$ is the sign function.
b) the rounded piecewise solution given by @Joriki has an $I=1.5$
c) We could make the function in a) above continuous, by converting the sign function
into one of its continuous approximations, for instance
$$
{\mathop{\rm sgn}} (x) \approx {x \over {\sqrt {x^{\,2}  + \varepsilon ^{\,2} } }} + \left( {1 - {1 \over {\sqrt {1 + \varepsilon ^{\,2} } }}} \right)x
$$
where the second term is to reconduct $sign(\pm 1)$ to exactly $\pm 1$ as
to keep that function is passing through the assigned points.
The corresponding integral has a minimum for $\varepsilon \approx 0.817 $
giving $I \approx 1.514$.
d) If we want to remain within the polynomial ring then as in the premise let's put
$$
\left\{ \matrix{
  p_{\,2} (x) = \left( {x^{\,2}  + x + 2} \right)/2 \hfill \cr
  q_{\,3} (x) = x\left( {x - 1} \right)\left( {x - 2} \right) \hfill \cr}  \right.
$$
Putting $g(x) \equiv 0$ we are going to have
$$
f(x) = p_{\,2} (x)\quad  \Rightarrow \quad f''(x) = 1\quad  \Rightarrow \quad I = 2
$$
Putting instead $g(x)$ to be a first degree polynomial and minimizing we get
$$
g(x) =  - {5 \over {42}}\left( {x - 1} \right)\quad  \Rightarrow \quad I = 32/21 \approx 1.52
$$
while putting it to be a 3rd degree we get
$$
g(x) = {7 \over {170}}\left( {x - 3} \right)\left( {x - 1} \right)\left( {x + 1} \right)\quad  \Rightarrow \quad I = 128/85 \approx 1.506
$$


text:
Q: Input stack size=5000 error when using \include I am "including" a .tex file. I get the error "TeX capacity exceeded, sorry [input stack size=5000].@nomath ...e@font@warning etc."
The error is located by latex in the line that says

\pic[current plane, draw,fill=orange!50,fill opacity=.5, text
opacity=1,"\footnotesize $\phi$", angle
eccentricity=2.2]{angle=ketplus--origin--psiProjectedEquat}; %je
nachdem, ob der Psi Pfeil links oder rechts von der z-Achse ist, muss
man die Reihenfolge bei "angle=" umkehren   }

I should point out that the file that is "included" works when compiled on its own (where the preamble isn't in the masterfile but in the file itself. It seems that the \usepackage[ngerman]{babel} in the masterfile causes the problem.
MWE:
"file.tex":
\documentclass{article}
\usepackage[ngerman]{babel}

\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{tikz}
\usetikzlibrary{positioning,arrows,calc,math,angles,quotes}
\usepackage{blochsphere}
\usepackage{braket}
\usetikzlibrary{arrows.meta}

\begin{document}
\include{file1}
\end{document}

"file1.tex":
\def\rotationSphere{-10} %Drehung im Uhrzeigersinn aus der Standardposition "x-Achse aus Bildebene heraus, y-Achse nach rechts"; 89.9 statt 90 (sonst Division von 0 durch 0)
\def\tiltSphere{10} %0.01 statt 0 da bei 0 Fehler bei der im Paket hinterlegten Rechnung mit Sinus/Cosinus kommen
\def\radiusSphere{2cm}
\def\psiTheta{70} %Winkel Theta
\def\psiPhi{65} %Winkel Phi

 %Farbeinstellung als Hinweis für sämtliche color= Befehle
  %draw={rgb,255:red,199; green,199; blue,199}

\begin{blochsphere}
[ball=none,radius=\radiusSphere,opacity=1,rotation=\rotationSphere,tilt=\tiltSphere,color=white]

\newcommand\drawLatitudeCircleNew[2][]{
\begingroup
\pgfmathsetmacro\yshift{sin(#2)*\blochsphere@radius}
\pgfmathsetmacro\radius{\blochsphere@radius*cos(#2)}
\drawCircleNew[#1,shift={{0,0,\yshift}},radius=\radius]{0}{0}
\endgroup
}%

\newcommand\drawLongitudeCircleNew[2][]{
\begingroup
\drawCircleNew[#1]{90}{#2+90}
\endgroup
}

\newcommand\drawCircleNew[3][]{
\begingroup
%\setkeys{blochsphere}{#1}
\setDrawingPlane{#2}{#3}
\computeVisibility{#2}{#3}{agamma}{abeta}
\begingroup\edef\tmp{\endgroup%
\noexpand\draw[opacity=0.2,line width=0.8,current plane,on layer=front,\unexpanded\expandafter{\blochsphere@style}] \unexpanded\expandafter{(\agamma-\abeta-0.2:\blochsphere@radius+\the\pgflinewidth*0.5) arc (\agamma-\abeta-0.2:\agamma+\abeta+0.2:\blochsphere@radius+\the\pgflinewidth*0.5)};
\noexpand\draw[current plane,opacity=0.5,line width=0.8,on layer=front,\unexpanded\expandafter{\blochsphere@style}] \unexpanded\expandafter{(\agamma+\abeta:\blochsphere@radius+\the\pgflinewidth*0.5) arc (\agamma+\abeta:\agamma-\abeta+360:\blochsphere@radius+\the\pgflinewidth*0.5)};
} \tmp
\endgroup
}%hier Dicke, Form und Farbe von Longitude/Latitude Circle einstellen

\pgfdeclareradialshading[tikz@ball]{ball}{\pgfqpoint{-10bp}{10bp}}{
color(0bp)=(tikz@ball!90!white);
color(9bp)=(tikz@ball!90!white);
color(18bp)=(tikz@ball!90!white);
color(25bp)=(tikz@ball!90!black);
color(50bp)=(black)
}
\drawBall[ball=3d,radius=\radiusSphere,opacity=1,rotation=\rotationSphere,tilt=\tiltSphere,color=white]

      %\drawBallGrid[style={opacity=.3}]{30}{30}
  %Vertikale Ebene (als Kreis) zeichnen
  %\drawLongitudeCircle[]{\rotationSphere}
  \drawLongitudeCircleNew[style={opacity=0.3,line width=0.8}]{-90-0} %Schreibe bei Befehle, die Latitude und Longitude verwenden immer {90-phiTheta} und {-90-phi)}
  %Horizontale Ebene (als Kreis) zeichnen
  \drawLatitudeCircleNew[style={opacity=0.3,line width=0.8}]{90-90} %style={dashed} falls Linie gestrichelt haben will

  %Punkte auf der Kugel definieren (für Achsen)
  \labelLatLon[radius=\radiusSphere*1.3]{ket0}{90-0}{-90-0}; %Schreibe bei LatLon Befehl immer {90-phiTheta} und {-90-phi)} wegen Definition von LabelLatLon
  \labelLatLon[radius=\radiusSphere]{ket1}{90-180}{-90-0};

  \labelLatLon[radius=\radiusSphere]{ketminus}{90-90}{-90-0+180};
  \labelLatLon[radius=\radiusSphere*2.2]{ketplus}{90-90}{-90-0};

  \labelLatLon[radius=\radiusSphere*1.25]{ketpluspi2}{90-90}{-90-90};
  \labelLatLon[radius=\radiusSphere]{ketplus3pi2}{90-90}{-90-90+180};
  \labelLatLon{psi}{90-\psiTheta}{-90-\psiPhi};

  %Achen zeichnen und markieren
  %z-Achse
  \draw[-latex,opacity=0.5,line width=0.8] (0,0,0) -- (ket0) node[below right,inner sep=.5mm,opacity=0.5] at (ket0) {\footnotesize $z$};
  %Bemerkung: 0,0,0 karthesische Koordinaten; ket0 in 2D Koordinaten auf der Kugeloberfläche
  %gepunkteter Teil der z-Achse
   \draw[-latex,opacity=0.3,line width=0.8,-] (0,0,0) -- (ketplus3pi2) node[below right,inner sep=.5mm,opacity=0.5] at (ketplus3pi2) {};
   %usw.
   \draw[-latex,opacity=0.3,line width=0.8,-] (0,0,0) -- (ket1) node[below right,inner sep=.5mm,opacity=0.5] at (ket1) {};
   \draw[-latex,opacity=0.3,line width=0.8,-] (0,0,0) -- (ketminus) node[below right,inner sep=.5mm,opacity=0.5] at (ket1) {};
  \draw[-latex,opacity=0.5,line width=0.8] (0,0,0) -- (ketplus) node[above left,inner sep=.5mm,opacity=0.5] at (ketplus) {\footnotesize$x$};
  \draw[-latex,opacity=0.5,line width=0.8] (0,0,0) -- (ketpluspi2) node[below left,inner sep=0.5mm,opacity=0.5] at (ketpluspi2) {\footnotesize $y$};
  %|psi> zeichnen
  \draw[-latex,color=orange,line width=2] (0,0,0) -- (psi) node[above]{\footnotesize $\ket{\psi}$};
  \def\phitest{65}
     \labelLatLon{test}{90-90}{-90-65};
  \draw[-latex,color=orange,line width=2] (0,0,0) -- (test) node[above]{\footnotesize $\ket{test}$};
  %Winkel zeichnen
  \coordinate (origin) at (0,0,0);
  {
     %Projektion zeichnen - cosinus verwendet
    \setDrawingPlane{0}{0}
    \draw[current plane,dashed] (0,0,0) -- (180+\psiPhi:{cos(90-\psiTheta)*\radiusSphere}) coordinate (psiProjectedEquat) -- (psi); %Winkel:Länge Polarkoordinaten
    %Winkel schattieren (phi)
    \pic[current plane, draw,fill=orange!50,fill opacity=.5, text opacity=1,"\footnotesize $\phi$", angle eccentricity=2.2]{angle=ketplus--origin--psiProjectedEquat}; %je nachdem, ob der Psi Pfeil links oder rechts von der z-Achse ist, muss man die Reihenfolge bei "angle=" umkehren
  }
  { \setLongitudinalDrawingPlane{-90-\psiPhi}
    %Winkel schattieren (theta)
    \pic[current plane, draw,fill=orange!50,fill opacity=.5, text opacity=1,"\footnotesize $\theta$", angle eccentricity=1.5]{angle=ket0--origin--psi}; %je nachdem, ob der Psi Pfeil links oder rechts von der z-Achse ist, muss man die Reihenfolge bei "angle=" umkehren
  }
\end{blochsphere}

A: As you've noticed, the combination of your tikz picture and babel causes the problem. You can fix this by loading the babel tikz library:
\documentclass{article}
\usepackage[ngerman]{babel}

\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{tikz}
\usetikzlibrary{positioning,arrows,calc,math,angles,quotes}
\usepackage{blochsphere}
\usepackage{braket}
\usetikzlibrary{arrows.meta,babel}

\begin{document}
\include{file1}
\end{document}


text:
Q: Does the .git folder update on each pull I have an application that doesn't have any client side cache invalidation yet.
We need a quick solution for a temporary measure until we devise a fuller solution.
The prod server tracks the master branch.
Is it safe to assume the .git folder will update its last modified time-stamp upon every git pull?
If so a quick solution would be to set the last modified timestamp of the .git folder to be the js and css cache key... ie
<script src="<?= asset('build/js/main.js') ?>?v=<? echo $timestamp; ?>"></script>

A: You can assume that but i would not count on that.
A better way is to use the fetch command
git fetch --all --prune

Which will update the .git/FETCH_HEAD file stamp and you can use this instead.


text:
Q: Insert Dynamic Section Headers in UITableView I have a UITableView in which i want to add the section headers dynamically as the user clicks add button. The user should also be able to delete the headers if they dont need it. Under each header the user should be able to add relevant list of items. And apart from that the user should be able to insert rows dynamically under selected section only. Please suggest some ideas to achieve this functionality. Thanks in advance.

A: You can achieve this by removing and then adding that section again, this will cause a call to tableView:titleForHeaderInSection:
Assume your section index is 0:
BOOL shouldShowHeader;
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    shouldShowHeader ? @"Your Header" : nil;
}

- (IBAction)buttonAction:(id)sender
{
    shouldShowHeader = !shouldShowHeader;
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
    [self.tableView beginUpdates];
    [self.tableView deleteSections:set withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView insertSections:set withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
}

Footer works the same way.

A: I will tell for dynamic section header. Keep a flag and set to 0 initially. When User clickes on button in that buttonClick method set flag to 1 and reload tableView.
          -(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
          {
                  if(flag)
                       return aView;//alloc init aView and return.
                  else
                       return nil.
          }

Similarly for dynamic rows have a array and numberOfRows be array.count.
On click of button insert one more item in array and reload Table.
I hope this help.

A: When user clicks on button in this method set a flag and reload your tableview and then do it..
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(flag)
    {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,320, 30)];
        return headerView;
    }
    else
        return nil;
}

and you can delete header in table view like this......
If you want to remove the table's header view, just set the myTable.tableHeaderView property to nil. If what you have is actually a section header, then you need to return nil from the viewForHeaderInSection method and call [myTableView reloadData]
and i hope this will work fine.


text:
Q: calling a rest endpoint in a springboot application which is better alternative for calling REST endpoint in springboot application, calling REST endpoints using WebClient or calling REST endpoints using RestTemplate ?

A: Spring's documentation recommends using WebClient, but that's only a valid recommendation for reactive apps. If you aren't writing a reactive app, use OpenFeign instead. Like anything else in software, it fits well for some cases, but might complicate things for others. Choosing WebClient to implement the REST endpoint calls is strongly coupled to making your app reactive

A: RestTemplate gives many advantages if you are using it from within Springboot application, i.e. in your server side to another part of your own app - sort of like an internal call. Because the RestTemplate "knows" all your entities and beans and so if you need to send over or receive an object which is known within your springboot application RestTemplate can map them automatically which is a very nice advantage. If you sending a request to some third party api and do not pass or receive your known entities RestTemplate is still a valid option but it just becomes just another Http client. Its just simply there as part of Springboot provided tools. But in this case you may use any other client as well.


text:
Q: How can I let the keyboard pop up automatically I would like the keyboard to be shown without the user touch the username text field.
I found the code from How to open the keyboard automatically on UITextField?
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    textField.becomeFirstResponder()
}

So I tried this
@IBOutlet var userNameTF: UITextField!

@IBOutlet var passwordTF: UITextField!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    userNameTF.becomeFirstResponder()

}

but it gives an error
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

A: Double check your outlets are connected if you are using the storyboard, and then try this:
1) Place your userNameTF.becomeFirstResponder in viewDidLoad() instead of viewDidAppear().
2) Convert
@IBOutlet var userNameTF: UITextField!
@IBOutlet var passwordTF: UITextField!

to:
@IBOutlet weak var userNameTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!

A: I think problem is with IBOutlets
@IBOutlet var userNameTF: UITextField!

1) You are using a strong reference here which will cause you issue later that even after the presented View with these TF is removed memory will not be released as reference to property are strong
2) Try using @IBOutlet weak var usernameTF: UITextField! and when you make changes remove the connected outlet from storyBoard and reconnect it with Written outlet and build
Crash - Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
occurs in two case -
1) This is occurring as you are trying to access a property which is not properly connected

2) When you are Presenting the same presented view In hierarchy

Try using Solutions mentioned and let me know if issue still exists
import UIKit

class TFVC: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var usernameTF: UITextField!
    @IBOutlet weak var passowrdTF: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        usernameTF.delegate = self
        passowrdTF.delegate = self

    }

    override func viewDidAppear(_ animated: Bool) {
        usernameTF.becomeFirstResponder()
    }


text:
Q: AbstractController::DoubleRenderError in Home#index I am getting the following error message. I have researched other posts but in my case there is no other render partial being called so I am unsure as to why I am getting this error...
Showing /home/ubuntu/workspace/app/views/home/index.html.erb where
line #11 raised:

Render and/or redirect were called multiple times in this action.
Please note that you may only call render OR redirect, and at most
once per action. Also note that neither redirect nor render terminate
execution of the action, so if you want to exit an action after
redirecting, you need to do something like "redirect_to(...) and
return".

Extracted source (around line #7):
      image_tag(user.avatar, class: 'avatar-circle')
     else
      render partial: 'shared/avatar', locals: { user: user }
     end
   end
 end

Here is my code:
app/controllers/home_controller.rb
class HomeController < ApplicationController
  include UsersHelper
  helper_method :show_avatar

  def index
    @posts = Post.all
  end
end

app/controllers/concerns/users_helper.rb
module UsersHelper

  def show_avatar(user)
    if user.avatar?
      image_tag(user.avatar, class: 'avatar-circle')
    else
      render partial: 'shared/avatar', locals: { user: user }
    end
  end
end

app/views/home/index.html.erb
<% @posts.each do |post| %>

      <%= image_tag post.picture.url %>

        <%= show_avatar(post.user) %>

<%= post.user.full_name %> - <%= post.description %>

Button Button

<% end %>

The only thing I can think is that the partial is being called within the loop for each post, but surely this can't be the issue?

A: You can't render html in a helper method, you have to build it.
def show_avatar(user)
  if user.avatar?
    image_tag(user.avatar, class: 'avatar-circle')
  else
    render partial: 'shared/avatar', locals: { user: user }
  end
end

Try change the code in else statement to something similar to template shared/avatar:
content_tag(:div, 'something', class: 'whatever')

Or you can move the logic to shared/avatar to handle when user.avatar?


text:
Q: R add totals to columns? I have a dataframe like this:
a b
1 4
2 5
3 6

I want to add a column totals like this:
      a b
      1 4
      2 5
      3 6
Total 6 15

I am trying to play with dplyr::summarise but without luck. Please advise.

A: Using the builtin data frame BOD try this:
addmargins(as.matrix(BOD), 1)

giving:
    Time demand
       1    8.3
       2   10.3
       3   19.0
       4   16.0
       5   15.6
       7   19.8
Sum   22   89.0

It could also be written like this (or use library(magrittr) in place of library(dplyr) since there is nothing from dplyr used here except what is imported from magrittr).
library(dplyr)

BOD %>%
    as.matrix %>%
    addmargins(1)


text:
Q: How to change Ubercart status messages in Drupal? my client asked me to replace "cart" in status messages (e.g. "Item added to your shopping cart.") with the word "bag". However, I found out that all these messages are hardcoded in Ubercart module. What's the best way to change them?
Thanks.

A: This module https://drupal.org/project/messages_alter provides Drupal hook for altering status messages. This hook enables developers to alter the text that is displayed in status messages before the messages are themed.


text:
Q: What is OpenCMIS Bridge? I just noticed this project at Apache OpenCMIS:
https://svn.apache.org/repos/asf/chemistry/opencmis/trunk/chemistry-opencmis-bridge
There is no description, no documentation, and reading the code does not give many hints about what it is supposed to do.
Apache OpenCMIS sometimes releases great software silently, with little communication, so we might be missing another great piece of software here.
A Google Search for "OpenCMIS Bridge" returns only source code and the bare download page.

A: The OpenCMIS Bridge works like a proxy server. It accepts CMIS requests and forwards them to a CMIS server. On the way it can change the binding, and filter, enrich and federate data.
Here are few use cases:

*

*If a repository does not support the CMIS 1.1 browser binding, you can put the OpenCMIS Bridge in front of it. The bridge then could talk JSON to the client and AtomPub to the server. The client wouldn't notice that the server doesn't support the browser binding.

*Code can be added to the bridge to redact property values or filter whole objects when they are transferred through the bridge. That could add another level of security that the native repository doesn't support.

*Code can also be added to add or enrich object data. For example, property values could be translated from cryptic codes into readable values. Virtual secondary types can be added on the fly. Or additional renditions could be provided.

*The bridge can also be used to provide different views of multiple repositories. Repositories of different vendors can be access through one unified endpoint. It's possible to build one virtual repository across multiple backend repositories that then, for example, allows a federated query across all backends.

The OpenCMIS Bridge is only a framework, though. It just provides the infrastructure and the hooks to add your own code and rules.
If you are looking for a real world application, check SAP Document Center (formerly "SAP Mobile Documents"). It is based on the OpenCMIS Bridge.


text:
Q: Artifact from CodeBuild cannot be deployed with CodeDeploy With CodeBuild I compile my SpringBoot application and put the resulting jar in a folder called deploy/. In my buildspec.yml at the end I provide:
artifacts:
   files:
    - deploy/*

When I plug this in to CodePipeline, this creates a zip file in S3. But the problem is, that this zip file contains the root folder, i.e. deploy. So the structure of the zip file is:
deploy.zip
  - deploy/
     - appspec.yml
     - app.jar
     - ...

This leads to the problem that CodeDeploy cannot find the appspec.yml, becuase it's not looking inside the deploy folder. I've been trying to overcome this providing a zip file as artifact at the end of the build process, but then in the pipeline it just gets zipped again..
Any idea how to solve this would be much appreciated.

A: There is a new flag you can add in the artifacts section called base-directory to specify a base path for your artifacts package. This will allow you to truncate the deploy/ path out of your artifacts without losing the rest of the structure underneath.
artifacts:
  files:
    - **/*
  base-directory: deploy

http://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html

A: You can add discard-paths: yes
artifacts:
  files:
    - deploy/*
  discard-paths: yes

Keep in mind that it discards ALL paths, including sub-directories
Source: http://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html


text:
Q: Print same text several time to one page I have a odt(or pdf, or ps) file. [Really I have odt, but I can easily convert it], it consist of 1 page.
No I want to print it to another pdf 4 times to 1 page. There is an option pages per side, so If I copy-paste 4 times my document and set this option to 4 I'll have my expected result.
But I want to do it without copy-paste because it's quite annoying to copy-and-paste before each printing.
Is it simpler way?

A: You can use the tool ConTeXt. Either you install it with your package manager (eg. from TeXLive) or on a per-user base: Installation
Then you create a file fourup.tex with the following content:
\setuppapersize     [A6] [A4]
\setuppagenumbering [location=]
\setupbackgrounds   [page]
\setuplayout        [nx=2, ny=2]

\starttext
\doifdocumentargumentelse{inputfile}{%
  \copypages [\getdocumentargument{inputfile}] [scale=500]}{Missing input file}
\stoptext

Then you can call ConTeXt: context --inputfile=myfile --result=result.pdf fourup.
myfile is the original file without PDF extension. The result is a file result.pdf with four pages copied on one.


text:
Q: How do I assign a value inside list comprehension I write a small program using comprehension list python and I need to assign a value to dictionary.
It gives me syntax error.
all_freq = {}
Input = 'google.com'
[all_freq[s] += 1 if s in Input  else  all_freq[s] = 1 for s in Input]

It says "[" was not closed.
Could you please help me.

A: Use a normal for loop, not a list comprehension, as you are not trying to create a list of anything.
all_freq = {}
for s in Input:
    if s in all_freq:
        all_freq[s] += 1
    else:
        all_freq[s] = 1

which can be simplified slightly to
all_freq = {}
for s in Input:
    if s not in all_freq:
        all_freq[s] = 0
    all_freq[s] += 1

which can be replaced entirely with
from collections import Counter
all_freq = Counter(Input)

A: Just inspired by earlier post, you can also do this way:
Of course, Counter is the best to do quick tallying.

from collections import defaultdict

all_freq = defaultdict(int)        # initialize the dict to take 0, if key is not existing yet

for s in 'google':                 # each for-loop, just increment the *count* for corresponding letter
    all_freq[s] += 1

print(all_freq)
defaultdict(<class 'int'>, {'g': 2, 'o': 2, 'l': 1, 'e': 1})


text:
Q: Angular NGRX split large array to chunks and combine API requests results So the problem is that I have a large array of objects, let's say a 1000 that I need to send to our API in NGRX Effect and then dispatch a new Action with the response, but API takes too long to process such a large requests at once, so I want to divide this array into smaller chunks, send a request with each of them one after another and then combine responses from all of them into a single action. I've tried it with mapping this large array of data into an array of Observables with from() operator, but couldn't figure out what to use next after it was mapped, I've tried casting it to Promises and use Promise.all() on them but again, no luck. In summary what I need to do is this:

*

*Action triggers an Effect that needs to send API call with an array of data from Action,

*In the Effect, array of data gets divided into chunks of 100 objects,

*These chunks are mapped into API requests, sent one after another, and the response from each needs to be combined with previous ones,

*After all of these requests are done, an Action with the combined response from them needs to be dispatched to update Store.

Here is a simplified Effect that I'm using currently and what I need to divide is action.rows:
loadRows$ = createEffect(() => {
  return this.actions$.pipe(
    ofType(RowsActions.LoadRows),
    switchMap((action) => {
      return this.eventsService.getBatchRows(action.rows).pipe(
        switchMap((response) => {
          return [
            new RowsLoaded({ rows: response.rows }),
            new LoadedTableData(response.rows),
          ];
        }),
        catchError(() => {
          return of(new RowsFailedToLoad());
        })
      );
    })
  );
});

A: have implemented similiar logic,
if one chunk will have 100 items - it still to big number.
I am running ALL items paralelly.
UPD:
if you will change mergeMap to concatMap - all calls will be sequential
it does not matter if it is single row or chunk of rows
        from(action.rows)
            .pipe(
                mergeMap(id => api(id).pipe(catchError(e => EMPTY))),
                toArray())
             )

here is working example: https://codesandbox.io/s/rxjs-playground-forked-u8c7jd?file=/src/index.js
FINAL VERSION:
const { of, from } = require("rxjs");
const {
  switchMap,
  concatMap,
  toArray,
  catchError,
  map,
  tap
} = require("rxjs/operators");

const chunkArray = (arr, size) =>
  arr.length > size
    ? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
    : [arr];
const getBatchRows = (rows) => of({ response: { rows } });

of({ rows: ["id1", "id2", "id3", "id4", "id5"] })
  .pipe(
    switchMap((action) =>
      from(chunkArray(action.rows, 2))
        .pipe(
          concatMap((rows) =>
            getBatchRows(rows).pipe(catchError((e) => of({})))
          )
        )
        .pipe(toArray())
    ),

    tap((data) => console.log(data)),
    map((responseArray) => responseArray.map((i) => i.response.rows).flat()),
    map(rows => [
      new RowsLoaded({ rows }),
      new LoadedTableData(rows),
    ])
  )
  .subscribe((data) => {
    console.log(data);
  });

to use chunk way - almost nothing to do
will use
const chunkArray = (arr, size) =>
  arr.length > size
    ? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
    : [arr];

and use here:
 from(chunkArray(action.rows, 100))

//and change this
 mergeMap(rows => this.eventsService.getBatchRows(rows)


text:
Q: How to refer to HTML input by C#? I've got this C# written in a .cshtml document:
@int[,] grid = new int[81];

for (int i = 0; i < 9; i++)
{
   for (int j = 0; j < 9; j++)
   {
      <input type="text" maxlength="1"/>
   }
}
<button>OK</button>

It creates a 2-dimensional array 'grid' and 81 empty html input boxes, everyone of which should be filled by the user with a single digit. When the 'OK' button is clicked the 'grid' should get the values from every input element (e.g. grid[0] = '1st input's value', grid[1] = '2nd input's value'... etc.), but I don't know how to reffer to every input element in order to get its value, because each is automatically generated by nested for-loops, therefore I can not give it a unique id or name. Any ideas?

A: I'm not sure if you can pass 2-dimensional array, but you can do that with 1-dimensional.
Let's say you have an action Grid in Home controller which accepts array of int:
public ActionResult Grid(int[] grid)
{
    // do something with grid
}

In your view you should generate names for inputs:
@using (Html.BeginForm("Grid", "Home", FormMethod.Post))
{
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 9; j++)
        {
            <input type="text" maxlength="1" name="grid[@(i*9 + j)]"/>
        }
    }
    <button>OK</button>
}

After submitting this form you will have grid parameter filled with values from the form.

A: Using view models to represent what you editing will give you 2-way binding and the ability to add client and server side validation
View Models
public class Column
{
    [Range(1, 9, ErrorMessage = "Please enter a value between 1 and 9")]
    public int Value { get; set; }
}

public class Row
{
    public Row()
    {
        Columns = Enumerable.Repeat(new Column(), 9).ToList();
    }
    public List<Column> Columns { get; set; }
}

public class Grid
{
    public  Grid()
    {
        Rows = Enumerable.Repeat(new Row(), 9).ToList();
    }
    public List<Row> Rows { get; set; }
}

Controller
public ActionResult Edit()
{
    Grid model = new Grid();
    return View(model);
}

[HttpPost]
public ActionResult Edit(Grid model)
{
    // Get the value of the 3rd column in the 5th row
    int value = model.Rows[2].Columns[4];
}

View
@model ContractWeb.Controllers.Grid
@using(Html.BeginForm())
{
    for(int i = 0; i < Model.Rows.Count; i++)
    {
        <div>
            @for(int j = 0; j < Model.Rows[i].Columns.Count; j++)
            {
                @Html.TextBoxFor(m => m.Rows[i].Columns[j].Value)
                @Html.ValidationMessageFor(m => m.Rows[i].Columns[j].Value)
            }
        </div>
    }
    <input type="submit" />
}

Note: Assumes input is styled as inline-block. You will also want to consider the placement of the validation errors so their display does not screw up the grid layout (perhaps in a separate (nested) loop so they are outside the grid?)


text:
Q: Single touch to move and double finger touch to resize Image view I want to single touch listener to move object (Image View rect) and double finger to resize image
Try:
rect.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            ViewGroup.LayoutParams lp = rect.getLayoutParams();
            float lasty = 0f;
            float lastx = 0f;
            final float distheight = event.getRawY() - lasty;
            final float distwidth = event.getRawX() - lastx;

            Log.d("MotionTouch:", "finger: " + event.getPointerCount());

            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    Log.d("MotionTouch:","ACTION_DOWN");
                    dx = v.getX() - event.getRawX();
                    dy = v.getY() - event.getRawY();
                    lastAction = MotionEvent.ACTION_DOWN;
                    break;

                case MotionEvent.ACTION_MOVE:
                    Log.d("MotionTouch:","ACTION_MOVE");
                    v.animate().x(event.getRawX() + dx).y(event.getRawY() + dy).setDuration(0).start();
                    break;

                case MotionEvent.ACTION_POINTER_DOWN:

                    Log.d("MotionTouch:","ACTION_POINTER_DOWN");
                    lp.height -= distheight;
                    lp.width -= distwidth;
                    rect.setLayoutParams(lp);
                    break;

                case MotionEvent.ACTION_POINTER_UP:
                    Log.d("MotionTouch:","ACTION_POINTER_UP");
                    lp.height += distheight;
                    lp.width += distwidth;
                    rect.setLayoutParams(lp);
                    break;

                default:

                    return true;
            }

           /* v.invalidate();
            v.requestLayout();*/
            return true;
        }
    });

It works but when two finger touches(MotionEvent.ACTION_POINTER_DOWN case run then hide) then it hide Image View (rect)
why it hide touch object(ImageView rect)
rect is rectangle image view.


text:
Q: Plotly: Add traces using a loop I just learn Plotly and I am trying to make my python code better. This is my dataframe:

To visualize, this is my code but I think it could be done with For loop:
fig = go.Figure()

fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,0], mode ='lines', name = 'Australian Capital Territory'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,1], mode ='lines', name = 'New South Wales'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,2], mode ='lines', name = 'Northern Territory'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,3], mode ='lines', name = 'Queensland'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,4], mode ='lines', name = 'South Australia'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,5], mode ='lines', name = 'Tasmania'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,6], mode ='lines', name = 'Victoria'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,7], mode ='lines', name = 'Western Australia'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,8], mode ='lines', name = 'New Zealand'))

annotations = []

annotations.append(dict(xref='paper', yref='paper', x=0.0, y=1.05,
                              xanchor='left', yanchor='bottom',
                              text="Covid 19 Death Cases between Australian' states vs New Zealand",
                              font=dict(family='Arial',
                                        size=18,
                                        color='rgb(37,37,37)'),
                              showarrow=False))

fig.update_layout(legend=dict(y=0.5, traceorder='reversed', font_size=16),
                  plot_bgcolor='white',
                  annotations=annotations,
                  xaxis_title="Date",
                  yaxis_title="Number of Death"
                 )

fig.show()

I am trying to use For loop for this part:
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,0], mode ='lines', name = 'Australian Capital Territory'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,1], mode ='lines', name = 'New South Wales'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,2], mode ='lines', name = 'Northern Territory'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,3], mode ='lines', name = 'Queensland'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,4], mode ='lines', name = 'South Australia'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,5], mode ='lines', name = 'Tasmania'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,6], mode ='lines', name = 'Victoria'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,7], mode ='lines', name = 'Western Australia'))
fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,8], mode ='lines', name = 'New Zealand'))

Any thought on how to use For loop for this, will be much appreciated.
This is an example from Plotly:
import plotly.graph_objects as go
import numpy as np

title = 'Main Source for News'
labels = ['Television', 'Newspaper', 'Internet', 'Radio']
colors = ['rgb(67,67,67)', 'rgb(115,115,115)', 'rgb(49,130,189)', 'rgb(189,189,189)']

mode_size = [8, 8, 12, 8]
line_size = [2, 2, 4, 2]

x_data = np.vstack((np.arange(2001, 2014),)*4)

y_data = np.array([
    [74, 82, 80, 74, 73, 72, 74, 70, 70, 66, 66, 69],
    [45, 42, 50, 46, 36, 36, 34, 35, 32, 31, 31, 28],
    [13, 14, 20, 24, 20, 24, 24, 40, 35, 41, 43, 50],
    [18, 21, 18, 21, 16, 14, 13, 18, 17, 16, 19, 23],
])

fig = go.Figure()

for i in range(0, 4):
    fig.add_trace(go.Scatter(x=x_data[i], y=y_data[i], mode='lines',
        name=labels[i],
        line=dict(color=colors[i], width=line_size[i]),
        connectgaps=True,
    ))

    # endpoints
    fig.add_trace(go.Scatter(
        x=[x_data[i][0], x_data[i][-1]],
        y=[y_data[i][0], y_data[i][-1]],
        mode='markers',
        marker=dict(color=colors[i], size=mode_size[i])
    ))

fig.update_layout(
    xaxis=dict(
        showline=True,
        showgrid=False,
        showticklabels=True,
        linecolor='rgb(204, 204, 204)',
        linewidth=2,
        ticks='outside',
        tickfont=dict(
            family='Arial',
            size=12,
            color='rgb(82, 82, 82)',
        ),
    ),
    yaxis=dict(
        showgrid=False,
        zeroline=False,
        showline=False,
        showticklabels=False,
    ),
    autosize=False,
    margin=dict(
        autoexpand=False,
        l=100,
        r=20,
        t=110,
    ),
    showlegend=False,
    plot_bgcolor='white'
)

annotations = []

# Adding labels
for y_trace, label, color in zip(y_data, labels, colors):
    # labeling the left_side of the plot
    annotations.append(dict(xref='paper', x=0.05, y=y_trace[0],
                                  xanchor='right', yanchor='middle',
                                  text=label + ' {}%'.format(y_trace[0]),
                                  font=dict(family='Arial',
                                            size=16),
                                  showarrow=False))
    # labeling the right_side of the plot
    annotations.append(dict(xref='paper', x=0.95, y=y_trace[11],
                                  xanchor='left', yanchor='middle',
                                  text='{}%'.format(y_trace[11]),
                                  font=dict(family='Arial',
                                            size=16),
                                  showarrow=False))
# Title
annotations.append(dict(xref='paper', yref='paper', x=0.0, y=1.05,
                              xanchor='left', yanchor='bottom',
                              text='Main Source for News',
                              font=dict(family='Arial',
                                        size=30,
                                        color='rgb(37,37,37)'),
                              showarrow=False))
# Source
annotations.append(dict(xref='paper', yref='paper', x=0.5, y=-0.1,
                              xanchor='center', yanchor='top',
                              text='Source: PewResearch Center & ' +
                                   'Storytelling with data',
                              font=dict(family='Arial',
                                        size=12,
                                        color='rgb(150,150,150)'),
                              showarrow=False))

fig.update_layout(annotations=annotations)

fig.show()

A: Here is the line you're after to create all traces in a for loop:
for idx, col in enumerate(anz_d_df.columns, 0):
    fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,idx], mode ='lines', name = col))

Explanation:
This loop uses the enumerate function which takes an iterable (in this case, list of column names) and returns a tuple of (index, string).  For example:
(0, 'Australian Capital Territory')
(1, 'New South Wales')
...
(8, 'New Zealand')

Then, these values are passed into each add_trace() call.
Context Code:
Below is the code used to create a dataset to replicate yours (albeit, a zero DataFrame), as well as the loop to create the traces.
# Build dataset
cols = ['Australian Capital Territory',
        'New South Wales',
        'Northern Territory',
        'Queensland',
        'South Australia',
        'Tasmania',
        'Victoria',
        'Western Australia',
        'New Zealand']
index = pd.date_range(start='2020-01-22', periods=10)

# Create working DataFrame.
anz_d_df = pd.DataFrame(0,columns=cols, index=index)

# Add all traces.
for idx, col in enumerate(anz_d_df.columns, 0):
    fig.add_trace(go.Scatter(x = anz_d_df.index , y = anz_d_df.iloc[:,idx], mode ='lines', name = col))

Hope this helps!


text:
Q: If $G=\bigoplus_i\Bbb Z/p_i^{n_i}\Bbb Z$, then for which integers $r\neq\pm 1$ is $G=Gr$? Let $G=\bigoplus_i\Bbb Z/p_i^{n_i}\Bbb Z$ be a finite Abelian group with $p$ prime, $n,i$ integers.  For a fixed $r\in \Bbb Z$, let $f_r$ be a multiplication endomorphism on $G$ for which $f_r(g)=gr$ for all $g\in G$.
Question: Describe any possible elements $r\in \Bbb Z, r\neq \pm1$ for which $f_r$ is surjective on $G$.  In other words, for which integers $r$ is $Gr=G$?
My attempt:  Since any $r$ with a prime factorisation involving any of the $p_i^{n_i}$ will collapse some of the components the $\Bbb Z/p_i^{n_i}$, we avoid $r=\prod_ip_i^{n_i}$.
So we may stick with any  $r$ different from all elements whose prime factorisation is $\prod_i p_i^{n_i}$.   Hence for any $r\neq\prod_ip_i^{n_i}, f_r$ is a surjection of $G$.
My question is that, is that enough?  Is there any other better way of identifying such integers?


text:
Q: Uniformization theorem: Equivalence between simply connected Riemann surfaces and closed Riemannian 2-manifolds? Recently, I read a proof of the uniformization theorem using the Ricci flow on closed Riemannian 2-manifolds. It is implied by some sources that this is equivalent to the uniformization theorem for simply connected Riemann surfaces for example Wikipedia says:
"The uniformization theorem also has an equivalent statement in terms of closed Riemannian 2-manifolds: each such manifold has a conformally equivalent Riemannian metric with constant curvature."
I am unable to see why this is true. Could someone please direct me to a proof?
Remark:
I did find an earlier question that addresses part of this issue, but didn't get the answer I was looking for:
Uniformization of metrics vs. uniformization of Riemann surfaces

A: One cannot trust Wikipedia too much on these matters: Anybody can edit a Wikipedia article. The Wikipedia article is sloppy about distinguishing compact and noncompact surfaces. The Uniformization Theorem has the following equivalent forms:
A. Every simply-connected Riemann surface is biholomorphic to $S^2$ or to ${\mathbb C}$ or to the unit disk $\Delta$ in ${\mathbb C}$.
B. Every connected Riemann surface $X$ is biholomorphic either to $S^2= {\mathbb C}P^1$ (with its standard complex structure), or to the quotient  of $U={\mathbb C}$ or of $U=\Delta$ by a group $\Gamma$ of linear-fractional transformations of $U$ acting on $U$ freely and properly discontinuously.
C. Every connected Riemannian surface $(S,g)$ admits a positive smooth function $\lambda$ such that $(S, \lambda g)$ is a complete Riemannian manifold of constant curvature. (Note that the surface $S$ is not required to be oriented.)
Remark. i. In all three formulations, the surface $S$ is not required to be compact. The compactness assumption made by the Wikipedia article is totally unnecessary. Compactness is used in some of the proofs but not in other proofs.
ii. There is no way to prove the UT for general noncompact surfaces from the UT for compact surfaces.
Equivalence of the three statements (A, B and C) is not hard to establish. The key facts are the existence of a conformal Riemannian metric on every Riemann surface and that every group $\Gamma$ as in Part B, acts on $U$ isometrically with respect to the Euclidean or hyperbolic metric respectively.
Regarding the Ricci flow, what is true is that there is a proof of the Uniformization Theorem (UT) for compact (closed) Riemann surfaces via the Ricci Flow (RF). This result by itself does not imply the full UT.
In order to prove the UT for noncompact surfaces using RF one would have to work much harder than in the compact case and I am unaware of such a proof in the literature. Even short-term existence of the flow becomes a problem. See for instance
Xiaorui Zhu, Ricci Flow on Open Surface, J. Math. Sci. Univ. Tokyo 20 (2013), 435–444.
for some partial results on proving UT via RF on open surfaces.
Of course, if your (say, simply connected) Riemann surface is compact, then RF indeed does the job: First equip your surface $X$ with an arbitrary conformal Riemannian metric $g_0$ (i.e. a metric which in the local holomorphic coordinates of $X$ has the form $\rho_k(z)|dz|^2$). For a proof of existence of such a metric see my answer here.
Then apply the normalized RF to $g_0$. This, in finite time, converges to a constant curvature metric $g_T$ (the curvature has to be positive). For surfaces, RF preserves the conformal class of the metric. Hence, $g_T$ is still a conformal Riemannian metric on $X$. After rescaling, $g_T$ has curvature $1$. Now, use the theorem (due to Killing and Hopf in all dimensions) that all compact simply-connected surfaces of curvature $1$ are isometric to each other. Hence, $(X,g_T)$ is isometric to the standard unit sphere $S^2$. The isometry $f: X\to S^2$ has to be conformal in the sense of Riemannian geometry, hence (after changing orientation if needed) is conformal in the sense of complex analysis. qed


text:
Q: How do I change the WPF Expander Header Text when expanded or collapsed? Using a WPF expander, I want the Header to change from See More to See Less when the control is expanded, and back to See More when it's collapsed again.
I'd prefer a WPF pure solution, rather than a C# or other code behind method.
I get the feeling this should be easy, but I'm struggling for the right terms to get a solution via google.
Thanks!

A: Old (I know), but this can be done with using two simple Trigger without binding:
<Expander>
    <Expander.Style>
        <Style TargetType="Expander" >
            <Style.Triggers>
                <Trigger Property="IsExpanded" Value="True">
                    <Setter Property="Header" Value="See Less" />
                </Trigger>
                <Trigger Property="IsExpanded" Value="False">
                    <Setter Property="Header" Value="See More" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Expander.Style>
</Expander>

A: You could probably do this in a style trigger:
<Expander>
    <Expander.Style>
        <Style TargetType="Expander">
            <Setter Property="IsExpanded" Value="False" />
            <Setter Property="Header" Value="See More" />

            <Style.Triggers>
                <DataTrigger Binding="{Binding IsExpanded,RelativeSource={RelativeSource Self}}" Value="True">
                    <Setter Property="Header" Value="See Less" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Expander.Style>
</Expander>

That's untested, but it should give you something to go on.


text:
Q: Carrier Privileges not provided to the app I am working on an application that is supposed to gain Carrier Privileges . We have an eSIM card, that already has a SHA-1 and fingerprint of a keystore used to sign application written to it, but the application not able to get the privileges.
Is there anything the application suppose to call in order to get the access?
I have the Service that extends CarrierService running, but it seems to not call onLoadConfig method at all.

A: I believe the documentation here is incorrect.  It says to use:
<service android:name=".SampleCarrierConfigService"
android:label="@string/service_name"
android:permission="android.permission.BIND_CARRIER_SERVICES">
      <intent-filter>
      <action android:name="android.service.carrier.ConfigService"/></intent-filter>
</service>

but I think you need to use <action android:name="android.service.carrier.CarrierService"/> instead.
At least when we use the documented version, our onLoadConfig isn't called, and when we use android.service.carrier.ConfigService we do get the callback.
One other thing you can do is call something like this in your application (just in a regular activity, not in the service):
    val telephonyManager =
        context?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    val haspriv = telephonyManager.hasCarrierPrivileges()
    Log.d(TAG, "priv: $haspriv")

If telephonyManager.hasCarrierPrivileges() returns true, you know the signature checking is correct.  This has nothing to do with the service; you can have an application that has carrier privileges without implementing android.service.carrier.ConfigService.  (I don't know why you'd do that, but it's possible.)


text:
Q: Jenkins is unable to built project using maven I have Configured SVN-Jenkins-Maven-Tomcat for a project. Every thing is working fine with small projects. But when I tried to build my actual project which contains lots of jars and packages.. it shows error.. xxx package not found. I have manually added dependency jars to local maven repository.
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>optaplanner</groupId>
      <artifactId>optaplanner</artifactId>
      <version>1.0-SNAPSHOT</version>
        <packaging>jar</packaging>
          <dependencies>
         <dependency>
          <groupId>annotation.code</groupId>
          <artifactId>annotations</artifactId>
          <version>2.0.1</version>
        </dependency>

        <dependency>
          <groupId>antlr-runtime.code</groupId>
          <artifactId>antlr-runtime</artifactId>
          <version>3.5</version>
        </dependency>

        .....
        .....

      </dependencies>
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
              <source>1.7</source>
              <target>1.7</target>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>

Error:

/C:/Users/ANIRBAND/.jenkins/jobs/Test/workspace/src/main/java/org/optaplanner/examples/common/swingui/SolutionPanel.java:[25,48]
  package org.optaplanner.core.api.domain.solution does not exist
  /C:/Users/ANIRBAND/.jenkins/jobs/Test/workspace/src/main/java/org/optaplanner/examples/common/swingui/SolutionPanel.java:[72,29]
  cannot find symbol
  /C:/Users/ANIRBAND/.jenkins/jobs/Test/workspace/src/main/java/org/optaplanner/examples/common/swingui/ConstraintMatchesDialog.java:[45,17]
  package org.slf4j does not exist

Can you help me in resolving the same?

A: Given the error message I'd think you didn't add slf4j as a dependency into your project maybe?
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.12</version>
</dependency>

Could you please post full pom.xml and error messages?

A: First thing to is to add SLF4j in your project, to do that add SLF4j API:
<properties>
<slf4jVersion>1.7.12</slf4jVersion>
</properties>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4jVersion}</version>
</dependency>

Next choose a binding library; from one of the following:
1).  Binding for NOP, silently discarding all logging.
 <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-nop</artifactId>
    <version>${slf4jVersion}</version>
 </dependency>

2).  Binding for System.out
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>${slf4jVersion}</version>
</dependency>

3). Binding for log4j version 1.2.x. Also need to place log4j.jar on your class path.
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4jVersion}</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
    <scope>runtime</scope>
</dependency>

4). Binding for commons logging over slf4j.
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>jcl-over-slf4j</artifactId>
   <version>${slf4jVersion}</version>
   <scope>runtime</scope>
</dependency>


text:
Q: voice sound during boot and at login ubuntu 22.04 new install - a voice (at first sounds German) speaks then my login appears, then an english voice reads the screen and makes sounds as I login with my password. How do I disable the voice?
The sound under accessibility screen reader is off.
Johnf

A: In my case after a fresh install of Ubuntu 22.04 I started hearing a voice at boot up.  Of course that annoyed me.  Oh I'm sure it is helpful for someone with impaired vision.  But I didn't like it.
The fix is simple when you see the login screen there is a sound icon (upper right) just turn off the sound.  It did not effect any sound settings I have after login.
Johnf


text:
Q: text from a file turned into a variable? If I made a program that stores strings on a text file using the "list"-function(#include ), and then I want to copy all of the text from that file and call it something(so I can tell the program to type in all of the text I copied somewhere by using that one variable to refer to the text), do I use a string,double,int or what do I declare that chunk of text as?
I'm making the program using c++ in a simple console application.
Easier explanation for PoweRoy:
I have a text in a .txt file,I want to copy everything in it and then all this that I just copied, I want to call it "int text" or "string text" or whatever.But I don't know which one of those "int","string","double" etc. to use.

A: To take some pity on you, this is about the simplest C++ program that reads a file into memory and then does something with it:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;

int main() {

    ifstream  input( "foo.txt" );
    if ( ! input.is_open() ) {
        cerr << "could not open input file" << endl;
        return 1;
    }

    vector <string> lines;
    string line;
    while( getline( input, line ) ) {
        lines.push_back( line );
    }

    for ( unsigned int i = 0; i < lines.size(); i++ ) {
        cout << (i+1) << ": " << lines[i] << "\n";
    }
}

A: Broadly speaking, you are talking about the concept of Serialization - storing variable values in permanent storage like a file so you can reload them later.  Have a look at that link to broaden your understanding.
Specifically, it sounds like you have arbitrary text in a file and want to refer to it in your program.  In that case, string sounds appropriate.  Unless the text in the file is intended to represent one single number, that seems most appropriate.
Note that if you have structured data (like a CSV file or XML file), a more complex data structure (e.g. a class, array of classes, etc) might be a better choice.

A: #include <iostream>
#include <fstream>
#include <string>

int main() {
   // Open stream from file
   std::ifstream ifs("foo.txt");

   // Get file contents
   std::string file_contents(
      (std::istreambuf_iterator<char>(ifs)),
      std::istreambuf_iterator<char>()
   );

   // Output string to terminal to see that it works
   std::cout << file_contents;
}


text:
Q: Unable to use the map function on an array of objects TypeError: this.state.users.map is not a function
I've rewritten this a few times, following a tutorial, but I keep getting the same error. It's pointing to the  tag inside divMapper, but i'm not sure what It's trying to tell me
here's the App component:
import React, { Component } from 'react'
import User from './Components/User'

class App extends Component {
    state = {
        users: [
            {name: 'user1', id: '001'},
            {name: 'user2', id: '002'},
            {name: 'user3', id: '003'},
        ]
    }

    nameChangeHandler = (event, id) => {
        const userIndex = this.state.users.findIndex(userName => {
            return userName.id === id
        })

        const user = {...this.state.users[userIndex]}
        user.name = event.target.value
        const userList = {...this.state.users}
        userList[userIndex] = user

        this.setState({
            users: userList
        })
    }
    render() {
        let divMapper = (

                {this.state.users.map(person => {
                    return <User
                                name={person.name}
                                id={person.id}
                                changed={event => this.nameChangeHandler(event, person.id)}
                            />
                })}

        )

        return (

                {divMapper}

        )
    }
}

export default App

and here's the User component:
import React from 'react'

function User(props) {
    return (

            <input
                type="text"
                placeholder="type here..."
                onChange={props.changed}
            />

{props.name}

    )
}

export default User

TypeError: this.state.users.map is not a function
I've rewritten this a few times, following a tutorial, but I keep getting the same error.
It's pointing to the  tag inside divMapper, not sure what It's trying to tell me


text:
Q: Problem with installation of LaTeXDraw! I was using LaTexDraw 2, which I had got it form Ubuntu Software Center. As the functions were limited and I couldn't use math to label out, I searched and found this new 3.1 version.
After downloading it. I followed the manual and ran the installer using the script provided.It showed that it installed peacefully in /opt.
Launching directly from terminal worked, using superuser.
Problems.

*

*Not able to launch the app as a normal user.
It shows this error.
$ latexdraw
$ Error: Unable to access jarfile /root/Desktop/latexdraw/LaTeXDraw.jar

*The .jar file has is in the root folder, for some reason!!?? It should have been in the /opt folder. I have tried changing the ownership, but in no use.

*Then there is the problem with the .desktop file. It doesn't do anything. No shortcuts or launches. Do I need to modify this file? And where do I need to put it?
So any help how to make this app run in normal mode (without superuser) and launching it directly with the command latexdraw from the terminal?

A: *

*Download the version 3.3.1 from here.

*Extract the archive in your download folder with
unzip LaTeXDraw-3.3.1-bin.zip

*Start the installer without sudo
LaTeXDraw-3.3.1/install_debian_ubuntu

*Use /opt as target folder

*Start Latexdraw via the Dash


text:
Q: Battle pass quest disconnect Does a victory count for a battle pass quest when the game is safe to leave for connection issues ?
Seems like every time I get a decent team someone on the other team leave at start .

A: No, it does not count. It's the same behavior as it is with the win itself.


text:
Q: How to pass server/domain credentials when accessing SSRS report through SSRS Web service programmatically? I am trying to render SSRS Report located on my remote report server in my ASP.NET MVC 4 app through reporting services web service programmatically.
how can i send the server (windows/domain credentials) at runtime?
tried below but no success.
ReportingService2010 service = new ReportingService();
service.Credentials = new System.Net.NetworkCredential("username", "password");
service.Url = "http://MyReportServer/ReportServer/";


text:
Q: permission for show media folder images in django, python I want set permission for show media folder images. for example, I want show my images to users who are staff. When user in not staff, show 404 Error.
Thanks


text:
Q: Array - DS HackerRank in C The code is running fine on my Dev C++ IDE, but it keeps failing on the HackerRank IDE.
Am I making some mistake?
Here's a link to the problem:
https://www.hackerrank.com/challenges/arrays-ds/problem?isFullScreen=true
The function I wrote is as follows, please explain to me where am I going wrong?
int* reverseArray(int a_count, int* a, int* result_count) {
    int i, j;
    for(i=0; i<a_count; i++) {
        result_count[i] = a[i];
    }
    for(j=a_count-1; j>=0; j--) {
        printf("%d ",result_count[j]);
    }
    return result_count;
}

A: Your answer is corrct ,you copy the elements of array 1 from end to start in array 2
if you want to reverse your array in the same array,you just use variable temporary to swap the elements like this :
#include<stdio.h>

void* reverseArray(int a_count, int* a) //you return an array (type complexe) so ,you should use void
{
    int temp=0;
    for(int i=0; i<a_count/2; i++)
    {
        temp= a[a_count-i-1];
        a[a_count-i-1]=a[i];
        a[i]=temp;
    }
    for(int i=0; i<a_count; i++)
    {
        printf("%d ",a[i]);
    }
}

int main()
{
     int t[5]={1,2,3,4,5};
     reverseArray(5,t);
}


text:
Q: Triggering method when element is added to the document I am trying to implement a placeholder feature for IE.
So far I have got the following code:
if(!$.support.placeholder) {

    $('#closestStaticParent').on('focus', '[placeholder]' function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).on('blur', '[placeholder]' function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur();

}

So it adds the placeholder on blur and the code blurs every element with placeholder.
The issue now is that only initially loaded elements blurs. If I load textfields with ajax, they do not trigger blur().
How do I make so that new textfields initiate blur() on themselves when they are added to the document (loaded)?
PS. Please no answers with time-interval-based or ajax-success re-checks.

A: change $('#closestStaticParent') to $('body')  if the elements you are creating are not a child of closestStaticParent