text:
Q: Make changes in UI work in background (with ProgressDialog)? I am working on an app where in one of the activity different views are added into a ViewGroup, this process takes a while starting up so I wanted to run a progress Dialog in foreground while the UI could setUp in background .
What I have Tried
I tried using
1.AsyncTask but it gave Exceptions .
2. while using threads and runnable() I am getting InvocationTargetException.
I wanted to know what could be the best possible approach to this?

A: You cannot make UI changes from a background task.
If you use an AsyncTask, you can only update the UI from the onPostExecute() or onProgressUpdate() methods.
The other option is to use a Handler, which (amongst others) can execute Runnables on the main thread.
Edit:
The Handler has to be instantiated on the main thread. From any thread, you could use post(Runnable) or sendMessage(Message) and various variations of them. For sendMessage() you would need to override handleMessage(Message).

A: Can you insert some of your code? It would help a lot determining the cause of the problem.
But you need to know that you can't change the UI from a background thread. It will give you an exception.
What you can do is write an AsyncTask, which initializes the objects and assigns values to them in its doInBackground method and then modifies the UI thread in its onPostExecute method.
It would look something like this:
private class myAsyncTask extends AsyncTask<Void,Void,Void>
{
  @Override
  protected void onPreExecute()
  {
   //show progress dialog
  }

  @Override
  protected Void doInBackground(Void... arg0)
  {
    //init objects, and do stuff with them
    return null;
  }

  @Override
  protected void onPostExecute(Void result)
  {
    //make changes to UI thread
    //close progress dialog
  }

}

A: Juste keep your AsyncTask and update UI in onPostExecute instead to do it in doInBackground.


text:
Q: How to remove warning messages in R Markdown document? I have an R Markdown document, which takes a really long time to knit because of heavy computations. Mistakenly there are some code chunks where I forgot to put warnings=False before knitting the document. Is their any way to remove those warning messages, without knitting the document again??
Is there any way to remove warnings from the Markdown document and rebuild an html file from the markdown. I don't want to execute the code again.
Need the similar changes in the markdown document as well.

A: *

*To fix the .Rmd to stifle all warnings entirely, in the initial setup chunk in the document, add ```{r setup, warning=FALSE}

*For your post-knit HTML document you can always just open it in the browser, like chrome for instance, right-click on the warning then choose select element to see the HTML that makes up the displayed warning and then remove that from the HTML file without having to knit the R Markdown again.

A: If you want to turn off messages and warnings in the whole document you can use this code chunk right after the yaml portion.
```{r setup, include=FALSE}
knitr::opts_chunk$set(warning = FALSE, message = FALSE)
```

redpajama_set_name: RedPajamaStackExchange


text:
Q: Class to JSON object using ArraySegment I am trying to figure out this problem,
I want to transfer Json object using ArraySegment
my JSON Data is
in this format
{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

I have used this tool to create specified class like
public class Employee
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

public class RootObject
{
    public List<Employee> employees { get; set; }
}

now I am inserting data into object like this
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Employee>
          {
             new Item { firstName="abc", lastName="xyz"},
             new Item { firstName="pqr", lastName="stu"}
          };

but now I am facing problem, I don't know how to send it using
websocket
through this
ArraySegment<byte> max = new ArraySegment<byte>(, , );
await webSocket.SendAsync(max, WebSocketMessageType.Text, true, CancellationToken.None);

A: You need to serialize the objectToSerialize into a buffer of bytes first
var data = JsonConvert.SerializeObject(objectToSerialize);
var encoded = Encoding.UTF8.GetBytes(data);
var buffer = new ArraySegment<Byte>(encoded, 0, encoded.Length);
await webSocket.SendAsync.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);


text:
Q: Why ARMTemplateParametersForFactory.json do not get updated in Azure DevOps for Azure Data Factory I need Azure DevOps CI/CD Tips for Azure Data Factory.
I have Azure Data Factory which has Web Activity to Post json to Azure LogicApps. (ADF Web->Logic Apps) I have made URL as parameter in Web Activity.
Parameter in ADF Pipeline: MyReport_LogicAppURL

I have edited ARM Template
Manage->ARM Template->Edit Parameter Configuration
"Microsoft.DataFactory/factories/pipelines": {
    "properties": {
      "parameters": {
        "MyPremLoad_OnPremDb": {
          "defaultValue": "="
        },
        "MyReport_LogicAppURL": {
          "defaultValue": "="
        }
      }
    }
  },

I Save it and then publish.
However I don't see any updates in ARMTemplateParametersForFactory.json in Git Repo
Why ARMTemplateParametersForFactory.json do not get updated in Azure DevOps for Azure Data Factory? I have successfully done this in other environments. Also other person has successfully deployed MyPremLoad_OnPremDb in past.

A: Maybe if you have a non-standard git hierarchy, you should find or place the
arm-template-parameters-definition.json in Datafactory folder or the root folder.
Once you have made changes to parameter definitions, save and refresh the browser to reload the configurations.
If you still don't see the changes, i would suggest deleting arm-template-parameters-definition.json from your publish branch manually and save parameter definitions > refresh browser > publish from ADF portal.
Make sure you have a right json structure after the edit, Do share if you see any particular errors.
"Microsoft.DataFactory/factories/pipelines": {
    "properties": {
        "parameters": {
            "MyPremLoad_OnPremDb": {
                "defaultValue": "="
            },
            "MyReport_LogicAppURL": {
                "defaultValue": "="
            }
        }
    }
},

A: I added default value to parameter and it got fixed. Thank you KarthikBhyresh-MT for your support.


text:
Q: How does data-toggle work with html5 and bootstrap? I'm trying to do a simple dropdown menu on my website but my ide says that the data-toggle attribute is not supported by html5 on the  tags.
I'm using bootstrap with jquery here are my scripts. Help!

<link href="Content/bootstrap.css" rel="stylesheet" />
<link href="Content/newscarousel.css" rel="stylesheet" />
<link href="Content/custom.css" rel="stylesheet" />

                            About

About

Partners

To Request Funding

Testimonies

A: try this

<link href="Content/bootstrap.css" rel="stylesheet" />
<link href="Content/newscarousel.css" rel="stylesheet" />
<link href="Content/custom.css" rel="stylesheet" />

                            About

About

Partners

To Request Funding

Testimonies

Main reason:  the main reason is that you did not include jquery file in your code...


text:
Q: Почему сессия обновляется при вводе пароля? До ввода пароля юзер выбирает свое имя, год, и т.д. из списка. Все это сохраняется в сессий. Но почему то сессия обновляется при вводе пароля и IP и т.д. теряется и возвращается "Вы заблокированы на время".
Первый файл
 <?
    //Устанавливаем время жизни кукисов в 30мин
    $min = 30;
    ini_set('session.gc_maxlifetime', $min*60);
    ini_set('session.cookie_lifetime', $min*60);

    session_start();

    //Проверка входящих данных на нежелательные данные
    //Защита от хакеров :)

function secureSuperGlobalGET(&$value, $key)
{
    $_GET[$key] = htmlspecialchars(stripslashes($_GET[$key]));
    $_GET[$key] = str_ireplace("script", "blocked", $_GET[$key]);
    $_GET[$key] = mysql_escape_string($_GET[$key]);
            if (strpos($key, "[") > 0)      $_GET[$key] = 0;
    return $_GET[$key];
}

function secureSuperGlobalPOST(&$value, $key)
{
    $_POST[$key] = htmlspecialchars(stripslashes($_POST[$key]));
    $_POST[$key] = str_ireplace("script", "blocked", $_POST[$key]);
    $_POST[$key] = mysql_escape_string($_POST[$key]);
            if (strpos($key, "[") > 0)      $_POST[$key] = 0;
    return $_POST[$key];
}
array_walk($_GET, 'secureSuperGlobalGET');
array_walk($_POST, 'secureSuperGlobalPOST');

Другой файл:
    $id_user = (integer) $_POST["id_user"];
    $password = (integer) $_POST["p"]; //да, да в паролях только цифры

    if(!$_SESSION["IP"])
    {
            $block_client = $_SESSION["BLOCK"];
            $ip = getVisitorIP(); //Взять ip клиента
            $_SESSION[$ip] = session_id();
            $_SESSION["IP"] = $ip;
    }

    //Обработка введенного пароля
    if ($id_user AND $password AND !$block_client AND (isset($_COOKIE["PHPSESSID"]) ) AND ($_SESSION[$ip]== session_id())) {

            $sql_password = mssql_fetch_row(mssql_query("SELECT USER.PASS FROM USER WHERE USER.ID_USER = '$id_user' "));

            if ($password == $sql_password[0]) {

                    $_SESSION["user_id"] = $id_user;

                    echo '{"redirect": "reports.html"}'; //https://stackoverflow.com/a/1534662
            } else {

                    if ($ip == $_SESSION["IP"]) {
                            $_SESSION["TIMES"] = $_SESSION["TIMES"] + 1;

                            if($_SESSION["TIMES"] == 10){ //Если не правильно ввели пароль 10раз
                                    $_SESSION["BLOCK"] = 1;   //то заблокируем клиент на сколько столько время жизни кукисов
                            }
                    }
                    JsonError("Не верный пароль");
            }
            exit;
    }
     elseif ($id_user AND !$password)
    {
             JsonError("Пароль не введен");
    }
     else
    {
            $_SESSION["BLOCK"] = 1;
            JsonError("Вы заблокированы на время");
    }

?>

http://pastebin.com/JR87Zmxi

A: Проверь условие:
if ($id_user AND $password AND !$block_client AND (isset($_COOKIE["PHPSESSID"]) ) AND ($_SESSION[$ip]== session_id()))

UPDATE:
Если $ip это адрес клиента то его нельзя использовать как ключ, тем более что в сессии адрес записан как
        $_SESSION["IP"] = $ip;


text:
Q: Images not loading either on direct url or via twig asset function in ezpublish eZPublish guide: https://doc.ez.no/display/DEVELOP...p+2+-+Customizing+the+general+layout
I am entering the latest version of eZ after having spent some time a few years ago in version 4.
I have configured a vhost with the sample file from: https://github.com/ezsystems/ezplatform/tree/master/doc/apache2
I have now followed the bike guide and successfully got the system to use the correct css and js from the unzipped  assets folder which is now sitting in 'web/assets'. The page loads with the correct CSS and the layout of the page look good.
The guide instructs to load the images using the function asset:

The outcome of the above twig snippet is:

The image however refuses to load and will only r

No route found for "GET /assets/images/logo_just_letters.png" (from
  "http://john.ezpublish.net/") 404 Not Found - NotFoundHttpException 1
  linked Exception: ResourceNotFoundException »

Is there a setting somewhere that should be changed, or vhost config change?

A: try to add
RewriteRule ^/assets/ - [L]

under the
RewriteRule ^/bundles/ - [L]

in your vhost (see example) and restart the apache server.


text:
Q: How to send image from database as email attachment using android I need to send an image that users puts into SQLite DB as an attachment via email.
Currently the image is stored as byte[] and with this code I can decode it:
Image dbHelper = new Image(getApplicationContext());
        dbHelper.open();
        byte[] bytes = dbHelper.retreiveImageFromDB();
        dbHelper.close();
        DbBitmapUtility bmpU = new DbBitmapUtility();
        bmpU.getImage(bytes);

//// METHODS
public byte[] retreiveImageFromDB() {
        Cursor cur = mDb.query(true, IMAGES_TABLE, new String[]{IMAGE,},
                null, null, null, null,
                IMAGE_ID + " DESC", "1");
        if (cur.moveToFirst()) {
            byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE));
            cur.close();
            return blob;
        }
        cur.close();
        return null;
    }

public Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }

Now I need to somehow put the image as an email attachment.
How can I do that?


text:
Q: Detect when no buttons are being pushed PyQt I have a GUI that is controlling a device over USB.
The way I have it set up is with basically two buttons, forward and back, and while the button is pressed that function is transmitted to the motor, when the button is released, the off signal is triggered once.
    def on_release():
        print('Off')
        self.off()

    def on_click():
        print('forward')
        self.forward()
    button = QPushButton('Cut', self)
    button.move(100,70)
    button.pressed.connect(on_click)
    button.released.connect(on_release)

    def on_click():
        print('back')
        self.back()
    button = QPushButton('back', self)
    button.move(200,70)
    button.pressed.connect(on_click)
    button.released.connect(on_release)

I've recently encountered an interesting failure mode where if the USB connection is paused (in my case I was using GDB and hit a breakpoint, released the button, then released the breakpoint) at the moment the button is released, the kill signal is never sent and the motor will continue going back or forward forever. (It can be killed by either clicking one of back or forward and releasing, or by killing USB entirely")
I already have protections in place (a threaded heartbeat signal) for turning off the motor in the condition that a USB connection is severed but I'd like to make this fail a little more safely in case that one particular USB off transmission were to fail.
Is there a way for me to check if no buttons are pressed so I can use this to trigger the off signal?

A: Learning material from tjmarkham stepper.py script at [https://github.com/tjmarkham/python-stepper] for a raspberry Pi which can be put behind your buttons:
#CURRENT APPLICATION INFO
#200 steps/rev
#12V, 350mA
#Big Easy driver = 1/16 microstep mode
#Turn a 200 step motor left one full revolution: 3200

from time import sleep
import RPi.GPIO as gpio #https://pypi.python.org/pypi/RPi.GPIO
#import exitHandler #uncomment this and line 58 if using exitHandler

class stepper:
    #instantiate stepper
    #pins = [stepPin, directionPin, enablePin]
    def __init__(self, pins):
        #setup pins
        self.pins = pins
        self.stepPin = self.pins[0]
        self.directionPin = self.pins[1]
        self.enablePin = self.pins[2]

        #use the broadcom layout for the gpio
        gpio.setmode(gpio.BCM)

        #set gpio pins
        gpio.setup(self.stepPin, gpio.OUT)
        gpio.setup(self.directionPin, gpio.OUT)
        gpio.setup(self.enablePin, gpio.OUT)

        #set enable to high (i.e. power is NOT going to the motor)
        gpio.output(self.enablePin, True)

        print("Stepper initialized (step=" + self.stepPin + ", direction=" + self.directionPin + ", enable=" + self.enablePin + ")")

    #clears GPIO settings
    def cleanGPIO(self):
        gpio.cleanup()

    #step the motor
    # steps = number of steps to take
    # dir = direction stepper will move
    # speed = defines the denominator in the waitTime equation: waitTime = 0.000001/speed. As "speed" is increased, the waitTime between steps is lowered
# stayOn = defines whether or not stepper should stay "on" or not. If stepper will need to receive a new step command immediately, this should be set to "True." Otherwise, it should remain at "False."

    def step(self, steps, dir, speed=1, stayOn=False):
        #set enable to low (i.e. power IS going to the motor)
        gpio.output(self.enablePin, False)

        #set the output to true for left and false for right
        turnLeft = True
        if (dir == 'right'):
            turnLeft = False;
        elif (dir != 'left'):
            print("STEPPER ERROR: no direction supplied")
            return False
        gpio.output(self.directionPin, turnLeft)

        stepCounter = 0

        waitTime = 0.000001/speed #waitTime controls speed

        while stepCounter < steps:
            #gracefully exit if ctr-c is pressed
            #exitHandler.exitPoint(True) #exitHandler.exitPoint(True, cleanGPIO)

            #turning the gpio on and off tells the easy driver to take one step
            gpio.output(self.stepPin, True)
            gpio.output(self.stepPin, False)
            stepCounter += 1

            #wait before taking the next step thus controlling rotation speed
            sleep(waitTime)

        if (stayOn == False):
            #set enable to high (i.e. power is NOT going to the motor)
            gpio.output(self.enablePin, True)

print("stepperDriver complete (turned " + dir + " " + str(steps) + " steps)")

teststepper.py:
from Stepper import Stepper

#stepper variables
#[stepPin, directionPin, enablePin]
testStepper = Stepper([22, 17, 23])

#test stepper
testStepper.step(3200, "right"); #steps, dir, speed, stayOn


text:
Q: Azure ARM template with PowerShell deployment fails on the NIC with an InvalidResourceReference error I have an Azure generated template and parameters file for creating a simple VM. It works fine with the supplied deploy.ps1. I've updated the parameters file to create another VM in a new resource group, but it now fails with an "Invalid resource reference" error.
I've reviewed the template, but not changed it. I can see there's nothing hard-coded. The deployment creates the Network Security Group and the public IP address but then fails on the NIC. I've checked for region issues, but can't see any.
The NIC part of the template looks like this:
"variables": {
        "nsgId": "[resourceId(resourceGroup().name, 'Microsoft.Network/networkSecurityGroups', parameters('networkSecurityGroupName'))]",
        "vnetId": "[parameters('virtualNetworkId')]",
        "subnetRef": "[concat(variables('vnetId'), '/subnets/', parameters('subnetName'))]"
    },
    "resources": [
        {
            "type": "Microsoft.Network/networkInterfaces",
            "apiVersion": "2018-10-01",
            "name": "[parameters('networkInterfaceName')]",
            "location": "[parameters('location')]",
            "dependsOn": [
                "[concat('Microsoft.Network/networkSecurityGroups/', parameters('networkSecurityGroupName'))]",
                "[concat('Microsoft.Network/publicIpAddresses/', parameters('publicIpAddressName'))]"
            ],
            "properties": {
                "ipConfigurations": [
                    {
                        "name": "ipconfig1",
                        "properties": {
                            "subnet": {
                                "id": "[variables('subnetRef')]"
                            },
                            "privateIPAllocationMethod": "Dynamic",
                            "publicIpAddress": {
                                "id": "[resourceId(resourceGroup().name, 'Microsoft.Network/publicIpAddresses', parameters('publicIpAddressName'))]"
                            }
                        }
                    }
                ],
                "networkSecurityGroup": {
                    "id": "[variables('nsgId')]"
                }
            }
        },

The error message is:

New-AzResourceGroupDeployment : 17:11:30 - Resource
  Microsoft.Network/networkInterfaces 'newRHserverNIC' failed with
  message '{   "error": {
      "code": "InvalidResourceReference",
      "message": "Resource /subscriptions//resourceGroups/Scripttest2/providers/Microsoft.Network/virtualNetworks/NewvirtNet/subnets/default
  referenced by resource /subscriptions//resourceGroups/Scripttest2/providers/Microsoft.Network/networkInterfaces/newRHserverNIC
  was not found. Please make sure that the referenced resource exists,
  and that both resources are in the same region.",
      "details": []   } }'

A: well, its either of two, subnet is in a different region\different resource group\different subscription or called differently.

A: Don't ignore <azuredeploy.parameters.json> file.
In my case, this file was faulty. It had a different Location than the current Resource Group, because I extracted it from a previous execution.


text:
Q: Flutter How Can I Show Dialog on Another Page I want to show dialog when I press the button I want to be navigated to another page and then I want to show a dialog indicating that I have been navigated to that page.
So I try this code;
InkWell(
                          onTap: () async {
                            Navigator.pushAndRemoveUntil(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => BottomBarD()),
                                (route) => false);
                            Dialog(
                              child: Container(
                                child: Column(
                                  children: [
                                    Text(
                                      "Navigated to Another Page",
                                      style: TextStyle(
                                        fontFamily: "Quando",
                                        fontWeight: FontWeight.w500,
                                        fontSize: 15,
                                      ),
                                    ),
                                    TextButton(
                                      onPressed: () async {
                                        Navigator.of(context).pop();
                                      },
                                      child: Text(
                                        "Okey",
                                        style: TextStyle(
                                          fontFamily: "Quando",
                                          fontSize: 15,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                  colors: [Colors.orangeAccent, Colors.red],
                                  begin: Alignment.bottomRight,
                                  end: Alignment.centerLeft),
                              borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(112.0),
                                topLeft: Radius.circular(112.0),
                                bottomRight: Radius.circular(112.0),
                                topRight: Radius.circular(112.0),
                              ),
                            ),
                            height: MediaQuery.of(context).size.height * 0.065,
                            width: MediaQuery.of(context).size.width * 0.80,
                            margin: EdgeInsets.only(
                              top: 30.0,
                              bottom: 10.0,
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  child: Text(
                                    "Navigate and ShowDialog Button",
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 17,
                                        fontFamily: "Quando"),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),

But when I press the okay button in the dialog, the okay button does not work and it gives a that error;
Unhandled Exception: Null check operator used on a null value

A: This worked fine on DartPad:
  void _incrementCounter() {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (c) => Scaffold(body: Text('new page'))
    ));
    showDialog(context: context,
      builder: (c) => AlertDialog(content: Text('the dialog in it'),)
    );
  }

Notice that .push() returns a Future immediately. The dialog you show after that is shown on top of page 2, since we don't await for it.

A: I put the Dialog in my second page BottomBarD() and I displayed it based on a conditional field every time the BottomBarD() loads.


text:
Q: RTP/RTSP library usable in Java I'm looking to write a voip application, I know JMF has RTP code but it's old and 32bit only. Is there a robust library that does RTP/RTSP that can be used with java?
Thanks

A: no way JMF - its 10 years out of date
list java RTP RTSP packages:
RTSPClientLib.tar.gz  on code.google
http://github.com/brunodecarvalho/efflux
i used the efflux on a java project and it was worth the time learning his packages. The combined netty/efflux is very robust on the variety of RFC's involved in networking underlying RTSP/RTP.
i think i have an eclipse project archived somewhere using efflux for alot of RTSP dialog type stuff.


text:
Q: Stata esttab twoway tabulate labels Say that I have this dataset:
webuse union, clear

I want to run a tabulation:
tab union smsa

I want to export it to a .tex file and have it look similar to the above tabulation. Is there a way to have code similar to the following display the labels (union worker and lives in SMSA) automatically instead of having to hard code them in?
eststo clear
eststo: estpost tab union smsa
esttab est1 using "${path}/example.tex", cell(b) unstack noobs ///
    replace nonum collabels(none) eqlabels(, lhs("union worker")) ///
    mtitles("lives in SMSA")

A: Can you clarify what you mean by "automatically"? I can't test this because those variables are not in the auto dataset when I load it, but you could call the variable label macro instead of the variable label explicitly:
eststo clear
eststo: estpost tab union smsa
esttab est1 using "${path}/example.tex", cell(b) unstack noobs ///
    replace nonum collabels(none) eqlabels(, lhs("`:variable label union'")) ///
    mtitles("`:variable label smsa'")

Try help extended_fcn for details.


text:
Q: "WebClient.DownloadFile" throws an error when I pass arguments to it but works fine if I hardcode the values I have a C# exe that uses .NET 4.6.1 framework. I launch this exe from a C++ exe as that is the requirement. It worked before but it suddenly stopped working the way it was supposed to.
I launch the exe with 5 parameters. I checked the value and the length of the arguments received, they all appear to be correct when the C# exe receives it but when it comes to the DownloadFile method it seems to throw an exception.
On the other hand, if I hardcode the values or run the exe in the command prompt and pass the arguments to it seems to work fine.
As soon as launch it from the C++ exe it writes this from the stack trace to the log that I'm printing it into

username is: abc uname length is: 3| password is: abc@123 pass length
is: 7| patch download from path is: \10.1.1.119\Backup_share\patch
testing\Skype-8.81.0.268.zip FileToDownload length is: 60| patch
download to path is: E:\Test\Patch.zip localDestinationFilePath length
is: 17
System.Net.WebException Exception in DownloadPFile(
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at
IPMPlusAlternatePatchDownloader.IPMPlusPatchDownloader.DownloadPFile(String userName, String password, String FileToDownload, String localDestinationFilePath)

Here is the code I'm using
static void Main(string[] args)
{
     PacthDownload.DownloadPFile(args[1], args[2], args[3], args[4]);
}
private void DownloadFileShareAndFTP(string userName, string password, string FileToDownload, string localDestinationFilePath)
{
            WebClient client = new WebClient();
            client.Credentials = new NetworkCredential(userName, password);
            client.DownloadFile(FileToDownload, localDestinationFilePath);
}

Here is how it looks when I hardcode the values instead of getting them from the arguments
static void Main(string[] args)
    {
          PacthDownload.DownloadFileShareAndFTP("abc", "abc@123",@"\\10.1.1.119\Backup_share\patch testing\Skype-8.81.0.268.zip", @"E:\Test\Patch.zip");
         //PacthDownload.DownloadPFile(args[1], args[2], args[3], args[4]);
    }
    private void DownloadFileShareAndFTP(string userName, string password, string FileToDownload, string localDestinationFilePath)
    {
                WebClient client = new WebClient();
                client.Credentials = new NetworkCredential(userName, password);
                client.DownloadFile(FileToDownload, localDestinationFilePath);
    }

username is: abc uname length is: 3| password is: abc@123 pass length
is: 7| patch download from path is: \10.1.1.119\Backup_share\patch
testing\Skype-8.81.0.268.zip FileToDownload length is: 60| patch
download to path is: E:\Test\Patch.zip localDestinationFilePath length
is: 17
DownloadPFile EOF

the length is those of the arguments, not the values I hardcoded.
Here is a screenshot of how it looks like once the file is downloaded but for some reason it only

I'm using visual studio 2017 for this.
I have removed the log statements from the code while adding it here so as to make it look cleaner.
Any ideas on how to fix this?

A: The Argument your receive which contains the path this one "patch download from path is: \10.1.1.119\Backup_share\patch testing\Skype-8.81.0.268.zip" doesn't seem to contain any escape sequences for the characters for the "\" character which is probably why you're receiving the exception. Add an extra "\" after every "\" character that should fix it.


text:
Q: How can I get a project type on Netbeans Platform? Is there a way to know the type of a selected project? I would like to do some specific actions depending of the project type like a J2SE project.
Below is the only way that I found to do that:
public final class MyAction extends CookieAction {

@Override
public boolean isEnabled() {
  if(this.getActivatedNodes() == null || this.getActivatedNodes().length != 1) {
        return false;
    }

    Lookup lookup = this.getActivatedNodes()[0].getLookup();

    // gets the selected project
    Project currentProject = lookup.lookup(Project.class);

    // checks if the selected project is a J2SE Project or a Maven Project
    if(currentProject != null && (currentProject.getClass().getSimpleName().equals("J2SEProject")
            || currentProject.getClass().getSimpleName().equals("NbMavenProjectImpl"))) {
        return true;
    }

    return false;

}}

A: simple new -> action -> conditionaly enabled  (Project) and it is all.
 package project.action;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import org.netbeans.api.project.Project;

import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.openide.util.NbBundle.Messages;

@ActionID(category = "Build",
id = "project.action.SomeAction")
@ActionRegistration(displayName = "#CTL_SomeAction")
@ActionReferences({
    @ActionReference(path = "Menu/File", position = 0)
})
@Messages("CTL_SomeAction=SomeAction")
public final class SomeAction implements ActionListener {

private final Project context;

public SomeAction(Project context) { // this is enable !!
    this.context = context;
}

public void actionPerformed(ActionEvent ev) {
    // TODO use context
}
}

Jirka


text:
Q: Filtros en vista blade con Laravel Me encuentro realizando un proyecto inmobiliario y realizo una búsqueda y mando todas las propiedades del controlador a la vista.
public function busquedaPropiedades(Request $request){

    //BUSCAMOS CATEGORIA Y LA ENVIAMOS A ALGOLIA
    //Buscamos la categoría seleccionada
    $categoria = $request->get('categoria');
    //Enviamos el id de la categoría seleccionada
    $categoria_id = Category::where('nombre_categoria', $categoria)->pluck('id');

    //UTILIZAMOS ALGOLIA PARA BUSCAR LA CATEGORÍA Y LO QUE EL USUARIO ESCRIBA
    $propiedadesObtenidas = Property::search($request->get('ubicacion'))->where('category_id', '=', $categoria_id[0])->get();

     return view('web.secciones.busquedasPropiedades', [
        'propiedadesObtenidas' => $propiedadesObtenidas,
        'categoria' => $categoria
    ]);
}

En la vista muestro lo que el usuario buscó.
Ahora estoy investigando como puedo agregar "filtros de búsqueda" algo como la siguiente imagen.

No encuentro información de como realizar este procedimiento. Y me gustaría que me brinden una orientación de como se hace este filtrado en la vista.
Por ejemplo si envío la categoría desde el controlador al filtro de la vista:
$resultadosCategorias = Category::get();

¿Como es que la vista se debe actualizar con lo seleccionado por el usuario?
@foreach($resultadosCategorias as $categorias)

    <input class="form-check-input" type="radio" name="rbCategoria" id="rb-categoria" value="option1" checked>

        {{ $categorias->nombre_categoria }}

@endforeach

¿Como puedo realizar que la vista muestre lo que selecciona el usuario?
Suponiendo que el foreach muestra los siguientes items

*

*venta

*alquiler

En radiobutton y el usuario selecciona uno que forma es la correcta para renderizar la vista?
EDICIÓN:
Al enviar los valores seleccionados por el usuario siempre tengo un problema con la vista que no encuentra una u otra variable o no muestra nada, basandome en el ejemplo @L.Flor
Para que me actualice la vista hago lo siguiente:
@if($categories == 'null')

  @foreach($categories as $categoria)
           ...
  @endforeach

@endif

Y esto me genera una vista sin resultados. Como puedo validad si me llegan datos y mostrar los valores correspondientes?

A: Si ves en la documentación, en la parte de rendering-components, podrás notar que vista y componente pueden interactuar de la siguiente manera:
En tu componente debes tener los criterios de búsqueda y también las categorías que serán retornadas mediante el método render().
namespace App\Http\Livewire\Nav;

use Livewire\Component;

class SearchCategories extends Component
{
     // Criterios de búsqueda
     public $tipoPropiedad;
     public $tipoOperacion;

     // Categorias
     public $categories;

     public function render()
     {
          $this->categories = Category::
                where('tipo_op', $this->tipoOperacion)
                ->where('tipo_prop', $this->tipoPropiedad)
                ->get();

          return view('livewire.vista');
     }
}

Posteriormente, en tu vista, deberás tener reflejado esto. Sólo a modo de ejemplo te pongo esto:

   <input type="text" wire:model="tipoOperacion" />
   <input type="text" wire:model="tipoPropiedad" />

   @foreach($categories as $categoria)
           ...
   @endforeach

A: Lo solucione agregando una vista recursiva. Muchas gracias @L.Flor tu ayuda me sirvió muchísimo!!
Mi vista recursiva
@each('web.secciones.partials.filtroCategoria', $categorias, 'categoriaFiltrada')


text:
Q: VBA Excel Compare sheets with nested For I want to compare every row of NBG_Data sheet with every row of Comparison_Data sheet , so i want each row of NBG_Data to be compared with all the rows of the Comparison_Data Sheet then go to the next row , till it reaches the MAX_Row ,the issue is that i couldn't Nest the For loop (which i really wanted) so i am trying the Do loop , but when i start the error is "Loop without Do"
If anyone please tell me what I did wrong in the Do loop or better modify the for so i can have a nested working for loop .
For Row = 2 To MAX_Row

CompMonth = Worksheets(NBG_ComparisonDataWorksheetName).Cells(Row, SOP).Value
CompMonth = DatePart("m", CompMonth)

CompYear = Worksheets(NBG_ComparisonDataWorksheetName).Cells(Row, SOP).Value
CompYear = DatePart("yyyy", CompYear)

CompCarmaker = Worksheets(NBG_ComparisonDataWorksheetName).Cells(Row, Carmaker).Value
CompProject = Worksheets(NBG_ComparisonDataWorksheetName).Cells(Row, Project).Value
CompFamily = Worksheets(NBG_ComparisonDataWorksheetName).Cells(Row, Family).Value
CompStatus = Worksheets(NBG_ComparisonDataWorksheetName).Cells(Row, Status).Value
CompShare = Worksheets(NBG_ComparisonDataWorksheetName).Cells(Row, Share).Value

Do While Row <= 2

NBGMonth = Worksheets(NBG_DataWorksheetName).Cells(Row, SOP).Value
NBGMonth = DatePart("m", NBGMonth)

NBGYear = Worksheets(NBG_DataWorksheetName).Cells(Row, SOP).Value
NBGYear = DatePart("yyyy", NBGYear)

NBGCarmaker = Worksheets(NBG_DataWorksheetName).Cells(Row, Carmaker).Value
NBGProject = Worksheets(NBG_DataWorksheetName).Cells(Row, Project).Value
NBGFamily = Worksheets(NBG_DataWorksheetName).Cells(Row, Family).Value
NBGStatus = Worksheets(NBG_DataWorksheetName).Cells(Row, Status).Value
NBGShare = Worksheets(NBG_DataWorksheetName).Cells(Row, Share).Value

Row = Row + 1

 ' StatusBar Show

 Application.StatusBar = "VerifySumofShares. Progress: " & Row & " of " & MAX_Row

        If (NBGMonth = CompMonth And NBGYear = CompYear And CompCarmaker = NBGCarmaker And CompProject = NBGProject And CompFamily = NBGFamily And NBGStatus <> "LOST" And CompStatus <> "LOST" And CompShare + NBGShare <= 99 And CompShare + NBGShare > 100) Then

            Worksheets(Issue_SumofSharesWorksheetName).Cells(3 + Issue_SumofSharesCnt, "A").Value = Row
            Worksheets(Issue_SumofSharesWorksheetName).Cells(3 + Issue_SumofSharesCnt, "B").Value = Worksheets(NBG_RegionaDataWorksheetName).Cells(Row, Project).Value
            Worksheets(Issue_SumofSharesWorksheetName).Cells(3 + Issue_SumofSharesCnt, "C").Value = GetMonthAndQuarter(Worksheets(NBG_RegionaDataWorksheetName).Cells(Row, SOP).Value)
            Worksheets(Issue_SumofSharesWorksheetName).Cells(3 + Issue_SumofSharesCnt, "D").Value = Worksheets(NBG_RegionaDataWorksheetName).Cells(Row, Family).Value
            Worksheets(Issue_SumofSharesWorksheetName).Cells(3 + Issue_SumofSharesCnt, "E").Value = Worksheets(NBG_RegionaDataWorksheetName).Cells(Row, Responsible).Value

           ' Region As String
            Region = ""

            'Add any other GeoRegion which is also responsible in the recorded data

            If Worksheets(NBG_DataWorksheetName).Cells(Row, "BC") Then
            Region = Region + "@EMEA"
            End If

            If Worksheets(NBG_DataWorksheetName).Cells(Row, "BD") Then
            Region = Region + "@AMERICAS"
            End If

            If Worksheets(NBG_DataWorksheetName).Cells(Row, "BE") Then
            Region = Region + "@GCSA"
            End If

            If Worksheets(NBG_DataWorksheetName).Cells(Row, "BF") Then
            Region = Region + "@JAPAN&KOREA"
            End If

            Worksheets(Issue_SumofSharesWorksheetName).Cells(3 + Issue_SumofSharesCnt, "F").Value = Region

            'Count the number of the cases recorded

            Issue_SumofSharesCnt = Issue_SumofSharesCnt + 1

            'If there is no items , the Message to show

        ElseIf (Worksheets(NBG_RegionaDataWorksheetName).Cells(Row, SOP).Value = "There are no items to show in this view.") Then

    End If

     Loop Until Row = MAX_Row

Next Row

A: You have a hybrid between a Do While...Loop and a Do...Loop Until loop, which VBA doesn't know how to interpret.
Either change:
    Do While Row <= 2

to:
    Do

to make a valid Do...Loop Until loop.
Or change:
    Loop Until Row = MAX_Row

to:
    Loop

to make a valid Do While...Loop loop.


text:
Q: UNIQUE constraint on DataTable Can I have a clustered key on DataTable in C# ?
There's a requirement in my code to have constraints for possible combinations of 3 columns to be unique .....

A: What you need is really a unique constraint on your DataTable. Clustered keys are a SQL Server on-disk feature and not applicable to a DataTable.
Check out MSDN doc on DataTable constraints:

The UniqueConstraint object, which can be assigned either to a single column or to an array of columns in a DataTable, ensures that all data in the specified column or columns is unique per row. You can create a unique constraint for a column or array of columns by using the UniqueConstraint constructor.

So try something like this:
// this is your DataTable
DataTable custTable ;

// create a UniqueConstraint instance and set its columns that should make up
// that uniqueness constraint - in your case, that would be a set of *three*
// columns, obviously! Adapt to your needs!
UniqueConstraint custUnique =
   new UniqueConstraint(new DataColumn[] { custTable.Columns["CustomerID"],
                                           custTable.Columns["CompanyName"] });

// add unique constraint to the list of constraints for your DataTable
custTable.Constraints.Add(custUnique);

And that should do the trick for you!

A: To make your columns enforce a UNIQUE constraint you could use
DataTable dt = new DataTable();
dt.Columns.Add("UniqueColumn");
dt.Columns["UniqueColumn"].Unique = true;

Solution two
If you want some combination of the values in some columns to have unique value, you can try this.
DataTable dt = new DataTable();
dt.Columns.Add("UniqueColumn1");
dt.Columns.Add("UniqueColumn2");
dt.Columns.Add("UniqueColumn3");
dt.Columns.Add("NormalColumn");

string
       value1 = string.Empty,
       value2 = string.Empty,
       value3 = string.Empty,
       value4 = string.Empty;

//Logic to take values in string values variables goes here

DataRow[] founded = dt.Select("UniqueColumn1 = '"+ value1+
                              "' and UniqueColumn2 = '"+value2+
                              "' and UniqueColumn3 = '"+value3+"'");
if (founded.Length > 0)
      // Message to say values already exist.
else
      // Add a new row to your dt.

In this code you check the data present in DT to enforce uniqueness


text:
Q: How to assign every line of the file to the node of the double linked list in c++? I have a seperate a class that has this assign method, and I need to use my double linked list implementation to this class's method
typedef string Elem;
class A{
    private:

    public:
       method assign {
                 ifstream infile("initial_text.txt",ios::in);
                string current;
                string temp=" ";
                int count=0;
                while(getline(infile, current))
                {
                    for(int i=0;i<current.size();i++) {
                        temp+=current[i];
                        if(current[i]=='.' || current[i]=='?' || current[i]=='!') {
                            cout<<temp<<"\n";
                            count++;
                            temp="";
                        }

                    }
                }
                cout<<"Total Sentences: "<<count<<"\n";

}

class Node {
        public:
            Node* next;
            Node* prev;
            Elem elem;
            friend class Linkedlist;
            Node(): next(NULL), prev(NULL)
            {}
            Node(Elem elem) : elem(elem)
            {}
    };
class Linkedlist {
    private:
        Node *head;
        Node *tail;
        int N;

    public:
        Linkedlist();//
        ~Linkedlist();//

Linkedlist::Linkedlist() {
   N = 0;
   head = new Node;
   tail  = new Node;
   head->next = tail;
   tail->prev = head;
}
Linkedlist::~Linkedlist() {
    Node *current = head;
    while (current)
    {
        Node* next = current->next;
        delete current;
        current = next;
    }
}

For now it is just filters text file by assigning each sentence to a new line, and in this loop I need to assign it to the nodes of the linked list, but I am not sure how to implement it.
Thank you!

A: maybe something like this:
void assign() {
  ifstream infile("initial_text.txt",ios::in);
  string current;
  string temp=" ";
  int count=0;
  LinkedList list;  // create a linked list
  while(getline(infile, current))
  {
    for(int i=0;i<current.size();i++) {
      temp+=current[i];
      if(current[i]=='.' || current[i]=='?' || current[i]=='!') {
          cout<<temp<<"\n";
          // add `temp` to the end of the list
          list.add(temp);
          count++;
          temp="";
      }
    }
  }
  cout<<"Total Sentences: "<<count<<"\n";
}

class Linkedlist {
 private:
  Node *head;
  Node *tail;
  int N;

 public:
  Linkedlist();//
  ~Linkedlist();//

  void add(Elem elem);  // TODO: implement this!!!

  /* These may be useful as well, but what functions you want to provide depend
   * on your application
   */
  void print();       // print entire list
  void remove(...);   // remove an element
  void at(int i);     // retrieve the element at index i
  void size() { return N; }
  // alternatively, iterator allows standard container access
  class iterator : public std::iterator<bidirectional_iterator_tag, Elem> {
    Node *node_;
   public:
    explicit iterator(Node *node) : node_(node) {}
    iterator& operator++() { ... }           // prefix operator, i.e. ++it
    iterator operator++(int) { ... }         // postfix operator, i.e. it++
    bool operator==(iterator other) { ... }  // equality operator, i.e. it1 == it2
    bool operator!=(iterator other) { ... }  // not equal operator, i.e. it1 != it2
    Elem& operator*() { ... }                // dereference operator, i.e. string &tmp = *it
  }
  iterator begin() { return iterator(head->next); }
  iterator end() { return iterator(tail); }
}

Here we've encapsulated the functionality of adding to your LinkedList so that you only have to implement it once and never have to worry about memory leaks if you do it right.  The iterator also provides standard c++ style bidirectional container access if you like, so that you can easily iterate through the linked list and utilize pre-made algorithms in the STL
LinkedList list;
... // populate list
// print list
for (auto elem : list)
  std::cout << elem << std::endl;;
/*** STL pre-defined functions ***/
// reverse the list in place
reverse(list);
// remove duplicates in the list
auto last = std::unique(list.begin(), list.end());
list.erase(last, list.end());
// finds location of "hello" in list, or N if it is not in the list
auto index = std::find(list.begin(), list.end(), "hello") - list.begin();
// count the number of elements beginning with a capital letter
int numCaps = std::count_if(list.begin(), list.end(),
                            [](int elem){ return isupper(elem[0]); });
// append newline to every element
std::for_earch(list.begin(), list.end(), [](string &elem) { elem += "\n"; });

Note: I didn't test this code but it should give you an idea of how to proceed.


text:
Q: recursive problem using the image module in racket I have the following error on line 27:
first: expects a non-empty list; given: #<image>

Is it a problem with recursion?
I've been researching but can't find an example where the image package is used recursively.
I can't think of anything, I don't understand why it gives me that error :(
; You must make a program that needs a list of n figures, which you will paint,
; all the color options that the user indicates and separates by a fixed distance that you determine.
; These figures contain a name (they depend on the naming options that you set),
; a measurement or measurements according to what the figure requires and an indicator of whether it is painted full or only the silhouette.
; NOTE: These drawings must be made using the image of the package.

(require 2htdp/image)

(define-struct triangulo_ (color size complete))
(define-struct cuadrado_  (color size complete))
(define-struct circulo_   (color size complete))

(define circulo   (make-circulo_   "yellow" 10 "outline"))
(define triangulo (make-triangulo_ "blue"   10 "solid"))
(define cuadrado  (make-cuadrado_  "orange" 10 "outline"))

(define lista_figuras (cons circulo (cons triangulo (cons cuadrado empty))))

(define (validar figura ID)
  (cond
    [(empty? figura) ID]
    [(and (circulo_? (first figura))   (positive? (circulo_-size (first figura))) (number? (circulo_-size (first figura)))   (string? (circulo_-color (first figura)))   (string? (circulo_-complete (first figura))))   (validar (rest figura) #t)]
    [(and (cuadrado_? (first figura))  (positive? (cuadrado_-size (first figura))) (number? (cuadrado_-size (first figura)))  (string? (cuadrado_-color (first figura)))  (string? (cuadrado_-complete (first figura))))  (validar (rest figura) #t)]
    [(and (triangulo_? (first figura)) (positive? (triangulo_-size (first figura))) (number? (triangulo_-size (first figura))) (string? (triangulo_-color (first figura))) (string? (triangulo_-complete (first figura)))) (validar (rest figura) #t)]
    [else (validar (rest figura) #f)]))

(define (pathway figura)
  (cond
    [(empty? figura) empty]
    [(circulo_?   (first figura)) (pathway(circle   (circulo_-size (first figura))   (circulo_-complete (first figura))   (circulo_-color (first figura))))]
    [(triangulo_? (first figura)) (pathway(triangle (triangulo_-size (first figura)) (triangulo_-complete (first figura)) (triangulo_-color (first figura))))]
    [(cuadrado_?  (first figura)) (pathway(square   (cuadrado_-size (first figura))  (cuadrado_-complete (first figura))  (cuadrado_-color (first figura))))]
    [else (pathway (rest figura))]))

(define (main figura)
  (cond
    [(boolean=? (validar figura 0) #t) (pathway figura)]
    [else "Error, solo se permiten: [ circulos, cuadrados y triangulos <equilateros> ]"]))

(main lista_figuras)

A: It's a type error. In the recursive call to pathway, you're passing in an image but it requires a list which contains triangulo_/cuadrado_/circulo_. Also the right hand side of the cond clauses in validar have multiple expressions, each will be evaluated from left to right but their values wouldn't matter, even if they're false. It's better to combine validation of each field with an and.
First, give a name to the structs you define, let's call it ImageConfig
At a higher level, the problem with the design is that you're mixing up list-processing with the processing of the element in the list. It's better to separate those.
Now separate the processing of [List-of ImageConfig] from ImageConfig for both validar and pathway.
; validar-l : [List-of ImageConfig] -> Boolean
; validar   : ImageConfig -> Boolean
; pathway-l : [List-of ImageConfig] -> [List-of Image]
; pathway   : ImageConfig -> Image
; main      : [List-of ImageConfig] -> [List-of Image]

; You must make a program that needs a list of n figures, which you will paint,
; all the color options that the user indicates and separates by a fixed distance that you determine.
; These figures contain a name (they depend on the naming options that you set),
; a measurement or measurements according to what the figure requires and an indicator of whether it is painted full or only the silhouette.
; NOTE: These drawings must be made using the image of the package.

(require 2htdp/image)

; ImageConfig is one of
(define-struct triangulo_ (color size complete))
(define-struct cuadrado_  (color size complete))
(define-struct circulo_   (color size complete))

(define circulo   (make-circulo_   "yellow" 10 "outline"))
(define triangulo (make-triangulo_ "blue"   10 "solid"))
(define cuadrado  (make-cuadrado_  "orange" 10 "outline"))

(define lista_figuras (cons circulo (cons triangulo (cons cuadrado empty))))

; [List-of ImageConfig] -> Boolean
(define (validar-l fl)
  (cond [(empty? fl) true]
        [else (and (validar (first fl)) (validar-l (rest fl)))]))

; ImageConfig -> Boolean
(define (validar f)
  (cond
    [(circulo_? f)   (and (positive? (circulo_-size f))   (number? (circulo_-size f))   (string? (circulo_-color f)))]
    [(cuadrado_? f)  (and (positive? (cuadrado_-size f))  (number? (cuadrado_-size f))  (string? (cuadrado_-color f)))]
    [(triangulo_? f) (and (positive? (triangulo_-size f)) (number? (triangulo_-size f)) (string? (triangulo_-color f)))]))

; ImageConfig -> Image
(define (pathway f)
  (cond
    [(circulo_?   f) (circle   (circulo_-size f)   (circulo_-complete f)   (circulo_-color f))]
    [(triangulo_? f) (triangle (triangulo_-size f) (triangulo_-complete f) (triangulo_-color f))]
    [(cuadrado_?  f) (square   (cuadrado_-size f)  (cuadrado_-complete f)  (cuadrado_-color f))]))

; [List-of ImageConfig] -> [List-of Image]
(define (pathway-l fl)
  (cond
    [(empty? fl) empty]
    [else (cons (pathway (first fl)) (pathway-l (rest fl)))]))

; [List-of ImageConfig] -> [List-of Image]
(define (main fl)
  (cond
    [(boolean=? (validar-l fl) true) (pathway-l fl)]
    [else (error "Error, solo se permiten: [ circulos, cuadrados y triangulos <equilateros> ]")]))

(main lista_figuras)

Result:


text:
Q: How to create a calculated field with a where clause in the calculation The image shows the table from this code:  select * from PunchClock
where punchmonth = 1 and PunchDay = 1 and PunchYear = 2018
I am trying to calculate the number of hours worked per day in a database. Our table for this has 2 columns that pertain to this. InOut is a column that has either 1 or 0 (1 = punch in, 0 = punch out), and then there is the punchdatetime. How could I use these two fields to calculate how many hours are worked per day.
I have tried to subtract the punch time in from the punch time out but that won't work.
select PunchMonth, PunchDay, PunchYear,
      ((PunchDateTime where InOut = 0) - (punchdatetime where InOut = 1))
  from PunchClock

Error Message: Incorrect syntax near the keyword 'where'.

A: could be you need  case (not where)
select PunchMonth
  , PunchDay
  , PunchYear
  , case INOut = 0 then PunchDateTime else -PunchDateTime end
from PunchClock

A: I think you want a case expression.  Also, because a given row has either an InOut value of 0 or 1 but not both, I think you need aggregation.
So, I'm guessing:
select PunchMonth, PunchDay, PunchYear,
       datediff(second, min(case when InOut = 0 then punchdatetime end),
                max(case when InOut = 1 then punchdatetime  end)
               ) as seconds_diff
from PunchClock
group by PunchMonth, PunchDay, PunchYear;


text:
Q: Double MongoDb Version Problem with MongoDB Version
I installed Mongo Db follow this Link
http://www.mkyong.com/mongodb/how-to-install-mongodb-on-mac-os-x/
After i updated with Brew
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/
mongod --help for help and startup options
2014-04-28T10:49:46.475+0200 [initandlisten] MongoDB starting : pid=2197 port=27017 dbpath=/data/db 64-bit host=Foo.local
2014-04-28T10:49:46.475+0200 [initandlisten]
2014-04-28T10:49:46.475+0200 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2014-04-28T10:49:46.475+0200 [initandlisten] db version v2.6.0
2014-04-28T10:49:46.475+0200 [initandlisten] git version: nogitversion
2014-04-28T10:49:46.475+0200 [initandlisten] build info: Darwin minimavericks.local 13.1.0 Darwin Kernel Version 13.1.0: Thu Jan 16 19:40:37 PST 2014; root:xnu-2422.90.20~2/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49
2014-04-28T10:49:46.476+0200 [initandlisten] allocator: tcmalloc
2014-04-28T10:49:46.476+0200 [initandlisten] options: {}
2014-04-28T10:49:46.476+0200 [initandlisten] exception in initAndListen: 10309 Unable to create/open lock file: /data/db/mongod.lock errno:13 Permission denied Is a mongod instance already running?, terminating
2014-04-28T10:49:46.476+0200 [initandlisten] dbexit:
2014-04-28T10:49:46.476+0200 [initandlisten] shutdown: going to close listening sockets...
2014-04-28T10:49:46.476+0200 [initandlisten] shutdown: going to flush diaglog...
2014-04-28T10:49:46.476+0200 [initandlisten] shutdown: going to close sockets...
2014-04-28T10:49:46.476+0200 [initandlisten] shutdown: waiting for fs preallocator...
2014-04-28T10:49:46.476+0200 [initandlisten] shutdown: lock for final commit...
2014-04-28T10:49:46.476+0200 [initandlisten] shutdown: final commit...
2014-04-28T10:49:46.476+0200 [initandlisten] shutdown: closing all files...
2014-04-28T10:49:46.477+0200 [initandlisten] closeAllFiles() finished
2014-04-28T10:49:46.477+0200 [initandlisten] shutdown: removing fs lock...
2014-04-28T10:49:46.477+0200 [initandlisten] couldn't remove fs lock errno:9 Bad file descriptor
2014-04-28T10:49:46.477+0200 [initandlisten] dbexit: really exiting now

➜  ~  mongo --version
MongoDB shell version: 2.6.0

but if i do this:
> use foo
switched to db foo
> use foo
switched to db foo
> foo.version()
2.4.9

How can I clean my double Installation?
I want 2.6.0

A: @monkeyUser,
Running two different MongoDB instances is not an issue per-se provided they use different data directories. In your case, looks like you have two MongoDB installation with same data directory configured for both. If you intend to keep both the instances you'll need to change the dbPath for one of them to point at some other directory.
If you do not intend to run two instances and only the latest instance, uninstall the previously installed instance using same steps from the blog post but executing them in reverse order (bottom up) and in inverted sense i.e. if blog has a step to create a directory /data/db, you would execute this steps as "deleting the data directory /data/db". Once you have removed one of the instances, second instances should come up fine.


text:
Q: Git post-receive nor post-update hooks aren't executed
*

*I use these hooks on my git server (another computer from my local network).

*Yes, files are executable.

*Yes, partition, where git repo is situated, doesn't have an noexec flag.

*Yes, I'm sure that I push new files and my server have something to update.

*Yes, script body code works properly.

*Yes, my files are named properly.

My system - server - Ubuntu, connection to the git server via HTTPS


text:
Q: Как реализовать обработку различных значений введенных пользователем? Только недавно изучаю C# и столкнулся с проблемой на практике. В зависимости от входного числа (от 1 до 100), которое вводит пользователь, на экран выводится строка:

*

*если 1 -  "i hate it"

*если 2 -  "i hate that i love it"

*если 3 -  "I hate that I love that I hate it"

и т.д.
Подскажите пожалуйста, как реализовать подобное?

A: static void Main(string[] args)
{
    string Func(byte count) => string.Join(' ', "i hate", string.Join(' ', EnumerableOfStrings().Take(count)), "it");

    for (byte c = 0; c < 10; c++)
    {
        Console.WriteLine(Func(c));
    }
    Console.ReadLine();
}

private static IEnumerable<string> EnumerableOfStrings()
{
    while (true)
    {
        yield return "that i love";
        yield return "that I hate";
    }
}

Сделал тот дополнительный "метод", чтобы легче было писать другие штуки. Если хочешь другой способ - используй в цикле StringBuilder и подобие state machine
Вот несколько строчек вывода с консоли:

i hate  it
  i hate that i love it
  i hate that i love that I hate it
  i hate that i love that I hate that i love it
  i hate that i love that I hate that i love that I hate it


text:
Q: How can I change the commit pointed to by a signed tag? Specifically, while retaining the tag's annotation message and date.
Last night, I created a signed tag for a repo I'm working on.  A few minutes later, I unthinkingly amended the commit I'd tagged.  Now, I'm getting ready to push my changes and need to clean up that tag before I do.
Looking at a similar (ish) question, I've attempted various combinations of GIT_AUTHOR_DATE and GIT_COMMITER_DATE with no luck:
$ git show v0.1.1 | awk '{ if ($1 == "Date:") { print substr($0, index($0, $3)) } }'
Nov 26 18:14:17 2017 -0800
Nov 26 18:13:21 2017 -0800

$ git tag -d v0.1.1
Deleted tag 'v0.1.1' (was d4189a2)

$ GIT_AUTHOR_DATE="Nov 26 18:14:17 2017 -0800" \
> GIT_COMMITER_DATE="Nov 26 18:14:17 2017 -0800" \
> git tag v0.1.1 9aa951c -s -m 'Display in columns.'

$ git show v0.1.1 | awk '{ if ($1 == "Date:") { print substr($0, index($0, $3)) } }'
Nov 27 13:34:16 2017 -0800
Nov 26 21:18:34 2017 -0800

How can I "fix" this tag?

A: You're mostly there: you're making a new signed, annotated tag.  You just have a typo:

GIT_COMMITER_DATE="Nov 26 18:14:17 2017 -0800" \

This should read:
GIT_COMMITTER_DATE="Nov 26 18:14:17 2017 -0800" \

(two T's in "committer").  But there's no obvious reason to force the tag time stamp back, since you're already making a new and different tag: you might as well just make a new signed tag with today's time-stamp.
Discussion
You must make a new signed tag (using, if you like, very similar contents and perhaps even the same tag-name, although before you re-use a tag name, you should read the documentation discussion on the topic).  The issue here is that the signature is itself a cryptographic assertion about the tag's content, including the tag message and the commit hash of the target of the tag.  This means that in the new signed tag, you must have a different signature.
Since it is a new and different tag, if there's a chance that anyone else has the old tag, it's wisest to just give the new tag a new name (see linked discussion).  If there's no such chance, you can simply overwrite the old tag with -f.  The special Git environment variables can be used to override the default timestamps.

A: In my tests, the syntax you used doesn't make the GIT_COMMITTER_DATE variable visible to the subsequent git command.  I had better luck with
export GIT_COMMITTER_DATE=...

which of course you'd then want to un-set after running git.  There may be other shorthand ways; this is just what worked for me.
Also make sure you're using a recognized date format.  "YYYY-MM-DD hh:mm:ss" worked for me.
By the way, I don't think "author date" matters; AFAIK (and as far as the docs indicate) a tag would only worry about one date.  In your output, the 2nd date is coming from the underlying commit (as you can see from the unprocessed show output).
So all of that said, one question... why?  If the amended commit was done "unthinkingly", why not use the reflog to back it out and commit your other changes as a separate commit?  Or, why is it a big deal that the tag date be retroactive anyway?


text:
Q: Keeping audio player persistently/continuously playing while navigating HTML pages I am using Dewplayer to play a background music on my website.
I have done the integration and it works fine.
When I click on my next page, the player stops playing the music until and unless I again click to start which restarts the music. My pages are static HTML pages. Below is my code with the link to the files.
The CSS:
#content {
  margin-left:15%;
  width:500px;
  text-align:left;
}
#hint {
  color:#666;
  margin-left:15%;
  width:300px;
  text-align:left;
  margin-top:3em;
}

The HTML:
  Link1
    Link2
    Link3

<object type="application/x-shockwave-flash" data="dewplayer-mini.swf?mp3=mp3/test2.mp3" width="160" height="20" id="dewplayer-mini"><param name="wmode" value="transparent" /><param name="movie" value="dewplayer-mini.swf?mp3=mp3/test2.mp3" /></object>

So from the above link, when you click to play the music, the music will be played, but as soon as you click on link2 or link3, it will be stopped. What I need is, that it should be played consistently and continuously irrespective of page navigation. People have suggested me using Frameset, iframes or flash (not the flash audio player), but I am not willing to use them.
I searched a lot of such similar question on Stackoverflow which are as below.
https://stackoverflow.com/questions/18411148/continuous-persistant-audio-players
How to keep audio playing while navigating through pages?
Audio Player: Constant playing
The second one suggested that it can be done with Ajax, but I am creating static pages and don't have a great hand on using Ajax.
PS: I am open to using any other player which has this functionality.
EDIT : Created the same using jQuery
As people suggested me to use jQuery/JavaScript for flash, I have created the player using jQuery as below. On the demo, the red Square box is stop/pause and Blue is Play.
The HTML:
<audio id="player" src="http://www.soundjay.com/ambient/check-point-1.mp3"></audio>

The jQuery Code:
$(document).ready(function() {
    var playing = false;

    $('a#button').click(function() {
        $(this).toggleClass("down");

        if (playing == false) {
            document.getElementById('player').play();
            playing = true;
            $(this).removeClass('soundIcnPlay');
            $(this).addClass('soundIcnPause');

        } else {
            document.getElementById('player').pause();
            playing = false;
            $(this).removeClass('soundIcnPause');
            $(this).addClass('soundIcnPlay');
        }

    });
});

The CSS:
.soundIcnPlay {
    background: none repeat scroll 0 0 red;
    cursor: pointer;
    display: block;
    height: 100px;
    width: 100px;
}

.soundIcnPause {
    background: none repeat scroll 0 0 blue;
    cursor: pointer;
    display: block;
    height: 100px;
    width: 100px;
}

The jsFiddle Link:
Audio Demo

A: This is a wonderful solution without a player. It uses pure HTML5 Audio object; yet there will be a small gap between pages but you won't play from beginning. Hope its acepted gap. Thank you for good question +1.
I am including the answer with little hack to decrease gap between page load.
You can see from attached image; it will load first thing on waterfall; less than 50 ms.... but suitable for testing and local host only. ie. interval to 0 ms.
audio.js file:
function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) +
    ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^\s+|\s+$/g,"");
      if (x==c_name)
        {
        return unescape(y);
        }
      }
}

var song = document.getElementsByTagName('audio')[0];
var played = false;
var tillPlayed = getCookie('timePlayed');
function update()
{
    if(!played){
        if(tillPlayed){
        song.currentTime = tillPlayed;
        song.play();
        played = true;
        }
        else {
                song.play();
                played = true;
        }
    }

    else {
    setCookie('timePlayed', song.currentTime);
    }
}
setInterval(update,1000);
// default is 1000 ms; but for testing I set that to 0 ms..
I guess it's exhausting JS interpreter (don't know much about it).

player.html file:

<title>Player</title>

    <audio id="audioplayer" autobuffer="" loop="true" preload="auto" src="song.mp3">
    </audio>

*

*It uses Cookies without a plugin.

*It's not possible to remove the gap permanently; but please feel free to edit if you think that is possible!.

A: As far as I know AJAX is the only way to have an audio player run cross browser over multiple pages. As soon as the whole page reloads, everything running on it stops, for that reason you are forced to only exchange a part of it. You can save the player position on page exit, but sounds should be off until the new page is loaded and initalized. If course you could also exchange your content in some iframe but that would be giving you new problems.
By the way, it's not scary to load an page into a div using for example jQuery. You could for example add an DIV to your page, the using the jQuery load-function to pull pages into it:
http://api.jquery.com/load/
There's also a jQuery-plugin that automates a few of the tasks you would run into usually, read the answer on the follow SO question:
Load HTML page dynamically into div with jQuery

A: You want to look into CSS layers and even more likely HTML In-Line Frames (i-frames)...
I think this i-frame tutorial [ http://manda.com/iframe/ ] will be enough to achieve what you want. Scroll down to the "Simple Link to iFrame Example" heading and there you will see a demo of an i-frame holding navigation links above another html container of the link pages content (AltaVista, AOL etc). Complete with scrolling.
Anyway the point is: where those navigation links are is where your player would be placed, then you can visit other pages on your site but the player is constantly visible and un-interrupted in its own container i-frame. Closing your site ends the music. Also the browser address might not change as you click links to different pages on your site (since they show via an i-frame at the current url address)
Another good one (see Multiple Frames example):
[ http://www.htmlgoodies.com/tutorials/frames/article.php/3479271 ]
Also here's a basic look into the CSS Layers thingy-majik:
[ http://www.echoecho.com/csslayers.htm ]


text:
Q: With JavaScript how would I increment strings using an array to create a loop? I'm trying to make a web page that has its wallpaper change every time you refresh. I'd like it to display the next image in the array every time the page is refreshed. So every refresh works its way through the list until the end, and then starts over.
Right now I'm using an array and accessing it with a random index, but I need to access it using one that increases by 1 each time, and once I reach the array length I need it to start over again... Right now I'm using this (which took me forever to figure out):
$(function background() {
    var images = [
      "wallpaper1.jpg",
      "wallpaper2.jpg",
      "wallpaper3.jpg",
      "wallpaper4.jpg"
    ];
    $("#hero").css({
      "background-image":
        "url(images/wallpapers/" +

        images[Math.floor(Math.random() * images.length)]

        + ")"
    });
  });

I have found out about incrementing numbers in an array using this:
var arr = [1,2,3,4];
arr = arr.map(function(val){return ++val;});
console.log(arr);

But I can't seem to get the number solution to work with strings. I'm ultra new at all this and I am losing my mind :/

A: You need to save a counter to localStorage that you can retrieve on each page load, increment,, make the check, and then save again.
$(function () {

    const images = [
      'wallpaper1',
      'wallpaper2',
      'wallpaper3',
      'wallpaper4'
    ];

    // We must check to see if localStorate exists before
    // we do anything
    function hasLocalStorage() {
      try {
        localStorage.setItem('count', 0);
        if (localStorage.getItem('count') === '0') {
          return true;
        }
      } catch(e) {
          return false;
      }
      return false;
    }

    // Fetch the count from localStorage. Because it's
    // saved as a string we need to coerce it to a number
    let count = Number(localStorage.getItem('count'));

    $("#hero").css({
      'background-image': `url(${images[count]})`
    });

    // Increase the count
    count++;

    // If the count is the length of the array (minus one
    // because the array is indexed-based) set the
    // localStorate count to zero, otherwise save the count
    if (count === images.length - 1) {
      localStorage.setItem('count', 0);
    } else {
      localStorage.setItem('count', count);
    }

});

A: You can add a helper function to do this:
var getNextImage = (() => {
  var i = 0;

  return () => {
    if (i >= images.length)
    {
      i = 0;
    }

    return images[i++];
  };
})();

and then replace the images[Math.floor(Math.random() * images.length)] call with getNextImage()
Like so:
$(function background() {
    var images = [
      "wallpaper1.jpg",
      "wallpaper2.jpg",
      "wallpaper3.jpg",
      "wallpaper4.jpg"
    ];

    var getNextImage = (() => {
      var i = 0;

      return () => {
        if (i >= images.length)
        {
          i = 0;
        }

        return images[i++];
      };
    })();

    $("#hero").css({
      "background-image":
        "url(images/wallpapers/" + getNextImage() + ")"
    });
  });

A: Possible, but the persistence is only becuase of the localStorage
Hey! Check this out.
This basically selects an image from the array and then changes the background continuously according to the current image. If the last image (when the user last visited the page) was wallpaper4.jpg, the next would be automatically the wallpaper1.jpg.

Assuming that the target browser has localStorage enabled, this would be the JavaScript code

var images = [
    "wallpaper1.jpg",
    "wallpaper2.jpg",
    "wallpaper3.jpg",
    "wallpaper4.jpg"
    ];

getBgImage = () => {
    var lastImage = localStorage.getItem("wallpaperIdx");
    if (lastImage && images.indexOf(lastImage) < (images.length - 1) && images.indexOf(lastImage) >= 0) {
        localStorage.setItem("wallpaperIdx", images[(images.indexOf(lastImage) + 1)]);
        return images[(images.indexOf(lastImage) + 1)];
    } else if (images.indexOf(lastImage) === (images.length - 1)) {
        localStorage.setItem("wallpaperIdx", images[0]);
        return images[0];
    } else {
        localStorage.setItem("wallpaperIdx", images[0]);
        return images[0];
    }
}

$(function () {
    setInterval(() => {
        var image = getBgImage();
        $('#hero').css({
            "background-image": `url("images/wallpapers/${image}")`,
            "transition": "1s"
        });
    }, 1000)
    clearInterval();
});

$(() => {
    $(window).on("load", () => {
        document.getElementById("hero").style.backgroundImage = `url("images/wallpapers/${image}")`;
    })
})

A: <!DOCTYPE html>
<html>
<body>
<script>
// Checking if the Local Storage feature is available.
if (typeof(Storage) !== "undefined") {
  // If it is available, check if there is a value stored by the name 'val'.
  if(localStorage.getItem("val") != null) {
    // If yes increase it by 1.
    localStorage.setItem("val", parseInt(localStorage.getItem("val")) + 1);
  }
  else {
    // If no then create one and set it to 1.
    localStorage.setItem("val", 1);
  }
  // Printing the value on the console and the page to check if it is working (You can remove this later.)
  console.log(localStorage.getItem("val"));
  document.write(localStorage.getItem("val"));

}
// If it is not available notify the user.
else {
  console.log("Sorry, your browser does not support Web Storage...");
  document.write("Sorry, your browser does not support Web Storage...");
}

var num = parseInt(localStorage.getItem("val"));
</script>
</body>
</html>

Local Storage is a feature is in HTML. It can be used to store data in the tab and will be there as long as the tab isn't closed. So, now whenever you reload your page you will get the next number starting from one.


text:
Q: has_many :through связки моделей в active_admin Имеется 3 модели
Item:
has_many :ItemColors
has_many :DetailColors, :through => :ItemColors

ItemColor:
belongs_to :Item
belongs_to :DetailColor

DetailColor:
has_many :ItemColors
has_many :Items, :through => :ItemColor

схема ItemColor:
t.string   "name"
t.integer  "item_id"
t.decimal  "size"
t.integer  "detailcolor_id

ItemColor у каждого Item может быть сколько угодно
подскажите как я могу получить список size + detailcolor.name из ItemColor для каждого Item на странице Items в active_admin
A: item.DetailsColors.map { |i| [i.size, i.DetailColor.name] }
Кроме того, придерживайтесь общепринятого стиля именования, как описано здесь


text:
Q: Extract file extension from String using regex I have the following String:
"data:audio/mp3;base64,ABC..."

And I'm extracting the file extension (in this case "mp3") out of it.
The String varies accordingly to the file type. Some examples:
"data:image/jpeg;base64,ABC..."
"data:image/png;base64,ABC..."
"data:audio/wav;base64,ABC..."
"data:audio/mp3;base64,ABC..."

Here's how I've done:
public class Test {

    private static final String BASE64_HEADER_EXP = "^data:.+;base64,";

    private static final Pattern PATTERN_BASE64_HEADER = Pattern.compile(BASE64_HEADER_EXP);

    private String data;

    private String fileName;

    public String getFileName() {
        Matcher base64HeaderMatcher = PATTERN_BASE64_HEADER.matcher(data);
        return String.format("%s.%s", getFilenameWithoutExtension(), getExtension(base64HeaderMatcher));
    }

    private String getFilenameWithoutExtension() {
        return fileName.split("\\.")[0];
    }

    private String getExtension(Matcher base64HeaderMatcher) {
        if (base64HeaderMatcher.find()) {
            String base64Header = base64HeaderMatcher.group(0);
            return base64Header.split("/")[1].split(";")[0];
        }
        return fileName.split("\\.")[1];
    }

}

What I want is a way to do it without having to split and access array positions like I'm doing above. Maybe extract the extension using a regex expression.
I'm able to do it on RegExr site using this expression:
(?<=^data:.*/)(.*)(?=;)

But, when trying to use the same regex on Java, I get the error "Require that the characters immediately before the position do" because, aparently, Java doesn't support repetition inside lookbehind:

A: How about using capturing groups?
private static final String BASE64_HEADER_EXP = "^data:[^/]+/([^;]+);base64,";

This way you can use base64HeaderMatcher.group(1) and get file type.

A: This should do it for the examples you gave:
(?<=data:)(?:[A-z]+)/(.*?);

Explanation:
Positive look-behind
(?<=data:)

Non-capturing group to account for image, audio, etc.
(?:[A-z]+)

Match / literally, capture group for file extension, match ; literally
/(.*?);

A: "Strings in Java have built-in support for regular expressions. Strings have four built-in methods for regular expressions, i.e., the matches(), split()), replaceFirst() and replaceAll() methods."
-http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
Using This Info We can quickly make a regex and test it against our string.
//In regex each set of () represents a capture field which can later be
//referenced with $1, $2 etc..
//The below regex breaks the string into four fields

string pattern="(^data:)(\\w+?/)(\\w+?)(;.*$)";

//First Field
//This field matches the start of a line (^) followed by "data:"

//Second Field
//This matches any wordCharacter (\\w), one or more (+) followed by a "/"
// the "?" symbol after the + means reluctantly match, match as few
//characters
//as possible. this field will effectively capture a seriece of letters
//followed by a slash

//Third Field
//This is the field we want to capture and we will reference with $3
//it matches any wordCharacter(\\w), one or more reluctantly

//Fourth Field
//This captures the rest of the string including the ";"

//Now to extract the extension from this test string

string test="data:image/jpeg;base64,ABC...";
string testExtension="";

//Replace the contents of testExtension with the 3rd capture field of
//our regex pattern applied to our test string like so

testExtension = test.replaceAll(pattern, "$3");

//This invokes the String class replaceAll() method

//And now our string testExtension should contain "jpeg"


text:
Q: Retrieve the sum of each column I have a table that looks like the following:

A
B
C
D

1
2
3
3

2
3
3
1

3
4
3
3

I want to retrieve a new table with the sum of each column:

A
B
C
D

6
9
9
7

Is there an SQL formula that allows me to do that without mentioning the name of each single column?

A: Not sure what is the scenario and why you don't want to specify the column name, but still if you want to to you can try like following using dynamic query.
DROP TABLE IF EXISTS TEST_TABLE

CREATE TABLE TEST_TABLE  (A INT, B INT,C INT,D INT)
INSERT INTO  TEST_TABLE SELECT 1,2,3,4
INSERT INTO  TEST_TABLE SELECT 2,2,3,4
INSERT INTO  TEST_TABLE SELECT 3,2,3,4
INSERT INTO  TEST_TABLE SELECT 2,2,3,4

DECLARE @Tablename NVARCHAR(max) = 'TEST_TABLE'

DECLARE @qry NVARCHAR(MAX) =
'SELECT ' + STUFF((
    SELECT ', ' +  'SUM(' + QUOTENAME(c.name) + ') AS ' +  QUOTENAME(c.name)
    FROM sys.columns c where c.object_id = object_id(@Tablename)
    FOR XML PATH(''), TYPE).value('.','nvarchar(max)'),1,2,'') +
  + ' FROM ' + @Tablename

EXEC (@qry)

Demo


text:
Q: Is catching a specific exception less expensive than catching a generic one? Say I'm loading a Bitmap onto my Android device. There are many possible exceptions that can be thrown. For the sake of simplicity let's take NullPointerException and OutOfMemoryError.
Now I have two pieces of code.
Code 1
try{
//load the bitmap
}
catch(Exception e)
{
//do something
}

Code 2
try{
//load the bitmap
catch (NullPointerException e)
{
//do something
}
catch(OutOfMemoryError e)
{
//do something else
}

Is one piece of code more effective than the other performance wise? If so, why?

A: From byte code point of view it is more effective (less code) to do the first one.
But you should NEVER look at performance in that way.
If you have the same behavior for all type of exceptions, you should use the first bunch of code, in any other way, the second one.
In byte code you have following code responsible for catching eceptions:
   L2
    LINENUMBER 7 L2
   FRAME SAME1 java/lang/NullPointerException
    ASTORE 1
    GOTO L4
   L3
    LINENUMBER 9 L3
   FRAME SAME1 java/lang/Exception
    ASTORE 1
   L4

So each exceptions has a code that is responsible for catching that, but as I said this is such a minor difference that it shouldn't be taken into consideration.

A: Performance wise there's no difference as only one catch will be executed even in case of multiple catch blocks.
Code wise, yes first one is better as Michal said. Good practice wise second approach is better as you are able to capture specific exceptions and handle them appropriately.
Side note: don't catch out of memory error ever, its an error not exception and you cant handle it effectively

A: if you have different behaviours for each exception the second one is better than the first.
The performances will be the same.


text:
Q: Push view controller not appearing below tab bar controller I have embed the login screen to navigation controller and i use only push method to go to another view when user logs in and all.
When the user press login button, the tab bar controller containing 4 tabs are pushed and viewed.
Default screen is named home which contains two buttons inside the view.
When the user press each button,it should take the user to another view controller without hiding the tab bar below,and it should be the same looking tab bar (my tab bar is transparent).
Problem here is when ever i press the button,Entire view is changed which means the new view controller is presented over top of the tab bar.
I am confused about the navigation controller stuff.
Is there any requirement for any connection between view controllers since i am using push method.I am not using segue from storyboard.
Everything is programatic.
Please help me to fix this out.

A: It happens when you push your viewController into your navigationController or present your viewController modally. You should just change your tabbarController's seletedIndex when you tap the button.
tabBarController.selectedIndex = #index of your controller#


text:
Q: Send SMS with Amazon SNS in node js : Invalid parameter: PhoneNumber Reason: +XXXX is not valid to publish Here is my code for sending SMS to a particular number with AWS sms service.
var AWS = require('aws-sdk');

        AWS.config.update({
            accessKeyId: '{ID}',
            secretAccessKey: '{KEY}',
            region: 'us-east-2'
        });
        var sns = new AWS.SNS();

        var params = {
            Message: 'this is a test message',
            MessageStructure: 'text',
            PhoneNumber: '+XXXXXXXX'
        };

        sns.publish(params, function(err, data) {
            if (err) console.log(err, err.stack); // an error occurred
            else     console.log(data);           // successful response
        });

But i got the following error in console

'InvalidParameter: Invalid parameter: PhoneNumber Reason: +XXXXXX is
  not valid to publish

A: It is a bit misleading to ask everyone to change the region to us-east-1.
All the supported region are listed in the following link:  https://docs.aws.amazon.com/sns/latest/dg/sms_supported-countries.html
P.S. I am new user, I can't add comments or edit anyone posts to include the supported list.

A: SNS currently supports SMS only in the form of E.164 formats, please make sure you are using the same format.
Check it out here: https://en.wikipedia.org/wiki/E.164
Additionally, you are using SNS sms service in us-east-2, which does not support SMS delivery as of yet. Checkout the SMS enabled regions: http://docs.aws.amazon.com/sns/latest/dg/sms_supported-countries.html

A: Please try with setting the region to "us-east-1". It worked for me before.
var sns = new AWS.SNS({ "region": "us-east-1" });

A: change your region us-east-2 to us-east-1 it worked for me
var sns = new aws.SNS({
    "accessKeyId": functions.config().aws.key,
    "secretAccessKey": functions.config().aws.secret,
    "region": "us-east-1",
});


text:
Q: date parsefailure to convert in logstash Mon Nov 18 09:38:45 2019
Is there any idea on how to convert this above date so that it can be digest in grok filter ?
Here is what i did but still date parsefailure is there in logstash
date { match => ["starttime","E MMM dd HH:mm:s yyyy"]
       target => starttime  }

A: You are using wrong the filter. You need to specify that you want a Grok match and give it a name. In addition, it seems that your date format does not follow any of the standards (that can be checked in Github), so you'll need a custom one that adjusts to your format. Something like this should work:
grok {
    match => { "starttime" => "%{DAY} %{MONTH} %{MONTHDAY} %{TIME} %{YEAR}"}
}

This should go inside your filter and then you can use starttime as you wish.


text:
Q: 'NA' stands for 'North America', NOT a NaN / Null I have a value in my pandas df that is 'NA', as a string. It is NOT a null/NaN. In this case 'NA' stands for 'North America', but it's a code, 'EU' is for 'Europe' for example.
.fillna(value='NA') is used after pd.read_csv to correct this. Simple enough for one Jupyter Notebook. But what happens when you then export this data to a new CSV, and upload it again into a different Jupyter Notebook?
Do I need to .fillna(value='NA') all over again? Or is a there a more lasting solution?
Any hacks? I'm guessing something to do with Regex? Or perhaps it is something to do with how Pandas is set up?

A: As @user17242583 said, try np.nan, like:
MY_DICT = {'A':['NA', 456], 'B':[111, 400]}
import pandas as pd
import numpy as np
df = pd.DataFrame(MY_DICT)

print('before:')
print(df)
print('type(df.loc[0,\'A\']):' ,type(df.loc[0,'A']))
print('\nafter: ')
df = df.replace('NA', np.nan)
print(df)
print('type(df.loc[0,\'A\']):' ,type(df.loc[0,'A']))

outputs:
before:
     A    B
0   NA  111
1  456  400
type(df.loc[0,'A']): <class 'str'>

after:
       A    B
0    NaN  111
1  456.0  400
type(df.loc[0,'A']): <class 'numpy.float64'>


text:
Q: Bisectors of two vertical angles are continuations of each other This is a question from Kiselev's Geometry.

The way I argue is that since the $\angle ABC = \angle DBE$, $EB$ and $GB$ are their bisectors respectively, therefore $\angle ABE = \angle EBC = \angle DBG = \angle GBE$.
This proves that EB and BG is continuation of each other, otherwise, if any of the angle above is not equal to one another, we cannot have $\angle EBG=180^{\circ}$
Is my proof correct? Is there any other ways to prove this proposition?

A: I think you are on the right track. We can show using bisector definition and transitivity that $\angle ABF = \angle FBC = \angle DBG = \angle GBE$ (I think point between $A$ and $C$ should be $F$) . Then $\angle DBC = \angle DBG + \angle GBE + \angle EBC=180^{\circ}$ but we also have that $\angle GBF = \angle GBE + \angle EBC + \angle CBF=\angle GBE + \angle EBC + \angle DBG=180^{\circ}$

A: I think easier is to say $\angle EBC=\angle DBG$ because they are half the vertical angles, then $\angle EBG=\angle CBD+\angle CBE-\angle DBG$


text:
Q: Equivalent of TypeScript Record in Flow? TypeScript provides the utility type Record and I am looking for its equivalent in Flow.
I tried: { [key: KeyType]: Value } but that definition has a different semantic.

A: The equivalent is almost identical to TypeScript:
// @flow

type Record<T, V> = {
  [T]: V
}

Pulling the example from the TypeScript docs:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>

const test: ThreeStringProps = {
  prop1: 'test',
  prop2: 'test',
  prop3: 'test',
}

// Fails because prop3 is not a string
const failingTest: ThreeStringProps = {
  prop1: 'test',
  prop2: 'test',
  prop3: 123,
}

// Fails because `prop4` isn't a valid property
const failingTest2: ThreeStringProps = {
  prop1: 'test',
  prop2: 'test',
  prop3: 'test',
  prop4: 'test',
}

You can see this in action at Try Flow.


text:
Q: Read specific element from XElement I want to bind the MultipleCheckbox items from Choice Column of sharepoint List to asp.net CheckBoxListItem using c#. I am retriving information of List using XELEMENT as:
XElement listStructure;

listStructure = proxy.GetList("WebsiteSubscriber");

<Field Type="MultiChoice" DisplayName="Area" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" FillInChoice="FALSE" ID="{16cc1615-a490-44de-a870-c7ebe603e2cc}" SourceID="{2c8a80ea-38c5-48f7-9d7d-400d445a5e64}" StaticName="Area" Name="Area" ColName="ntext2" RowOrdinal="0">
  <Default>Articles</Default>
  <CHOICES>
    <CHOICE>Articles</CHOICE>
    <CHOICE>Websites</CHOICE>
    <CHOICE>Books</CHOICE>
  </CHOICES>
</Field>

I want to read choices from this XML. and get values only "Articles,Websites,Books"
Note: This XML may contain many sections with <choices> i want to fetech it by <fieldType> or the DisplayName="Area" attribute and get values in c#.

A: Try this:
var temp =
    listStructure.Descendants("Field")
                 .Where(i => i.Attribute("DisplayName").Value == "Area")
                             .Select(i => i.Descendants("CHOICE")
                                          .Select(j => j.Value)).ToList();

List<string> result = new List<string>();

foreach (IEnumerable<string> item in temp)
{
    result.AddRange(item);
}

//result: Articles; Websites; Books

A: var xml = @"<Field Type=""MultiChoice"" DisplayName=""Area"" Required=""FALSE"" EnforceUniqueValues=""FALSE"" Indexed=""FALSE"" FillInChoice=""FALSE"" ID=""{16cc1615-a490-44de-a870-c7ebe603e2cc}"" SourceID=""{2c8a80ea-38c5-48f7-9d7d-400d445a5e64}"" StaticName=""Area"" Name=""Area"" ColName=""ntext2"" RowOrdinal=""0"">
  <Default>Articles</Default>
  <CHOICES>
    <CHOICE>Articles</CHOICE>
    <CHOICE>Websites</CHOICE>
    <CHOICE>Books</CHOICE>
  </CHOICES>
</Field>";

var doc = XDocument.Parse(xml);

XElement element =
         doc.Descendants("Field")
            .First(field => (string)field.Attribute("DisplayName") == "Area");

string[] result =
         element.Descendants("CHOICE")
                .Select(v => (string)v)
                .ToArray();

Console.WriteLine(string.Join(Environment.NewLine, result));

prints:
Articles
Websites
Books


text:
Q: CSS Overflow Firefox issue I am trying to write a CSS in which when the user writes text and it overflows instead of having a scrollbar or hiding, it just goes down like in a normal Word Document or so. I have this code:
#content-text {
    width: 960px;
    padding-left: 10px;
    padding-right:10px;
    text-align: left;
    color:#000;
    height:100%;
    margin-left: 25px;
    margin-right:25px;
}

The odd thing, is that while this code actually does what I want in IE in Firefox it overflows and becomes a scrollbar. I've tried overflow:auto; overflow:hidden; and overflow:inherit; just to see if any helped but no luck so far, and I honestly have no idea of why is this happening in Firefox, =/ would any of you know?

Update:
I tried with overflow:visible; but I just get the overflow...well visible but still it doesn't wraps. and ONLY in Firefox so far. =/

Update:
The only other thing that could be affecting is that I have another CSS code and the first is contained:
#content-title{
    background-color: transparent;
    background-image: url(../img/content-title-body.png);
    background-repeat: repeat-y;
    background-attachment: scroll;
    background-x-position: 0%;
    background-y-position: 0%;
    height:auto;
    position:absolute;
    z-index :100; /* ensure the content-title is on top of navigation area */
    width:1026px;/*1050px*/
    margin: 160px 100px 5px 100px;
    overflow: visible;
    top: 55px;
}

and the HTML that uses this is:

             Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!Hola!
Hola!Hola!Hola!Hola!Hola!Hola!
Hola!Hola!Hola!Hola!
Hola!Hola!Hola!Hola!
Hola!Hola!Hola!
Hola!Hola!Hola!Hola!
Hola!Hola!

A: Try: overflow: visible.

A: So your css is probably fine.  For example on my page I have css is like this:
 textarea.input_field2 {
    margin: 10px 10px 10px 0px;
    width: 440px;
    height: 150px;
    background:#696969;
    color: white;
    border: none;
    font-size: 14px;
    text-align: left;
    vertical-align: middle;
    }

Then in the body I call it up like this:
 <textarea rows="9" cols="9" class="input_field2" name="user_comments"></textarea>

It works fine.
But make sure when you test it you test it with something like Lorem Ipsum, words with spaces and not one long string like 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' cause that will force a scroll bar probably.  Also check your html and css for validation.

A: There must be more to the story than you are showing here.  I used the CSS provided and I am seeing the same behavior in both Internet Explorer and Firefox.  The page is rendered 960 pixels wide and when the browser width is less than this, a horizontal scroll bar is rendered.
If you specify a width on an element, the browser is not going to render it less than this value.  If you remove the width declaration from your example, the element will only render as wide as it needs to.
If this is not the answer you are looking for, please provide more code to give us the whole picture.

A: Add word-wrap: break-word; to your #content-text


text:
Q: Custom view not filling parent I have a custom view like this
public class ButtonBar extends HorizontalScrollView
{
  public View mButtonRows;

  public ButtonBar(Context context, AttributeSet attrs)
  {
    super(context, attrs);
    LayoutInflater inflater = (LayoutInflater)
        context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mButtonRows = inflater.inflate(R.layout.toolbar, null);

    // button click handling code goes here

    addView(mButtonRows);
  }
}

which is included in my main xml like this
<com.example.ButtonBar
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_alignParentBottom="true"
  android:layout_below="@+id/pagecontent" />

and inflates an xml file like this:
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/ButtonsRow"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal">
  <Button
    android:id="@+id/button1"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_weight="0.3"
    android:text="button1"
  />
  <Button
    android:id="@+id/button2"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_weight="0.3"
    android:text="button2"
  />
  <Button
    android:id="@+id/button3"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_weight="0.3"
    android:text="button3"
  />
</LinearLayout>

(It currently only has three buttons, but more are going to be needed in later versions, hence the HorizontalScrollView.)
Looking in hierarchyviewer, the custom view does seem to be screen wide, but the LinearLayout is only as wide as the buttons it contains (about 2/3 of the screen at the current button size), despite having the fill_parent width set; the buttons don't stretch.  If I set the LinearLayout's background to @android:drawable/bottom_bar (which is a png the width of the screen), the buttons properly resize; I realise I could do the same thing by creating my own images to match, but I'd much rather do it without if possible.
What am I doing wrong?

ETA: if I change HorizontalScollView to ScrollView, it works fine.  Do HSVs just not allow their children to "fill_parent"?

ETA2: Setting android:fillViewport="true" in the main xml fixed it!

A: Setting android:fillViewport="true" in the main xml fixed it!

A: If you change to this, for each of the buttons, does it work?
android:layout_width="0px"
android:layout_weight="1"