text:
Q: Convert a select dropdown into a list depending on screen size I have an HTML select tag
<select class="filter">
   <option values="1">One</option>
   <option values="2">Two</option>
   <option values="3">Three</option>
</select>

I would like to display the different options as an horizontal list of  hyperlinks for screen sizes above 481px and assign the same option values as in the select tag when the hyperlinks are clicked/selected and as a dropdown list for screen sizes of 480px and bellow.
I have seen examples online where a list of several  elements would be transformed into what looks like a dropdown list using jquery, but what it really did was taking all of these elements and stacking them over eachother and display the dropdown when clicked.

A: 3 steps involved;
1) use jQuery to duplicate select dropdown into unordered list of links,
2) use media queries to toggle between displaying the list and the dropdown,
3) use jQuery to sync active selections between both, ie, if the second dropdown option is selected, it sets the second link as active as well, and visa versa.
$('select.filter').after('

');
$('select.filter option').each(function () {
    $('ul.list').append('
' + $(this).text() + '
');
});

//set first item as active on ready
$('ul.list li:eq(0)').addClass('active');

// set active to selction and sync

// update dropdown when links selected
$('ul.list > li > a').click(function(){
   $('ul.list > li').removeClass('active');
   $(this).parent().addClass('active');
    var e =  $(this).parent().index();
   $('select.filter option:eq('+e+')').prop('selected', true);
});
// update list when dropdown selected
$('select.filter').change(function() {
    var e =  $('option:selected', this).index();
    $('ul.list > li').removeClass('active');
    $('ul.list > li:eq('+e+')').addClass('active');
});

Note: If your html is static and you know it is not going to change, or is very unlikely to change, you can remove all of the JavaScript associated with step 1 and manually create the ul link list in your html.
jsFiddle working example

A: There are a couple of ways to accomplish this.
1) Use @media rules to show/hide different element that perform the same function.
You can have a select and a ul that show/hide depending on viewport width. See Example - resize fiddle output window
2) Use jQuery
Use javascript to simply take the options in the select and transform it into a ul - See Example - all credit to this question


text:
Q: Number of Tetrahedrons in a Cube I am trying to find out Number of Tetrahedrons in a unit cube
My Try: Total ways to choose four vertices if $\binom{8}{4}=70$
From this we have to remove
$1.$ All $6$ faces
$2.$ $6$ Quadrilaterals formed by face Diagonals
$3.$ $2$ Concave Quadrilaterals formed by Body Diagonals
Hence Total tetrahedrons is $70-6-6-2=56$
Is this fine?

A: There are ${8\choose4}=70$ ways to choose $4$ vertices of the cube. Now we have to eliminate the coplanar quadruples. How many of them  are there?
We can see the $6$ quadruples coming from the faces of the cube and $6$ more coming from pairs of opposite edges of the cube. If these are all then there remain $58$ admissible quadruples.
Drawing a figure we cannot detect more coplanar quadruples. For a proof that there are indeed none we can argue as follows: The $8$ vertices of the cube can be partitioned into a "blue" and a "red" quadruple, both of them  forming a regular tetrahedron. A forbidden quadruple  would have to contain vertices of both colors, among them at least two red ones, say. These two are lying diagonally opposite on a common face of the cube. Every blue vertex of the cube is connected by an edge to one of these two red vertices; hence the plane of our forbidden quadruple contains at least one edge of the cube. It is then easy to see that this quadruple is one of the forbidden quadruples counted above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does this conditional statement do? I'm working on some javascript legacy code and I came across this conditional, can anyone tell me what does the '?' do? The 'items' property is not part of the currentItem object and it never is...
if (currentItem?.items)

A: See: Optional Chaining in JavaScript

That's the optional chaining operator.

The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

Read more: Optional chaining (?.) (MDN)


text:
Q: How to Show the Json api data in the dynamic Bar Charts in flutter/ **im trying development Covid 19 app in a flutter.And trying to render a dynamic bar chart in the dashboard of the application. I try to write some codes but this is not going to work to fetching data from API show into it bar dynamic bar charts.
Here are some codes which I tried my best but showing error.

here is my testing application screenshot
enter image description here

enter code here

import 'dart:convert';

import 'dart:convert';

import 'package:NavigationBar/userModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter_sparkline/flutter_sparkline.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:NavigationBar/userModel.dart';
import 'package:http/http.dart'as http;

class Dashboard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }

  }

  @override
  Widget build(BuildContext context)
  {

    return MaterialApp(

      debugShowCheckedModeBanner: false,
      home: HomePage(

      ),

    );

  }

class HomePage extends StatefulWidget
{

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

class _HomePageState extends State<HomePage>
{

    Map mapResponce;

  static List<charts.Series< addcharts, String>> get series => null;

    Future fetchdata() async{
      http.Response response;
      response = await http.get("https://disease.sh/v3/covid-19/all");
      if(response.statusCode==200){
        setState(() {
          mapResponce =json.decode(response.body);
        });
      }
    }

  //static var chartdisplay;

  //get _getUser => null;

  @override
  void initState() {
    // TODO: implement initState
    fetchdata();
    super.initState();

  }
    Widget databody() {
      var data =
      [
        addcharts("val1", mapResponce['v1']),
        addcharts("val2", 20),
        addcharts("val3", 30),
        addcharts("val4", 40),
        addcharts("val5", 50),
        addcharts("val6", 60),
        addcharts("val7", 70),

      ];

      var series = [charts.Series(

        domainFn: (addcharts addcharts, _) => addcharts.label,
        measureFn: (addcharts addcharts, _) => addcharts.value,
        id: 'addcharts',
        data: data,
      ),
      ];
    }
    var chartdisplay = charts.BarChart(series,
      animationDuration: Duration(microseconds: 2000),
    );

  Material myItems(IconData icon,String heading,int color){
    return Material(
      color: Colors.white,
      elevation: 14.0,
      shadowColor: Colors.grey,
      borderRadius: BorderRadius.circular(24.0),
      child: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Center(
                    child:
                    //Text part
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(heading,
                        style: TextStyle(
                            color: new Color(color),
                            fontSize: 20.0
                        ),
                      ),
                    ),

                  ),

                  Material(
                    color: new Color(color),
                    borderRadius: BorderRadius.circular(24.0),
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Icon(
                        icon,
                        color: Colors.white,
                        size: 30.0,
                      ),
                    ),
                  ),

                ],

              )
            ],
          ),
        ),

      ),

    );
  }

  @override
  Widget build(BuildContext context)
  {
    var chartdisplay;
    return Scaffold(
      appBar: AppBar(

        title: Text("Dashboard",
            style: TextStyle(
              color: Colors.white,
            )),
        centerTitle:true,
        leading: IconButton(icon: Icon(Icons.arrow_back),
            onPressed: (){
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => HomePage(),
                  ));

            }
        ),
      ),

      body:StaggeredGridView.count(
        crossAxisCount: 2,
        crossAxisSpacing: 12.0,
        mainAxisSpacing: 12.0,
        padding: EdgeInsets.symmetric(horizontal: 16.0,vertical: 8.0),

        children: <Widget>[
          myItems(Icons.add_alert,"ALERT",0xfff44336),
          myItems(Icons.ad_units,"22.13",0xffed622b),
          myItems(Icons.ad_units,"0",0xffed622b),
          myItems(Icons.read_more_outlined,"22.13",0xffed622b),
          myItems(Icons.date_range,"2/2/2021",0xffed622b),
       // FutureBuilder(
       //    future: _getUser,
       //    builder: (context,snapshot) {
       //      if (snapshot.hasData) {
       //
       //      }
       //
       //      else {
       //        return CircularProgressIndicator();
       //      }
       //    },),
          databody(),
    Expanded(
            flex: 3,
            child:Container(
              padding: EdgeInsets.all(40.0),
              height: MediaQuery.of(context).size.height*0.30,
              color: Colors.white,
              child: chartdisplay,
            ),
          ),
          Expanded(
            flex: 3,
            child:Container(
              padding: EdgeInsets.all(40.0),
              height: MediaQuery.of(context).size.height*0.30,
              color: Colors.white,
              child: chartdisplay,
                         ),
          ),

        ],
        staggeredTiles: [
          StaggeredTile.extent(2, 130.0),
          StaggeredTile.extent(1, 150.0),
          StaggeredTile.extent(1, 150.0),
          StaggeredTile.extent(1, 150.0),
          StaggeredTile.extent(1, 150.0),
          StaggeredTile.extent(2, 250.0),
          StaggeredTile.extent(2, 250.0),

        ],
      ),

    );
  }
}

// class dashboard extends StatelessWidget {
//   @override
//   Widget build(BuildContext context) {
//     return Container();
//   }
//
// }

class addcharts
{
  final String label;
  final int value;

  addcharts(this.label,this.value);
}

A: Remove this line from this code
Widget build(BuildContext context) {
    // TODO: implement build
    //throw UnimplementedError();       //this line
  }


text:
Q: Localization using ultrasonic sensors I don't know if this is the right place to ask this question.
I am working on a project in which I have to use ultrasonic sensors only to do "simultaneous localization and mapping" of robot. I have 8 such sensors. Assume that i have enough computation power and the limited sensing(8 ultrasonic sensor) capability.
What would be an appropriate algorithm to use in this case?

A: I found SLAM for Dummies to be very helpful.

A: According to your question, the algorithm to use is SLAM.
There are many possible SLAM implementations. http://openslam.org


text:
Q: Bloomberg price Market/Source information for a ticker (instrument) (BB c++ API) Seeking some insight on price data feeds via Bloomberg (utilising c++ BB API at the moment). The gist of the issue is that with every price tick received I am interested in knowing the market origin of the price (market source). Basically the exchange or specifically the country of origin of the exchange of the instrument for which a price is requested. The endpoint I communicate with is this one: //blp/mktdata
Have tried adding various fields to the payload of requests, specifically:
EXCH_CODE
FEED_SOURCE
EVT_STATUS_SIMP_SEC_STAT_RT
Getting various yields on these:
EXCH_CODE Field not available for subscription service(BAD_FLD)
FEED_SOURCE Field not available for subscription service(BAD_FLD)
EVT_STATUS_SIMP_SEC_STAT_RT Field not applicable to security(BAD_FLD)
Maybe, someone across the wide userbase here, used BB's c++ API (or their API in general) and had a similar requirement. I might provide a small code snippet later, but I think this is more of a general BB API question, rather a specific implementation question. Happy to provide more details, if I missed explaining some bit of information...


text:
Q: best practice for Redis Node setup i have setup the redis client on the separate file
export function getRedisClient() {
  const port: number = redisConfig.port || 6379;
  const host = redisConfig.host;

  const client = redis.createClient(port, host, {
    no_ready_check: true,
    retry_strategy: function(options) {
      if (options.error && options.error.code === 'ECONNREFUSED') {
        // End reconnecting on a specific error and flush all commands with
        // a individual error
        return new Error('The server refused the connection');
      }
      if (options.total_retry_time > 1000 * 60 * 60) {
        // End reconnecting after a specific timeout and flush all commands
        // with a individual error
        return new Error('Retry time exhausted');
      }
      if (options.attempt > 10) {
        // End reconnecting with built in error
        return undefined;
      }
      // reconnect after
      return Math.min(options.attempt * 100, 3000);
    },
  });

  client.on('error', function(error) {
    console.error(error);
  });

  client.on('ready', function() {
    console.log('Redis Server Connected...');
  });

  return client;
}

the issue is it throw me max number of clients reached.
does calling the function create a new client each time i call the function?
if so can you guys suggest me a better practice of implementing the redis within the multiple service.

A: you dont have to create another client everytime. just create a single client and export it. import it whenever you want to use redis.


text:
Q: Promise.all() method doesn't resolve to a value The following code resolves to Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} in the last then handler.
Though when logging the array with promises to the console, each has status resolved and all the requests are fulfilled.
MusicService
  .getArtists()
  .then((res) => {
     let arr = res.filter((a) => {
        return a.id.length;
     });
     return Promise.all(arr.map(function(a) {
        return fetch(`//service.com/api/artist/${a.id}`);
     }));
   })
   .then((res) => {
      console.log(res);
   });

So what am I missing to get this working?

A: FWIW, this can be reduced to:
MusicService
  .getArtists()
  .then(res => Promise.all(
    res
      .filter(a => a.id.length > 0)
      .map(a => fetch(`//service.com/api/artist/${a.id}`))
    )
  )
  .then(res => {
    console.log(res);
  });

In the last callback, res would be an array of fetch() results, it can't be anything else.


text:
Q: get different duration result of a method? I have simple program to measure the process times of a method. But, I get the different result for each run.
Even I just print out the "Hello" string, I get different result. I thought that I will get the same result. Could you provide some explanation?
public static void run() throws Exception {
    double start = System.nanoTime();
    System.out.println("Hello");
    // other operation
    double end = System.nanoTime();
    System.out.println(end - start);
}

First Result  : 112573.0
Second Result : 122195.0
Third Result  : 293140.0

A: From the Java Documentation:

public static long nanoTime()

Returns the current value of the most precise available system timer, in nanoseconds.
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.
So the nanoTime can results different time.

A: The time difference you are experiencing because of the system resources and the time of allocation of them.
The System.out.println("") always takes the same time but depending upon the system resources allocated at that time, the run-time differs.


text:
Q: How to remove all files and ubuntu? I'd like to sell my old pc (writing this on it) that has ubuntu 16.04 LTS. The guy who I am selling this to is my brother. He doesn't want the hdd to have ubuntu on it. So I'd like to know how do I delete all files and ubuntu too from this drive. It is the only drive on this PC. So basically the hdd would be in it's original state.

A: The harddisk cannot be deleted while ubuntu is running from it, so you will have to boot a Live CD from a CD or flashdrive.
Method 1: Terminal
You can use a dd comand:

*

*Boot into the Live CD

*Check the partitions with fdisk -l

*Run dd if=/dev/zero of=/dev/sda (assuming that /dev/sda is your HDD)
Method 2: GUI only
Here we will use gParted:

*

*Boot into the Live CD

*Run gParted from live CD. It should come with the Live CD, but in case it does not, run: apt-get update && apt-get install gparted

*Delete all partitions on your HDD (not the medium you are booting the Live CD from).

*Click the green "Apply All Operations" check-mark.


text:
Q: How can I deactivate Asset Versioning in Magnolia 5.7 We have a massive problem regarding assets (images) in our magnolia 5.7 system.
I can describe it like this:

*

*On our author server we create a completely new asset.

*When we publish that asset and look at it on our public server we see that it has the mixinTypes "mgnl:hasVersion" and the link to the image (That is inserted and worked on our author server) is not working anymore.

Do you know what could be the cause of this and how can I deactivate that automatic versioning of images?
UPDATE:
We have managed to fix the broken links problem with using the recovery-flag from here: https://docs.magnolia-cms.com/product-docs/Administration/Troubleshooting/Broken-version-history.html
Still we have versioning on our public server. Here is the diff between the two xml-exports of the asset-nodes:
<     <sv:value>mix:versionable</sv:value>
13,24d11
<   <sv:property sv:name="jcr:baseVersion" sv:type="Reference">
<     <sv:value>55f158e2-16c7-44ce-a973-cd48a5cad53b</sv:value>
<   </sv:property>
<   <sv:property sv:name="jcr:isCheckedOut" sv:type="Boolean">
<     <sv:value>true</sv:value>
<   </sv:property>
<   <sv:property sv:name="jcr:predecessors" sv:type="Reference" sv:multiple="true">
<     <sv:value>55f158e2-16c7-44ce-a973-cd48a5cad53b</sv:value>
<   </sv:property>
<   <sv:property sv:name="jcr:versionHistory" sv:type="Reference">
<     <sv:value>e1dfbbf9-e9be-468d-a20c-11c2cb978aa4</sv:value>
<   </sv:property>
31,33d17
<   <sv:property sv:name="mgnl:comment" sv:type="String">
<     <sv:value/>
<   </sv:property>
41c25
<     <sv:value>2021-03-03T10:42:37.277+01:00</sv:value>
---
>     <sv:value>2021-03-03T10:47:35.533+01:00</sv:value>
45a30,35
>   <sv:property sv:name="mgnl:lastActivatedVersion" sv:type="String">
>     <sv:value>jcr:frozenNode</sv:value>
>   </sv:property>
>   <sv:property sv:name="mgnl:lastActivatedVersionCreated" sv:type="Date">
>     <sv:value>2021-03-03T10:47:35.139+01:00</sv:value>
>   </sv:property>
93c83
<       <sv:value>2021-03-03T10:42:37.278+01:00</sv:value>
---
>       <sv:value>2021-03-03T10:47:35.539+01:00</sv:value>

A: You can find it under the node type definition, must be named such as this: magnolia-dam-nodetypes.xml
If you remove <supertype>mgnl:versionable</supertype> from the definition, it should not version the nodes anymore.

A: Could you try with decorations to override and remove catalog: versioned from publish action.
Original actions:
https://git.magnolia-cms.com/projects/MODULES/repos/dam/browse/magnolia-dam-app-jcr/src/main/resources/dam-app-jcr/decorations/dam-assets-app/apps/dam.subApps.yaml
/your module name/decorations/dam-assets-app/apps/dam.subApps.yaml
jcrBrowser:
  actions:
    publish: !override
      icon: icon-publish
      class: info.magnolia.ui.contentapp.action.JcrCommandActionDefinition
      command: publish
      availability: *notDeletedWritableAvailability


text:
Q: My HTML form is not mailing the results to me I have made and html file following the books Computer Learning by Sumita Arora and it's Cornestone
class 7. I have been making a form using chapter 7, and it's not working!  The full code is (the wrong line is the mailto: line)
<!DOCTYPE html>

<title>A Form</title>

A Form

<form action = "mailto:email address blured for obvious reasons" method = "post">

First name:
<input type = "text" id = "firstname" style="background-color:black">

Last name:
<input type = "text" id = "firstname" style="background-color:black">

School:
<input type = "text" id = "School" style="background-color:black">

Address
<input type = "text" id = "Address" style="background-color:black">

<input type = "submit" value = "Send" style="background-color:black"> <input type = "reset" style="background-color:black">

Copyright © Manik Sharma (THEOP05) 2022

</form>

A: mailto does not send an email in an automated way. It instructs the user's browser to show the user an email client. When I run your code on my local machine, the "Submit" button pops open Mozilla Thunderbird, since that's the email client installed on my machine. If you don't have an email client installed on your machine, then it's possible nothing will happen.
Of course, that's the client's machine, which is very likely not what you want. If you really want your form to send an email with the form results to THEOP05@example.com, you need to do that routing on the server side. The details will depend on your server framework (Django, Rails, PHP, etc.), but you should add an ordinary HTTP endpoint on your server, something like http://example.com/form-submit, which takes the form input as a POST parameter and, using whatever language your server is written in, sends the email server-side.
I know Django has facilities for automating the handling of forms (and conventions in place to make it easier). I suspect Rails does as well.

A: Try to change the method to "get"
<form action = "mailto:email address blured for obvious reasons" method = "get">

A: In order to send email with a form, you need an email delevery service. In the MVC, Html is the view (frontend) and sending email should be done by the controller or the model (backend). I like to use mailgun, but any other large scale email delevry service will provide you a nice UI and multiple usefull features. If your backend is PHP, you can use composer to install dependencies. I recommand the symfony mailer composer require symfony/mailer with you favorite 3rd Party Transport (eg.: composer require symfony/google-mailer for gmail.)
> Note that if your backend directly send emails, thoses emails can go into spam pretty much every time, and it takes a lot of ressoruces to process the email delevery, but this is a decision you can take based on how you want to send your emails.


text:
Q: Can't get regex to match in Java I'm trying to match just the file extension on a URL to an image.. I've got this regex:
(?<=\.)(jpe?g|png|gif|bmp|tga|tiff)$

I've tested this on several websites and it matches just fine.. but when I try to use it in Java I added an extra \ to escape the . and I don't think I should have to add more than that? but this isn't working:
Pattern extensionPat = Pattern.compile("(?<=\\.)(jpe?g|png|gif|bmp|tga|tiff)$", Pattern.CASE_INSENSITIVE);
    Matcher findExtension = extensionPat.matcher(imageURL);
    String extension = findExtension.group();

where imageURL is "https://www.google.com/images/srpr/logo4w.png"
At a coworker's recommendation I tried escaping the pipes as well into:
Pattern extensionPat = Pattern.compile("(?<=\\.)(jpe?g\\|png\\|gif\\|bmp\\|tga\\|tiff)$", Pattern.CASE_INSENSITIVE);

I've tried escaping the $, and the <, and nothing seems to work...

A: You need to call findExtension.find() first, otherwise findExtension.group() returns nothing.


text:
Q: Is there an option to change Date Picker form? I implemented date picker in my project from here: https://developer.android.com/guide/topics/ui/controls/pickers
The problem is, this date picker is in the format of regular calendar, and it takes a long time to choose faraway dates. In my app this kind of action is going to be performed all the time.
So, my question is, is there a possibility to change this calendar-like form to something faster? For example like in the picture below.
Picture of date picker i would like to make

A: check that library: https://github.com/florent37/SingleDateAndTimePicker
I've used it some time ago and it did almost exactly what you're looking for ;)
If it doesn't fit your needs, you can look for more 'iOS style date pickers' for Android, for example in this SO post:
ios like date/time picker for android platform
Edit:
It seems that this picker is Holo Light style and is achievable with this piece of code:
DatePickerDialog datepickerdialog = new DatePickerDialog(getActivity(),
     AlertDialog.THEME_HOLO_LIGHT,this,year,month,day);

But you need to check that on your own because they might be deprecated or not working with other themes.

A: Did you check this for Material Design?
Here is its documentation and code.

A: The DatePicker widget in Android has an attribute called android:datePickerMode that has a calendar option and a spinner option.
You can use the spinner option to get the appearance of the DatePicker you are after.


text:
Q: How to host 2 Django Application using gunicorn & nginx in Production Hello I want to host 2 djagno websites using Gunicorn and Nginx and I don't know how to do this this is my first time to host 2 django websites in one server and 2 domain so please tell me how to host 2 django website.
Here is my 1 file located /var/www/site1
and here is my 2 file /var/www/site2

A: Assuming you run your gunicorn instances on ports 8081 and 8082, you have two options:
Option 1: Subdomains
To use subdomains to reverse-proxy with NGINX, see this answer.
http://site1.example.com/ redirects to Site 1 and http://site2.example.com/ to Site 2.
NGINX config:
server {
    listen 80;
    server_name site1.example.com;
    location / {
        proxy_pass http://127.0.0.1:8082;
    }
}
server {
    listen 80;
    server_name site2.example.com;
    location / {
        proxy_pass http://127.0.0.1:8082;
    }
}

Option 2: Locations
http://example.com/site1/ now redirects to Site 1 and http://example.com/site2/ to Site 2.
NGINX config:
server {
    listen 80;
    server_name example.com;
    location /site1/ {
        proxy_pass http://127.0.0.1:8081;
    }
    location /site2/ {
        proxy_pass http://127.0.0.1:8082;
    }
}

EDIT - Option 3: Domains
You can also just use different domains for the different sites just as in option 1.
http://site1.com/ redirects to Site 1 and http://site2.com/ to Site 2.
NGINX config:
server {
    listen 80;
    server_name site1.com;
    location / {
        proxy_pass http://127.0.0.1:8082;
    }
}
server {
    listen 80;
    server_name site2.com;
    location / {
        proxy_pass http://127.0.0.1:8082;
    }
}

Note: These are bare minimum setups and may need additional configuration to work with your specific services.


text:
Q: Recovery of data after "Erase disk and install Ubuntu" I am new to Ubuntu. I have just installed Ubuntu on my system and unfortunately I have selected the "Erase disk and install Ubuntu"-option while installing
the same.
It has deleted all my previous valuable data and an important project. Kindly tell me how I can recover all data.
I had Windows 7 before installing Ubuntu.

A: *

*Use an Ubuntu live CD and do not use the hard disk that was erased in any way

*Press super(Windows) key and try Software Sources. Enable to Universe repository

*Install testdisk using sudo apt-get update && sudo apt-get install testdisk

*Start testdisk using sudo testdisk

*Create a log, locate your partition and select its type (e.g.: Intel PC/ GPT etc.)

Read the options on the screen and proceed
Note: Save the recovered files (if any) to some other drive, preferably an external drive, not on the hard disk that was erased.

A: Generally when it says deleted all the data it doesn't actually refer to delete. Your partition has just been labeled for overwrites with use. That is, the information has been classified as worthless and will be overwritten when more useful data needs to be stored(i.e. your new data like installing Ubuntu) So the more data you use the more of your 'supposed deleted data' is going to get overwritten.
Sadly there is no way to completely reverse the process, But
There are many tools for recovery of deleted data

http://www.cgsecurity.org/wiki/TestDisk

Command line, could be a challenge if you aren't comfortable &

http://www.cgsecurity.org/wiki/PhotoRec

Are some of the tools you can use
Do note this is only if the data is still present in some form hidden/ghost and has not been corrupted by overwriting of the bytes.
Some of the Steps you can perform Using testdisk:
1) Under Unix/Linux/BSD, you need to be root to run TestDisk (ie. sudo testdisk-6.13/testdisk_static). You must have installed testdisk in the first place using, in my case it was
tar -xjf /<path to>/testdisk-7.0.linux26-x86_64.tar.gz
cd testdisk-7.0.linux26-x86_64
./configure
make
sudo make install

After you download it, in that order.
Then you can try the following recommended steps from testdisk's intruction webpage:
1) To repair a filesystem not listed by TestDisk, run testdisk device, i.e.
testdisk /dev/mapper/truecrypt0

or
testdisk /dev/loop0

to repair the NTFS or FAT32 boot sector files from a TrueCrypt partition. The same method works with filesystem encrypted with cryptsetup/dm-crypt/LUKS.
To repair a filesystem on top of a Linux RAID device.
testdisk /dev/md0

2) Press Create in the next step, if it gives an error opt for 'No Log'
3) All hard drives should be detected and listed with the correct size by TestDisk:
Use up/down arrow keys to select your hard drive with the lost partition/s.
Press Enter to Proceed.
4) Partition table type selection
TestDisk displays the partition table types.
Select the partition table type - usually the default value is the correct one as TestDisk auto-detects the partition table type.
Press Enter to Proceed.
5) Current partition table status
TestDisk displays the menus (also see TestDisk Menu Items).
menus
Use the default menu "Analyse" to check your current partition structure and search for lost partitions.
Confirm at Analyse with Enter to proceed.
Now, your current partition structure is listed. Examine your current partition structure for missing partitions and errors.
Analyse
The first partition is listed twice which points to a corrupted partition or an invalid partition table entry.
Invalid NTFS boot points to a faulty NTFS boot sector, so it's a corrupted filesystem.
Only one logical partition (label Partition 2) is available in the extended partition. One logical partition is missing.
Confirm at Quick Search to proceed.
6) Quick Search for partitions
TestDisk displays the first results in real time.
quick search
During the Quick Search, TestDisk has found two partitions including the missing logical partition labeled Partition 3.
first results
Highlight this partition and press p to list your files (to go back to the previous display, press q to Quit, Files listed in red are deleted entries).
All directories and data are correctly listed.
Press Enter to proceed.
7)  For the rest of the steps I highly recommend you visit the testdisk website as there are many exhaustive steps with complete details
http://www.cgsecurity.org/wiki/TestDisk


text:
Q: How to Get all Order using GraphQL in Magento 2? I want to get all Pending order Status Orders using GraphQL, Anyone can share a complete example or module. How to I'll do that ?
I have create Custom module Admin Grid, Now i want to display Only Pending Orders in that grid. So i want to get all those orders using GraphQL. So Kindly help me on this. How to I'll do that ?
Thanks

A: For Check What is GraphQL in Magento 2, Read Blog, GraphQl in Magento 2
Check the link, Get List of Orders of Customer using GraphQl Magento 2 full module
For Get List of orders of Customer by customer id, You need to create a schema file for getting a response from Query.
In above you have declared schema file for getting multiple records of order for a specific customer.
type SalesOrder @doc(description: "Sales Order graphql gather Data of specific order information") {
    order_array: [String] @doc(description: "Array of order list.") }

In above order_array is used for getting an array of records but in your resolver, you made mistakes for multiple records.
In $orderCollection[] you need to pass array key for each record and you forgot to add that in your code.
You can try with,
foreach($orders as $k => $order) {
            $orderCollection['order_array'][$k] = [
                'increment_id' => $order->getIncrementId(),
                'grand_total' => $order->getGrandTotal(),
                'customer_id' => $order->getCustomerId(),
            ];
        }

Let me know if you have any query.


text:
Q: Why the name O for category O? What is the motivation behind naming the category O appearing in the theory of Lie algebras? Does O stand for something?
Here is a question Why the BGG category O? that further confuses me. It seems like there is a notion of when a category is O, is it?

A: From [Humphreys: Representations of semisimple Lie algebras in the BGG category O], notes for Chapter 1:

The letter chosen to label the category is the first letter of a
  Russian word meaning "basic"

which is основной.


text:
Q: Mbed Simple C Calculator I have created a code to implement a keypad on an Mbed microcontroller. The code checks the entered pin versus the correct pin.
Now, I need some help for converting this code into a simple calculator. I do not know how to convert the character array into a string to return integer values. I want to be able to enter number one, choose an operation, enter number 2, and compute. ex: 10+21= 31
I would like to be able to assign the operations (+,-,/,*) to keys 1-4. Any help would be appreciated!
edit: I have tried using 'value= atoi(str)' with no luck. Would initially creating a integer array instead of a character array be more beneficial?
#include "mbed.h"

DigitalOut led2(LED2);
DigitalOut led1(LED1);               // Declare LED
DigitalOut rows [4]= {PA_5, PA_1, PA_2, PA_3};       // Declare Rows
DigitalIn columns [3]= {PB_6, PB_7, PD_0};           // Declare Columns
char numpad [4] [3]= {
    {'1', '2', '3'},
    {'4', '5', '6'},
    {'7', '8', '9'},
    {'*', '0', '#'},
};
int c= 0;

int main (){
    char detected [6] = " ";
    char strCheck[]   = "3333#";
    led2 = 1;

    columns [0]. mode (PullUp);
    columns [1]. mode (PullUp);
    columns [2]. mode (PullUp);
    char read;

    while (1){
        for (int i=0; i<4; i++){
            rows[0]= 1;
            rows[1]= 1;
            rows[2]= 1;
            rows[3]= 1;
            rows[i]= 0;
            wait (0.01);
            for (int j= 0; j<3; j++) {
                if (columns [j]== 0) {
                    read= numpad [i][j];
                    printf("%c \n\r", read);
                    detected [c]= numpad [i][j];
                    detected [c+1]= '\0';
                    printf("%s \n\r", detected);
                    c++;
                         if (c==5) {
                         c= 0;
                    }
                    wait (0.005);
                    while (columns [j]== 0);
                }
            }
        }
        if (strcmp (detected, strCheck)== 0){
            led1 = 1;
            led2 = 0;
            printf ("%s \n\r", detected);
            c = 0;
            detected[0]= '\0';
        }
        else if (read== '*') {
            led1 = 0;
            led2 = 1;
            c = 0;
            detected [0] = '\0';
        }
    }
}


text:
Q: How to download XLSX file from a server response in javascript? I have a react frontend and java server using the Micronaut framework. In the BaseController of my Micronaut Framework, I am creating an XLSX file and then sending the response so that it gets downloaded when called from the frontend code.
BaseController
@Inject ExportService exportService

@Controller('/abc/api/v1')
@Slf4j
class BaseController implements CachingHandler, CommonUtils {
    @Post('/export/{name}')
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.ALL)
    executeExporter(String name, @Nullable @Body LinkedHashMap payload) {
        def handler = { LinkedHashMap paramMap ->
            List paramMapList = paramMap.get("data") as List
            Byte[] resultBytes = exportService.exportToXLSX(paramMapList, getFileName(getLookupValue(name), paramMap.get("key") as String), true)
            log.info String.format("About to return XLSX file %s for %s",getFileName(getLookupValue(name), paramMap.get("key") as String), name)
            return resultBytes
        }
        def results = handler.call(payload)
        InputStream inputStream = new ByteArrayInputStream(results)
        return new StreamedFile(inputStream, getFileName(getLookupValue(name), payload["key"] as String))
    }
}

ExportService
Note: Using the main method of this class I am able to create a TestReport.xlsx file. XLSXExporter class uses Apache POI library to generate XLSX file.
@Prototype
@Slf4j
class ExportService implements CommonUtils {

    Byte[] exportToXLSX(List response, String fileName, boolean isDelete) {
        def headers = []
        try {
            headers = response[0].keySet()
        } catch(Exception e) {
            e.printStackTrace()
        }
        Map params = [:]
        params[Constants.HEADERS] = headers
        params[Constants.DATA] = response

        XLSXExporter xlsxExporter = new XLSXExporter()
        boolean fileCreated = xlsxExporter.writeData(Constants.DEFAULT_SHEET_NAME, fileName, params)
        if (fileCreated) {
            Byte[] workbookContent = xlsxExporter.getFile(fileName, isDelete)
            return workbookContent
        } else {
            return new Byte[0]
        }
    }

    static void main(String[] args) {
        def param = []
        for (int i in 1..5) {
            def paramMap = [:]
            paramMap["key1"] = "data"+i
            paramMap["key2"] = "data"+i
            paramMap["key3"] = "data"+i
            param.add(paramMap)
        }
        ExportService exportService = new ExportService()
        Byte[] resultBytes = exportService.exportToXLSX(param, "TestReport.xlsx", false)

        /**
            I am able to create a proper TestReport.xlsx file using this main method
        **/
    }
}

I tested the above API from Postman and it is able to download an XLSX file.

When I call the above export API using my application (javascript), it is able to download an xlsx file but it does not open.
Javascript code to call export API
const exportData = (filteredRows, activity) => {
    let filename = "TestReport.xlsx";
    return axios({
        headers: {
            'Content-type': 'application/json'
         },
        accept:'application/x-www-form-urlencoded',
        url: '/abc/api/v1/export/'+ activity,
        method: 'post',
        data: {
            "key": "8575",
            "type":"userdetails",
            "data":filteredRows
        }
    }).then(resp => {
        var blob = resp.data;
        if(window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveBlob(blob, filename);
        }
        else{
            var downloadLink = window.document.createElement('a');
            downloadLink.href = window.URL.createObjectURL(new Blob([blob], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}));
            downloadLink.download = filename;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
           }
    });
}

Once I click yes on the above dialog I get below error and nothing gets displayed as opposed to the file downloaded from Postman.

A: Your MS Excel (XLSX) file generated on the server and sent back to the client via your API. You can download the response as a file by using responseType = blob. You should also set a filename on your browser to give a name to the downloaded file.
Try below snippet.
const exportData = (filteredRows,activity) => {
    let filename = "TestReport.xlsx";
    let xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = function() {
        var a;
        if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
            a = document.createElement('a');
            a.href = window.URL.createObjectURL(xmlHttpRequest.response);
            a.download = filename;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
        }
    };
    xmlHttpRequest.open("POST", '/abc/api/v1/export/'+ activity);
    xmlHttpRequest.setRequestHeader("Content-Type", "application/json");
    xmlHttpRequest.responseType = 'blob';
    xmlHttpRequest.send(JSON.stringify({
        "key": "8575",
        "type":"userdetails",
        "data":filteredRows
    }));
}

A: From node is send the excel file , then i did this -
axios({
  url: 'http://api.dev/file-download',
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
   const url = window.URL.createObjectURL(new Blob([response.data]));
   const link = document.createElement('a');
   link.href = url;
   link.setAttribute('download', 'file.pdf'); //or any other extension
   document.body.appendChild(link);
   link.click();
});

A: I have also faced the same issue in my project but reloved by adding responseType: "arraybuffer"}  in the header of your request.
The response is a JavaScript ArrayBuffer containing binary data.

A: Thanks to @AabinGunz. I could put comments since I don't have 50 reputation. but his snippet works.
I have the jsonString coming from a variable set before. the xlsx file downloaded is not corrupted.
thanks again to AabinGunz
    const exportData = () => {
    let filename = userName+".xlsx";
    let xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = function() {
        var a;
        if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
            a = document.createElement('a');
            a.href = window.URL.createObjectURL(xmlHttpRequest.response);
            a.download = filename;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
        }
    };
    xmlHttpRequest.open("POST", '/calc-reverse-matches');
    xmlHttpRequest.setRequestHeader("Content-Type", "application/json");
    xmlHttpRequest.responseType = 'blob';
    xmlHttpRequest.send(JSON.stringify(jsonString));
}


text:
Q: Meteor: Change the Iron Router Data Reactive Variable Without Page Reload In my meteor app, I am using iron-router's waitOn method to subscribe to all relevant documents and the data method to return just one document's contents to the template as a reactive variable. (Since these documents are large, I want to load just one at a time as a reactive variable for speed concerns).
  //...
  waitOn: function() {
    // subscribe to ohlcOneMin, ohlcThreeMin, etc.
    return Meteor.subscribe(this.params.exchange, this.params.market);
  },
  data: function() {
    return {
      ohlc: Widgets_Exchanges_Btcchina.findOne({market: this.params.market, dataType:'ohlcOneMin'})
    };
  },
  //...

By default on route load, iron-router will store data from the ohlcOneMin document under the Router.current().data().ohlc reactive variable. And that works great in my template. Now, imagine I have a button in my template. On click, it would change the iron-router data source to the contents of the ohlcThreeMin document... essentially toggling iron-router's Router.current().data() reactive variable between different document data which the user is subscribed to, without having to re-load the route or have all the data from all the documents stored in a reactive variable at the same time. How can this be achieved? Thanks!


text:
Q: How to raise an action through an interactivity trigger at an unittest? i got some little problems. I want to write some unittest fora c#/wpf/interactivty project with visual studio 2010. and dont forget im a beginner, so sorry for that  ;)
the unittest should simulate a (virtual) Key Down Event on a textbox and the result should raise an action.(Action result: Console output - just to check as first step)
i still fixed 2 problems -> the dispatcher problem & the presentationSource bug.
The unittest still simulates the keyevent and the keyevent reached the textbox but the question is, why the action not raised through the keydown event on the textbox?
It's a threading problem? what's my missunderstand?
here is the code
The Unittest
at the end of the unittest u could check the textbox - the keyboard works
[TestMethod]
public void simpleTest()
{
    var mockWindow = new MockWindow();

    //simple test to check if the virtualKeyboard works
    string CheckText = "Checktext";

    mockWindow.SendToUIThread(mockWindow.textbox, CheckText);

    mockWindow.SendToUIThread(mockWindow.textbox, "k");

    //needed to start the dispatcher
    DispatcherUtil.DoEvents();
}

the Dispatcher fix
public static class DispatcherUtil
    {
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        public static void DoEvents()
        {
            DispatcherFrame frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame);
            Dispatcher.PushFrame(frame);
        }

        private static object ExitFrame(object frame)
        {
            ((DispatcherFrame)frame).Continue = false;
            return null;
        }
    }

My Testaction
 class TestAction : TriggerAction<UIElement>
    {
        protected override void Invoke(object parameter)
        {
            Console.WriteLine("testAction invoke");
        }
    }

The MockWindow
public class MockWindow : Window
{
    public TextBox textbox { get; private set; }

    public MockWindow()
    {
        //add a grid&textbox
        Grid grid = new Grid();
        textbox = new TextBox();

        this.Content = grid;
        grid.Children.Add(textbox);

        //create the testaction/triggerEvent & add them
        TestAction testAction = new TestAction();
        System.Windows.Interactivity.EventTrigger TestTrigger = new System.Windows.Interactivity.EventTrigger();
        TestTrigger.EventName = "KeyDown";
        TestTrigger.Actions.Add(testAction);
        TestTrigger.Attach(this.textbox);
    }

    //enter a keyboard press on an UIElement
    public void SendToUIThread(UIElement element, string text)
    {
        element.Dispatcher.BeginInvoke(new Action(() =>
        {
            SendKeys.Send(element, text);
        }), DispatcherPriority.Input);
    }
}

the MockKeyboard added from codeplex sendkeys + a presentationCore fix for unittest(added at class SendKeys)
public class FixPresentationSource : PresentationSource
{
    protected override CompositionTarget GetCompositionTargetCore()
    {
        return null;
    }

    public override Visual RootVisual { get; set; }

    public override bool IsDisposed { get { return false; } }
}


text:
Q: Probability that the distance between two random points inside a circle is less than some value Two points are chosen at random within a circle of radius R. What is the probability that the distance between them is less than D?
I can solve the problem for the special case $R=D$ as follows:
For simplicity assume $R=D=1$
Let $O$ be the centre of the original circle of radius $R=1$. Let $A$ and $B$ be the two random points and let $d$ be the distance between them.
Suppose the distance $OA$ is $r$. Then we draw another circle of radius $D=1$, centred on $A$. Then the conditional probability $P(d<1|OA=r)$ is the area of the intersection of the two circles divided by the area of the original circle.
Let $C$ and $D$ be the points of intersection of the two circles. Now $CD$ is a line of symmetry and the area of intersection of the two circles is twice the area of the smaller segment bounded by $CD$ and the original (or equivalently the other) circle.
Intersection area = $2(\frac{1}{2}(1^2)(\theta - sin(\theta)))=\theta - sin(\theta)$, where $\theta=\angle COD$
Therefore $P(d<1|OA=r)=\frac{\theta - sin(\theta)}{\pi(1)^2}=\frac{\theta - sin(\theta)}{\pi}$
Where $cos(\frac{\theta}{2})=\frac{r}{2}$
Rearranging gives $r=cos(\frac{1}{2}\theta)$
Hence $\frac{dr}{d\theta}=-sin(\frac{1}{2}\theta)$
Now we are ready to do the integral:
$P(d<1)=\int_0^1(\frac{\theta - sin(\theta)}{\pi})\frac{2\pi r}{\pi(1)^2}dr$
$=\frac{2}{\pi}\int_0^1(\theta - sin(\theta))(r)dr$
$=\frac{2}{\pi}\int_\pi^{\frac{2\pi}{3}}(\theta - sin(\theta))(r\frac{dr}{d\theta})d\theta$
$=\frac{2}{\pi}\int_\pi^{\frac{2\pi}{3}}(\theta - sin(\theta))(-2cos(\frac{1}{2}\theta)sin(\frac{1}{2}\theta))d\theta$
$=\frac{2}{\pi}\int_\pi^{\frac{2\pi}{3}}(\theta - sin(\theta))(-sin(\theta))d\theta$
$=\frac{2}{\pi}\int_{\frac{2\pi}{3}}^\pi(\theta sin(\theta) - sin^2\theta)d\theta$
Computing this integral (us integration by parts for the first term and the half-angle formula for the second) gives a probability of $1-\frac{3\sqrt{3}}{4\pi}$ ($0.5865$ to 4dp), a result which I have verified to 2dp using a random number simulation.
When I tried to use a similar method for the general case, where D is not equal to R, I found that the equations for $r$ in terms of $\theta$ was quadratic and the resulting integral would have been extremely complicated. I thought perhaps a different approach might be called for.

A: According to MathWorld, the probability density for the distance $s$ between two points uniformly randomly chosen in a disk of radius $R$ is
$$
f(s)=\frac{4s}{\pi R^2}\arccos\frac s{2R}-\frac{2s^2}{\pi R^3}\sqrt{1-\left(\frac s{2R}\right)^2}\;.
$$
Thus the probability for the distance to be at most $s$ is
\begin{eqnarray*}
F(s)&=&\int_0^tf(t)\mathrm dt
\\
&=&
1-\frac2\pi\left(1-\frac {s^2}{R^2}\right)\arccos\frac s{2R}-\frac s{\pi R}\left(1+\frac{s^2}{2R^2}\right)\sqrt{1-\left(\frac s{2R}\right)^2}\;,
\end{eqnarray*}
in agreement with your result for $s=R$.
Here's a plot for $R=1$.


text:
Q: Form only submits when there is one input I have a <form> element surrounding several inputs:
<form>

        <button type="button" class="button grab formwidget" id="widget611">m</button>

        <input type="text" name="name" value="target volume profile 1" id="widget607" class="formwidget textbox">

</form>

I would like to trigger a submit event on the form when the user presses enter while focused on an element (standard behavior for input elements wrapped in a <form> tag), but when I press enter, nothing happens (fiddle).  If I remove all but one input element, the code works, and I get the expected behavior of pressing enter and triggering a form submit (fiddle).
How do I get the desired behavior (pressing enter submits the form) in the first example where I have multiple forms?
Note: I have found this same behavior in Safari 5.1, Chrome 17, Firefox 9, and IE 9.
Clarification: I know I can just throw some Javascript at it, but I'd like solve it with just markup.
Update: as some of you have helpfully pointed out, I can get the desired behavior by adding an <input type=submit>.  The problem is I don't want the user to see the submit button.  I can't just set its display to none, because then browsers won't submit when return is pressed, so I borrowed from QUnit and set the following:
HTML:
<input type=submit class=hide-me />

CSS:
.hide-me {
  position: absolute;
  left: -10000px;
  top: -10000px;
}

A: I have noticed that forms don't like to submit without a submit button. The problem is simply resolved by adding a submit button.  See this fiddle for a demonstration.  Furthermore, browsers submit when a user presses enter by default, so fix that and you won't need a javascript trigger to cause it.
EDIT:
If you don't want to use a <input type="submit"> simply because it's styling deficiencies, consider a <button type="submit">, it should also do the trick.  If you just don't want a submit button at all, stick with the CSS hack.

A: After trying it myself I couldn't believe it either.
Looks like this is the issue:
Why does forms with single input field submit upon pressing enter key in input

A: It's default behaviour for browsers to automatically submit simple forms (like search ones) which is why it's working when there is only one input. I believe if you want this functionality on complex forms you will need to use javascript. If you're not against using jQuery the following should do the trick.
$(function(){
     $("#formid input").keypress(function(event){
         if (event.which = 13){
             $("#formid").submit();
         }
     }
}

A: *

*Add an element
 <input type="submit" name="xx" value="submit" />
it will trigger submit behavior automatically.

*you can also use jQuery to handle press event.

Sean.

A: Try this one. i use this on my textarea with tinymce for a chat system

s_say is the ID of the input type submit btn.


text:
Q: I can't copy and paste into the terminal in Unity 16.04 on a Chromebook I have a Chromebook and have installed Unity 16.04 on the device. I cannot seem to copy and paste into the terminal as it is a laptop and does not have a mouse button which, when I looked, seemed to be required for copying and pasting.

A: Try using ctrl + insert for copy and shift + insert for paste.

A: If your mouse is not accessible, try copying the command with your keyboard (Control button+V) and opening your terminal by (Control+Alt+T) and pasting the same required command by (CONTROL+SHIFT+V)


text:
Q: Saving a random choice string to a usable variable in ansible Hoping someone can help me figure out what I feel should be a simple nested string problem. I have the following tasks to randomly choose a string, save it to a variable and print it:
  tasks:
    - name: Debug Section 1
      debug:
        msg: "{{ item }}"
      with_random_choice:
        - MY_CHOICE1
        - MY_CHOICE2
      register: choice

    - name: Set result to a fact
      set_fact:
        THE_CHOICE: "{{ choice.results }}"

    - name: Debug Section 3
      debug:
        msg: "{{ THE_CHOICE }}"

The results return with:
PLAY [Testing variable] **********************************************************************************************************************************************************************************************************************
TASK [Debug Section 1] ***********************************************************************************************************************************************************************************************************************ok: [localhost] => (item=MY_CHOICE1) => {
    "msg": "MY_CHOICE1"
}

TASK [Set result to a fact] ******************************************************************************************************************************************************************************************************************ok: [localhost]

TASK [Debug Section 3] ***********************************************************************************************************************************************************************************************************************ok: [localhost] => {
    "msg": [
        {
            "ansible_loop_var": "item",
            "changed": false,
            "failed": false,
            "item": "MY_CHOICE1",
            "msg": "MY_CHOICE1"
        }
    ]
}

PLAY RECAP ***********************************************************************************************************************************************************************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

I would like the variable THE_CHOICE to just return the item, but I can't seem to get it to work.  In the set_fact section I've tried the following:
THE_CHOICE: "{{ choice.results['item'] }}"
THE_CHOICE: "{{ choice.results.item }}"
THE_CHOICE: "{{ choice['results']['item'] }}"

All attempts result in something to the effect of this:
"The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'item'

Could anybody provide some insight into what I'm missing?

A: It would be simpler to use the random filter (since Ansible 1.6):
  vars:
    choices:
      - MY_CHOICE1
      - MY_CHOICE2
  tasks:
    - name: Set fact random
      set_fact:
        THE_CHOICE: "{{ choices | random }}"

About your original playbook, choice.results is a list, containing one result for each item of the loop. In your case, it only contains one result, because the with_random_choice loop only iterates once. So, in order to access your item, you must select the first result of the list with [0]:
    - name: Set result to a fact
      set_fact:
        THE_CHOICE: "{{ choice.results[0].item }}"


text:
Q: Simple set exercise seems not so simple Exercise about sets from Birkhoff's "Modern Applied Algebra".

Prove that for operation $\ \Delta $ , defined as

$\ R \Delta S = (R \cap S^c) \cup (R^c \cap S) $

following is true:

$\ R \Delta ( S \Delta T ) = ( R \Delta S ) \Delta T $

($\ S^c $ is complement of  $\ S $)
It's meant to be very simple, being placed in the first excercise block of the book. When I started to expand both sides of equations in order to prove that they're equal, I got this monster just for the left side:

$\ R \Delta ( S \Delta T ) = \Bigl( R \cap \bigl( (S \cap T^c) \cup (S^c \cap T) \bigr)^c \Bigr) \cup \Bigl(R^c \cap \bigl( (S \cap T^c) \cup (S^c \cap T) \bigr) \Bigr) $

For the right:

$\ ( R \Delta S ) \Delta T = \Bigl(\bigl( (R \cap S^c) \cup (R^c \cap S) \bigr) \cap T^c  \Bigr) \cup \Bigl( \bigl( (R \cap S^c) \cup (R^c \cap S) \bigr)^c  \cap T \Bigr)   $

I've tried to simplify this expression, tried to somehow rearrange it, but no luck. Am I going the wrong way? Or what should I do with what I have?

A: This is the symmetric difference. It includes all elements that are in exactly one of the two sets. In binary terms, it's the XOR operation. Independent of the order of the operations on the three sets, the result will contain exactly the elements that are in an odd number of the sets.

A: joriki's answer it the best way to understand this conceptually. Still, it's perfectly possible to continue formally the way you started: simply repeatedly apply De Morgan's laws:
$(A \cup B)' = A' \cap B'$ and $(A \cap B)' = A' \cup B'$.

A: You're doing the right thing. I just did it just to check.
As a hint: you can transform either side into
$$ (R \cap S^c \cap T^c) \cup (R\cap S \cap T) \cup (R^c \cap S \cap T^c) \cup (R^c \cap S^c \cap T)  $$


text:
Q: On the top left bar I am not allowed to enter the name I own Ubuntu 18.04 LTS with Unity Desktop. I would like to know if it is possible for my name to appear in the top bar as in previous versions. At the moment even with Unity Tweak Tool I have not succeeded. Are there any bugs that I am not aware of? Thank you

A: In 16.04 LTS it was possible by
gsettings set com.canonical.indicator.session show-real-name-on-panel true

but it will not work on 18.04 LTS because of the bug 1697412 in indicator-session or Unity<>systemd internals. Possible alternative maybe installation of ayatana-indicator-session, but it does not work on Unity.
So I would recommend to install Ubuntu MATE on top of your existing system by sudo apt-get install ubuntu-mate-desktop^, select MATE session on login, and then switch MATE Panel layout to Mutiny to get something like shown below:


text:
Q: What drives you to keep accruing reputation? So after 25k reputation points it seems that is the maximum of privileges here on meta or Stack Exchange. For users with 25k+, what is the drive to keep getting more reputation points?
I've seen some with like 140k reputation points and they aren't even moderators. They are just regular users like everyone else. Are there some hidden rewards for people that are 25k+ that isn't on the SE website that is inherited?
I haven't found any related question to this specific question.
Update: 9-13-21 I'm getting some closed votes on this from this proposed question
gentrification : equality or equity before the bounties
It's a good answer but I don't like the question. Negative 22 downvotes
The reason why I asked the question is to get a discussion going with high rep users and there say so on why they keep going when they reached the highest point
What is the end goal once you are at the top?

A: Nothing.
What drives me to ask is wanting the answer. I like my questions being upvoted, but I mainly want the answer.
What drives me to answer is wanting to help and wanting to show off. Not getting rep as a way to unlock new privileges. Perhaps getting rep as a short form for "look how helpful I have been." And getting not-the-points-actual-reputation like "this person really knows what they're talking about."
I don't care what my numbers are. I am over 100k on one site, and over 40k on 3, but I had to check the dropdown to know that. Rep isn't really what motivates most people. Getting an upvote (or dozens of them) motivates lots of us - the total rep is just an accumulated reminder of those dopamine hits.


text:
Q: I have to click twice for jQuery function to run when the screen resolution on my website gets to the width of that of a phone or an iPad then i made it turn into a bar with a image when that is clicked i want a bar to drop down with the navbar but easier to use however it must be clicked twice for the function to be ran. If anyone could help it would be great!! :)

function onTogglePan() {
  var clicks = $(this).data('clicks');
  if (clicks) {
    $("#navhide").css("display", "block");
    $("#navhide").css("visibility", "visible");
  } else {
    $("#navhide").css("display", "none");
    $("#navhide").css("visibility", "hidden");
  }
  $(this).data("clicks", !clicks);
};

  <button onclick="onTogglePan()">Drop</button>

I am #navhide

A: Do you mean this ?(Just a css solution)

function onTogglePan() {
  var clicks = $(this).data('clicks');
  if (clicks) {
    $("#navhide").css("display", "block");
    $("#navhide").css("visibility", "visible");
  } else {
    $("#navhide").css("display", "none");
    $("#navhide").css("visibility", "hidden");
  }
  $(this).data("clicks", !clicks);
};

  <button onclick="onTogglePan()">Drop</button>

I am #navhide

Please tall me if is this, I don't understand if the problem is about the doubleclick or about the nav menu

A: I am still not sure what you are looking for, but I try to explain
This is what you do:
function onTogglePan() {
    // since you don't set data-clicks per default the
    // first value of clicks is false
    var clicks = $(this).data('clicks');
    if (clicks) {
        // clicks is true - show the bar
        // this happens on second click
        $("#navhide").css("display", "block");
    } else {
        // clicks is false (hide the bar)
        // this happens on first click
        $("#navhide").css("display", "none");
    }
    $(this).data("clicks", !clicks);
};

I guess you want it the other way round. so if you simply switch the conditions using if (!clicks) instead if (clicks) it should work. Anyway, you might not need such an attribute. You also could check the visibility:
function onTogglePan() {
    var nav = $('#navhide');
    // if is visible hide, otherwise show
    var vis = (nav.is(':visible')) ? 'none' : 'block';
    nav.css("display", vis);
};

See your updated example here.

A: Just remove your [a] tag and put the id="showmenu" on your [button] tag


text:
Q: Are there faster ways in data.table fread() to read large gz file into memory? I am trying to read back a large gz file (about 1.5 Gb, with two columns: 1st column is numeric and 2nd column is character) named CID-Title.gz from my computer disk (originally, I downloaded this file from here
I used data.table::fread() as below:
dat <- data.table::fread(file = "CID-Title.gz", showProgress = TRUE, nThread = 16)

How can I make this fread faster when reading this gz file? Or is there other trick to read the large gz file with faster speed?

A: You can try the vroom package (web page here, CRAN page here). It reads to a tidyverse tibble: I don't know if there is a downstream performance penalty for converting the tibble to a data.table object.

vroom doesn't stop to actually read all of your data, it simply indexes where each record is located so it can be read later. The vectors returned use the Altrep framework to lazily load the data on-demand when it is accessed, so you only pay for what you use. This lazy access is done automatically, so no changes to your R data-manipulation code are needed.

vroom also uses multiple threads for indexing, materializing non-character columns, and when writing to further improve performance.

vroom supports reading zip, gz, bz2 and xz compressed files automatically, just pass the filename of the compressed file to vroom.

From the vroom benchmarks vignette:


text:
Q: Value starting with a "Space" in HttpURLConnection.add Request Property? This is the code in the client: connection.addRequestProperty("key", value);
This is the code in the server :
String user=req.getHeader("key");
System.out.println(user);

If the value is, for eg, "abcd xyz" in the client, printed value in the server is the same. But if the value is " abcd xyz", the value printed in the server is "abcd xyz" i,e the starting space is not there.
What is the problem here?

A: In HTTP header field values, leading and trailing whitespace is not significant. Thus, they will be gone after parsing.


text:
Q: ASM Inline call C external function I'm trying to call an external function in c by an asm inline with a branch. I'm compiling to an arm m0 instruction set but it returns bad expression.
The code is:
__asm volatile (
                "   cmp     r3,#0                   \n"
                "   b %[my_function]                \n" //Call function
                "   bx r14                          \n"
                : // no output
                : [my_function] "i" (my_function) // input
                : "r0" // clobber
            );

The return is:
/tmp/ccICkDIE.s: Assembler messages:
/tmp/ccICkDIE.s:152: Error: bad expression -- `b #my_function'

What we need to do?

A: You want the BL instruction.  This is "branch and link".  It does a jump and stores the return address in r14.
But, you've still got a problem ...  When you do BL, it destroys the r14 that you need.  You've still got more work to do, even after the following:
stmfd   sp!,{v1-v6,lr}              // preserve caller registers
bl      %[my_function]              // call function
ldmfd   sp!,{v1-v6,pc} @std         // restore caller registers and return

You'll need more investigation.  You might want to disassemble the compiled function and see what wrapper goes around your inline asm and adjust accordingly.  It may do the stmfd/ldmfd for you.  Try marking r14 as a clobber.
You may be better off with just the BL.  The BX without restore might produce an infinite loop or unpredictable results.  I'd leave it off

A: It is interesting that inline assembler from GCC has no way to deal with call frames.  My answer attempts to address this by adding a function wrapper and giving the syntax to get an address.  The same complaint by 'NotLikeThat' is comments to Craig Estey's answer.  Indeed, if you need to save/restore floating point registers, etc. That answer will not work.  You also need to clue the compiler that a stack frame needs to be emitted.  I tried to do this through the wrapping function.
This answer is not generic to all cases, do not copy paste it.  It tries to address the concepts of getting a function address to a register and transferring control.  'C' is a procedural programming language so the compiler performs many optimizations based on the context of the function.
No information is generic, but might get you to a specific solution.  GCC's label variables and other concepts might be suitable (and more portable) depending on the use case.  The code is meant to be informative.  All of my answers are written for people who can think about a problem and never canned solutions.

After composing the below, I remembered the ethernut tutorial.  He has virtually the same answer,
asm volatile(
    "mov lr, %1\n\t"
    "bx %0\n\t"
    : : "r" (main), "r" (JMPADDR)
    : // probably unsafe without "lr" clobber in most use-cases
   );
 // and also __builtin_unreachable() to tell the compiler execution doesn't leave

The OP would do well to read this tutorial; even though it is for traditional ARM as opposed to an 'm0'.
This method works for simple functions but is not a generic solution.  However, it demonstrates getting an address to a register.  The OP's original query.  The use case here is in a start function where you  are doing a tail call that will eventually call main().

You may use the 'r' constraint to place the address in a register and branch to it.
An example can be found on the online compiler godbolt.
extern int my_function(void);

// prevent inlining and optimization across functions,
// so we can take advantage of the calling convention instead of using proper clobbers
void f(void) __attribute__((noinline,noipa))
{
__asm volatile (
                "   cmp     r3,#0                   \n"
// Below is a tail call, not setting LR, it will return to the caller of f()
// It relies on the caller of f() having populated the 'lr'.
// See further comments below.
                "   b %[my_function]                \n"
                "   bx r14 \n" // does nothing...
                : // no output
                : [my_function] "r" (my_function) // input
            );

 }

This example relies on the fact it is embedded in a function.  The function will do the stack manipulation needed to prepare a call for the particular function you call from.  It may not be possible to inline this generically as you can specify clobbers such as r0-r3, memory and 'cc', but it would not tell the compiler that a stack frame must be well formed at this point.  Some answers will depend on what the called function does as you need to match the EABI (calling convention expected).  However, this is much beyond the capabilities of the original poster and they were struggling with much more basic concepts.
__attribute__((noinline,noipa)) was added to prevent inlining of an external function.  Since the answer was written, it is much more likely that GCC will perform global optimizations that may try to inline the routine.
With the output (using particular build options with a specific compiler version),
f():
    ldr r3, .L2
       cmp     r3,#0
   b r3
   bx r14

    bx  lr
.L2:
    .word   my_function()

We can see several issues with the output.  r14 is lr and the b r3 will transfer control directly and return to the caller of f.  The cmp r3, #0 seems completely un-needed (given limited context of question).
The sample above answers the question and it could be used for a tail-call macro or other use, but it obviously needs some work.  A function pointer like,
int (*g)(void) = my_function;

will also work as the parameter 'my_function' to the GCC extended assembler.
Another method is just to use 'C' macro string concatenation.  Here is a starting sample,
#define xstr(s) str(s)
#define str(s) #s
#define TAIL_CALL(func) __asm volatile(" b  " str(func) "\n")

For most code sizes (jump distance), the branch will be able to resolve (4MB?).  If you use the function pointer method, then there is no issue.  This example (as on godbolt) needs to be embedded in a function wrapper to take care of stack frame.  It is just meant as an example of how to get a function address to a register (the OPs original question).


text:
Q: Why do I not get compiler warning about access uninitialized member variable in ctor? Here is a simple test case that compiles without any warning. Looks like a common mistake but clang, gcc and visual studio doesn't emit warning in this case. Why?
class Image {
  private:
    int width, height;
    int* array;
  public:
    Image(int _width, int _height);
    void crashTest();
};
Image::Image(int _width, int _height)
{
  array = new int[width * height];
               // ^^^^^   ^^^^^^ this is wrong
               // I expect a warning here e.g.: 'width is uninitialized here'
  width = _width;
  height = _height;
}
void Image::crashTest()
{
  for (int x = 0; x < width; ++x)
  {
    for (int y = 0; y < height; ++y)
      array[x + y * width] = 0;
  }
}
int main()
{
  const int ARRAY_SIZE = 1000;
  Image image(ARRAY_SIZE, ARRAY_SIZE);
  image.crashTest();
  return 0;
}

e.g.:
g++ -Wall -Wextra -O2 -Wuninitialized test.cpp
clang++ -Wall -Wextra -O2 -Wuninitialized test.cpp

gives me no warning

A: A follow-up to this old question: You can get the warning you are looking for with g++ by enabling warnings from "Effective C++" with -Weffc++. This will complain about member variables that are not explicitly initialised.
This is possibly too aggressive in that it will also complain about class members with default constructors that are not explicitly initialised.
I have not seen an equivalent option for Clang -- I agree a warning about classes with uninitialised primitive data members would be very useful.

A: Short Answer
As pointed out in the comments, reading from an uninitialized variable is undefined behavior. Compilers are not obligated by the standard to provide a warning for this.
(In fact, as soon as your program expresses undefined behavior, the compiler is effectively released from any and all obligations...)
From section [defns.undefined]  of the standard (emphasis added):

undefined behavior
behavior for which this International Standard imposes no requirements
[ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed. —end note ]

Long Answer
This can be a difficult situation for a compiler to detect (and if it does detect it, it's difficult to inform the user about it in some useful way).
Your code only exhibits undefined behavior because it's trying to read from uninitialized member variables width and height. The fact that they're member variables is one of the things that can make this situation tricky to diagnose.
With local variables, the static analysis involved in detecting this can be relatively straightforward (not all the time, mind you).
For example, it's very easy to see the problem here:
    int foo()
    {
        int a;
        int b = 0;

        return a + b; // Danger! `a` hasn't been initialized!
    }

How about in this scenario:
    int foo(int& a)
    {
        int b = 1;

        return a + b; // Hmm... I sure hope whoever gave me `a` remembered to initialize it first
    }

    void bar()
    {
        int value;
        int result = foo(value); // Hmm... not sure if it matters that value hasn't been initialized yet
    }

As soon as we start dealing with variables whose scope extends beyond a single block, it's very difficult to detect whether or not a variable has been initialized.
Now, relating this back to the problem at hand (your question): the variables width and height are not local to the constructor - they could have been initialized outside the constructor.
For example:
    Image::Image(int _width, int _height)
    {
      Initialize();

      array = new int[width * height]; // Maybe these were initialized in `Initialize`...

      width = _width;
      height = _height;
    }

    Image::Initialize()
    {
        width = 0;
        height = 0;
    }

Should the compiler emit a warning in this scenario?
After some cursory analysis we can conclusively say "no, it shouldn't warn", because we can see that the Initialize method does indeed initialize the member variables in question.
But what if Initialize delegates this to another method MoreInitialize()? And that method delegates it to another method YetEvenMoreInitialize? This begins to look like a problem that we can't reasonably expect the compiler to solve.


text:
Q: How to encrypt epub file and read without storing in sd card I Tried following code.
How to read encrypted .epub file (Without saving decrypted file on sd card)
I want to maintain security for .epub file
is it possible to maintain security?
Thanks for Help in prior
static void encrypt() throws IOException, NoSuchAlgorithmException,
               NoSuchPaddingException, InvalidKeyException {
        // Here you read the cleartext.
        String file_en_path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Decrypted";
        File extStore = new File(file_en_path,"text.epub");
        FileInputStream fis = new FileInputStream(extStore);
        // This stream write the encrypted text. This stream will be wrapped by
        // another stream.
        File extStore_enc = new File(file_en_path,"text_enc.epub");
        FileOutputStream fos = new FileOutputStream(extStore_enc);
        Log.d("encrypt--fis------------->>>>>>",""+fis);
        Log.d("encrypt--fos------------->>>>>>",""+fos);
        // Length is 16 byte
        SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),"AES");
        // Create cipher
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, sks);
        // Wrap the output stream
        CipherOutputStream cos = new CipherOutputStream(fos, cipher);
        // Write bytes
        int b;
        byte[] d = new byte[8];
        while ((b = fis.read(d)) != -1) {
               cos.write(d, 0, b);
        }
        // Flush and close streams.
        cos.flush();
        cos.close();
        fis.close();
 }

static void decrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

     String file_de_path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Decrypted";
     File extStore = new File(file_de_path,"text_enc.epub");
        //File extStore = Environment.getExternalStorageDirectory();
       FileInputStream fis = new FileInputStream(extStore);
       File extStore_dec = new File(file_de_path,"text_dec.epub");
       FileOutputStream fos = new FileOutputStream(extStore_dec);
        //FileOutputStream fos = context.openFileOutput("fontsize_dec.txt",Context.MODE_PRIVATE);

        Log.d("decrypt--fis------------->>>>>>",""+fis);
        Log.d("decrypt--fos------------->>>>>>",""+fos);

        SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),"AES");
        IvParameterSpec ivSpec = new IvParameterSpec("MyDifficultPassw".getBytes());
        Cipher cipher = Cipher.getInstance("AES");
        try {
            cipher.init(Cipher.DECRYPT_MODE, sks, ivSpec);
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CipherInputStream cis = new CipherInputStream(fis, cipher);
        int b;
        byte[] d = new byte[8];

        StringBuilder sb = new StringBuilder();
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(cis, "UTF-8"));
        /*line = reader.readLine();
        sb.append(line);
        Log.d("sb.append(line)--------------------------->",""+sb.append(line));*/
        while ((line = reader.readLine()) != null) {
            sb.append(line);
           // Log.d("sb.append(line)--------------------------->",""+sb.append(line));
           // Log.d("Line--------------------------->",""+line);
        }
        Log.d("sb.toSting-------------------->",""+sb.toString());
        while ((b = cis.read(d)) != -1) {
            //Log.d("cis.read(d)------------------------>>>>>>>",""+cis.read(d));
               fos.write(d, 0, b);
        }
        fos.flush();
        fos.close();
        cis.close();
 }


text:
Q: Sencha Touch setActiveItem shows animation then requires click to show When I move between views in my Sencha Touch app I see the animation (slide), then the original view(the one I started at) is shown again. At that point, if I click anywhere in the app the view will change to the correct newly active item.
I'm using Sencha Touch, XCode 4, iOS 5 SDK, and PhoneGap 1.3.0.
Thanks in advance!
here's the code for the main viewport:
plantanalyzer.views.Viewport = Ext.extend(Ext.Panel, {
fullscreen: true,
layout: 'card',
cardSwitchAnimation: 'slide',
initComponent: function() {
Ext.apply(plantanalyzer.views, {
          login: new plantanalyzer.views.Login(),
          plantDetail: new plantanalyzer.views.PlantDetail(),
          buildingList: new plantanalyzer.views.BuildingList()
          });
Ext.apply(this, {
          items: [
                  plantanalyzer.views.login,
                  plantanalyzer.views.plantDetail,
                  plantanalyzer.views.buildingList
                  ]
          });

   plantanalyzer.views.Viewport.superclass.initComponent.apply(this, arguments);
    }
});

and for the viewController:
plantanalyzer.controllers.viewController = new Ext.Controller({
index: function(options) {
    plantanalyzer.views.viewport.setActiveItem(plantanalyzer.views.plantDetail, options.animation);
},
show: function(options) {
    plantanalyzer.views.viewport.setActiveItem(plantanalyzer.views.buildingList,

options.animation);
    }
});

and this is the code for one of the views:
plantanalyzer.views.PlantDetail = Ext.extend(Ext.Panel, {
width: 320,
height: 480,
items: [
    {
        xtype: 'panel',
        html: '',
        tpl: '{name}',
        cls: 'plantToolbar'
    },
    {
        xtype: 'button',
        name : 'buildingSelect',
        text: 'Select Building',
        cls: 'standardButton',
        listeners: {
            'tap': function () {
                'use strict';
                Ext.dispatch({
                    controller: plantanalyzer.controllers.viewController,
                    action: 'show'
                });
            }
        }
    },
    {
        xType: 'panel',
        cls: 'infoBoxes',
        html: 'Efficiency (kw/ton)
<canvas id="eff"></canvas>'
    },
    {
        xType: 'panel',
        cls: 'infoBoxes',
        name: 'totalTons',
        html: 'Total Plant Tons: '
    },
    {
        xType: 'panel',
        cls: 'infoBoxes',
        name: 'totalCost',
        html: 'Real-time Plant Cost: '
    },
    {
        xType: 'panel',
        name: 'uodateTime',
        cls: 'lastUpdate',
        html: 'Last Update: '
    }
    ]
});

A: The code looks fine in both sections. When i had issues with phonegap and sencha touch doing this i generally found there was a javascript error occurring or extra html markup was in between the body tag of the index.html file. The first thing would be to open the console in chrome or safari and check the javascript console to determine if it is a javascript error. If you can't run it in them i would suggest the Wienre application that will give you a console and was written to debug phonegap applications (wienre will also allow you to view the html markup to make sure it is correct)

A: The problem must be somewhere in the view files. The code you have shown is correct.

A: Well, for what it's worth, after rebuilding the app I found the issue. It was some custom css that was screwing up the app. Specifically the width that was being set on some of the components.
Hopefully, this will save somebody else some time and heartache.
Thanks, Darren and Ilija for your help!


text:
Q: Docker - How to access a volume not attached to a container? I have (had) a data container which has a volume used by other containers (--volumes-from).
The data container has accidentally been removed.
Thankfully the volume was not removed.
Is there any way I can re run the data container and point it BACK to this volume?

A:
Is there any way can re run the data container and point it BACK to this volume?

Sure, I detailed it in "How to recover data from a deleted Docker container? How to reconnect it to the data?"
You need to create a new container with the same VOLUME (but its path /var/lib/docker/volumes/... would be empty or with an initial content)
Then you move your legacy volume to the path of the volume of the new container.
More generally, whenever I start a data volume container, I register its volume path in a file (to reuse that path later if my container is accidentally removed)

A: Not entirely sure but you might try
docker run -i -t --volumes-from yourvolume ubuntu /bin/bash

You should then be able to access the directory, i think.

A: When I came to this question, my main concern was data loss. Here is how I copied data from a volume to AWS S3:
# Create a dummy container - I like Python
host$ docker run -it -v my_volume:/datavolume1 python:3.7-slim bash

# Prepare AWS stuff
# executing 'cat ~/.aws/credentials' on your development machine
# will likely show them
python:3.7-slim$ pip install awscli
python:3.7-slim$ export AWS_ACCESS_KEY_ID=yourkeyid
python:3.7-slim$ export AWS_SECRET_ACCESS_KEY=yoursecrectaccesskey

# Copy
python:3.7-slim$ aws s3 cp /datavolume1/thefile.zip s3://bucket/key/thefile.zip

Alternatively you can use aws s3 sync.
MySQL / MariaDB
My specific example was about MySQL / MariaDB. If you want to backup a database of MySQL / MariaDB, just execute
$ mysqldump -u [username] -p [database_name] \
            --single-transaction --quick --lock-tables=false \
            > db1-backup-$(date +%F).sql

You might also want to consider

*

*--skip-add-drop-table: Skip the table creation if it already exists. Without this flag, the table is dropped.

*--complete-insert: Add the column names. Without this flag, there might be a column mismatch.

To restore the backup:
$ mysql -u [username] -p [database_name] < [filename].sql


text:
Q: How to change Xaml page title dynamically in wpf? How can I change my Xaml page title dynamically in a WPF application?

A: Try this.
this.WindowTitle = "Your title here";

A: You can create a function like this
public void SetPageTitle(dynamic title)
{
  string DefaultTitle = "Name";
  try
  {
    this.Title = title.ToString();
  }
  catch
  {
    this.Title = DefaultTitle;
  }
}

A: You can set page's Title by set Title property in your code.
this.Title = "My Application" + DateTime.Now;

A: Instead of using the "THIS", you can use the name of your window.
MainWindow.Title = "My Window";


text:
Q: Deleting rows based on cell value in a certain column I'm working on an Excel VBA project.
I delete multiple rows when the cell in Column B is blank. And the code is as follows:
Columns("B:B").Select
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.EntireRow.Delete

Now, I would like to delete multiple rows when the cell value in Column E is not a number.
Could you help me with a code similar to the one above?
Thanks!

A: SpecialCells can select other cell type too:
Columns(2).SpecialCells(xlCellTypeConstants, _
  xlTextValues + xlLogical + xlErrors).EntireRow.Delete

and/or
Columns(2).SpecialCells(xlCellTypeFormulas, _
  xlTextValues + xlLogical + xlErrors).EntireRow.Delete


text:
Q: Using discord.py I have made a blacklist that filters certain words, it seems to be deleting user images and I cannot find out why Code:
#W A T C H E R
@bot.event
async def on_message(message):
  # L O G G I N G
  username = message.author.display_name
  msg = message.content
  with open('blacklist.txt', 'r') as f:
    blacklist = f.read()
    if message.author.bot:
      return
    elif msg.lower() in blacklist:
      await message.delete()
    else:
      await bot.process_commands(message)

That code just checks if user input is in the blacklist word list and based on that deletes or keeps the message. But the bot keeps deleting images that users post instead of just words that are listed in the blacklist category.
Literally auto-deletes user images in any channel.

A: When they send an image they most likely dont send any content so msg.lower() is an empty string and an empty string is always inside any string
>>> "" in "some words here"
True

consider making it check if the content is inside a list of blacklisted words instead of a single string, for example
if msg.lower() in blacklist.split():
    ...

str.split returns a list of words in the string: https://docs.python.org/3.8/library/stdtypes.html#str.split
or even better loop over blacklist.split() and check if any of the words are inside msg.lower(), for example if any(word for word in blacklist.split() if word in msg.lower()).


text:
Q: In core data: why does arraycontroller view doesn't notice changes in object.otherobject.property but only object.property? I have an nsarraycontroller * ctrlr1 fetching its data from core data entity obj1 witch has a relationship one to one to obj2 also fetched by nsarraycontroller * ctrlr2
in ctrlr i have set via IB a fetch predicate like this
inactive == 0 && obj2.active ==1

I have a view with bound properties for obj1 attributes and if i click the checkbox bound to inactive my nscollection view correctly fades obj1 and its view BUT
If in another nscollectionview I change obj2 attribute active to be 0, the first nscollectionview doesn't get updated istantly even if I force a fetch: method, what could it be? fetch works perfectly on first fetch (app launch)

A: The NSArrayController doesn't know that it needs to observe a potentially arbitrarily deep tree of objects, and just observes properties on the objects in the observed array (and the array itself). So you'd need to provide a change notification programatically for a "deep" change to bubble up to the array controller, or explicitly tell the controller to observe those deep key paths.


text:
Q: Push to github from local, cloned from another repo If you have already cloned someone else's repo (rather than forking) and have been committing locally, what's the appropriate way to push that into a new remote repo on GitHub?

A: You can change the remote or add another one.
To change the remote
git remote set-url origin https://www.something.com/my_repo.git

To add a secondary remote as e.g. other_origin
git remote add other_origin https://www.something.com/my_repo.git

If you changed origin you can git push to the new remote. If you added another remote, you can specify during git push which remote you want to push to.


text:
Q: Somebody Is "Hijacking" My URL I track traffic to the domains that I own through a "home brew" cookie system. One one site, I have noticed that I get a lot of HTTP referer traffic from one particular domain (http://www.getbig.com/). I did some sleuthing, and found out what this person has done. This person has attempted to use my sites logo as their avatar on a forum. However, instead of linking to the image in the "img" tag:

they have linked to my main domain name:

Every single time a page is loaded where this person has posted in this forum, a new hit gets registered. This is artificially inflating my visitor statistics, and I would like to stop it. If they had simply linked to the image, I could just change the image name, but they have linked to the site itself and I am not sure what to do. Aside from sending them a "cease and desist", what technical options do I have?

A: What I would recommend is check out the Referer, and if it is coming from http://www.getbig.com/, instead of your website you serve the absolute filthiest image you can find on the internet.
It's much, much easier to just send them an email though.. (this is my actual advice).

A: The principle is called hotlinking – or at least it is when done correctly, as you pointed out. There are a few solutions to "stop" it from happening.

*

*The most common one is to serve a different page or image instead of the expected one. Apache's mod_rewrite (or similar) allows you to rewrite URLs based on particular criteria, such as the referer header in this case. You will need to be at least allowed to create your own .htaccess file. There are tools to help generate the .htaccess content.

*A less informative way to do this would be to deny access via environment variable. First check the referer header with SetEnvIf and deny access based on it. This would only return a HTTP#403 response code.

*If you don't have this sort of access, you could read the referer header at the application level and make a decision there. This might only be a partial solution depending how the content is delivered (i.e. request handled by the webserver or an additional application layer such as PHP).

*Contact the user in question. This is less scalable and doesn't stop them if they don't agree with your kind request.
The first three are solutions to stop hotlinking in general. They can be adjusted to match only a particular referer.
In this particular case, I doubt any of these will have a significant effect unless you provide a picture in response. If the URI doesn't contain the actual image name but only the protocol and domain name, the browsers opening the page are unlikely to show anything relevant for the img tag at the moment. Providing a different content won't change this situation, unless it's an image. Serving an image explaining why you don't allow hotlinking (even if they request the main page) would probably have a more important impact on the user.
It is difficult to assess how your statistics will be affected by these solutions. Assuming they are collected on the main page, they could bring the data back to normal as that page won't be served anymore. If they're based on the access logs, it might be a different story.


text:
Q: mail- sending Output as attachment and not in the body Am having a issue when trying to output the content of a PHP Script to email.
Every time i try, regardless of the method, the Output always ends up as an attachment.
I was thinking it may of something to do with HTML.
But when passing the -html via Mail i still am faced with the same problem.
Some of the things i have attempted:
Cron254=$(php httpdocs/DIR/Cron-Run.php) | echo $Cron254 | mail -s "cron output" email@domain.com <<< $Cron254

This gives me an attachment with the following content in the file:
  00 Days, 00 Hours, 37 Minutes, and 11 Seconds have passed since the session was started

 This script will auto end in 3 hours (180 minutes) its possible the time may need extending the more data that is on the website

 Todays Timestamp: 20160229142124

 Todays Timestamp -180 minutes: 20160229112124

 session already in progress

I also tried the simple method:
php /dir/to/script.php > output | mail -s "cron output" email@domain.com

I can find 1000 ways to do this, but every way appears to attach the file to the email.


text:
Q: Is there a quick-save shortcut? Is there a quick-save and/or quick-load shortcut in Deus Ex: Human Revolution?

A: Yes there is in fact.
Pressing F5 will quicksave the game, and pressing F8 will load the quicksave.