text:
Q: FCM push notification working in Foreground and Background but not working when app is closed I have implemented Firebase but unfortunately notifications are only working when app is in Foreground or Background but unable to receive any notification when app is closed. I tried surfing online but couldn't get any results.
Is there any way to keep app alive in background even after closing it?
If yes i think this will help to receive notifications. Any helpful suggestions are entertained. Thanks

A: One thing i do is that i don't rely on the notification response, I rather pass the data object and make a custom notification myself.
Here is the code that might help you as we can access the data object even when app is open as well as closed:
Map<String, String> dataMap = remoteMessage.getData();
String notif = dataMap.get("title");

Then i use this function to make a notification
 private void notificationManager(Context context, String message) {

    try {
        long when = System.currentTimeMillis();

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

        Log.v("message", "," + message);

        Intent notificationIntent = new Intent(context, SplashActivity.class);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        builder.setContentTitle(context.getString(R.string.app_name));
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        builder.setContentText(message);
        builder.setTicker(message);
        builder.setLights(Color.GREEN, 500, 500);
        builder.setWhen(when);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(intent);

        Notification notification = builder.build();
        notification.ledARGB = 0xFFff0000;
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
        notification.ledOnMS = 100;
        notification.ledOffMS = 100;
        notificationManager.notify(1, notification);

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        wl.acquire(15000);

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

}

Hope this helps.

A: FCM has two messaging services

*

*Display messaging

*Data messaging
Probably you are using display messaging. You should use data messaging instead of display messaging. Display messaging won't work when app is closed.


text:
Q: Shiny Starter Pokemon on Fire Red using a GBA Emulator on Android I'm running Pokemon Fire Red on an Android phone using "My Boy!" emulator. Is it possible to get a shiny starter pokemon (Charmander) by reseting the game everytime I choose the starter pokemon? (I saved the game right before chosing it).
I made this question because I read on the Internet that it's not possible to get a shiny starer pokemon by reseting the game if you're using an emulator, because the interal code that determines whether if a pokemon is shiny or not does never reset.

A: It depends on how you reset the game.
Most emulators offer what is called "save states". Save states contain the entire memory dump of a game, unlike regular save games which only contain what the developer believes is important for the game.
Save states are particularly popular among emulator users, because they offer a way to cheat, such as resetting a particular move in combat.
In this case, the save state will contain the RNG (Random Number Generator) which a regular save game would not; why keep the RNG in memory, if you can generate a new one every time you launch the game? Of course, this also means you cannot simply load a save state to improve your chances of getting a shiny Pokémon, you'll have to reload a regular save game instead.
In other words: you'll have to quit the game, launch it again, then load the save game from within the in-game menu.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change Date value from one TimeZone to another TimeZone my case is I have a Date obj the date inside is UTC time. However I want it to be changed to Japan time.
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Japan"));
    calendar.setTime(someExistingDateObj);
     System.out.println(String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)) + ":" + calendar.get(Calendar.MINUTE));

the existingDateObj is mapped from db and db value is 2013-02-14 03:37:00.733
04:37
it seems the timezone is not working?
thanks for your time....

A: sdf2 and sdf3 are equaly initialized, so there is no need for two of them.

A: Your problem may be that you're looking at things wrong. A Date doesn't have a time zone. It represents a discrete moment in time and is "intended to reflect coordinated universal time". Calendars and date formatters are what get time zone information. Your second example with the Calendar and TimeZone instances appears to work fine. Right now, this code:
public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Japan"));
    System.out.println(String.valueOf(calendar.get(Calendar.HOUR)) + ":" + calendar.get(Calendar.MINUTE));
}

Reports:
0:32

That appears correct to me. What do you find wrong with it?
Update: Oh, perhaps you're expecting 12:32 from the above code? You'd want to use Calendar.HOUR_OF_DAY instead of Calendar.HOUR for that, or else do some hour math. Calendar.HOUR uses 0 to represent both noon and midnight.
Update 2: Here's my final attempt to try to get this across. Try this code:
public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat format = new SimpleDateFormat("H:mm a Z");
    List<TimeZone> zones = Arrays.asList(
            TimeZone.getTimeZone("CST"),
            TimeZone.getTimeZone("UTC"),
            TimeZone.getTimeZone("Asia/Shanghai"),
            TimeZone.getTimeZone("Japan"));
    for (TimeZone zone : zones) {
        calendar.setTimeZone(zone);
        format.setTimeZone(zone);
        System.out.println(
                calendar.get(Calendar.HOUR_OF_DAY) + ":"
                + calendar.get(Calendar.MINUTE) + " "
                + (calendar.get(Calendar.AM_PM) == 0 ? "AM " : "PM ")
                + (calendar.get(Calendar.ZONE_OFFSET) / 1000 / 60 / 60));
        System.out.println(format.format(calendar.getTime()));
    }
}

Note that it creates a single Calendar object, representing "right now". Then it prints out the time represented by that calendar in four different time zones, using both the Calendar.get() method and a SimpleDateFormat to show that you get the same result both ways. The output of that right now is:
22:59 PM -6
22:59 PM -0600
4:59 AM 0
4:59 AM +0000
12:59 PM 8
12:59 PM +0800
13:59 PM 9
13:59 PM +0900

If you used Calendar.HOUR instead of Calendar.HOUR_OF_DAY, then you'd see this instead:
10:59 PM -6
22:59 PM -0600
4:59 AM 0
4:59 AM +0000
0:59 PM 8
12:59 PM +0800
1:59 PM 9
13:59 PM +0900

It correctly shows the current times in Central Standard Time (my time zone), UTC, Shanghai time, and Japan time, respectively, along with their time zone offsets. You can see that they all line up and have the correct offsets.


text:
Q: Transfer hashmaps across fragments Android Say I have:
private Map<Integer,String> prices = new HashMap<Integer,String>();
private Map<Integer,String> titles = new HashMap<Integer,String>();
private Map<Integer,String> descriptions = new HashMap<Integer,String>();
private Map<Integer,String[]> pictures = new HashMap<Integer,String[]>();

I want to transfer these to another fragment via bundle:
Bundle bundle = new Bundle();
bundle.put  //best way?
fragment.setArguments(bundle);
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
    .replace(R.id.frame_container, fragment).commit();
}

What would be the most efficient/simplest way to do this?

A: Create a setter of these HashMaps in your fragment class. then use it to pass these parameters to fragment.
fragment.setHashMaps(Map<Integer,String> prices, Map<Integer,String> titles, Map<Integer,String> descriptions, Map<Integer,String[]> pictures) {
    this.prices = prices;
    this.titles= titles;
    this.descriptions = descriptions;
    this.pictures = pictures;
}


text:
Q: CentOS 7.2 Azure VM - MariaDB/Apache killing memory I have an Azure VM with CentOS 7.1, Apache 2.4.6, and MariaDB 5.5. The VM has 2 cores and 3.5 GB RAM. The server is only hosting a small WordPress site with almost no traffic.
For the past two days, MariaDB constantly crashes with an OOM error. I've tried so many different things for tweaking performance and so far absolutely nothing has helped. This is the current config from the my.cnf file:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
performance_schema = off
innodb_buffer_pool_size = 1024M
key_buffer_size = 50M

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

The Apache is a prefork version and I've added the following tweaks:
KeepAlive On
KeepAliveTimeout 3

StartServers 1
MinSpareServers 3
MaxSpareServers 6
ServerLimit 24
MaxClients 24
MaxRequestsPerChild 3000

I've tried with the default settings too and it makes no difference. Here is a sampling of the errors from the MariaDB log:
160124 15:04:53 mysqld_safe Number of processes running now: 0
160124 15:04:53 mysqld_safe mysqld restarted
160124 15:05:47 [Note] /usr/libexec/mysqld (mysqld 5.5.44-MariaDB) starting as process 4014 ...
160124 15:05:47 InnoDB: The InnoDB memory heap is disabled
160124 15:05:47 InnoDB: Mutexes and rw_locks use GCC atomic builtins
160124 15:05:47 InnoDB: Compressed tables use zlib 1.2.7
160124 15:05:47 InnoDB: Using Linux native AIO
160124 15:05:48 InnoDB: Initializing buffer pool, size = 128.0M
InnoDB: mmap(137756672 bytes) failed; errno 12
160124 15:05:48 InnoDB: Completed initialization of buffer pool
160124 15:05:48 InnoDB: Fatal error: cannot allocate memory for the buffer pool
160124 15:05:48 [ERROR] Plugin 'InnoDB' init function returned error.
160124 15:05:48 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
160124 15:05:48 [ERROR] mysqld: Out of memory (Needed 128917504 bytes)
160124 15:05:48 [ERROR] mysqld: Out of memory (Needed 96681984 bytes)
160124 15:05:48 [ERROR] mysqld: Out of memory (Needed 72499200 bytes)
160124 15:05:51 [Note] Plugin 'FEEDBACK' is disabled.
160124 15:05:52 [ERROR] Unknown/unsupported storage engine: InnoDB
160124 15:05:52 [ERROR] Aborting

What can I do? I have other VM's in Azure with the same specs and running many more, and more complex, sites, and they have zero crashes.
EDIT This is what the memory looks like within one minute of starting up MariaDB:
[root@linuxvm admin]# systemctl start mariadb
[root@linuxvm admin]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3442         670        2573           2         198        2577
Swap:           511          68         443
[root@linuxvm admin]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3442        1181        2052           2         207        2059
Swap:           511          64         447
[root@linuxvm admin]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3442        1523        1709           2         209        1715
Swap:           511          64         447
[root@linuxvm admin]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3442        1829        1397           2         214        1404
Swap:           511          64         447
[root@linuxvm admin]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3442        2713         506           2         222         515
Swap:           511          63         448
[root@linuxvm admin]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3442        3206          93           2         143          59
Swap:           511          63         448

A: I'll just put this here in case someone else needs it cause I literally just stumbled upon the answer now through trial and error, after an entire day of troubleshooting this issue. I read so many posts and blogs and none of them recommended adding the max_connections directive to my.cnf.
After adding the following lines, all my issues cleared up and MariaDB/MySQL stopped hogging all the memory. Your values may need to be adjusted for your specific scenario.
[mysqld]
max_connections = 50
innodb_buffer_pool_size = 1024M

A: By default Linux VMs don't have any swap enabled...
When you fire up a VM, a random "compute node" is chosen that has the capacity for the size of the VM that you chose.  Compute Node, is just a highly modified machine with Hyper-V installed.  Your OS disk; /dev/sda is not local to that server, and therefore not as fast as local storage. (and also subject to throttling, look for the amount of IOPS your VM size allows).
You will however get a local ephemeral disk on /dev/sdb which is suitable for swap.  (/dev/sdb).  The problem is that your VM might not always be hosted on the same compute node. (If your VM is resized or shutdown for more than 5 minutes, it is considered "deallocated", which means when you start it again, it has a high chance to use a different compute node, which won't have your local disk.
To solve this, Linux VMs use software called the WALinuxAgent, which among many things, allows you to create a swap file.  Every time your VM comes up, the agent will create a swap file on the ephemeral disk.
It's not enabled by default, but you can enable it in:
/etc/waagent.conf
# Create and use swapfile on resource disk.
ResourceDisk.EnableSwap=n

# Size of the swapfile.
ResourceDisk.SwapSizeMB=5120

Change n to y and reboot, that way if mysqld does use too much memory, OOM-killer won't kick in and bring down your VM.


text:
Q: Join content of several WordPress categories into new virtual category Lets imagine we have the following categories in WP:

*

*/shop/jeans/black

*/shop/jeans/blue

*/shop/jeans/white

*/shop/t-shirts/black

*/shop/t-shirts/blue

*/shop/t-shirts/white

What I need is to create virtual categories that can show content from certain given ones, for example:

*

*/shop/clothes/black

will hold content from /shop/jeans/black and /shop/t-shirts/black showing only black clothes.
I know I can virtually join categories content by custom links like

*

*/shop/jeans,t-shirts

but it is not useful.
I also know I can use tags. Also I can add content to multiple categories.
All that don't work in my case.
Is there a way to organize categories themselves into categories?

A: There are plenty of plug-ins at WP's repository exactly for this need, just search for custom taxonomy. I would recommend Simple Taxonomy. This plug-in haven't been updated for more than three years but it seems to be working as expected with WP 4.4.2. It is quite powerful and totally free.


text:
Q: Why a SELECT inside a simultaneous transaction in MySQL is not returning the expect result? I'm running two simmultaneos PHP/MySQL scripts.
The gg MySQL table has 11 rows at the start of the scripts, with IDs ranging from 1 to 11.
I won't bother with the right functions, but will handle this as some sort of pseudocode.
In the first one, I have the following code:
php mysql_query "BEGIN WORK;"
php mysql_query "SELECT * FROM gg;"
php mysql_query "DELETE FROM gg WHERE id > 5;"
php "sleep(15)"
php mysql_query "SELECT * FROM gg;"
php mysql_query "COMMIT;"

The results of the first select are 11 rows.
The results of the second select are 05 rows.
In the second one, I have the following code (no sleep):
php mysql_query "BEGIN WORK;"
php mysql_query "SELECT * FROM gg;"
php mysql_query "DELETE FROM gg WHERE id > 5;"
php mysql_query "SELECT * FROM gg;"
php mysql_query "COMMIT;"

The results of the first select are 11 rows.
The results of the second select are 11 rows.
The sleep function is just used to force the delay before the commit.
The second select in the second transaction, is executed after the commit from the first script.
My doubt is: Why the second SELECT in the second transaction is returning 11 rows if the commit from the first transaction was already performed?


text:
Q: PHP Web Crawler MultiThreaded Support I want to make a website crawler using only PHP. I want to make it multithreaded as well not to be really slow.
I can use either pthreads xtension from here http://pthreads.org/ or pcntl_fork()
The question is how i am going to implement such a feature. Can someone explain me how i can achieve this using PHP or a diagram or something?
I know PHP, so just focus on the algorithm. I just need ideas
Thank you


text:
Q: Deeplinking not working in google chrome android I've implemented deep linking in my android application, and so far it is working fine when I type URL in the address bar in Opera and MozilaFirefox but somehow it's not working in google chrome and Samsung default browser.
As most people use google chrome as a default browser, so I want to know if there is any way to fix this issue?
below is my manifest code
<activity
        android:name=".IntroActivity"
        android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
        android:screenOrientation="portrait"
        android:launchMode="singleTop"
        android:windowSoftInputMode="stateHidden|adjustPan">

        <!-- android:windowSoftInputMode="stateHidden|adjustResize" -->
        <!-- android:windowSoftInputMode="stateHidden|adjustPan" -->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data
                android:scheme="myapplication" />
        </intent-filter>
    </activity>


text:
Q: Why did I not get notified that my question was closed? I posed a question on meta.money.stackexchange.com and ticked the "Notify (email address) daily of any new answers" option.
The question was closed by an attentive moderator less than 20 minutes later, however I was not notified of this.
Now, I know it says "Notify [...] of any new answers" but I would argue that closing a question, specifically when closed as duplicate, is actually providing new answers, by transitivity. (If I'm interested in the answer to a question, then the fact that there is an exact duplicate question, probably with answers of its own, would be of interest too!)
Separately to this, the closure of the question didn't show up in my 'Recent Activity' listing either. I'd argue that question closure, of any type, would be of interest and should be shown here.
Should question closures be notified by email and/or appear in 'Recent Activity'?


text:
Q: How to scan/log already running processes on Unix you can use ps to list running processes, but I would like to know if there is a way to inspect the running processes to any level of detail. for example, maybe there is a way to see every assembly instruction it invokes, or every change it makes to the file system or global memory. these are processes i don't directly invoke or control.

A: You can attach a debugger such as gdb to any running process.
stop it and single step it etc
If you have the source and debug table you can set breakpoints at lines instated of just a public functions. I have not tried to used gdb with a dissassembly.
.


text:
Q: How to find count based on condition in MOngoDB Aggregation? I need to get the distinct categoryCode and categoryName and print the count with this combination of how many documents are repeated. here is one condition with match operation gets all the documents based on cat_type , if cat_type does not exist then in category response count show as 0 sample Data:
[
   {
      "cat_id":1,
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat":[
         {
            "type":"A"
         },
         {
            "type":"B"
         },
         {
            "type":"C"
         }
      ]
   },
   {
      "cat_id":2,
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat":[
         {
            "type":"A"
         }
      ]
   },
   {
      "cat_id":3,
      "categoryCode":"categoryCode2",
      "categoryName":"categoryName2",
      "cat":[
         {
            "type":"C"
         }
      ]
   },
   {
      "cat_id":4,
      "categoryCode":"categoryCode3",
      "categoryName":"categoryName3",
      "cat":[
         {
            "type":"A"
         }
      ]
   }
]

Expected Output: here match with type='A', category1 and category3 have type='A' then count is print as normal but category2 does not have this cat_type then category2 also show in response with cat_count=0
[
   {
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat_count": 2
   },
   {
      "categoryCode":"categoryCode2",
      "categoryName":"categoryName2",
      "cat_count": 0
   },
   {
      "categoryCode":"categoryCode3",
      "categoryName":"categoryName3",
      "cat_count": 1
   }
]

I am using query- but query work with the outside field but not work inside array based condition
db.collection.aggregate([
   {
      "$group":{
         "_id":{
            "categoryCode":"$categoryCode",
            "categoryName":"$categoryName"
         },
         "catCount":{
            "$sum":{
               "$cond":{
                  "if":{
                     "$eq":[
                        "$cat.type",
                        "A"
                     ]
                  },
                  "then":1,
                  "else":0
               }
            }
         }
      }
   },
   {
      "$project":{
         "categoryCode":"$_id.categoryCode",
         "categoryName":"$_id.categoryName",
         "catCount":1,
         "_id":0
      }
   }
])

A: Just need to use $in operator condition instead of $eq operator condition,
  {
    $group: {
      _id: {
        "categoryCode": "$categoryCode",
        "categoryName": "$categoryName"
      },
      "cat_count": {
        $sum: {
          $cond: [{ $in: ["A", "$cat.type"] }, 1, 0]
        }
      }
    }
  }

Playground

A: You can try to evaluate / count the number of type: A element in the cat array by $reduce first. Then $sum the result in the $group to get your answer.
{
    "$group": {
      "_id": {
        "categoryCode": "$categoryCode",
        "categoryName": "$categoryName"
      },
      "catCount": {
        "$sum": {
          "$reduce": {
            "input": "$cat",
            "initialValue": 0,
            "in": {
              "$cond": {
                "if": {
                  $eq: [
                    "$$this.type",
                    "A"
                  ]
                },
                "then": {
                  // add 1 to accumulator if type is A
                  $add: [
                    "$$value",
                    1
                  ]
                },
                // otherwise, simply keep the accumulator as-is
                "else": "$$value"
              }
            }
          }
        }
      }
    }
}

Here is the Mongo playground for your reference.


text:
Q: How to calculate the numpy.sum(axis=1) and numpy.angle From the following test code, it is easy to understand the x.sum() and x.sum(axis=0).
Question 1:
How to calculate each value in x.sum(axis=1)?
Question 2:
What does the value of np.angle(x, deg=True) mean, and how np.angle works for an array?
test code:
import numpy as np
x = np.arange(27).reshape((3,3,3))
x

output:
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

test code:
x.sum()

output:
351

test code:
x.sum(axis=0)

output:
array([[27, 30, 33],
       [36, 39, 42],
       [45, 48, 51]])

test code:
x.sum(axis=1)

output:
array([[ 9, 12, 15],
       [36, 39, 42],
       [63, 66, 69]])

test code:
x.sum(axis=2)

output:
array([[ 3, 12, 21],
       [30, 39, 48],
       [57, 66, 75]])

test code:
y = np.angle(x, deg=True)
y

output:
array([[[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]]])

A: You can think of a 3D array, like the one you have shown here as having the following dimensions (batch, rows, columns).
When using x.sum() you get the result of the sum of all of the values in the 3D array.
When using x.sum(axis=0) you get an array with shape (1,3,3) where you've performed a straight forward matrix addition operation such as:

When using x.sum(axis=1) you get an array with shape (1,3,3) where you've performed a row-wise addition. In the image above it would be like adding a + b, c + d, w +x, and y + z.
Finally, When using x.sum(axis=2) you get an array with shape (1,3,3) where you've performed a column-wise addition. In the image above it would be like adding a + c, b + d, w + y, and x + z.
In your last example, this keeps returning 0s because you providing an integer, not a complex number. An example of a complex number would be 2i or 2i + 1.
See this example from the numby docs:
>>> np.angle([1.0, 1.0j, 1+1j])               # in radians
array([ 0.        ,  1.57079633,  0.78539816])
>>> np.angle(1+1j, deg=True)                  # in degrees
45.0

visit the numpy docs for more info : https://numpy.org/doc/stable/reference/generated/numpy.angle.html


text:
Q: How to implement an odometer on an iPhone I'm working on a fairly simplistic trip application for the iPhone for use when running, biking, etc.
One of the features I'd like to implement is an odometer.
I'm getting the location periodically via didUpdateToLocation.
I've tried measuring the distance between newLocation and oldLocation and accumulating the result, but this is not very accurate.  The accumulated value is generally much greater than actual distance traveled.
What algorithm can I use to improve the accuracy of this calculation?

A: It sounds like poor GPS signal is moving the (reported) location of your device all over the place, which your app interprets as the user constantly changing direction. Perhaps it would help to separate the movement from one location to the next into its x- and y-component, and run them through some kind of low-pass filter. This should minimise the effect of "bad" updates that have the effect of moving your location completely out of your actual path.

A: I'm trying to figure this out and think something can be done with the CLLocationManager distanceFilter property.  The property lets you limit didUpdateToLocation delegate calls to updates that are at least a minimum distance from the previous update.  For example with the odometer problem, say you're standing still but the gps is erratically reporting positions 1m around you.  If you set the distanceFilter to 2, then none of these updates will be registered as movement.
The trick is to find a value of distanceFilter that works, and I believe this is somehow related to the horizontalAccuracy of the GPS (which I assume is the cause of the erroneous updates) and the speed at which you're traveling.  The horizontalAccuracy should be good with outdoor activity, but the assumption is that these little inaccuracies accumulate and cause the incorrect odometer reading.
If each call to didUpdateLocation introduces a small amount of error (say, up to 10cm per reading), then it makes sense a slow activity such as walking will be grossly inaccurate if a call were made each meter to didUpdateToLocation.  That would be up to (10cm/1m=) 10% of error per update.  If this were done in a car traveling at 100km/h and the distanceFilter were set to 10m (which is a safe setting since a car traveling at 100km/h will drive very close to a straight line over 10m), then that same error of 10cm will only have a maximum of (10cm/10m=) 1% error per update.  It's probably more complicated than this, but I'm trying to illustrate that speed plays a role.
I think the solution is to pick a value for distanceFilter that minimizes erroneous updates, but most importantly takes into account the speed of the user (such as with the car in the previous example).  Anyone want to figure out an algorithm or formula?


text:
Q: Angular ng-show is not executing with ng-message tag Not sure what I am doing wrong here.
I want to display an  ng-message after the user submit the form. However , the message is shown when the form is rendered. It seem like the ng-show is not evaluating.
I printed the field in the expression and it is false when I open the form. Also, I change it to ng-hide but I have the same issue.
Can you please have a look ..

   first name
 *

<input name="firstName"
  type="text"
  maxlength="25"
  ng-disabled="isSubmitting" required
  ng-model="candidate.firstName"
  ng-class="{error:isFormSubmitted && contactForm.firstName.$error.required}" />

This is a required field {{isFormSubmitted}}

A: Think about ng-messages as a switch clause, you can nest the /ng-show/ng-hide inside ng-message directive but not use them together
For example:

      This is a required field {{isFormSubmitted}}

If you don't want an extra element: , try ng-if, basically ng-if has the priority higher than any other angularjs directive and it will force the ng-message directive to be removed from the DOM tree if the expression is not positive.

This is a required field {{isFormSubmitted}}


text:
Q: Delete a Single Gmail contact using PHP I'm using this script to delete contacts from GMAIL and sometimes it works but it won't delete every contact example, im trying to delete "ADRIANA CALI" this contact is on a group called "modelos", but it won't delete this name... any ideas please?
<?php

// load Zend Gdata libraries
//require 'init_autoloader.php';
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "sampleeemail@gmail.com";
$pass = "samplepassword";
//contact name to delete
$contact_name = 'ADRIANA CALI';

try {
   $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, 'cl');
} catch (Zend_Gdata_App_CaptchaRequiredException $cre) {
    echo 'URL of CAPTCHA image: ' . $cre->getCaptchaUrl() . "\n";
    echo 'Token ID: ' . $cre->getCaptchaToken() . "\n";
} catch (Zend_Gdata_App_AuthException $ae) {
   echo 'Problem authenticating: ' . $ae->exception() . "\n";
}
try {
  // perform login and set protocol version to 3.0
  $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, 'cp');
  $gdata = new Zend_Gdata($client);
  $gdata->setMajorProtocolVersion(3);

  $query = new Zend_Gdata_Query('https://www.google.com/m8/feeds/contacts/default/full');
  $feed = $gdata->getFeed($query);

$contacts=array();;

foreach($feed as $entry){
    $name = (string) $entry->title;
    if(strcasecmp($name,$contact_name)==0) {
        //echo '<xmp>';print_r($entry);echo '</xmp>';
        $id = substr((string) $entry->id,(strpos((string) $entry->id,'base')+5));
        $contacts[] = array('id'=>$id,'name'=>$name);
        echo $entry->id;
    }
    //$xml = simplexml_load_string($entry->getXML());

    //$obj = new stdClass;echo $entry->title."
";
    //$obj->name = (string) $entry->title;
    //$editLink = $entry->getEditLink()->href;
    //echo $editLink.'-66
';
    //$extra_header = array('If-Match'=>'*');
    //$entry->delete();
}

  ?>

Deleting One Contact

<?php echo count($contacts); ?> contact(s) found for deletion under Contact "<?php echo $contact_name; ?>".

  <?php

  foreach($contacts as $contact){
      $deleteLink = 'https://www.google.com/m8/feeds/contacts/default/full/'.$contact['id'];

   //$deleteLink = ' http://www.google.com/m8/feeds/contacts/userEmail/base/contactID';

   //echo $deleteLink.'
';
   //$deleteLink = $contact['id'];
   //$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, 'cp');
    $client->setHeaders(array('If-Match'=>'*','If-None-Match'=>'anything'));
    $gdata = new Zend_Gdata($client);
    $gdata->setMajorProtocolVersion(3);
    // delete entry
    $gdata->delete($deleteLink);

  }
} catch (Exception $e) {
  die('ERROR 71:' . $e->getMessage());
}
?>

<?php
// display results
foreach ($contacts as $contact) {
?>

<?php echo (!empty($contact['name'])) ? $contact['name'] : 'Name not available' . ' deleted!'; ?>

<?php
}
?>

A: It was because maximum contact was reached and query was not processing further, Now I have set the maximum limit to 1000
<?php

// load Zend Gdata libraries
//require 'init_autoloader.php';
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_Feed');

// set credentials for ClientLogin authentication
$user = "sampleemail@gmail.com";
$pass = "sample password";
//contact name to delete
$contact_name = 'ADRIANA CALI';

try {
   $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, 'cl');
} catch (Zend_Gdata_App_CaptchaRequiredException $cre) {
    echo 'URL of CAPTCHA image: ' . $cre->getCaptchaUrl() . "\n";
    echo 'Token ID: ' . $cre->getCaptchaToken() . "\n";
} catch (Zend_Gdata_App_AuthException $ae) {
   echo 'Problem authenticating: ' . $ae->exception() . "\n";
}
try {
  // perform login and set protocol version to 3.0
  $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, 'cp');
  $gdata = new Zend_Gdata($client);
  $gdata->setMajorProtocolVersion(3);

  $query = new Zend_Gdata_Query('https://www.google.com/m8/feeds/contacts/default/full?max-results=1000');
  $feed = $gdata->getFeed($query);

$contacts=array();;

foreach($feed as $entry){
    $name = (string) $entry->title;
    if(strcasecmp($name,$contact_name)==0) {
        //echo '<xmp>';print_r($entry);echo '</xmp>';
        $id = substr((string) $entry->id,(strpos((string) $entry->id,'base')+5));
        $contacts[] = array('id'=>$id,'name'=>$name);
        //echo '
m-'.$name.'-'.$entry->id;
    }
    //$xml = simplexml_load_string($entry->getXML());

    //$obj = new stdClass;echo $entry->title."
";
    //$obj->name = (string) $entry->title;
    //$editLink = $entry->getEditLink()->href;
    //echo $editLink.'-66
';
    //$extra_header = array('If-Match'=>'*');
    //$entry->delete();
}

  ?>

Deleting One Contact

<?php echo count($contacts); ?> contact(s) found for deletion under Contact "<?php echo $contact_name; ?>".

  <?php

  foreach($contacts as $contact){
      $deleteLink = 'https://www.google.com/m8/feeds/contacts/default/full/'.$contact['id'];

   //$deleteLink = ' http://www.google.com/m8/feeds/contacts/userEmail/base/contactID';

   //echo $deleteLink.'
';
   //$deleteLink = $contact['id'];
   //$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, 'cp');
    $client->setHeaders(array('If-Match'=>'*','If-None-Match'=>'anything'));
    $gdata = new Zend_Gdata($client);
    $gdata->setMajorProtocolVersion(3);
    // delete entry
    $gdata->delete($deleteLink);

  }
} catch (Exception $e) {
  die('ERROR 71:' . $e->getMessage());
}
?>

<?php
// display results
foreach ($contacts as $contact) {
?>

<?php echo (!empty($contact['name'])) ? $contact['name'] : 'Name not available' . ' deleted!'; ?>

<?php
}
?>


text:
Q: Logo and image responsiveness Jsfiddle: https://jsfiddle.net/gu7b3fbs/
I'm looking to position the image in the center, and the "Go to the main website" to the ultimate right higher than the picture, while keeping responsivness. However when re-sizing the window, "Go to the main website" should pass above the image. Any help?
HTML:

Go to the main website

CSS:
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,dl,dt,dd,ol,nav ul,nav li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline;}
article, aside, details, figcaption, figure,footer, header, hgroup, menu, nav, section {display: block;}
ol,ul{list-style:none;margin:0;padding:0;}
blockquote,q{quotes:none;}
blockquote:before,blockquote:after,q:before,q:after{content:'';content:none;}
table{border-collapse:collapse;border-spacing:0;}
/* start editing from here */
a{text-decoration:none;}
.txt-rt{text-align:right;}/* text align right */
.txt-lt{text-align:left;}/* text align left */
.txt-center{text-align:center;}/* text align center */
.float-rt{float:right;}/* float right */
.float-lt{float:left;}/* float left */
.clear{clear:both;}/* clear float */
.pos-relative{position:relative;}/* Position Relative */
.pos-absolute{position:absolute;}/* Position Absolute */
.vertical-base{ vertical-align:baseline;}/* vertical align baseline */
.vertical-top{  vertical-align:top;}/* vertical align top */
.underline{ padding-bottom:5px; border-bottom: 1px solid #eee; margin:0 0 20px 0;}/* Add 5px bottom padding and a underline */
nav.vertical ul li{ display:block;}/* vertical menu */
nav.horizontal ul li{   display: inline-block;}/* horizontal menu */
img{max-width:100%;}
/*end reset*/
body {
  background: url('../images/bg.jpg') repeat;
}
.wrap {
    width: 80%;
    margin: 0px auto;
}

.header {
    background: white;
    border-bottom: 13px solid white;
    border-top: 13px solid white;
    margin-top: 0em;
}
.logo
{
    float: left;
  padding-top: 21px;
}
.nav
{
    float: right;
    width: 47%;

}
.nav ul li
{
    float:left;
    border-right: 1px solid rgba(238, 238, 238, 0.65);
}
.nav ul li.a
{
    border-left: 1px solid rgba(238, 238, 238, 0.65);

}
.nav ul li a
{
    font-size: 1.0em;
    color:#5F6A72;
    font-family: 'Verdana', sans-serif;
  display: block;
     -webkit-transition: 0.5s linear;
    -moz-transition: 0.5s linear;
    -ms-transition: 0.5s linear;
    -o-transition: 0.5s linear;
    transition: 0.5s linear;
    padding: 3px 30px;

}
.nav ul li a:hover
{

}

This is the position:

A: is this the desired output?
 .logo{
      padding-top: 21px;
      margin: 0px auto;
      //float: left; //remove this
 }


text:
Q: How to use Streamreader data in another method in C# using windows form app I'm new to using C# in windows form application and I'm trying to get data from an opened file that was read in the streamreader in one method and use it in another method.
The method streamreader was initially used in:
private void mnuFileLoad_Click(object sender, EventArgs e)
        {
            //open file and store values into array
            OpenFileDialog fileDialog = new OpenFileDialog();

            //reading the file selected
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                //reads first line in file (size of array)
                StreamReader sr = new StreamReader(fileDialog.OpenFile());
                int data = int.Parse(sr.ReadLine());

            }
        }

Trying to transfer the streamreader data to another method and use its data
private void btnAscending_Click(object sender, EventArgs e)
        {
//reads first line in file (size of array)
            StreamReader sr = new StreamReader(what do I put here);
            int data = int.Parse(sr.ReadLine());
}

How can I use its data in the method that it was initially used without using the OpenFileDialog command again in another method?

A: You can do it like below. Your existing methods are within a class. To give you an example, I put my methods in the class MyClass. Your class will have a different name. But see the line StreamReader sr = null; Since that declaration is on class level the variable sr can be accessed by any non static method in the class now. To make that clear, I used this.sr one time. But the this-keyword isn't required as you can see in the other method below.
I also added a null check to make sure that the file was opened before, otherwise you're getting an error.
I also added a couple of comments to guide you further
class MyClass
{
    StreamReader sr = null;

    private void mnuFileLoad_Click(object sender, EventArgs e)
    {
        //open file and store values into array
        OpenFileDialog fileDialog = new OpenFileDialog();

        //reading the file selected
        if (fileDialog.ShowDialog() == DialogResult.OK)
        {
            //reads first line in file (size of array)
            this.sr = new StreamReader(fileDialog.OpenFile());
            int data = int.Parse(sr.ReadLine());

        }
    }

    private void btnAscending_Click(object sender, EventArgs e)
    {
        //reads first line in file (size of array)
        // sr = new StreamReader(what do I put here); No longer required

        if (sr == null)
        {
            // When the file wasn't opened yet, sr will be null, in this case do nothing
            return;
        }

        // now continue using sr as planned
        int data = int.Parse(sr.ReadLine());
    }

}

A: It depends a lot on what the logic is about and where your goal is. This is not clearly recognisable from your question.
In your example, you create the StreamReader again with the comment that the first line should be read out again. So both methods should always read out the first line of the file, correct?
If so, then I would not work with a stream, but remember the file path:
        /// <summary>
        /// Gets or sets the last selected file from the OpenFileDialog.
        /// </summary>
        private string LastSelectedFile { get; set; } = null;

        /// <summary>
        /// Reads the first line from the given file.
        /// </summary>
        /// <param name="file">The full path to the file.</param>
        /// <returns>Returns the parsed content of the first line.</returns>
        protected int ReadFromFile(string file)
        {
            using (StreamReader reader = new StreamReader(file))
            {
                return int.Parse(reader.ReadLine());
            }
        }

        private void BtnFileOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                this.LastSelectedFile = fileDialog.FileName;
                int data = this.ReadFromFile(this.LastSelectedFile);
            }
        }

        private void BtnSecondButton_Click(object sender, EventArgs e)
        {
            int data = this.ReadFromFile(this.LastSelectedFile);
        }

However, if the content of the file does not change, then I would rather remember the value read out in a property instead of the last file opened:
        private int FileContent { get; set; }

        private void BtnFileOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                using (StreamReader reader = new StreamReader(fileDialog.OpenFile()))
                {
                    this.FileContent = int.Parse(reader.ReadLine());
                }
            }
        }

        private void BtnSecondButton_Click(object sender, EventArgs e)
        {
            int data = this.FileContent;
        }

If different contents are to be read from the file, then the answer from AdrAs would be more suitable for you.


text:
Q: Easy connectable/click system between enclosures I'm planning to make some devices which I want to easily connect together.
Normally cables are used, but I wonder if there exists something like a 'clicable'  connector, where the output of one enclosure 'clicks' into the input of another enclosure. Like a connection without or with a very short and solid 'cable'.
Of course I can use a cable from one component/microcontroller from one enclosure to the other, but than I cannot detach them. I want to have a detachable solution, without the excess of a cable.
Pins needed:

*

*GND (by default)

*VCC (that would save an adapter for the second device)

*TX (to transmit the signal)

*Maybe RX (for some acknowledgement, but maybe not necessary because of the short distance).

So 3 pins would do probably.
The transmission speed is probably 250 kbs, but maybe I extend it later to 1 mbps max.

A: 3 Formats come to mind:
1 - Pogos and magnets

(Image is from http://www.foxlink.com/)
When you mentioned "click" the magnet action came to mind. This is the least exerted force one, and also easiest to unplug. Not very dense, a bit expensive.
Some examples of products which use this are LitteBits and the old Macbook charger.
2 - Board to board / Mezzanine connectors
This is probably the highest density option, missing the "click" action. Potentially the stiffest connection.

(Image is from http://www.hirose.com/)
3 - Edge connectors
I bet you remember these? They are cheap on the PCB side (and I personally have found to be expensive on the connector side unless you use PCI-express). Also missing the "click" factor.

(Image from Wiki Commons)
Other alternatives
Or just use pin headers protruding from the enclosure. I've also done a short-term project with springs and magnets in cheap a pogo-ish way - very cheap and has the "click" action.
Also, as in the MacBook charger, if you get at least N*2-1 connections, you can make the connector orientation indifferent. (As in, instead of VCC, GND, TX, you do VCC, GND, TX, GND, VCC, so you can flip it.)

A: If I were to want to join two or more enclosures side to side in an inexpensive and rugged way I would consider the use of standard low cost D-Type connectors. These very conveniently can be mounted on the facing sides of the enclosures using male and female flavors of the connectors on either side.

These connector types can be procured with many types of back side interface types. Solder cup pin tails can have wires soldered to them to join to internal circuits. There are ribbon cable types where a ribbon can be attached and then terminated to internal circuits at the other end of the ribbon. Finally there are PCB mount types in both right angle mount and vertical mount where the connector can be mounted directly to the internal circuit board and protrude through a hole in the side of the enclosure.
The 9-pin size I show above should be applicable for your requirements. These are also available in 15, 25, 37 and 50 pin varieties as well.

A: In general it seems you want things called board to board connectors.  Look around on the web site of any decent distributor, like Mouser or DigiKey.  You can also look around on the web sites of obvious suspects that manufacture such things, like Molex, Tyco, etc.


text:
Q: When do browsers add CSS styles as attributes, even though these have not been specified explicitly? Dear StackOverflowers,
I am currently working on a web-site and I happened to stumble across a weird CSS style interpretation.
What I get is

...

for elements that do not have these styles specified anywhere, and even if I view the page source, there is no such styles!
So, the question is, what could be the reason for these styles appearing out of nowhere?
In my particular case there are following styles assigned to the
 element:
position: absolute;
top: 0px;
right: 0px;
height: 100%;
-moz-box-align: center;
-moz-box-pack: center;
display: -moz-box;
padding-bottom: 15px;
padding-top: 15px;
box-sizing: border-box;

Using any browser (Firefox/Chrome/Internet Explorer) I can see that padding-top and padding-bottom styles get overridden with those inline styles mentioned above.
What am I missing here? Where should I search for hints?

A: Ok, as suggested in the comments, the reason for such (weird) behavior was really actually JavaScript.
At first I thought it was not, because I was sure to have all the JS scripts removed from my page, however, there were a couple left.
Thank you everybody, especially shennan and Paulie_D for the ideas.


text:
Q: Javascript best way to handle binded element events in ajax loaded content I have the following jquery ui automplete widget bind:
$(document).ready(function() {
    $('.zip-code-input').autocomplete({
        minLength: 2,
        source: function (request, response) {
            // Get list of zip codes
        },
        select: function(event, ui) {
            // Do something with the selected item
        }
    });
});

Works fine for all zip code elements which are loaded on page request. Now i have to load a html form via ajax with a zip code input in it. Of course the autocomplete doesn't work. How can i handle it, without copy and past the same javascript code into the ajax loaded content?

A: You can do something like this:
function addAutoComplete(inputIdentifier){
   $(inputIdentifier).autocomplete({
     minLength: 2,
     source: function (request, response) {
        // Get list of zip codes
    },
    select: function(event, ui) {
        // Do something with the selected item
    }
 });

Then after your HTML loads,
addAutoComplete(INPUT_IDENTIFIER);


text:
Q: php break string into smaller parts based on string, not length I have read up on the php functions wordwrap and chunk_split but I can't figure out how to break down a string into smaller chunks when there are no physical breaks in the string.
I have a URL-encoded string:
%5B%7B%22partNumber%22%3A%2243160-1104%22%7D%2C%7B%22partNumber%22%3A%2242410-6170%22%7D%2C%7B%22partNumber%22%3A%2222-10-2021%22%7D%2C%7B%22partNumber%22%3A%2255091-0674%22%7D%2C%7B%22partNumber%22%3A%2243160-0106%22%7D%2C%7B%22partNumber%22%3A%2287832-1420%22%7D%2C%7B%22partNumber%22%3A%2273415-1001%22%7D%2C%7B%22partNumber%22%3A%2253627-1274%22%7D%2C%7B%22partNumber%22%3A%2243650-0510%22%7D%5D

of a bunch of part numbers I'm feeding into an API.  This API can only take 500 characters at a time before it returns a false to me, so I need to break my string down to UNDER 500 characters, but still be a complete, searchable string.
Meaning - however it's broken down, each iteration of this new string needs to be

*

*under 500 characters

*end with B%22, so that the next iteration of the string starts with

*partNumber%22
I'm not sure how I would accomplish this using the wordwrap + explode method as I've only ever used this to break a string by length.  Is there a function similar to this that I can use where I can specify an exact string to break at after so many characters?

A: use explode.
$apiStrings = explode("B%22", $string);
foreach($apiStrings as $apiString)
{
    //Do request
}


text:
Q: MVC Validation checkbox I am trying to make sure that at least one 'input checkbox is checked in this list there is about 10 items but I am not sure how to do this? Do I need a flag in the model?

* Data

 @Html.ValidationMessageFor(x => x.flgData,"", new { @class = "text-danger" })

     @foreach (var item in Model.ListOfData)
     {

               <input type="checkbox" value="@item.Value" name="chk" />
               @Html.Raw(@item.Name)
               <input type="hidden" asp-for="@item.DictionaryId" />
               <input type="hidden" asp-for="@item.Name" />

     }

A: You could loop though all the checkbox and check if it is checked
HTML
<input type="button" id="btnSubmitCB" value="Submit" class="btn btn-primary" />
<input type="checkbox" class="chkbox" value="Bike" /> Bike
<input type="checkbox" class="chkbox" value="Car" /> Car
<input type="checkbox" class="chkbox" value="Boat" /> Boat

JQuery
$(document).ready(function () {

    $('#btnSubmitCB').click(function () {
        var cbChecked = false;
        $('input[type=checkbox]').each(function () {
            if (this.checked) {
                cbChecked = true;
                return false;
            }
        });

        if (cbChecked) {
            alert("At least one checkbox is checked");
        }
        else {
            alert("No checkbox is checked");
        }

    });

});

Another way without using .each function
$(document).ready(function () {
    $('#btnSubmitCB').bind("click", function () {
        let checkedCount = $('input[type=checkbox]:checked').length;
        if (checkedCount == 0) {
            alert("no checkbox has been checked")
        }
        else {
            alert("checkbox has been checked");
        }
    });
});


text:
Q: Cipher method not supported on laravel passport I have a project that I want to build an api auth as a part of it, so i have read the Laravel Passport Article: https://laravel.com/docs/5.4/passport as a quick start to do so.
I followed the guide until requesting token. Here is a route which will redirect back to server for authentication:
Route::get('/redirect', function () {
$query = http_build_query([
'client_id' => 'client-id',
'redirect_uri' => 'http://example.com/callback',
'response_type' => 'code',
'scope' => ",
]);

return redirect('http://your-app.com/oauth/authorize?'.$query);
});

Here is the redirect URL:
http://myapp.dev/oauth/authorize?client_id=3&redirect_uri=http%3A%2F%2Fmyapp.dev%2Fcallback&response_type=code&scope=
Once the URL had been visited, a permission page will show up asking me to approve the request.
Once I clicked "Authorize" button, the page shows the following error message:
"Cipher method not supported. This is normally caused by an outdated version of OpenSSL (and/or OpenSSL compiled for FIPS compliance). Please upgrade to a newer version of OpenSSL that supports aes-256-ctr to use this library."
I'm using MAMP 3.5 on macOS Seirra.
openssl version OpenSSL 0.9.8zh 14 Jan 2016
openssl ciphers DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:EDH-RSA-DES-CBC3-SHA:EDH-DSS-DES-CBC3-SHA:DES-CBC3-SHA:DES-CBC3-MD5:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:DHE-RSA-SEED-SHA:DHE-DSS-SEED-SHA:SEED-SHA:RC2-CBC-MD5:RC4-SHA:RC4-MD5:RC4-MD5:EDH-RSA-DES-CBC-SHA:EDH-DSS-DES-CBC-SHA:DES-CBC-SHA:DES-CBC-MD5:EXP-EDH-RSA-DES-CBC-SHA:EXP-EDH-DSS-DES-CBC-SHA:EXP-DES-CBC-SHA:EXP-RC2-CBC-MD5:EXP-RC2-CBC-MD5:EXP-RC4-MD5:EXP-RC4-MD5
I've upgraded openssl from 0.9.8zh to 1.0.2l throw brew command, but I could not link it to be the default openssl.
I have been stuck in this page for one day now. Hope anyone can help.
Thanks

A: I fixed it by installing MAMP PRO 4.x
Thanks


text:
Q: JavaScript Conditionals: confusion with && I am unpacking some data gathered from a form and setting object properties. If the input was a text, I am storing the value. If it was a checkbox, I am storing the "checked" attribute. If it was a radio and it was checked, I am storing the value.
Here is my code:
for (var key in assessment_data) {
  if(assessment_data.hasOwnProperty(key)){
    var type = assessment_data[key].type;
    var name = assessment_data[key].name;
    var isThisChecked = assessment_data[key].checked;
    if (type === "text") {
      this[key] = assessment_data[key].value;
    }
    else if (type === "checkbox") {
      this[key] = assessment_data[key].checked;
    }
    else if (type === "radio" && isThisChecked) {
      this[name] = assessment_data[key].value;
    }
  }
}

I am getting unexpected values for some properties so I am stepping through it in Firebug and finding that the last else if is executing when it should not. For example, when type = "button" and checked = false, the code in that last else if is still executing. Here is a screenshot of firebug at that step. You can see the variables in the conditional and their values on the right. Why is it hitting this code?
I changed the variable name in the question to be clearer and put up a new screenshot showing the code matching in Firebug. Also, here is the contents of the assessment_data object:
I found the cause of my problem (a bad conditional elsewhere: if(this.height_type = "Length") ).
I also figured out that the code inside the last else was not really executing as I though. Firebug was making it look like it was executing and I really don't understand why. The yellow > that shows you what line you are on as you step through was stopping at the line within that if statement, but the code was not actually running. I was able to reproduce this in JSFiddle: http://jsfiddle.net/NDYR8/. I don't understand why it is doing that but for the time being I am happy.
assessment_date Object { value= "05/01/2013" , checked= false , type= "text" }
  checked:  false
  name: undefined
  type: "text"
  value: "05/01/2013"

child_name  Object { name= "child_name" , checked= false , type= "text" }
  checked:  false
  name: "child_name"
  type: "text"
  value: ""

dob Object { value= "05/01/2009" , checked= false , type= "text" }
  checked:  false
  name: undefined
  type: "text"
  value: "05/01/2009"

female  Object { value= "female" , name= "gender" , checked= false , more...}
  checked:  false
  name: "gender"
  type: "radio"
  value: "female"

head_cm  Object { checked= false , type= "text" , value= "" }
  checked:  false
  name: undefined
  type: "text"
  value: ""

head_in  Object { checked= false , type= "text" , value= "" }
  checked:  false
  name: undefined
  type: "text"
  value: ""

head_unit_cm  Object { value= "cm" , name= "head_units" , checked= false , more...}
  checked:  false
  name: "head_units"
  type: "radio"
  value: "cm"

head_unit_in  Object { value= "in" , name= "head_units" , checked= true , more...}
  checked:  true
  name: "head_units"
  type: "radio"
  value: "in"

height_cm   Object { checked= false , type= "text" , value= "" }
  checked:  false
  name: undefined
  type: "text"
  value: ""

height_ft   Object { value= "42" , checked= false , type= "text" }
  checked:  false
  name: undefined
  type: "text"
  value: "42"

height_in   Object { value= "42" , checked= false , type= "text" }
  checked:  false
  name: undefined
  type: "text"
  value: "42"

height_type Object { value= "Height" , name= "height_type" , checked= true , more...}
  checked:  true
  name: "height_type"
  type: "radio"
  value: "Height"

height_unit_cm  Object { value= "cm" , name= "height_units" , checked= false , more...}
  checked:  false
  name: "height_units"
  type: "radio"
  value: "cm"

height_unit_ft_in  Object { value= "ft_in" , name= "height_units" , checked= false , more...}
  checked:  false
  name: "height_units"
  type: "radio"
  value: "ft_in"

height_unit_in  Object { value= "in" , name= "height_units" , checked= true , more...}
  checked:  true
  name: "height_units"
  type: "radio"
  value: "in"

length_type  Object { value= "Length" , name= "height_type" , checked= false , more...}
  checked:  false
  name: "height_type"
  type: "radio"
  value: "Length"

male  Object { value= "male" , name= "gender" , checked= true , more...}
  checked:  true
  name: "gender"
  type: "radio"
  value: "male"

reload  Object { value= " Clear and \n Start Over " , checked= false , type= "button" }
  checked:  false
  name: undefined
  type: "button"
  value: " Clear and \n Start Over "

use_head_circ  Object { value= "head_circumference" , checked= false , type= "checkbox" }
  checked:  false
  name: undefined
  type: "checkbox"
  value: "head_circumference"

use_height  Object { value= "height" , checked= true , type= "checkbox" }
  checked:  true
  name: undefined
  type: "checkbox"
  value: "height"

use_weight  Object { value= "weight" , checked= true , type= "checkbox" }
  checked:  true
  name: undefined
  type: "checkbox"
  value: "weight"

weight_kg  Object { checked= false , type= "text" , value= "" }
  checked:  false
  name: undefined
  type: "text"
  value: ""

weight_lb  Object { value= "47" , checked= false , type= "text" }
  checked:  false
  name: undefined
  type: "text"
  value: "47"

weight_oz  Object { checked= false , type= "text" , value= "" }
  checked:  false
  name: undefined
  type: "text"
  value: ""

weight_unit_kg  Object { value= "kg" , name= "weight_units" , checked= false , more...}
  checked:  false
  name: "weight_units"
  type: "radio"
  value: "kg"

weight_unit_lb  Object { value= "lb" , name= "weight_units" , checked= false , more...}
  checked:  false
  name: "weight_units"
  type: "radio"
  value: "lb"

weight_unit_lb_oz  Object { value= "lb_oz" , name= "weight_units" , checked= true , more...}
  checked:  true
  name: "weight_units"
  type: "radio"
  value: "lb_oz"

A: i'd retry with the last condition beeing isChecked===true ...
that seems to be because JavaScript ist testing if there is a value other than false ...
So if your checked isn't set (which it isn't if unchecked, because it's a attribute without a value if set and not present if not checked) you'll still enter that else if, even if it's null.


text:
Q: как управлять системой из raw-режима на Linux? Необходимо считывать скан-коды клавиш (press и realese отдельно), для этого, как я понимаю необходим raw-режим (kbd_mode -s). Мне выдает какие-то квадратики и символы, которые не особ понятны и для выхода в нормальный режим требуется перезагрузка системы.
Вопросы в следующем, как выйти в нормальный режим из kbd_mode -s?
Или подскажите другую возможность считывать скан-коды клавиш в положении up и down?
заранее спасибо!

A: В иксах можно прочитать сканкоды клавиш через тест:
eri@eri-mini ~% xinput list
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ SYNA7DB5:00 06CB:7DB7 Touchpad            id=11   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Video Bus                                 id=6    [slave  keyboard (3)]
    ↳ Power Button                              id=7    [slave  keyboard (3)]
    ↳ Sleep Button                              id=8    [slave  keyboard (3)]
    ↳ Sleep Button                              id=9    [slave  keyboard (3)]
    ↳ HD WebCam: HD WebCam                      id=10   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=12   [slave  keyboard (3)]
    ↳ Acer WMI hotkeys                          id=13   [slave  keyboard (3)]
eri@eri-mini ~% xinput test 12
key release 36
key press   41
key press   42
key press   43
key release 41
key release 42
key release 43
key press   41
key press   42
key press   43

Окно в фокусе вроде не нужно.
Какие-то квадратики это байты. Там простая структура нажал-отпустил и код клавиши. Чтоб в них разобраться надо загружать байты в структуры. Для этого понадобится си или питон. Выйти из сырого режима можно закрыв программу, но с клавиатуры это врятли получится.
В консоли надо читать event устройство и разбирать структуру байтов которая льётся оттуда. Готовый кейлогер в котором можно посмотреть как всё устроенно на гитхабе. На баше не выйдет.


text:
Q: Yahoo.extend in alfresco for extending dnd-upload component I would like to customize the dnd-upload.js file. For example I want to override _adjustGuiIfFinished method. I've tried several times to do it, but all of them failed (I was using some tutorials/examples:

*

*http://blogs.alfresco.com/wp/wabson/2011/08/12/custom-admin-console-components-in-share/

*https://forums.alfresco.com/forum/developer-discussions/alfresco-share-development/javascrip-autocompete-yahoo-library-03152012)

Here are my steps:

*

*create .js file, let's say dnd-upload-ep.js with following contents:

(function ()
    {
      Alfresco.EpDNDUpload = function Alfresco_EpDNDUpload(htmlId)
      {
        Alfresco.EpDNDUpload.superclass.constructor.call(this, htmlId);
        return this;
      };

      YAHOO.extend(Alfresco.EpDNDUpload, Alfresco.DNDUpload,{
        _adjustGuiIfFinished: function EpDNDUpload_adjustGuiIfFinished()
        {
    ...
    // function body with some modifications
    ...
      })
    });

*

*include just created file in .ftl. Override dnd-upload.get.html.ftl and include file in js dependencies:

...
<@markup id="js">
   <#-- JavaScript Dependencies -->
  <@script type="text/javascript" src="${url.context}/res/components/upload/dnd-upload.js" group="upload"/>
  <@script type="text/javascript" src="${url.context}/res/components/upload/dnd-upload-ep.js" group="upload"/>
</@>
...

*

*instead of original DNDUpload instantiate recently created EpDNDUpload. To do it override dnd-upload.get.js changing 'Widget instantiation metadata':

...
//Widget instantiation metadata...
   var dndUpload = {
      id : "EpDNDUpload",
      name : "Alfresco.EpDNDUpload",
      assignTo : "dndUpload"
   };
   model.widgets = [dndUpload];
...

Seems that it should work, but it doesn't. When I upload document I got error that Alfresco.EpDNDUpload not created and could't be instantiated.
Is there is something I do wrong?


text:
Q: How to update state from a computed property in in vuejs? I want to update my state data inside a computed property called computedFirstName but I got some problems.
I'm able to make changes to the state but it changes on every letter I typed. I don't want that I want it to change only when I click on submit button and update method is called.
Here is my code
vuex
export default new Vuex.Store({
  plugins: [vuexLocalStorage.plugin],
  state: {
    APIData: {
      userInfo: {first_name: null},
    },
  },
  mutations: {
    updateFirstName(state, newFirstName) {
      state.APIData.userInfo.first_name = newFirstName;
    },
  },
  getters: {},
  actions: {},
  modules: {},
});

my component
<script>
import { mapState } from "vuex";
import { getAPI } from "../../axios-base";
import VueJwtDecode from "vue-jwt-decode";
export default {
  name: "UpdateUserInfoDialog",
  computed: {
    ...mapState(["APIData"]),
    computedFirstName: {
      get() {
        return this.APIData.userInfo.first_name;
      },
      set(newFirstName) {
        this.$store.commit('updateFirstName', newFirstName);
      },
    },
  },
  methods: {
    update: function() {
      var user_id = VueJwtDecode.decode(this.$store.state.accessToken).user_id;
      getAPI
        .patch(
          `/rest/api/users/${user_id}/`,
          {
            first_name: this.computedFirstName,

          },
          {
            headers: {
              Authorization: `Bearer ${this.$store.state.accessToken}`,
            },
          }
        )
        .then(() => {
          this.APIData.userInfo.first_name = this.computedFirstName;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

UPDATED
I have also tried like this
    computedFirstName: {
      get() {
        return this.APIData.userInfo.first_name;
      },
      set(newFirstName) {
        this.$emit("update:APIData.userInfo.first_name", newFirstName)
      },
    },

But with this i wont be able to make any change even on submit button
Are there anyway I can do it? Thanks!

A: From what I understand, you just want a debounce when you're typing, if so install debounce package with npm install debounce and use something like this:
<template>
  <input v-model="name" @input="saveDebounced()">
  <button @click="saveName()">Save</button>
</template>

<script>
import { mapState } from "vuex";

export default {
  data: () => ({
    name: ''
  }),
  computed: {
    ...mapState(["APIData"])
  },
  mounted () {
    this.name = this.APIData.userInfo.first_name
  },
  methods: {
    saveName () {
      // update the store and call the API or call an action
      this.$store.commit('updateFirstName', newFirstName)
    },
    // you need an anonymous func here rather than an arrow
    // otherwise you have issues accessing `this`, or you can also
    // try to use this.saveName directly
    saveDebounced: debounce(function () { this.saveName() }, 500)
  }
}
</script>


text:
Q: I need Loopback remote method to return null So I'm learning Loopback for NodeJs and I'm trying to do authentication using bcrypt lib.
I need my login remote method to return a null value if the user is not found or the password doesn't match.
My implementation of login is:

 User.login = function(username, password,cb){
        User.findOne({where:{username: username}}, function(err, user){
            cb(null, user);
            console.log(JSON.stringify(user));

            if(user === null){
                console.error('User not found');
                return null;
            }

            console.log('User found');

            if(!bcrypt.compareSync(password, user.password)){
                console.error('Illegal Password');
                user = null;
                console.log('USER SHOULD BE NULL =======>   '+JSON.stringify(user));
                return user;
            }
            console.log('User Authenticated');

            return user;
        });
    }

In fact the console.log that should be null is actually null if the user is found, however in the auth.service function that should receive the null value if password doesn't match it does receives a user.

 login(username: string, password: string) {

    return this.http.post(this.configService.apiUrl + '/users/login', { username: username, password:password })
      .pipe(map(user =>{

        console.log('AUTHSERVICE USER SHOULD BE NULL  ===========>  '+ JSON.stringify(user));

        //THIS USER IS NEVER NULL IF USER IS FOUND!!! EVEN IF PASSWORD IS NOT MATCHED

        if(!user || user === null){
          console.error('Invalid credentials');
          return;
        }

          sessionStorage.setItem('currentUser', JSON.stringify(user));
          this.loggedIn.next(true);
          this.router.navigate(['/']);
          return user;

      }));
      }

I'sure I'm missing something here any help would be appreciated it.
Thanks.

A: Please note that LoopBack remote methods are async, therefore the result must be passed via the second callback argument, not as a return value.
 User.login = function(username, password,cb){
    User.findOne({where:{username: username}}, function(err, user){
        // ** DON'T FORGET TO HANDLE ERRORS **
        if (err) return cb(err);

        console.log(JSON.stringify(user));

        if(user === null){
            console.error('User not found');
            // ** THE FIRST ARG IS "error", THE SECOND ARG IS "result"
            cb(null, null);
        }

        console.log('User found');

        if(!bcrypt.compareSync(password, user.password)){
            console.error('Illegal Password');
            user = null;
            console.log('USER SHOULD BE NULL =======>   '+JSON.stringify(user));
            return cb(null, null);
        }
        console.log('User Authenticated');

        cb(null, user);
    });
}

To explain the behavior you are observing: in your implementation of login, you always return the user found by findOne, see here:
    User.findOne({where:{username: username}}, function(err, user){
        cb(null, user);

        // none of the code below matters, because the result
        // has been already set via `cb(null, user)`
    }


text:
Q: CMake generated project file to list external source please consider the following structure:
dev_root/
  \__ common/
        \__ inc/
        \__ src/
        \__ CMakeLists.txt
  \__ project1/
        \__ inc/
        \__ src/
        \__ CMakeLists.txt
  \__ project2/
        \__ inc/
        \__ src/
        \__ CMakeLists.txt

Project1 and Project2 are separated projects.
They both use common code.
I want to list (selectively) some common source files into each project's visual studio project file, so that I could edit them in IDE.
I don't want a standalone library for the common code.
For now I use relative paths, for example, in project1's cmake file:
set(_hdr
    inc/proj1.h
    ../common/inc/common1.h
)
set(_src
    src/proj1.cxx
    ../common/src/common1a.cxx
    ../common/src/common1b.cxx
)
source_group("common\\inc" FILES
              ../common/inc/common1.h
)
source_group("common\\src" FILES
              ../common/src/common1a.cxx
              ../common/src/common1b.cxx
)
source_group("inc" FILES inc/proj1.h)
source_group("src" FILES src/proj1.cxx)

add_executable( project1 ${_src} ${_hdr} )

This is not flexible - if ever I want to move folders around, all CMakeLists.txt must be reviewed and modified.
Is there a more elegant way to de-couple the dependencies, or what is a better way to deal with common source files?
Any suggestions welcomed.
Thanks a lot.

A: You may set variable to the path to 'common' folder, and use it for refer to files in it. So, whenever you need to move 'common' folder around, you need to edit only this variable.
CMakeLists.txt:
set(COMMON_DIR ${CMAKE_CURRENT_SOURCE_DIR}/common)

project1/CMakeLists.txt:
set(_hdr
    inc/proj1.h
    ${COMMON_DIR}/inc/common1.h
)
set(_src
    src/proj1.cxx
    ${COMMON_DIR}/src/common1a.cxx
    ${COMMON_DIR}/src/common1b.cxx
)
...


text:
Q: accessing resource property file in *.js file Hi my project is in struts 2. We have written common js files for client side validation.
now the problem is that to implement internalization we have to change alert message as per the language.
so my question is that is there any way to access resource property in js file.
or any one suggest some alternative or example for the same.

A: Store the alert messages in js files with file names like
alert_en.js
alert_fr.js
alert_jp.js
In each file store the alerts like this
var ALERT_EMAIL_INCORRECT = "Incorrect email";
var ALERT_USERNAME_INCORRECT = "Incorrect username";

Include file as per the user languages.
OR
You can load messages from the resource bundle using a JSP file and link in your page like this.
<script type="text/javascript" src="YOUR-FILE.JSP"></script>

In this JSP file you output JavaScript after reading from resource bundle.
Check this also.

A: You can read properties file in js file using messageResource.js library created by me.
1) Include messageResource.js in your html.
<script src="messageResource.min.js"></script>

2) You can access key-value pair of properties file from js as follows.
// initialize messageResource.js with settings
messageResource.init({
  // path to directory containing message resource files(.properties files),
  // give empty string or discard this configuration if files are in the
  // same directory as that of html file.
  filePath : 'path/messageresource/'
});

// will load the file 'path/messageresource/moduleName_en_US.properties'
// and callbackFunction will be executed when loading is complete.
messageResource.load('moduleName', callbackFunction, 'en_US');

// use messageResource.get function to get values from loaded file.
var value = messageResource.get('key', 'moduleName', 'en_US');

A: You can write a JSON file with the native English language as key and L10N message as the value, and use AJAX to load the related JSON depending on user's browser language configuration, and alert the message with alert(tanslatedTable[USER_LANG][ENGLISH_STRING])

A: I do this in my javascript within script tags on the jsp pages :
<code>
    alert("<s:text name="amountMustBeNumeric"/>");
</code>

Works fine for me.


text:
Q: System.FormatException: Unrecognized argument format: '.\application.api.dll' So, I was trying to do the self contained deployed. I got an .exe with my whole publish folder and seems to include all the dlls and other settings like web.config and appsettings.json
I tried to run it locally from folder dotnet application.api.dll and it worked
Then I uploaded whole publish folder on hosting and got that inside of my logs/stdout

Unhandled Exception: System.FormatException: Unrecognized argument format: '.\application.api.dll'.
     at Microsoft.Extensions.Configuration.CommandLine.CommandLineConfigurationProvider.Load()
     at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
     at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
     at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices(AggregateException& hostingStartupErrors)
     at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
     at kado.api.Program.Main(String[] args) in C:\Users\besti\Git\gra\kado.api\Program.cs:line 28

I feel like that I have already tried everything and I cannot figure out what am I suppose to do to fix it. Could anyone guide me a bit? If needed I might give more info.

A: Double check that when using a self-contained app that you are invoking just .\application.api.exe, not .\application.api.exe application.api.dll
For example, your web.config file should look like
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath=".\application.api.exe"
                stdoutLogEnabled="false"
                stdoutLogFile=".\logs\stdout" />
  </system.webServer>
</configuration>


text:
Q: Completeness of Holder Space How do I show that the space of complex-valued functions on $[0,1]$ such that
$$|f(x) -f(y)| < C|x-y|^\frac{1}{2}$$ with norm
$$\|f\| = \sup_{x \in [0,1]} |f(x)| + \inf C$$ where inf is over the constants such that the holder bound holds, is a Banach space? $C$ depends on the function.

A: Note that $\inf C$ for a function $f$ is better described as $$\sup_{x, y \in [0,1], x \ne y} \frac{|f(x) - f(y)|}{|x - y|^{1/2}}$$
Also notice that $f$ is Hölder continuous if and only if this supremum is finite.

Let $(f_n)_n$ be a Cauchy sequence of Hölder continuous functions w.r.t $\|\cdot\|$.
Since $\|\cdot\|_\infty \le \|\cdot\|$ it follows that $(f_n)_n$ is Cauchy w.r.t $\|\cdot\|_\infty$. Recall that $(C[0,1], \|\cdot\|_\infty)$ is a Banach space so there exists $f \in C[0,1]$ such that $f_n \xrightarrow{n\to\infty} f$ uniformly (namely, $f_n$ is precisely the pointwise limit of $f_n$).
We need to show that $f_n \xrightarrow{\|\cdot\|} f$ and that $f$ is  Hölder continuous.
Let $\varepsilon > 0$. $(f_n)_n$ is Cauchy w.r.t $\|\cdot\|$  so there exists $N \in \mathbb{N}$ such that $m, n \ge N \implies \|f_m - f_n\| < \frac\varepsilon3$.
In particular we have $\|f_m - f_n\|_\infty < \frac\varepsilon3$ so letting $m\to\infty$ we get $\|f - f_n\|_\infty \le \frac\varepsilon3$.
On the other hand, for all $x,y \in [0,1], x \ne y$ we also have
$$\frac{|(f_m(x) - f_n(x)) - (f_m(y) - f_n(y))|}{|x - y|^{1/2}} < \frac\varepsilon3$$
Letting $m\to\infty$ we get
$$\sup_{x, y \in [0,1], x \ne y}\frac{|(f(x) - f_n(x)) - (f(y) - f_n(y))|}{|x - y|^{1/2}} \le \frac\varepsilon3$$
Putting this together, we get that for all $n \ge N$ holds $\|f - f_n\| \le \frac{2\varepsilon}3 < \varepsilon$. It follows that $f_n \xrightarrow{\|\cdot\|} f$.
Now, for any $n \ge N$ we have
$$\|f\| \le \|f - f_n\| + \|f_n\| < \varepsilon + \|f_n\| < +\infty$$
so we conclude that $f$ is Hölder continuous.
Therefore, the space of Hölder continuous functions equipped with $\|\cdot\|$ is a Banach space.
Also see here for a similar proof concerning a slightly different norm on Hölder continuous functions.


text:
Q: Showing results of a database query inside Navigation Tab I want to show the results of a database query inside the navigation tab of the home page. How do I call the $results variable inside the posts tab of the home page (the last code block). Thanks
PostController.php
class NoteController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $posts = DB::select(....);
return view('posts.index',['results' => $posts]);
}

The post index blade
@extends('layouts.app')

@section('content')

    @foreach($results as $notes)

          {{$notes->note}}

    @endforeach

@endsection

The home index file
@extends('layouts.app')

@section('content')

Posts

@endsection

A: to use save function in multiple views you can use AppServiceProvider.php file in App->Providers. there you can make composer view to pass variables in all your views look at sample below:
View::composer('*', function ($view) {
  $ads = Ad::all();
  foreach($ads as $ad){
    $customJs = $ad->js;
    $customCss = $ad->css;
  }
  $view->with('customJs', $customJs);
  $view->with('customCss', $customCss);
});

by this sample now I have ability of using $customJs and $customCss in any view i want.
Hope it helps.


text:
Q: How to exclude css to load from homepage alone in magento 2? I want to add if condition in layout xml file to allow css to load in below scenarios.

*

*To load css file only in home page alone.

*To load css by devices(Desktop, mobile & tab)?

Please let me know how to add condition in layout xml file?
<head>
    <css src="fonts/Lato/lato.css" /> <!-- Should be loaded in website home page only -->
    <css src="css/styles-mobile.css"/> <!-- Should be loaded in mobile devices only -->
</head>

A: To load css file only on home page you need to do this things.
You can add below code in you custom theme
app\design\frontend\<vendor>\<theme>\Magento_Theme\layout\cms_index_index.xml

<?xml version="1.0"?>
   <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
       <css src="fonts/Lato/lato.css"/>
    </head>
    <body>
    </body>
</page>

And add lato.css into app\design\frontend\<vendor>\<theme>\web\css\fonts\Lato.


text:
Q: How to make the scroll menu span across the pages of my html output? I have two more pages which begin this way, each with their own scrolling menu, I would like to make a sigle one for all of them. Then I need to run knitr on them for a html page
    ---
    title: "page"
    author: "me"
    date: "26/02/2020"
    output:
      html_document:
        toc: yes
        toc_depth: 3
        toc_float:
          collapsed: yes
          smooth_scroll: yes
      word_document: default
    ---
<style type="text/css">

body{ /* Normal  */
      font-size: 14px;
  }
td {  /* Table  */
  font-size: 12px;
}
h1.title {
  font-size: 38px;
  color: DarkRed;
}
h1 { /* Header 1 */
  font-size: 28px;
  color: DarkBlue;
}
h2 { /* Header 2 */
    font-size: 22px;
  color: DarkBlue;
}
h3 { /* Header 3 */
  font-size: 18px;
  font-family: "Times New Roman", Times, serif;
  color: DarkBlue;
}
code.r{ /* Code block */
    font-size: 12px;
}
pre { /* Code block - determines code spacing between lines */
    font-size: 12px;
}
</style>

<style type="text/css">

#TOC {
  margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
  position: relative;
  width: 100%;
}
}

.toc-content {
  padding-left: 30px;
  padding-right: 40px;
}

div.main-container {
  max-width: 1200px;
}

div.tocify {
  width: 20%;
  max-width: 260px;
  max-height: 85%;
}

@media (min-width: 768px) and (max-width: 991px) {
  div.tocify {
    width: 25%;
  }
}

@media (max-width: 767px) {
  div.tocify {
    width: 100%;
    max-width: none;
  }
}

.tocify ul, .tocify li {
  line-height: 20px;
}

.tocify-subheader .tocify-item {
  font-size: 1.00em;
  padding-left: 25px;
  text-indent: 0;
}

.tocify .list-group-item {
  border-radius: 0px;
}

</style>


text:
Q: Node Puppeteer generating PDF not including Form Inputs I'm trying to use Puppeteer (
https://github.com/GoogleChrome/puppeteer) to create a PDF file for an express app, here is the code:
var puppeteer = require('puppeteer');

var browser = await puppeteer.launch({headless: true});
var page = await browser.newPage();
await page.goto(fullUrl + '/#shareDiv', {waitUntil: 'networkidle'});
page.emulateMedia('screen');
await page.pdf({path:'./uploads/pdfDownload'+Date.now()+'.pdf', printBackground: true, width: '1000px'});

browser.close();

That generates a pretty good PDF but it is hiding any input elements (radios, checkboxes, etc.)
Also I want to target a specific div referenced by ID.
One other thing is get rid of pages on the PDF.
Is this type of customization available on Puppeteer?

A: If anyone runs into an problem similar to this, note that Pupeteer pretty much matches Chrome exactly, so if you are using Mozilla Firefox to test it wont match your PDF exactly, so test in Chrome when using Puppeteer and will be much smoother.

A: Puppeteer will use print-media to generate the PDF, so you'll probably want to try and emulate a screen and see if that fixes your issues (see docs here).


text:
Q: What is the collective word for any semi-literate person that you can hire What is the word to describe any body that has a particular skill that did not go to college to learn the skill.
E.g carpenters, brick layers, DJ's, caterers, repair men, clowns etc.
The closest word I could find was artisan. However, the word artisan suggests that the person creates or repairs things with their hands.But I am looking for the word for anyone at all with a monetizable skill which is not taught in college or Universities.
A compound or word phrase would be acceptable.

A: Tradesman is about as close as it gets for a single-word umbrella term.
AHD

*

*A man who practices a manual trade.

trade

*An occupation, especially one requiring skilled labor; craft: the building trades.

Wikipedia

A tradesman, skilled tradesman, or tradie refers to a worker who
specializes in a particular occupation that requires work experience,
on-the-job training, and often formal vocational education, but not a
bachelor's degree.

Skilled worker also comes close, but doesn't have the blue-collar connotations that tradesman does.
Wikipedia

A skilled worker is any worker who has special skill, training,
knowledge, and (usually acquired) ability in their work. A skilled
worker may have attended a college, university or technical school.
Or, a skilled worker may have learned their skills on the job.
Examples of skilled labor include engineers, scientists, software
development, paramedics, police officers, soldiers, physicians, crane
operators, cdl truck drivers, machinist, drafters, plumbers,
craftsmen, cooks and accountants. These workers can be either
blue-collar or white-collar workers, with varied levels of training or
education, even though they sometimes are called "purple collars".


text:
Q: sending packed iso messages with mux I need to send a packed iso message, i.e. message of type byte[] over a channel. But I need to use the MUX
ISOMsg responce = mux.request(m, 10000);

    if (responce != null){

        //we have a responce
    }
    else{

        //we retransmit or send a reversal
    }

but that 'm' in the MUX request I need it to be packed. Up to now I have been sending my messages like this:
m.setPackager(packager);
byte[] data = m.pack();
channel.send(data);

and its been working great but now I want to hanlde revesals and I am not sure how to do that. Is there a way to send a packed message over the wire and set a timeout like I would do with the MUX?


text:
Q: Add values from a 4d array into another 4d array with 4d corresponding 4d indices I have been trying for quite some time to add the values of a 4d array to another array of same dimension at the same indices and have tried various nested loops, indexing directly, reading the numpy docs ad nauseum, searching for functions to help, etc., but have not been able to figure it out. Printed out the first "half" of each below.
import numpy as np
np.random.seed(3)
vals = np.random.randn(2,3,4,4)
dim1 = np.array([0]*12+[1]*12)
dim2 = np.array([[0]*4+[1]*4+[2]*4 for i in range(2)]).flatten()
dim3 = np.random.randint(4,size = 24)
dim4 = np.random.randint(4,size = 24)
inds = np.array(list(zip(dim1,dim2,dim3,dim4))).reshape(vals.shape)
z = np.zeros((2,3,4,4))
print(vals[0,...], inds[0,...], z[0,...], sep = '\n')

[[[ 1.78862847  0.43650985  0.09649747 -1.8634927 ]
  [-0.2773882  -0.35475898 -0.08274148 -0.62700068]
  [-0.04381817 -0.47721803 -1.31386475  0.88462238]
  [ 0.88131804  1.70957306  0.05003364 -0.40467741]]

 [[-0.54535995 -1.54647732  0.98236743 -1.10106763]
  [-1.18504653 -0.2056499   1.48614836  0.23671627]
  [-1.02378514 -0.7129932   0.62524497 -0.16051336]
  [-0.76883635 -0.23003072  0.74505627  1.97611078]]

 [[-1.24412333 -0.62641691 -0.80376609 -2.41908317]
  [-0.92379202 -1.02387576  1.12397796 -0.13191423]
  [-1.62328545  0.64667545 -0.35627076 -1.74314104]
  [-0.59664964 -0.58859438 -0.8738823   0.02971382]]]
[[[0 0 1 3]
  [0 0 0 0]
  [0 0 1 0]
  [0 0 3 0]]

 [[0 1 3 3]
  [0 1 1 2]
  [0 1 3 2]
  [0 1 0 3]]

 [[0 2 3 3]
  [0 2 2 1]
  [0 2 3 0]
  [0 2 1 1]]]
[[[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]

 [[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]

 [[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]]```

so for example, trying to get z[0,0,...] to look like:

[[[1.78862847 0. 0. 0.]
  [-0.2773882  0. 0. -0.62700068]
  [0. 0. 0. 0.]
  [0.88131804 0. 0. 0.]]


text:
Q: Rails - annotate PDF in browser In my (very first) rails app, I have a model called "Annotations"; this will take some generic data as well as an attachment (PDF). Next, I need to the ability to do the actual annotations to this attachment/PDF ("annotate") and store the results on a field on the "Annotations" model (as a JSON?).
Currently, I think I should create a new method "annotate" in the AnnotationsController (needs to update the annotations object) and call a new view called "annotate.html.erb".
Any advice how to go about "the rails way" ?
Update
meanwhile, I have:
model (annotation.rb)
class Annotation < ApplicationRecord
    has_many :comments, dependent: :destroy
    belongs_to :documenttype
    has_attached_file :file, styles: { large: "600x600>", medium: "500x500>", thumb: "150x150#" }, default_url: "/images/:style/missing.png"

    accepts_nested_attributes_for :documenttype

    validates_attachment_content_type :file, content_type: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf']

    validates :name, presence: true, uniqueness: true, length: { minimum: 10, maximum: 50 }
    validates :description, length: { minimum: 20, maximum: 500 }
    validates :documenttype, presence: true
    validates :file, presence: true
end

routes
  Rails.application.routes.draw do
      root 'dashboard#index'
      devise_for :users
      resources :users,:documenttypes, :documents
      resources :annotations do
        resources :comments
  end
  get "annotate", to: "annotations#annotate"

the controller (AnnotationsController)
class AnnotationsController < ApplicationController
before_action :annotate, only: [:edit, :update ]

def index
    @annotations = Annotation.all
end

def show
    @annotation = Annotation.find(params[:id])
end

def new
    @annotation = Annotation.new
end

def edit
    @annotation = Annotation.find(params[:id])
end

def create
    @annotation = Annotation.new(annotation_params)

    if @annotation.save
        redirect_to @annotation
    else
        render 'new'
    end
end

def update
    @annotation = Annotation.find(params[:id])

    if @annotation.update(annotation_params)
        redirect_to @annotation
    else
        render 'edit'
    end
end

def destroy
    @annotation = Annotation.find(params[:id])
    @annotation.destroy

    redirect_to annotations_path
end

private

    def annotate
        @annotation = Annotation.find(params[:id])
    end

    def annotation_params
        params.require(:annotation).permit(:name, :description, :file, :active, :documenttype_id)
    end
end

views that render 1 form (using simple_form)

Annotation

      <%= simple_form_for @annotation,  html: { class: 'form-horizontal', multipart: true },
        wrapper: :horizontal_form,
        wrapper_mappings: {
            check_boxes: :horizontal_radio_and_checkboxes,
            radio_buttons: :horizontal_radio_and_checkboxes,
            file: :horizontal_file_input,
            boolean: :horizontal_boolean
          } do |f| %>

          <%= f.error_notification %>

          <% if @annotation.file.blank? %>
            <%= f.input :file, as: :file, input_html: { accept: ('application/pdf') } %>
            <% else %>
          <% end -%>

            <%= f.input :name, placeholder: 'Enter name' %>

            <%= f.input :description, placeholder: 'Description' %>

            <%= f.association :documenttype %>

          <%= f.input :active, as: :boolean %>

          <%= f.button :submit %>
          <% unless @annotation.file.blank? %>
          <%= link_to ' Annotate', annotate_path(@annotation), :class => "btn btn-default" %>
          <% end -%>

      <% end -%>

<%= link_to 'List' , annotations_path %>

    <% unless @annotation.file.blank? %>

File name: <%= @annotation.file_file_name %>

      <iframe src="<%= @annotation.file %>" width=100% height=450px class="img-rounded">

    <% end %>

  <% unless @annotation.new_record? %>

        <%= render @annotation.comments %>

        <%= render 'comments/form' %>

  <% end -%>

Also, I created a view call annotate.html.erb
It is called now as static page under http://localhost:3000/annotate ; while I think it should be under http://localhost:3000/annotations/annotate/:id -- so looks like a routing issue (for) now. (Routing still is a bit of a mystery to me :-) )

A: If you want to do it the rails way:
Your model should be singular, so: Annotation.rb:
class Annotation < ApplicationRecord

end

Your controller should be called AnnotationsController and have the standard CRUD methods: new and create (to create a new annotation). edit and update to update an annotation and destroy to destroy your annotations.
SOMETHING LIKE:
class AnnotationsController < ApplicationController
  before_action :set_annotation, only: [:edit, :update, :destroy]

  def index
    @annotations = Annotation.all
  end

  def new
    @annotation = Annotation.new
  end

  def create
    @annotation = Annotation.new(annotation_params)

    if @annotation.save
      redirect_to annotations_path, notice: "annotations created"
    else
      render action: 'new'
    end
  end

  def edit
  end

  def destroy
    @annotation.destroy
    redirect_to annotations_path
  end

  def update
    if @annotation.update(annotation_params)
      redirect_to annotations_path
    else
      render action: 'edit'
    end
  end

  private

  def set_annotation
    @annotation = Annotation.find(params[:id])
  end

  def annotation_params
    params.require(:annotation).permit(:name, ...)
  end
end

Your views should live in views/annotations/
Since this is your first rails app, I suggest you use the scaffolding option to build your app, which according to the documetation is:

A scaffold in Rails is a full set of model, database migration for
  that model, controller to manipulate it, views to view and manipulate
  the data, and a test suite for each of the above.

rails g scaffold Annotate
see: http://guides.rubyonrails.org/command_line.html

A: Found the routing get "annotations/:id/annotate" => "annotations#annotate", as: 'annotate'
And the set_annotation method should not be private.
May be there is a better routing (always welcome), but it works now.