text:
Q: Как изменить файл на удаленном компьютере? Имеется:

*

*На удаленном компьютере(Linux) лежит файл.

*строка с данными.

Необходимо:

*

*подключиться к компьютеру,

*прочитать данный файл. Если в файле имеется искомая строка с данными, то завершаем выполнение, иначе добавляем строку в конец файла.

Чтение файла, поиск и добавление строки - сделал, на локальном компьютере работает. Подскажите, пожалуйста, как проделать все это на удаленном компьютере?

A: Если по простому делать,
то можно использовать что-то от @Даниил_Чижевский или rsync:
скачали-обработали-закачали.
Но возможны сложные случаи:
Если один и тот же скрипт запускается одновременно несколько раз,
например из веб сервера с разными искомыми строками,
то в файле в результате окажется непонятно что.
Если взломают компьютер со скриптом, могут получить доступ и к удаленному с файлом.
Так что задача может усложниться до своего веб сервиса на удаленном компьютере:

*

*с API (POST /add-str)

*с проверкой доступа.

*с блокировкaми файла (flock) или базой данных с атомарной операцией.

A: "Родной" протокол для передачи информации между серверами Linux - SSH. Также существует протокол SFTP - он работает поверх SSH и позволяет передавать файлы или информацию о них.
Для Python существует модуль PySftp - он хоть и староват, но вполне работоспособен. Документацию по модулю можно найти на PyPi: https://pypi.org/project/pysftp/.

A: ssh user@host "if ! grep icq /path/to/file; then echo appendix >> /path/to/file; fi"

*

*логинимся на host как пользователь user

*проверяем при помощи grep наличие строки, которая содержит icq

*в случае, если grep не нашел строку, добавляем в конец файла appendix.

Без питона но логика тут такая - на удаленном хосте должен работать хоть какой-то сервис sshd, Apache, ftpd и тд.
В случае sshd у пользователя должны быть права на чтение запись в желаемый файл.


text:
Q: Regex rule in an NGinx Config to only compare against the first url param Here is an example of our current Nginx rule that will redirect some traffic from one base domain to another (result of a DNS Migration):
location ~* /(var1|var2|var3) {
    rewrite ^ http://newurl.com$uri? permanent;
}

So using the url above the following url: oldurl.com/var1/foo
properly get redirected to: newurl.com/var1/foo
Using this approach oldurl.com/foo currently does not redirect to the new domain which is as designed and what we want.
However the problem we are now having is that if any keywords that are found in the location statement are used anywhere in the URL then it get's redirected.  We only want to pattern match against variables found in the first /###/ folder of the url sequence.
In other words we want oldurl.com/var1/foo
to redirect but not oldurl.com/foo/var1
Given our current regex rule it finds var1 in the url (even though it is in the 2nd position) and redirects.
In other words: oldurl.com/foo/var1
redirects to newurl.com/foo/var1
but we don't want it to.
My regex is just not that spiffy to pattern match against only the first block of /###/ code.  Can someone help me with the proper regex/nginx statement?

A: It's a regular expression so you need to anchor it to the beginning of the url path with ^ like this:
location ~* ^/(var1|var2|var3) {
    rewrite ^ http://newurl.com$uri? permanent;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Binary read loop continues after the last entry I'm trying reading from a binary file with a while loop with the code below but for some reason the loop doesn't break after the last entry. There are 4 entries, each in a line, with each line in below format.

StudentID StudentName StudentSurname StudentEmail StudentYear GPA

Function to create a filter file.
public bool createGPAFilterFile(string fileName, string GPAFilterFileName, double lowerGPA, double upperGPA){
        try
        {
            MainClass sideObj = new MainClass();
            sideObj.createBinaryFile(GPAFilterFileName);
            FileStream stream = File.Open(fileName, FileMode.Open);
            BinaryReader reader = new BinaryReader(stream);

            while (stream.CanRead)
            {
                double readGPA = reader.ReadDouble();

                if (readGPA > lowerGPA && readGPA < upperGPA)
                {
                    UInt32 readStudentID = reader.ReadUInt32();
                    String readStudentName = reader.ReadString();
                    String readStudentSurname = reader.ReadString();
                    String readStudentEmail = reader.ReadString();
                    Byte readStudentYear = reader.ReadByte();
                    sideObj.appendToFile(GPAFilterFileName, readStudentID, readStudentName, readStudentSurname, readStudentEmail, readStudentYear, readGPA);
                }

            }
            reader.Close();
            reader.Dispose();
            stream.Close();
            stream.Dispose();
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message + "\n" + ex.Source);
            return false;
        }
    }

Function that I used in the first place to append the data.
public bool appendToFile (string fileName, UInt32 studentID, string name, string surname, string email, byte classYear, double gpa){
        if (!File.Exists (fileName)) {
            bool success = createBinaryFile (fileName);
            if (!success) {

                return false;
            }
        }
        try{
            BinaryWriter writer = new BinaryWriter (File.Open (fileName, FileMode.Append));
            writer.Write (studentID);
            writer.Write (name);
            writer.Write (surname);
            writer.Write (email);
            writer.Write (classYear);
            writer.Write (gpa);
            writer.Close ();
            writer.Dispose ();
            return true;
        }
        catch{
            return false;
        }

    }

A: Found a solution for anyone else interested :)
Rather than using, while(stream.CanRead) I tried with while(stream.Position != stream.Length) and now the code is working as it should.


text:
Q: How to import .flt files into GRASS? I am trying to import a raster file (.flt) into GRASS. The raster file (.flt) was generated from HEC-RAS. The said raster format cannot be imported into GRASS (it shows the error "file not supported"). Is there a way to import the .flt into GRASS?

A: It seems that r.in.gdal will be able to import *.flt files. I just browsed some posts in GRASS Mailing lists, though the last one reports errors while importing due to some reasons, you could try them.

*

*[GRASSLIST:3013] arcview

*Floating Grid to raster GRASS

*Error in r.in.gdal

A: Can you use gdal_translate to convert to a raster format GRASS prefers?


text:
Q: AWS - Script to create EC2 snapshots and automatically rename them I'm currently trying to setup a script (using AWS CLI from an Ubuntu server) that will do the following:

*

*Create a snapshot of every existing volume. Those volumes already have a NAME tag (Like SERVER1, SERVER1DATA, SERVER2, SERVER2DATA etc).

*Rename those snapshots taken with the same tag NAMES (so then, on the AWS console i could filter them by date and would be able to easily identificate them).
The automatic rename is my main issue here.
I've been toying with ec2-describe-volumes , ec2-create-snapshot and ec2addtag commands but my scripting is not that good. So far i've been able to setup this by creating a list with VOLUME NAME and NAME TAG (those parameters are then taken by the ec2addtag) but i would have to manually update that list every time i add or remove a volume on the environment.
Any help will be greatly appreciated it.

A: I'm not positive I understand your question completely, but if what you want is to be able to generate a list of your volumes, along with name tags, something like this might work:
aws ec2 describe-tags --query "Tags[*].{Name:Value,ResourceId:ResourceId}" --filters "Name=key,Values=Name"  --filters "Name=resource-type,Values=volume" --output json

Basically what that says is "Give me the resource id and the value of the tag "name" for every resource of type "Volume".  In this case, I specified json as the output.  You may also specify "text" or "table" depending on your needs.
Another approach:
aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId}" --output text

This would return a list of your volumes.  If you piped this to a text file, the file would just contain a list of volume identifiers - one per line.
You could then get the Name tag for each volume in the list with something like this:
aws ec2 describe-tags --query "Tags[*].{Name:Value,ResourceId:ResourceId}" --filters "Name=key,Values=Name"  --filters "Name=resource-type,Values=volume" --filters "Name=resource-id,Values=vol-2e293949" --output json

This is basically saying "give me the resource id and the value of the tag name for the specified id vol-2e293949.
As you can see the CLI commands can be hard to read and the filtering and querying is a bit difficult.  (These examples use a recent version of the AWS CLI)

A: As for extracting the snapshot ID from your create-snapshot command, you can do it without needing awk/sed/grep/etc. by using a few CLI features (query and output).
For example:
$ SNAP_ID=`aws ec2 create-snapshot --cli-input-json file://$temp_file --query 'SnapshotId' --output text`
$
$ echo "snap id: "$SNAP_ID
snap id: snap-aaaabbbb
$
$ aws ec2 create-tags --resources $SNAP_ID --tags Key=Name,Value=$SOME_NAME
$

Note that with an output of json instead of "text" it wraps the returned snapshot id with double quotes per JSON standard.

A: A while back I wrote this bash script to do exactly this for me. Basically, you install it on each EC2 instance that you want to back up, and providing you give it a private key, a certificate file and the EC2 API tools, this will self-discover the instance ID, the volumes attached to it, and create a snapshot for each volume.
You must tag the volumes with Name and Device. Name is just a user-friendly name that appears in the snapshot's description. Device is is the actual device name on the server. /dev/sdf for instance. Finally, it will rotate your snapshots once a predefined limit has been reached. The default is 50. When the 51st snapshot is created, the oldest one will be deleted.

A: #!/bin/bash

aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId}" --output text > /tmp/volumes

for i in $(cat /tmp/volumes); do

aws ec2 create-snapshot --volume-id $i | awk {'print $2'} | grep snap* | sed 's/\"//g'|sed 's/\,//g' > /tmp/snapname

SNAPENAME=$(cat /tmp/snapname)

TAGNAME=$(aws ec2 describe-tags --query "Tags[*].{Name:Value,ResourceId:ResourceId}" --filters "Name=key,Values=Name" --filters "Name=resource-type,Values=volume" --filters "Name=resource-id,Values=$i" --output text | awk '{ print $1 }')

sleep 5

aws ec2 create-tags --resources $SNAPENAME --tags Key=Name,Value=$TAGNAME >/dev/null

done

It's a little bit messy and perhaps unnecessary long, but it does what required: Create a snapshot of all available volumes and (if those had NAME tags) then rename them with those NAME tags.


text:
Q: Fatal: pathspec 'file.txt' did not match any files, using git I have started learning Git.
Now at the starting I got stuck with this error
Fatal: pathspec 'file.txt' did not match any files.
Here is the log and screenshot of my problem:

ln: failed to create symbolic link /etc/atab': Permission denied
"C:\Windows\system32\drivers\etc\hosts'> /etc/hosts'
/usr/bin/cp: cannot create regular file '/etc/hosts': Permission denied
'C:\Windows\system32\drivers\etc\protocol > /etc/protocols"
/usr/bin/cp: cannot create regular file '/etc/protocols': Permission denied
'C:\Windows\system32\drivers\etc\services > /etc/services'
/usr/bin/cp: cannot create regular file '/etc/services': Permission denied
'C:\Windows\system32\drivers etc\networks > /etc/networks
/usr/bin/cp: cannot create regular file '/etc/networks': Permission denied
rm: cannot remove /etc/post-instal1/01-devices.post': Permission denied
rm: cannot remove /etc/post-instal1/03-mtab.post': Permission denied
rm: cannot remove /etc/post-instal1/06-windows-files.post': Permission denied
rm: cannot remove /etc/post-instal1/99-post-install-cleanup.post': Permission denied

HTCODESKTOP-V8D4M7P MINGW64 - (master)
S git add index.html
fatal: pathspec 'index.html' did not match any files

HTCODESKTOP-V8D4M7P MINGW64- (master)
S^C

HTCODESKTOP-V8D4M7P MINGK64- (master)

A: Make sure first you have not opened a git bash session from a CMD run as Administrator.
Its '~' ($HOME) would be C:\windows\System32, and nothing good would happen from a git repository initialized directly in $HOME.
Make sure to run your bash as a regular user, and initialize a new local repository using a folder name which does not yet exist, and will be created by git init:
cd
pwd
git init myFirstRepo
cd myFirstRepo

A: Try this - It worked for me
$ echo hello > index.html
$ git add index.html


text:
Q: Handling keyboard input on a dialog - Windows I am programming an application that is non-modal dialog based. I am using the Visual Studio resource editor to build the dialog and create the application. Everything is going great so far. However, I have reached a brick wall when it comes to handling keyboard input. My research has shown that windows captures keyboard input before it reaches the dialog callback procedure to implement the ability to move the focus using the keyboard.
I created a bare bones dialog to test this and, when I have a dialog without any controls on it, everything works as I would expect it to. When I add a control, it stops working.
Here is the code from the bare bones project:
#include <Windows.h>
#include <CommCtrl.h>
#include <tchar.h>
#include "resource.h"

INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM  lParam);
HWND dlghandle;
int WINAPI _tWinMain(HINSTANCE hInst, HINSTANCE h0, LPTSTR lpCmdLine, int nCmdShow)
{
HWND hDlg;
MSG msg;
BOOL ret;

hDlg = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_DIALOG1), 0, DialogProc, 0);
ShowWindow(hDlg, nCmdShow);
dlghandle = hDlg;
while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
    if (ret == -1)
        return -1;
    if (!IsDialogMessage(hDlg, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}
return 0;
}

INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
 {
    switch (uMsg)
{
case WM_KEYDOWN:
    MessageBox(NULL, L"Test", L"Test", MB_OK);
    break;
case WM_CLOSE:
    DestroyWindow(hDlg);
    break;
case WM_DESTROY:
    PostQuitMessage(0);
    return 0;
    break;
}
return 0;
}

What options do I have?

A: The first place keyboard input appears is your message loop, so just check for the keypress you're looking for before passing it off to IsDialogMessage() / TranslateMessage() / DispatchMessage(). For example:
while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
    if (ret == -1)
        return -1;

    if (msg.message == WM_KEYDOWN && msg.wParam == 'Q')
    {
        // trap and handle the Q key no matter which control has focus
    }
    else
    if (!IsDialogMessage(hDlg, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

If you wanted you could even wrap this in a function to make it neater, e.g.:
#define MYMSG_DOSOMETHING   (WM_APP + 1)

BOOL MyIsDialogMessage(HWND hDlg, MSG* pMsg)
{
    if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'Q')
    {
        PostMessage(hDlg, MYMSG_DOSOMETHING, 0, 0);
        return TRUE;
    }
    return IsDialogMessage(hDlg, pMsg);
}

// then your message loop would be:

while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
    if (ret == -1)
        return -1;

    if (!MyIsDialogMessage(hDlg, &msg))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

A: You could also use SetWindowsHook to create low level keyboard proc.
NOTE this looks a bit complex and advanced  but it works great with Dialogs without doing any extra effort to message loop.
HHOOK g_hLowLevelKeyHook;

//windows Main.
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    g_hLowLevelKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, GetModuleHandle(NULL), NULL);

........
.......
}

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    KBDLLHOOKSTRUCT *pkbhs = (KBDLLHOOKSTRUCT *)lParam;
    if (nCode == HC_ACTION && wParam == WM_KEYUP)
    {
        if (pkbhs->vkCode == VK_F1)
            MessageBoxA(NULL"F1 Pressed","INFO",MB_ICONINFORMATION);
    }
    return CallNextHookEx(g_hLowLevelKeyHook, nCode, wParam, lParam);
}


text:
Q: a worker gets killed that has delayed data in dask distributed I have problem debugging the error I got from dask distributed.
I am using loc to take out small dataframe from large ~100M rows and converting to daskArray.
only when I want to grab the data from the cluster I ran into this issue.

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  errors=errors,
  *
  Finally when my data is ready to be taken out with
  ddf2local=client.gather(chunkDelayedDB.result())

*
The worker contains data that will die and I get following message. In one machine with 32 gb it works fine
File "/home/yousef/pipy/lib/python3.6/site-packages/distributed/client.py", line 244, in _result
    result = await self.client._gather([self])
File "/home/yousef/pipy/lib/python3.6/site-packages/distributed/client.py", line 1761, in _gather
    response = await future
File "/home/yousef/pipy/lib/python3.6/site-packages/distributed/client.py", line 1813, in _gather_remote
    response = await self.scheduler.gather(keys=keys)
File "/home/yousef/pipy/lib/python3.6/site-packages/distributed/core.py", line 748, in send_recv_from_rpc
    result = await send_recv(comm=comm, op=key, **kwargs)
File "/home/yousef/pipy/lib/python3.6/site-packages/distributed/core.py", line 547, in send_recv
    raise exc.with_traceback(tb)
File "/home/admin/mypy36/lib/python3.6/site-packages/distributed/core.py", line 403, in handle_comm
File "/home/admin/mypy36/lib/python3.6/site-packages/distributed/scheduler.py", line 2561, in gather
KeyError: 'delayedDB-42a099cc4ddd139877f60c67295ab09a'
I trackdown the memory of the worker being killed at is fine untill getting the data (also it had alot of data.)
I would acknowledge any support that might help so greatly.


text:
Q: How to find vendor name from JEDEC id? I would like to get the manufacturer name from JEDEC ids. Here is an example of some ids.
JEDEC ID:7F 7F 7F 7F 7F 51 00 00
JEDEC ID:80 2C
JEDEC ID:80 CE
JEDEC ID:AD 00 00 00 00 00 00 00
JEDEC ID:CE 01 09 13 45 67 5E F4
JEDEC ID:CE 01 09 13 47 7A 3E 5A

I found this list of manufacturer ids from JEDEC, but I'm not sure if this ids match to my ids and how to connect them correctly.
For example:
If I look at the JEDEC id CE 01 09 13 47 7A 3E 5A, the first Byte CE is equal to 11001110. If I compare this value with the JEDEC list, I get Samsung as Vendor. This is correct for the hardware.
But for example the Byte value 80 from JEDEC id 80 CE is missing in the list. Also I cannot find the vendor for 7F 7F 7F 7F 7F 51 00 00. Additional to that I don't know when to use which Byte value from the JEDEC list (Byte 1, Byte 2, ...) In guess 01 00 00 00 is AMD and 00 00 01 00 is Camintonn Corporation. But in my case I haven't any leading zeros. How should I know when to use the second Byte value?
Any idea how to get the vendor name from the ids? Are there any rules?

A: JEDEC provides a document called JEP106 which contains all manufacturers. You can download this document here (rev AP release in Feb 2015). In that document the different banks are continued with the byte value 7F.
If you have the id 7F 01 you're in the second bank and you're vendor is Cirrus Logic. Without leading 7F you're in the first bank.


text:
Q: Waiting for a Future to complete before making assertions I have a Scala Play application and one of the controllers fires a Future which does some logging. I have a simple call back function which executes when the Future completes.
I have written a test to check whether this logging happens. The rough logic is as follows:
feature{

  scenario{
    Given()
      // set up the call
    When()
      // make a FakeRequest via reverse routing - logging will done in a separate thread via a Future
    Then()
      Thread.sleep(50) // sleep to allow logging to finish
      // check if the logging has been done

The issue is the Thread.sleep. I have added that call in to block the main testing thread in order to give enough time to elapse for the Future which does the logging in a separate thread to complete before actually doing the checks to see if the logging has been done.
My question is whether there is a better way to do this? In reality if my application is running and the logging is taking an inordinate amount of time, then the main thread which governs the application will not terminate until the Future that does the logging in a separate thread finishes. So I don't see a problem of putting in the Thread call above to simulate that. But I just want to confirm if this is correct.
For me, there is absolutely no other way than to do this. If I try to replicate how the app behaves in reality with my test, then the main thread for the test should complete and terminate even though the future for the logging is still going on; there is no call back in the test and neither should there be.

A: Assuming you're using ScalaTest ; you can use whenReady construct ; which periodically inspects the passed future, until it is either ready or the configured timeout has been surpassed;
see
http://www.artima.com/docs-scalatest-2.0.M5/org/scalatest/concurrent/Futures.html
http://doc.scalatest.org/2.0/index.html#org.scalatest.concurrent.ScalaFutures


text:
Q: Have a single useEffect hook after any component has been rendered So I have my routes that render a component:
const Layout = () => {

  return (
    <InitLayout>
      <Switch>
        <Redirect exact from='/' to='/home/recent' />
        <Route path="/home/:category" exact component={Home}></Route>
        <Route path="/about" exact component={About}></Route>
        <Route path="/help" exact component={Help}></Route>
        <Route path="/users/:userId" exact component={UserProfile}></Route>
        <Route path="/ask" exact component={AskQuestion}></Route>
        <Route path="/review" exact component={ReviewPost}></Route>
        <Route path="/posts/:postId/review" exact component={ReviewPost}></Route>
        <Route path="/users/:userId" exact component={UserProfile}></Route>

        <Redirect from='*' to='/home/recent' />
      </Switch>
    </InitLayout>
  );
};

In any of these components I would theoretically set the following effect:
  useEffect(() => {
    if (!isSsr) {
      fetchPosts();
    }
    setSsrState({ isSsr: false }); // ==> Here
  }, []);

This code will basically set an SSR state, to prevent the client to re-request data from the server when it has already been preloaded from the server.
Now this state needs to be set from any of the components, but I don't want to duplicate this code in all components. Forgetting to put it will result in bugs, so that is definitely a bad idea.
Is there a straightforward way to define an effect once, and have it called in every of the route's component?

A: After speaking with Trace, the issue was able to be resolved by wrapping the layout component with an HOC, which sets the SSR state to false.
Interestingly enough, by wrapping the component inside an HOC, this sets off the child components first before the HOC component. That way, we are able to first check on the child component level if the SSR is set. After the child component useEffect is ran, the HOC useEffect is then ran, which sets the SSR flag back to false.


text:
Q: Visual basic Making a global round function I am working in on a project which is some sort of a calculator for Quadratic equations and others parts. One of the tasks is to make an accuracy option to make the user set the rounding between 1-5 decimal places.
I have constructed some sort of function already to do that, however what I need is a way for the program to round the values when there are two different results(i.e quadratic equations), if I use my function to kinda joins the two answers and rounds them.
How do i make the variable that holds the results, and the function that rounds the result be able to store two different answers without joining them? or maybe I have written the code not how it is supposed to be? any tips?
I am using the Math.round function.
Here is the code;
Function Accuracy()
    Dim choice As Integer = 0
    Console.WriteLine("This is the accuracy option")
    Console.WriteLine("Enter the decimals places to be set from 1 - 5")
    DP = Console.ReadLine()
    Console.WriteLine("The current decimals places are set to: " & DP)
    ...

Function round()
    Result = Math.Round(Result, DP)
End Function

The way i tried to make it work was by making the result = to "result" of the calculation and then run the round() function

*

*DP and result are global variables.

A: Ok here is basically the structure I would build. Keep in mind I don't know about your project and even less about quadratic equations...
File MyResult.vb
Public Class MyResult
   Public Property Result as Double 'I suppose
   Public Property RoundedDecimals as Integer 'We hold here the rouding
   Public Readonly Property RoundedResult as Double
   Get
     Return Math.Round(Result, RoundedDecimals)
   End Get
   End Property

   Public Sub New(Result as Double)
     Me.Result = Result
     RoundedDecimals = 5
   End Sub

   '... End of your class
End Class

File MainModule.vb
Public Module MainModule

  Sub Main()
    'Calculate your stuff
    ...

    'Create your result
    Dim Result As New MyResult(CalculatedValue)

    'Ask for Rounding
    Dim round = 0
    Do
        Console.WriteLine("Enter number of decimals : ")
        round = Console.ReadLine()
    while not Integer.TryParse(round, Result.RoundedDecimals)

    'Displaying rounded result
    Console.WriteLine("Rounded Result is {0}", Result.RoundedResult)

    '...
  End Sub()

End Module


text:
Q: Combining multiple observations n R dataframe I have this table with multiple observations

I want the table to look like this

The observations MI and MA have multiple values which I want to add up.

A: We can use aggregate to do a group by sum
aggregate(all_bills ~ st_name, df1, sum)

A: Here's the dplyr approach:
library("dplyr")

dataset %>%
  group_by(st_name) %>%
  summarize(all_bills = sum(all_bills))

Also, here's the dataset:
dataset <- structure(list(
  all_bills = c(33, 57, 126, 23, 97, 58, 27),
  st_name   = c("AL", "MI", "MI", "MA", "SC", "VA", "MA")),
  .Names = c("all_bills", "st_name"),
  row.names = c(NA,-7L),
  class = "data.frame")


text:
Q: Boundary condition: displacement I have a controversial case. I have a rod, which is fixed from one end (constraint). From another end, I apply a compressive force, by pressing the rod down. So in a way I have a constraint, but at the same time an external force. How do I model it? Do I give a boundary condition (displacement = 0) from both ends, or just from one?

A: You have different types of boundary conditions:

*

*Dirichlet boundary conditions. Which specify the value of the solution to the differential equation. In this case you are solving for displacements, so this kind of BC is the one that you used to constraining the fixed end of the rod.

*Neumann boundary conditions. These specify the value of the derivative of your solution is going to take. In this case the derivative of the displacements is related with the strain tensor, which is related to the appliance of external forces, which is what you are doing at the end of the rod.

*Robin boundary conditions. I dont know much about these...so according to wikipedia: When imposed on an ordinary or a partial differential equation, it is a specification of a linear combination of the values of a function and the values of its derivative on the boundary of the domain.

So: Do I give a boundary condition (displacement = 0) from both ends, or just from one?
(for an axially loaded bar) Displacement u = 0 just in one end, and σ(L) = 0, meaning EA du/dx at (x=L) = 0, at the other (L being the length of the bar).

A: You have a boundary condition of zero displacement at the truly restrained end (assuming that the restrained end is a totally rigid wall).  The rod is elastic (like a very stiff spring), so there will be a displacement at the end where you supply the force.  The displacement will vary linearly from 0 at the restrained end to $u_{max}$ at the end where you apply the displacement.  The strain in the rod will be uniform at $u_{max}/L$, where L is the original length of the rod, and the force will be $F=EA\frac{u_{max}}{L}$, where A is the cross sectional area of the rod and E is the Young's modulus of the rod metal.


text:
Q: Even created a global class, still cannot save a variable from try-catch Android Studio topic
My story flow:

*

*Created a GlobalClass for saving user info.

*Login to a Facebook account to draw user info (JSONobject).

*In an inner class (onSuccessListener), I want to save user name in my GlobalClass for later use.

*AndroidStudio requests me to use try-catch for JSON exception. OK, I must use one then.

*What I do is: try-(Draw user name from JSONObject when login success and save the user Nickname in GlobalClass) and catch-(exception). Done.

However, wherever outside the onSuccess inner class, my GlobalClass is null!
Any ideas?
updated with code: the "globalVariable.setGlobalUserFacebookName()" will have no value when leaving, for other user information, it can save.
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            accessToken = loginResult.getAccessToken();
            @SuppressLint("StringFormatMatches") String tempText = String.format(getString(R.string.loginInformation,
                    loginResult.getAccessToken().getUserId(),
                    loginResult.getAccessToken().getToken(),
                    AccessToken.getCurrentAccessToken().getPermissions().toString()));
            fbtoken.setText(tempText);

            globalVariable.setGlobalUserFacebookID(loginResult.getAccessToken().getUserId());
            globalVariable.setGlobalUserFacebookToken(loginResult.getAccessToken().getToken());
            globalVariable.setGlobalUserFacebookPermission(AccessToken.getCurrentAccessToken().getPermissions().toString());

            final String FirebaseEmail = globalVariable.getGlobalUserFirebaseEmail();
            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {

                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {// Application code

                            try {
                                FacebookUserName = (String) response.getJSONObject().getString("name");
                                // the value of this globalClass null after leaving this inner class
                                globalVariable.setGlobalUserFacebookName(FacebookUserName);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            loggedInView.setText(FacebookUserName);

                        }

                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "name");
            request.setParameters(parameters);
            request.executeAsync();
        }

public class GlobalClass {
private static GlobalClass instance;
private static String globalUserFirebaseName;
private static String globalUserFirebaseEmail;
private static String globalUserFirebasePassword;
private static String globalUserFacebookName;
private static String globalUserFacebookID;
private static String globalUserFacebookToken;
private static String globalUserFacebookPermission;

public static void setInstance(GlobalClass instance) {
    GlobalClass.instance = instance;
}

public static String getGlobalUserFirebaseName() {
    return globalUserFirebaseName;
}

public static void setGlobalUserFirebaseName(String globalUserFirebaseName) {
    GlobalClass.globalUserFirebaseName = globalUserFirebaseName;
}

public static String getGlobalUserFirebaseEmail() {
    return globalUserFirebaseEmail;
}

public static void setGlobalUserFirebaseEmail(String globalUserFirebaseEmail) {
    GlobalClass.globalUserFirebaseEmail = globalUserFirebaseEmail;
}

public static String getGlobalUserFirebasePassword() {
    return globalUserFirebasePassword;
}

public static void setGlobalUserFirebasePassword(String globalUserFirebasePassword) {
    GlobalClass.globalUserFirebasePassword = globalUserFirebasePassword;
}

public static String getGlobalUserFacebookName() {
    return globalUserFacebookName;
}

public static void setGlobalUserFacebookName(String globalUserFacebookName) {
    GlobalClass.globalUserFacebookName = globalUserFacebookName;
}

public static String getGlobalUserFacebookID() {
    return globalUserFacebookID;
}

public static void setGlobalUserFacebookID(String globalUserFacebookID) {
    GlobalClass.globalUserFacebookID = globalUserFacebookID;
}

public static String getGlobalUserFacebookToken() {
    return globalUserFacebookToken;
}

public static void setGlobalUserFacebookToken(String globalUserFacebookToken) {
    GlobalClass.globalUserFacebookToken = globalUserFacebookToken;
}

public static String getGlobalUserFacebookPermission() {
    return globalUserFacebookPermission;
}

public static void setGlobalUserFacebookPermission(String globalUserFacebookPermission) {
    GlobalClass.globalUserFacebookPermission = globalUserFacebookPermission;
}

public static synchronized  GlobalClass getInstance() {
    if(instance == null) {
        instance = new GlobalClass();
    }
    return instance;
}

}

A: If an object is created inside a class then that object can only be referenced inside that class unless you create a method which returns that object. With that said, any class with access to the object can call the methods associated with that object. This does not mean the variables can be seen though. In order for the variable values to be retrieved, you must have methods returning those values, like you have in GlobalClass. Thus, the problem is related to scope.

A: According to csell's answer, which is correct, this is just a matter of scope.
You can read more oracle's official doc about anonymous class and the final keyword to solve your problem.
You should consider making only the field "instance" of the GlobalInstance to be static for singleton use. Others fields should be at object's instance level (non-staic) to make sure that you always use the same global variable, and you go more into abstraction/encapsulation.


text:
Q: Nexus S 4g not detected by computer A little bit of a disclaimer, I have very little knowledge of the correct terminology for some of the things I'm going to ask about, and I apologize in advance
I have a Nexus S 4g phone that is, at the moment of writing, connected to my 11.10 computer through its USB charger cable.  In the past, connecting the phone like this has allowed me to transfer files between my computer and my phone; I'm able to get my music onto my phone, and my photos onto my computer, for example.  For some reason, this has stopped working.  My phone still charges its battery when connected to the computer, but neither the computer nor the phone recognized that they are connected.
Is there something I can do to get the phone and the computer to detect each other?  I don't know how to fix this, and it's more than a little frustrating.  Any help would be greatly appreciated.

A: Newer Android devices (as of 3.0 Honeycomb) no longer support USB Mass Storage for the internal storage, because that allows Android to not have to support the FAT32 file system.  In order to connect to a 3.0 or later device over USB you'll need to use something that speaks MTP; there are a few applications for Linux which do so such as aafm or gmtp.  I have had the most success using mtpfs, although it's not really that user-friendly to work with.
You can also try one of the many ftp/scp/bluetooth file transfer tools for Android and see if that does what you need.  Astro has a few file transfer plugins available, and there's also several FTP clients and servers as well.  I find that to usually be less of a hassle than MTP, although it also tends to be slower since it has to go over the network (or Bluetooth) instead of USB.

A: If you are really using the Nexus S 4g try this:
On my Samsung Galaxy S+ I had to go to system settings -> Applications -> Developement -> and then check USB Debugging in order to have the phone work like a usb storage device. Since the Nexus uses another android version I believe, there might have been some changes...but just try
If you are using the Galaxy Nexus (the new one that just came out...with android 4.0 on it)
This instruction should help you:
http://www.omgubuntu.co.uk/2011/12/how-to-connect-your-android-ice-cream-sandwich-phone-to-ubuntu-for-file-access/

A: I recently made a post here on how to connect the Nexus 7 to an Ubuntu laptop. This should be applicable to your phone as well, just make sure you replace the Nexus 7's device id (18d1) with your phone's device id (you can find the device id by running mtp-detect | grep idvendor after installing the mtp-tools packages).

A: I had similar issues with my Galaxy S2 and Ubuntu. Here is what I did:
On your android phone, go to Application->Settings
In there, go to Wirelessand Network and select USB Utilities
Click on Connect Storage to PC
A message should pop up: Connect USB cable to use mass storage
Now connect the USB cable to computer
A green android robot should be on display with an option of "Connect USB storage", click on it
The green robot turns orange now and now you can access the files on the SD card of your phone

Source: http://www.computerandyou.net/2012/01/how-to-fix-android-samsung-galaxy-s2-not-recognized-on-linux/
I wrote the above mentioned post afterwards and it has solved the problem of many people since then.


text:
Q: Skylake Integrated Graphics | HP ProOne 400 G2 AIO Install Problems Trying to install Ubuntu on HP ProOne 400 G2
It has an i3 Skylake and intel integrated graphics.
I have been unsuccessful in installing Ubuntu 14 - 16 and getting the graphics to work correctly with a decent resolution.
I have tried Ubuntu 14 w/ i915.preliminary_hw_support=1 (Kernel 4.2 - 4.4) <-- Did not work
I have tried Ubuntu 15 w/ 01.org Intel Installer (Different kernels too) <-- Did not work
Ubuntu 16 <-- Did not work
All versions do not show driver as enabled, and I have to put nomodeset in grub.
What am I doing wrong??

A: Could you please elaborate more what you mean by "have been unsuccessful in installing Ubuntu 14 - 16"?
Was the installation successful and you just did not manage to configure graphics correctly or the whole installation failed?
If you are able to install Ubuntu 16.04, try to replace installed kernel with kernel 4.6.3 (how-to below for your 64-bit installation), this should resolve your issues.

$ cd /tmp
$ wget kernel.ubuntu.com/~kernel-ppa/mainline/v4.6.3-yakkety/linux-headers-4.6.3-040603_4.6.3-040603.201606241434_all.deb kernel.ubuntu.com/~kernel-ppa/mainline/v4.6.3-yakkety/linux-headers-4.6.3-040603-generic_4.6.3-040603.201606241434_amd64.deb kernel.ubuntu.com/~kernel-ppa/mainline/v4.6.3-yakkety/linux-image-4.6.3-040603-generic_4.6.3-040603.201606241434_amd64.deb

Install the kernel:
$ sudo dpkg -i linux-headers-4.6.3*.deb linux-image-4.6.3*.deb

Reboot your PC and check if kernel 4.6.3 is currently used by issuing command
$ uname -r


text:
Q: Synchronize access between TFS and Sharepoint portal in my setup each project in tfs 2015 has own project portal. But group permissions are different in tfs and sharepoint. Is there some approaches to synchronize them?

A: There isn`t standard tools to synchronize users and permissions between TFS and SharePoint. I think you may try to use next ways:

*

*Common active directory groups. Create separate group for readers and contributors (for each project), add them to SP and TFS. Then add and remove users from these groups.

*Use Team Foundation Server Administration Tool as centralized tool. This tools was created for TFS 2013. But TFS 2015 supports TFS 2013 object model. You have to (on your local workplace) install Team Foundation Server 2013 object model, download archive, rename last release to TFS AdministrationTool.zip and install it.


text:
Q: Callback function used in jquery to set css value Below code uses a function that has index and oldValue as callback values, i want to know what value do i get from oldValue, currently i am getting a value in px from oldValue but i do not understand what that value represents. How can i find a documentation on that function ?
setInterval(function() {
            $('#ship-container').css({
                left: function(index ,oldValue) {
                    return calculateNewValue(oldValue, 37, 39);
                }
            });
        }, 20);


text:
Q: How to define multiple elements in XML Schema with the same name and different attribute value allowed? I would like to create XML Schema for this chunk of xml, I would like to restrict the values of "name" attribute, so that in output document on and only one instance of day is allowed for each week day:
<a>
  <day name="monday" />
  <day name="tuesday" />
  <day name="wednesday" />
</a>

I have tried to use this:
 <xs:complexType name="a">
  <xs:sequence>
    <xs:element name="day" minOccurs="1" maxOccurs="1">
      <xs:complexType>
        <xs:attribute name="name" use="required">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:enumeration value="monday" />
            </xs:restriction>
          </xs:simpleType>
        </xs:attribute>
      </xs:complexType>
    </xs:element>
    <xs:element name="day" minOccurs="1" maxOccurs="1">
      <xs:complexType>
        <xs:attribute name="name" use="required">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:enumeration value="tuesday" />
            </xs:restriction>
          </xs:simpleType>
        </xs:attribute>
      </xs:complexType>
    </xs:element>
  </xs:sequence>
</xs:complexType>

but XML Schema validator in eclipse says error "Multiple elements with name 'day', with different types, appear in the model group.".
Is there any other way?

A: You need something like this:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="a">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="day"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="day">
    <xs:complexType>
      <xs:attribute name="name" use="required">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:enumeration value="monday"/>
                <xs:enumeration value="tuesday"/>
                <xs:enumeration value="wednesday"/>
            </xs:restriction>
        </xs:simpleType>
        </xs:attribute>
    </xs:complexType>
  </xs:element>
</xs:schema>

A: In order to satisfy the at-most-once constraint described in the original question, you need to use a xs:unique element in your schema.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified">

  <xs:element name="a">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="day" maxOccurs="7" minOccurs="1">
          <xs:complexType>
            <xs:attribute name="name" use="required">
              <xs:simpleType>
                <xs:restriction base="xs:string">
                  <xs:pattern value="(mon|tues|wednes|thurs|fri|satur|sun)day"/>
                </xs:restriction>
              </xs:simpleType>
            </xs:attribute>
          </xs:complexType>
          <xs:unique name="eachDayAtMostOnce">
            <xs:selector xpath="day"/>
            <xs:field xpath="@name"/>
          </xs:unique>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

A: Have you considered something like this? (i.e. day is a type, and the elements are named after the days of the week)
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:complexType name="day" />
  <xs:element name="a">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="monday" maxOccurs="1" minOccurs="0" type="day" />
        <xs:element name="tuesday" maxOccurs="1" minOccurs="0" type="day" />
        <xs:element name="wednesday" maxOccurs="1" minOccurs="0" type="day" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

A: Try this:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="a">
    <xs:complexType>
        <xs:sequence>
            <xs:element maxOccurs="unbounded" name="day">
                <xs:complexType>
                    <xs:attribute name="atrib" type="xs:string" use="required" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

I think the maxOccurs="unbounded" is what you need.

A: Use choice instead of sequence
By that way u can have only day element one's in a element
And for name attribute use ref attribute and reference it with enumeration


text:
Q: `go tool pprof` reports error `unrecognized profile format` I am trying to generate PNG of goroutine profile with this demo, but it reports error parsing profile: unrecognized profile format. failed to fetch any source profiles
package main

import (
    "fmt"
    "log"
    "os"
    "os/exec"
    "runtime/pprof"
    "time"
)

func main()  {
    // start demo go routine
    go func() {
        for {
            time.Sleep(time.Second)
        }
    }()

    // get executable binary path
    exePath, err := os.Executable()
    if err != nil {
        log.Println(err.Error())
        return
    }
    log.Println("exePath", exePath)

    // generate goroutine profile
    profilePath := exePath + ".profile"
    f, err := os.Create(profilePath)
    if err != nil {
        log.Println(err.Error())
        return
    }
    defer f.Close()
    if err := pprof.Lookup("goroutine").WriteTo(f, 2); err != nil {
        log.Println(err.Error())
        return
    }

    // generate PNG
    pngPath := exePath + ".png"
    result, err := exec.Command("go", "tool", "pprof", "-png", "-output", pngPath, exePath, profilePath).CombinedOutput()
    if err != nil {
        log.Println("make error:", err.Error())
    }
    log.Println("make result:", string(result))
}

A: You are using a debug value of 2 in pprof.Lookup("goroutine").WriteTo(f, 2). This will produce an output which the pprof tool can't parse, it is meant as directly human readable.
From the pprof.(*Profile).WriteTo docs:

The debug parameter enables additional output. Passing debug=0 writes the gzip-compressed protocol buffer described in https://github.com/google/pprof/tree/master/proto#overview. Passing debug=1 writes the legacy text format with comments translating addresses to function names and line numbers, so that a programmer can read the profile without tools.
The predefined profiles may assign meaning to other debug values; for example, when printing the "goroutine" profile, debug=2 means to print the goroutine stacks in the same form that a Go program uses when dying due to an unrecovered panic.

Changing this line to pprof.Lookup("goroutine").WriteTo(f, 0) resolves the issue.

Also, not relevant to the issue, but you might want to consider closing the file f.Close() before using it in the pprof command. WriteTo should flush the file to disk, but it can't hurt.
if err := pprof.Lookup("goroutine").WriteTo(f, 2); err != nil {
    log.Println(err.Error())
    return
}

if err := f.Close(); err != nil {
    log.Println(err.Error())
    return
}

// generate PNG
...


text:
Q: Salesforce Managed package security review, how can I change custom settings field visibility which contains sensitive data to private or protected? In the process of getting a managed package reviewed by Salesforce and it has been flagged for Insecure Storage of Sensitive Data and they highlight the following xml.
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
    <customSettingsType>List</customSettingsType>
    <enableFeeds>false</enableFeeds>
    <fields>
        <fullName>Client_Id__c</fullName>
        <deprecated>false</deprecated>
        <externalId>false</externalId>
        Client Id
        <length>100</length>
        <required>false</required>
        <trackTrending>false</trackTrending>
        <type>Text</type>
        <unique>false</unique>
    </fields>
    <fields>
        <fullName>Client_Secret__c</fullName>
        <deprecated>false</deprecated>
        <externalId>false</externalId>
        Client Secret
        <required>false</required>
        <trackTrending>false</trackTrending>
        <type>TextArea</type>
    </fields>
    ConnectedApp
    **<visibility>Public</visibility>**
</CustomObject>

Notes
Sensitive data like Client_Id__c and Client_Secret__c which is use in api call, should be stored in a protected custom setting or named credential.
Related Code
public class CRMA_AuthenticationCheck {
    ...
    @AuraEnabled
    public static ResponseWrapper authorizeCRMA(String session_id, String userId, String consumerSecret){
        ResponseWrapper rw = new ResponseWrapper();
        string successMsg;
        string crmaUrl;
        ConnectedApp__c conApp;
        try{
            Boolean isStaging = [SELECT Id, IsSandbox FROM Organization LIMIT 1].IsSandbox;
            if(isStaging){
                crmaUrl = 'https://salesforcestaging.mydummysite.com/index.php/logincb/';
            }else{
                crmaUrl = 'https://salesforce.mydummysite.com/index.php/logincb/';
            }
            conApp = ConnectedAppCreator.createConnectedApp(crmaUrl+userId);
            Boolean isSuccess = false;
            if(String.isBlank(consumerSecret)){
                consumerSecret = conApp.Client_Secret__c;
            }
            if(String.isBlank(consumerSecret)){
                rw.StatusCode = 120;
                rw.ResponseMessage = 'Please Enter the Consumer Secret from Connected App with name Foo Connected App' ;
                rw.toastType = 'dismissable';
                return rw;
            }else {
                conApp.Client_Secret__c = consumerSecret;
            }
            if(conApp != null && String.isNotBlank(conApp.Client_Id__c)){
                successMsg = ConnectedAppDetailsToCRMA.connectedAppDetails(conApp.Client_Id__c, consumerSecret,UserInfo.getOrganizationName(), userId, session_id);

                if(successMsg == 'SUCCESSFUL'){
                    isSuccess = true;
                }
            }
            ...
        }
        ...
        return rw;
    }
    ...
}

Given that the managed package is generated and we are not specifically defining ConnectedApp, don't see how we can modify the field visibility to private or protected.  Any link or relevant samples are appreciated. Thank you !


text:
Q: how to Convert ajax call values in to C# I am able to get the values in single string by using ajax-call but its returning [object Object]
public static object Details4(string selectedJobSheet)
    {

       foreach (var item in selectedJobSheet)
            {
                Console.WriteLine(item);
            }

    }

when I am using Foreach Loop its returning Different Values ex:'1110'

A: I'm assuming that what you are parsing using AJAX is an object that has been serialised.
Maybe try deserialising the string into an object using
JobSheet Example = JsonConvert.DeserializeObject<JobSheet>(selectedJobSheet);

public class JobSheet
{
    Email {get; set;}
}

https://www.newtonsoft.com/json/help/html/DeserializeObject.htm


text:
Q: How to configure y-axis using seqmtplot in R? I am battling to define the y-axis of a plot using seqmtplot. I followed the steps described in a previous post (How to configure y-axis using seqIplot in R?). However, they do not seem to work for seqmtplot.
The y axis of my plot goes from 0 to 9, so I want it to disply tick marks in intervals of 1 i.e. 0, 1, 2...9
I am running these lines of code.
seqmtplot(LSAY.seq, group= , title="Mean time", yaxis=F)
#axis(2, at=seq(from=0, to=9, by=1))

The problem with this is that the starting point of the y axis (i.e. 0) of my plot moved below the bars displaying the data.
Any ideas how could I fix this?
A second associated question is: how can I access the data underlaying the plot produced by seqmtplot?
Thanks in advance.

A: You can control the length of the y axis with ylim=. For instance using the mvad.seq state sequences defined in How to configure y-axis using seqIplot in R?
seqmtplot(mvad.seq, title="Mean time", ylim=c(0,30))

For controlling the tick marks, you need, as already explained in How to configure y-axis using seqIplot in R?, to

*

*Disable the plotting of the y-axis with yaxis=FALSE

*Disable the legend with withlegend=F.

and you should then plot the legend separately. For example:
par(mfrow=c(1,2))
seqmtplot(mvad.seq, title="Mean time", yaxis=F, ylim=c(0,30), withlegend=FALSE)
axis(2, at=seq(from=0, to=30, by=5))
seqlegend(mvad.seq)

The data plotted are accessible with
seqmeant(mvad.seq)


text:
Q: Stored procedure take 80 seconds to execute I have a Stored Procedure that seems to be taking way too long in comparison to other stored procedures. I have ran a SQL profiler and it is taking upto 80 seconds for this to return data on some occasions via an ASP.NET application, is there something wrong with the stored procedure?
USE [Payments]
GO
/****** Object:  StoredProcedure [dbo].[liftsGetByCustomerNumber]    Script Date: 30/01/2017 15:35:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[liftsGetByCustomerNumber]

    @mprn BIGINT,
    @startDate DATE,
    @endDate DATE,
    @customerNumber nVarChar(50)

AS
BEGIN

SELECT b.[transactionId]
      ,b.[accountGUID]
      ,b.[transactionDate]
      ,b.[transactionAmount]
      ,b.[transactionType]
      ,b.[transactionDeposit]
FROM accounts  as a,transactions as b
where a.GUID = b.accountGUID
and  a.mprn = @mprn
and a.customernumber = @customerNumber
and b.transactionDate between @startdate and @enddate
and b.transactionAmount > 0
and b.transactionType not in ('00','0', '0N', '99')
order by transactionDate, transactionType
END

There are only 80,000 accounts and 200,000 transactions in the table so i cannot foresee this being so slow, what other problems could I check for?


text:
Q: Django unable to hide sensitive variables I have hooked my app to Sentry, and I'm trying to check if I can prevent sensitive varaiables from being logged.
Here's my code:
   @sensitive_variables('user', 'pw', 'cc')
    def get(self, request):
        user = "foobar"
        raise Exception(f"{user}")

My expectation was the it would replace the value of user with  stars (**********), according to the docs: https://docs.djangoproject.com/en/2.2/howto/error-reporting/#filtering-sensitive-information
However, the exception printed out its actual value -- and the sentry logs reflected this.
How do i get it to replace the value of sensitive information with stars?

A: You can either configure Sentry to hide certain fields/values or you can define a filter function
import sentry_sdk

def strip_sensitive_data(event, hint):
    # modify event here
    return event

sentry_sdk.init(
    before_send=strip_sensitive_data
)

This will require a little bit of experimentation to get exactly what you want


text:
Q: Where to specify key and IV value when doing AES encryption/decryption in Android? I am working on AES encryption and decryption in android. I have an Audio file which is encrypted using AES/CBC. I have the key and IV (initialization vector).
I have read some links. From this
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

The SecretkeySpec class used. Where should I use my key and IV values?
And I need to decrypt only first 256 bytes data only. How can I achieve this?

A: In your code snippet, raw is your key (as a byte array):
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
//                                         ^^^ this is your key

Of course, if you have your key as a hex string, you'll need to convert it to bytes.
When encrypting, you can either specify an IV yourself or let a random one be generated. If you want to specify yourself, use:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // adjust padding
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(...));

if you want to use an automatic one, be sure to record which one was chosen by calling
cipher.getIV();

For decryption, you must specify the IV and you do so using an IvParameterSpec, just like with encryption.

And I need to decrypt only first 256 bytes data only. How can I achieve this?

Consider using a CipherInputStream and read only 256 bytes from it.


text:
Q: Cannot write to a file using open() This code always goes into the except section
to_add = "text to add"
try:
    with open ('text.txt','r') as txt:
        txt.write('text to add'+to_add')
        print("done")
    except:
        to_add== 0 or None or ''
        print("unable to write to file")

A: Open file as 'w' not 'r'
with open('test.txt', 'w') as txt:

A: There are a couple fixes required.
try with this snippet:
to_add = "text to add"
try:
  with open ('text.txt', 'w') as txt:    # change the mode to write
      txt.write('text to add' + to_add)  # removing the last char '
  print("done")
except NameError:
  print("unable to write to file")


text:
Q: Unable to ssh via cloud shell terminal [google cloud platform] It's a couple of days I'm trying to login and use my VM via SSH cloud shell as I always did with no issues.
here the error I got
Transferring SSH keys to the VM. The key transfer to project metadata is taking an unusually long time. Transferring instead to instance metadata may be faster, but will transfer the keys only to this VM. If you wish to SSH into other VMs from this VM, you will need to transfer the keys accordingly. Click here to transfer the key to instance metadata. Note that this setting is persistent and needs to be disabled in the Instance Details page once enabled. You can drastically improve your key transfer times by migrating to OS Login.
After digging a bit I found this more detailed error in my connection log:
Mar 5 13:46:02 ubuntu-tw google-accounts: ERROR Exception calling the response handler. [Errno 2] No usable temporary directory found in ['/tmp', '/var/tmp', '/usr/tmp', '/'].#012Traceback (most recent call last):#012 File "/usr/lib/python3/dist-packages/google_compute_engine/metadata_watcher.py", line 200, in WatchMetadata#012

I tried to increase my VM disk space, but the result is the same.
At this point I think the easy way is to simply download my scripts there, but how to access the files?

A: If you want to change or increase the size of your disk first you must create a new instance and recreate the boot disk from a snapshot to resize it.you can do this with this link Recovering an inaccessible instance or a full boot disk

*

*Go to the VM instances creation page

Google Cloud -> Compute Engine ->VM Instances
a. Click the instance name to open the VM instance details page.
b. Click Stop
c. In the Boot disk section, note the boot disk's size and name.

*In the Google Cloud Console, go to the Snapshots creation page.

Google Cloud -> Compute Engine -> Storage -> Snapshots
a. Enter a snapshot Name.
b. Select the boot disk from the Source disk drop-down list.
c. Click Create.

*Go to the VM instances creation page.

Google Cloud -> Compute Engine ->VM Instances

*Enter the instance details.

*Create a new boot disk from the snapshot of the old boot disk.
a. Under Boot disk, select Change.
b. Select Snapshots.
c. Select the snapshot of the old boot disk from the Snapshot drop-down list.
d. Select the Boot disk type.
e. Enter the new size for the disk.
f. Click Select to confirm your disk options.

*Click Create.

*Mount and format the disk.
Another option is attach the disk to a VM : Formatting and mounting a zonal persistent disk
Also I recommended you to do a snapshot or a clone of your disk to avoid the risk of losing the data.
to do this go to disks
Google Cloud -> Compute Engine ->Disks
select your disk and then in the actions toolbar select the option Create Snapshot or Clone disk to do this.
If you only need to resize your disk you can do it in this part: Resizing a zonal persistent disk
go to your disks page
Google Cloud -> Compute Engine ->Disks

*

*Click on your disk name

*Click on the edit button

*in Properties you can change the size of your disk

*Click on Save button
Then you need to restart your VM and your changes there will be applied
Edit 03082021
found this, to access via serial console: Interacting with the serial console
Edit 03092021
for add or remove the SSH keys you need to follow this next steps:
Adding or removing project-wide public SSH keys
To add or remove project-wide public SSH keys from the Cloud Console :

*

*In the Google Cloud Console, go to the metadata page for your project.
Go to the Metadata page

*Under SSH Keys, click Edit.

*Modify the project-wide public SSH keys:
To add a public SSH key, click Add item. A text box opens.
Copy and paste the contents of your public SSH key file into the text box.
Repeat this process for each public SSH key that you want to add.
To remove a public SSH key, click the removal button next to it:

Repeat this process for each public SSH key that you want to remove.

*When you have finished editing the SSH keys, click Save.

and here you create a new SSH key Creating a new SSH key
Open a terminal on your workstation
run this command:
ssh-keygen -t rsa -f ~/.ssh/[KEY_FILENAME] -C [USERNAME]

Replace the following:
[KEY_FILENAME] : the name that you want to use for your SSH key files. For example, a filename of my-ssh-keygenerates a private key file named my-ssh-keyand a public key file named my-ssh
[USERNAME]: the name of the user connecting to the VM. For example, youremail@gmail.com
here is an example:
ssh-keygen -t rsa -f ~/.ssh/my-new-ssh-key -C myficticialmail@gmail.com

The next is choose a passphrase that you remember and confirm the passphrase

*Restrict access to your private key so that only you can read it and nobody can write to it
chmod 400 ~/.ssh/[KEY_FILENAME]
where [KEY_FILENAME] is the name that you used for your SSH key files.
Repeat this process for every user who needs a new key.


text:
Q: Ansible Role include I have a task that can be used by several roles. I added it to lib/mycommontask.yml
On my playbook on roles/my-project/tasks/main.yml I have:
--
- include: lib/mycommontask.yml
  vars:
    project: my-project
    version: "{{ version }}"

- name: ...

When I run the task, I receive the following error
ERROR: Syntax Error while loading YAML script, /home/lg/src/devops/deploy/roles/my-porject/tasks/main.yml
Note: The error may actually appear before this position: line 2, column 10

--
- include: lib/mycommontask.yml
         ^

Can I include inside a role task? How should I do that?

A: For your playbook to be a valid YAML file the 1st line must contain 3 dashes ---, not 2.


text:
Q: PostgreSQL: Updating data on a column of a table with a counter I want to change a column of a table in our database to UNIQUE NOT NULL and first I need to write a postgres sql script to fix current data.
What I need to do basically is find all the instances with column 'code' being NULL or ' ' and change it with a text like this: (1), (2), (3), (4)..
Sameway, I have to find all instances with repeated code and change them into something like this: 'sameCode(1)', 'sameCode(2)', 'equalCode(1)', 'equalCode(2)', 'equalCode(3)'.
Example input       Expected Output
╔════╤═══════╗      ╔════╤══════════╗
║ id │ code  ║      ║ id │ code     ║
╠════╪═══════╣      ╠════╪══════════╣
║ 1  │ null  ║      ║ 1  │ (1)      ║
╟────┼───────╢      ╟────┼──────────╢
║ 2  │ ' '   ║      ║ 2  │ (2)      ║
╟────┼───────╢      ╟────┼──────────╢
║ 3  │ 'FOO' ║      ║ 3  │ 'FOO(1)' ║
╟────┼───────╢      ╟────┼──────────╢
║ 4  │ 'FOO' ║      ║ 4  │ 'FOO(2)' ║
╟────┼───────╢      ╟────┼──────────╢
║ 5  │ 'BAR' ║      ║ 5  │ 'BAR(1)' ║
╟────┼───────╢      ╟────┼──────────╢
║ 6  │ 'BOB' ║      ║ 6  │ 'BOB'    ║
╟────┼───────╢      ╟────┼──────────╢
║ 7  │ 'BAR' ║      ║ 7  │ 'BAR(2)' ║
╚════╧═══════╝      ╚════╧══════════╝

Writing loops with counters and updates using SQL is not one of my strengths and I'm finding it a bit difficult.
Conceptually it is plain an simple. Obtain an ordered list of ids and their codes ordered by code (and NULL and ' ') and then loop over it adding '(++counter)' to the current code text, but restarting the counter every time the code changes. This is going to be slow but it doesn't matter, it is only a one time thing and we're not talking millions of instances here.
DECLARE
    list_of_instances tablename[]; #dunno how to declare an instance
    counter INTEGER;
    oldcode CHARACTER VARYING;
BEGIN
    list_of_instances:=(select id, code from tablename
                       where code is null or code = ' ' or code in
                        (select code from tablename group by code having count(*) > 1)
                       order by codi desc);
    counter:=1;
    oldcode:=tablename[0].code;
    for i in list_of_instances LOOP
        UPDATE tablename SET code=i.code + '(' + cast(counter as text) +')'
        WHERE id=i.id;
        counter:= counter+1;
        IF i.code <> oldcode THEN
            oldcode:=i.code;
            counter:=1;
        END IF;
    END LOOP;
END
$$ language 'plpgsql';

Needless to say this code isn't working.

A: You can generate the number you want using window functions. Apparently you want to treat null and strings with only whitespace as the same thing, so you need to normalize those.
The following query generates the numbers you want, and also supplies the information if a single string occurs more than once:
select id, code,
       row_number() over (partition by coalesce(nullif(trim(code),''),'') order by id) as counter,
       count(*) over (partition by coalesce(nullif(trim(code),''),'')) as num_rows
from tablename
order by id;

With your sample input, this returns:
id | code | counter | num_rows
---+------+---------+---------
 1 |      |       1 |        2
 2 |      |       2 |        2
 3 | FOO  |       1 |        2
 4 | FOO  |       2 |        2
 5 | BAR  |       1 |        2
 6 | BOB  |       1 |        1
 7 | BAR  |       2 |        2

The expression coalesce(nullif(trim(code),''),'') "normalizes" NULL values and strings that only consist of whitespace, e.g. '  ' to an empty string ''.
This can now be used to update the table. As you only want to add the counter to values that occur more than once you need to restrict the update to those:
update tablename as tn
  set code = concat(trim(tn.code), '(', x.counter, ')')
from (
  select id, code,
         row_number() over (partition by coalesce(nullif(trim(code),''),'') order by id) as counter,
         count(*) over (partition by coalesce(nullif(trim(code),''),'')) as num_rows
  from tablename
) x
where x.id = tn.id
  and x.num_rows > 1;

After the update, your sample looks like this:
id | code
---+-------
 1 | (1)
 2 | (2)
 3 | FOO(1)
 4 | FOO(2)
 5 | BAR(1)
 6 | BOB
 7 | BAR(2)

Online example: http://rextester.com/WGAL85544


text:
Q: Can i generate unique text 1 lacs time in javascript through any method who does not need any framework? i have a word from A to Z. all word should in small latter (Capital not include) and  1 to 9 (included all special word who can be used in email address (just for a test)).
how i can generate unique 1 lacs text who never repeat itself. can anyone solve this puzzle.
i want a another thing that all words should not more then 10 char and not should minimum 6 char long

A: Put the characters in an array. Copy the array as the source of a new line. Randomly slice words from the array and put them in the line (use Math.random() * array.length | 0). Keep going for the required number of words.
You can also just use a string and charAt(index) if you only want single characters, but you have to keep cutting out the character that you select which is likely less efficient than using array.slice.
Whatever suits though, since performance is likely irrelevant.


text:
Q: How to integrate eSewa payment gateway for iOS apps? I need to integrate eSewa payment gateway into my app. As such I have gone through several blogs but did not found it helpful. I could not found pod files also. if I go with SDK then I will get compiler 5.1 error?

A: There is no pod for eSewa. You have to download the SDK as zip, drag and drop it on your project as it says on their documentation.
iOS Documentation


text:
Q: Pasar variables de un javascript a un html Buenas,tengo el siguiente script jquery:

Que recoge  los datos de:

prueba 1

prueba 2

Quiero enviar esas variables de javascript a otra página HTML.

A: Pues haces un GET o un POST pasando los datos que quieras al servidor (PHP).
EJEMPLO con POST (mejor para los datos que quieres pasar)
   $(document).ready(function(){
    $("a").on("click", function() {
    var img = $(this).children('img').attr('src');
    var p = $(this).children('p').text();

    $.ajax({
        type: "POST",
        url: '/tu/url',
        data: {'img':img,'p':p},
        success: function(data) {
          //success actions
        },
        dataType: 'json'
      });
    });
   });

Si los campos a pasar los tienes dentro de un formulario, el data puede pasar a ser directamente
data : $('#<mi_form_id>').serialize()

A: Podrías usar la API de LocalStorage para no tener que pasar por PHP.
Por ejemplo :

  //Ahora para llamar a esas variables en otra ventana.

<form action="PaginaDos.html" name="FormEnvioDatos" id="FormEnvioDatos" method="get">

prueba 1

        <input type="hidden" id="Prueba1" name="Prueba1" value="Prueba 1" />

prueba 2

        <input type="hidden" id="Prueba2" name="Prueba2" value="Prueba 2" />

    <input type="hidden" id="imgDesdeLaPagina1" name="imgDesdeLaPagina1" value="" />
</form>

PaginaDos.html


text:
Q: Custom form helpers Is there a way that I can create a custom form helper so that instead of:
special_field_tag :object, :method

I can achieve something like:
form.special_field :method

A: @Tilendor, thanks so much for the pointers. Here is an example of an enum_select form tag helper that uses Rails 4.1 enums to automatically populate the options of a select tag:
# helpers/application_helper.rb
module ApplicationHelper
  class ActionView::Helpers::FormBuilder
    # http://stackoverflow.com/a/2625727/1935918
    include ActionView::Helpers::FormTagHelper
    include ActionView::Helpers::FormOptionsHelper
    def enum_select(name, options = {})
      # select_tag "company[time_zone]", options_for_select(Company.time_zones
      #   .map { |value| [value[0].titleize, value[0]] }, selected: company.time_zone)
      select_tag @object_name + "[#{name}]", options_for_select(@object.class.send(name.to_s.pluralize)
        .map { |value| [value[0].titleize, value[0]] }, selected: @object.send(name))
    end
  end
end

The trickiest construct is @object.class.send(name.to_s.pluralize) which produces a hash of available values (e.g., Company.time_zones). Putting it in helpers/application_helper.rb makes it automatically available. It is used like:
<%= f.label :billing_status %>:
<%= f.enum_select :billing_status %><br />

A: Yes, you can add to the FormBuilder class and get access to the object passed into the form_for.  I've done this for a lot of things: dates, times, measurements, etc.  Heres an example:
class ActionView::Helpers::FormBuilder
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::FormTagHelper
  include ActionView::Helpers::FormOptionsHelper
  include ActionView::Helpers::CaptureHelper
  include ActionView::Helpers::AssetTagHelper

  # Accepts an int and displays a smiley based on >, <, or = 0
  def smile_tag(method, options = {})
    value = @object.nil? ? 0 : @object.send(method).to_i
    options[:id] = field_id(method,options[:index])
    smiley = ":-|"
    if value > 0
      smiley = ":-)"
    elsif smiley < 0
       smiley = ":-("
    end
    return text_field_tag(field_name(method,options[:index]),options) + smiley
  end

  def field_name(label,index=nil)
    output = index ? "[#{index}]" : ''
    return @object_name + output + "[#{label}]"
  end

  def field_id(label,index=nil)
    output = index ? "_#{index}" : ''
    return @object_name + output + "_#{label}"
  end

end

Which you can use like this:
<% form_for @quiz do |f| %>
  <%= f.smile_tag(:score) %>
<% end %>

There are some instance variables created by Rails that you can access in these helper methods:

*

*@object - the model object specified by the form

*@object_name - the class name of the object

*@template - I think its an instance of the ActionView, you can possibly bypass all the includes I added by calling methods on the template.  Haven't tried that yet.

*@options - options passed to the FormBuilder when its created by the form_for call

I wrote the field_id and field_name methods to create these attributes on the HTML input elements the same way the regular helpers do, I'm sure there is a way to tie into the same methods that Rails uses, but I haven't found it yet.
The sky is the limit on what you can do with these helper methods, they simply return strings.  You can create entire HTML tables or pages in one, but you better have a good reason to.
This file should be added in the app/helpers folder

A: Our app was displaying phone numbers in text fields, and we wanted to omit the country code for domestic numbers. I was using form helpers. After reading this and rails source a bit, i came to this solution:
class ActionView::Helpers::FormBuilder
  def phone_text_field name, options = {}
    value = object.public_send(name).to_s
    if value.start_with? "9" # national number
      value = value[1..-1]
      options["value"] = value
    end
    text_field name, options
  end
end

I put this on app/helpers/application_helper.rb and use it like i use text_field() helper. Hope this helps someone.


text:
Q: how to replace multiple special character in a number? I have a number say 2,500.00 and i want to convert the number into 2.500,00. So, we can replace the special character using replace like
var x = 2,500.00;
x.replace(/,/g,".");

and for "Dot" also, we can do it. But in this case, it won't work because when we apply replace function for comma as above, the number will become 2.500.00 and if we apply now, it will become as 2,500,00.
So is there any way to convert 2,500.00 into 2.500,00 ?

A: String.prototype.replace can take a function:
'2,123,500.00'.replace(/[,.]/g, function(c){ return c===',' ? '.' : ','; });

A: You can use:
var x = '2,123,500.00';
var arr = x.split('.');
var y = arr[0].replace(/,/g, '.') + ',' + arr[1];
//=> 2.123.500,00

A: You're in luck, .replace() accept a function as second argument. That function has the matched string as argument and the returned value will be the replace_by value of .replace().
In short, you can simply check what the matched string is and return the right value :

var str = "2,500.00";

var changed_str =  str.replace(/,|\./g, function(old){
    if (old === '.')
        return ',';
    else if (old === ',')
        return '.';
});

document.write(changed_str)

A: Why not use the built-in methods to format your numbers correctly?
Number.toLocaleString() would work just fine here.
If you actually have a number as you said, you can easily achieve this using the right locale. If you have a String representation of your number, you would first have to parse it.

A: This (now) works for any number of commas or dots, even if trailing or leading dots or commas.
HTML:

JS:
var x = '.,2.123,50.0.00.';

var between_dots = x.split('.');
for (var i = 0; i < between_dots.length; i++) {
    between_dots[i] = between_dots[i].replace(/,/g, '.');
}
var y = between_dots.join(',');

document.getElementById('result').innerHTML = y;

Here's the JSFiddle


text:
Q: C# and ASP.NET MVC: Using #if directive in a view I've got a conditional compilation symbol I'm using called "RELEASE", that I indicated in my project's properties in Visual Studio. I want some particular CSS to be applied to elements when the RELEASE symbol is defined, and I was trying to do that from the view, but it doesn't seem to be working.
My view code looks like this (shortened a bit for demo purposes):
<% #if (RELEASE) %>

Banner text here

<% #else %>

Banner text here

<% #endif %>

With this code, and with the RELEASE symbol set, the 'else' code is running and I'm getting a div with the debugBanner class. So it doesn't seem to think that RELEASE is defined. It's worth noting that my actual C# code in .cs files is recognizing RELEASE and runs the correct code. It's only the view that is giving me the problem.
Does anyone have any insight into this? Any help would be appreciated. Thanks.
Clarification: I should have mentioned that this view is already a partial view, and I'll simply render it in pages where I need it. That's because these banners will be on certain pages and not others. So even when rendering it as a partial view via:
Html.RenderPartial("BannerView");
it's not working.

A: @if (HttpContext.Current.IsDebuggingEnabled)
{
    // Debug mode enabled. Your code here. Texts enclosed with <text> tag
}

A: A better, more generic solution is to use an extension method, so all views have access to it:
public static bool IsReleaseBuild(this HtmlHelper helper)
{
#if DEBUG
    return false;
#else
    return true;
#endif
}

You can then use it like follows in any view (razor syntax):
@if(Html.IsReleaseBuild())
...

A: You can use ViewBag instead of viewmodel (but viewmodel-like approach is better) :
Controller :

View :
@{
   bool hideYoutubeVideos = ViewBag.hideYoutubeVideos ?? false;
}

Usage :
@if (!hideYoutubeVideos)
{
     hello youtube
}

Also, be sure, that NIKITA_DEBUG variable exist in build tab of your project :

A: In your model:
bool isRelease = false;

<% #if (RELEASE) %>
    isRelease = true;
<% #endif %>

In your view:
<% if (Model.isRelease) { %>

Banner text here

<% } else { %>

Banner text here

<% } %>

A: I recently discovered that you can simply test:
HttpContext.Current.IsDebuggingEnabled

in Views, which saves you checking symbols in other parts of your app.

A: For me, the code below has worked very well. When the application is Debugging my buttons appear, when is Release, don't.
@if (this.Context.IsDebuggingEnabled)
{
    <button type="button" class="btn btn-warning">Fill file</button>
    <button type="button" class="btn btn-info">Export file</button>
}

A: You can use Debugger.IsAttached like this:
@using System.Diagnostics

@{
    string gridID = $"the-grid-7";

    if (Debugger.IsAttached)
        gridID = gridID + new Random().Next(1, 1000).ToString();

    var loadUrl = ViewBag.LoadUrl;
}

A: Below is the Razor syntax for conditional compiler directives.   It loads the developer version of jquery when DEBUG variable is set in VS profile or web.config.  Otherwise the min version is loaded.
    @{
#if (DEBUG)
    }

    @{
#else
    }

    @{
#endif
    }


text:
Q: Behaviour and Order of evaluation in C#
Possible Duplicate:
C#: Order of function evaluation (vs C)

Code snippet:
i += ++i;
a[++i] = i;
int result =  fun() - gun();
//statement of similar kind

Are their behavior well-defined in C#? In C++, such code invokes undefined/unspecified behavior. Please also quote the relevant sections from the language specification in your response!

A: The key here is the table in "1.4 Expressions", and "7.3.1 Operator precedence and associativity". I won't duplicate the table from 1.4, but to quote 7.3.1:

*

*Except for the assignment operators,
  all binary operators are
  left-associative, meaning that
  operations are performed from left to
  right. For example, x + y + z is
  evaluated as (x + y) + z.

*The
  assignment operators and the
  conditional operator (?:) are
  right-associative, meaning that
  operations are performed from right to
  left. For example, x = y = z is
  evaluated as x = (y = z).

The first is logically expanded (or: use the associativity rules) as:
i = i + ++i;

here, the order (from the table) is pre-increment, then additive, then assignment - so we should expect i to double plus one. And indeed, with i=6, we get 13 as expected.
a[++i] = i;

again from the table, order should be array access, pre-increment, assignment - so I would expect the i+1'th value to be i+1. And indeed, checking:
    int[] a = { 0, 0, 0, 0, 0 };
    int i = 2;
    a[++i] = i;

we do indeed get {0, 0, 0, 3, 0}.
With the last, method invocation takes priority over subtraction, then it is left-to-right; so it should be fun(), gun(), -, assignment.

A: People always get this so confused, which is unfortunate because in C# it is extremely straightforward. The rules are:

*

*subexpressions are observed to be evaluated left to right when observed from the executing thread, period, end of story. (Order of evaluation is permitted to be observed to be different by some other thread if some other thread is watching the side effects.)

*the order in which the operators execute is determined by their precedence and associativity.
Those are the only two relevant rules, and they completely define the behaviour of the code you give. In
i += ++i;

first i is evaluated, then ++i is evaluated, and then the += is executed.
a[++i] = i;

First 'a' is evaluated, then ++i is evaluated, then the indexing operator runs, then i is evaluated, then the assignment happens.
int result =  fun() - gun();

first result is evaluated, then fun, then gun, then the subtraction, then the assignment.

Please also quote the relevant sections from the language specification in your response!

You are perfectly capable of looking in the table of contents. It's not hard to find.


text:
Q: libucrl failed to check server certificate I am using libcurl (in C) to login to a secure site (https). So far it was working fine. Since yesterday it is not able to login. The code looks as below.
bool login(char *user, char *password)
{
    bool result = false;
    CURL * curl = NULL;
    char errbuf[CURL_ERROR_SIZE];
    char status_text[1024];
    CURLcode res;
    long resp_code = 0;
    int index;

    /* These fields should be collected from license file */
    char *user_field = "name";
    char *password_field = "pass";

    char *form_id_field = "form_id";
    char *form_id = "user_login";

    char *link = "https://example.com/user/login";

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl == NULL) goto on_error;

    curl_easy_reset(curl);

    curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/4.0");
    curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)NULL);

    curl_easy_setopt(curl, CURLOPT_URL, link);
    res = curl_easy_perform(curl);

    if(res == CURLE_OK)
    {
        curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(curl, CURLOPT_REFERER, link);

        /* Data should be "name=user&pass=password&form_id=user-login" */
        index = sprintf(status_text, "%s=%s&%s=%s&%s=%s",
            user_field, user, password_field,
            password, form_id_field, form_id);

        *(status_text + index) = 0x0;

        resp_code = 0;
        res = CURLE_ABORTED_BY_CALLBACK;

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, status_text);
        res = curl_easy_perform(curl);
        curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &resp_code);

        if((resp_code == 200) && (res != CURLE_ABORTED_BY_CALLBACK))
        {
            result = true;
        }
        else
        {
            result = false;
        }
    }

on_error:
    if(curl)
    {
        curl_easy_cleanup(curl);
        curl_global_cleanup();
        curl_global_cleanup();
    }

    return result;
}

While curl_easy_perform is executed it fails. The errbuf shows error like "server certificate verification failed. cafile /etc/ssl/certs/ca-certificates.crt crlfile none". I understand it is somewhat problematic with /etc/ssl/certs/ca-certificates.crt file, but I did not change anything.
What may be the issue here, any hint to fix this, highly appreciated.

A: It is more a hint than an answer but I don't have enough rep points to comment.

Since yesterday it is not able to login

This might be connected to the fact that Sectigo's legacy AddTrust External CA Root certificate expired on May 30, 2020 https://support.sectigo.com/articles/Knowledge/Sectigo-AddTrust-External-CA-Root-Expiring-May-30-2020
From the link above

Certificates for your site are issued from a "chain" of issuing or "intermediate" CA that completes a path back to these trusted root certificates.

If I understand the above statement correctly, AddTrust External CA Root certificate is probably one of the certs in chain thus validation fails - at least for some clients.
EDIT
What also worked for me is this https://www.agwa.name/blog/post/fixing_the_addtrust_root_expiration

*

*edit /etc/ca-certificates.conf and put a bang/exclamation mark (!) before mozilla/AddTrust_External_Root.crt

*Run update-ca-certificates


text:
Q: Tensoring locally free sheaves - global sections Suppose you two locally free sheaves $L,M$ on an integral scheme $X$ over $k$. Is it true that the map
$L(X) \otimes M(X) \to ( L \otimes M)(X)$
Is injective? The map is formally induced by the general map from a presheaf to its sheafification, recalling that the tensor of two sheaves is the sheafification of the presheaf which is "openwise" $U \mapsto L(U)\otimes M(U)$.
Concretely, is just thinking a product of sections in the tensor sheaf.
My try:

*

*Let U be a open such that both L,M are free. Then the tensor sheaf coincides with the tensor presheaf, because for a ring $A$, $f \in A$, and $r,s$ natural holds
$(A^{rs})_f \simeq A^r_f \otimes A^s_f $
By the exactness of localisation.

*Suppose $\sum s_i \otimes t_i $ goes to zero. Then it's stalks are everywhere null, and in particular by 1 there exist an open set $U$ such that $\sum s_i \otimes t_i | U = 0$.
Recall that $X$ is integral, thus $U$ is dense.

*I would like now to conclude the restriction map to $U$ is injective, because is the tensor of two injective maps over $k$. Is is true?
Best,
Andrea

A: This is not injective in general. Consider $X = \Bbb P^1_k$, $L = M = O_X(1)$. Then $L(X) = M(X) \cong k^2$ so that $L(X) \otimes_k M(X) \cong k^4$, but $L \otimes_{O_X} M \cong O_X(2)$ has a $3$-dimensional space of global sections.
A presheaf $F$ is said to be separated when the sheafification map $F \to F^+$ is injective. The example above is a non-separated presheaf $U \mapsto L(U) \otimes_{O_X(U)} M(U)$. See also here.

Let me call $f$ the natural map $L(X) \otimes_{O_X(X)} M(X) \to (L \otimes_{O_X} M)(X)$.
In your second step, when you are writing $\sum s_i \otimes t_i | U = 0$, I guess that you mean
$$\mathrm{Res}_U^X \left[ f\left(\sum_i s_i \otimes t_i \right)\right] = 0$$
But even if the restriction map $\mathrm{Res}_U^X$ was injective (as you mention in your 3rd point), you've proven nothing, since you don't know if $f$ is injective. This is precisely what you are trying to prove. Unless I misunderstood your reasoning.


text:
Q: get paid doing smth, get paid for doing smth, get paid to do smth I didn't find anything helpful in the dictionaries.
What is the correct way to use "get paid" when explaining what the person does to earn money? They earn money by doing something like training/coaching people...
You can get paid for coaching kids.
You can get paid coaching kids.
You can get paid to coach kids.


text:
Q: Push notifications not coming using Android 8.1 Oreo using FCM I am working on FCM push notifications. It is working fine till Android O lesser versions. I have reviewed Android Docs and did Channels in push notifications as well, but problem is that push is not coming in my CustomPushReceiver. For lower versions it is working perfectly fine. My custom push receiver along with manifest codes are given below:
public class CustomPushReceiver extends ParsePushBroadcastReceiver {

    int importance = NotificationManager.IMPORTANCE_HIGH;
    private SharedPreferences prefs ;
    Boolean languageBoolean = true;

    public CustomPushReceiver() {
        super();
        Log.e("CustomPushReceiver","Come to this portion");
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.e("onReceive","Come to this portion");
    }

    @Override
    public void onPushReceive(Context context, Intent intent) {

        Log.e("onPushReceive","Come to this portion");
        if (intent == null)
            return;
        try {
            String action = intent.getAction();
            JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
            if (action.equalsIgnoreCase("com.parse.push.intent.RECEIVE")) {
                if (json.has("alert"))
                {
                    String message = json.getString("alert");

                    localPushNotifications26GreaterAPI(context, message, json);
                }
            }
        } catch (JSONException e) {
        }
    }

    @Override
    protected void onPushDismiss(Context context, Intent intent) {
        super.onPushDismiss(context, intent);
        Log.e("onPushDismiss","Come to this portion");
    }

    @Override
    protected void onPushOpen(Context context, Intent intent) {
        super.onPushOpen(context, intent);
        Log.e("onPushOpen","Come to this portion");
    }

    public void localPushNotifications26GreaterAPI(Context context, String message, JSONObject jsonObject){

        Log.e("localPushNoti26API","Come to this portion");

        try {
            if (ParseUser.getCurrentUser() != null) {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

                    Intent intent = new Intent(context, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

                    // The id of the channel.
                    String id = "my_channel_01";
                    CharSequence name = "com.dcas.responder";
                    String description = "Description";

                    NotificationChannel mChannel = new NotificationChannel(id, name, importance);
                    mChannel.setDescription(description);
                    mChannel.enableLights(true);
                    mChannel.setLightColor(Color.RED);
                    mChannel.enableVibration(true);
                    mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                    mNotificationManager.createNotificationChannel(mChannel);
                    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    int notifyID = 1;
                    String CHANNEL_ID = "my_channel_01";

                String contentTitle = "", contentText ="", messageText ="";
                    if (languageBoolean == true) {
                        contentTitle =  "Dubai Corporation Ambulance Services";
                        contentText  =  "Emergency Request";
                        messageText  =  message;
                    }else{
                        contentTitle =  context.getString(R.string.dubai_corporation_for_ambulance_services);
                        contentText  =  context.getString(R.string.emergency_request);
                        messageText  =  context.getString(R.string.press_here_to_get_medical_help_in_minutes);
                    }

                    Notification notification = new Notification.Builder(context, CHANNEL_ID)
                            .setContentTitle(contentTitle)
                            .setContentText(contentText)
                            .setStyle(new Notification.BigTextStyle().bigText(messageText))
                            .setContentIntent(contentIntent)
                            .setSmallIcon(R.drawable.push_icon)
                            .setChannelId(CHANNEL_ID)
                            .build();
                    notification.flags |= Notification.FLAG_AUTO_CANCEL;

                    mNotificationManager.notify(notifyID, notification);
                } else {
                    localPushNotifications26LowerAPI(context , message);
                }

            }
        }catch(Exception exp){
            exp.getMessage();
        }

    }

    public void localPushNotifications26LowerAPI(Context context, String message){

        Log.e("localPushNotiLowAPI","Come to this portion");

        if (ParseUser.getCurrentUser() != null) {
            Intent intent = new Intent(context, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder b = new NotificationCompat.Builder(context);

            String contentTitle = "", contentText ="", messageText ="";
            if (languageBoolean == true) {
                contentTitle =  "Dubai Corporation Ambulance Services";
                contentText  =  "Emergency Request";
                messageText  =  message;
            }else{
                contentTitle =  context.getString(R.string.dubai_corporation_for_ambulance_services);
                contentText  =  context.getString(R.string.emergency_request);
                messageText  =  context.getString(R.string.press_here_to_get_medical_help_in_minutes);
            }

            b.setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.push_icon)
                    .setTicker(contentText)
                    .setContentTitle(contentTitle)
                    .setContentText(messageText)
                    .setContentIntent(contentIntent)
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                    .setContentIntent(contentIntent)
                    .setContentInfo("Info");

            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(1, b.build());

        }
    }
}

My Manifest file where I am declaring my FCM settings and CustomPushReceiver:
<receiver
            android:name="receivers.CustomPushReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="com.parse.push.intent.RECEIVE" />
                <action android:name="com.parse.push.intent.DELETE" />
                <action android:name="com.parse.push.intent.OPEN" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="com.parse.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.dcas.responder" />
            </intent-filter>
        </receiver>

<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <meta-data android:name="com.parse.push.gcm_sender_id"
            android:value="id:5562400#####" />

My Application class where I am initializing and subscribing to parse push channel:
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
        installation.put("GCMSenderId", "5562400#####");
        installation.saveInBackground();

ParsePush.subscribeInBackground("dcas" + ParseUser.getCurrentUser().getObjectId(), new SaveCallback() {
                                @Override
                                public void done(ParseException e) {
                                    if(e==null){
                                        Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
                                        startActivity(intent);
                                        finish();
                                    }
                                }
                            });

This is working perfectly fine on Android 27 lower versions and only some times it starts working on Android 27 version too which is very weird without any reason.