firebase_messaging onResume and onLaunch not working

Question: I am getting the notification when the app is in the foreground but not when the app in the background. Also, I have google-ed/StackOverflow-ed for like 2 hours or more but able to resolves this.
My Configurations are :
  firebase_auth: ^0.10.0
  firebase_messaging: ^5.0.0

The manifest is like this:

The code is like this:
final notifications = new FirebaseMessaging();

class AppNotifications {
  static String fcmToken = '';

  static Future<Null> init() async {
    appLogs("AppNotifications init");

    notifications.requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true));

    await configure();

    fcmToken = await notifications.getToken();
    appLogs("FCM TOKEN : " + fcmToken);

    notifications.onTokenRefresh.listen((newToken) {
      fcmToken = newToken;
      appLogs("FCM TOKEN onTokenRefresh: " + fcmToken);
    });

    await updateFCMToken();
  }

  static Future<Null> configure() async {
    appLogs("AppNotifications Configure");

    notifications.configure(onMessage: (msg) {
      appLogs('FCM onMessage: ' + msg.toString());
    }, onLaunch: (lun) {
      appLogs('FCM onLaunch: ' + lun.toString());
    }, onResume: (res) {
      appLogs('FCM onResume: ' + res.toString());
    });
  }

  static Future<Null> updateFCMToken() async {
    auth.currentUser.fcmToken = fcmToken;
    await updateUserInSharedPreference();
  }
}

I am calling the function like this:
class HomeScreenState extends State<HomeScreen> {

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration(milliseconds: 100), () async {
      await AppNotifications.init();
    });
  }

..... ....

I am using postman for sending the notification :

My logs :
**(App is Foreground)**  I/flutter (31888): APPLOGS : FCM onMessage: {notification: {title: Test notification title, body: Test notification body}, data: {status: done, id: 1, foo: bar, click_action: FLUTTER_NOTIFICATION_CLICK}}
  **(App is Background)**  W/FirebaseMessaging(31888): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.

Flutter doctor :
[✓] Flutter (Channel stable, v1.2.1, on Mac OS X 10.14.4 18E226, locale en-GB)
    • Flutter version 1.2.1 at /Users/Ajay/SDK/flutter
    • Framework revision 8661d8aecd (3 months ago), 2019-02-14 19:19:53 -0800
    • Engine revision 3757390fa4
    • Dart version 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/Ajay/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.2.1, Build version 10E1001
    • ios-deploy 1.9.4
    • CocoaPods version 1.6.0

[✓] Android Studio (version 3.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 34.0.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[!] VS Code (version 1.33.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    ✗ Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (1 available)
    • ONEPLUS A5000 • b47e8396 • android-arm64 • Android 9 (API 28)

Comment: @ShangariC `click_action` is recommended if you target Android devices. Otherwise `onLaunch` / `onResume` won't be called when user clicks on a notification in the tray. For more info check out _[Sending Messages](https://pub.dev/packages/firebase_messaging#sending-messages)_ in the docs.
Comment: @George Is click_action param is must when push notification is received from API.onLaunch & onResume is not called.
Comment: I'm struggling with notifications support on Android too. Except that I don't get notifications while the app is in foreground. But even with 'background-arrived' notifications, data payload is lost on app launch. iOS works perfectly fine though.
Comment: I finally solved my Firebase Messaging issues by initializing Firebase inside of `runApp(MyApp())`. Since you already seem to do that, the only difference between your code flow & mine is that you use version `5.0.0`. Did you try downgrading? E.g. I use `4.0.0+4`.
Comment: @AjayKumar Did you resolved the issue?
Comment: @George Okay sure,Thanks,But in iOS If my app is in background notification banner is not coming.while opening an app foreground notification with dialog only working from APi.If I hit from console all works fine.Any suggestion regarding this.
Answer: lost my 2 days to fix this issue, it may helpful for you.
notification tag only for showing notification. you can access only data content on onResume/onLaunch.
If you want handle notification message inside onResume/onLaunch add those messages in data tag also, Then you can do what ever you want.
refer more detail on this link
send this notification message
{
       "notification": {
          "body": "body",
          "title": "title"
       },
       "priority": "high",
       "data": {
        "body": "body",
          "title": "title"
          "click_action": "FLUTTER_NOTIFICATION_CLICK",
          "id": "1",
          "status": "done",
          "image": "https://ibin.co/2t1lLdpfS06F.png",
       },
       "to": <your token>
    }

you will receive below information onResume or onLaunch, your notification tag will be empty here
{notification: {}, data: {image: https://ibin.co/2t1lLdpfS06F.png, google.original_priority: high, google.sent_time: 1560858283888, google.delivered_priority: high, body: body , title: title, click_action: FLUTTER_NOTIFICATION_CLICK, google.message_id: 0:1560858283908500%eefdc741eefdc741, collapse_key: <package>, google.ttl: 2419200, from: <from>, id: 1, status: done}}

you can use title and body which is added in data tag.
Comment: This is the right answer! The `click_action` key needs to be inside the `data` object. Firebase is spectacularly undocumented.
Comment: In some tutorials they mention "clickAction" that poses this problem
Comment: @MDavid can you please tell me which route I put code of firebase init?
I have add this but still not wroking.
notifications are showing in background but onResume is not working..
Comment: it is working when click_action is n notification not data?
Comment: totally agreed with Anand Saga ,
Comment: @Hayat I am not sure it is good practice or not if you want that you receive notification in any mode you have to add and receive the "Message", "Title" inside the "data" object  as well.
in short the "Notification" object will be used by OS and "data" object will be all yours. do let me know if didn't get my point.
Comment: Actuclly I am making video calling app I want start 'Incoming Call' screen on notification, in every mode.
Comment: @Hayat add and read some custom tag in "data" object it will work in all mods
Comment: Thanks @MDavid can you give me an example, i try but I not able to find out.
Comment: @Hayat A working Example which I am using and receiving it in every case
```json
{
    "notification": {
        "body": "Message String",
        "title": "Title String"
    },
    "priority": "high",
    "data": {
        "click_action": "FLUTTER_NOTIFICATION_CLICK",
        "Custom_App_Action ": "Video Call",
        "Message": "Message String",
        "Title": "Title String"
    },
    "to": "Device Token"
}
```
Comment: @MDavid okay, I have received data now i want to start my ringing screen on null context, becuase app in background.
Please check:  https://stackoverflow.com/questions/61700435/how-to-start-specific-screen-when-notification-appear-in-flutter
Comment: @AnandSaga This is the one which i was looking for last few days. how did you created this json format. Do you have any sample code for the same.
Answer: In my case, onResume and onLoad were not firing because I was missing click_action: 'FLUTTER_NOTIFICATION_CLICK' under the notification property, not the data property.
Once I changed my payload to be in the following format, onResume and onLoad started firing for me.
{
    notification: {
        title: 'Title',
        body: 'Body',
        click_action: 'FLUTTER_NOTIFICATION_CLICK'
    }
}

I found this documented here.
If you are setting this in TypeScript (possibly others), it will be necessary to set this via the message's android.notification.clickAction property.  Otherwise, you may receive errors about the property being invalid.  An example of this with a MulticastMessage is as follows.  Note that it doesn't show message construction from start to finish; only enough to show the context for setting clickAction.
// Initialize the notification
const notification: admin.messaging.Notification = {
    title: 'Hello',
    // Though the "clickAction" property is available here, it throws an error about
    // having an invalid property when actually trying to send the notification.
    // Instead, the "clickAction" property is set further downstream under the
    // MulticastMessage.android.notification object.
    // clickAction: 'FLUTTER_NOTIFICATION_CLICK'
};

// Do other things to build your notification

const message: admin.messaging.MulticastMessage = {
    tokens: [],
    notification: notification
};

// Do other things to build your message

// If a notification is being sent then set the click_action
if (message.notification) {
    // Combine with the existing message.android object, if one exists
    message.android = message.android || {};
    message.android.notification = Object.assign(message.android.notification || {}, {
        clickAction: 'FLUTTER_NOTIFICATION_CLICK'
    });
}

Comment: its launching my activity if place inside data tag. but onResume and onLoad not working.
Comment: I am getting this error if I add it in the `notification` payload: `Invalid JSON payload received. Unknown name "click_action" at \'message.notification\': Cannot find field.`
Comment: I updated my answer to show an example of how we're setting it in code.
Comment: this has to be placed in the android.notification object, not the regular notification object!!!!!!!!!!!!!
Answer: On the documentation of the firebase_messaging package in this section link to plugin docs they say you need to include click_action: FLUTTER_NOTIFICATION_CLICK as a "Custom data" key-value-pair in your server-side post request for your onResume and Onlaunch methods to be called.
For example here am using the php firebase admin sdk to send notifications to the FCM here is a code sample for sending a notification:
        $factory = (new Factory)->withServiceAccount('path to firebase keys json file');
                $messaging = $factory->createMessaging();

                $deviceToken = $user->deviceToken;
    $message = CloudMessage::withTarget('token', $deviceToken)
                        ->withNotification(Messaging\Notification::create('title', 'body'))
                        ->withData(['custom-data-key1' => 'custom-data-value1', 'custom-data-key2' => 'custom-data-value2', 'click_action'=>'FLUTTER_NOTIFICATION_CLICK']);
$messaging->send($message);

Answer: Your are probably missing some metadata in AndroidManifest (as your log tells you).
You need to add the following to your manifest:
<meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="@string/default_notification_channel_id"/>

It seems like a duplicate
Answer: The answer posted by Anand saga is correct
You need to add title and body in data section.Notification payload will be blank onResume and onLaunch although it was sent from backend nodejs API.
Below is the sample payload flutter is resolving to onResume:
on resume {notification: {}, data: {image: https://ibin.co/2t1lLdpfS06F.png, google.original_priority: normal, google.sent_time: 1577389234347, google.delivered_priority: normal, body: "Custom Body", type: OrderDetail, title: "Custom title", click_action: FLUTTER_NOTIFICATION_CLICK, google.message_id: 0:1577389234352165%dfef845edfef845e, collapse_key: <<App NAme>>, google.ttl: 2419200, from: 790713779055, id: "5e050c04c308f6abb5a60b2e"}}

Typical dart config will look like this.
firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print('on message ${json.encode(message['data']['title'])}');
        redirectScreenOnLoad(message);
      },

      onResume: (Map<String, dynamic> message) async {
        firebaseMessaging.onTokenRefresh;
        print('on resume $message');
        redirectScreenOnLoad(message);

      },

      onLaunch: (Map<String, dynamic> message) async {
        firebaseMessaging.onTokenRefresh;
//        await API.updateUserApiToGetFCMKey();
        print('on launch $message');
        redirectScreenOnLoad(message);
      },
    );

in redirectScreenOnLoad(String message) i am checking the input payload and redirecting to different screen
Comment: this is over Android, but in iOS [data] does not exist in the json, did you fix this also for iOS i have been with this for the last week works in onResume but fails on onLaunch
Comment: I didn't test this in iOS. Can you post the response you are getting in iOS from firebase messaging?
Comment: just make it work i needs to be call from initiState to work
Comment: Where is redirectScreenOnLoad() function?
Comment: it was a matter of configurations you need to do the steps in documentation completely and it gonna work
Comment: can you show us redirectScreenOnLoad function?
Answer: Another thing to add for the troubleshooting with FCM is within your onMessage handling.
First, in onMessage, print the output to see if your device is receiving the message. Notifications can fail beyond this point and not show, so it's good to know if it's getting it at all. If it is, then you know you have configured FCM correctly and that your problem lies within your UI handling.
Next, inspect the onMessage print statement and ensure your handling of that data after is correct. I noticed that the Android data was in a different structure pattern than the iOS type -- so this can lead you to parsing the data incorrectly, which may not show the notification and will not throw an error either.
Here's an example of what I mean:
    _fcm.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        String sender;
        String parsedMessage;

        if (Platform.isAndroid) {
          sender = message['notification']['title'];
          parsedMessage = message['notification']['body'];
        }
        if (Platform.isIOS) {
          sender = message['aps']['alert']['title'];
          parsedMessage = message['aps']['alert']['body'];
        }
      },
    );

You can see that I parse the same data differently depending on the platform. Without doing this, the notification never appeared and no failure was ever indicated.
Again, this is just something to try before you tear apart your .ts/.js cloud functions.
Answer: Complete guide to handle firebase messaging:
handleMessaging() {
  _firebaseMessaging.configure(
    onMessage: (Map<String, dynamic> message) async {
      // showNotification(
      //     message['notification']['title'], message['notification']['body']);
      print("onMessage: $message");

      print('Data is: '+ message['data']['screen'].toString());

    },
    onLaunch: (Map<String, dynamic> msg) {
      print("Called onLaunch");
      print(msg);
      print('Data is: '+ msg['data']['screen'].toString());

      if(msg['data']['screen'].toString() == 'Chat Screen') {
        return //Navigate to chatApp();
      }
      return null;
    },
    onResume: (Map<String, dynamic> msg) {
      //(App in background)
      // From Notification bar when user click notification we get this event.
      // on this event navigate to a particular page.
      print(msg);

      // // Assuming you will create classes to handle JSON data. :)
      // Notification ns = Notification(title: msg['title'], body: msg['body']);
      //
      return null;
    },
    // onMessage: (Map<String, dynamic> msg) {
    // // (App in foreground)
    // // on this event add new message in notification collection and hightlight the count on bell icon.
    // // Add notificaion add in local storage and show in a list.
  );
}

Answer: if your android app is in kotlin you should add this as your application activity
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistrantCallback {

    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
    }
}

and don't forget to add it your Manifist
android:name=".Application"
Answer: onLaunch: (Map<String, dynamic> msg) {
    print("Called onLaunch");
    print(msg);
    if(msg['data']['screen'].toString() == 'chat') {
        //Navigate to chat screen
    }
    return null;
},

Answer: Important note that the new version of FirebaseMessaging is a big change so all of the above will not work if you discover this thread.
Configure is gone, as with other Flutter 2 updates things are through .listen methods.
There is a thread on this:
How to configure Firebase Messaging with latest version in Flutter?


Rewrite the image markup from specific image field

Question: In a Drupal 7 site, I have an image field that allows unlimited images, called field_gallery_images. I built a template file for this field to create a custom image slider. I want to rewrite the HTML markup for the image to add a lazy-load component. So, instead of:

I want:

Right now, the images are being run through theme_image() and so by the time it gets to the template, the markup is all set. I only want to alter the markup for this one field. I tried theme_preprocess_image(), but that altered all images.
Comment: Here is the same question for D8: https://drupal.stackexchange.com/questions/272250/rewrite-the-image-markup-from-specific-image-field-in-drupal-8 Just in case.
Comment: Which Drupal version?
Comment: Edited. Yes Drupal 7
Answer: I assume that you are using Drupal 7.
Short Answer
Implements template_preprocess_field() and overrides theme_image().
/**
 * Implements template_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];

  if ($element['#field_name'] === 'field_image') {
    foreach (element_children($element) as $key) {
      $item = &$element[$key]['#item'];

      $src = file_create_url($item['uri']);
      unset($item['uri']);
      $item['attributes']['data-lazy'] = $src;
      $item['attributes']['class'] = array('lazyload');

      $element['#items'][$key] = $item;
      $variables['items'][$key]['#item'] = $item;
    }
  }
}

/**
 * Overrides theme_image().
 */
function mytheme_image($variables) {
  $attributes = $variables['attributes'];

  if (!empty($variables['path']) || !isset($attributes['data-lazy')) {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '';
}

Long Answer
By implementing template_preprocess_field(), you can alter the theme variables and also the theme function for a field.
Example code:
/**
 * Implements template_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];

  if ($element['#field_name'] === 'field_image') {
    foreach (element_children($element) as $key) {
      $item = &$element[$key]['#item'];

      $src = file_create_url($item['uri']);
      unset($item['uri']);
      $item['attributes']['data-lazy'] = $src;
      $item['attributes']['class'] = array('lazyload');

      $element['#items'][$key] = $item;
      $variables['items'][$key]['#item'] = $item;
    }
  }
}

Remember to change field_image to the field name you defined.
It is the structure of $variables:

$variables['items'][0]['#item'] is a typical usage of theme function in render array. The code above has done a couple of things:

unset uri, which is used to format the attribute src in theme_image()
construct image path and assign it to the attribute data-lazy
add lazyload to class
synchronise the item array to different location of $variable

The last point is a bit weird, but there are 3 different location always store the same item array. They are

$variables['element'][0]['#item']
$variables['element']['#items'][0]
$variables['items'][0]['#item']

Theoretically, $variables['items'][0]['#item'] is the only one be used in theme function, But, in my opinion, it is better to change them at the same time for preventing any potential issue in future. (Maybe someone can provide more suggestion here?)
The last but not the least, you have to override the theme_image(). It is a global change but won't affect too much.
/**
 * Overrides theme_image().
 */
function mytheme_image($variables) {
  $attributes = $variables['attributes'];

  if (!empty($variables['path']) || !isset($attributes['data-lazy')) {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '';
}

Comment: Jimmy Ko, this is awesome. Thanks for such an in-depth response. Worked perfectly.
Comment: One more question: any thoughts on how I could alter the image src to be a placeholder? I tried adding `$item['uri'] = '/' . path_to_theme() . '/images/placeholder.jpg';` The current image src is `src="//localhost:3010/sites/default/files/styles/property_slideshow_500h/public?itok=zKlJQsDU"` which is essentially no image or a broken image.
Comment: Do you mean a default image for the field? You can upload one in the field settings. If you need more details, please update this question or just raise a new question. I will follow up.


Postgresql cannot restart No PostgreSQL clusters exist

Question: I want to restart my postgres using command
sudo service postgresql restart

However I'm getting the following error:

[warn] No PostgreSQL clusters exist; see "man pg_createcluster" ...
(warning).

I already have postgres running, showing through ps aux:
# ps aux| grep postgres
postgres     1  0.0  1.1 287484 24328 ?        Ss   21:58   0:00 postgres
postgres    77  0.0  0.4 287608  8588 ?        Ss   21:58   0:00 postgres: checkpointer process
postgres    78  0.0  0.1 287484  3884 ?        Ss   21:58   0:00 postgres: writer process
postgres    79  0.0  0.4 287484  8680 ?        Ss   21:58   0:00 postgres: wal writer process
postgres    80  0.0  0.3 287896  6640 ?        Ss   21:58   0:00 postgres: autovacuum launcher process
postgres    81  0.0  0.1 142612  3120 ?        Ss   21:58   0:00 postgres: stats collector process
root      1253  0.0  0.0  12788   972 pts/0    S+   22:31   0:00 grep postgres

Now searching online, I found this post. I followed the solution to create a cluster:
sudo pg_createcluster 9.6 main
sudo service postgresql stop
sudo service postgresql start

After this, I am able to "restart" posgres through
sudo service postgresql restart

HOWEVER, this is not on the original cluster. As if I run ps-aux, I see a new cluster setup, this is not what I want.
# ps aux| grep postgres
postgres     1  0.0  1.1 287484 24328 ?        Ss   21:58   0:00 postgres
postgres    77  0.0  0.4 287608  8588 ?        Ss   21:58   0:00 postgres: checkpointer process
postgres    78  0.0  0.1 287484  3884 ?        Ss   21:58   0:00 postgres: writer process
postgres    79  0.0  0.4 287484  8680 ?        Ss   21:58   0:00 postgres: wal writer process
postgres    80  0.0  0.3 287896  6640 ?        Ss   21:58   0:00 postgres: autovacuum launcher process
postgres    81  0.0  0.1 142612  3120 ?        Ss   21:58   0:00 postgres: stats collector process
postgres  1292  0.0  1.2 287628 25680 ?        S    22:42   0:00 /usr/lib/postgresql/9.6/bin/postgres -D /var/lib/postgresql/9.6/main -c config_file=/etc/postgresql/9.6/main/postgresql.conf
postgres  1294  0.0  0.1 287628  3944 ?        Ss   22:42   0:00 postgres: 9.6/main: checkpointer process
postgres  1295  0.0  0.1 287628  3940 ?        Ss   22:42   0:00 postgres: 9.6/main: writer process
postgres  1296  0.0  0.1 287628  3944 ?        Ss   22:42   0:00 postgres: 9.6/main: wal writer process
postgres  1297  0.0  0.3 288056  6464 ?        Ss   22:42   0:00 postgres: 9.6/main: autovacuum launcher process
postgres  1298  0.0  0.1 142620  3172 ?        Ss   22:42   0:00 postgres: 9.6/main: stats collector process
root      1329  0.0  0.0  12788   968 pts/0    S+   22:42   0:00 grep postgres

All the start/restart/stop is all applied to the new cluster. I just want to restart the original cluster. How can I do that?
Comment: PostgreSQL 9.6 EOL'd last month. Upgrade your system as soon as possible
Comment: It indicates that the original Postgres instance that is running `postgres` was created/started from a different system. What OS and version? Have you installed Postgres from more then one source? Have you looked in ``\etc\init.d\`` for a Postgres script? Add answers as update to your question.
Answer: I found that this happened because the postgresql db was running inside a container. To restart the database, I'll need to restart the docker container


Can a stiff piano action be lightened?

Question: I have a grand piano with an extremely heavy/stiff action. Is it possible to lighten the action without completely rebuilding it?  Is this something a professional piano tuner would do or would I have to find someone else with this specific skill/training?
(In case it matters, this is an old 5'8" Kimball Viennese Classic)
I am aware of the importance of good posture, fingering, using arm weight properly, etc., but I'm just learning so my skill is low and it's difficult to improve when I can't practice more than 15-20 minutes at a time due to fatigue.
Comment: Related: https://music.stackexchange.com/questions/64065/what-makes-an-acoustic-piano-touch-heavy
Comment: Thanks for link - my searching didn't turn up that one (although I remember seeing a similar discussion of using arm weight etc in a different topic - definitely something I need to focus on)
Answer: You say it's heavy/stiff.  Which?  If the action is well-regulated, there's probably little that can be easily done about the weight.  But a piano technician can do something about 'stiff'.   We can't diagnose this online.  Call your tuner in to advise.
Comment: I guess I don't know what the difference is between heavy and stiff (lack of experience, sorry).  It takes significantly more force (compared to other pianos I've used) to push the keys down.
Comment: My advice stands.
Answer: Yes, a stiff piano action can be lightened. Possible causes for the resistance can come from:

an unbalanced key;
deteriorated or misadjusted pivot felts.

To start with, you could try making your feeling objective by measuring the minimal weight that initiates the motion of the keys. I don't remember the normal values but that can be found online, or you can compare with other pianos.
If the required weight is larger than normal, this may be adjusted by changing / picking or even adding oil in the pivot joints. But this should not done randomly, by guess! A standard regulation procedure should be applied. In some extreme cases, weight can be added in the key itself---as in this picture, but with weights on the other side of the key support).
A professional should be able to tell you easily. If, for some reasons, you want to avoid calling a tuner, you might want to try evaluating if friction in the pivot joints is too high. For example, by disassembling the hammer and counting the number of oscillations when dropped from ... (see standard procedures).

Can a stiff piano action be lightened?


How to model the distribution of a random variable

Question: Problem:
Suppose there are two different versions of a piece of software that are distributed among 2*N employees within a company, such that exactly N employees get one version and the rest get the other version. Each employee installs the version on his/her respective computer. The company then hosts a programming competition between N participants and they all need to use the same software. To ensure this, an employee is selected to check the software on each computer until they find exactly N computers that have the same version installed (it doesn't matter which version it is). Upon finishing his task, the employee reports the number of computers that were checked to the project supervisor (K) and the order in which they were checked, but fails to note the version that the participants would be using. The supervisor then needs to check the computers in the same order until he is sure he knows what version of the software to use.
Let $X$ be the random variable used to model the number of computers the supervisor would need to check in order to be sure of the version that they would have to use. What is the distribution of $X$?
Note: I'm currently working on a piece of software that for the most part doesn't deal with probability, random variables etc. so this is not a field I'm really familiar with. I did some searching, however, but I can't fully commit to reading everything I need to know to tackle problems like the one I'm posting about (it's really the only one I need to deal with in the entire project), so I would appreciate if you guys could help me out.
Answer: For the employer to know the order in which the computers were checked, he must have been noting the first computer as version $A$ and the first computer with a different version than $A$ as $B$ and then forgetting what version $A$ and $B$ correspond to. An example of a sample path of him noting:
A, A, B, A, B, B, A, ...

When he has $N$ of the same system he will then call that version $T$ (TRUE) and the other version $F$ (FALSE).  In the above example, if he has $N$ of version $A$ he will then rewrite the sample path to
T, T, F, T, F, F, T, ...

and otherwise, if he has $N$ of version $B$ he will rewrite the sample path to
F, F, T, F, T, T, F, ...

Hence no matter what, we will have

$N$ computers with version $T$ and
$K - N$ computers with version $F$. $\scriptsize (K-N \in [0,N))$

If the first computer was registered as one of the computers with the version that we have $N$ of, i.e. $T$ then the supervisor can announce

We will use {the version on computer 1}.

If the first computer was registered as one of the computers with the version that we have $K-N$ of, i.e. $F$, the employer can tell the supervisor "this is the incorrect version" so the supervisor can announce the other version

We will use {the version different than the one on computer 1}.

By construction the supervisor can always announce the correct version, only checking one computer so $X = 1$, i.e. it is deterministic and not random.


Trying to understand independence

Question: Consider this probability problem: An urn with 100 marbles. 90 are white, 10 are colored. Of the colored marbles three are red and seven are blue. When drawing out a single marble,

P(Red) = .03),
P(colored marble) = .1),
P(Red|a colored marble) =  .3

Now the events, "colored marble" and "Red Marble given a colored marble" are clearly not independent, but if you multiply P(colored) and P(Red| colored marble) you get P(Red). This seems to be a broad, frequently occurring  exception to the rule that one can only multiply the probability of independent events. What am I missing?
Comment: I think you are onfusing your rules.  Independence says that $P(A\cap B)=P(A)\times P(B)$.  Here, of course, one event is contained in the other, so the intersection is just "Red", hence, $P(\text {Red}\cap \text {coloured})=P(\text {Red})=.03$.
Answer: Given arbitrary events $A,B$ the equality
$$
P(A\cap B) = P(A|B) \cdot P(B) = P(B|A) \cdot P(A)
$$
is always true, so there is nothing wrong with your example.
However, for independent events we get
$P(A|B) = P(A)$ and $P(B|A) = P(A)$ and the above formula simplifies to
$$P(A\cap B) = P(A) \cdot P(B)$$

Trying to understand independence


How to add custom GUI component to ToolBox

Question: I have downloaded objectListView but do not know how to add the component to ToolBox, and so that I could drag it to my application. Anyone know how to do that?
Answer: Simply follow these steps:

In the Toolbox, right click to select Add Tab.
Provide appropriate name to that Tab.
Right click in the new tab and select Choose Items...
Browse the DLL and all the components will be listed in the new Tab.
Answer: Just to clarify: in the Choose Items dialog, make sure you have the ".NET Framework Components" selected. For some reason I started in the "COM Components" tab myself, and while you can click the Browse button there as well, you will get a message that there are no controls in the dll.


Programmatically set active facets on non search page

Question: I'm using facet api with search api and SOLR. This all works as expected.
For non-search pages I use the views facet block and this displays the facets as required.
What I want to do though is have some of the facets pre-selected on non search pages.
For example:
I have a views page: example.com/london I would like to show facets with 'london' preselected as if I was on a search page for london.
I've tried using a contextual filter on the views facet block and it half works. It shows only the selected city BUT the facet checkbox isn't checked; and if I click any of the other facets it does not show results filtered by city...
Any suggestions how I can get this to work?
Comment: OK. I can get the behaviour I want by hacking facetapi/plugins/facetapi/adapter.inc and substituting my own parameters into setParams().

I really don't want to go down this route but can't seem to find a way to access the adapter object early enough. I did manage to set the parameters without hacking but it seemed to fire after the facets were built.
Answer: So, despite the overwhelming response ;) after about 20 hours of banging my head against the desk I have this figured. I'm not sure if it is the most efficient way to do this, but I don't think the overheads are massive.
I did end up hooking into the adapter class but I couldn't find a facetapi hook that was called at the right time. In the end, I used hook_init.
You will need to get your parameters ($SOME_ID_VARIABLE) into the code. I used the current URL via request_path() and got node IDs from this.
The important bits of the code looks something like:
function MY_MODULE_init(){
  $searcher = 'search_api@MY_INDEX';
  $adapter = facetapi_adapter_load($searcher);
  $param_arr = array();

  $param_arr['f'][] = 'field_WHATEVER_FIELD:'.$SOME_ID_VARIABLE;
  $param_arr['q'] = 'VIEWS_SEARCH_PAGE/search';
  $adapter->setParams($param_arr);
}

Oh, and you still need to use a views facet block to get the facets to show up on the non-search page. I have used some caching on this block and everything still seems to work as expected.
The info on this page got me going in the right direction.


Correct Syntax for this SQL CASE?

Question: I am new to SQL plus . Could anyone help me figure out the syntax error for my code?
CREATE OR REPLACE VIEW BR_STATUS AS
SELECT CARTS_PER_CUSTOMER.loginName,CARTS_PER_CUSTOMER.number_of_carts,
       CASE WHEN (number_of_carts < 1 ) THEN 'BR-1 Satisfied.'
           ELSE 'BR-2 violated.'
       END AS 'BR-status'
FROM CARTS_PER_CUSTOMER;

Whenever I try to run this part of the code, I get this error message

ORA-00923: FROM keyword not found where expected.

I followed several oracle documentation for CASE, but can't figure out what I am writing wrong. Any suggestions would be appreciated.
Comment: remove the comma before the from. `END AS 'BR-status',`should be  `END AS "BR-status"`
Comment: Use double quotes for that column alias,  `"BR-status"`.
Answer: There is a unnecessary comma before FROM clause nothing wrong with CASE statement. Also use double quotes for Alias name instead of single quotes (thanks to Jarlh)
SELECT CARTS_PER_CUSTOMER.loginName,
       CARTS_PER_CUSTOMER.number_of_carts,
       CASE
         WHEN ( number_of_carts < 1 ) THEN 'BR-1 Satisfied.'
         ELSE 'BR-2 violated.'
       END AS "BR-status" --Remove the comma here
FROM   CARTS_PER_CUSTOMER;

Comment: Use double quotes for that column alias, `"BR-status"` .
Comment: @shamveel_ahammed - There is a missing comma after `itemNum` in your `select` list `inventoryItem.itemNum,CASE`
Comment: Tried it without the comma `CREATE OR REPLACE VIEW BR_STATUS AS
SELECT CARTS_PER_CUSTOMER.loginName,CARTS_PER_CUSTOMER.number_of_carts,
CASE WHEN (number_of_carts < 1) THEN 'BR-1 Satisfied.'
ELSE 'BR-2 violated.'
END AS 'BR-status'
FROM CARTS_PER_CUSTOMER;` Still get the same error message.
Comment: @shamveel_ahammed - check now
Comment: @jarlh .. Thanks, it worked.. Should have used double quotes.
Comment: @prdp @jarlh Could you help me with this SQL query... I am still getting the same error message, but I think I am using the correct syntax  for CASE `SELECT inventoryItem.itemNum
CASE WHEN ( Count_same_color < 2  AND Count_same_size <2) THEN 'BR-1 Satisfied.'
ELSE 'BR-1 violated.'
END AS "BR-status"
FROM (
SELECT inventoryItem.itemNum,inventoryItem.itemSize,inventoryItem.itemColor,COUNT(inventoryItem.itemColor) AS Count_same_color,COUNT(inventoryItem.itemSize) AS Count_same_size
FROM  inventoryItem
GROUP BY inventoryItem.ItemColor,inventoryItem.ItemSize,inventoryItem.ItemNum
);`

Correct Syntax for this SQL CASE?


How to render a Drupal 7 field in stand alone PHP file?

Question: Hi this is probably a really basic question, but hopefully you guys can help me out...
I have a javascript client application (Separate to my main Drupal 7 website) and rather than maintaining a duplicate select list with a large number of values, I would like to use an AJAX call to a PHP file on the Drupal server which will render the HTML for the list I need.
The list is configured as a custom field (Text List type).
Can I create a PHP file in the root of the website, and include the required module files?
An example would be fantastic!
Thanks!
Answer: You could definitely bootstrap Drupal in a standalone file, but if you're doing it inside the same document root as the Drupal installation you'd be better off implementing a custom menu path in a module, and using the callback for that path to output the necessary value.
If you print directly from a page callback function and don't return anything, the standard theme wrappers won't be included and you'll just be left with the value you've printed.
A basic example might look like this:
function MYMODULE_menu() {
  $items['custom-path'] = array(
    'title' => 'Custom page', // Required, won't actually be displayed anywhere
    'access arguments' => array('access content'),
    // 'access callback' => TRUE, // This is an alternative to the access arguments if you don't need any access control for this path
    'page callback' => 'MYMODULE_ajax_page',
    'type' => MENU_CALLBACK
  );

  return $items;
}

function MYMODULE_ajax_page() {
  $output = function_to_produce_field_output();

  print $output;
}

After you clear Drupal's caches any request for http://mysite.com/custom-path should produce the un-themed results from your page callback; you can then use that path as your AJAX callback.
You might also want to look at drupal_add_http_header() to set an appropriate content type before you print the output.
As far as getting the field output goes, it's a bit of a pain but this should work:
$entity_type = 'user';
$bundle = 'user';
$field_name = 'field_field_name';

// Get field info for the allowed values
$field_info = field_info_field($field_name);

// Get instance info for label/required/description/default value
$field_instance = field_info_instance($entity_type, $field_name, $bundle);

// Build the select list
$select = array(
  '#type' => 'select',
  '#value' => $field_instance['default_value'],
  '#options' => $field_info['settings']['allowed_values'],
  '#required' => $field_instance['required']
);

// Build the element wrapper
$wrapper = array(
  '#title' => t($field_instance['label']),
  '#description' => t($field_instance['description']),
  '#children' => theme('select', array('element' => $select))
);

// Get the fully rendered element
$rendered = theme('form_element', array('element' => $wrapper));

print $rendered;

Comment: @Darren Thanks but don't worry about that, I'm not bothered about the reputation :) What I'm worried about is this moron giving real users of this site the impression that correct answers are actually incorrect. Glad it helped either way :)
Comment: @Clive Here, have an upvote for a good answer.  Same thing happened to me  few months back.
Comment: @Chapabu Thanks dude :) I'll come find you and buy you a pint next time I'm over in Falmer (I'm just down the road in Lewes)
Comment: Good answer, but I'm not so sure about the access_callback comment. Why would you create open doors with ajax calls? IMO they should be protected as any other resource, so probably the same as the page that normally calls the given ajax call.
Comment: @fietserwin It's pretty common practice; the core filter, image, locale, openid, system, update and user modules all use it (as well as a ton of contrib modules). But yeah, setting `access arguments` instead is just as good (maybe better), depends on your use case I guess
Comment: Thanks, @Clive, that makes total sense. And I agree this is just rendering a simple Select List with no sensitive data inside it, so security isn't an issue.
Comment: @Clive I just tried to vote-up your answer, but don't have enough reputation yet (Newb on this forum)
Comment: @Clive he..I live in Uckfield, but I tend to always head to the Dorset or Snowdrop in Lewes if I head out!  Small world.  Pint is a definite at some point though :-)
Comment: @Chapabu Nice! I stay away from the Dorset because of the scary German bar tender (she kept talking to me about falconry and horse whispering...seriously). But next time you're over gimmie a shout!
Comment: Sorry to interrupt @Clive, The bar tender in the Dorset sounds mental ;) Anyhoo, I've now got my menu working, calling a function in my custom module, but I'm still stuck on how to render the raw HTML for a field (There is no $node or $entity context so I'm not sure how I can easily render the HTML for the field).
Comment: Heh no worries, you'll have to come down for a drink :P So yeah, you'll need to get some context to that script somehow...is it being called from a node page? I'm thinking you could tack `?nid=123` on to the end of the URL then check `$_GET['nid']` in the script
Comment: Beer sounds good - but I'm up in the East midlands, so its a bit of a trek! The URL I created is being called by a totally separate web app, which needs the same select list as the one configured in Drupal against a User's Profile. However there is no specific user so I just want to render the list. Maybe I need to load a dummy user to get this working?
Comment: Ah well another time! Thinking about it, you won't need to load a dummy user as you can get what you need with the field metadata and some theme functions. I've added some code to the answer, it should do the trick
Comment: @Clive I've got some contact info on my bio - hit me with some contact details :)
Comment: and @Darren - I'm sure you could make it down South at some point ;-)
Comment: @clive thanks! That has worked perfectly. Seems a bit of an overhead to just render a field, but it will save me maintaining the list in 3 different systems!


Writing a batch file for date-based file copying

Question: I need to make a batch file that can copy files from one path to another based on parameters.
For example, typing "datecopy -m 8 c:/copyfrom/*.* d:/copyto/*.*", would find all files in c:/copyfrom dated less than 8 months old, and copy them to d:/copyto -folder. Alternately, instead of -m for month, I could use -h for hour or -y for year.
That's not the full program of course, but should get me started. Thanks for any potential tips. :)
Answer: I know this might not look like it's answering your question, but save yourself more pain and heartache than you can imagine by doing this in jscript or VbScript
Lately I've been looking at Windows Powershell, basically Windows Scripting on speed.
However you can be assured that Windows Script Host (jscript & VBScript) is already on Windows from XP onwards (possibly from W2k onwards).
My advice is to NOT use windows batch commands.
Comment: Powershell is a great way to go if you have it installed
Comment: Starting with Windows 98, even.
Comment: Tried to get it for Vista a month or two back, but there were some complications. Might try again with Win 7. Thanks for the reply btw, this is definitely an option, though I still need to find out about basic batch file scripting sooner or later as well.
Answer: Supposing you can assemble a set of good-old-unix tools, do take a look at the find utility.  It has the options you ask for, and more.
find c:/copy/from -atime 240 | xargs cp "{}" c:/copyto

Answer: Here is a script that will copy files newer than 8 months.
# Script TimedCopy.txt
var str from, to, timediff, list, file
lf -n "*" $from ($ftype=="f") AND ($fmtime > addtime(diff(("-"+$timediff)))) > $list
while ($list <> "")
do
    lex "1" $list > $file
    system copy ("\""+$file+"\"") ("\""+$to+"\"")
done

The lf (list files) command is pretty flexible. Its help page is at http://www.biterscripting.com/helppages/lf.html .
To run the script, copy and paste the script into file C:/Scripts/TimedCopy.txt, start biterscripting and run this command.
script "C:/Scripts/TimedCopy.txt" from("c:/copyfrom") to("d:/copyto") timediff("240000000")

Explanation of the timediff argument
"240000000" means 240 days, 00 hours, 00 mins, 00 secs
"120000" means 12 hours, 00 mins, 00 secs
"3000" means 30 mins, 00 secs
"30" means 30 seconds
etc.
(By dated, I assume you mean modified. If you meant created, use $fctime instead of $fmtime in the script.)
Hope this helps.


Prove that the perimeter and midline of a trapezoid circumscribed about a circle are commensurable.

Question: Trapezoid ABCD circumscribing cirlce O http://www.hicksvillepublicschools.org/cms/lib2/NY01001760/Centricity/Domain/1129/trapezoidcircle2.bmp
Definition:  Two segments are called commensurable if they have a common measure
Definition:  A common measure of two segments is a third segment
such that it is contained in each of the first two a whole number of
times with no remainder
So I have trapezoid ABCD which circumscribes circle O.  I've constructed the midline of the trapezoid, EF.  I've also constructed perpendiculars from points B and C down to segment AD.
Now, I know that EI is half of AG since it is the midline of triangle ABG.  Similar argument for FJ and HD.  And IJ is congruent to OH.
BC is congruent to IJ since BCJI is a parallelogram (easily proven)
AG + GH + HD + DC + BC + BA = perimeter
EI + IJ + JF = midline
2EI + IJ + 2JF + DC + IJ + BA = perimeter
2EI + 2IJ + 2JF + DC + BA = perimeter
2*midline + DC + BA = perimeter.
And then I get stuck.  I'm not even certain if I'm approaching this question the correct way.
Comment: In your last equation, midline should be $2\cdot$midline.
Answer: Hint: as your trapezoid is circumscribed to a circle, the distance from a vertex to the two tangency points of the sides that meet at that vertex is the same. It follows that $AB+CD=AD+CB$.
Comment: I can't believe I forgot that!!  Thank you!


How to expand path in binary PowerShell module?

Question: I'm writing a simple sample binary PowerShell module:
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace MyModule
{
    [Cmdlet(VerbsDiagnostic.Test,"SampleCmdlet")]
    [OutputType(typeof(System.String))]
    public class TestSampleCmdletCommand : PSCmdlet
    {
        [Parameter(
            Mandatory = true,
            Position = 0,
            ValueFromPipeline = true,
            ValueFromPipelineByPropertyName = true)]
        public string Path { get; set; }

        // This method gets called once for each cmdlet in the pipeline when the pipeline starts executing
        protected override void BeginProcessing()
        {
            WriteVerbose("Begin!");
        }

        // This method will be called for each input received from the pipeline to this cmdlet; if no input is received, this method is not called
        protected override void ProcessRecord()
        {
            WriteObject( Path );
            WriteObject( System.IO.Path.GetFullPath(Path) );
        }

        // This method will be called once at the end of pipeline execution; if no input is received, this method is not called
        protected override void EndProcessing()
        {
            WriteVerbose("End!");
        }
    }

}

When I import the module and run the code, GetFullPath() always returns a path relative to the user profile and not the real full path:
PS C:\Users\User\GitHub\MyModule\source\MyModule> Import-Module -Name .\bin\Debug\netstandard2.0\MyModule.dll
PS C:\Users\User\GitHub\MyModule\source\MyModule> cd \
PS C:\> Test-SampleCmdlet -Path .\Temp\
.\Temp\
C:\Users\User\Temp\
PS C:\>

How can I expand the path parameter properly?
Comment: What do you get when you display `Environment.CurrentDirectory` or `System.IO.Directory.GetCurrentDirectory()`?
Answer: .NET methods use the process-wide current directory as reflected in Environment.CurrentDirectory, which is not the same as PowerShell's runspace-specific (thread-specific) current location.[1]
You cannot directly rely on System.IO.Path.GetFullPath(), at least not without also specifying the runspace's current file-system location as the optional 2nd basePath argument - which is only available in .NET Core / PowerShell [Core] 6+.
To robustly refer to the calling runspace's current file-system location, even when a different provider's location happens to be the current one[2], you can use .CurrentProviderLocation("FileSystem").ProviderPath as follows in PowerShell [Core] 6+ / .NET Core (Path is the property representing the cmdlet's -Path parameter, i.e. the input path):
# Get the runspace's file-system location.
string currentDir = CurrentProviderLocation("FileSystem").ProviderPath;

# .NET Core ONLY: Resolve the given path to a full path as a native path.
#                 relative to the given base path.
string fullPath = System.IO.Path.GetFullPath(Path, currentDir);

In Windows PowerShell more work is needed:
# Get the runspace's file-system location as a native path.
string currentDir = CurrentProviderLocation("FileSystem").ProviderPath;

# Requires `using System.Text.RegularExpressions;`
# Strips a ".\" or "./" prefix from a relative path.
string relativePathWithoutPrefix = Regex.Replace(Path, @"^.[\\/]", "")

# Caveat: Combine() will not resolve any additional, *interior* .
#         or .. components, should they be present in relativePathWithoutPrefix.
string fullPath = System.IO.Path.Combine(currentDir, relativePathWithoutPrefix);

Both methods will pass a Path value that already is a full path through.
Note:

The resulting path is by design a native file-system path, even if the runspace's current file-system location is based on a PowerShell-only drive (created with New-PSDrive).
The approach implies that your cmdlet supports file-system paths only.

For information about how to work with PS provider locations more generally, including wildcard resolution, see this answer.

[1] This discrepancy is an unfortunate side effect of PowerShell supporting multiple runspaces (threads) inside a single process, all of which need to have their own current location - see this GitHub issue for background information.
[2] For instance, the runspace's current location may be a registry location such as HKCU:\Console.
Comment: Ah yes, for my purpose it will always be the file system, no registry or other provider so I will stick to your answer.
Comment: Thank you very much for the detailed answer. It also works even if path is an absolute path because the `Path.Combine()` function manages it. Too bad there's nothing builtin `System.Management.Automation` to manage path expansion though.
Comment: Glad to hear it, @Chris. There is [`System.Management.Automation.PSCmdlet.GetUnresolvedProviderPathFromPSPath()`](https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.pscmdlet.getresolvedproviderpathfrompspath), as demonstrated in the [linked answer](https://stackoverflow.com/a/58723810/45375), but it it invariably uses whatever provider underlies the runspace's current location, which may or may not be the file-system provider.


Recommendation for syncing data on Windows Servers securely over the internet?

Question: I have a Windows Server at a data center and an EC2 Windows Server running in the cloud.  In the *Nix world I know the answer to sync these would be rsync.  What are some good options for Windows?  Is FTP over SSL the only choice here?  What programs are good for syncing thousands of files over FTP?  Robocopy?
Answer: How about rsync?  I've used this particular Windows rsync distribution with great success.
There is a "friendly" rsync distribution for Windows, DeltaCopy, but I can't say much about it because I've never used it.
Obviously, you'll need to wrap the traffic in encryption, but either SSH or a VPN can take care of that for you.
Comment: Thanks for the tip on DeltaCopy (where I also discovered Syncrify).  The transport is a concern, as running SSH on windows is somewhat of a pain.  I've setup cygwin once before for this, but would rather just pay for a commercial product now.
Answer: For a solution you can automate yourself or run on-demand, robocopy can do mirroring similar to rsync (you'll need to have one of the directories available as a shared directory, first, though).
For a more automated solution, you might want to look into DFS Replication.  Once setup, it's fairly automatic in syncing any changes.
Comment: You'd need to add a VPN to this solution to make it anywhere close to tenable.
Comment: I'd like to avoid the hassle of a VPN connection, though it certainly seems like a doable option with EC2 now.  I thought robocopy could work over FTP, but maybe not?
Comment: Unless I am missing it, no. Sorry... http://ss64.com/nt/robocopy.html
Comment: Yeah, a VPN (or otherwise secure connection) is absolutely needed.  Sorry, I'd meant to include that, but forgot.
Answer: rsync or any of its front-end that suits your needs is good,
as for the encryption you can use putty to create an ssh tunnel between the two hosts
Comment: This is what @Evan suggested above.
Answer: FTP 7.5 comes as a separate download. Install FTP 7.5 on your Windows Server 2008 instance. Use this tutorial to setup your FTP over SSL


limit amount of upload images (through imagefield module) to only 1 by code/programmatically

Question: I use image field with possibility to upload unlimited images. BUT under the user registration, I want to limit the possibility to just one image. So that the anonymous user, who wants to become a registered user, can only upload one image. After they become users, then they can upload as many images as they wish.
Does anybody know how to do that?
Answer: You want to use a hook_form_alter to process this for just that form, ex.
function mymodule_form_alter(&$form, $form_state, $form_id) {

    if ($form_id == 'user_register') {
        // do stuff here
    }

}

The 'stuff' is the real challenge, especially since you are allowing for unlimited uploads. There is a previous post on this with a solution for a limited set (<10):
https://stackoverflow.com/questions/5701488/change-fields-number-of-values-per-role
My suggestion for resolving this (though not ideal) would be to add a custom handler as part of your logic that would check to see if one already exists and gently prod them not to add more than one.
if ($form_id == 'user_register') {

    $form['<image field name>']['#element_validate'] => array('_mymodule_only_one_image'),

}

and then for your validation function, you could simply test whether a 2nd image exists and prod the user to only submit one. Rough psuedo-code example here, haven't tied this to an actual form.
function _mymodule_only_one_image($element, &$form_state) {

    if (!empty($element['<image_field_name>'][1])) {
        form_error($element, t('Please only upload one image');
    }

}

Another option would be to try and disable the ajax handler that initiates the 2nd upload through your own custom jquery override, which you could also add in to this custom form through the above form_alter.
Comment: Thankyou very much for a great answer!!
I haven't thought about the element_validate possibility.
I will try it out, and thanks once again.


How to programmatically send an email?

Question: I'd like to use Drupal's email system to programmatically send an email from my custom module. Is that possible?
Comment: this question is linked to: https://drupal.stackexchange.com/questions/84268/use-hook-cron-to-send-daily-mail-but-i-get-45-the-same-mail-every-day
Answer: Using hook_mail and drupal_mail you can create and send an e-mail.
Implement an e-mail use hook_mail:
function MODULENAME_mail ($key, &$message, $params) {
  switch ($key) {
    case 'mymail':
      // Set headers etc
      $message['to'] = 'firstname.lastname@example.com';
      $message['subject'] = t('Hello');
      $message['body'][] = t('Hello @username,', array('@username' => $params['username']));
      $message['body'][] = t('The main part of the message.');
      break;
  }
}

To send a mail use drupal_mail:
drupal_mail($module, $key, $to, $language, $params = array('username' => 'John Potato'), $from = NULL, $send = TRUE)

Obviously replace the parameters: $key should equal 'mymail'
An e-mail is sent in a few steps:

drupal_mail is called
Drupal builds the e-mail
hook_mail is called for the specifics (implementation)
hook_mail_alter is called so other modules can modify it
drupal_send_mail is called
Comment: In this example `$message['to']` is hard coded to `email@example.com`. Omit this and the message will be sent to the recipient that is specified when `drupal_mail()` is called.
Comment: He's right, but to clarify a bit hook_mail provides you with a way to structure and theme an email based on an arbitrary key that you define. drupal_mail() is what you call to send an email. Pass the key for the structure you'd like to use. (and the module that responds to that key)
Comment: This solution is deprecated.
Answer: If you'd like a simpler way of sending emails, check out Simple Mail; it's a module I'm working on to make sending emails with Drupal 7+ much easier, and it doesn't require any extra hook implementations or MailSystem knowledge. Sending an email is as simple as:
simple_mail_send($from, $to, $subject, $message);

Comment: ...and it works with Drupal 8, too, with the exact same API :)
Answer: You can use a simpler way of sending emails, check out mailsystem ; it's a module.
<?php
$my_module = 'foo';
$from = variable_get('system_mail', 'firstname.lastname@example.com');
$message = array(
  'id' => $my_module,
  'from' => $from,
  'to' => 'email@example.com',
  'subject' => 'test',
  'body' => 'test',
  'headers' => array(
    'From' => $from,
    'Sender' => $from,
    'Return-Path' => $from,
  ),
);

$system = drupal_mail_system($my_module, $my_mail_token);
if ($system->mail($message)) {
  // Success.
}
else {
  // Failure.
}
?>

Comment: Works perfectly.
Answer: You can use this code in a hook of your own choice within your custom module:
 function yourmodulename_mail($from = 'default_from', $to, $subject, $message) {
            $my_module = 'yourmodulename';
            $my_mail_token = microtime();
            if ($from == 'default_from') {
                // Change this to your own default 'from' email address.
                $from = variable_get('system_mail', 'firstname.lastname@example.com');
            }
            $message = array(
                'id' => $my_module . '_' . $my_mail_token,
                'to' => $to,
                'subject' => $subject,
                'body' => array($message),
                'headers' => array(
                    'From' => $from,
                    'Sender' => $from,
                    'Return-Path' => $from,
                ),
            );
            $system = drupal_mail_system($my_module, $my_mail_token);
            $message = $system->format($message);
            if ($system->mail($message)) {
                return TRUE;
            } else {
                return FALSE;
            }
        }

Then you can use the above function like this:
        $user = user_load($userid); // load a user using its uid
        $usermail = (string) $user->mail; // load user email to send a mail to it OR you can specify an email here to which the email will be sent
        customdraw_mail('default_from', $usermail, 'You Have Won a Draw -- this is the subject',  'Congrats! You have won a draw --this is the body');

How to programmatically send an email?


Does "size matter" in tennis?

Question: Martina Navrátilová is considered to be one of the greatest, if not the greatest woman's player of all time. At 5' 8" in height, she is above average (for a woman) in this regard. But one opponent who has given her a lot of trouble over the years (when not her doubles partner) is Pam Shriver, who is much taller, at 6'0". Perhaps Shriver has advantages such as arm reach or power that Navrátilová lacks, partly compensating for Navrátilová's greater raw talent.
Another small, scrappy men's player is Michael Chang, who was the youngest man to win the French open. Great things were predicted of him, but he lost other Grand Slam finals to men like Boris Becker, Patrick Rafter and Thomas Muster who are much taller than Chang's 5'8".
Are the setbacks of Chang (and to a lesser extent Navrátilová) attributable to "size" (or lack thereof), or to other non-size factors such as skill, stamina, strategy, etc.? Did anyone "smaller" than Pam Shriver do better against Navrátilová in match play? Was Chang ever beaten by anyone close to his size (5'9" or shorter), or were all his defeats to much bigger men?
Answer: I think you could make the argument that "size matters" in every sport - look at jockeys in horse racing, for example.
If I had to describe the ideal "size" for tennis players, I would say it is between about 6'1" and 6'4" and about 175-190 pounds. Tennis players need to be strong, but not bulky or too muscular to the point where it inhibits flexibility and speedy movement around the court.
The advantages that more height provides in tennis is on the serve - you can get better angles out wide and get more pace on the serve. Also at the net - you have greater reach. The drawbacks to being taller is that it tends to be harder for the really tall guys (Karlovic, Isner, etc.) to get to low balls and they tend not to have the fastest legs/feet so - their movement suffers a little.
Size (or the lack of) isn't always the reason for setbacks in tennis though. I'd hardly call Navrotilova's career one that had many setbacks - I think she was an overachiever, in fact. And for being a smaller guy - Chang made it to #2 in the world, won a major, and was on a winning Davis Cup team. A lot of players would like to have those achievements.
Comment: In other words, the size of one's heart matters? :)
Comment: The site, askjamauss.com/tennis should probably exist - your answers are so great.
Comment: @edmastermind29 Basically. Which isn't specific to tennis at all, right?
Comment: @NicholasV. Thanks man - just trying to share what I know with these people asking questions around here.

Does "size matter" in tennis?


Execute a Javascript function immediately after Google Analytics creates/updates all its cookies

Question: How do we make a web page to execute a JavaScript function immediately after Google Analytics creates/updates all its cookies and the page DOM is loaded.
Can it be done with jQuery? How?
This function gets information from the GA cookies. I've tried executing the function when the page DOM is loaded, but sometimes GA has not created it's cookies yet.
Answer: There are 2 elements here: First, DOM ready with jQuery. That's easy:
$(document).ready(function(){
//do something
});

The way to ensure that your function executes after Google Analytics has created its cookies (once it had implicitly executed initData()) is to pass the function within the _gaq array queue so that it gets executed after the _trackPageview call.
For example:
_gaq.push(["_trackPageview"]);
_gaq.push(function(){
    //when this executes, the google analytics cookies definitely exist
});

So, you could put the following anywhere on the page below _gaq.push(["_trackPageview"]) (or after any _gaq call that initiates the cookies; most commonly, _trackPageview, _trackEvent, and _setCustomVar.
_gaq.push(function(){
    //do something
});

Now to ensure that the function both executes after DOM Ready and that initData() is implicitly called, you can either do this:
_gaq.push(function(){
    $(document).ready(function(){
        //do something
    });
});

Or:
$(document).ready(function(){
    _gaq.push(function(){
        //do something
   });
});

They both do what you're looking for, though it sounds like the first one better fits your mental model of what you're trying to accomplish.
Answer: To complete/update @Yahel's answer, concerning the syntax, you should now write:
ga(function(tracker) {
  console.log(tracker.get('clientId'));
});

Source: developers.google.com
Comment: This is the optimal answer


ListView item does not invoke onItemClick

Question: I have ListView used custom Adapter. ListView item contains TextView and ImageView.
When i set up setOnclickListener on ImageView, ListView no longer invoke onItemClick for specified listener. It is ok. But if i set up OnClickListener of ImageView as null, ListView still does not invoke onItemClick. Do you have any idea? Thanks a lot.
Comment: Could you try 'setFocusable(false)' on the 'ImageView'? If a 'ListView' row has focusable childs, it has troubles gaining focus or invoking click events
Comment: Yes I tried do this, did not help.
Comment: I think that ImageView fill to rowView, therefore onItemClick didn't work
Answer: If you implement onClickListener for List Itemm child then List onItemClick no longer invoked So which ClickListener have to implement its depended on requirement Like :

When provide different action on List Item each child then implement each child onClickListener in Adapter
When provide single action on List Item use List onItemClick.
Comment: I have next situation. Depending on flag (bool variable, for clearly), one way I need to have two different actions one for item (not including ImageView) and one for ImageView. another way I need to have only one action for whole item in list..
Answer: Try to add this code in your  TextView and ImageView :
android:focusableInTouchMode="false"
android:focusable="false"

To make sure the items dont gain focus so the ListView should be clickable.
Comment: focusableInTouchMode and focusable uses for another purpose. It is only focus, nothing else. If i need view to get focus, and if i need view to get focus by user touch. As I think.
Comment: @busylee from my experience, wrong focus on an item in your row make the entire row cant be clicked


bluetoothAdapter.startDiscovery() doesn't start without clicking the bluetooth button from the notification panel and finishes immediately

Question: In android 12 api 31
I run this app ,it doesn't work properly
I want to find the name of the nearby devices but the Bluetooth device doesn't start until I click on  the Bluetooth button from the notification panel and in log it shows Discovery Started and Gave another Log which shows Discovery Finished without searching a device.
package com.aditya.bluetoothfinder;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
ListView listView;
TextView statusTextView;
Button searchButton;
BluetoothAdapter bluetoothAdapter;//The BluetoothAdapter is required for any and all Bluetooth activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = findViewById(R.id.listView);
    statusTextView = findViewById(R.id.statusTextView);
    searchButton = findViewById(R.id.searchButton);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}

public void searchClicked(View view) {
    if (bluetoothSupported()) {
        openBluetooth();
    } else {
        statusTextView.setText("Bluetooth Not Supported");
    }
}

//This function will check that the bluetooth is supported on the device or not
public boolean bluetoothSupported() {
    return getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
}

//This function opens the bluetooth
public void openBluetooth() {
    if (!bluetoothAdapter.isEnabled()) {
        Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            requestThePermissons();
        } else {
            startActivityForResult(enableBluetoothIntent, 1);
        }
    } else {
        searchBluetoothDevices();
    }
}

//This function request the permission
private void requestThePermissons() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { //if we don't have any permission
        requestPermissionLauncher.launch(Manifest.permission.BLUETOOTH_CONNECT);
    } else { //if we already have permissionn of bluetooth connect
        searchBluetoothDevices();

    }
}

//This is a callback which give us the information that the user gave us the permission or not
private final ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
    if (isGranted) {
        // Permission is granted. Continue the action or workflow in your
        searchBluetoothDevices();
    } else { //If user declined the permission request
        Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
    }
});

//This is the function for searching bluetooth devices
public void searchBluetoothDevices() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "Unable to locate bluetooth device", Toast.LENGTH_SHORT).show();
        requestPermissions(new String[]{Manifest.permission.BLUETOOTH_SCAN},1);
    } else {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Unable to locate", Toast.LENGTH_SHORT).show();
        }
bluetoothAdapter.startDiscovery();
        statusTextView.setText("Searching...");
        searchButton.setEnabled(false);
    }
}

When I call the bluetoothAdapter.startDiscovery();
It shows
D/BluetoothAdapter: startDiscovery(): called by: com.aditya.bluetoothfinder
but doesn't show the log Discovery started until I click on the Bluetooth button from the notification panel and after that it gives another Log Discovery Finished
//This function give us the details of the bluetooth device if found
BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            Log.i("this", "Device Found");
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                requestThePermissons();
                Toast.makeText(MainActivity.this, "Unable to find", Toast.LENGTH_SHORT).show();
            } else {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
                String text = (String) statusTextView.getText();
                statusTextView.setText(text + "\n" +deviceName + "\n" + deviceHardwareAddress);

            }
        } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            Log.i("this", "Discovery Finished");

            statusTextView.setText("Finished");
            searchButton.setEnabled(true);
        } else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            Log.i("this", "Discovery started");
            Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
        }
    }
};
}

Permission used in AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-feature android:name="android.hardware.bluetooth" android:required="true"/>

Answer: You also have to take location permission from the user and the user has to turn on location services in order to see other Bluetooth devices.
Comment: If this is the answer to your problem, you should mark it as such (maybe even with some examples?) so others can easily see your question was answered.
Comment: add permission

 and take permission from the user then the Bluetooth works fine
Comment: Don't add your answer in the comments. Add it as an edit to your answer and click the checkmark.


where does the VxWorks console store data

Question: i was using the console for resolving a "errno" like this:
-> strerror(0x23)
value = 22279888 = 0x153f6d0
-> d 0x153f6d0
NOTE: memory values are displayed in hexadecimal.
0x0153f6d0:  5f53 7265 6e72 5f6f 4e45 544f 5553 0050  *S_errno_ENOTSUP.*
0x0153f6e0:  0000 0000 0000 0000 0000 0000 0000 0000  *................*
...
0x0153f7c0:  0000 0000 0000 0000 0000 0000 0000 0000  *................*
value = 0 = 0x0

Also, if i create a new variable:
-> a=6
New symbol "a" added to kernel symbol table.
a = 0x45446f60: value = 6 = 0x6

Now it is stored and available.
But now i am wondering where are those bytes saved?
Does the console make a mem allocation in the background or has it already allocated some RAM for those purposes?
Should i be concerned where this is going to be saved?
I guess those data is stored until reboot and eating up mem as long as i am working with the console.
I took a look into "Kernel Shell User's Guide" but couln't find an answer.
(VxWorks 7.0)
Comment: After reading the Guide again, i guess it is defined with "SHELL_STACK_SIZE".
Comment: I don't think it would be saved into the stack, as it is quite likely to overflow if shell is used for a long time. Shell stack should be used instead when the user makes a function call from the stack. I don't have access to any material right now, but I remember the kernel API having functions like "releaseShellStrings" and something similar for the variables. If memory is tight for you, I suggest you look into those functions.
Answer: strerror returns pointer to error text by error number. Error text isn't some dynamic string, it's predefined constant known before compilation starts, so it must be stored in .data segment along with all other constants, next to all other initialized data. Whenever you call strerror with the same param, you get the same address of the same memory area, feel free to try.
Creating new variable is a different thing, it actually allocates memory from the heap the same way malloc/new does. If you call malloc for small amount of data (e.g. 16 bytes) right after creating new variable, you might get pointer really close to the address of new variable. And even more, you can call free &a from console to correctly release memory back, no error should appear.
You can actually study memory map if you want to

Start and size of stack/heap should be determined somewhere within your project configuration
You can ask linker to generate .map file like this and check segments addresses in it.

So either way you'll be able to guess memory section by pointer value
Note, I worked with older versions of VxWorks only (5.5 which has ), so this might not be inaccurate, but the main idea should be OK.


Como ler dois vetores e colocar os valores em um terceiro vetor e em ordem crescente?

Question: o enunciado do problema é o seguinte: Faça um programa que leia um valor inteiro N. Após isso, leia N valores inteiros colocando-os em um vetor A de tamanho N. Em seguida, leia um valor inteiro M. Então, leia M valores inteiros colocando-os em um vetor B de tamanho M. Assuma que A e B sempre estarão ordenados de forma crescente.
O programa deve juntar os valores de A e B em um vetor C, de forma que C também esteja ordenado. Ao final, escreva o vetor C resultante. Não é permitido utilizar algoritmo de ordenação.
eu fiz o seguinte código:
<code>#include<stdio.h>
#include<stdlib.h>

int main(){
  int N;
  scanf("%d", &N);

  int vetorA[N];
  for(int i = 0; i < N; i++){
    scanf("%d", &vetorA[i]);
  }

  int M;
  scanf("%d", &M);

  int vetorB[M];
  for(int j = 0; j < M; j++){
    scanf("%d", &vetorB[j]);
  }

  int *vetorC;
  int j = 0;
  int k = 0;

  vetorC = (int *)(malloc(100 * sizeof(int)));

  if(vetorC == NULL){
    printf("\n erro ao alocar memoria");
    system("pause");
    exit(1);
  }

  for(int i = 0; i < (M + N); i++){
    if (vetorA[j] < vetorB[k]) {
      vetorC[i] = vetorA[j];
      j++;
    }
    else if(vetorB[k] < vetorA[j]){
      vetorC[i] = vetorB[k];
      k++;
    }

    else{
      vetorC[i] = vetorA[j];
      j++;
    }
  }
  for(int i = 0; i < (M + N); i++){
    printf("%d ", vetorC[i]);
  }

  free(vetorC);

}
</code>
mas o programa sempre printa errado no final.
um exemplo de input:
4
1 2 7 8
3
3 4 7
a saída deveria ser:
1 2 3 4 7 7 8
mas minha saída é:
1 2 3 4 7 7 0
Answer: O erro é que, quando j atinge o valor "M", todos os valores de vetorA já foram utilizados, então vetorA[j] está apontando para um valor aleatório, fora do limite da matriz.
O programa poderia quebrar, mas para seu azar não quebrou, e ainda pegou um valor aleatório igual  a um digitado, o que faz parecer que o problema é outro.
A parte relevante ficaria assim, salvo melhor juízo:
<code>if (j >= N) {
  // vetorA esgotado
  vetorC[i] = vetorB[k];
  k++;
} else if (k >= M) {
  // vetorB esgotado
  vetorC[i] = vetorA[j];
  j++;
} else if (vetorA[j] <= vetorB[k]) {
  vetorC[i] = vetorA[j];
  j++;
} else if (vetorB[k] < vetorA[j]){
  vetorC[i] = vetorB[k];
  k++;
}
</code>
Note ainda que simplifiquei o caso de vetorA[j]  igual a vetorB[j].


Alteração nome de um campo do conjunto de dados - PowerBI

Question: Olá tenho um conjunto de dados (Excel) que foi carregado no PowerBI. Quando altero o nome de uma coluna/campo no Excel o PowerBI não atualza os dados porque não reconhece o nome da coluna que foi renomeada no Excel. Como posso fazer com que o PowerBI entenda que a coluna/campo ainda é o mesmo mas que apenas teve o nome do campo alterado?
Answer: Os passo são os seguintes:
Vai em Editar Consulta:

Seleciona a tabela que está apresentando o erro ( No meu caso com o nome 'Plan 1' ) clica com o botão direito sobre ela e então selecione Editor Avançado:

Na janela que abrir você vai ter de alterar o nome da coluna antigo para o novo manualmente. No meu exemplo eu possuía anteriormente uma coluna com o nome 'COLUNA3' e quis alterar seu nome para 'COLUNAC'. Veja o exemplo:
1 - Antes da alteração no Nome da coluna.

2 - Resultado depois de alterar.

Feito isso, basta atualizar a tabela e utilizar normalmente.


Why the difference between interval ratios and the harmonic series?

Question: I've observed that the harmonic series which are the most consonant pitches of the fundamental such as the note A for this example, with A's first harmonic series being (A) E and C#.. Do not correlate with the consonance to dissonance ratios. In the ratios it would be A,E and D..

Harmonic Series - A (root) E (fifth) C# (Third)
Interval Ratios - A (root) E (fifth) D (Fourth)

It is also worth mentioning that the following harmonic after the third (C#) is a 7th (G).. While in interval ratios the order would be Unison, Octave, Fifth, Fourth and a Major Sixth.
What is going on here?
Also, could you folks confirm the validity of this interval ranking shown in the image below? Image Source: https://www.pnas.org/content/112/36/11155

Thank you.
Comment: BTW I think it would really be worth reading and fully understanding that paper I linked to - at least I think it would be good for me, and probably good for you too!
Comment: Look into David Cope's concept of "interval strength", which is similar to what you're trying to do here. (My answer would be that harmony is only loosely related to harmonics, as exemplified by the eleventh harmonic, which is right in-between two notes.)
Comment: Where are you getting your information about what are "the most consonant pitches of the fundamental"? Are you saying that because they're the earliest harmonics?
Comment: What do you mean "confirm the validity of this interval ranking"? They asked a bunch of random people, and took the average ranking. That means it's valid for the average person from that group. There's a chance that the average person in another group will agree, unless the group is non-random, like only trained musicians or fans of a particular genre. But mr. Blue Dot likes minor sevenths as much as major thirds, while mr. Cross put major thirds first and minor sevenths in 10th place; those two will never agree, and I don't know how you're going to make music that appeals to both of them.
Comment: I don't think you can really have universally accepted rules when human perception and preference comes into play, anymore than you can determine the world's favourite colour.
Comment: Btw, this old question just popped up in the active questions list, and may interest you: https://music.stackexchange.com/questions/30531/what-are-the-characteristic-intervals-or-scales-of-13-limit-harmony-and-beyond
Comment: @topo morto yes, I'm getting it from the harmonic series of a fundamental pitch although the order of consonance for ratios differ quite a bit. Why process (harmonic or ratios) provide the actual harmonic consonance order?
Comment: @YourUncleBob I'm asking about validity because i see different sources with the same intervals hold different ratios but maybe your conclusion of the source of their information is why. I really don't understand how if consonance is dictated by two waves constructive interference, this whole consonance dissonance stuff can be so vague and not at all precise. I've been weeks trying to find the universally accepted levels of consonance for intervals within an octave and i'm still at it..
Comment: @YourUncleBob thank you Bob, ill check it out now.
Answer: It's because the fourth is the inversion of the fifth.  E is the third harmonic of A, and C# is the fifth harmonic of A, but A is the third harmonic of D.
So the ratio of the ascending fifth (the interval, that is, in this example A to E) is 3:2.  The ascending major third (for example A to C#) is a ratio of 5:4, and the ratio of the ascending fourth (A to D) is 4:3.  Notice that the odd factor is in the denominator here, because A is an overtone of D rather than D being an overtone of A.
Comment: @ScottWallace it's more common to express the ratios for ascending intervals rather than descending, but, regardless, the powers of two in the numerator or denominator can also be seen simply as adjusting by octaves. Whether the major third is the distance between the fourth and fifth harmonics or the distance between the fundamental and the fifth harmonic, adjusted by two octaves, is not particularly significant, is it? I rather think the whole idea that the scale is "derived from" the harmonic series is seriously overrated. We don't use intervals based on the 7th or 11th harmonic.
Comment: @Seery if the two tones are sounding at the same time there is no ascending or descending.  Your question is analogous to comparing which relationship is closer, that between a parent and child or that between a child and parent.
Comment: Yep.  Another way of looking at it is that the series of most consonant intervals (in the classical music sense) is obtained (with the usual temperament factors) from the harmonic series, but not from 1/1, 1/2, 1/3, 1/4, 1/5, etc, but rather 1/2, 2/3, 3/4, 4/5, and so forth.
Comment: @Seery they are each other's reciprocals.  For example, an ascending major third is 5:4 while a descending major third is 4:5.  Inversions of chords may be more dissonant to the extent that the fourth is sometimes regarded as dissonant, that is, for reasons of melody or voice leading, but otherwise, that is acoustically, inversions are more or less equally consonant and dissonant.  That is, the second and seventh are dissonant, while the third and the sixth are consonant.
Comment: @Seery It depends on the context and on the listener. If a piece in G major or G minor ends with an open fifth (G-D-G), that doesn't sound more dissonant to me than a major or minor triad. Does it sound more dissonant to you? Or are you talking about a chord like G-C-D? That is more dissonant because you have to look at all the intervals, not just relative to the root. G-C-D has a perfect fourth, a major second, and a perfect fifth. G-B-D has a major third, a minor third, and a perfect fifth. The major second in G-C-D is more dissonant than any of the intervals in G-B-D.
Comment: @phoog in what way do ratios for ascending intervals differ from ratios of descending intervals? Also, when creating inversions of chords, does the level of consonance/dissonance of a chord shift and if so how does this process work? Thank you!
Comment: @phoog i'll ask you also, if we say that the most consonant intervals are P1,P8,P5,P4.. How is it that a chord with P1,P5 and P4 sounds more dissonant compared to a chord of P1,P5 and M3 (C Major Triad)?
Comment: @phoog in regards to this quote "an ascending major third is 5:4 while a descending major third is 4:5." would that imply that the descending major third is more consonant than the ascending based off its lower ratio?
Comment: @phoog "If a piece in G major or G minor ends with an open fifth (G-D-G), that doesn't sound more dissonant to me than a major or minor triad. Does it sound more dissonant to you?" No it doesn't it sound more dissonant to me, i would agree with you.
Comment: @phoog excuse my novice-ness. I'm assuming that the ratios presented in the graph i posted are applicable to our standard equal temperament tuning, yes?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/96270/discussion-between-phoog-and-seery).
Answer: The harmonic series is not in strict order of pitch consonance with the fundamental. This can be seen from the fact that there are harmonics that are two, three, four.... octaves above the fundamental, all of which would themselves be very consonant with the fundamental, and yet have harmonics either side of them representing pitches that are less consonant.
Consonance and dissonance are subjective sensations which aren't necessarily even particularly well-defined. Plomp and Levelt's 1965 paper discusses some of the difficulties in pinning down what consonance really is, and discusses how their curve of interval consonance was calculated. I thought it was obtained directly from experiments on people, but on reading the paper, that isn't the case - it's derived from experiments using simple tones (sine waves).
Comment: @Seery I'm a bit confused as to what you mean - I can't see *anything* in image A in your post that says anything about consonance degrees. I think image A just tells you what's on the X axis on image B.
Comment: @Seery as to your point about imperfection - a lot of that is because it involves human beings with all their vagaries! (and I don't think music is alone in this) -  The graph you've posted, which represents actual listener assessments, is what I *thought* the Plomp curve represented - in fact his curve for musical tones was calculated from his curve for simple tones.
Comment: @Seery it's like we said in another question - you can't just look at the interval from the root to every other note - you have to look at the intervals between every note and every other note. The minor third between M3 and P5 is more consistent than the second between P4 and P5
Comment: i read a portion of the paper and found it to confirm concepts i've come across thus far. I've added an image in my post of a cons/disso curve i have found.. Could you confirm its validity? I apologise if i seem to be going in circles here. Also i came across compound intervals regarding 9ths,10ths,11ths,12ths,13th,14th and 15ths being extensions of 2nd,3rd,4ths,5ths and so on.. If for example a 2nd is dissonant and a 5th is consonant, how does that measurement of conso/disso correlate with the 2nd and 5ths compound intervals 9th and 12th? Thank you sir!
Comment: @Seery this is a topic that interests me too! I think I'd need to do my own revision on the derivation of that dissonance curve to really be able to make a stronger statement on the extent of its validity... I will aim to do so at some point!
Comment: Thank you! I also see that the consonance degrees differ from image A to image B once you reach Minor 6th on image B and compare it to the degree order of image A.. Why is this? I've been over a month possibly just on trying to validate this topic and its unbelievably vague in certain areas of the topic. Who would have thought that sonics that sound so perfect in its song format, can be so imperfect in its mechanics! Possibly one of the few arts thats perceived perfection doesn't match its actual mechanics.
Comment: Cheers for validating. Music is not alone in this although its imperfection may be uncommon in other arts. I will be studying mixed martial arts (another passion of mine) after this project is complete and i can move on and i have reasons to believe mma will hold perfect mechanics as it's basically the anatomy of the human body in its movement limits which are the basis of jiu jitsu and movements generating maximum force such as in striking. Thank you again topo!
Comment: @Seery the mechanics might be perfect, but I suspect there's a lot of psychology involved in actually winning a fight! BTW you remind me of these guys: https://www.bbc.co.uk/news/uk-scotland-glasgow-west-48879158 ; https://hcmf.co.uk/laura-jayne-bowler-pieces-never-just-piece-music/
Comment: Absolutely psychology is also an element. The link won't load and a google search didn't bring up the article! Also a question, if we say that the most consonant intervals are P1,P8,P5,P4.. How is it that a chord with P1,P5 and P4 sounds more dissonant compared to a chord of P1,P5 and M3 (C Major Triad)?


Create SSH user with limited privileges to only use Git repository

Question: I have a git repository hosted on my SunOS server, that I remotely use through ssh
git clone ssh://firstname.lastname@example.com/path/to/git

Now I need to add more users to be able to access that repository, but not sure how.
I have added one testUser to ssh, but I can't seem to limit that user privileges to only use git.
testUser is able to ssh through and browse the entire server.
How can I create users that can only access git remotely, to clone/pull/push etc...
thanks
Answer: You basically have two options.

As topdog mentioned, when you create users on the server, set their shell to git-shell (book entry here).  This will allow the user to login in via SSH, but instead of running a normal, fully-featured shell (e.g. sh,bash,etc.) it will run, git-shell, which only provides access to git functionality.
Alternatively, you can make your repositories available via another protocol, such as TCP (using git-deamon) or HTTP/HTTPS.  I'd only recommend such a scenario for read-only access though.

You mention wanting to support 'push' functionality for your users, so you should really go with option #1.
Comment: note: you can change the shell of that user with `usermod -s /usr/bin/git-shell username`
Answer: You might consider using gitolite under a single user instead of setting up multiple git-shell users (and the required group and group permissions so they can share access to the repositories).
gitolite runs under a single, normal user on the server and uses
SSH public keys to differentiate access to Git repositories (see "how gitolite uses ssh" for some of the details of how gitolite does its SSH-based identification).
gitolite offers per-repository, per-branch, and even some per-path access control.
Comment: +1 for gitosis... It was made exactly for this setup.
Answer: you need to change their shell to git-shell, that will only give them access to git functions only.
Comment: thanks for the book reference! very helpful. Ended up using gitolite, still having issues with the setup though.
Comment: Thanks topdog. Basically the user will be using his own git shell on his Mac. I don't really want him to be able to ssh to the server.
So if the git repo is on mydomain.com

from testUser computer/Mac, in the terminal he could just

git clone ssh://firstname.lastname@example.com/path/to/git

be prompted for his password, then download the repo.
I just tried now setting his shell to git-shell. It prompts when calling clone but the password is being rejected.
Comment: you need to set myUsers shell to git-shell if all you want them to do on the server is run git commands and not be able to shell in. for the password prompts please use keys. For more detailed coverage of git on a server look at the free git book http://progit.org/book/ch4-0.html
Comment: _git-shell_: "This is a login shell for SSH accounts to provide restricted Git access. It permits execution only of server-side Git commands implementing the pull/push functionality, plus custom commands present in a subdirectory named git-shell-commands in the user's home directory." On Linux, add "/bin/git-shell" to "/etc/shells" and then "usermod --shell /bin/git-shell $USER". Btw, the git book is now at http://git-scm.com/book/en/ch4-0.html
Answer: Another way to do it is by limit access of the users within ssh.
(http://prefetch.net/blog/index.php/2006/09/05/limiting-access-to-openssh-directives/)
The example is just by using only one user, but if the users are on the same group you can filter them out by using group directive. Something like
AllowTcpForwarding yes
X11Forwarding yes

Match Group Users
         AllowTcpForwarding no
         X11Forwarding no
         $Here is a directive for git$

Comment: What do you mean with `$Here is a directive for git$`?


How to decode char from wchar_t

Question: I have an encoded wstring. because wchar_t is 16bit wide we have encoded 2 chars to it.
wstring e_str = L"A B C \uffff";
....
wstring temp;
....
wchar_t value = e_str[i]; /* e_str = encoded wstring */
....
if (value > L'\u00ff) {
    temp.append(1,(character-(character % 256))/256);
    temp.append(1,character % 256);
}

after encoding it becomes "A B C \uÿÿ".
What i want to do is get the original string back (e_str).
Comment: I think you need to learn more about encodings in general before attempting this. Different characters have different representations in different encodings. It's not usually as straightforward as you believe it to be.
Comment: you mean "2 chars back"?
Comment: When does it "become 'A B C \uÿÿ"? When you printf() it? What is the corresponding code?
Comment: e_str is 7 charactes long. You can't expect to get the original string back if you use append 2 times for the last characters. each append call will add a new wchar_t to temp. Explain what you are trying to do, please
Comment: The modulus operation in `(character-(character % 256))/256)` does nothing useful. Can you explain what you hoped to achieve with that line?
Comment: "What i want to do is get the original string back" -- that is impossible. The original string contains a wchar value that cannot be represented in a char.
Answer: Try:
char loChar=(char)(value);
char hiChar=(char)(value>>8);

How to decode char from wchar_t