text:
Q: Processing an array of objects according to element nesting via Vanilla JS / JQuery I have an array of objects that I have to process and then include data from it to HTML. The problem is that now everything is displayed one by one and if I try to toggle class to li element, it toggles to all li elements. The data can be changed dynamically so I cannot access elements by ID.
I want to access the "main" category first (desserts, water, tea), then be able to proceed to subcategory of the selected main category etc. Further I will create a menu like in the screenshot (a one menu, a pic shows different states of it)
I have 2 problems now:

*

*For some reason the main category isn't showing at all - why is it happening?

*How can I access the elements according to hierarchy and nesting?

const menu = [
  {
    id: 1,
    name: "Desserts",
    groups: [
      {
        id: 2,
        name: "Cold",
        groups: [
          {
            id: 3,
            name: "Ice Cream",
            groups: []
          },
          {
            id: 4,
            name: "Cold brew coffee",
            groups: []
          }
        ]
      },
      {
        id: 5,
        name: "Hot",
        groups: [
          {
            id: 6,
            name: "Pancakes",
            groups: []
          },
          {
            id: 7,
            name: "Apple pie",
            groups: []
          }
        ]
      }
    ]
  },
  {
    id: 8,
    name: "Water",
    groups: []
  },
  {
    id: 7,
    name: "Tea",
    groups: [
      {
        id: 8,
        name: "Green tea",
        groups: [
          {
            id: 9,
            name: "With Jasmine",
            groups: []
          },
          {
            id: 10,
            name: "Plain",
            groups: []
          }
        ]
      },
      {
        id: 11,
        name: "Black Tea",
        groups: []
      }
    ]
  }
];

let menuEl = document.querySelector(".funding__categories");

addElements(menuEl, menu[0].groups);

function addElements(parent, arr) {
  let allCategories = parent.appendChild(document.createElement("ul"));
  allCategories.classList.add("parent");
  arr.forEach((el) => {
    let subCategory = allCategories.appendChild(document.createElement("li"));
    subCategory.dataset.id = el.id;
    subCategory.textContent = el.name;
    if (el.groups.length > 0) addElements(subCategory, el.groups);
  });
}

A: The first problem is because you're passing menu[0].groups to the function. That skips over the top-level categories and starts at the items nested under Desserts. Pass menu as the argument.
I don't understand the second question. Access them in what way?

const menu = [
  {
    id: 1,
    name: "Desserts",
    groups: [
      {
        id: 2,
        name: "Cold",
        groups: [
          {
            id: 3,
            name: "Ice Cream",
            groups: []
          },
          {
            id: 4,
            name: "Cold brew coffee",
            groups: []
          }
        ]
      },
      {
        id: 5,
        name: "Hot",
        groups: [
          {
            id: 6,
            name: "Pancakes",
            groups: []
          },
          {
            id: 7,
            name: "Apple pie",
            groups: []
          }
        ]
      }
    ]
  },
  {
    id: 8,
    name: "Water",
    groups: []
  },
  {
    id: 7,
    name: "Tea",
    groups: [
      {
        id: 8,
        name: "Green tea",
        groups: [
          {
            id: 9,
            name: "With Jasmine",
            groups: []
          },
          {
            id: 10,
            name: "Plain",
            groups: []
          }
        ]
      },
      {
        id: 11,
        name: "Black Tea",
        groups: []
      }
    ]
  }
];

let menuEl = document.querySelector(".funding__categories");

addElements(menuEl, menu);

function addElements(parent, arr) {
  let allCategories = parent.appendChild(document.createElement("ul"));
  allCategories.classList.add("parent");
  arr.forEach((el) => {
    let subCategory = allCategories.appendChild(document.createElement("li"));
    subCategory.dataset.id = el.id;
    subCategory.textContent = el.name;
    if (el.groups.length > 0) addElements(subCategory, el.groups);
  });
}


text:
Q: Formula Expression is required on the action attributes error Problem: I want to override the Case tab with a Visualforce page , but send Users who click a Visualforce page Tab "Case List Views" to the standard Salesforce.com Case home page.
My problem is similar to the one presented here:
http://developer.force.com/cookbook/recipe/overriding-a-page-for-some-but-not-all-users
Here's my code for my visualforce page:
<apex:page action="{if(!$CurrentPage.parameters.CaseListViews != 'yes' ,    null,urlFor($Action.Case.Tab , $ObjectType.Case , null, true))}" >

<apex:enhancedList listId="00B80000008pq6U" height="600" customizable="false" rowsPerPage="25"/>

</apex:page>

I keep getting a "Formula Expression is required on the action attributes." error.
So, I have a couple of issues here:
1) why am I getting the Formula Expression error, and how do I avoid it?
2) Am I correctly passing a parameter from a Visualforce Tab? Here's the code for my page:
<apex:page >

<script>

function launchWindow()

{

window.open("/apex/Case_consolidated_View_2?CaseListViews='yes'");

}

</script>

</apex:page>

Please let me know what I can do differently to make this work. Do I need a controller and page reference? In advance, I'll let you know that I am an admin-learning-to-code, so any detailed explanations to your solution in plain English are much appreciated.
Thank you so much!

A: You have your "!" character in the wrong place:
{!if($CurrentPage.parameters.CaseListViews != 'yes',
  null,urlFor($Action.Case.Tab , $ObjectType.Case , null, true))}

Merge fields are always {! ... }.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I write Dto Model conversion more easily in C#? (Mapping) I have a product list query that I wrote under normal conditions. I have created a mapper for this query and I can use it as follows.
        public IActionResult Index()
        {
            // use normal selecting
            var productList = _context.Products.Select(s => new ProductDto
            {
                Id = s.Id,
                CreateTime = s.CreateTime,
                Title = s.Title,
                Description = s.Description
            }).ToList();

            // use my mapper
            var productListMap = _context.Products
                .ToMap<Product, ProductDto>().ToList();

            return View();
        }

On simple data types it works just fine as long as the type and name are the same. But it cannot convert complex types (classes and models).
I thought it would be a nice idea to specify it as a parameter at the time of writing, so that it gets the job done. So I want a layout like below.
        public IActionResult Index()
        {
            // what i'm doing now
            var productList = _context.Products.Select(s => new ProductDto
            {
                Id = s.Id,
                CreateTime = s.CreateTime,
                Title = s.Title,
                Description = s.Description,
                Features = s.Features.ToMap<Feature, FeatureDto>().ToList(),
                Images = s.Images.ToMap<Image, ImageDto>().ToList()
            }).ToList();

            // i want to do
            var productListMap = _context.Products
                .ToMap<Product, ProductDto>(p => p.Features, p.Images).ToList();

            return View();
        }

What do I need to change/add in the mapper class below to make it easy to use this way?
    public static class Mapper
    {
        public static IEnumerable<TDestination> ToMap<TSource, TDestination>(this IEnumerable<TSource> sourceList)
        {
            return sourceList.Select(source => source.ToMap<TSource, TDestination>());
        }

        public static TDestination ToMap<TSource, TDestination>(this TSource source)
        {
            if (source == null) return default;
            var entityProperties = source.GetType().GetProperties();
            var dtoInstance = Activator.CreateInstance<TDestination>();

            for (int i = 0; i < entityProperties.Length; i++)
            {
                var currentPropertyName = entityProperties[i].Name;
                var value = GetPropertyValue(source, currentPropertyName);
                if (dtoInstance.GetType().GetProperty(currentPropertyName) == null)
                    continue;
                try { dtoInstance.GetType().GetProperty(currentPropertyName).SetValue(dtoInstance, value); }
                catch (Exception ex) { /* Nothing */ }
            }
            return dtoInstance;
        }

        public static object GetPropertyValue(object source, string propName)
        {
            if (source == null) throw new ArgumentException("Value cannot be null.", nameof(source));
            if (propName == null) throw new ArgumentException("Value cannot be null.", nameof(propName));
            var prop = source.GetType().GetProperty(propName);
            return prop != null ? prop.GetValue(source, null) : null;
        }
   }


text:
Q: Prepending/appending values returned in Google Sheets Select Query I have a query like this:
=query(Orders,"select A,B,C WHERE C = 'Open'")

Which returns data, e.g
1234,test@email.com,Open

I'd like to prepend a string to the final value, so that it displays:
1234,test@email.com,Status:Open

Is there a way to do this within the Query or via some other method?

A: Try SUBSTITUTE:
=SUBSTITUTE(query(Orders,"select A,B,C WHERE C = 'Open'"),"Open","Status:Open")

A: You can also try the following formula (provided your data is in 3 separate columns)
=QUERY({A1:B,ARRAYFORMULA("Status:"&C1:C)},
          "select Col1, Col2, Col3 where Col3='Status:Open' ",0)


text:
Q: Flutter Animation Not Fading (It's Blinking) I'm following along with the the animation tutorial on flutter here: https://flutter.io/tutorials/animation/#animationcontroller, and I'm trying to get an icon to fade in and out between purple and orange. Unfortunately all I've managed to do is get an icon to blink which seems very frustrating as that is not how the ColorTween class is defined. From the docs:

We recommend that you do not pass Colors.transparent as begin or end
  if you want the effect of fading in or out of transparent. Instead
  prefer null. Colors.transparent refers to black transparent and thus
  will fade out of or into black which is likely unwanted.

https://docs.flutter.io/flutter/animation/ColorTween/ColorTween.html
I infer this to mean that fading comes "out of the box". However, I have tested this with a CurvedAnimation class as well, and it still blinks. I've also tested with a text box, thinking that somehow the fact that it was loading an icon may be messing it up. However, the text value also blinks between orange and purple. In the code below I have it reversing the animation - I also tried ripping that out but that is not affecting the blinking. I'm thinking it may have something to do with how I'm setting state, but I'm not sure.
My main tutorial example I am trying to base the below code off of comes from here: https://raw.githubusercontent.com/flutter/website/master/_includes/code/animation/animate3/main.dart.
Please see the code below for my implementation. Any advice would be very much appreciated.
class CloudAnimation1 extends StatefulWidget {

  @override
  CloudAnimation1State createState() => new CloudAnimation1State();
}

class CloudAnimation1State extends State<CloudAnimation1> with SingleTickerProviderStateMixin {

  Animation<Color> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = new AnimationController(
        duration: const Duration(milliseconds: 1000), vsync: this);
    final Animation curve = new CurvedAnimation(parent: controller, curve: Curves.easeOut);
    animation = new ColorTween(begin: Colors.orange, end: Colors.purple).animate(curve);

    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
      setState(() {
        // the animation object's value is the changed state
      });
    });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      child: new Row(
        children: <Widget>[
          new Text("hello there sailor",
              style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 25.0, color: animation.value)),
          new Icon(FontAwesomeIcons.cloud, color: animation.value, size: 40.0)
        ],
      ),
    );
  }

  dispose() {
    controller.dispose();
    super.dispose();
  }

}

A: You need to create an AnimatedIcon to actually handle the animation state.
class AnimatedIcon extends AnimatedWidget {
  final IconData icon;

  AnimatedIcon({Key key, Animation<Color> animation, this.icon})
      :super(key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    final Animation<Color> animation = listenable;
    return new Row(
        children: <Widget>[
          new Text("hello there sailor",
              style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 25.0, color: animation.value)),
          new Icon(icon, color: animation.value, size: 40.0)
        ],
      );
  }
}

Then you can replace the build in CloudAnimation1State with
@override
Widget build(BuildContext context) {
  return new Container(
    child: new AnimatedIcon(
      animation: animation,
      icon: Icons.ac_unit,
    ),
  );
}

And then remove the empty setState in the animation status listener.

Alternatively...
The reason that this is blinking is because animation.addStatusListener is only called when the animation status changes, and not on each tick. The AnimatedWidget just wraps and abstracts listening for the tick.
Add the following code to your initState
animation.addListener(() => setState((){}));

This callback listens to each tick of the animation and will cause the widget to re-render. Since you want to redraw all the children of this widget each tick, this makes sense. If you only wanted to redraw some of the children, you'd probably want to wrap them in AnimatedWidgets.
You'll still want to remove the setState inside of the addStatusListener as it is redundant with the new listener.


text:
Q: Firstname-lastname swapping in BibTeX I am writing a paper for an Elsevier journal -- Renewable and Sustainable Energy Reviews -- where the bibliography style for authors' names should be like this: lastname firstinitial
[1] Singaravel RMM, Arul SD. Studies on battery storage requirement of PV fed
wind-driven induction generators. Energy Conversion and Management
2013;67:34--43.
[2] Rydh CJ, Sandén BA. Energy analysis of batteries in photovoltaic systems. Part
II: energy return factors and overall battery efficiencies. Energy Conversion
and Management 2005;46:1980–2000

However, I am using the elsarticle-num.bst style provided by Elsevier. My reference style currently looks like this: firstinitial. lastname
   [1] G. Pepermans, J. Driesen, D. Haeseldonckx, R. Belmans, W. Dhaeseleer,
Distributed generation: definition, benefits and issues, Energy Policy
33 (6) (2005) 787--798. doi:http://dx.doi.org/10.1016/j.
enpol.2003.10.004.
URL http://www.sciencedirect.com/science/article/pii/
S0301421503003069

   [2] R. Yan, S. Roediger, T. K. Saha, Impact of photovoltaic power
fluctuations by moving clouds on network voltage: A case study of an
urban network, in: AUPEC 2011, 2011, pp. 1–-6.

   [3] C. Limsakul, R. Songprakorp, A. Sangswang, P. Parinya, Impact of
photovoltaic grid-connected power fluctuation on system frequency
deviation in contiguous power systems, in: IECON 2015 - 41st Annual
Conference of the IEEE Industrial Electronics Society, 2015, pp.
003236–003241. doi:10.1109/IECON.2015.7392599.

I want to have a reference style following the lastname-firstinitial setup.
Also how to get rid of URL and doi fields without deleting them from .bib file?

A: I suggest you proceed as follows:

*

*Find the file elsarticle-num.bst in your TeX distribution. Make a copy of this file, and name the copied file (say) elsarticle-num-mod.bst. Don't edit an original file of the TeX distribution directly -- edit only a copy.

*Open the file elsarticle-num-mod.bst in a text editor. The program you edit your tex files will do fine.

*In the file, locate the function format.names. (In my copy of this file, the function starts at line 495.)

*In this function, locate the following line:
      "{f.~}{vv~}{ll}{, jj}" format.name$

Change this line to
      "{vv~}{ll}{ f{}}{ jj}" format.name$

You can probably guess that vv, ll, and jj denote the "von", "lastname", and "junior" components of a name. With the change in place, the abbreviated firstname(s), without terminating "dot", will be placed after rather than before the lastname component.

*Next, locate the function write.url; it should start at around line 485. The function definition should look like this:
FUNCTION {write.url}
{ url empty$
    { skip$ }
    { "\newline\urlprefix\url{" url * "}" * write$ newline$ }
  if$
}

Change it to
FUNCTION {write.url}
{}

If you were to think that the modified function does nothing at all, you would be correct. :-)

*Finally, locate the function format.doi (ca. line 1080). It should look this:
FUNCTION {format.doi}
{ doi empty$
    { "" }
    { doiprefix doi * doiurl doi * make.href }
  if$
}

Change it to
FUNCTION {format.doi}
{ "" }

*Save the file elsarticle-num-mod.bst, either in the directory where your main tex file is located or in a directory that's searched by BibTeX. If you choose the latter method, be sure to also update the filename database of your TeX distribution suitably.

*In your main tex file, change the instruction \bibliographystyle{elsarticle-num} to \bibliographystyle{elsarticle-num-mod}, and perform a full recompile cycle: latex-bibtex-latex-latex to fully propagate all changes.
Happy BibTeXing!

A full MWE:

\RequirePackage{filecontents}
\begin{filecontents}{mybib.bib}
@misc{abcd,
   author = "Anna Brenda Carla Duthor and Walter Xavier Yves Zwicki",
   title  = "Thoughts",
   year   = 3001,
   url    = "http://someurl.com",
   doi    = "1.2.3.4",
}
\end{filecontents}

\documentclass{elsarticle}
\bibliographystyle{elsarticle-num-mod}

\begin{document}
\nocite{*}
\bibliography{mybib}
\end{document}


text:
Q: Cordova iOS crashes when targeting remote server I have a cordova app built on Angular 1.6 and Ionic v1. I'm facing a terrible issue on iOS and I don't even know what's going wrong. I'll explain the problem and what I've tried so far, hopefully someone will shed some light on this.
The Problem
We have a screen which is a simple form, you fill in some text and add attachments if you like. For attachments, you can:

*

*Take a picture from your camera

*Shoot a video with you camera

*Record audio

*Choose from your library

*Choose from your iCloud Drive (iOS) or the File System (Android)

You can then save the record, which stores everything on the file system. Or upload to server, which again stores the record on your device.
The issue is, when I choose a file from the library, or any other source, the app crashes unexpectedly shortly after. I can add attachments and save/upload but when I navigate away, the app crashes. This only happens on iOS. No errors, no warnings, no debuggable output, just crashes. I examined the crash logs on my iPhone and apparently the main thread is being blocked for over 5sec. Which causes a watchdog transgression exception to be thrown. Hard to tell what's causing this thread lock, no idea.
I'm using an iPhone 8 running iOS 12.1. It's worth mentioning that the app works fine on the simulator, no bugs or crashes there.
What I've Tried So Far
At first, I thought perhaps something's wrong with my code. So I reviewed every code file line by line, refactored my JS code and improved the code quality. Made sure promises work as intended, resolved JSLint/TSLint warnings etc.
I have updated all cordova plugins to their latest versions. Also removed both platforms and added the latest versions. None of them helped. So I thought maybe I'm missing a configuration quirk or something. Dug through github documentations and SO threads, couldn't find anything useful. Some other things that I've tried:

*

*Disabled HTTPS on our production server, and sent everything through HTTP

*Added NSAppTransportSecurity settings to the *.plist file, and white-listed our domain

*Tinkered with the Content-Security-Policy, even removed it altogether

*Privacy Descriptions are properly configured (NSCameraUsage etc.)

None of them worked. I've been struggling with this issue for two weeks now.
The Weird Part
What's confusing me, is that when I target my local dev machine, that is, when I set the base URL for my API calls to point to my local IIS, the apps works perfectly fine. No bugs/errors, no crashes.
But when I target our remote server, the app crashes when I try to work with attachments (camera, iCloud etc.). I have no idea what I'm missing here. There are no differences between my machine and our remote server. Both run the exact same software, same configuration, and the mobile app is the same build, running on the same device.
So what I can say for certain, is that this issue has nothing to do with my application code, or Cordova and its plugins. The same build works perfectly when targeting my local IIS.
My app is already in production and this needs to be fixed NOW. This is driving me mad, I've tried everything that I could possibly think of and still, no luck. Has anyone had a similar issue? Any help is appreciated.
I'm not authorized to share my code, and like I said, there's nothing wrong with the code, it works absolutely fine when targeting my local IIS. But for your reference, here's some information about my project.
Preferences in Config.xml
<preference name="SplashScreen" value="screen" />
<preference name="windows-target-version" value="10.0" />
<preference name="AndroidPersistentFileLocation" value="Internal" />
<preference name="iosPersistentFileLocation" value="Library" />
<preference name="webviewbounce" value="false" />
<preference name="UIWebViewBounce" value="false" />
<preference name="DisallowOverscroll" value="true" />
<preference name="BackupWebStorage" value="local" />

Cordova Plugins
<plugin name="cordova-plugin-geolocation" spec="^2.4.3">
    <variable name="GEOLOCATION_USAGE_DESCRIPTION" value="Location access allows you to capture your geolocation information on to your records." />
</plugin>
<plugin name="cordova-plugin-device" spec="^1.1.7" />
<plugin name="cordova-plugin-whitelist" spec="^1.3.3" />
<plugin name="cordova-plugin-app-icon-changer" spec="^1.0.0" />
<plugin name="es6-promise-plugin" spec="^4.2.2" />
<plugin name="cordova-plugin-ios-camera-permissions" spec="^1.2.0">
    <variable name="CAMERA_USAGE_DESCRIPTION" value="Camera access allows you to capture and attach photos that you take to your records." />
    <variable name="MICROPHONE_USAGE_DESCRIPTION" value="Microphone access allows you to capture voice information to your records." />
    <variable name="PHOTOLIBRARY_ADD_USAGE_DESCRIPTION" value="Photo library access allows you to upload your photos and media files to your records." />
    <variable name="PHOTOLIBRARY_USAGE_DESCRIPTION" value="Photo library access allows you to upload your photos and media files to your records." />
</plugin>
<plugin name="cordova-plugin-android-fingerprint-auth" spec="^1.4.1" />
<plugin name="cordova-plugin-inappbrowser" spec="^3.0.0" />
<plugin name="cordova-plugin-filechooser" spec="1.1.0" />
<plugin name="cordova-plugin-crosswalk-webview" spec="2.4.0">
    <variable name="XWALK_VERSION" value="23+" />
    <variable name="XWALK_LITEVERSION" value="xwalk_core_library_canary:17+" />
    <variable name="XWALK_COMMANDLINE" value="--disable-pull-to-refresh-effect" />
    <variable name="XWALK_MODE" value="embedded" />
    <variable name="XWALK_MULTIPLEAPK" value="true" />
</plugin>
<plugin name="cordova-plugin-statusbar" spec="2.4.2" />
<plugin name="cordova-plugin-add-swift-support" spec="1.7.2" />
<plugin name="cordova-plugin-touch-id" spec="3.4.0">
    <variable name="FACEID_USAGE_DESCRIPTION" value="OnRecord would like to access your touch ID to let you log in securely." />
</plugin>
<plugin name="cordova-plugin-media-playback" spec="1.0.2-dev5" />
<plugin name="cordova-plugin-documentpicker" spec="1.0.0" />
<plugin name="cordova-plugin-file" spec="6.0.1" />
<plugin name="cordova-plugin-file-transfer" spec="1.7.1" />
<plugin name="cordova-plugin-media-capture" spec="3.0.2" />
<plugin name="cordova-plugin-camera" spec="4.0.3" />

Content-Security-Policy in index.html
<meta http-equiv="Content-Security-Policy" content="default-src 'self' gap://ready ms-appdata file://* *; img-src 'self' content: android-webview-video-poster: data: *; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://maps.googleapis.com https://maps.gstatic.com; media-src *; connect-src *">

App Transport Security Policies
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
  <key>NSAllowsArbitraryLoadsInWebContent</key>
  <true/>
  <key>NSAllowsLocalNetworking</key>
  <true/>
  <key>NSExceptionDomains</key>
  <dict>
      <key>your.domain.com</key>
      <dict>
          <key>NSIncludesSubdomains</key>
          <true/>
          <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
          <true/>
          <key>NSTemporaryExceptionMinimumTLSVersion</key>
          <string>1.0</string>
          <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
          <false/>
      </dict>
  </dict>
</dict>

Privacy Descriptions (Permissions)
<key>NSFaceIDUsageDescription</key>
<string>This app would like to access your touch ID to let you log in securely.</string>
<key>NSCameraUsageDescription</key>
<string>This app needs camera access</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app would like to access your location to let you track your records.</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app needs microphone access</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app needs write-access to photo library</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs read/write-access photo library access</string>

Let me know if you need more information or any further explanations. I've tried to describe the problem best as I can. To recap:
The app works flawlessly when targeting my local machine, but crashes when targeting our remote server. What's bugging me is, this shouldn't have anything to do with my app. The camera plugin, choosing files from different sources etc. happen locally on the device, what's it got to do with my base API address?! Very strange indeed.
Update: Clarification
After more test runs, I have figured out what's causing the app to crash. Although it's still not clear, from a UX perspective, this is what happens on iOS:
As soon as I use the Camera plugin (cordova-camera), the app crashes shortly after. It doesn't matter if I choose a file from the camera roll/library, or take a picture etc. I just open the camera or library, cancel and navigate away. The app crashes. So clearly it has something to do with the camera plugin.
What's bugging me is that, as I mentioned before, when I target my local IIS by changing the base URL address, the app works fine. I don't understand why this has anything to do with camera usage, because it happens locally on the device. What I'm speculating now is, perhaps something is causing the app to throw exceptions because the remote URL uses HTTPS. But I'm not getting any warnings/errors in Xcode, so who knows.
Certainly, the issue is not with cordova-ios, the camera plugin, my JS code, or any security configurations (App Transport Security, and Content-Security-Policy). Because the app works fine when targeting my IIS. I think I'm missing something here.

A: I finally found what's causing the iOS app to crash. The problem was in our code but still, it had something to do with Cordova as well, specifically the File and Camera plugins.
We had a TypeScript class in our project that was developed by someone else long ago. This class handled data access uinsg the File plugin and the native file system. We were using it to store JSON objects on the device, which was working fine, but only for small cases like saving a file or two. You fetch some data from the server, and for each record we create a JSON file on the file system and store it. The problem occured when we used this in a loop. Say you get a 100 records back from the server, and within a loop you call the save method to store the records.
This worked fine, but immediately after using the Camera plugin (or sometimes other plugins like the iCloud Document Picker) the app crashed silently. I'm guessing the File plugin or the write operations were causing memory leaks, or the app to go low on memory, subsequently accessing the Camera plugin crashed the app. I'm not quite sure why everything worked fine on Android, perhaps because the Cordova engine and the Android file system are different.
Nevertheless, there was no need to store JSON data on the file system. So I refactored the project to use LocalStorage instead. It's so much faster and it also resolved the issue. No crashes on iOS! It might be that the code for writing to the file system could be changed to fix the issue, but it wasn't necessary anyway.
I'm glad I have finally figured this out, but it's a bloody nightmare to debug Cordova plugins and spot memory leaks. The only thing left is to replace LocalStorage with something more reliable like SQLite. Because the OS can decide to clear out the data when low on memory/space and we have no control over it. For now, it's totally fine. I've been trying to use the Ionic Storage module because it uses SQLite and allows storing JSON or key/value pairs. But I haven't been able to use the module in Angular 1 which is a bummer because I can use other Ionic Native modules just fine. Case closed.


text:
Q: Script to prevent screen blanking using "mouse move" doesn't work This is my attempt to make a script that will use a "mouse move" to prevent screen blanking while watching videos. I'm hoping to use the value for highest CPU% process in top and if CPU usage exceeds 5%, a mouse move should occur.
#!/usr/bin/env bash

sleep_period=60s

while true; do
  if (( $(top -bn 1 | sed -nrs '8p' | awk '{ print $9 }') -gt 5 )); then
    while (( $(top -bn 1 | sed -nrs '8p' | awk '{ print $9 }') -gt 5 )); do
      xdotool mousemove 0 100
      xdotool mousemove 0 50
      sleep ${sleep_period}
    done
  else
    sleep ${sleep_period}
  fi
done

Unfortunately, it does not work. The errors are like this:
[07:20 PM] /bin $ noo.sh
/home/vasa1/bin/noo.sh: line 6: ((: 0.0 -gt 5 : syntax error: invalid arithmetic operator (error token is ".0 -gt 5 ")
/home/vasa1/bin/noo.sh: line 6: ((: 6.4 -gt 5 : syntax error: invalid arithmetic operator (error token is ".4 -gt 5 ")

How do I fix this? (Please note that I'm not experienced in scripting.)

Based on answers here, I put together:
#!/usr/bin/env bash

sleep_period=5m

while true; do
  if [[ $(top -bn 1 | sed -nrs '8p' | awk '{ print int($9) }') -gt 8 ]]; then
    while [[ $(top -bn 1 | sed -nrs '8p' | awk '{ print int($9) }') -gt 8 ]]; do
      xset -dpms; xset s off
      xset +dpms; xset s on
      sleep ${sleep_period}
    done
  else
    sleep ${sleep_period}
  fi
done

Then, I reported this code over at Ubuntu Forums and Vaphell worked on it further. Below is Vaphell's version and is what I am using:
#!/usr/bin/env bash

sleep_period=5m

while true; do
  if top -bn 1 | awk 'NR==8 { exit !($9>8); }'; then
    xset -dpms; xset s off
    xset +dpms; xset s on
  fi
  sleep ${sleep_period}
done

A: You can use
xset -dpms; xset s off

to stop the screen from going black.
To enable this again use
xset +dpms; xset s on

So -dpms disables the the power energy saving features, which can turn off the whole monitor and s off turns off the screen saver feature of the X server.
This does not work with the xscreensaver, which was mentioned in the comments.

A: You have a couple of issues, first, you will need 2 iterations of top each time, see my answer here and the bug report here.
The other problem is that bash does not do floating point, so if your CPU usage is something like 6.2, the .2 will break the script. Bash is simply not designed for 'complex' arithmetic operations.  One way around this would be to move the >5 check inside your awk command:
#!/usr/bin/env bash

sleep_period=60s

while true; do
    until top -bn 2 -d 0.01 | sed -nrs '8p' | awk '{if($9>5){exit 1}else{exit 0}}'; do
      xdotool mousemove 0 100
      xdotool mousemove 0 50
      sleep ${sleep_period}
    done
   sleep ${sleep_period}
done

A: First, you need to install xdotool & rand. Example on Ubuntu:
sudo apt install xdotool rand

Then run this one-liner in a terminal (as user):
eval $(xdotool getdisplaygeometry --shell); while true; do xdotool mousemove `rand -M $WIDTH` `rand -M $HEIGHT` && sleep $((`rand -M 300` + 120)); done;


text:
Q: Могу ли я использовать WebView в Service? Мне необходимо совершать некоторые операции с JavaScript на сайте, для этого я использую WebView. Могу ли я инициализировать WebView от контекста сервиса и пользоваться им в дальнейшем: ходить по сайтам, совершать операции с JavaScript? Мне не нужно выводить WebView в UI, поэтому нет никакой необходимости инициализировать WebView в activity. Я бы парсил сайт через GET-запрос, но вся проблема в использовании JavaScript.

A: Да, это возможно. WebView, как и все остальные виджеты, будет работать даже если не отображать его, а просто инициализировать


text:
Q: Escaping strings with python mysql.connector I am trying to insert a bunch of strings into mysql using python and mysql.connector. My current code looks something like this:
db = mysql.connector.Connect('config blah blah')
cursor = db.cursor()
data = (somestring1, somestring2)
sql = "INSERT INTO mytable (col1, col2) VALUES ('%s', '%s')"
cursor.execute(sql, data)

How should I go about escaping my strings? I could try doing it in python but I know this isn't the right way.
Note: I realise mysql.connector is still in development.
update:
Line 4 should read:
sql = "INSERT INTO mytable (col1, col2) VALUES (%s, %s)"

A: Since mysql.connector is DB API v2.0 compliant, you do not need to escape the data yourself, it does it automatically for you.

A: The answer from infrared is the best approach.
But, if you really need to escape some arbitrary string, you can do this (before 2.1.6):
db = mysql.connector.connect(......)

new_str = db.converter.escape('string to be escaped')

Newer versions (use lowlevel C-API):
db = mysql.connector.connect(......)

new_str = db._cmysql.escape_string('string to be escaped')

Another option is to use mariadb python connector (pip install mariadb).
db = mariadb.connector(....)
new_str = db.escape_string("quote ' this")

A: Indeed, the best approach would be to let module escape values by itself.  If you absolutely need to do it by hand (I, for example, want to only print SQL in my script's debug mode, and mysql.connector doesn't seem to implement mogrify()), there's also another option:
>>>> import mysql.connector
>>>> cnx = mysql.connector.connect()
>>>> cur = cnx.cursor()
>>>> cur._connection.converter.escape("tic ' toc")
"tic \\' toc"

Admittedly, it still uses "non-public API", but at least it is consistent between recent versions (so far; tested on 2.0.4, 2.1.3, 2.2.9, 8.0.16).

A: Here is what worked for me:
import mysql.connector
db = mysql.connector.connect(host="HOST",    # your host, usually localhost
                     user="USERNAME",         # your username
                     passwd="PASSWORD",  # your password
                     db="DATABASE")        # name of the data base

query_string = "Geor'ge"
escaped_string = db.converter.escape(query_string)

The first step is to import mysql.connector, followed by creating a connection by using the connect function. After that, you can call the db.converter.escape function.

A: You can do this with the pymysql package:
import pymysql
from pymysql.converters import escape_string
from mysql.connector import connect, Error

then you can do:
with connect(
    host="localhost",
    user="root",
    password="",
    database="mydb",
) as connection:
    with connection.cursor(buffered=True) as cursor:
        cursor.execute(escape_string("YOUR_SQL_STATEMENT"))


text:
Q: How to display file unzip progress? I am trying to figure out a way to display the current progress as well as the time remaining to unzip and write the contents of a zip file to disk. I am currently using the ZipArchiver class found here http://code.google.com/p/ziparchive/ which is working quite well.  Problem is, that a lot of it is written in C++ which i dont have too much experience in. Here is the relevant function:
-(BOOL) UnzipFileTo:(NSString*) path overWrite:(BOOL) overwrite
{
    BOOL success = YES;
    int ret = unzGoToFirstFile( _unzFile );
    unsigned char           buffer[4096] = {0};
    NSFileManager* fman = [NSFileManager defaultManager];
    if( ret!=UNZ_OK )
    {
            [self OutputErrorMessage:@"Failed"];
    }

    do{
            if( [_password length]==0 )
                    ret = unzOpenCurrentFile( _unzFile );
            else
                    ret = unzOpenCurrentFilePassword( _unzFile, [_password cStringUsingEncoding:NSASCIIStringEncoding] );
            if( ret!=UNZ_OK )
            {
                    [self OutputErrorMessage:@"Error occurs"];
                    success = NO;
                    break;
            }
            // reading data and write to file
            int read ;
            unz_file_info   fileInfo ={0};
            ret = unzGetCurrentFileInfo(_unzFile, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
            if( ret!=UNZ_OK )
            {
                    [self OutputErrorMessage:@"Error occurs while getting file info"];
                    success = NO;
                    unzCloseCurrentFile( _unzFile );
                    break;
            }
            char* filename = (char*) malloc( fileInfo.size_filename +1 );
            unzGetCurrentFileInfo(_unzFile, &fileInfo, filename, fileInfo.size_filename + 1, NULL, 0, NULL, 0);
            filename[fileInfo.size_filename] = '\0';

            // check if it contains directory
            NSString * strPath = [NSString  stringWithCString:filename];
            BOOL isDirectory = NO;
            if( filename[fileInfo.size_filename-1]=='/' || filename[fileInfo.size_filename-1]=='\\')
                    isDirectory = YES;
            free( filename );
            if( [strPath rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"/\\"]].location!=NSNotFound )
            {// contains a path
                    strPath = [strPath stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
            }
            NSString* fullPath = [path stringByAppendingPathComponent:strPath];

            if( isDirectory )
                    [fman createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:nil];
            else
                    [fman createDirectoryAtPath:[fullPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
            if( [fman fileExistsAtPath:fullPath] && !isDirectory && !overwrite )
            {
                    if( ![self OverWrite:fullPath] )
                    {
                            unzCloseCurrentFile( _unzFile );
                            ret = unzGoToNextFile( _unzFile );
                            continue;
                    }
            }
            FILE* fp = fopen( (const char*)[fullPath UTF8String], "wb");
            while( fp )
            {
                    read=unzReadCurrentFile(_unzFile, buffer, 4096);
                    if( read > 0 )
                    {
                            fwrite(buffer, read, 1, fp );
                    }
                    else if( read<0 )
                    {
                            [self OutputErrorMessage:@"Failed to reading zip file"];
                            break;
                    }
                    else
                            break;
            }
            if( fp )
            {
                    fclose( fp );
                    // set the orignal datetime property
                    NSDate* orgDate = nil;

                    //{{ thanks to brad.eaton for the solution
                    NSDateComponents *dc = [[NSDateComponents alloc] init];

                    dc.second = fileInfo.tmu_date.tm_sec;
                    dc.minute = fileInfo.tmu_date.tm_min;
                    dc.hour = fileInfo.tmu_date.tm_hour;
                    dc.day = fileInfo.tmu_date.tm_mday;
                    dc.month = fileInfo.tmu_date.tm_mon+1;
                    dc.year = fileInfo.tmu_date.tm_year;

                    NSCalendar *gregorian = [[NSCalendar alloc]
                                                                     initWithCalendarIdentifier:NSGregorianCalendar];

                    orgDate = [gregorian dateFromComponents:dc] ;
                    [dc release];
                    [gregorian release];
                    //}}

                    NSDictionary* attr = [NSDictionary dictionaryWithObject:orgDate forKey:NSFileModificationDate]; //[[NSFileManager defaultManager] fileAttributesAtPath:fullPath traverseLink:YES];
                    if( attr )
                    {
                            //              [attr  setValue:orgDate forKey:NSFileCreationDate];
                            if( ![[NSFileManager defaultManager] setAttributes:attr ofItemAtPath:fullPath error:nil] )
                            {
                                    // cann't set attributes
                                    NSLog(@"Failed to set attributes");
                            }

                    }

            }
            unzCloseCurrentFile( _unzFile );
            ret = unzGoToNextFile( _unzFile );
    }while( ret==UNZ_OK && UNZ_OK!=UNZ_END_OF_LIST_OF_FILE );
    return success;
}

I am having a hard time trying to figure out how i would be able to insert some code that would let me display the current percentage progress as well as the time remaining to unzip and write all files to disk. Any ideas on how i could go about achieving this?
thx

A: Don't "insert some code to display the progress."  Instead, do the actual work in a separate operation, and have that communicate its progress to the main thread for presentation to the user.
Just reading through your code there are a few extremely obvious places to pass this information out.  For example, there's an inner loop that reads data from a single file in the archive, and there's an outer loop that iterates over the files in the archive.  You could easily create a set of delegate messages that can be used to report which file is being extracted, how far along it is, and how far along in the entire archive the extraction is.
Then you can create a specific delegate that knows how to interact with your UI (on the main thread) and present this progress to the user.

A: Use:
https://github.com/mattconnolly/ZipArchive
or from cocoapods:
pod 'ZipArchive', '1.1.0'
Just create a block of progress assign it to your zip variable and let the nslog show you.
Easy ...
Use:
ZipArchive *zip = [[ZipArchive alloc] init];

ZipArchiveProgressUpdateBlock progressBlock = ^ (int percentage, int filesProcessed, int numFiles) {
    NSLog(@"total %d, filesProcessed %d of %d", percentage, filesProcessed, numFiles);
};

zip.progressBlock = progressBlock;

//open file
[zip UnzipOpenFile:path];

//unzip file to
[zip UnzipFileTo:contentPath overWrite:YES];

A: This is the equation you use to estimate the time remaining:
([TimeTaken] / [NumberOfFilesProcessed]) * [NumberOfFilesRemaining] = EstTimeRemaining
TimeTaken:
The number of seconds elapsed since the start of the process. You can use NSTimeInterval and the NSDate functions to get this result.
As for percentage, you can only view the percentage of files processed, but not the progress of a current unzip.


text:
Q: Can't submit job with Flink 1.5 cluster Trying to move from Flink 1.3.2 to 1.5 We have cluster deployed with kubernetes. Everything works fine with 1.3.2 but I can not submit job with 1.5. When I am trying to do that I just see spinner spin around infinitely, same via REST api. I even can't submit wordcount example job.
Seems my taskmanagers can not connect to jobmanager, I can see them in flink UI, but in logs I see

level=WARN   akka.remote.transport.netty.NettyTransport - Remote connection to [null] failed with
  org.apache.flink.shaded.akka.org.jboss.netty.channel.ConnectTimeoutException:
  connection timed out:
  flink-jobmanager-nonprod-2.rpds.svc.cluster.local/25.0.84.226:6123
level=WARN   akka.remote.ReliableDeliverySupervisor - Association with remote system
  [akka.tcp://flink@flink-jobmanager-nonprod-2.rpds.svc.cluster.local:6123]
  has failed, address is now gated for [50] ms. Reason: [Association
  failed with
  [akka.tcp://flink@flink-jobmanager-nonprod-2.rpds.svc.cluster.local:6123]]
  Caused by: [No response from remote for outbound association.
  Associate timed out after [20000 ms].]
level=WARN   akka.remote.transport.netty.NettyTransport - Remote
  connection to [null] failed with
  org.apache.flink.shaded.akka.org.jboss.netty.channel.ConnectTimeoutException:
  connection timed out:
  flink-jobmanager-nonprod-2.rpds.svc.cluster.local/25.0.84.226:6123

But I can do telnet from taskmanager to jobmanager
Moreover everything works on my local if I start flink in cluster mode (jobmanager + taskmanager).
In 1.5 documentation I found mode option which flip mode between flip6 and legacy (default flip6), but If I set mode: legacy I don't see my taskmanagers registered at all.
Is this something specific about k8s deployment and 1.5 I need to do? I checked 1.5 k8s config and it looks pretty same as we have, but we using customized docker image for flink (Security, HA, checkpointing)
Thank you.

A: The issue with jobmanage connectivity. Jobmanager docker image cannot connect to "flink-jobmanager" (${JOB_MANAGER_RPC_ADDRESS}) address.
Just use afilichkin/flink-k8s Docker instead of flink:latest
I've fixed it by adding new host to jobmanager docker. You can see it in my github project
https://github.com/Aleksandr-Filichkin/flink-k8s/tree/master


text:
Q: My SPA is not working on Laravel 8 and Vue 3 I have a problem with my single page application(SPA) using Vue 3, Vue Router 4 & Laravel 8, my problem is that the components is not loading.
I made sure I installed vue-router, I don't know why the code can't run. The links are not even clickable. I have been on this for over 3 days now and still I haven't found the solution to the problem
This is my code.
app.js
require('./bootstrap');
window.Vue = require('vue').default;
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
Vue.use(VueRouter);

Vue.component('home', require('./components/Home.vue').default);
Vue.component('about', require('./components/About.vue').default);
Vue.component('contact', require('./components/Contact.vue').default);

const app = new Vue({
    el: '#app',
    router: new VueRouter(routes)
});

routes.js
import Home from './components/Home.vue';
import About from './components/About.vue';
import Contact from './components/Contact.vue';
export default{
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'home',
            component: Home
        },

        {
            path: '/about',
            name: 'about',
            component: About
        },

        {
            path: '/contact',
            name: 'contact',
            component: Contact
        }
    ]
}

contact.vue
<template>

This is the contact us page.

</template>

about.vue
<template>

This is the about us page.

</template>

home.vue
<template>

This is the home page.

</template>

app.blade.php
    <!doctype html>
getLocale()) }}">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

            @yield('content')

welcome.blade.php
@extends('layouts.app')
@section('content')
    <router-link class="text-center" to='/'>Home</router-link>
    <router-link class="" to='/about'>About</router-link>
    <router-link class="" to='/contact'>Contact</router-link>
    <router-view></router-view>
@endsection

web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/{any}', function(){
    return view('welcome');
})->where('any', '.*');

The links are not clickable

A: I have removed the extra div that make You confused.
 @extends('layouts.app')
@section('content')

    <router-link class="text-center" to='/'>Home</router-link>
    <router-link class="" to='/about'>About</router-link>
    <router-link class="" to='/contact'>Contact</router-link>
    <router-view></router-view>

@endsection


text:
Q: Shortcut to file permissions I have two mapped drives on our server (M & P, management and public) with rights for everyone on P and only rights for management on M.
We now have team leads who have to access just a few folders on M.  Is it possible to create a shortcut on P to the needed folders on M which would allow the Team Leads to access the just files they need on M?  For instance the Team Lead needs access to M:\Ops\Schedules (and the files within the Schedule folder).  I would like to create a shortcut on P to M:\Ops\Schedules allowing the Team LEad to open the Schedule folder.
I have tried adding the Team Lead group (which have read and execute permissions) to both the shortcut and the folder where the files reside but I get an error message saying that the user does not have sufficient rights.
TIA,
Brian Enderle

A: You might want to ask this question at ServerFault, since this seems more of a server administration question than a programming one.
But to attempt answer your question, assuming the shares are Windows file shares, you would need to check two things: that the permissions of M:\Ops\Schedules are set so that members of the Team Leads group have access to the directory, and that the share permissions of the Management share are set so Team Leads have (at minimum) read access.  If either of these are not present, team leaders will be denied access to the directory.
As an alternative, you could create a new share on the server that points to \Ops\Schedules, and give team leads access to this share.  You could then create a shortcut on P: directly to that share.  Team Leads will need access (through NTFS permissions) to the \Ops\Schedules directory.
Either approach should work, and the one to use might depend on whether you are relying primarily on NTFS permissions or share permissions to secure your file shares.


text:
Q: Inferring back emf from oscilloscope I have this stepper motor with unknown back EMF / RPM.  There are 200 steps/rev (i.e. 1.8deg step angle), and 8mH "phase inductance", but I'm not sure if that's enough to calculate back EMF.
I hooked up one of the parallel windings from each phase to an oscilloscope.  (Specifically, red/yellow on one probe, white/orange on the other probe.)
I then manually rotated the shaft and captured the following measurement.  You can see that the time between two signal peaks is ~770Hz and the voltage magnitude is ~33V.

*

*Do those two 90deg-phased peaks correspond to one step each, therefore implying that the RPM at that time was 770(step/sec) / 200(step/rev) * 60(sec/min) = 231RPM?

*Does that imply that the back EMF is 33V/231RPM = 143mV/RPM?

*If so, how is that reconciled with the specs saying 30VDC is sufficient to drive the stepper at 1500RPM, which would then correspond to ~214V in back EMF?

I'm a bit confused.  If the motor was hooked up in "serial" mode instead, that would result in an even "worse" (double) back EMF/RPM.

Edit: FYI, in case anyone thinks this is because there is no load attached, I applied a 22 Ohm resistor to one of the parallel winding terminals, performed a similar measurement and calculated a similar back EMF constant of 134mV/RPM (compared to 143mV/RPM earlier).  So I don't think it has to do with the terminals being "open circuit" (which they technically wouldn't be anyway, since the scope probe or air has a very large but still not infinite resistance).

Edit 2: This question is similar and seems to support my back emf constant measurement method.  However, that person was also encountering an unexpected value, and no satisfying answer was given.

Edit 3:  I should add, my calculated back EMF / RPM was based on the sinusoidal peak vs the average (which it should be according to this answer).  Therefore, to make my calculated back EMF constant above consistent with the usual definition, it should be multiplied by 2/pi ~= .637.  However, even 64% of the calculated voltage at 1500 RPM is still way above the 30V I was expecting to be able to use.

A: This is a big stepper motor. The motor inductance of 8mH per phase is an indicator that is made to be used with high voltage stepper driver, like 325 VDC or 230VAC rectified, with a chopper driver, that has a current setpoint.
Have a look for similar model: Sanyo Denki

It has near 4mH per phase, similar to yours if you connect 8mH phases in parallel and it has 0.46 ohm per phase, similarly yours have 0.9 per phase, but connected in parallel gives 0.45 ohm.  With a BEMF constant of 161V/kRPM you can expect similar torque characteristics also from yours motor.
At 140 VDC supply it has a knee point at 1200 rpm
At 48 VDC this drops to a 300 rpm
EDIT:
143mv/RPM is :
$$\require{cancel}\dfrac{143mV\cdot min}{R} =0,143V \dfrac{\bcancel{2\pi\ rad}\cdot 60s\cdot\bcancel{ min}}{2\pi\ rad\cdot\bcancel{ 60s}\cdot\bcancel{R}} = 1.366 \dfrac{V\cdot s}{rad} $$
$$k_t \approx 1.366\ Nm/A$$
While this doesn't hold for your motor : 1.366*6= 8.1Nm, it holds for Sanyp Denki motor. 0.161V/RPM = 1.54 Vs/rad; 1.54 Nm/A * 6A = 9.2 Nm.


text:
Q: Shopify - Forgot password / reset password not working I'm trying to add a Forgot/Reset Password link to my Shopify page.
I tried this:
reset

But /account/login#recover link brings me to the login page instead of to Forgot/Reset Password page.
What is the right URL for going directly to Forgot/Reset Password page?

A: Yes, it is correct url which one you are using. Actually forgot password form is also on the same page as login. It is hiding and showing Login/Forgot-Password based on url parameters.


text:
Q: mobile IOS Google chrome address bar behaviour I have spent a lot of time trying jquery/javscript "fix" to get this worked. Since the last update of chrome mobile for IOS, the address bar of the browser behaves differently. I'm sure you guys are aware of what I'm talking about: You scroll down your page, the bar hides up, but once you scroll up, it appears. Yes, it is a good user experience, I can tell.
The problem is that I do have fixed element on top of my web app (header), and every time I scroll up, the address bar goes over my fixed element.
I've lookup other web apps (twitter, gmail), and they seems to have found a way to avoid this. I would like to read your ideas of how they achieved it.  There is no need to tell me not to use fixed element.
So my question is : is there a way to avoid this? What's your idea of the situation.
example: https://mobile.twitter.com/EmWatson (must see on iphone preferably)
FYI : I use Jquery mobile framework for my web app.
thanks.

A: Well, I found a way to work.

    FIXED HEADER

                  ...(content)...

It appears that we need an inner scrollable element and remove overflow on body. I overthought it, it seems. Hope this helps someone.


text:
Q: Rearranging div hierarchy with jquery I'm using jQuery's form plugin to submit a form asynchronously. The server sends back HTML which goes into a div #boardcontainer by setting the target of an ajaxForm call. This works fine.
...
    var options = {
      target:        '#boardcontainer',    // target element(s) to be updated with server response
      beforeSubmit:  showRequest,  // pre-submit callback
      success:       showResponse  // post-submit callback
      };
    $('#myForm').ajaxForm(options);
...

Problem is, the HTML that comes back from the server contains two divs:

...

...

"#board" is a giant HTML table prerendered by the server. "#status" is a short message and should ideally go into a div other than #boardcontainer.
What's the best way to handle this situation? Can jquery change a div's parent? If so I can change the parent in the post-submit callback, but I can't seem to find a way to do it.

A: In your success callback you could rearrange the divs using appendTo.  Alternatively you could return json and build the divs in your success callback.
 $('#status').appendTo('#realTarget');

EDIT: Upon checking, appendTo itself does what you need it to do without losing the event handlers.

A: I ended up building the divs with json (with the html for the divs embeded as strings, though)
Here's the code:
$(document).ready(function () {
    var options = {
        beforeSubmit: showRequest,  // pre-submit callback
        success: showResponse,  // post-submit callback
        dataType: 'json'
    };
    $('#myForm').ajaxForm(options);
});

function showResponse(data) {
    $('#statusTarget').html(data.status);
    $('#boardcontainer').html(data.board);
};

It works and both the #statusTarget and the #boardTarget are replaced with the new html every time the form is submitted.


text:
Q: How do I test the availability of the internet in Java? I don't want to tell the hard way that the internet is unavailable when I catch an exception from url.openStream().
Is there a simple way to tell if the computer is connected to the internet in Java?
In this scenario, "connected to the internet" means being able to download data from a specific url.
If I try to download from it and it is not available, then the program hangs for a bit. I dont want that hanging. Therefore, i need a fast way of querying whether the website is available or not.

A: Use
Process p1 = java.lang.Runtime.getRuntime().exec("ping www.google.com");
System.out.println(p1.waitFor());
// return code for p1 will be 0 if internet is connected, else it will be 1

A: There is no such thing as "Internet availability".
Imagine that your HTTP request go through a transparent HTTP proxy, you are trying to access a blacklisted site and you get a HTTP response from the proxy server telling you about access denied. Is Internet available in this scenario or not?
I think you shall be more specific about your problem.

A: You might be able to tell if a compouter is connected to a network but even if it is there's no guarantee the networking is working or that it's connected to the internet.
This is one of those "suck it and see" problems.
What's wrong with trying to connect?  And why are you concerned whether or not they're connected to the internet?

A: If the criteria is whether you can access a given web server the only way to find out, is to access that web server.
You can, however, do it in a background thread at start up so the application is not delayed by it.  Then the "yes/no" answer is available when the actual downloading is desired.   Put a message in the status line so the user knows what is going on and is not suprised about uninitiated "connect to network" if s/he is not connected when your program is started.

A: The problem you are trying to avoid is waiting for for your http connection to determine that the URL you are trying to access is really unavailable. In order to achieve this you need to stop using url.openStream() which is a shortcut for openConnection().getInputStream() and get some finer control over your connection.
URLConnection conn = url.openConnection();
conn.setConnectTimeout(timeoutMs);
conn.setReadTimeout(timeoutMs);
in = conn.getInputStream();

This code will allow you to timeout the connection attempt if either the connection or the read exceeds the time you provide in the timeoutMs paramater.

A: I don't know much about the low level HTTP plumbing available in Java, but you could always issue an http HEAD request for the url in advance. This causes the server to send back only the headers and not the data. With a 1-3 second timeout, you should be able to avoid any lengthy delays.

A: If you program is hanging while waiting to download then you are probably using the GUI thread to do the download.  If you use a background thread, your program won't hang even if it take a long time to timeout/download.

A: You could send an ICMP message to a very well known host...

A: You can check for a NTP server if your firewall does not forbids.
Any way I think the best option is to try to open an URL as you try to avoid, because is the service most commonly to be opened.
You can check for one or two dynamic URL that change constantly. For instace, some web that shows time. For instance this one i found googleing. More than one because the sites can be down ;-)


text:
Q: Flag Update in james james-2.3.2.1 I am new to Apache james,  using james-2.3.2.1, I am able to send and retrieve the mail but unaware about how to update the flag of the the retrived message . I tried with pop3 but is not allowing me for  the same.
Having error :

javax.mail.IllegalWriteException: POP3 messages are read-only

Can you please suggest me the right path?

A: Probably the OS is a Linux based and seems that you don't have the right access there.


text:
Q: Online position on QGIS using the INPUT app I am using QGIS 3.22. I have created a project and loaded into the INPUT app. Is there a way that I can see on my QGIS the current location of the person that is using the INPUT app in the field in real-time?

A: The short answer is no. For that to work, we would need to implement tracking option (https://github.com/MerginMaps/input/issues/500) and also having auto-sync on.


text:
Q: Retrieve XDocument Immediate Node Value linq to xml I have the following XML data:
<?xml version="1.0"?>
<response version="1.0">
    <respcode>200</respcode>
    <respmessage>Success</respmessage>
    <datetime>Thu, 18 Jan 2018 06:20:25 +0000</datetime>
    <location>
        <site_code>COH</site_code>
        <phone>781-383-0180</phone>
        <fax>781-383-9093</fax>
        <standardized_operation_hours>
            <Monday>07:30-17:00</Monday>
            <Tuesday>07:30-17:00</Tuesday>
            <Wednesday>07:30-17:00</Wednesday>
            <Thursday>07:30-17:00</Thursday>
            <Friday>07:30-17:00</Friday>
            <Saturday>X</Saturday>
            <Sunday>X</Sunday>
    </standardized_operation_hours>
    <scheduling>YES</scheduling>
    <time_zone>America/New_York</time_zone>
    </location>
</response>

Here is my code to parse and retrieve values of the child elements:
XDocument document = XDocument.Load(@"F:\Appointment Scheduling
  Info\CompleteFacilities.xml");

var locations = from location in document.Descendants("location")
                select new
                {
                    siteCode = location.Element("site_code").Value,
                    phone = location.Element("phone").Value,
                    fax = location.Element("fax").Value,
                    standardized_operation_hours = location.Element("standardized_operation_hours"),
                    timeZone = location.Element("time_zone") != null ? location.Element("time_zone").Value : null,
                    scheduling = location.Element("scheduling") != null ? location.Element("scheduling").Value : null
                };

Question:
I can retrieve the PhoneNUmber using: locations.First().phone
But when I access, locations.First().standardized_operation_hours.Value - I was expecting to get the child node value:
<Monday>07:30-17:00</Monday>
<Tuesday>07:30-17:00</Tuesday>
<Wednesday>07:30-17:00</Wednesday>
<Thursday>07:30-17:00</Thursday>
<Friday>07:30-17:00</Friday>
<Saturday>X</Saturday>
<Sunday>X</Sunday>`

What is retrieved is the leaf value: "07:30-17:0007:30-17:0007:30-17:0007:30-17:0007:30-17:00XX"
How do I retrieve the above expected value with complete child node info containing Monday / Tuesday..?


text:
Q: H5py import not working in Maya I'm trying to install h5py in Maya. It seems like its installed properly in the correct folder, i.e. : C:\Program Files\Autodesk\Maya2018\Python\Lib\site-packages\h5py. But when I try to import h5py in Maya's Python tab, I'm getting the following error
ImportError: file C:\Program Files\Autodesk\Maya2018\Python\lib\site-packages\h5py\__init__.py line 26:
DLL load failed: The specified module could not be found.

A: Got this thing working , if anyone is facing this issue please follow the following article http://3deeplearner.com/neural-network-inside-maya/
The author of this tutorial helped a lot with the required solution for this issue
Thank you Gus from 3deeplearner.com


text:
Q: Does a free $R$-module of countable rank ever arise as a (double) dual of some $R$-module? The usual counterexample to all vector spaces being canonically isomorphic to their double duals goes something like this: if $F$ is a field, take $F^{\omega}$. Since contravariant hom takes colimits to limits, its dual is an infinite product rather than an infinite direct sum, and so assuming the axiom of choice has uncountable dimension. This generalizes to show that dimension always jumps when you take duals of infinite-dimensional vector spaces.
It's clear that for vector spaces, $F^{\omega}$ never arises as a (double) dual. I'm curious about the case for modules over a commutative ring.

A: By a theorem of Specker,
$$Hom(\bigoplus_n \mathbb{Z},\mathbb{Z})\cong \prod_n \mathbb{Z}$$
$$Hom(\prod_n \mathbb{Z},\mathbb{Z})\cong \bigoplus_n \mathbb{Z}$$
where $n$ ranges through the integers. Hence $\bigoplus_n \mathbb{Z}$ is the double dual of itself.


text:
Q: Deleting what unique_ptr points to I have a coding assignment and I need to free whatever memory I allocate, so I'm trying to delete all the semaphores that my unique_ptr's are pointing to. The unique_ptrs are all in a map. The code snippets:
static map<string, unique_ptr<semaphore>> locks;

This is where all the semaphores are created using "new":
 89         unique_ptr<semaphore>& up = locks[article.title];
 90         if (up == nullptr) {
 91                 up.reset(new semaphore(6));
 92         }

Later, I try to delete the semaphores in the following code:
160         for (map<string, unique_ptr<semaphore>>::iterator it = locks.begin(); it != locks.end();
161                 ++it) {
162                 cout << it->first << endl;
163                 delete it->second;
164         }

And I get the compiler error:
news-aggregator.cc: In function âvoid processAllFeeds(const string&)â:
news-aggregator.cc:163:14: error: type âclass std::unique_ptr<semaphore>â argument given to âdeleteâ, expected pointer
make: *** [news-aggregator.o] Error 1

A: The error is clear:
delete takes a pointer as argument, not a unique_ptr. Why you are trying to delete a pointer when you are using  unique_ptr for the very same purpose? The point of using smart pointers like unique_prt or shared_ptr is that they automatically delete the pointed object when no longer needed (i.e. out of scope) or you explicitly use reset .

A: All you need to do to delete what a unique_ptr points to is to reset the unique_ptr,
it->second.reset();

A: The purpose of std::unique_ptr is to own a memory allocation and automatically delete it when it goes out of scope. IF you actually need to manually release the memory of a unique pointer early, there are ways to do it (reset, etc).
In your specific case, the memory will be automatically freed if you delete the entry in the container.
     for (auto it = locks.begin(), endit = locks.end(); it != endit; ++it) {
             cout << it->first << endl;
             delete it;
     }

Here we are deleting the element of the container, which implicitly calls the unique_ptr's destructor, which deletes the memory it owns.
You can't use this pattern if container's iterators are invalidated by a delete.
If you have full C++11 support you could use:
    for (auto it : locks) {
        std::cout << it.first << '\n';
        delete it.second;
    }

But better still:
    for (auto it : locks)
        std::cout << it.first << '\n';
    locks.clear();

The call to clear will automatically call unique_ptr::~unique_ptr on the value of each element. If you don't have C++11, just replace the for loop with an iterator loop, the call to clear will have the same effect.


text:
Q: Python: Non-Blocking + Non defunct process I would like to create a parent process, which will create many child process. Since the parent process is responsible to create the child process, the parent process would not care the status of the childs.
Since subprocess.call is blocking, it doesn't work. Therefore I use subprocess.Popen to replace call. However Popen will generate zombie (defunct) process once the child terminate(Link).
Is there a way to solve this problem?
Thanks in advance

A: After terminating or killing a process the operating system waits for the parent process to collect the child process status. You can use the process' communicate() method to collect the status:
p = subprocess.Popen( ... )
p.terminate()
p.communicate()

Note that terminating a process allows the process to intercept the terminate signal and do whatever it wants to do with it. This is crucial since p.communicate() is a blocking call.
If you do not wish this behavior use p.kill() instead of p.terminate() which lets the process not intercept the signal.
If you want to use p.terminate() and be sure the process ended itself you can use the psutil module to check on the process status.

A: There are a lot of ways to deal with this.  The key point is that zombie / "defunct" processes exist so that the parent process can collect their statuses.

*

*As the creator of the process, you can announce your intent to ignore the status.  The POSIX method is to set the flag SA_NOCLDWAIT (using sigaction).  This is a bit of a pain to do in Python; but most Unix-like systems allow you to simply ignore SIGCHLD / SIGCLD (the spelling varies from one Unix-like system to another), which is easy to do in Python:
import signal
signal.signal(signal.SIGCHLD, signal.SIG_IGN)

*Or, if this is not available for some reason or does not work on your system, you can use an old stand-by trick: don't just fork once, fork twice.  In the first child, fork a second child; in the second child, use execve (or similar) to run the desired program; and then in the first child, exit (with _exit).  In the original parent, use wait or waidpid or whatever the OS provides, and collect the status of the first child.
The reason this works is that the second child has now become an "orphan" (its parent, the first child, died and was collected by your original process).  As an orphan it is handed over to a proxy parent (specifically, to "init") which is always wait-ing and hence collects all the zombies right away.

*In addition to the double fork, you can make your sub-processes live in their own separate session and/or give up controlling terminal access ("daemonize", in Unix-y terms).  (This is a bit messy and OS-dependent; I've coded it before but for some corporate code I don't have access to now.)

*Finally, you could simply collect those processes periodically.  If you're using the subprocess module, simply call the .poll function on each process, whenever it seems convenient.  This will return None if the process is still running, and the exit status (having collected it) if it has finished.  If some are still running, your main program can exit anyway while they keep running; at that point, they become orphaned, as in method #2 above.
The "ignore SIGCHLD" method is simple and easy but has the drawback of interfering with library routines that create and wait-for sub-processes.  There's a work-around in Python 2.7 and later (http://bugs.python.org/issue15756) but it means the library routines can't see any failures in those sub-processes.
[Edit: http://bugs.python.org/issue1731717 is for p.wait(), where p is a process from subprocess.Popen; 15756 is specifically for p.poll(); but in any case if you don't have the fixes, you have to resort to methods 2, 3, or 4.]

A: torek's methods is ok!
I found another way to deal with defunct process;
we can use waitpid to recycle defunct process as needed:
import os, subprocess, time

def recycle_pid():
    while True:
        try:
            pid, status, _ = os.wait3(os.WNOHANG)
            if pid == 0:
                break
            print("----- child %d terminated with status: %d" %(pid, status))
        except OSError,e:
            break

print("+++++ start pid:", subprocess.Popen("ls").pid)
recycle_pid()
print("+++++ start pid:", subprocess.Popen("ls").pid)
recycle_pid()
time.sleep(1)
recycle_pid()

recycle_pid is non-blocking, can call as needed.

A: Please look at http://docs.python.org/2/library/multiprocessing.html
It provides an API that is very similar to threads. You can wait for the child process to exit, if you want.


text:
Q: ValueError: Unable to create dataset (name already exists) I was running a similar model previously(But slightly different) and have been saving the weights only. I deleted all the h5 files after the modification of the model and it raised this error. I have searched all the possible answers but I can't find the solution for this.
I'm a bit frustrated at the moment. What can I do to solve this issue?
my model is
model_Unet_input = UNet(Input_layer)
model_SegNet_input = SegNet(Input_layer)

model_Unet_output = UNet.layers[-3].output
model_Segnet_output = SegNet.layers[-3].output

avg = tf.keras.layers.Average()([model_Unet_output,model_Segnet_output])
data_output1 = layers.Conv2D(2, 1, strides=1,kernel_initializer='he_normal')(avg)
data_ouput2 = layers.BatchNormalization()(data_output1)
model_Unet_SegNet = Model([UNet.input, SegNet.input],data_ouput2)

model_Unet_SegNet.summary()

model_Unet_SegNet_dir ='/nobackup/projects/bddur22/eunji/dissertation/model/saved_models/Unet_SegNet_avg'
model_Unet_SegNet.compile(adam_optimizer, total_loss, metrics=metrics)
model_Unet_SegNet_checkpoint = ModelCheckpoint(os.path.join(model_Unet_SegNet_dir,'ckpt', 'unet_seg_model-{epoch:03d}-{iou_score:03f}-{val_iou_score:03f}-{loss:03f}-{val_loss:03f}.h5'), monitor='val_loss', verbose=1, save_best_only=True, mode='min')

print('model compile completed, model training starts',end='\n')

model_Unet_SegNet_history=model_Unet_SegNet.fit([x_train_processed_res,x_train_processed_res],
y_train, verbose=1,batch_size = batch_size,
epochs = epochs,validation_data([x_val_processed_res,x_val_processed_res], y_val),
callbacks =[model_Unet_SegNet_checkpoint])

The error appears like
Traceback (most recent call last):
  File "/nobackup/projects/bddur22/eunji/dissertation/data/model_UNet_SegNet_avg_test.py", line 199, in <module>
    model_Unet_SegNet_history=model_Unet_SegNet.fit([x_train_processed_res,x_train_processed_res],
  File "/users/eunji/miniconda/envs/tf-env/lib/python3.9/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/users/eunji/miniconda/envs/tf-env/lib/python3.9/site-packages/h5py/_hl/group.py", line 148, in create_dataset
    dsid = dataset.make_new_dset(group, shape, dtype, data, name, **kwds)
  File "/users/eunji/miniconda/envs/tf-env/lib/python3.9/site-packages/h5py/_hl/dataset.py", line 137, in make_new_dset
    dset_id = h5d.create(parent.id, name, tid, sid, dcpl=dcpl)
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "h5py/h5d.pyx", line 87, in h5py.h5d.create
ValueError: Unable to create dataset (name already exists)

A: This error occurs when the layer names are duplicates across the namespaces of the pre-trained model and your downstream-task network. It may be useful if you choose to call every layer of your downstream task network with unique names.  Add a name='some_unique_name' to all the layers you create to solve the problem.
data_output1 = layers.Conv2D(2, 1, strides=1,kernel_initializer='he_normal',name='conv_2d_output_1')(avg)


text:
Q: pthread member function of a class with arguments I was successful at attaching a thread to class member using the code on the bottom of this page: http://www.tuxtips.org/?p=5.
I can't figure out how to expand the code to encapsulate a method such as void* atom(void *inst) where *inst is a structure that contains various thread parameters. Specifically neither Netbeans nor I understand where the example::*f is defined and how it can be valid in the thread_maker scope.

A: I think a better solution for using things such as pthread(which take c callbacks) is to create a wrapper function so that you can use much easier to manipulate boost::functions instead. This is  similar to Using boost::bind() across C code, will it work?.
Then you could solve your problem simply with boost::bind
class myClass
{
    void atom(myStruct *data); // void return type to keep it similar to other code
    // You could change it to a void* return type, but then you would need to change the boost::function declarations
};

boost::function<void(void)> function = boost::bind(&myClass::atom,&myClassInstance,&myStructInstance); //bind your function
boost::function<void(void)>* functionCopy = new boost::function<void(void)> (function); //create a copy on the heap

pthread_t id;
pthread_create(&id,NULL,&functionWrapper,functionCopy);

The wrapper function would look like this.
void functionWrapper(void* data)
{

   boost::function<void(void)> *func = (boost::function<void(void)>* ) (data);
   (*func)();
   delete(func);
}

While this method may be more work than manually passing in data, it is much more extendable, making it easy to bind anything and pass it to start your thread.
EDIT
One last note: myClassInstance and myStructInstance should be on the heap. If they are on the stack they could get deleted before your thread starts.


text:
Q: Windows 2008 R2: can't extend C drive, mystery partitions I have a Windows 2008 R2 server running under VMware ESX 4.0.0.  I have reallocated disk space to it in order to extend the C drive, but Disk Management has "Extend Volume" greyed out.  DISKPART shows more partitions than Disk Management shows, including one after the volume I'm trying to extend, which would explain why Disk Management isn't allowing the extension.
Disk Management shows:
System Reserved / 100MB NTFS / Healthy (System)
(C:) / 39.39 GB NTFS / Healthy (Boot, Page File, Crash Dump)
10.00 GB / Unallocated

DISKPART shows:
Partition 1    Dynamic Data       992 KB    31 KB
Partition 2    Dynamic Data       100 MB  1024 KB
Partition 3    Dynamic Data        39 GB   101 MB
Partition 4    Dynamic Data      1024 KB    39 GB

My question at this point is: what the heck are partitions 1 and 4, where did they come from, why doesn't Disk Management show them, and, most importantly, can I delete partition 4 in order to extend partition 3?

A: A few hours later, "Extend Volume" became active.  The tech that performed the extension didn't look at the partitions before he did it, but now with the extension complete, it shows the same mystery partitions, with #4 "magically" relocated to after the extended #3.
The only thing that any of us can think of that was done to the system was run a "Rescan Disks" from Disk Management.  (The space extended into was created only a few hours earlier — I probably should have mentioned that — so this might be relevant.)
If and when this happens again, I'll try and remember to update here.  If anyone can confirm or deny if they're in the same situation, that would also be helpful.

A: The default partitioning layout for Windows Server 2008 R2 would be a 100 MB system partition at the beginning of the disk and one partition with the "rest". Your other partitions of about 1 MB in size might be the result of some pre-O/S "recovery" or analysis functionality.
If you have P2V-converted this system, chances are good that these partitions belong to the management suite of the hardware you no longer use.


text:
Q: PHP/MySQL - Ordering a database table by year and month separately. I'm trying to build a HTML table from a list of newsletters in a MySQL database.
It's currently ordered by descending order, and outputting as below:
https://jsfiddle.net/e8zrLjqu/
As you will see the years are in the right place, but the months of the newsletters need to be in ascending order, while keeping the years in descending order, so that each newsletter matches up with the table heading....like this example:
Do I somehow need to use DATE_FORMAT to separate the ordering? The date in the database is formatted like this: 2014-07-01
Php:
        $category_data_fields = '`id`';
        $category_where_conditions = '`publish` = \'y\' and `fund_id` = ' . $this_fund_id . ' and `category_status` = \'n\'';
        $category_result = $db->selectByStrings($category_data_fields, '`category`', $category_where_conditions, '`position`');
        $resource_data_fields = '`id`, `date`, `heading`, `file`';
        $heading_investor_newsletter = $lang_row['name'] . ' Investor Newsletters';
        $copy_investor_newsletter = $tab0 . $lang_row['investor_news_copy'] . $retn . $retn;
        $note = $tab1 . $lang_row['investor_news_note'] . $retn . $retn;
        if ($db->getNumRows($category_result) > 0)  {
            $cat_data = $db->getNextRow($category_result);
            /*
             * list selectable years
             */

            $resource_where_conditions = '`publish` = \'y\' and `category_id` = ' . $cat_data['id'];
            $date_result = $db->selectByStrings($resource_data_fields, '`resource`', $resource_where_conditions, '`date` desc');
            $current_year = '';
            $base_url_query = (_USE_SEO_URLS === true) ? $_SERVER['PHP_SELF'] . '?' : $_SERVER['REQUEST_URI'] . '&';
            if ($req->isRequest ('year')) $url_year = $req->getRequest ('year');
            if ($db->getNumRows($date_result) > 0)  {
                $copy_investor_newsletter .= $tab0 . '

January	Feburay	March	April	May	June	July	August	September	October	November	December

' . $retn;
                while ($data = $db->getNextRow($date_result))   {
                    if (substr ($data['date'], 0, 4) != $current_year)  {
                        $current_year = substr ($data['date'], 0, 4);
                        if (!isset ($latest_year)) $latest_year = $current_year;
                        if (!isset ($url_year)) {
                            $navsel = ' class="ActNav"';
                            $url_year = $current_year;
                        } elseif ($url_year == $current_year)   {
                            $navsel = ' class="ActNav"';
                            $selected_year = $url_year;
                        } else $navsel = '';
                        $copy_investor_newsletter .= $tab1 . '
';
                //      if ($url_year == $current_year) {
                            /*
                             * read and display all newsletters for selected year
                             */
                            $resource_where_conditions = '`publish` = \'y\' and `category_id` = ' . $cat_data['id'] . ' and substr(`date`,1,4) = \'' . $current_year . '\'';
                            $resource_result = $db->selectByStrings($resource_data_fields, '`resource`', $resource_where_conditions, '`date` desc');
                            if ($db->getNumRows($resource_result) > 0)  {
                        //      $copy_investor_newsletter .= $retn . $tab2 . '
' . $retn;
                                while ($data = $db->getNextRow($resource_result))   {
                                    $copy_investor_newsletter .= $tab3 . '' . $data['heading'] . '	' . $retn;
                                }
                            //  $copy_investor_newsletter .= $tab2 . '
' . $retn . $tab1;
                            }
            //          }
                        $copy_investor_newsletter .= '
' . $retn;
                    }
                }
                $copy_investor_newsletter .= $tab0 . '

' . $retn . $retn;
            }
        }
    }

A: Try:
... ORDER BY YEAR(`date`) DESC, MONTH(`date`) ASC

See also the documentation of YEAR and MONTH