text:
Q: When we have persist MEMORY_ONLY option in spark then why we need cache () function? What is the exact difference between these 2 and when to use what cache() method default saves it to memory (MEMORY_ONLY). In persist() method if we define it as persist(StorageLevel.MEMORY_ONLY) it is same as cache(). So then what is the difference between these two? why we need cache() when we can use persist(StorageLevel.MEMORY_ONLY) or vice versa.
Please advice, thanks

A: One is just a handy shortcut for the other, there is no difference. (Infact I believe cache just calls persist(StorageLevel.MEMORY_ONLY))


text:
Q: Handling null objects in an array I have an array with 18 objects in it, and the array is allocated to have 25 objects in it (the remaining 7 objects are null for future use). I'm writing a program that prints out all the non-null objects, but I'm running in to a NullPointerException and I can't figure out how to get around it.
When I try this, the program crashes with Exception in thread "main" java.lang.NullPointerException:
        for(int x = 0; x < inArray.length; x++)
        {
            if(inArray[x].getFirstName() != null)//Here we make sure a specific value is not null
            {
                writer.write(inArray[x].toString());
                writer.newLine();
            }
        }

And when I try this, the program runs, but still prints the nulls:
        for(int x = 0; x < inArray.length; x++)
        {
            if(inArray[x] != null)//Here we make sure the whole object is not null
            {
                writer.write(inArray[x].toString());
                writer.newLine();
            }
        }

Can anyone point me in the right direction for handling null objects in an array? All help is appreciated!

A: your check should be:
if(inArray[x] != null && inArray[x].getFirstName() != null)

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to filter isNullOrEmpty in spark scala In code below, I am filtering based on isNull and now I want to filter null or Empty string both. Can anyone please help me with this code:
type IdentifiedDataFrame = {SourceIdentfier, DataFrame}
def splitRequestIntoDFsWithAndWithoutTransactionId(df: DataFrame) : Seq[IdentifiedDataFrame] = {
    seq((DeltaTableStream(RequestWithTransactionId),
         df.filter(
           col(RequestLocationCodeColName).isNull &&
           col(ServiceNumberColName).isNull &&
           col(DateOfServiceColName).isNull &&
           col(TransactionIdColName).isNotNull)),

        (DeltaTableStream(RequestWithoutTransactionId),
         df.filter(
           col(RequestLocationCodeColName).isNotNull &&
           col(ServiceNumberColName).isNotNull &&
           col(DateOfServiceColName).isNotNull)))
}


text:
Q: Accessing objects in a JSON Array to generate a modal window's content I have 6 bootstrap cards generated from 6 objects, each card has a button that gets a data-id from the ids of the objects. When I press the button I would like the content that matches that id to appear in its own modal window but everything is appearing right now. How can I achieve this?
Image of card:

Image of all data appearing:

main.js
var data = [
  {id: 0, name: 'Cause1', desc: 'This is cause 1', descLong: "This is a longer description of cause 1", votes: 10, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 1, name: 'Cause2', desc: 'This is cause 2', descLong: "This is a longer description of cause 2", votes: 20, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 2, name: 'Cause3', desc: 'This is cause 3', descLong: "This is a longer description of cause 3", votes: 30, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 3, name: 'Cause4', desc: 'This is cause 4', descLong: "This is a longer description of cause 4", votes: 40, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 4, name: 'Cause5', desc: 'This is cause 5', descLong: "This is a longer description of cause 5", votes: 50, votesTarg: 100, image: "https://via.placeholder.com/220"},
  {id: 5, name: 'Cause6', desc: 'This is cause 6', descLong: "This is a longer description of cause 6", votes: 60, votesTarg: 100, image: "https://via.placeholder.com/220"}
];

  for (var i=0; i < data.length; i++){
document.getElementById('row').innerHTML += ("

" + data[i]["name"] + "

 " + data[i]["desc"] + "
<button type='button' class='btn btn-primary readmore' data-toggle='modal' data-target='#modal-info' data-id='" + data[i]["id"] + "' value='" + data[i]["id"] + "'>Read more</button>

" + data[i]["votes"] + " / " + data[i]["votesTarg"] + " signatures" + "

10% Complete

");

document.getElementById('modal-title').innerHTML += data[i]["name"];
document.getElementById('modal-desc').innerHTML += data[i]["descLong"];
}

index.html

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              ×
            </button>

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Sign the Cause</button>

A: You are appending all data objects to without checking the data-id of the card.
Please try this:
    /*
    please replace readmoreElement (I just used that name to convey the point - to retrieve data-id attribute value) with your button element (or) use event.target.id.
    I am assuming you are invoking this on the button click of "Read More". so, in the button click event, you will get id of the button via event.target.id
    */
        var temp = readmoreElement.getAttribute('data-id'); // document.getElementById(event.target.id).getAttribute('data-id');
        // instead of for loop you can pluck the element by using underscore or lodash library functions.
        for (var i=0; i < data.length; i++){
            if (temp === i)
            {
                document.getElementById('row').innerHTML += ("

" + data[i]["name"] + "

 " + data[i]["desc"] + "
<button type='button' class='btn btn-primary readmore' data-toggle='modal' data-target='#modal-info' data-id='" + data[i]["id"] + "' value='" + data[i]["id"] + "'>Read more</button>

" + data[i]["votes"] + " / " + data[i]["votesTarg"] + " signatures" + "

10% Complete

");

                document.getElementById('modal-title').innerHTML += data[i]["name"];
                document.getElementById('modal-desc').innerHTML += data[i]["descLong"];

                break;
            }
        }


text:
Q: Trying to parse a nested json and store in a nested Map. While reading it gives extra values in the Map. Code, output and json below Map < String, Map < String, String >> appPayload = new HashMap < String, Map < String, String >> ();
Map < String, String > featurePayload = new HashMap < String, String > ();

JSONArray appList = new JSONArray();
JSONArray requestDetails = new JSONArray();
requestDetails = new JSONObject(payload).getJSONArray("requestDetails");
appList = requestDetails.getJSONObject(0).getJSONArray("apps");

for (int i =0; i<appList.length();i++) {

    String appName = appList.getJSONObject(i).getString("appName");
    JSONArray featureList = appList.getJSONObject(i).getJSONArray("features");

    for (int j =0; j<featureList.length();j++) {
        String featureName = featureList.getJSONObject(j).getString("featName");
        String featureResponse = featureList.getJSONObject(j).getString("featResponse");
        featurePayload.put(featureName, featureResponse);
    }
    appPayload.put(appName, featurePayload);
}

return appPayload;

}

Output :
Appname : CD
{Video Snapshot=enabled, Base=enabled}

Appname : CSU
{Video Snapshot=enabled, Base=enabled}

Appname : FO
{Video Snapshot=enabled, Base=disabled}

Appname : EDL
{Video Snapshot=enabled, Base=enabled}

Appname : CA
{Video Snapshot=enabled, Base=disabled}

And here is the json string
{
  "apiVersion": "1.0",
  "providerID": 504070500,
  "timeStamp": "2019-09-12T19:51:56.902Z",
  "messageID": "3abb70f4-d5bb-11e9-bb65-2a2ae2dbcce4",
  "requestDetails": [
    {
      "esn": "64000008",
      "boxID": "357649070551015",
      "apps": [
        {
          "appName": "CD",
          "features": [
            {
              "featName": "Base",
              "featResponse": "enabled"
            },
            {
              "featName": "Video Snapshot",
              "featResponse": "enabled"
            }
          ]
        },
        {
          "appName": "CSU",
          "features": [
            {
              "featName": "Base",
              "featResponse": "enabled"
            }
          ]
        },
        {
          "appName": "FO",
          "features": [
            {
              "featName": "Base",
              "featResponse": "disabled"
            }
          ]
        },
        {
          "appName": "EDL",
          "features": [
            {
              "featName": "Base",
              "featResponse": "enabled"
            }
          ]
        },
        {
          "appName": "CA",
          "features": [
            {
              "featName": "Base",
              "featResponse": "disabled"
            }
          ]
        }
      ]
    }
  ]
}

A: Try to instantiate featurePayload before the nested loop


text:
Q: List all living nodes / actions / animations in a Cocos2D app Is it possible to list all living nodes (actions and animations are of interest to me too) in a Cocos2D app?
Currently I am fighting memory issues in an app and even though profiler helps with that I would like to try other approaches too.

A: You can recursively list all child nodes. The start node will be your scene. For actions, I know that you can get number of actions for given node, but i don't know if it is possible to list all actions in some way.
Also, you may use CCTextureCache to check if all of unused textures were already removed from memory. It has no public methods to access this data, but you can see loaded textures names in debugger or add some dumping method.
To prevent memory leak by scheduling some action on node, that you want to remove from parent, send cleanup message to all of nodes before removing from parent. Or if it is instance of your class, make [self cleanup]; in it's onExit() method.
I don't think, that you can receive the list of all created nodes. It sounds like garbage collection in .net =) In objective-C you must watch for leaked objects by yourself.


text:
Q: Solve $\frac{1}{|x-2|} > 1$ I tried this:
\begin{align*}
            \frac{1}{|x-2|} > 1
            &\iff \left|\frac{1}{x-2}\right| > 1\\
            &\iff \frac{1}{x-2} > 1 \vee \frac{1}{x-2} < -1\\
            &\iff 1 > x-2 \vee 1 < 2 - x\\
            &\iff 3 > x \vee 1>x
        \end{align*}
Which means that $x\in (-\infty, 3)\cup (-\infty, 1)$. But the solution should be $x\in\left(1,\:2\right)\cup \left(2,\:3\right)$.


text:
Q: Android action bar overlay Is there a way to extend the action bar in android for a single icon like in the image below? I would like to highlight the rightmost action to the user. I know that this might be against the design guidelines.

A: You can use tabs instead of buttons to get a bar beneath the selected icon. You can add icons to a tab using setIcon() of class ActionBar.Tab.


text:
Q: asp.net textarea title should display the content of textbox Is there a way to define attribute of textarea title='this.value' so that what change made on value of text area will reflect on tooltip.
My requirement is to show the entire content of textarea as tooltip since the page holds large number of text areas and size of text area is too small. so instead of scrolling they want to see complete text as tooltip on hovering on top of the text area.


text:
Q: python nmap: what to do to speed up the process I am working on idea to check port status of websites using NMAP library of python. so, I done some code, I used This Link to check 'open' word in dictionary I was getting in to print directly port number and status.
I need help to get result fast as I am not able to do it. I want to check port range of 80 to 443 ports.whenever I try to do that range It takes about 15 mins for one host (i.e. google.com). I have about 4-5 host names with range of 80 to 443 ports to check.
code image is for reference, what my code is looked like. but I used a list for host names. and basically two for loops to work all this. one for host name and other for range of port numbers.
any help is appreciated.
Thank you

A: Hmm, that's really slow for a scan which would indicate to me there's something wrong with the host you're scanning (IDS?) or poor connection (you probably ruled this out). I believe IPs should be strings (as you correctly did in your script) but ports are numeric. Also maybe try scanning your local host or another local network machine which will be much faster and won't block your IP.
Either way, some other  ways to improve your speed include multi-threading (via threading, Queue and a host of other libraries), passing the T1-5 flags in Nmap (-T0 is slowest, -T3 is default, -T5 is insane mode).  There's also IDS evasive Nmap settings if you're set on scanning actual remote hosts


text:
Q: Not able to get the Latitude and Longitude while using 'GeoLocator' package
*

*I am trying to use 'GeoLocator' to retrieve Latitude & Longitude. However, not able to get any output?

*Also will be helpful if someone can help me organize the 'geoLocator' package as a service in a separate dart file.

*As suggested I tried changing the code, but still not able to get the geolocation. Also when I call the '_determinePosition()' getting "Instance of 'Future'
".

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //

  Future<Position> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.deniedForever) {
        // Permissions are denied forever, handle appropriately.
        return Future.error(
            'Location permissions are permanently denied, we cannot request permissions.');
      }

      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }

    return await Geolocator.getCurrentPosition();
  }

  @override
  Widget build(BuildContext context) {
    // TESTIST IF PRINT CAN WORK HERE
    print(_determinePosition());
    return Scaffold(
      appBar: AppBar(
        title: Text("Location"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
              child: Text("Get location"),
              onPressed: () {
                // PRINTING IN THE CONSOLE
                _determinePosition();
              },
            ),
          ],
        ),
      ),
    );
  }
}

A: Try to add the Internet permission in addition to the location permissions per the documentation (https://pub.dev/packages/geolocator):
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Regarding getting "intsantce of a Future" instead of the result you need to await the call to _determinePosition() just like this:
onPressed: () async{
            // PRINTING IN THE CONSOLE
           await _determinePosition();
          },

For using Geolocator as a service I recommend to use a dependency injection solution like Provider(https://pub.dev/packages/provider) or GetIt(https://pub.dev/packages/get_it)

A: Use below function which checks the permission and returns current position, so before getting location it's important to check whether we had required permission or not.
import 'package:geolocator/geolocator.dart';

/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
  bool serviceEnabled;
  LocationPermission permission;

  // Test if location services are enabled.
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    // Location services are not enabled don't continue
    // accessing the position and request users of the
    // App to enable the location services.
    return Future.error('Location services are disabled.');
  }

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
        'Location permissions are permanently denied, we cannot request permissions.');
    }

    if (permission == LocationPermission.denied) {
      // Permissions are denied, next time you could try
      // requesting permissions again (this is also where
      // Android's shouldShowRequestPermissionRationale
      // returned true. According to Android guidelines
      // your App should show an explanatory UI now.
      return Future.error(
          'Location permissions are denied');
    }
  }

  // When we reach here, permissions are granted and we can
  // continue accessing the position of the device.
  return await Geolocator.getCurrentPosition();
}


text:
Q: How to convert an array of strings values to numeric values for Mongoose schema containing few numeric fields? My problem is that, I have a MongoDB collection named 'sold', which contains some string fields and some numeric fields.
    const soldSchema = new Schema(
  {
    sku: String,
    hsn: String,
    qty: Number,
    article: String,
    mrp: Number,
    disc: Number,
    taxrate: Number,
    tax: Number,
    total: Number,
    orderid: String,
  },
  { collection: "sold", timestamps: true }
);
const Sold = mongoose.model("sold", soldSchema);
module.exports = { Customer, Stock, Sold, Order };

The 'Customer', 'Stock', and 'Order' are other schema are in the same module.
For the sold schema, I received the data from the front end, which is an array of objects like this as shown below:
[
  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops',
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  },
  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops',
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  },
  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops',
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  }
]

The above array is the result of req.body i.e. console.log(req.body)
If I change all the fields to type 'String' in soldSchema, then all the values get inserted in a single go.
This function works fine with all string values in the schema.
async function insertManySold(req, res) {
  let items = req.body;
  try {
    let result = await model.Sold.insertMany(items);
    res.json(result);
  } catch (error) {
    res.json(error);
  }
}

But, if I change the data types to Numbers for some fields in the schema as mentioned above, then it doesn't work. Please let me know how to achieve this.
I have searched many articles on the web but could not find the answer.
Could you please help me?

A: Your above code won't work for string contains characters like (abc...z), Number will convert any string which contains alphabets to NaN, you should try this way instead.

const object1 =  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops',
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  }

const data = {}

for (const [key, value] of Object.entries(object1)) {

  const temp_value = Number(value)

  // Here we are checking for NaN and 0
  data[key] =  temp_value ? temp_value : temp_value == 0 ? 0 : value

}

console.log(data);

Your way will give this error run below code

let items=
  {
    sku: '10005',
    hsn: '3652',
    qty: '3',
    article: 'tops', // Look for this key
    mrp: '550',
    disc: '0',
    taxrate: '5',
    tax: '82.50',
    total: '1732.50',
    orderid: '1633515982545'
  }

    let data = {}
    for ( let key in items ) {
      data[key] = Number(items[key])
    }
console.log(data)

A: when i posted this question i was very new in javascript, so i couldn't think of it like a programmer, the answer is very simple, all you have to do is to parse the object i.e. req.body again. i mean to say, make a new object and insert all the values in it via looping over req.body. like this.
let items=req.body
    let data = {}
    for ( let key in items ) {
      data[key] = Number(items[key])
    }

if the req.body has any numerc value it will get parsed into numbers and get stored in the new object data.
this solution worked for me if there is any other approach for the same, please share it with me here.
tanks.

A: I suggest this should be handled from front-end directly.
Otherwise you need to convert for each known Number key, because this Number will convert,
each string which has numeric values into Number.
string with char. data into NaN.
and, as you are storing sku,hsn,orderId in String, but Number will convert into numeric value.
so i strongly suggest handle this from frontend directly.


text:
Q: Need terminate and main menu options on C# CODE Excuse the messy code haha I'm currently learning how to  C# code. The user needs to be able to navigate between the main menu and carry out other operations without needing to terminate the program. There also needs to be an option to 'exit' or terminate at any stage when the program is running.
I've tried for days but i CAN'T figure it out. :(
Can someone please help me.
using System;

namespace TASK1.ASS_BMI
{
    class Program
    {

        static void Main(string[] args)

        {

        //Main menu

            string location;
            Console.WriteLine("Please select from the following options.");
            Console.WriteLine("BMI calculator");
            Console.WriteLine("Membership rates");
            Console.WriteLine("Type Exit to terminate application.");
            Console.ReadKey();

                location = Console.ReadLine();

                switch (location)
            {
                //BMI
                case "BMI calculator":
                    {
                        Console.WriteLine("Welcome to the BMI Calculator");
                        Console.WriteLine("Press any key to continue");
                        Console.ReadKey();

                        // Ask User their name, Stored as UserName.
                        Console.WriteLine("What is your name?");
                        string userName = Console.ReadLine();

                        //Ask User Height, Stored in UserHeight
                        Console.WriteLine("\nHello " + userName + ". What is your height? (CM)");
                        double UserHeight = Convert.ToDouble(Console.ReadLine());

                        //Ask User Weight, Store as UserWeight
                        Console.WriteLine("\nAnd finally, what is your weight? (KG) ");
                        double UserWeight = Convert.ToDouble(Console.ReadLine());

                        //Calculate BMI
                        // BMI FORMULA = WEIGHT / HEIGHT * Height

                        UserHeight = UserHeight / 100;
                        double BMI = UserWeight / (UserHeight * UserHeight);

                        if (BMI < 18.5)
                        { Console.WriteLine("Your BMI is " + BMI + ". According to guidelines you are underweight"); }  //Telling User that they are underweight
                        if (BMI >= 18.6 & BMI <= 24.9)
                        { Console.WriteLine("Your BMI is " + BMI + ". According to guidelines you are normal"); } //Telling User that they are Normal Weight
                        if (BMI >= 25 & BMI <= 29.9)
                        { Console.WriteLine("Your BMI is " + BMI + ". According to guidelines you are overweight"); } //Telling User that they are Overweight
                        if (BMI > 30)
                        { Console.WriteLine("Your BMI is " + BMI + ". According to guidelines you are obese"); } //Telling User that they are Obese
                        break;
                    }

                case "Membership rates":

                    {

                        //Ask user what membership they want
                        Console.WriteLine("What type of membership would you like?");
                        Console.WriteLine("Basic");
                        Console.WriteLine("Regular");
                        Console.WriteLine("Premium");
                        Console.ReadKey();

                        String name = Console.ReadLine();  // read a string (name) from the screen

                        if (name.Contains('c'))
                        {
                            Console.WriteLine("Our Basic membership fee is $40 a month. That is only $10 a week!"); //Telling User Basic fee
                        }
                        if (name.Contains('l'))
                        {
                            Console.WriteLine("Our Regular membership fee is $60 a month.That is only $15 a week!"); //Telling User Regular fee
                        }
                        if (name.Contains('m'))
                        {
                            Console.WriteLine("Our Premium membership fee is $80 a month.That is only $20 a week!"); //Telling User Premium fee
                        }

                        break;

                    }

                        default:
                    {
                        Console.WriteLine("Sorry I didn't get that. Remember, I am case sensitive..Please try again.");

                        break;
                    }

                    } // end of switch
        }  // end of Main
    }


text:
Q: Allocated memory for returning values in C If the return value of a function, say, myFunc, is an allocated space. Does the parent function still need to free that part of the memory?
For example:
char * myFunc() {
    return malloc(5);

    // free() not called
}

int main() {
    char * str = myFunc();

    // does str need to be freed?
    return 0;
}

A:
To free() or not to free()?

When a process terminates, all of its memory is returned to the system, including heap memory allocated by functions in the malloc package. In programs that allocate memory and continue using it until program termination, it is common to omit calls to free(), relying on this behavior to automatically free the memory. This can be especially useful in programs that allocate many blocks of memory, since adding multiple calls to free() could be expensive in terms of CPU time, as well as perhaps being complicated to code.
Although relying on process termination to automatically free memory is acceptable for many programs, there are a couple of reasons why it can be desirable to explicitly free all allocated memory:
 1. Explicitly calling free() may make the program more readable and maintainable in the face of future modifications.
 2. If we are using a malloc debugging library to find memory leaks in a program, then any memory that is not explicitly freed will be reported as a memory leak. This can complicate the task of finding real memory leaks.
3. To avoid memory leak.

A: It is recommended that str is to be freed: replace // does str need to be freed? with free(str). This is good programming practice to avoid potential memory leaks.
In your case, the OS will clean up the allocated memory taken by this short program.


text:
Q: SQL Server 2008 R2 Express 10GB Filesize limit I have reached the file size limit on my SQL Server 2008 R2 Express database which I believe is 10Gb. I know this because I see Event ID 1101 in the event log.

Could not allocate a new page for database 'ExchangeBackup' because of insufficient disk space in filegroup 'PRIMARY'

I have removed some historic data to work around the problem for now but it is only a temporary fix. One table (PP4_MailBackup) is much larger than the others so when I created this database 12 months ago, I converted this table to be a Filestream table and the data is stored outside the FileGroup in the File System. This appeared to be working successfully until I received the error and new data was no longer being added to my database.
When I do a report on table sizes I see the Reserved(KB) column adds up to almost 10GB.
The folder that holds my FileStream data is 176 GB
The database .mdf file is indeed 10GB.
Does anyone have any idea why the table PP4_MailBackup is still using nearly 7GB?
Here is the "Standard Reports -> Disk Usage report" for this database:
Thanks in advance
David

Update
Here is some more info.
There are 868,520 rows in this table.
This cmd returns 1 so I'm assuming Ansipadding is on. I have never changed this from the default.
SELECT SESSIONPROPERTY('ANSI_PADDING')

The columns are defined like this

Even if every record for every column filled the full record size, by my rough calculation the table would be around 4,125,470,000 bytes. I understand that the nvarchar columns only use the actual space required.
I'm still missing a lot of space.

A: Not really an answer but more of a conclusion.
I have given up on this problem and resided myself to remove data to stay under the 10GB Primary file size limit.  I figured out that the nvarchar columns store 2 bytes per character in order to deal with Unicode characters although they do only use the space required and don't pad out the column with spaces. So this would account for some of the space I can't find.
I tried to convert my char(500) columns to varchar(500) by adding new columns with the correct type copying data into them and then removing the old column.  This worked but the table actually got bigger because removing the column is only a Meta data change and does not actually remove the data.  To recover the space I would need to create a new table and copy the data across then remove the old table of course I don't have enough space in the primary file to do that.
I thought about copying the table to temp db removing the original table then copying it back but temp db doesn't support filestream columns (at least to my knowledge) so I would need to hold all 170GB within the temp db table.  This sounded like a dubious solution and my test server didn't have enough space on the partition where temp db was stored.  I couldn't find anything on the files size limit of tempdb  on sql 2008 Express, but at this point it was all getting too hard.


text:
Q: Javascript: is there "Symbol.iterator" analogue for the object spread syntax - { ...obj }? There is a well known symbol: Symbol.iterator, that, when defined as a generator function property on an object, allows the object to be used in a [...object] syntax. So, you can do, eg., this:
const newArray = [ ...foo, ...object, ...bar ];

However, I couldn't find an analogue of that functionality, allowing this:
const newObject = { ...foo, ...object, ...etc };

or Object.assign with non-own properties.
Case in point: instances of ES6 classes with get prop() / set prop() accessors - they are defined on the .prototype property of the class constructor:
const C = class {
  #num = 42;
  #str = 'aaa';

  get num() { return this.#num; }
  set num(val) { /* validate new value */ this.#num = val; return true; }

  get str() { return this.#num; }
  set str(val) { /* validate new value */ this.#num = val; return true; }
}

const obj = new C();

Now obj has built-in validation for obj.num = ... and obj.str = .... However, it cannot be used in {...foo, ...obj}, or in Object.assign(foo, obj), because the accessors are on the prototype. Proxies can be spread, and property acces trapped for validation, but one of my goals is to make accessing obj.prop as close in performance as possible to accessing plain object prop. And look at this:
const p = new Proxy({ num: 0 }, {});

suite.add('instance with class-accessors', () => obj.num++);
suite.add('proxy', () => p.num++);
suite.run();

instance with class-accessors x ***235***,971,841 ops/sec ±0.20% (86 runs sampled)
proxy x ***1***,014,238 ops/sec ±1.91% (84 runs sampled)

Two orders of magnitude slower! So, is there a way to allow { ...obj } / Object.assign for instances with prototype based getters?
I did experiment, just in case, with defining *[Symbol.iterator]() {...} in the class, yielding Object.entries-style pairs of [prop, val], didn't work. Didn't find anything useful on MDN's "Well known symbols". Expected to find something like, eg., Symbol.entries, something that can control spread/assign and make instances with getters usage transparent.

A: No, there is not. Object literal spread syntax just picks all enumerable own properties, that's it.
The common workaround is to define a getter method to serialise an object that can be spread as you want, often also used for JSON conversion:

class C {
  #num = 42;
  #str = 'aaa';
  get num() { return this.#num; }
  get str() { return this.#num; }
  // …
  toJSON() {
    return {num: this.#num, str: this.#str};
  }
}

const object = new C();

const newObject = { x: 1, ...object.toJSON(), y: 2 };
console.log(newObject);
console.log(JSON.stringify(object));


text:
Q: python open an access database with pyodbc I am trying to open a MS Access Database with python :
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\file.accdb')
cursor = conn.cursor()
cursor.execute('select * from Table1')

but I get this error :`
InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')`
MS Access and Python are both in 64bit and by looking closer I discovered that my available DSN is an Adaptative Server Client and I do not have Microsoft access Driver
Does anyone know how I can make the connection?


text:
Q: Changing controller variable from directive and passing it to ng-show - Angular JS I need to change a controller variable from a directive and then pass its updated value to ng-show. Please see my code below:
Controller:
self.menuVisible = false;

Directive:
icon.bind('click', function(){
    scope.menuCtrl.menuVisible = true;
})

NOTE: there are lot more code lines in the directive which are not relevant to the question, and this is the reason why I use directive instead of controller function which I could pass with ng-click.
View:

Although nothing visible happens on the element click, when I check the menuCtrl.menuVisible in devtools it returns true after the action.
Could you please explain what I am doing wrong?
Thanks in advance!

A: Most likely you're not updating your variable inside $digest loop, try like this:
icon.bind('click', function(){
    $scope.$apply(function() {
        scope.menuCtrl.menuVisible = true;
    }
})


text:
Q: how to create form elements with custom name in cakephp? I am working on existing project. There are many forms like this:
<?php echo $form->create('MyForm', array('id' => 'MyFormId')); ?>

  <?php echo $form->input('User.0.username', array( 'label' => false, )); ?>
  <?php echo $form->input('User.0.location', array( 'label' => false, )); ?>

<?php echo $form->end(); ?>

It is generating form elements like this:
<input type="text" id="User0Username" name="data[User][0][username]">
<input type="text" id="User0Location" name="data[User][0][location]">

Bu I want them to be look like this:
<input type="text" id="User0Username" name="User_0_username">
<input type="text" id="User0Location" name="User_0_location">

Is there any $form->create(); function option to get this html instead of changing my forms elements?
Thanks

A: The Form helper is pretty smart. Whenever you specify a field name with the form helper methods, it'll automatically use the current model name to build an input with a format like the following:

    <input type="text" id="ModelnameFieldname" name="data[Modelname][fieldname]">

You can manually specify the model name by passing in Modelname.fieldname as the first parameter.
echo $this->Form->input('Modelname.fieldname');

If you need to specify multiple fields using the same field name, thus creating an array that can be saved in one shot with saveAll(), use the following convention:
<?php
echo $this->Form->input('Modelname.0.fieldname');
echo $this->Form->input('Modelname.1.fieldname');
?>

<input type="text" id="Modelname0Fieldname" name="data[Modelname][0][fieldname]">
<input type="text" id="Modelname1Fieldname" name="data[Modelname][1][fieldname]">

A: I always use the bracket version - even for jquery ajax submit. this way it works, by the way:
var ids = new Array();
var myCheckboxes = new Array();
$("#ProductCalculation input:checked").each(function() {
    ids.push($(this).val());
});
...
$.ajax({
    dataType: 'json',
    type: "post",
    data: {
        'data[Product][product_calculation_id]': ids,
        'data[Product][brand_id]': brands,
        'data[Category][Category]': categories,
        'data[Form][connect]': c
    },
    url: targeturl,
    beforeSend: function(xhr) {
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    },
    success: function(html) {
        ...
    }
});

you can manually grab the form elements. not ideal, but it does not break cake-styled coding
i am also sure one could write a jquery plugin to make this automatically in some way. that is actually quite an interesting thing to do.


text:
Q: BigQuery Firebase Average Coins Per Level In The Game I developed a words game (using firebase as my backend) with levels and coins.
Now, I'm facing some difficulties while trying to query my DB, so that it will output a table with all levels in the game and average user coins for each level. For example :
Level     Avg User Coins
0             50
1             12
2             2

Attached is a picture of my events table:

So as you can see, there is an event of 'level_end', then we can see the 'user coins' and 'level_num'. What is the right way to do that?
This is what I managed to do so far, obviously the wrong way :
SELECT event_name,user_id
FROM `words-game-en.analytics_208527783.events_20191004`,
  UNNEST(event_params) as event_param
WHERE event_name = "level_end"
AND event_param.key = "user_coins"

A: You seem to want something like this:
SELECT event_param.level_num, AVG(event_param.user_coins)
FROM `words-game-en.analytics_208527783.events_20191004` CROSS JOIN
     UNNEST(event_params) as event_param
WHERE event_name = 'level_end' AND event_param.key = 'user_coins'
GROUP BY level_num
ORDER BY level_num;

I'm a little confused by what is in event_params and what is directly in events, so you might need to properly qualify the column references.


text:
Q: Simple question regarding Gauss's electric law I just read that electric flux=enclosed charge/permittivity.
Considering the charge in an enclosed surface is always 0, what is the point in even having this equation?
Or is the equation actually electric flux= charge/ permittivity? So therefore the surface does not always have to be closed and you can have any charge, not just an enclosed charge?
This was on hyperphysics:

Gauss's Law: The total of the electric flux out of a closed surface is equal to the charge enclosed divided by the permittivity.

Why not just say the flux out of a closed surface is equal to 0 instead of relating it to Q which is also 0?

A:
Considering the charge in an enclosed surface is always 0

I'm not exactly sure what you mean by this but do understand that the Gaussian surface 'encloses' a volume of space within which the enclosed charge resides.
For example, consider an isolated point charge $q$.  Due the spherical symmetry, the appropriate Gaussian surface is a sphere of radius $r > 0$ centered on the charge.
There is no doubt that there is charge within the volume enclosed by this surface and the electric flux through the surface is simply $\Phi_E = \frac{q}{\epsilon_0}$ by Gauss's law.


text:
Q: Azure Service Bus - Long running task throws Microsoft.Azure.ServiceBus.MessageLockLostException We are getting the following exception when executing a long running task in our service bus subscriber.

Microsoft.Azure.ServiceBus.MessageLockLostException: The lock supplied
  is invalid. Either the lock expired, or the message has already been
  removed from the queue.

The long-running task does several things including reading 4.5M records from the database, building an Excel document (using OpenXml) with multiple sheets (~1M records per sheet), updating a few entities in the database, etc. It's all wrapped inside one method of a service, and that's the only method exposed to the subscriber.
Since this task takes longer than the message is locked for, the message is released to the queue. The subscriber picks it up and starts working on it again. When the first call to the task is finished, we make the following call which immediately throws the exception:
await client.CompleteAsync(message.SystemProperties.LockToken)
We'd like to successfully renew the message lock before it is released back to the queue. We've added an alternative logic using a timer to execute await client.RenewLockAsync(message.SystemProperties.LockToken) before the message is released based on the value of message.SystemProperties.LockedUntilUtc. This seems to work correctly and effectively if we mimic the task with a Task.Delay(TimeSpan.FromHours(2)), for example, but with the actual call await internalService.ExportReport(), the renew doesn't seem to be effective. The message lock release seems to happen at the 5 minute mark always. We've registered our client's OperationTimeout and ServisceBusConnection.OperationTimeout with TimeSpan.FromHours(10), but that doesn't seem to have an effect on the message lock timeout.
Our core libraries target netstandard2.0, our application targets netcoreapp2.2 and we're using Microsoft.Azure.ServiceBus v4.0.0.
Can anyone out there give us some suggestions on how better approach this case, or any long-running task in general?


text:
Q: Parent.Grid + Child.Grid => Shared ColumnDefinitions I want to share a parent column definition with a child grid.
I have a parent grid like:
<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="Auto" />
  </Grid.ColumnDefinitions>
  <controls:GridEntry />
  <controls:GridEntry />
  <controls:GridEntry />
</Grid>

and a child that is a UserControl (controls:GridEntry) with following content:
<Grid>
  <Label x:Name="caption" />
  <TextBox x:Name="value" />
  <Button x:Name="button" />
</Grid>

My current idea is to find the parent grid from the child and set the constraints (if possible as binding, otherwise copy. When copying I have to catch all resize operations manually).
Is there an easy way to transfer the ColumnDefinitions of the parent grid to the child grid (preferably via XAML)?


text:
Q: Python pie chart using matplotlib, rearrange labels Lets say I have the following Pie Chart:
import matplotlib.pyplot as plt
sizes = [0.988799675982225, 0.009625725741571165, 0.0015745982762038959]
labels = ["Aaaaaa", "Bbbbbbbbbb", "CcCcccCc"]
plt.pie(sizes, labels = labels)
plt.show()

We immediately see the overlap of the labels. Is it possible to create a line from the fraction to the label and furthermore, get more distance between them?
Like this, for example:

A: I can't think of a way to achieve this efficiently. Your safest bet is to place the labels separately(imagine having a lot more fragments in a single pie chart). Try this as an alternative:
import matplotlib.pyplot as plt
sizes = [0.988799675982225, 0.009625725741571165, 0.0015745982762038959]
labels = ["Aaaaaa", "Bbbbbbbbbb", "CcCcccCc"]
patches, texts = plt.pie(sizes)
plt.legend(patches, labels, loc="best")
plt.axis('equal')
plt.tight_layout()
plt.show()


text:
Q: Event Custom Post Type Title show by upcoming Event Dates I've few Custom Post Type "Events" on different dates. Event Date is coming from Metabox.
Example:
Event Title 1
- Event Date: 20-10-06
Event Title 2
- Event Date: 20-03-26
Event Title 3
- Event Date: 20-01-19
Event Title 4
- Event Date: 20-06-12
Event Title 5
- Event Date: 20-12-10
I need to arrange those Post Titles by latest upcoming event dates.
It should be like this:
Event Title 3
Event Title 2
Event Title 4
Event Title 1
Event Title 5
I've made my query like this:
  $args = array(
    'posts_per_page'   => 5,
    'order'            => 'DESC',
    'meta_key'         => '_event_date',
    'orderby'          => 'meta_value',
    'post_type'        => 'events'
    );

   $args2 = array (
      'post_type'               => 'events',
      'posts_per_page'          => 3,
      'post__not_in'            => $do_not_duplicate,
      'offset'                  => '3',

      'order'                   => 'DESC',
      'meta_key'                => '_event_date',
      'orderby'                 => 'meta_value',

      );

NOTE: I've two queries there for two Blocks( Left Block 3 Posts, Right Block 3 Posts). I need to show latest upcoming events on left side and those events PAST shows on right side by Post date order.


text:
Q: Generalization of the concept of convergence over any Field $\mathbb F$
"Let $(a_n)_{n \in \mathbb N}$ be a sequence of elements of $\mathbb R$ or $\mathbb C$."

All of the sequences that I've studied until this point were sequences of this kind, and I have an intuitive understanding of what convergence means in this context. But that got me wondering: What if instead of considering sequences of Real or Complex numbers we consider sequences of elements of a Field $\mathbb F$?
Is there any natural way to extend the definition of convergence to any field? I know that some fields can be very exotic and strange so, if the concept of convergence doesn't make sense when we are working over a general Field, what properties must a field $\mathbb F$ have in order for convergence to make sense?
For example, does convergence of a sequence over $\mathbb Q$ make sense?

A: Convergence makes intuitive sense as soon as one has a metric on some set $X$. A metric is just a function $d: X \times X \longrightarrow \mathbb{R}_{\geq 0}$, "measuring the distance" between two elements of $X$. To be considered a metric, $d$ must satify the following 3 ($\forall x,y,z \in X$):

*

*$d(x,y) = 0 \iff x = y$

*$d(x,y) = d(y, x)$

*$d(x,z) \leq d(x,y) + d(y,z)$
Now for a sequence $(x_n)_n \subset X$, one says that the sequence converges if there is $x\in X$ such that $\forall \epsilon > 0$ we find some $n_0 \in \mathbb{N}$ such that $d(x_n,x) < \epsilon \; \forall n \geq n_0$.
Intuitively it says that, given any small radius around the limit point, we always find a "timepoint" where all elements of the sequence $(x_n)$ stay inside this small radius. Note that this notion is completely indepentend of any field. But it makes sense to define convergence on for instance normed vectorspaces over some field, such as $\mathbb{R}, \mathbb{C}$ or $\mathbb{R}^n$.
If we have a norm, "measuring distance from the origin", we can define a metric on the space, by setting $d(x,y) := ||x-y||$.
It is possible to define convergence more generally, using topologies as mentioned before. The idea is basically the same, one just has a different notion on what a "small radius" should be using the concept of open subsets.


text:
Q: Twilio Conference Call I was able to implement basic Voice Conferencing but I feel my implementation may be lacking.
client = Client('ACxxxxxxxx', '34xxxxxxxxx')

@app.route('/', methods=["GET", "POST"])
def home():
    form = ConferenceList() #form made using flask-wtf
    if form.validate_on_submit():
        contact_1 = form.data['contact_1'] #callee1
        contact_2 = form.data['contact_2'] #callee2
        from_ = form.data['from_'] #caller

        response = VoiceResponse()
        with Dial() as dial:
            if from_ == MODERATOR:
                dial.conference(
                   'Conf',
                   start_conference_on_enter=True,
                   end_conference_on_exit=True
                   )
            else:
                dial.conference('Conf', start_conference_on_enter=False)
        response.append(dial)

        '''here I feel could be a bottleneck'''
        add_user(contact_1, conference_name='Conf', label='laed#1')
        add_user(contact_2, conference_name='Conf', label="consumer")
        return Response(str(response), 'text/xml')

    return render_template('hello.html', form=form)

def add_user(contact, conference_name, label):
    participant = client.conferences(conference_name).\
            participants.create(
                label=label, #label for participant
                beep='onEnter',
                record=True,
                from_='from_', #same as above
                to=str(contact)
            )

if __name__ == '__main__':
    app.run(debug=True, port=8000)

Basically the submit button triggers the / endpoint and the conference starts.
I feel there could be an issue with this implementation as I plan on cleaning it up and pushing to production (salesperson can make a conference call to leads on the app). Is there something I could have done better?
The voice(one client-one client) utilizes the Twilio Voice SDK, it there a way I could tweak it for conferencing?

A: You only need to respond with TwiML to a webhook from Twilio. In this case it appears that you are responding with TwiML to your application's front end when a submit button is pressed.
So, you can drop all the TwiML:
@app.route('/', methods=["GET", "POST"])
def home():
    form = ConferenceList() #form made using flask-wtf
    if form.validate_on_submit():
        contact_1 = form.data['contact_1'] #callee1
        contact_2 = form.data['contact_2'] #callee2

        '''here I feel could be a bottleneck'''
        add_user(contact_1, conference_name='Conf', label='laed#1')
        add_user(contact_2, conference_name='Conf', label="consumer")
        return "whatever"

Since the settings you are trying to apply in the TwiML do not apply to the participants joining the conference, you need to adjust your add_user function to use them. In this case, the startConferenceOnEnter and endConferenceOnExit parameters for the moderator should be sent when you create the participant. It might be easier to write two methods, add_user and add_moderator, to make things clear:
def add_user(contact, conference_name, label):
    participant = client.conferences(conference_name).\
            participants.create(
                label=label, #label for participant
                beep='onEnter',
                record=True,
                from_='from_', #same as above
                to=str(contact),
                start_conference_on_enter=False
            )

def add_moderator(contact, conference_name, label):
    participant = client.conferences(conference_name).\
        participants.create(
            label=label,
            beep='onEnter',
            record=True,
            from_='from_',
            to=str(contact),
            start_conference_on_enter=True,
            end_conference_on_exit=True
        )

Then call different functions for the different participants:
        add_moderator(contact_1, conference_name='Conf', label='laed#1')
        add_user(contact_2, conference_name='Conf', label="consumer")

When you call add_user or add_moderator it will make an API request and slow down your server response. If you wanted to offload those requests to a worker, that would make your response quicker. But for 2 API requests, it is likely not a problem.
One other thing you might want to consider is the consumer experience. If they answer the phone before your agent does, then they will be greeted with hold music. You might want to architect it so that the application calls the agent first and only once they have picked up it then dials the consumer. Just worth considering.
Edit
After further explanation, you are now telling me that you want to make the call from the browser using the Twilio Voice SDK for JS.
To make outbound calls with the JS SDK you need to create an access token which includes an outgoing application sid, which refers to a TwiML application. That TwiML application has a voice URL. When you place the call with the SDK, Twilio makes a webhook request to the voice URL of your TwiML app. Your application can perform actions and return TwiML to tell Twilio what to do with the call.
When you create the call with the JS SDK you can pass parameters to the call.
const device = new Device(token);

const call = await device.connect({
  params: {
    To: ["+15551234567", "+145557654321"]
  }
});

Those parameters are sent with the webhook request to your TwiML App voice URL. You can then use a response very similar to your original code to respond here, because you need to return TwiML to the request from Twilio, and start calls to the other participants in the call.
@app.route('/conference', methods=["POST"])
def conference():
    const numbers = request.form["To"]

    response = VoiceResponse()
    with Dial() as dial:
        dial.conference(
           'Conf',
           start_conference_on_enter=True,
           end_conference_on_exit=True
       )
    response.append(dial)

    for number in numbers:
        add_user(number, conference_name='Conf')

    return Response(str(response), 'text/xml')

This code receives the To parameter, a list of numbers to dial into this conference, builds the TwiML response that will put the browser caller into a conference call, places outbound calls to the numbers to dial them into the conference and then returns the TwiML to Twilio. The dialler in the browser will start the conference and the other participants will arrive in the conference when they answer the phone.
In this case you don't make the request to your server yourself, you use the JS SDK to trigger the call and let Twilio make the request to your server. As mentioned in the comments, you may want to offload the API calls to create participants to a background job so that you can respond to the webhook request quicker, but that is beyond the scope of this answer.


text:
Q: moment.js in angular is not formatting as I would expect I have a Time being pulled from a server in the following JSON format:
"begins_at":"2016-04-22T08:11:07.000Z"

I am using momentjs with angular with the following filter:
{{event_details.begins_at | moment: "format": "HH:MM a"}}

I would expect the following output: 08:11 am.  Instead, I am getting: 04:04 am.  I suspect it might have something to do with timezones, but I'm not sure.  How do I fix this?

A: Change MM to mm (months to minutes : ))

angular.module('app', [])
  .provider('moment', function() {  // be nice for DI
    this.$get = function() {
      return moment
    }
  })
  .controller('ctrl', function() {
    this.event_details = {
      begins_at: '2016-04-22T08:11:07.000Z'
    }
  })
  .filter('moment', function(moment) {
    return function(input, options) {
      return moment(input).format(options.split('\'')[1]) // ugly formatter ; (
    }
  })

    moment: {{ c.event_details.begins_at | moment:"format: 'HH:mm a'" }}

A: An alternative. JS date is an ISO Date so we just need to use moments conversion method to use JS native date formatting. This does not require you to create a custom formatter.
{{myMomentDate.toISOString() | date: <your angular filter>}}


text:
Q: Parameter values for saxon not getting in the xslt I am not getting the parameter value (var in this case) into the XSLT when I tried to convert an XML document with saxon.
I got the following error in the terminal:
XPST0008: XPath syntax error at char 4 on line 8 in {$var}:
    Variable $var has not been declared
 Failed to compile stylesheet. 1 error detected.

I tried the following in the terminal (Ubuntu 14.04):
java -jar saxon-9.1.0.8.jar -s:x.xml -xsl:x.xsl -o:x.txt var="name"

My XSL stylesheet (x.xsl) is:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 version="2.0">

<xsl:output method="text"/>

<xsl:template match="//files">
  <xsl:value-of select="."/>
  <xsl:value-of select="$var"/>
</xsl:template>

</xsl:stylesheet>

The XML (x.xml) is:
<files>
 Var =
</files>


text:
Q: How to know disabled/enabled indexes in PostgreSQL and Oracle I would like to know a list of indexes that disabled/enabled in PostgreSQL and Oracle. Can someone suggest me the query?
I have a query for SQL Server like this
SELECT *
FROM sys.indexes I
INNER JOIN sys.tables T ON I.object_id = T.object_id
WHERE I.type_desc = 'NONCLUSTERED'
AND I.name IS NOT NULL
AND I.is_disabled = 1`

I am looking for a similar query for PostgreSQL and Oracle.

A: You can use this for postgres:
SELECT
    trel.relname AS table_name,
    irel.relname AS index_name,
    string_agg(a.attname, ', ' ORDER BY c.ordinality) AS columns
FROM pg_index AS i
         JOIN pg_class AS trel ON trel.oid = i.indrelid
         JOIN pg_class AS irel ON irel.oid = i.indexrelid
         JOIN pg_attribute AS a ON trel.oid = a.attrelid
         JOIN LATERAL unnest(i.indkey)
    WITH ORDINALITY AS c(colnum, ordinality)
              ON a.attnum = c.colnum
WHERE i.indisvalid -- WHERE not i.indisvalid
GROUP BY i, trel.relname, irel.relname;

Note, that disabling index in postgres means constant updates without it's usage for querying.

A: Use UserIndexes table
     select INDEX_NAME, TABLE_OWNER,
      TABLE_NAME, UNIQUENESS from
       USER_INDEXES u inner join
        all_tables a
       On u.table_name=a.table_name
        and u.table_owner=a.owner

For all indexes replace the tablename with all_indexes and join dba_tables


text:
Q: {} || [] is not valid JavaScript Why is {} || [] not valid?
$ echo '[] || {}' | node # this works
$ echo '{} || []' | node # but this doesn't
[stdin]:1
{} || []
   ^^

SyntaxError: Unexpected token ||
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Object.<anonymous> ([stdin]-wrapper:6:22)
    at Module._compile (module.js:652:30)
    at evalScript (bootstrap_node.js:466:27)
    at Socket.<anonymous> (bootstrap_node.js:237:15)
    at emitNone (events.js:111:20)
    at Socket.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)

$ echo '({}) || []' | node # unless you do this

A: When a statement starts with {, it's assumed by the parser to be the beginning of a block statement. In the case of {}, it's an empty block statement. So it's as if you had
{
  // no code here
}
|| []

and || cannot start a statement.
The one that does work, [] || {}, is unambiguous because a statement whose first token is [ can only be an expression statement.
Wrapping {} in ( ) means that the first token of the statement is (, not {.  The ( token cannot start any form of statement other than an expression (though it does have a little ambiguity, since it can start an anonymous "fat arrow" function; that's still an expression and the parser just has to disambiguate that later).
Note: the implementation of various debugging environments like your browser console and the Node command-line "console" have an effect on this sort of syntax. In order to keep things simple, such tools take the code you type in and one way or another they "wrap" it so that it can be parsed and evaluated interactively, statement by statement as you type. Unfortunately that process can introduce anomalies, such that something you try in the console may work fine there but not when you try it in a real block of code.


text:
Q: Download HTTPS website available only through username and password with wget? I'm trying to recursively download website which is normally available only when you login.
I have valid username and password, but the problem is that I need to login through web interface, so using --user=user and --password=password doesn't help.
wget downloads only one webpage with text:
Sorry this page is not available, maybe you've forgotten to login?
Is it possible to download?
I can't use --user, --password even at the login page because there is no FTP/HTTP file retrieval login as mentioned in man wget:
--user=user
--password=password
    Specify the username user and password password for both FTP and
    HTTP file retrieval.

Classic graphical login is there.
If I try to do this: wget --save-cookies coookies --keep-session-cookies --post-data='j_username=usr&j_password=pwd' 'https://idp2.civ.cvut.cz/idp/Authn/UserPassword'. Using POST method to login and trying to save cookies, the coookies file is empty and the saved page is some error page.
The URL is https://idp2.civ.cvut.cz/idp/Authn/UserPassword. Actually, when I want to log in, it redirects me to this page and when I successfully log in, it redirects me back to the page where I was before or some page where I wanted to be after logging in (example: https://progtest.fit.cvut.cz/.

A: The session information is probably saved in a cookie to allow you to navigate to other pages after you have logged in.
If this is the case, you could do this in two steps :

*

*Use wget's --save-cookies mycookies.txt and --keep-session-cookies options on the login page of the website along with your --username and --password options

*Use wget's --load-cookies mycookies.txt option on the subsequent pages you are trying to retrieve.

EDIT
If the --password and --username option doesn't work, you must find out the info sent to the server by the login page and mimic it :

*

*For a GET request, you can add the GET parameters directly in the address wget must fetch (make sure you properly quote the &, = and other special characters). The url would probably look something like https://the_url?user=foo&pass=bar.

*For a POST request you can use wget's --post-data=the_needed_info option to use the post method on the needed login info.

EDIT 2
It seems that you indeed need the POST method with the j_username and j_password set. Try --post-data='j_username=yourusername&j_password=yourpassword option to wget.
EDIT 3
With the page of origin, I was able to understand a little more of what is happening. That being said, I cannot make sure that it works because, well, I don't have (nor do I want) valid credentials.
That being said, here is what's happening :

*

*The page https://progtest.fit.cvut.cz/ sets a PHPSESSID cookie and present you with login options.

*Clicking the login button sends a request to https://progtest.fit.cvut.cz/shibboleth-fit.php which takes the PHPSESSID cookie (not sure if it uses it) and redirects you to the SSO engine with a specially crafted url just for you which looks like this : https://idp2.civ.cvut.cz/idp/profile/SAML2/Redirect/SSO?SAMLRequest=SOME_VERY_LONG_AND_UNIQUE_ID

*The SSO response sets a new cookie named _idp_authn_lc_key and redirects you to the page https://idp2.civ.cvut.cz:443/idp/AuthnEngine which redirects you again to https://idp2.civ.cvut.cz:443/idp/Authn/UserPassword (the real login page)

*You enter your credentials and send the post data j_username and j_password along with the cookie from the SSO response

*???

The first four steps can be done with wget like this :
origin='https://progtest.fit.cvut.cz/'

# Get the PHPSESSID cookie
wget --save-cookies phpsid.cki --keep-session-cookies "$origin"

# Get the _idp_authn_lc_key cookie
wget --load-cookies phpsid.cki  --save-cookies sso.cki --keep-session-cookies --header="Referer: $origin" 'https://progtest.fit.cvut.cz/shibboleth-fit.php'

# Send your credentials
wget --load-cookies sso.cki --save-cookies auth.cki --keep-session-cookies --post-data='j_username=usr&j_password=pwd' 'https://idp2.civ.cvut.cz/idp/Authn/UserPassword'

Note that wget follows redirection all by himself, which helps us quite a bit in this case.

A: Why are you playing around with wget? Better use some headless browser to automate this task.
What is a headless browser, you ask?

A headless browser is a web browser without a graphical user interface.
  They provide automated control of a web page in an environment similar to popular web browsers, but are executed via a command line interface or using network communication.

Two popular headless browsers are phantomjs (javascript) and Ghost.py (python).
Solution using phantomjs
First you will need to install phantomjs. On Ubuntu based systems, you can install it using the package manager or you could build it from source from their home page.
sudo apt-get install phantomjs

After this you write javascript script and run it using phantomjs:
phantomjs script.js

That's it.
Now, to learn how to implement it for your case, head over to its quickstart guide. As an example, to login to facebook automatically, and take a snapshot, one could use the gist provided here:
// This code login's to your facebook account and takes snap shot of it.
var page = require('webpage').create();
var fillLoginInfo = function(){
var frm = document.getElementById("login_form");
frm.elements["email"].value = 'your fb email/username';
frm.elements["pass"].value = 'password';
frm.submit();
}
page.onLoadFinished = function(){
if(page.title == "Welcome to Facebook - Log In, Sign Up or Learn More"){
page.evaluate(fillLoginInfo);
return;
}
else
page.render('./screens/some.png');
console.log("completed");
phantom.exit();
}
page.open('https://www.facebook.com/');

Look around the documentation to implement it for your specific case. If you face some troubles for your https website due to ssl errors, run your script like this:
phantomjs --ssl-protocol=any script.js

Solution using Ghost.py
To install Ghost.py, you will need pip:
sudo apt-get install python-pip   #On a Debian based system
sudo pip install Ghost.py

Now you have installed Ghost.py. Now, to use it inside a python script, just follow the documentation given in its home page. I've tried using Ghost.py on an https website but it somehow didn't work for me. Do try it and see if it works.
UPDATE : GUI based solution
You can also use tools like Selenium to automate the login process and retrieve the information. It is pretty easy to use. You will just need to install a plugin for your browser from here. And then you can record your process and replay it later on.

A: Try using 'curl'
curl --data "j_username=value1&j_password=value2" https://idp2.civ.cvut.cz/idp/Authn/UserPassword

You may need to look at the response type and set the 'content-type' header to match; i.e: XML, json etc

A: In addion to cookies, use user agent as firefox, chrome etc. Because most servers hate dwonload managers.
Alternatively  use firefox extension scrap book

*

*easy to use

*GUI

A: The way I would do it is: First I would use live HTTP Headers pluggin for firefox to analyze the communication. Referers and all that stuff may be needed. Once I have that information I would mimic that with wget saving cookies and loading when needed.

A: For a more modern tool to perform these kind of operations, checkout HTTPie:
https://httpie.org/

A: I was looking for the same thing and finally wrote a tool based on user43791's answer.
Therefore, what you are looking for is maybe something like that:
https://github.com/atar-axis/TUM-tools/blob/master/moodle_grabber/moodle_grabber.sh
It should be very easy to adapt this to any other shibboleth site and it is based only on wget!


text:
Q: Grivdview search not working properly flutter I have a gridview,i have implemented search,search is working fine,but the viewing of search item is not shows properly,
Before search

This how my gridview show after searching a item

Code
SliverGrid(
          gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: 200,
              childAspectRatio: 6 / 5,
              // crossAxisCount: 2,
              crossAxisSpacing: 0,
              mainAxisSpacing: 0),
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              SubCategoryModel data = sub_category_model[index];
              if (searchController.text.isEmpty) {
                return GestureDetector(
                  child: Card(
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Expanded(
                            flex: 0,
                            child: Container(
                              width: 100,
                              height: 100.0,
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(10.0),
                                child: CachedNetworkImage(
                                  fit: BoxFit.fill,
                                  imageUrl: Urls.BASE_IMAGE_URL +
                                      data.image.toString(),
                                  placeholder: (context, url) => Center(
                                      child: CircularProgressIndicator()),
                                  errorWidget: (context, url, error) =>
                                      Icon(Icons.error),
                                ),
                              ),
                            )),
                        Expanded(
                          flex: 0,
                          child: Padding(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 10, vertical: 10),
                            child: Text(
                              data.name,
                              style: TextStyle(
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 13),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  onTap: () {
                                        Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => OnlinecartSubitems(data.id.toString(),Category_Name),
                        ),
                      );
                  },
                );
              } else if (data.name.contains(searchController.text) ||
                  data.name.toLowerCase().contains(searchController.text) ||
                  data.name.toUpperCase().contains(searchController.text)) {
                return GestureDetector(
                  child: Card(
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Expanded(
                            flex: 0,
                            child: Container(
                              width: 100,
                              height: 100.0,
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(10.0),
                                child: CachedNetworkImage(
                                  fit: BoxFit.fill,
                                  imageUrl: Urls.BASE_IMAGE_URL +
                                      data.image.toString(),
                                  placeholder: (context, url) => Center(
                                      child: CircularProgressIndicator()),
                                  errorWidget: (context, url, error) =>
                                      Icon(Icons.error),
                                ),
                              ),
                            )),
                        Expanded(
                          flex: 0,
                          child: Padding(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 10, vertical: 10),
                            child: Text(
                              data.name,
                              style: TextStyle(
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 13),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  onTap: () {

                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => OnlinecartSubitems(data.id.toString(),Category_Name),
                        ),
                      );
                  },
                );
              } else {
                return Container();
              }
            },
            childCount: sub_category_model.length,
          ),
        )

A: Why not make a new list each time the search matches an item. Then, build a New GridView object based on the newly created list. Whenever your TextView is empty, you return the original list.
For Instance
//Create Search List
List<Object> searchList = [];

//Check if SearchTextView is empty or not with a ternary Operator
controller.text.isEmpty?

//Build your GridView based on the Original List
GridView.count(
   ...
   itemCount: mainList.length,
   ...
) //Replace with you SliverGrid

//Build your GridView based on the Search List
: GridView.count(
   ...
   itemCount: searchList.length
   ...
),//Replace with you SliverGrid

You can Replace my GridView with your SilverGrid widget.
The full Code (Spoiler alert: Very long):

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;
  MyHomePage({Key key, @required this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //Search TextField Controller
  final _searchController = TextEditingController();

  List<Fruit> mainList = [
    Fruit(name: 'Apple', imageUrl: 'https://images.pexels.com/photos/102104/pexels-photo-102104.jpeg'),
    Fruit(name: 'Banana', imageUrl: 'https://images.pexels.com/photos/5945848/pexels-photo-5945848.jpeg'),
    Fruit(name: 'Pineapple', imageUrl: 'https://images.pexels.com/photos/1071878/pexels-photo-1071878.jpeg'),
    Fruit(name: 'Mango', imageUrl: 'https://images.pexels.com/photos/918643/pexels-photo-918643.jpeg'),
  ];
  List<Fruit> searchList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          Container(
            width: MediaQuery.of(context).size.width,
            height: 60.0,
            child: TextFormField(
              controller: _searchController,
              onChanged: (text){
                final String queryString = _searchController.text;
                setState((){
                  if(queryString.isNotEmpty){

                    for(final fruit in mainList){
                      if(fruit.name.contains(queryString)){
                        searchList.add(fruit);
                      } else{
                        searchList.remove(fruit);
                      }
                    }
                  }else{
                    searchList.clear();
                  }
                });
              }
            ),
          ),

          Expanded(
            child: _searchController.text.isEmpty
            ? GridView.count(
              crossAxisCount: 2,
              children: mainList.map((fruit)=> CardWidget(fruit: fruit)).toList(),
            )
            :GridView.count(
              crossAxisCount: 2,
              children: searchList.map((searchedFruit)=>CardWidget(fruit: searchedFruit)).toList()
            ),
          ),
        ],
      ),
    );
  }
}

Create a Class to hold Fruit
class Fruit{
  final String imageUrl;
  final String name;

  Fruit({this.imageUrl, this.name});
}

Create widget to be built for each fruit object found in the mainList
//Card Widget
class CardWidget extends StatefulWidget{
  final Fruit fruit;

  CardWidget({this.fruit});

  @override
  _CardWidgetState createState()=> _CardWidgetState();
}

class _CardWidgetState extends State<CardWidget>{

  @override
  Widget build(BuildContext context){
    return Container(
      width: 100.0,
      height: 140.0,
      child: Column(
        children:[
          Image(image: NetworkImage(widget.fruit.imageUrl)),
          SizedBox(height: 10.0),
          Text(widget.fruit.name),
        ]
      )
    );
  }
}

Try it and let see

A: I have fixed the issue with help of Benedict and Farhan Syah thanks for the idea and some codes
Initialize variables
//Search controller for textfield

TextEditingController searchController = TextEditingController();

//For show list data first

List<SubCategoryModel> sub_category_model = [];

//for searchresult list

List<SubCategoryModel> _searchResult = [];

View
_searchResult.length != 0 ||searchController.text.isNotEmpty?SliverGrid(
                    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 200,
                        childAspectRatio: 6 / 5,
                        // crossAxisCount: 2,
                        crossAxisSpacing: 0,
                        mainAxisSpacing: 0),
                    delegate: SliverChildBuilderDelegate(
                      (BuildContext context, int index) {
                        SubCategoryModel data = _searchResult[index];

                        return GestureDetector(
                          child: Card(
                            elevation: 2,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(6),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Expanded(
                                    flex: 0,
                                    child: Container(
                                      width: 100,
                                      height: 100.0,
                                      child: ClipRRect(
                                        borderRadius:
                                            BorderRadius.circular(10.0),
                                        child: CachedNetworkImage(
                                          fit: BoxFit.fill,
                                          imageUrl: Urls.BASE_IMAGE_URL +
                                              data.image.toString(),
                                          placeholder: (context, url) => Center(
                                              child:
                                                  CircularProgressIndicator()),
                                          errorWidget: (context, url, error) =>
                                              Icon(Icons.error),
                                        ),
                                      ),
                                    )),
                                Expanded(
                                  flex: 0,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 10, vertical: 10),
                                    child: Text(
                                      data.name,
                                      style: TextStyle(
                                          color: Colors.black,
                                          fontWeight: FontWeight.bold,
                                          fontSize: 13),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                          onTap: () {

                          },
                        );
                      },
                      childCount: _searchResult.length,
                    ),
                  ):SliverGrid(//use same code above with **sub_category_model.length**)

Search widget
  Widget _SearchText() {
    return Container(
      width: 360,
      height: 65,
      color: Colors.transparent,
      child: new Padding(
        padding: const EdgeInsets.only(top: 10, left: 10, right: 10),
        child: new Card(
          elevation: 8,
          child: TextField(
            decoration: new InputDecoration(
                filled: true,
                hintStyle: TextStyle(fontSize: 11.5),
                hintText: 'Search by Name',
                suffixIcon: GestureDetector(
                    onTap: () {
                      FocusScope.of(context).unfocus();
                      searchController.clear();
                      _searchResult.clear();
                    },
                    child: Icon(Icons.cancel_rounded,
                        color: Color.fromRGBO(34, 83, 148, 1))),
                prefixIcon:
                    Icon(Icons.search, color: Color.fromRGBO(34, 83, 148, 1)),
                border: InputBorder.none),
            onChanged: onSearchTextChanged,
            controller: searchController,
          ),
        ),
      ),
    );
  }

Onchanged function for searching through list
onSearchTextChanged(String text) async {
    //clear search data before typing
    _searchResult.clear();
    if (text.isEmpty) {
      setState(() {});
      return;
    }
    //use searchcontroller text and loop through list of api data and add the result to _searchResult

    sub_category_model.forEach((searchValue) {
      if (searchValue.name.toLowerCase().contains(text))
        _searchResult.add(searchValue);
    });

    setState(() {});
  }

A: You are returning Container() when the search condition doesn't match. Container itself will take a place of a widget, hence, it will be an item of the grids.
To test this, you can try putting something inside the container, such as:
Container(
 child: Text('This grid is not empty)
)

The problem with this, is if you have 12 items in the data, no matter your search result, it will still build 12 items (including the empty container)
To solve this, you need a better way to filter the data, such as using a list to filter, and then passing the list data to the grid builder.
The concept is like this:
Original list : 10 items
Newlist based on the search: 5 items
The grid builder will build the items based on the list provided.


text:
Q: Heroku redirecting to http page I just made a new heroku application and I have a homepage with a form in the middle which when submitted redirects to the search results page with a GET request. The homepage has the https scheme but when I submit the form it redirects to the http scheme on the search results page.
I can manually change the url in the address bar to change it from http to https and it works but I can't just tell users to change the url in the address bar.

A: You can add directives to the .htaccess file at the root of your project to do this. Put this rule at the top of the file, if the file does not exist, create a new .htaccess file and add it.
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Or you can try with these
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]


text:
Q: Running python code in Apache Nifi ExecuteStreamCommand I'm trying to run python code in Nifi ExecuteStreamCommand processor.
The code includes non pure python modules like Pandas and Numpy so to use Nifi executeScript is not an option.
The issue is around reading in flow file and modifying flow file content.
Apparently it is possible to read incoming flow file with STDIN and to write out with STDOUT, see this SO question:
Python Script using ExecuteStreamCommand
But I have not been able to get this working.
1.
Tried simply reading in a CSV from STDIN and modifying it, but when sent to putFile processor the file is the same.
import sys
import pandas as pd
import io

df = pd.read_csv(io.StringIO(sys.stdin.read(1)))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
df2 = df.append(df2)

2.
Tried wrapping some other code in a function and returning in assumption that function output would go to STDOUT, but same outcome.
def convert_csv_dataframe():
    a = pd.read_csv(io.StringIO(sys.stdin.read(1)))
    a.replace(["ABC", "AB"], "A", inplace=True)
    return a

convert_csv_dataframe()

If anybody can help it would be most appreciated.
EDIT:
This code works. The issue was in Nifi. I was reading from "original" relationship instead of "output flow" relationship. Note that stdin is reading one line but don't think that should make a difference. The only question I have is: Can I reference a flow file itself (not it's contents) from executeStreamCommand ?
import sys

a = sys.stdin.readline()
a = a.upper()
sys.stdout.write(a)

A: I think you need to write to STDOUT somewhere in your script. I don't know much Python, but both examples look like you read from STDIN and then modify data in memory, but never write it back out.


text:
Q: Should HTTPRequest return the same as curl in this case The following shell script is used to access an IoT device that returns a JSON string, the content of which is not important for this question.
#!/bin/sh
secret= <not_telling>
id="e00fce688e6bcd0bad0763e7"
curl -k "https://api.particle.io/v1/devices/$id/peek" -d access_token=$<not_telling> -d args=5

I would like to reproduce this functionality in Mathematica
(* id and secret have been defined *)
req = HTTPRequest[
  "https://api.particle.io/v1/devices/" <> id <> "/peek",
  <|"Method" -> "POST",
   "Query" -> {"args" -> "5", "access_token" -> secret}|>]
URLExecute@req

This code does successfully POST; however it behaves as if the "-d args=5" portion of the query is missing or ignored.  I'm likely missing something trivial, but cannot place my finger on it.

A: The curl request is passing the arguments as a form body, but the Mathematica expression is passing query arguments in the URL.  Try changing the request property "Query" to "Body" to match the curl request:
req = HTTPRequest[
  "https://api.particle.io/v1/devices/" <> id <> "/peek",
  <|"Method" -> "POST",
    "Body" -> {"args" -> "5", "access_token" -> secret}|>]
URLExecute@req


text:
Q: UNEXPECTED_INTERNAL_API_ERROR when adding RemarketingUserList I am using google-adwords version v201101. When trying to insert the RemarketingUserList, I am getting the error
@errors: triggerxsi_typeInternalApiErrorreasonUNEXPECTED_INTERNAL_API_ERRORerror_stringInternalApiError.UNEXECTED_INTERNAL_API_ERRORfield_path
How to avoid this error?
My code snipper
private void createUserList() throws Exception {
    // Create conversion type (tag).
    UserListConversionType conversionType = new UserListConversionType();
    conversionType.setName("Mars cruise customers");

    // Create remarketing user list.
    RemarketingUserList userList = new RemarketingUserList();
    userList.setName("Mars cruise customers #" + System.currentTimeMillis());
    userList.setDescription("A list of mars cruise customers in the last year");
    userList.setMembershipLifeSpan(365L);
    userList.setConversionTypes(new UserListConversionType[] { conversionType });

    // Create operations.
    UserListOperation operation = new UserListOperation();
    operation.setOperand(userList);
    operation.setOperator(Operator.ADD);

    UserListOperation[] operations = new UserListOperation[] { operation };

    // Add user list.
    UserListReturnValue result = getUserListService().mutate(operations);

    // Capture the ID(s) of the conversion.
    List<String> conversionIds = new ArrayList<String>();
    UserList userListResult = result.getValue()[0];
    if (userListResult instanceof RemarketingUserList) {
        RemarketingUserList remarketingUserList = (RemarketingUserList) userListResult;
        for (UserListConversionType userListConversionType : remarketingUserList
                .getConversionTypes()) {
            conversionIds.add(userListConversionType.getId().toString());
        }
    }

    log.trace("List of conversionIds: " +conversionIds);

    // Create predicate and selector.
    Predicate predicate = new Predicate();
    predicate.setField("Id");
    predicate.setOperator(PredicateOperator.IN);
    predicate.setValues(conversionIds.toArray(new String[conversionIds.size()]));
    Selector selector = new Selector();
    selector.setFields(new String[] { "Id" });
    selector.setPredicates(new Predicate[] { predicate });

    // Get all conversion trackers.
    Map<Long, AdWordsConversionTracker> conversionTrackers = new HashMap<Long, AdWordsConversionTracker>();
    ConversionTrackerPage page = getConversionTrackerService()
            .get(selector);
    if (page != null && page.getEntries() != null) {
        for (ConversionTracker conversionTracker : page.getEntries()) {
            conversionTrackers.put(conversionTracker.getId(),
                    (AdWordsConversionTracker) conversionTracker);
        }
    }

    log.trace("User list with name " + userListResult.getName()
            + " and id " + userListResult.getId() + " was added.\n");

    // Display user list associated conversion code snippets.
    if (userListResult instanceof RemarketingUserList) {
        RemarketingUserList remarketingUserList = (RemarketingUserList) userListResult;
        for (UserListConversionType userListConversionType : remarketingUserList
                .getConversionTypes()) {
            log.trace("Conversion type code snippet associated to the list:\n"
                            + conversionTrackers.get(
                                    userListConversionType.getId())
                                    .getSnippet() + "\n");
        }
    }
}

A: UNEXPECTED_INTERNAL_API_ERROR means that there is some issue on the Google server side. Could you please obtain a SOAP request/response and post it on http://groups.google.com/group/adwords-api ?  That's the official forum for AdWords API, and someone from Google will follow up with you.
Based on your code, I assume you are using the Java client library for AdWords API. If so, the logging settings are in the log4j.properties file.


text:
Q: Randomly split a data table and make output files in R I want to randomly split a data table into n number of outputs; then I want to write.table those outputs for each list. So, in test I want to write a file for each list within test.
library(data.table)

set.seed(100)

dt <- data.table(x=rnorm(1000))

n <- 10 # number of data sets

# randomly splits dt into n number of outputs
test <- split(dt, sample(1:n, nrow(dt), replace=T))

# writing tables for each sublist within test
# write.table(test)
# names <- paste0("output", n, ".txt", sep="")

A: You could do :
lapply(seq_along(test), function(x)
       write.table(test[[x]], file = paste0('output', x, '.txt')))

A: We can use fwrite as it is a data.table and is much faster
library(data.table)
lapply(names(test), function(nm) fwrite(test[[nm]], paste0("output", nm, ".txt")))

The header 'x' is the column name and if we need some custom formatting, it can be done with cat
lapply(names(test), function(nm)
      cat(test[[nm]][[1]], file = paste0("output", nm, ".txt"), sep = "\n"))

Or as @chinsoon12 mentioned in the comments, specify col.names = FALSE (by default it is TRUE in fwrite)
lapply(names(test), function(nm) fwrite(test[[nm]],
          paste0("output", nm, ".txt"), col.names = FALSE))


text:
Q: How to Dynamically Assign property to drawable? I'm having a textview and its background is set using drawable resource.
<TextView
         android:id="@+id/label1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Label1"
         android:textColor="#FFFFFF"
         android:background="@drawable/rounded_label"
         android:layout_below="@id/snippet"
         android:layout_toRightOf="@id/label"
         android:layout_alignParentBottom="true"
         >

rounded_label.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#000000"/>
    <corners android:radius="3px"/>
    <padding android:left="0dp"
        android:top="0dp" android:right="0dp"
         android:bottom="dp" />
</shape>

The color assigned in <solid> must be performed in runtime using code not using XML?
Thanks in advance.

A: You have missing

android:bottom="10dp"

padding value please fix this value. or try this.
And other things ,
You have wrong color settings, you must specify 4 byte colors,

eg: #FFFF0000

<shape xmlns:android="http://schemas.android.com/apk/res/android">
       <solid android:color="#f0600000"/>
       <stroke android:width="3dp" color="#ffff8080"/>
       <corners android:radius="3dp" />
       <padding android:left="10dp" android:top="10dp"
          android:right="10dp" android:bottom="10dp" />
 </shape>


text:
Q: Clear tableofcontents page in book or report How do I clear the \tableofcontents page in book or report?
\documentclass[a4paper]{book}
\usepackage{lipsum}
\begin{document}

% i need clear this page
{\thispagestyle{empty} %but is not work
\tableofcontents}

\chapter{Book tableofcontents without page number}

\lipsum

\end{document}

A: I would combine \pagestyle and add \thispagestyle to the .tocfile, to have effect on the first page of the ToC.
\documentclass[a4paper]{book}
\usepackage{lipsum}
\begin{document}
\addtocontents{toc}{\protect\thispagestyle{empty}} % at the beginning of your document
     % writes \thispagestyle{empty} into the .toc file`, so here at the beginning
\pagestyle{empty}% switches to empty page style
\tableofcontents
\cleardoublepage% clear the page before changing back the page style
\pagestyle{headings}% switching back to the page style you use in your document
\chapter{Book table of contents without page number}
\lipsum
\end{document}

\protect is used to prevent expansion of \thispagestyle before it's written to the .toc file.

A: Use the following in your document preamble:
\documentclass[a4paper]{book}
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\usepackage{etoolbox}% http://ctan.org/pkg/etoolbox
\makeatletter
\patchcmd{\tableofcontents}{\@starttoc{toc}}{\thispagestyle{empty}\pagestyle{empty}\@starttoc{toc}}{}{}
\makeatother
\begin{document}

% i need clear this page
\tableofcontents
\clearpage
\pagestyle{headings}% ...or whichever heading style you use
\cleardoublepage
%...
\end{document}

You patch \tableofcontents using etoolbox to set the current page style to empty, as well as the following page styles (if your ToC spans more than one page) to empty. \clearpage flushes the current page (last one of the ToC), after which you can reset your page style to headings (or whatever you like). The additional \cleardoublepage makes sure that there's an additional page flush (if necessary) to make sure the chapter starts on a recto page.
The approach is similar to that followed in Clear tableofcontents page in memoir.