text:
Q: I cannot disable multiple fields using Jquery I have two radio buttons. When users click yes, all the fields can be entered. When the user clicks the "no" radio button all the fields disable.
The problem: I'm using jquery but it is only allowing me to disable one field at a time. Is there a work around. Heres the code.
Code below:
http://jsfiddle.net/moehammoud/YBe64/1/
It works for the first field but when I start to try and make the radio button affect more than one field it doesn't apply at all
$(function(){
$("#test-y, #test-n").change(function(){
    $("#field1", "#field2").attr("disabled",true);
    if($("#test-y").is(":checked")){
        $("#field1", "#field2").removeAttr("disabled");
        $( "#field1", "#field2").css("background-color","#CCCECA");
    }
    else if($("#test-n").is(":checked")){
        $("#field1", "#field2").attr("disabled");
        $( "#field1", "#field2" ).css("background-color","gray");
    }
});

});
http://jsfiddle.net/moehammoud/PM69z/1/
I want it to work for 8 fields and a submit button.
This code is the easiest for me to understand so far. If anyone knows a fix to this particular level of code, would be awesome, any ideas would be greatly appreciated
Thanks all.
Moe

A: You have incorrect syntax for selecting multiple elements in jQuery. If you want to select #field1 and #field2, the syntax is:
$("#field1, #field2")

When you write $("#field1", "#field2"), it's equivalent to $("#field2").find("#field1").
If you're repeatedly selecting several IDs like this you probably should give them a class so you can just specify the class name in the selector, rather than listing all the IDs separately.

A: It should be
$(function () {
    $("#test-y, #test-n").change(function () {
        var checked = $("#test-y").is(":checked");
        $("#field1, #field2").prop("disabled", checked).css("background-color", checked ? "#CCCECA" : "gray");
    });
});

Demo: Fiddle
Problems

*

*use .prop() to set the disabled state instead of .attr() - prop vs attr

*You need to use multiple selectors to select different elements

*You used the id field1 twice instead of field1 and field2

A: $("#field1", "#field2").attr("disabled" , true);

Isn't the correct way for your wish. I suggest you make use of classes and/or the name attribute. You can also call the function on load by
$("input[name=test]").change();

That makes less code.
$(function() {
$("input[name=test]").change(function() {
    if($("#test-y").prop("checked") == true) {
        $(".field").prop("disabled" , false);
        $(".field").css("background-color" , "#ccceca");
        }
    else {
        $(".field").prop("disabled" , true);
        $(".field").css("background-color" , "gray");
        }
    });
$("input[name=test]").change();
});

http://jsfiddle.net/Dinizworld/Ckz8c/


text:
Q: Table eats away tops of letters - what should I adjust to fix it? I have a table in an MS Word document created by FineReader, an OCR software. I use MS Word 2007. Now some of the words appear clipped at the top, like this:

What should I adjust to make the table look normal?

A: It appears that both tops and bottoms are clipped. It happens when line height is set too low. Try to adjust it to 1.

A: What should I adjust to make the table look normal?
You need to change the spacing before/after the paragraph and/or the line spacing.

*

*Select the paragraphs you want to change.
Tip: If you decide you want to change line spacing for the entire
  document, and not just specific paragraphs, press Ctrl+A. That
  combination of keys selects all text in your document.

*Choose Home > Line and Paragraph Spacing.

*Choose the number of line spaces you want or choose Line Spacing Options at the bottom of the menu, and then select the options you
  want in the Paragraph dialog box under Spacing.

If you want to change the spacing before or after the selected
  paragraphs, in the Before or After box and enter the amount of space
  that you want.

Source Change the line spacing in Word

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gaps and Islands with continuous ranges from previous row I have the following set of Data

SET
START
END
QTY

A
1
10
10

A
11
20
10

A
21
30
10

B
51
60
10

B
61
70
10

B
81
90
10

B
91
100
10

C
101
200
100

C
201
300
100

C
401
500
100

And wanted to have the following result:

SET
START
END
TOTAL_QTY

A
1
30
30

B
51
70
20

B
81
100
20

C
101
300
200

C
401
500
100

So it will check previous "End" range and if it's a continuous from the previous "Start" range then it will be grouped into one "Start - End" ranges with the Sum of Qty.
I don't know how this can be achieved with Oracle SQL, can anyone help?

A: select   "SET"
         ,min("START") as "START"
         ,max("END")   as "END"
         ,sum(QTY)     as  QTY
from     (
         select   t.*
                  ,count(mrk) over(partition by "SET" order by "START") as grp
         from    (
                 select  t.*
                        ,case when "START" - lag("END") over(partition by "SET" order by "START") > 1 then 1 end as mrk
                 from    t
                 ) t
         ) t

group by "SET", grp

SET
START
END
QTY

A
1
30
30

B
51
70
20

B
81
100
20

C
101
300
200

C
401
500
100

Fiddle


text:
Q: Should my schizophrenic console/gui Qt5 program use QApplication or QCoreApplication? My program will either open a GUI or not depending on some commandline parameters. Right now I am instantiating QApplication for my main event loop, but noticed that my program aborts when run from a headless machine (missing xorg/xcb) unless i specify some environment variables to trick it into believing there is an xorg running.
When I instead instantiate QCoreApplication I don't have access to activeWindow(). The code requiring activeWindow() will never run in the cases when the program is run headless (that is the purose of the commandline parameters).
So what I am asking is, would it be possible to make QApplication run without problems even on a headless machine, and simply not show any GUI?
What are my other options?

A: No, this is not possible.
But you can create QCoreApplication or QApplication in dependent from command line args.


text:
Q: Passing back multiple service uris I have created an asp.net web api 2 controller to manage a logical asset. As usual, the post creates it and returns the uri to the asset and the delete removes it, but I have 2 puts to perform seperate actions on the asset, so my code looks like:
public class Controller : ApiController
{
    public IHttpActionResult Post(Stuff stuff)
    {
        var id = CreateNewStuff(stuff);

        return CreatedAtRoute("DefaultApi", new { id = this.id }, id);
    }

    [HttpPut]
    public IHttpActionResult ActionA(int id, ActionAStuff stuff)
    {
        // Perform action A

        return Ok();
    }

    [HttpPut]
    public IHttpActionResult ActionB(int id, ActionBStuff stuff)
    {
        // Perform action B

        return Ok();
    }

    public IHttpActionResult Delete(int id)
    {
        // Delete the asset

        return Ok();
    }
}

So that the routing understands this, my routing rules are (including the default rule):
config.Routes.MapHttpRoute(name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}");
config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional });

This works, and feels like the system neatly seperates the put code by action, and ensures the system will reject requests for actions we do not support.
The problem is that the client that creates the asset via post does not know what the put (action) uris are, in the way it does for the asset uri via the location header returned from the post. If we change the uri form in future, the clients would break as they would be manually creating uris.
What is the correct way to either return multiple servicepoint uris from the post, or just do the above better.

A: Use Route for differentiating the actions.
For Example:
[RoutePrefix("api/Admin")]
public class Controller : ApiController
{
    [Route("ActionA")
    [HttpPut]
    public IHttpActionResult ActionA(int id, ActionAStuff stuff)
    {
        // Perform action A

        return Ok();
    }

    [Route("ActionB")
    [HttpPut]
    public IHttpActionResult ActionB(int id, ActionBStuff stuff)
    {
        // Perform action B

        return Ok();
    }

}

Then enable Attribute Routing in your webapiconfig.cs
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            // Other Web API configuration not shown.
        }
    }

finally in your client you can differentiate the put URIs like below:
http(s):///api/Admin/ActionA
http(s):///api/Admin/ActionB

A: One should use Route prefix for each method for differentiating.
[Route("ActionA")
[HttpPut]
public IHttpActionResult ActionA(int id, ActionAStuff stuff)
{
    // Perform action A

    return Ok();
}

When we configure the route using Route config from config.Routes.MapHttpRoute it has to be proper order as it added to stack and used from stack.
Once it founds the any entry from the routing table it will try to execute it.
So its better way is to use the Route Prefix.

A: You could add a link header to the result of the POST method:

*

*In order to add a custom header to the IHttpActionResult class you could define an extension method, for example:
public static class HttpActionResultHeaderExtensions
{
    public static IHttpActionResult AddHeader(this IHttpActionResult action,
                                              string headerName,
                                              params string[] headerValues)
    {
        return new HeaderActionResult(action, headerName, headerValues);
    }

    private class HeaderActionResult : IHttpActionResult
    {
        private readonly IHttpActionResult action;

        private readonly Tuple<string, IEnumerable<string>> header;

        public HeaderActionResult(IHttpActionResult action,
                                  string headerName,
                                  IEnumerable<string> headerValues)
        {
            this.action = action;

            header = Tuple.Create(headerName, headerValues);
        }

        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = await action.ExecuteAsync(cancellationToken);

            response.Headers.Add(header.Item1, header.Item2);

            return response;
        }
    }
}

*Add route attributes:
[System.Web.Http.RoutePrefixAttribute("api/stuff")]
public class Controller : ApiController
{
    [System.Web.Http.HttpPut]
    [System.Web.Http.RouteAttribute("ActionA", Name = "ActionA")]
    public IHttpActionResult ActionA(int id, ActionAStuff stuff)
    {
        // your code
    }

    [System.Web.Http.HttpPut]
    [System.Web.Http.RouteAttribute("ActionB", Name = "ActionB")]
    public IHttpActionResult ActionB(int id, ActionBStuff stuff)
    {
        // your code
    }
}

*Extend the POST method adding the header link to the result:
public IHttpActionResult Post(Stuff stuff)
{
    var id = CreateNewStuff(stuff);

    var actionALink = this.Url.Link("ActionA", new { id = id });

    var actionBLink = this.Url.Link("ActionB", new { id = id });

    return CreatedAtRoute("DefaultApi", new { id = id }, id)
        .AddHeader("Link", $"<{actionALink}>; rel=\"ActionA\"",
                           $"<{actionBLink}>; rel=\"ActionB\"");
}

*Extend configuration:
config.MapHttpAttributeRoutes();

config.EnsureInitialized();

A: Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API
You might use Attribute Routing in Web Api to solve your problems. Your Controller Action should be like this,
 [Route("ActionA/{id}"]
  [HttpPut]
public IHttpActionResult ActionA(int id, ActionAStuff stuff)
{
    // Perform action A

    return Ok();
}

    [HttpPut]
   [Route("ActionB/{id}"]
    public IHttpActionResult ActionB(int id, ActionBStuff stuff)
       {
            // Perform action B

            return Ok();
        }

and your HTTP request is http://localhost:1317/ActionA/1 and http://localhost:1317/ActionB/1


text: Q: ACF custom field map how do when address is 'Unnamed Road'? I have installed ACF custom field plugin and I added map custom field. It works well but when I set 'Unnamed Road' from Wordpress, it returns an empty map without pin locator. There is a way that returns a map with pin locator in the right position and the possibility of change address 'Unnamed Road' in the other custom name?


text:
Q: SharePoint - change the language of the site based on the browser language settings I have a multi-lingual site collection and I would like the site to load on the language specified in the browser settings of the user.
What is the best way to accomplish this?
Please provide some examples.
Thank you very much.

A: In SharePoint 2010, use the Multilingual user interface:

SharePoint Server 2010 selects the language in which to display pages of a site collection by using the first rule that applies from the following list:

*

*Does the user have a preferred language for this site collection on this computer? If so, use the user's preferred language.

*Is the language preference that is specified in the Web browser one of the supported languages for the page? If so, use the preferred language of the browser.

*Otherwise, use the default, primary language for the site collection.

(note: emphasis mine)
For an example of how to configure the multilingual user interface, see Use sites in multiple languages in SharePoint 2010.


text:
Q: Kubernetes one user per node in the cluster I've already manage to have max one pod with containerized application per node. Now I want to create Kubernetes cluster in which each user will have access to one, personal node. As a result I want to have architecture where each user will work in isolated environment. I was thinking about some LoadBalancing with Ingress rules, but I am not sure it's a good way to achieve this.
Architecture

A: Kubernetes in general is not a fit for you.
If you're trying to do "max 1 per pod node" or "a node for every user", you should not force yourself to use Kubernetes, maybe what you're looking for is just virtual machines.


text:
Q: How contact sql with tableau so that if there was a mistake in report he marked it as red? Suppose i have data source for tableau to perform report.
dbo.myreport
Also i check is the value(s) right or wrong?
Let me provide picture to be more clear

i create query that check is the value(s) right or wrong. For example 6,6 is wrong and in dbo.checkmyreport i have structure
date;variable;value;right-wrong
07.05.2021;x1;6,6;wrong

how to do to if value from dbo.checkmyreport marked is wrong then it must automatically must be marked as red in tableau report.
Is there possible?

A: I'm assuming that you have already added this data into Tableau and kept the column names as such right? And you have already created the desired bar chart.
In Tableau add the "right-wrong" dimension to the Color marks and set the colors as appropriate. That should let you color all the bars that are labelled as "wrong" in a specific color.


text:
Q: Why am I losing bytes? I am simply trying to dynamically declare an array in C
The code is as follows:
int maxSize = 3;
int *answer;
answer = malloc(maxSize * sizeof(int));
printf("this is max size: %d\n", maxSize);
printf("this is the mult result: %d\n", maxSize * sizeof(int));
printf("size of answer in bytes: %d\n", sizeof(answer));
printf("size of the answer array: %d\n", sizeof(answer) / sizeof(answer[0]));

Printing the result gives me:
this is max size: 3
this is the mult result: 12
size of answer in bytes: 8
size of the answer array: 2

I don't think it's an architecture thing (rather me being inexperienced), but I am running this on a Macbook Pro.
I do not understand why is malloc only allocating 8 bytes instead of 12 bytes for the integer array.

A: Sizeof(answer) is returning the size of the variable answer in memory, which is the same as sizeOf(int *). Since your computer architecture is 64-bit, the size of a pointer is 8 bytes, which is your result. Your computer is indeed allocating 12 bytes, but you don't really have a way to validate that.


text:
Q: How to track location in background with Flutter? I have been working on a team developing an app in Flutter. We need to track the distance travelled using the GPS but the challenge is that Flutter no longer allows both foreground and background location tracking (even with a coarse level of accuracy).
Based on a review of the latest Google guidelines, it seems like Google should allow our app to track the device when it's in the background, but it does not. In fact, turning on foreground and background location services seemed to be working a month or two back. We have tried both the location and geolocation packages, to no avail. Either of them immediately stops tracking when the app is in the background and we get one big jump in location when the app is returned to the foreground.
Here's what we've tried
AndroidManifest.xml
...
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
...

App Code Using Geolocation
...
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
 return Future.error('Location services are disabled.');
}

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

//Permission returns denied Location
//this is due to the background permission in the android manifest
//turn off background permission and the permission is allowed
if (permission == LocationPermission.deniedForever)
 return Future.error(
     'Location permissions are permanently denied, we cannot request permissions.');
}
...

App Code Using Location
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
 _serviceEnabled = await location.requestService();
 if (!_serviceEnabled) {
   print('Service could not be enabled');
   return false;
 }

// This code throws and exception even if I respond to the
// Google prompts and I select allow location service and all the time access
try {
 await location.enableBackgroundMode(enable: true);
} catch(error) {
 print("Can't set background mode");
}

Any guidance for how to achieve this would be much appreciated.

A: Natively, Flutter still doesn't support background localization.
I've seen some android-specific forms, but nothing was effective.
But actively looking, I found this lib:
https://pub.dev/packages/flutter_background_geolocation
It's a paid lib, to be used in production (for android keys. iOS is free). And it works perfectly.
Despite having a cost (which is unique and for life) the cost benefit is very good.
Highly recommend.
Note: Their documentation and support is wonderful.

A: Currently, I am using the background_fetch because everyone can't afford flutter_background_geolocation pricing BTW this plugin is also from the same company
background_fetch: ^0.7.2

So far it's working fine in Android will work nicely but in ios, it will take some time reason being Apple's background process algorithm once it will get used then It will be fine in apple as well.
Here is the link-:
https://pub.dev/packages/background_fetch
Setup
   int status = await BackgroundFetch.configure(
    BackgroundFetchConfig(
        minimumFetchInterval: 30,
        stopOnTerminate: true,
        enableHeadless: false,
        startOnBoot: false,
        requiresBatteryNotLow: false,
        requiresCharging: false,
        requiresStorageNotLow: false,
        requiresDeviceIdle: false,
        requiredNetworkType: NetworkType.NONE),
        (taskId){
         // This is the fetch-event callback.
        },

       (taskId){
      // This task has exceeded its allowed running time.
      // You must stop what you're doing and immediately finish(taskId)
    });
    print('[BackgroundFetch] configure success: $status');

A: The location plugin works perfectly and is free to use.
There could be several reasons that it did not work for you like some other external application killing your app in background or just your devices default OS could be stopping the application after a while in background.
Call the service enabling code in the initState of your Stateful Widget.
You can listen to the background changes as:
location.onLocationChanged.listen((LocationData currentLocation) {
  // do whatever you want with new location
});

A: You need this flutter_background_service package for this.
This package will help you to run the location service in a separate isolate.

A: Try using flutter_background_service
flutter_background_service: ^2.4.6

Required setup:
await service.configure(
androidConfiguration: AndroidConfiguration(
  onStart: onStart,
  isForegroundMode: true,
  notificationChannelId: 'my_foreground',
  initialNotificationTitle: 'AWESOME SERVICE',
  initialNotificationContent: 'Initializing',
  foregroundServiceNotificationId: 888,
),);

Use geoloactor within this background service,
@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {

  // use geolocator to get location here

}

This will shoot a notification and runs your code inside onStart on a separate isolate. The code inside isolate runs (even when the app is cleared from the recent) till you stop the background service.


text:
Q: How can I control my images and create an animation with it in my listview? I am currently working with a listview where I gather images. I do it succesfully but I now wish to add an animation to it. I start off by having the images completely 0 in terms of opacity and then I wish to increase it with a .FadeTo(1, 1000, Easing.SinIn); once the images has been gathered.
As I am working with a listview I cannot use x:name so I am not sure how to solve it with a listview.
This is my current code:
<ListView x:Name="listview" >
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <AbsoluteLayout>

                          <Image Source = "{Binding image}" Opacity = "{Binding animation}"/>

                        </AbsoluteLayout>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
 </ListView>

Code page:
public class info
{
   public string image {get; set;}
   public int animation {get;set;}
}

List<info> myList = new List<info>();

    async void loadCategories()
    {

        var getInfo = await databaseCS.gettheinfo();

        listview.ItemsSource = null;
        myList = new List<info>();

        foreach (var theitems in getInfo["results"])
        {
           myList.add (new info()
           {
              image = theitems["image"].ToString(),
              animation = 0
           });
        }

      //how can I now create a FadeTo function to make the images return to 1 again once it has been gathered?
      listview.ItemsSource = myList;
     }

UPDATED CODE when I use the CustomImage code provided by the answer below!
The bool:
public class info : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged == null)
                return;

        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private bool _result;

    public string image {get; set;}

    public bool isImageShowing
    {
        get {
                System.Diagnostics.Debug.WriteLine("GET");
                return _result;
            }

        set {
                System.Diagnostics.Debug.WriteLine("SET");
                _result = value;
                OnPropertyChanged("IsImageShowing");
        }
    }
}

When i add the image to the list:
myList.add (new info()
{
       image = theitems["image"].ToString(),
       isImageShowing = true
});

Code runs and the images appear, but i see no animation. In the log i get "SET" 3 times as I gather 3 images. The last part to complete this is to connect the public string image {get; set;}/my <Image> in xaml to the CustomImageif I am not mistaken but I am not quite sure on how to achieve this.

A: Since you need to perform the animation on your Image, I would say define your animation on an extension of the Image class.
I would also suggest that you create a bindable property on the extension to toggle the visibility through your animation.
something like below
public class CustomImage : Image
{
    public static readonly BindableProperty IsImageShowingProperty = BindableProperty.Create("IsImageShowing", typeof(bool), typeof(CustomImage), false, BindingMode.Default, propertyChanged: OnImageShowingChanged);

    private static void OnImageShowingChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if(newValue == null) return;

        var img = (CustomImage)bindable;
        var b = (bool)newValue;

        if(b)
        {
            img.ShowImage();
        }
        else
        {
            img.HideImage();
        }
    }

    public bool IsImageShowing
    {
        get {  return (bool)GetValue(IsImageShowingProperty); }
        set { SetValue(IsImageShowingProperty, value); }
    }

    public void ShowImage()
    {
        this.FadeTo(1, 1000, Easing.SinIn);
    }

    public void HideImage()
    {
        this.FadeTo(0, easing: Easing.SinIn);
    }
}

Now in your Info class, instead of having the Animation integer property, create a bool property to toggle the image animation and bind it to the IsImageShowingProperty. Once you have added the data to your ListView.ItemsSource, go through and toggle the boolean property on each item and it should run the animation.
Also make sure to implement the INotifyPropertyChanged on your Info class.
UPDATE:
if you need to run the animation when the data loads add this to your CustomImage class
protected override void OnBindingContextChanged()
{
    base.OnBindingContextChanged();
    if(IsImageShowing)
    {
        this.ShowImage();
    }
}

Also make sure to set the image Opacity to 0 when your initialize your CustomImage, otherwise you wouldn't see the fade in effect


text:
Q: ASP.NET Core won't run in IIS after upgrade to v1.1 I've upgraded my project.json to use the new v1.1 of asp.net core and now when I try to start IIS Express to debug, I get the following errors:

The program '[8784] dotnet.exe' has exited with code -2147450749
  (0x80008083).
The program '[7352] iisexpress.exe' has exited with code
  0 (0x0).

My upgraded project.json:
"dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.1.0",
      "type": "platform"
    },
    "Microsoft.ApplicationInsights.AspNetCore": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.1.0",
    "Microsoft.AspNetCore.Routing": "1.1.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
    "Microsoft.Extensions.Configuration.Json": "1.1.0",
    "Microsoft.Extensions.Logging": "1.1.0",
    "Microsoft.Extensions.Logging.Console": "1.1.0",
    "Microsoft.Extensions.Logging.Debug": "1.1.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
    "Microsoft.IdentityModel.Tokens": "5.1.0",
    "Microsoft.AspNetCore.Authentication": "1.1.0",
    "Microsoft.AspNetCore.Authentication.JwtBearer": "1.1.0",
    "Microsoft.AspNetCore.Authentication.Cookies": "1.1.0",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.0",
    "Microsoft.EntityFrameworkCore": "1.1.0",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "SapientGuardian.EntityFrameworkCore.MySql": "7.1.10",
    "AutoMapper": "5.1.1"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview4-final"
  },

  "frameworks": {
    "netcoreapp1.1": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

Maybe I am missing something in my project.json needed for the upgrade? Or one of the packages is not cooperating with v1.1? Any help is appreciated.
NOTE: When I change back to 1.0 everything runs fine.

A: With the help of HenkMollema's comments and our friends at the Core team I was able to get this resolved.  Please see this github issue for the answer.
The key was updating all of the packages as suggested to reference 1.1.0, or their appropriate updated package version for 1.1.0.  The table in the github link above lists the proper references for all packages that were updated in the v1.1 release.
I also installed the v1.1 SDK and Runtime available here.


text:
Q: How to swap tasks in a background thread which should do a callback My app should update its information about a web service. This work should be done in a separate thread. I don't want to do a simply async call from my ViewController because their is a lot of other work which have the thread to do.
If all responses are received and performed the other thread should call a delegate on my ViewController.
Can you give me some tips and rudiments how to implement that?

A: You can do this using NSURLConnection, but the code is quite complex.
I've written a simple class for making asynchronous web requests on a background thread. You can find it here: https://github.com/nicklockwood/RequestQueue
It works in a similar way to the NSOperationQueue that jsd suggested (you can actually use it with an NSOperationQueue if you want), but I think you'll find it's easier to use.
Here is how you would make your request from your view controller using my class:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://someurl?foo=bar"]];
[[RequestQueue mainQueue] addRequest:request completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    //do something with the response

}];

Because it uses blocks, you don't need to create a delegate method, you can just put your handling code directly inside the callback (where i've put the "do something with response" comment).
The code inside that callback will be called on the main thread, so it's safe to update your UI in there, however it will be called several seconds after you actually start the request, after it finishes downloading in the background - just like a delegate method.

A: You can use NSOperationQueue to perform an ordered series of tasks on a background thread.  If you want to update a web service then perform tasks in sequence, you could create a new class that used NSURLConnection to perform the update, then when the NSURLConnection finishes, you could start an NSOperationQueue.


text:
Q: Expected time of n events to complete What is the expected time do i have to wait until n events are completed each distributed in exponential time $\mu$?
I thought that $1/\mu$ is the expectation for the first since the events are coming as poisson processes and their interarrivals times are exponential. So for the $n$ events it is $n/\mu$. Is it correct?

A: If their distributions are consecutive (i.e. time for the second does not start until the first is done and so on) then you are correct.
If their distributions are concurrent (i.e. time for each of them starts with $t=0$) and they are independent, then the expected time for the first to occur is $\frac{1}{n\mu}$, the expected time between the first and the second occurrence is   $\frac{1}{(n-1)\mu}$ and so on up to the expected time between the penultimate and the final occurrence is   $\frac{1}{\mu}$ by the memoryless property, making the total time $\dfrac1\mu H_n$ where $H_n$ is the $n$th harmonic number.


text:
Q: Need to show the div before the page loads I want to show this codepen html code before loading the page and then after some user's input the page loads.
Basically I am trying to show the below codepen div on page load which will ask the user to select something and then upon successful selection the page loads with the remaining contents. But I need a little help. I also tried window.load() in javascript but no result.
https://codepen.io/leenalavanya/pen/XdrOzg?editors=1100

function g(a, n) {
  var divs = "";
  for (var s = 0; s < 50; s++) {
    divs += '

';
  }
  document.getElementById(a).innerHTML += divs;
}
g('h1');
g('h3');

function f(x, n, a) {
  var t = 0;
  setInterval(function() {
    if (t < 50) {
      x.style.bottom = (46 * t * n - t * t) + 20 + 'px';
      x.style.height = 10 - t / 4.6 + 'px';
      x.style.width = 10 - t / 4.6 + 'px';
      if (t > 15) {
        x.style.left = (a * t + 150) + 'px';
        x.style.bottom = (46 * t * n * n - t * t) + 20 + 'px';
      }
      t += 1.3
    }
  }, 50)
}

function Launch() {
  if ($('.revealleft,.revealright').hasClass('revealed')) {
    var i;
    for (i = 0; i < 150; i++) {
      var x = document.getElementsByClassName('div')[i];
      var a = parseInt(x.id);
      x.style.left = '150px';
      f(x, 1 + ((Math.random() * 5) + 1) / 100, a)
    }
  }
}

function getRandom() {
  return Math.random() * 10 - 5
}
html,body{background:#e6e6e6;width:100%;height:100%;padding:0;margin:0;overflow:hidden}
.reveal{width:600px;height:350px;box-shadow:0 0 30px -5px grey;background:#fff;margin:calc(50vh - 175px) auto;max-width:96%;position:relative;overflow:hidden}
.revealleft,.revealright{width:50%;background:#dc143c;height:100%;position:absolute;left:0;transition:all 1s}
.revealright{left:50%}
.revealleft.revealed{left:-50%}
.revealright.revealed{left:100%}
.reveal button{opacity:.99;margin:15px;padding:8px 15px;background:#dc143c;border:2px solid #fff;border-radius:6px;color:#fff;cursor:pointer;position:absolute}
.reveal button:hover{background:#fff;color:#dc143c;outline:0;border-color:#dc143c}
.reveal button:focus{outline:0}
h1{font-family:'Montserrat',sans-serif;font-size:4vw;margin:50px 30px 35px;text-align:center;color:#dc143c}
p{margin:0 30px;font-family:'Montserrat',sans-serif;color:grey;font-size:.8em;line-height:1.7em}
img{width:160px;float:right;margin:5px 0 5px 20px}
.ball{width:10px;height:10px;border-radius:100%;position:absolute;bottom:20px;left:50%;background:#dc143c}
#h1,#h3{position:absolute;bottom:-15px;width:300px;height:100%;z-index:100;pointer-events:none;-webkit-transform-origin:center bottom}

  <button onclick="$('.revealleft,.revealright').toggleClass('revealed');Launch()">Reveal</button>

A SURPRISE!

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis augue luctus, auctor eros at, commodo purus. Suspendisse potenti. Ut vel blandit nibh. Mauris luctus mollis turpis, at euismod
    quam fermentum iaculis. Donec non lectus vel purus porta ornare et vitae est. Sed porta luctus purus, at hendrerit lorem congue nec.

A: The proper way of doing this:
1- Let the page and scrips load normally.
2- Get User inputs with proper UI (custom HTML forms or prompt)
You can show the input form after the page load
3- Manipulate the DOM using javascript according to the user's inputs.
You can add or manipulate all elements after getting the inputs of the user.


text:
Q: Morphia: retrieve MongoDb document as java object I can insert easily a java object into MongoDb database by using Morphia. Now, I want to retrieve the document and mapped it as java object. The MongoDB document is like this:
{
    "Name":"XXX",
    "Fingertemplate":{ "immutable" : { "size" : { "x" : 388 , "y" : 374} , "minutiae" : [ ........

My sample code is shown below:
@Entity(value="fingertable", noClassnameStored=true)
public class RecordFingerTemplate {
    @Id private ObjectId id;
    @Property private String name;
    @Embedded private FingerprintTemplate fingertemp;
    public RecordFingerTemplate (){

    }
    public RecordFingerTemplate(String name)
    {
        this.name=name;
    }
    public ObjectId getId() {
        return id;
    }

    protected void setId( final ObjectId id ) {
        this.id = id;
    }
    public FingerprintTemplate getTemplate(){
        return fingertemp;
    }
    public void setTemplate(FingerprintTemplate template){
        this.fingertemp=fingertemp;
    }
}

and to save the object into the database I'm using datastore.save(Object) , it works perfectly
Now I want to retrieve the document and getting the fingerprint template object.
List<RecordFingerTemplate> result=datastore.createQuery(RecordFingerTemplate.class)
                .field("name").containsIgnoreCase("john")
                .order("name")
                .asList();

Error: ** org.mongodb.morphia.mapping.MappingException:Error setting
  value from converter (PassthroughConverter) for ImmutableTemplate.size
  to {"x": 388, "y.........**

A: Try moving/adding the @Embedded annotation to FingerprintTemplate and explicitly calling map() on your types.  The lazy mapping has some gaps in it and I'm afraid you might be slipping through such a case.


text:
Q: Given that $f:G\to G$ on a group $G$, defined by $f(x)=x^3$, is an isomorphism, how do I show that $G$ is abelian? Given that $f:G\to G$ on a group $G$, defined by $f(x)=x^3$, is an isomorphism, how do I show that $G$ is abelian, please?

A: Note that
$$
\forall a,b \in G: \quad ababab = (ab)^{3} = a^{3} b^{3} = aaabbb.
$$
Hence,
$$
\forall a,b \in G: \quad baba = aabb, \quad \text{or equivalently}, \quad (ba)^{2} = a^{2} b^{2}.
$$
Using this fact, we obtain
\begin{align}
\forall a,b \in G: \quad (ab)^{4} &= [(ab)^{2}]^{2} \\
                                  &= [b^{2} a^{2}]^{2} \\
                                  &= (a^{2})^{2} (b^{2})^{2} \\
                                  &= a^{4} b^{4} \\
                                  &= aaaabbbb.
\end{align}

*

*On the other hand,
\begin{align}
\forall a,b \in G: \quad (ab)^{4} &= abababab \\
                                  &= a (ba)^{3} b \\
                                  &= a b^{3} a^{3} b \\
                                  &= abbbaaab.
\end{align}

*Hence, for all $ a,b \in G $, we have $ aaaabbbb = abbbaaab $, which yields
$$
f(ab) = a^{3} b^{3} = b^{3} a^{3} = f(ba).
$$
As $ f $ is injective, we conclude that $ ab = ba $ for all $ a,b \in G $.Hence $G$ is an abelian group

A: Answer of the changed question: Note that for any $a,b \in G$, $xy=f(x^{-1})f(y^{-1})=f(x^{-1}y^{-1})=f((yx)^{-1})=yx$.Hence $G$ is abelian.


text:
Q: Android app update, assets update I have an  app and it uses .txt files from assets folder. In assets folder are more  directories in some depth.
Later I will want to add new files to this assets folder so I'll have a new apk(cause files in assets are part of the apk).
The question:  So what happens when someone, who is using my app, wants to update my app(with new files in assets) through Google Play, will it uninstall his old version and install the new one or how he receive these new files?
Or simpler: What happens during an app update?
Could someone make me keen vision in this a little? Thanks.

A: The old app is just replaced by the new app.
You don't have to worry about that. Apps are always installed completely without loosing data. That is, the .apk file is just replaced. So your assets will be also updated automatically.
Here an example:
Google Play Store downloads the new .apk file.
Next, it replaces the old apk file in /data/app/ by your new apk file.
That means that all the stuff that is in your new app is now available.
In this way the whole application is replaced.


text:
Q: Regex to wrap all words in span, excluding img elements I am trying to find a regex, in order to wrap all the words of a text in spans. I am using the following code:
$this.html($this.text().replace(
        /([^\s]*\s)/g, "$1"));

where this is referred to a div element. However, img and a elements, which are inside div, disappear. I tried to change the regex into:
$this.html($this.text().replace(
        /([^(\s |  | )]*\s)/g, "$1"));

but i didn't fix the problem.
Can someone help me?

A: replace non-whitespace (\S) where there is one or more (+) with a function, taking the match as a parameter.

var str = 'Hello dear world  Hello dear world ';

function replaceThings(str) {
  var pre = "";
  var modString = str
    .replace(/\S+/ig, function(word) {
      return pre + word + ""
    })
  .split(pre + "<img").join("").join("/>")
  .replace(//ig, function (img){
    return img.split(pre).join("").split("").join("")
  })

  return modString;
}
console.log( replaceThings(str) );

document.body.innerHTML = replaceThings(str)


text:
Q: Failed to flash file gapps-kk-20140606-signed.zip Genymotion All the times I try to install Google Play Services in my emulator I am getting the message:
Failed to flash file gapps-kk-20140606-signed.zip Genymotion

Step-by-step:

*

*I downloaded the gapps-kk-20140606-signed.zip

*I drag and drop it to emulator

*Emulator identify the flashable file and ask me if I wanna flash it...

*After some loading time comes the message of fail.

Important information:

*

*My emulator is Genymotion 2.3.1 - Android 4.4.4 Kitkat.

*I already installed the Genymotion-ARM-Translation and it flashed ok.

*I am using a Mac 10.10.1, the option Open Save Files of Safari is not checked.

A: Have your tried
    adb push gapps-kk-20140606-signed.zip  /sdcard/


text:
Q: Audio analysis and frequency peak I'm getting aan audio signal from a WAV file, and would like to get the peak frequency.
With SoX spectrogram, I can "see" this frequency (here 12kHz):

My need is to find this value, numerically, because it can be fluctuant according to source.
Regards,


text:
Q: Problem with updating Ubuntu 20.04 update-initramfs: Generating /boot/initrd.img-5.4.0-53-generic
I: The initramfs will attempt to resume from /dev/sda5
I: (UUID=35ea86ce-fbf6-4344-a6f5-19dc7c85efae)
I: Set the RESUME variable to override this.


text:
Q: React Native - Track Screen react-naviagtion I'm using react navigation for navigate screen. I used nested navigation, TabNavigator and StackNavigator. I would like to track the screen inside HeaderCustom so i can call different function when reached different screen.
Navi.js
import TopNavHeader from '../App/Components/HeaderCustom';
const mainNav = TabNavigator({
  Home: {
    screen: HomeScreen,
  },
  Live: {
   screen: LiveScreen,
  },
  Radio: {
   screen: RadioScreen,
  },
} );

export const mainStack = StackNavigator({
  Home: {
    screen: mainNav,
    navigationOptions: {
      header: (
        <HeaderCustom/>
      ),
    },
  },
  Content: { screen: ContentScreen },
});

HeaderCustom.js
class HeaderCustom extends React.Component {
    constructor(props) {
        super(props);
    }

    _CallDiffFunc(){
     if(screen == "home"){
      //do something
     }else{
      //do something
     }
    }

    render() {
        return(
            <View style={styles.topcontainer}>
                <Icon />
                <Icon />
                <Icon />
            </View>
        );
    }
}

module.exports = HeaderCustom;
AppRegistry.registerComponent('myApp', () => HeaderCustom);

A: navigationOptions prop can be a function that takes navigation as parameter.
Example
export const mainStack = StackNavigator({
  Home: { screen: mainNav },
  Content: { screen: ContentScreen },
}, {
  navigationOptions: ({navigation}) => ({
    header: (
      <HeaderCustom routeName={navigation.state.routeName}/>
    )
  }),
});

class HeaderCustom extends React.Component {
    constructor(props) {
      super(props);
      console.log(props.routeName); // Will log current Route's name
    }

    render() {
        return(
            <View style={styles.topcontainer}>
                <Icon />
                <Icon />
                <Icon />
            </View>
        );
    }
}

module.exports = HeaderCustom;


text:
Q: float pointer in ctypes python and pass structure pointer I'm trying to pass a structure pointer to the API wrapper, Where the struct is containing float pointer member. I'm not sure that how we can pass float pointer value to the structure.
/Structure/
class input_struct (ctypes.Structure):
    _fields_ = [
        ('number1', ctypes.POINTER(ctypes.c_float)),
        ('number2', ctypes.c_float),
        #('option_enum', ctypes.POINTER(option))
    ]

/wrapper/
init_func = c_instance.expose_init
init_func.argtypes = [ctypes.POINTER(input_struct)]

#help(c_instance)
inp_str_ptr = input_struct()
#inp_str_ptr.number1 = cast(20, ctypes.POINTER(ctypes.c_float)) # want to pass pointer
inp_str_ptr.number1 = 20 # want to pass as float pointer
inp_str_ptr.number2 = 100

c_instance.expose_init(ctypes.byref(inp_str_ptr))
c_instance.expose_operation()

A: You can either create a c_float instance and initialize with a pointer to that instance, or create a c_float array and pass it, which in ctypes imitates a decay to a pointer to its first element.
Note that ctypes.pointer() creates pointers to existing instances of ctypes objects while ctypes.POINTER() creates pointer types.
test.c - for testing
#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

typedef struct Input {
    float* number1;
    float  number2;
} Input;

API void expose_init(Input* input) {
    printf("%f %f\n",*input->number1, input->number2);
}

test.py
import ctypes

class input_struct (ctypes.Structure):
    _fields_ = (('number1', ctypes.POINTER(ctypes.c_float)),
                ('number2', ctypes.c_float))

c_instance = ctypes.CDLL('./test')
init_func = c_instance.expose_init
# Good habit to fully define arguments and return type
init_func.argtypes = ctypes.POINTER(input_struct),
init_func.restype = None

inp_str_ptr = input_struct()
num = ctypes.c_float(20)     # instance of c_float, similar to C "float num = 20;"
inp_str_ptr.number1 = ctypes.pointer(num) # similar to C "inp_str_ptr.number1 = #"
inp_str_ptr.number2 = 100

c_instance.expose_init(ctypes.byref(inp_str_ptr))

# similar to C "float arr[1] = {30}; inp_str_ptr = arr;"
inp_str_ptr.number1 = (ctypes.c_float * 1)(30)
c_instance.expose_init(ctypes.byref(inp_str_ptr))

Output:
20.000000 100.000000
30.000000 100.000000


text:
Q: Can't see graph using torch.utils.tensorboard I'm trying to get used to tensorboard, and I code my models using pytorch.
However when I try to see my model using the add_graph() function, I've got this:
With this as the test code:
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.linear = nn.Linear(2, 1)

    def forward(self, x):
        x = self.linear(x)
        return x

writer = SummaryWriter('runs_pytorch/test')
net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
writer.add_graph(net, torch.zeros([4, 2], dtype=torch.float))
writer.close()

On the other hand, if I try to see a graph using TensorFlow, everything seems fine:

with this as the test code this time:
import tensorflow as tf
tf.Variable(42, name='foo')
w = tf.summary.FileWriter('runs_tensorflow/test')
w.add_graph(tf.get_default_graph())
w.flush()
w.close()

In case you are wondering, I'm using this command to start tensorboard:
tensorboard --logdir runs_pytorch

Something I noticed is that when I use it on the directory allocated for my tensorflow test, I've got the usual message with the address, but if I do the same thing with  --logdir runs_pytorch I've got something more:
W1010 15:19:24.225109 15308 plugin_event_accumulator.py:294] Found more than one graph event per run, or there was a metagraph containing a graph_def, as well as one or more graph events.  Overwriting the graph with the newest event.
W1010 15:19:24.226075 15308 plugin_event_accumulator.py:322] Found more than one "run metadata" event with tag step1. Overwriting it with the newest event.
I'm on windows, I tried on different browsers (chrome, firefox...).
I have tensorflow 1.14.0, torch 1.2.0, Python 3.7.3
Thank you very much for your help, it's driving me crazy!

A: There are two ways to solve it:
1. update PyTorch to 1.3.0 and above:

*

*conda way:
    conda install pytorch torchvision cudatoolkit=9.2 -c pytorch

*pip way:
    pip3 install torch==1.3.0+cu92 torchvision==0.4.1+cu92 -f https://download.pytorch.org/whl/torch_stable.html

2. install tensorboardX instead:

*

*uninstall tensorboard:
if your tensorboard is installed by pip:
    pip uninstall tensorboard

if your tensorboard is installed by anaconda:
    conda uninstall tensorboard

*install tensorboardX
    pip install tensorboardX

*when writing script,
change
    from torch.utils.tensorboard import SummaryWriter

to
    from tensorboardX import SummaryWriter

A: This might have been caused by this known problem, and it seems that it was solved in pytorch 1.3 which was realeased yesterday - check out Bug Fixes in the release notes.


text:
Q: How to set offset with limit clause on AgensGraph? I want to set offset with limit clause on AgensGraph.
But, there is no "offset" token.
agens=# create (:v1{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# create (:v1{id:2});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# create (:v1{id:3});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# match (n:v1) return n offset 1 limit 1;
ERROR:  syntax error at or near "offset"
LINE 1: match (n:v1) return n offset 1 limit 1;
                              ^

How to set offset with limit clause on AgensGraph?

A: Use "SKIP" instead of "OFFSET".
agens=# match (n:v1) return n skip 1 limit 1;
        n
------------------
 v1[3.2]{"id": 2}
(1 row)


text:
Q: Regex to extract URL domain name with a dash in it using Node.js I am trying to extract just the websites name from a URL and all the stackoverflow answers haven't led me anywhere.
My URL is in the following format:
https://order-dev.companyname.com
I just want to extract order-dev from the URL.

A: Got this to work for me (?<=\/\/)(.*?)(?=\.)

A: If you have an express framework with your node app then it is easy to get a domain/list of subdomains directly from the incoming request..
Using Express Framework
req.hostname() // returns 'example.com'
req.subdomains() // return ['ferrets', 'tobi'] from Host: "tobi.ferrets.example.com"

For plain NodeJS
All Incoming request will contain the following header origin which can be extracted using the following request.headers.origin in any functions where you handle your incoming request MDN LINK

A: In most JavaScript engines (i.e., most browsers (excluding IE) and Node) you can also use URL for this, specifically URL.host combined with String.prototype.split():

const siteUrl = 'https://order-dev.companyname.com';
const myURLObject = new URL(siteUrl);
const subdomain = myURLObject.host.split(".")[0];
console.log(subdomain); // "order-dev"


text:
Q: Loop through Column restarting when value changes I've found a couple threads with similar titles but weren't really what I am looking to do. What I'm trying to do is go through the list of numbers in Col A, and calculate the time difference using NetworkDays for the first instance the number appears in Col B ' Received On ' and the last instance the number appears in Col C ' Processed On '. After the NetworkDays calculation is done I'd like to put that value repeating in Col D on every respective row. The number of times a value will appear in Col A constantly varies, and Col A itself is several thousand lines long and constantly growing. Once that is done I need to loop through all the other different sets of numbers in Col A and repeat the process. As an example, ***39430 first appears on Row 2 and last appears on Row 7. Using Networkdays(B2,C7) gives 11 days, and so forth. After that move onto ***39383. Sample below.
Sample data
Below is the code I have so far. From the sample above I have to put a blank row under ***39430 in order to get the code to work, otherwise it just continues on to the bottom of the list and calculates that difference (not what I want obviously). What I'm stumped on is how to tell the loop to restart whenever the value changes in Col A and then continue on. I suspect it might be something close to  Do Until ActiveCell.Value <> Activecell.Offset(-1,0).Value but I can't quite figure it out. Also how to get the Networkdays value to repeat on every respective row.
Dim counter As Integer
Dim CycleTime As Long

counter = 0

Do Until ActiveCell.Value = ""
counter = counter + 1

ActiveCell.Offset(1, 0).Select
Loop

'Gives the number of rows to offset
MsgBox counter

'Shows the correct number of days difference
MsgBox WorksheetFunction.NetworkDays(Range("B2"), Range("B2").Offset(counter - 1, 1))
CycleTime = WorksheetFunction.NetworkDays(Range("B2"), Range("B2").Offset(counter - 1, 1))
Range("D2").Value = CycleTime

Any help would be greatly appreciated. Thanks in advance.
Update
After using the code provided for a couple of weeks I've noticed a complication that I had not thought of before. Previously, I had thought that there was always only one output doc for each input doc (not considered in scope of original question), however as shown in Sample-New image in the top box there can be more than one output doc per input doc. For the new screenshot below I've included two additional columns, Col. C 'Output Doc #' and Col. D 'Output Doc Created On'.  What I'd like to be able to do, amending the code that @YowE3K provided below, is to nest another loop that goes through Col. D 'Output Doc #' and uses NetworkDays to calculate the difference from B1 and D1 for the first group, and then B1 and D8 for the second group. As it is now, the code isn't written to handle the change and calculates everything as shown in Column F, with the ideal code resulting in Column G. The second box (in dark blue) shows a typical example where the code performs perfectly. Loops are something I'm struggling with to understand and not really sure how to even take a stab at this. Any comments to the code in a response would be very helpful. Thanks in advance.
Sample - New

A: The following code loops using endRow as the loop "counter".
startRow is set to the row containing the start of the current "Doc Number", and endRow is incremented until it is pointing at the last row for that "Doc Number".
Once endRow is pointing at the correct place, CycleTime is calculated and written to column D of each row from startRow to endRow.  startRow is then set to point to the beginning of the next "Doc Number".
The loop ends when a blank cell is found in column A.
Sub Calc()

    Dim startRow As Long
    Dim endRow As Long
    Dim CycleTime As Long

    startRow = 2
    endRow = 2
    Do
        If Cells(startRow, "A").Value <> Cells(endRow + 1, "A").Value Then
            CycleTime = WorksheetFunction.NetworkDays(Cells(startRow, "B"), Cells(endRow, "C"))
            Range(Cells(startRow, "D"), Cells(endRow, "D")).Value = CycleTime
            startRow = endRow + 1
        End If
        endRow = endRow + 1
        If Cells(endRow, "A").Value = "" Then
            Exit Do
        End If
    Loop

End Sub

Edited to keep track of the first and last "Approved" record, and only update column D if one is found:
Sub Calc()

    Dim startRow As Long    'Start of the Doc Number
    Dim firstRow As Long    'First "approved" row
    Dim lastRow As Long     'Last "approved" row
    Dim endRow As Long      'End of the Doc Number
    Dim CycleTime As Long

    startRow = 2
    endRow = 2
    firstRow = -1
    lastRow = -1

    Do
        If Cells(endRow, "Q").Value = "Approved" Then
            'Found an "Approved" record

            'Set the first row if not already set
            If firstRow = -1 Then
                firstRow = endRow
            End If

            'Set the last row (will replace this if we find another record)
            lastRow = endRow
        End If

        If Cells(startRow, "A").Value <> Cells(endRow + 1, "A").Value Then
            If firstRow > 0 Then ' (If it is -1 then we never found an "Approved" record)
                CycleTime = WorksheetFunction.NetworkDays(Cells(firstRow, "B"), Cells(lastRow, "C"))
                Range(Cells(startRow, "D"), Cells(endRow, "D")).Value = CycleTime
            End If
            'Set up for next Doc Number
            startRow = endRow + 1
            firstRow = -1
            lastRow = -1
        End If
        'Go to next row
        endRow = endRow + 1
        'Exit when we hit a blank Doc Number
        If Cells(currentRow, "A").Value = "" Then
            Exit Do
        End If
    Loop

End Sub


text:
Q: How do I load google font in Nextjs with rel=preload, it only seems to work with rel=stylesheet Using:
<link rel="preload" as="font" type="font/woff2" href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400;1,800&display=optional"  />

results in data-href(due to next font optimization):
<link rel="preload" as="font" type="font/woff2" data-href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400;1,800&display=optional">

and the requested font is not inlined, as in(according to the docs):
<style data-href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400;1,800&display=optional">
  @font-face{font-family:'Inter';font-style:normal...
</style>

In summary Nextjs web font optimization doesn't seem to work with rel=preload, only rel=stylesheet as in:
<link
  href="https://fonts.googleapis.com/css2?family=Inter&display=optional"
  rel="stylesheet"
/>


text:
Q: Convert row_number() function for mysql ddl statement I am trying to run the below ddl statment generated on DB2 to mysql. However, it gives me error that row_number() doesn't exist on mysql.
Can someone please tell me how to emulate this in mysql ?
Query
CREATE VIEW "MY_PORTAL"."MyView" AS SELECT ROW_NUMBER() OVER() AS id, b.id batch_id,
b.name batch_name, b.description batch_desc, b.status batch_status, b.classname batch_classname,
b.active batch_active, b.server batch_server, s.id scheduler_id, s.typeid scheduler_type_id,
str.typename scheduler_type_name, s.days scheduler_days, s.hours scheduler_hours, s.minutes scheduler_minutes,
s.seconds scheduler_seconds FROM myDB.batches b LEFT OUTER JOIN myDB.schedulers s
ON s.batchid = b.id LEFT OUTER JOIN myDB.scheduler_type_ref str ON str.typeid = s.typeid;


text:
Q: stop bootstrap carousel to cycle at the end of the slide I wanted such that when I press the next button on the carousel, if it has reached the end of the slide then don't wrap around and go back to the first slide. Is there an easy way to do this in bootstrap 3?

A: Setting the wrap option to false makes the carousel to stop cycling automatically.
$('#myCarousel').carousel({
  interval: 1000,
  wrap: false
});

Also if you want to hide the left and right controls when the carousel is showing the first/last slides you can do this way:
  $('#myCarousel').on('slid.bs.carousel', '', function() {
  var $this = $(this);

  $this.children('.carousel-control').show();

  if($('.carousel-inner .item:first').hasClass('active')) {
    $this.children('.left.carousel-control').hide();
  } else if($('.carousel-inner .item:last').hasClass('active')) {
    $this.children('.right.carousel-control').hide();
  }

});

DEMO


text:
Q: Bash: How to kill eval if the process that receives its output terminates I have a little ugly bash script on my Ubuntu machine that contains the lines:
search_command="find -L $(printf "%q" "$search_folder") \( ! -regex '.*/\..*/..*' \) -mindepth 1 2> /dev/null"
for i in "${IGNOREENDINGS[@]}"
do
    search_command="$search_command -not -name \"*$i\""
done
search_command="$search_command | sed 's|^${search_folder}/\?||'"
choice=$(eval "$search_command"|fzf -q "$file_query" -1 --preview "preview $search_folder {}")

The script lets me choose a file, using fzf among the matches of a GNU find command.
It has the following problem: Once I choose a file in the interface of fzf the script closes the fzf interface, so that seems to be done, but then I still have to wait for the find command to complete (verified with top), which somehow takes very long. I'm not really sure why; the files that I want always appear almost instantly.
I included a few extra lines above to avoid an X Y problem. I am happy with anything with the same functionality and quicker execution.

A: There are two possibilities here: either fzf is not actually exiting when you select a file, or find is not exiting when fzf does. If it's the latter one, you can write a script to close find manually when fzf exits.
The way that pipes work in Linux, find does not know that the pipe it is writing to has nothing reading from that pipe until it tries to write to that pipe and fails. As a consequence, if you pick the file after find has already found everything it's going to find, find is no longer writing to the pipe, and so will iterate over the whole file system before exiting.
As an illustration of this, if you make a random file in / and then run find / -name $random_file_name | head -n 1, you will very quickly get all the output you are going to get, but the program will continue to run for a long time.
One way to get around this is by killing the process yourself when it's done. Probably the easiest way to do it in your specific case is a named pipe:
tmp_fifo=`mktemp -u`
mkfifo "$tmp_fifo"
eval "$search_command" > "$tmp_fifo" &
choice="$(fzf -q "$file_query" -1 --preview "preview $search_folder {}" < "$tmp_fifo")" ; kill $!
rm "$tmp_fifo"

This creates a temporary named pipe, find writes to it, and fzf reads from it. But when fzf exits, kill $! is run, where $! stands for the last background process to have been started, in this case find.

A: That other answer looks fine, the downside is you need to manage the fifo. With Bash's coproc you can solve the problem without a named fifo.
(Note: to make this answer address the general problem rather than your specific one, I dropped your variables, eval and similar stuff).
coproc find ...         # this silently runs in background, no `&' nor explicit redirection needed
<&${COPROC[0]} fzf ...  # piping from `find' to `fzf'
kill $!                 # killing the last background process, i.e. `find'


text:
Q: React hook arguments cause infinite rerendering I've got two custom react hooks one is just a wrapper for the other one.
The first one is a basic fetch hook, which returns the status and result or error.
interface State<T> {
  status: 'idle' | 'pending' | 'error' | 'success';
  data?: T;
  error?: string;
}

interface Cache<T> {
  [url: string]: T;
}

type Action<T> =
  | { type: 'request' }
  | { type: 'success'; payload: T }
  | { type: 'failure'; payload: string };

export function useFetch<T = unknown>(
  url: string,
  options?: RequestInit,
  cached = false
): State<T> {
  const cache = useRef<Cache<T>>({});
  const cancelRequest = useRef(false);

  const initialState: State<T> = {
    status: 'idle',
    error: undefined,
    data: undefined,
  };

  const fetchReducer = (state: State<T>, action: Action<T>): State<T> => {
    switch (action.type) {
      case 'request':
        return { ...initialState, status: 'pending' };
      case 'success':
        return { ...initialState, status: 'success', data: action.payload };
      case 'failure':
        return { ...initialState, status: 'error', error: action.payload };
      default:
        return state;
    }
  };

  const [state, dispatch] = useReducer(fetchReducer, initialState);

  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'request' });

      if (cache.current[url] && cached) {
        dispatch({ type: 'success', payload: cache.current[url] });
      } else {
        try {
          const res = await fetch(url, options);
          const json = await res.json();
          cache.current[url] = json;

          if (cancelRequest.current) return;

          if (res.status !== 200) {
            dispatch({ type: 'failure', payload: json.error });
          } else {
            dispatch({ type: 'success', payload: json });
          }
        } catch (error) {
          if (cancelRequest.current) return;

          dispatch({ type: 'failure', payload: error.message });
        }
      }
    };

    fetchData();

    return () => {
      cancelRequest.current = true;
    };
  }, [url, options, cached]);

  return state;
}

export default useFetch;

The second hook is a wrapper which provides some fetch options like a header containing a cookie to the useFetch hook. This way I wont have to write the same code over and over to do some requests against my API. I've called it useAPICall
export const useAPICall = <T>(url: string, body?: any, method = 'GET') => {
  return useFetch<T>(
    apiEndpoint + url,
    {
      method,
      body,
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        'x-access-token': getCookie('token'),
      },
    },
    false
  );
};

getCookie returns the cookie called token from the document.
This is how I would use the useAPICall hook:
const { status, data, error } = useAPICall<Request>('/example/route');

My problem is that whenever I want to use the useAPICall or the useFetch hook, while providing an options object as argument, it causes infinite rerenders and a maximum update depth exceeded error.
I figured out the problem lies within the options dependency of useEffect in my useFetch hook, when I remove it from the dependency array the fetch request works nicely.
The only problem being that my linter tells me to include options in the dependency array because useEffect relies on it.
I'm now wondering how I can do it correctly.

A: The problem is passing an object literal as options will cause the dependencies of your useEffect() to change every time the hook re-renders, meaning that, as you experienced, you'll be fetching repeatedly because the effect will run again with the new options reference every time the previous fetch has just completed.
In order to break the cycle, you'll need to either

*

*memoize the options you pass in from useAPICall()

*store your options in a useRef() within useFetch()
Additionally, since you want the fetch to be sensitive to options changing, if you decide on the second approach, you'll need to manually compare the new reference to the previous one each time the useFetch() hook renders, and only use the new reference if the value has changed.
Here's how you can implement the first approach in useAPICall(), leaving useFetch() alone:
export const useAPICall = <T>(url: string, body?: any, method = 'GET') => {
  const options = {
    method,
    body,
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      'x-access-token': getCookie('token'),
    },
  };
  const ref = useRef(options);

  if (
    ref.current.method !== options.method
    || ref.current.body !== options.body
    || ref.current.headers['x-access-token'] !== options.headers['x-access-token']
  ) {
    ref.current = options;
  }

  return useFetch<T>(
    apiEndpoint + url,
    ref.current,
    false
  );
};

Below is how you can implement most of the second approach, leaving useAPICall() alone, though I've left a comment where you'll need to flesh out the specifics of it:
interface State<T> {
  status: 'idle' | 'pending' | 'error' | 'success';
  data?: T;
  error?: string;
}

interface Cache<T> {
  [url: string]: T;
}

type Action<T> =
  | { type: 'request' }
  | { type: 'success'; payload: T }
  | { type: 'failure'; payload: string };

const initialState: State<any> = {
  status: 'idle',
  data: undefined,
  error: undefined,
};

function fetchReducer<T>(state: State<T>, action: Action<T>): State<T> {
  switch (action.type) {
    case 'request':
      return { ...initialState, status: 'pending' };
    case 'success':
      return { ...initialState, status: 'success', data: action.payload };
    case 'failure':
      return { ...initialState, status: 'error', error: action.payload };
    default:
      return state;
  }
};

// if (prev == next) { return prev; } else { return next; }
function headersReducer(prev?: HeadersInit, next?: HeadersInit) {
  if (prev === next) {
    return prev;
  }

  if (!prev || !next) {
    return next;
  }

  if (
    // headers are equal
  ) {
    return prev;
  }

  return next;
}

// if (prev == next) { return prev; } else { return next; }
function optionsReducer(prev?: RequestInit, next?: RequestInit) {
  if (prev === next) {
    return prev;
  }

  if (!prev || !next) {
    return next;
  }

  if (
    prev.body === next.body
    && prev.cache === next.cache
    && prev.credentials === next.credentials
    && prev.headers === headersReducer(prev.headers, next.headers)
    && prev.integrity === next.integrity
    && prev.keepalive === next.keepalive
    && prev.method === next.method
    && prev.mode === next.mode
    && prev.redirect === next.redirect
    && prev.referrer === next.referrer
    && prev.referrerPolicy === next.referrerPolicy
    && prev.signal === next.signal
    && prev.window === next.window
  ) {
    return prev;
  }

  return next;
}

export function useFetch<T = unknown>(
  url: string,
  options?: RequestInit,
  cached = false
): State<T> {
  const cache = useRef<Cache<T>>({});
  const optionsRef = useRef<RequestInit>();
  const [state, dispatch] = useReducer(fetchReducer, initialState);

  optionsRef.current = optionsReducer(optionsRef.current, options);
  const currentOptions = optionsRef.current;

  useEffect(() => {
    let cancelRequest = false;

    const fetchData = async () => {
      dispatch({ type: 'request' });

      if (cache.current[url] && cached) {
        dispatch({ type: 'success', payload: cache.current[url] });
      } else {
        try {
          const res = await fetch(url, currentOptions);
          const json = await res.json();
          cache.current[url] = json;

          if (cancelRequest) return;

          if (res.status !== 200) {
            dispatch({ type: 'failure', payload: json.error });
          } else {
            dispatch({ type: 'success', payload: json });
          }
        } catch (error) {
          if (cancelRequest) return;

          dispatch({ type: 'failure', payload: error.message });
        }
      }
    };

    fetchData();

    return () => {
      cancelRequest = true;
    };
  }, [url, currentOptions, cached]);

  return state;
}

export default useFetch;


text:
Q: Windows 8.1: Restore .bat file association to default A few weeks ago I accidentally changed .bat files to open with Notepad++ (a fairly common issue I believe). On Win XP and Win 7 I had a .reg file that updated the relevant registry keys and sorted out the problem. However, this batch file no longer works for Win 8.1 (I assume file associations are dealt with differently in Win 8.1) and none of my manual registry hacks are working.
No matter what I do, I can't seem to restore .bat files to their previous association. I've finally managed to disassociate .bat files with Notepad++, but I can't figure out how to apply the defaults.
I have tried the solutions listed on the below sites:
http://www.eightforums.com/tutorials/8486-default-file-associations-restore-windows-8-a.html
https://social.technet.microsoft.com/Forums/windows/en-US/a85d8a59-b93b-45a3-8aee-cdf93ce32079/how-do-i-reset-the-default-file-association-for-bat-files-on-windows-81?forum=w8itproinstall
Plus I've executed the following commands in an administrator command prompt to no avail (they both report the correct values):
C:\Users\Christopher>assoc .bat
.bat= batfile

C:\Users\Christopher>ftype batfile
batfile="%1" %*

But am not getting anywhere. Can anyone help?

A: This has been a bit of a nightmare, but I have solved it with the help of @Pariah. I had to run the following .reg file as administrator, then manually delete the following key manually:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.BAT\UserChoice

Run reg file as admin:
runas /user:administrator "regedit /s c:\test.reg"

Reg file:
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\batfile]
@="Windows Batch File"
"EditFlags"=hex:30,04,00,00
"FriendlyTypeName"=hex(2):40,00,25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,\
  00,6f,00,6f,00,74,00,25,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,\
  32,00,5c,00,61,00,63,00,70,00,70,00,61,00,67,00,65,00,2e,00,64,00,6c,00,6c,\
  00,2c,00,2d,00,36,00,30,00,30,00,32,00,00,00

[HKEY_CLASSES_ROOT\batfile\DefaultIcon]
@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,\
  00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,69,00,6d,00,\
  61,00,67,00,65,00,72,00,65,00,73,00,2e,00,64,00,6c,00,6c,00,2c,00,2d,00,36,\
  00,38,00,00,00

[HKEY_CLASSES_ROOT\batfile\shell]

[HKEY_CLASSES_ROOT\batfile\shell\edit]

[HKEY_CLASSES_ROOT\batfile\shell\edit\command]
@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,\
  00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,4e,00,4f,00,\
  54,00,45,00,50,00,41,00,44,00,2e,00,45,00,58,00,45,00,20,00,25,00,31,00,00,\
  00

[HKEY_CLASSES_ROOT\batfile\shell\open]
"EditFlags"=hex:00,00,00,00

[HKEY_CLASSES_ROOT\batfile\shell\open\command]
@="\"%1\" %*"

[HKEY_CLASSES_ROOT\batfile\shell\print]

[HKEY_CLASSES_ROOT\batfile\shell\print\command]
@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,\
  00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,4e,00,4f,00,\
  54,00,45,00,50,00,41,00,44,00,2e,00,45,00,58,00,45,00,20,00,2f,00,70,00,20,\
  00,25,00,31,00,00,00

[HKEY_CLASSES_ROOT\batfile\shell\runas]
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\batfile\shell\runas\command]
@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,\
  00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,63,00,6d,00,\
  64,00,2e,00,65,00,78,00,65,00,20,00,2f,00,43,00,20,00,22,00,25,00,31,00,22,\
  00,20,00,25,00,2a,00,00,00

[HKEY_CLASSES_ROOT\batfile\shell\runasuser]
@="@shell32.dll,-50944"
"Extended"=""
"SuppressionPolicyEx"="{F211AA05-D4DF-4370-A2A0-9F19C09756A7}"

[HKEY_CLASSES_ROOT\batfile\shell\runasuser\command]
"DelegateExecute"="{ea72d00e-4960-42fa-ba92-7792a7944c1d}"

[HKEY_CLASSES_ROOT\batfile\ShellEx]

[HKEY_CLASSES_ROOT\batfile\ShellEx\ContextMenuHandlers]
@="Compatibility"

[HKEY_CLASSES_ROOT\batfile\ShellEx\ContextMenuHandlers\Compatibility]
@="{1d27f844-3a1f-4410-85ac-14651078412d}"

[HKEY_CLASSES_ROOT\batfile\ShellEx\ContextMenuHandlers\OpenGLShExt]
@="{E97DEC16-A50D-49bb-AE24-CF682282E08D}"

[HKEY_CLASSES_ROOT\batfile\ShellEx\DropHandler]
@="{86C86720-42A0-1069-A2E8-08002B30309D}"

[HKEY_CLASSES_ROOT\batfile\ShellEx\PropertySheetHandlers]

[HKEY_CLASSES_ROOT\batfile\ShellEx\PropertySheetHandlers\ShimLayer Property Page]
@="{513D916F-2A8E-4F51-AEAB-0CBC76FB1AF8}"

[HKEY_CLASSES_ROOT\batfile\ShellEx\{8895b1c6-b41f-4c1c-a562-0d564250836f}]
@="{1531d583-8375-4d3f-b5fb-d23bbd169f22}"

A: The Final Reg File the user had to use to correct this issue in Windows 8.1 [after running the batch file provided by Notepad++ to set notepad++ as default batch file handler.  They tried both of the other fixes below this one.  In the end they had to run the following in a .reg file as admin.
FIRST, to run a reg file as admin:
Note: It is best to place this file on C:\ and name file something like fix.reg so in the end it is something like C:\fix.reg.  If you place this somewhere where the path and/or file name has any spaces included in it you will get an error message and the reg keys will not be added/changed.
The Command:
runas /user:Administrator "regedit.exe c:\fix.reg"

The contents of the fix.reg file:
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\batfile]
@="Windows Batch File"
"EditFlags"=hex:30,04,00,00
"FriendlyTypeName"=hex(2):40,00,25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,\
00,6f,00,6f,00,74,00,25,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,\
32,00,5c,00,61,00,63,00,70,00,70,00,61,00,67,00,65,00,2e,00,64,00,6c,00,6c,\
00,2c,00,2d,00,36,00,30,00,30,00,32,00,00,00

[HKEY_CLASSES_ROOT\batfile\DefaultIcon]
@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,\
00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,69,00,6d,00,\
61,00,67,00,65,00,72,00,65,00,73,00,2e,00,64,00,6c,00,6c,00,2c,00,2d,00,36,\
00,38,00,00,00

[HKEY_CLASSES_ROOT\batfile\shell]

[HKEY_CLASSES_ROOT\batfile\shell\edit]

[HKEY_CLASSES_ROOT\batfile\shell\edit\command]
@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,\
00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,4e,00,4f,00,\
54,00,45,00,50,00,41,00,44,00,2e,00,45,00,58,00,45,00,20,00,25,00,31,00,00,\
00

[HKEY_CLASSES_ROOT\batfile\shell\open]
"EditFlags"=hex:00,00,00,00

[HKEY_CLASSES_ROOT\batfile\shell\open\command]
@="\"%1\" %*"

[HKEY_CLASSES_ROOT\batfile\shell\print]

[HKEY_CLASSES_ROOT\batfile\shell\print\command]
@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,\
00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,4e,00,4f,00,\
54,00,45,00,50,00,41,00,44,00,2e,00,45,00,58,00,45,00,20,00,2f,00,70,00,20,\
00,25,00,31,00,00,00

[HKEY_CLASSES_ROOT\batfile\shell\runas]
"HasLUAShield"=""

[HKEY_CLASSES_ROOT\batfile\shell\runas\command]
@=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,00,25,\
00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,63,00,6d,00,\
64,00,2e,00,65,00,78,00,65,00,20,00,2f,00,43,00,20,00,22,00,25,00,31,00,22,\
00,20,00,25,00,2a,00,00,00

[HKEY_CLASSES_ROOT\batfile\shell\runasuser]
@="@shell32.dll,-50944"
"Extended"=""
"SuppressionPolicyEx"="{F211AA05-D4DF-4370-A2A0-9F19C09756A7}"

[HKEY_CLASSES_ROOT\batfile\shell\runasuser\command]
"DelegateExecute"="{ea72d00e-4960-42fa-ba92-7792a7944c1d}"

[HKEY_CLASSES_ROOT\batfile\ShellEx]

[HKEY_CLASSES_ROOT\batfile\ShellEx\ContextMenuHandlers]
@="Compatibility"

[HKEY_CLASSES_ROOT\batfile\ShellEx\ContextMenuHandlers\Compatibility]
@="{1d27f844-3a1f-4410-85ac-14651078412d}"

[HKEY_CLASSES_ROOT\batfile\ShellEx\ContextMenuHandlers\OpenGLShExt]
@="{E97DEC16-A50D-49bb-AE24-CF682282E08D}"

[HKEY_CLASSES_ROOT\batfile\ShellEx\DropHandler]
@="{86C86720-42A0-1069-A2E8-08002B30309D}"

[HKEY_CLASSES_ROOT\batfile\ShellEx\PropertySheetHandlers]

[HKEY_CLASSES_ROOT\batfile\ShellEx\PropertySheetHandlers\ShimLayer Property Page]
@="{513D916F-2A8E-4F51-AEAB-0CBC76FB1AF8}"

[HKEY_CLASSES_ROOT\batfile\ShellEx\{8895b1c6-b41f-4c1c-a562-0d564250836f}]
@="{1531d583-8375-4d3f-b5fb-d23bbd169f22}"

Other Possible fixes to try if above does not work for you [It has been verified to work by at least 1 person where the below did not in Windows 8.1]
Registry key to navigate to: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts.BAT\UserChoice
Delete the key named "user choice"
Code Block for clarity (per request):
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.BAT\UserChoice

Also listed on the reference page as a fix is the following:

I would disagree there. This is not a Windows 8 specific issue.
  Something has changed the file association, and it needs to be changed
  back. This same issue can be replicated all the way back to Windows
  2000 (and probably earlier). Did you check the following keys and make
  sure they were set to the values shown, as seen in the responses in
  that post?
[HKEY_CLASSES_ROOT.bat] @="batfile"
[HKEY_CLASSES_ROOT.bat\PersistentHandler]
  @="{5e941d80-bf96-11cd-b579-08002b30bfeb}"
[HKEY_CLASSES_ROOT\batfile\shell\open\command] @="\"%1\" %*"

The user of this second more complex solution also has a link to a *.reg file they created which should automagically set those several keys listed above this text for you to the default values.  See Bottom of reference page as this was marked as Best Solution and those are kept at bottom of page (why M$ made that decision is beyond me would you not put solutions at top of threads so they are easier to find?  Good ol M$)
That should do it and have notepad++ stop taking over.  As a side note you can right click a *.bat file and if you click the Edit entry in the menu that will open the batch file in notepad for you while still leaving the double click to execute the batch file in a command shell.
Reference used [Listed in the Windows 7 forum but is the same in Windows 8.1 btw]:
https://social.technet.microsoft.com/Forums/windows/en-US/fc2ca91d-5509-4c9b-92a5-5af19375e361/lost-bat-file-association?forum=w7itprogeneral
More detailed Info (how to open regedit and run as admin if needed)
For this one it is a little tricky since we have to use the Registry Editor.  You SHOULD be able to do this as a user since the change is a user level one most of the time, but depending on your security policies in place you may have to do the following.

*

*Click the Start Menu Button

*Type in regedit (just start typing when the start menu is visible and it should start searching automatically).

*Once you see regedit appear on screen right click on it

*When you see the context menu appear click on Run as Administrator

*Authenticate (type in your administrator password, place finger on fingerprint reader however you have it setup it's like logging in to the account)

Side Note: You can try it first without doing the administrator part if you would like. The worst thing that it will do is deny your ability to delete the key listed.  If this happens you must run as administrator and you will then be able to delete it.
Generally for MOST file associations in almost all versions of Windows (aside from system set ones such as batch files):
All you should have to do is hold the LEFT Shift Key down while you right click on a *.bat file.  When you do this to a file you should see an Open With ... option appear close to the top of the context menu that appears [the small menu that you get when you right click on things].  Once you click open with you will get a dialog where you can choose what to open the file with.  If you check the Use as default box in lower left corner it will become the new default action when you double click files of the same type.

A: Deleting this registry key (as an admin) was missing from all the above (Windows 8.1):
HKEY_CURRENT_USER\Software\Microsoft\Windows\Roaming\OpenWith\FileExts.bat\UserChoice.
Hope this helps.


text:
Q: Memory allocation for _M_start and _M_finish in a vector I'm defining a vector as:
vector< int, MyAlloc< int> > *v = new vector< int, MyAllooc< int> > (4);

MyAlloc is allocating space for only 4 ints. Memory for _M_start, _M_finish, and _M_end_of_storage is being allocated on the heap before the memory for the 4 ints. But who is allocating this memory for _M_start, _M_finish, and _M_end_of_storage? I want to allocate this memory myself. What do I have to do?

A: Do not use new for allocating the vector. Generally you should allocate vectors from stack:
vector< int, MyAlloc< int> > v(4);

If you really need to use your own allocator for that too, allocate the memory for the object and then call placement new on it to construct the vector.
It is also possible to overload global operator new/delete, but this is really messy and I would not recommend it.

A: Allocators allocate the data storage of the container, not the container data members, which are allocated as normal. This must be the case, or you would not be able to create the vector using new or on the stack.  This is clearest for a node based container like a list - the list nodes are allocated by the allocator, but the other data members, including the pointers to the first and last nodes (if implemented that way) are allocated normally.

A: new T allocates sizeof(T) memory on the heap. In your case, T is std::vector< int, MyAlloc< int> > and includes members like _M_start.
If you want to allocate that memory yourself, then don't call new.

A: When you create the vector, it allocates room for the vector's member variables (the _M ones) wherever you place the vector. If you use new, it allocates space for these variables on the heap. With local variables, the compiler makes space for them in the current stack frame. If you make the vector a member of a class, the compiler makes space for them in the containing class.
The vector then uses its allocator to allocate room for the data you wish to store in the vector, using whatever mechanism the allocator is defined to use.


text:
Q: jQuery animated div on scroll I have this
$(document).ready(function(){
$(window).scroll(function(){
   if($("#1").offset().top < $(window).scrollTop());
    $("#1").animate({"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fixed"}, 1000);
}, function() {
$("#1").animate({"color":"#333","font-size":"52pt", "top":"0", "position":"fixed"}, 1000);
  });
});

in jsfiddle As you can see, when you start to scroll, the text animates (I did get this from Stackoverflow, but lost the link, so thanks to the people who contributed to the first post) What I would like is for the text to animate back to its original state when the content once again reaches the top.
Any help is always much appreciated
Kind regards

A: What kind of browser support do you need? The catch with animating back is you need to know the original style.
Once method I can think of is using the window.getComputedStyle method to retrieve the styles for the element and store them in an object array to use for the animate back. You will need a couple extra supporting functions.
I tested the following code in Chrome, IE 9, and FireFox 24 and it seemed to work pretty well. It all depends on what styles you work with. Since you are animating, however, this should work with most.
Also, I stored your styles and speed in variables to make it cleaner. Fiddle below:
$(document).ready(function(){
    var aniCss = {"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fixed"};
    var speed = 1000;
    var props = getProps(aniCss);
    var curCss = getStyles($("#1"), props);
    $(window).scroll(function(){
        if ($(window).scrollTop() >0) {
            $("#1").animate(aniCss,speed);
        }
        else {
            $("#1").stop(true,true).animate(curCss,speed);
        }
    });

    function getProps(css) {
        var props = [];
        for (k in css) {
            props.push(k);
        }
        return props;
    }
    function getStyles($ele, props) {
        var compCss = getComputedStyle($ele[0]);
        var styles = {};
        for (var i = 0;i<props.length;i++) {
            var name = props[i];
            var prop = compCss.getPropertyValue(name);
            if (prop != '') { styles[name]=prop;}
        }
        return styles;
    }
});

Fiddle: http://jsfiddle.net/ajqQL/1/
Update: Just saw that in jQuery 1.9 they added the ability to pass an array of properties to retrieve the values. You can simplify the above by just using jQuery .css() method:
$(document).ready(function(){
    var aniCss = {"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fixed"};
    var speed = 400;
    var props = getProps(aniCss);
    var curCss = $('#1').css(props);
    $(window).scroll(function(){
        if ($(window).scrollTop() >0) {
            $("#1").animate(aniCss,speed);
        }
        else {
            $("#1").stop(true,true).animate(curCss,speed);
        }
    });

    function getProps(css) {
        var props = [];
        for (k in css) {
            props.push(k);
        }
        return props;
    }
});

Fiddle: http://jsfiddle.net/NZq8D/1/


text:
Q: I accidentally, deleted table of a model in db.sqlite (manually). How can I recreate it? I accidentally, deleted table of a model in db.sqlite. How can I recreate it?
When I run command 'python manage.py makemigrations' it works but when I run'python manage.py migrate' it says 'No migrations to apply'

A: Figure out which app and migration originally created the table. For example, if the model that created the table is in an app called users in the initial migration #0001, you can run this command to dump the SQL that created the table:
$ python manage.py sqlmigrate users 0001
BEGIN;
--
-- Create model User
--
CREATE TABLE "users_user" ("id" serial NOT NULL PRIMARY KEY, "password" varchar(128) NOT NULL, "last_login" timestamp with time zone NOT NULL, "is_superuser" boolean NOT NULL, "username" varchar(30) NOT NULL UNIQUE, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL, "email" varchar(75) NOT NULL, "is_staff" boolean NOT NULL, "is_active" boolean NOT NULL, "date_joined" timestamp with time zone NOT NULL, "subscriber_code" varchar(255) NOT NULL);
CREATE INDEX "users_user_username_06e46fe6_like" ON "users_user" ("username" varchar_pattern_ops);
COMMIT;

After that, you can open a database shell in SQLite, and run the SQL via copy and paste:
python manage.py dbshell

Good luck with your restore!

A: Delete migration files and re-run python manage.py makemigrations


text:
Q: Is there a way to install applications using the text based UI that is presented during the OS installation? During a installation of Ubuntu Server you are presented with a screen which has a list of applications you can check that will be installed.  For example, one of those applications is docker.  I believe these are called "snaps".
Is there a way of installing these apps using the same GUI after you have installed the OS?

A: You are talking about Subiquity installer. The screenshot of mentioned snap installation menu is below:

The below message is contained in Subiquity's source-code.

These are popular snaps in server environments. Select or deselect with SPACE, press ENTER to see more details of the package, publisher and versions available.

While the list of featured server snaps is contained in the server.section file. I compiled them to table below

Snap name
Publisher
Description

microk8s
canonical✓
Kubernetes for workstations and appliances

nextcloud
nextcloud✓
Nextcloud Server - A safe home for all your data

wekan
xet7
The open-source kanban

kata-containers
katacontainers✓
Build lightweight VMs that seamlessly plug into the containers ecosystem

docker
canonical✓
Docker container runtime

canonical-livepatch
canonical✓
Ubuntu Livepatch Client

rocketchat-server
rocketchat✓
Rocket.Chat server

mosquitto
mospuitto✓
Eclipse Mosquitto MQTT broker

etcd
canonical✓
RResilient key-value store by CoreOS

powershell
microsoft-powershell✓
PowerShell for every system!

stress-ng
cking-kernel-tools
ttool to load and stress a computer

sabnzbd
safihre
SABnzbd

wormhole
snapcrafters
get things from one computer to another, safely

aws-cli
aws✓
UUniversal Command Line Interface for Amazon Web Services

google-cloud-sdk
google-cloud-sdk✓
Google Cloud SDK

slcli
softlayer
PPython based SoftLayer API Tool.

doctl
digitalocean✓
The official DigitalOcean command line interface

conjure-up
canonical✓
PPackage runtime for conjure-up spells

postgresql10
cmd✓
PostgreSQL is a powerful, open source object-relational database system.

heroku
heroku✓
CLI client for Heroku

keepalived
keepalived-project✓
High availability VRRP/BFD and load-balancing for Linux

prometheus
canonical
TThe Prometheus monitoring system and time series database

juju
canonical✓
Juju - a model-driven operator lifecycle manager for K8s and machines

maas
canonical✓
Metal as a Service

You can install any of them  using  snap install snap-name  command without any additional application.


text:
Q: I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working. Can any one help me? I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working.
See the Screenshot Here
Currently, when changing the price by touch input, the price is not affected when click off.
Here are my files
CartItem.js:
import React from "react";
import {
  View,
  TextInput,
  Image,
  TouchableOpacity,
  StyleSheet,
  Platform,
  Alert,
} from "react-native";
//Colors
import Colors from "../../../utils/Colors";
//NumberFormat
import NumberFormat from "../../../components/UI/NumberFormat";
//Icon
import { MaterialCommunityIcons } from "@expo/vector-icons";
import CustomText from "../../../components/UI/CustomText";
//PropTypes check
import PropTypes from "prop-types";

export class CartItem extends React.PureComponent {
  render() {
    const { item, onAdd, onDes, onRemove } = this.props;
    const AddItemHandler = async () => {
      await onAdd();
    };
    const sum = +item.item.price * +item.quantity;
    const checkDesQuantity = async () => {
      if (item.quantity == 1) {
        Alert.alert(
          "Clear cart",
          "Are you sure you want to remove the product from the cart?",
          [
            {
              text: "Cancel",
            },
            {
              text: "Yes",
              onPress: onRemove,
            },
          ]
        );
      } else {
        await onDes();
      }
    };
    return (
      <View style={styles.container}>
        <View style={styles.left}>
          <Image
            style={{
              width: "100%",
              height: 90,
              resizeMode: "stretch",
              borderRadius: 5,
            }}
            source={{ uri: item.item.thumb }}
          />
        </View>
        <View style={styles.right}>
          <View
            style={{ flexDirection: "row", justifyContent: "space-between" }}
          >
            <CustomText style={styles.title}>{item.item.filename}</CustomText>
            <View>
              <TouchableOpacity onPress={onRemove}>
                <MaterialCommunityIcons name='close' size={20} color='#000' />
              </TouchableOpacity>
            </View>
          </View>
          <CustomText style={{ color: Colors.grey, fontSize: 12 }}>
          Provided by Brinique Livestock LTD
          </CustomText>
          <NumberFormat price={sum.toString()} />
          <View style={styles.box}>

            <TouchableOpacity onPress={checkDesQuantity} style={styles.boxMin}>
              <MaterialCommunityIcons name='minus' size={16} />
            </TouchableOpacity>

Code that I would like to be fixed starts here.
            <View>
              <TextInput
              keyboardType='numeric'
              onEndEditing={AddItemHandler}
              style={styles.boxText}>{item.quantity}</TextInput>
            </View>

Code that I would like to be fixed ends here.
            <TouchableOpacity
            onPress={AddItemHandler}
            style={styles.boxMin}>

            <MaterialCommunityIcons name='plus' size={16} />
            </TouchableOpacity>

          </View>
        </View>
      </View>
    );
  }
}

CartItem.propTypes = {
  item: PropTypes.object.isRequired,
  onAdd: PropTypes.func.isRequired,
  onRemove: PropTypes.func.isRequired,
  onDes: PropTypes.func.isRequired,
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginHorizontal: 10,
    height: 110,
    borderBottomWidth: 1,
    borderBottomColor: Colors.light_grey,
    flexDirection: "row",
    paddingVertical: 10,
    alignItems: "center",
    backgroundColor: "#fff",
    paddingHorizontal: 10,
    borderRadius: 5,
    marginTop: 5,
  },
  left: {
    width: "35%",
    height: "100%",
    alignItems: "center",
  },
  right: {
    width: "65%",
    paddingLeft: 15,
    height: 90,
    // overflow: "hidden",
  },
  title: {
    fontSize: 14,
  },
  box: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    height: Platform.OS === "ios" ? 30 : 25,
    backgroundColor: Colors.grey,
    width: 130,
    borderRadius: 5,
    paddingHorizontal: 15,
    marginTop: 5,
  },
  boxMin: {
    width: "30%",
    alignItems: "center",
  },
  boxText: {
    fontSize: 16,
    backgroundColor: Colors.white,
    padding: 5,
  },
});

A: *

*Use onBlur instead of onEndEditing.

*How should the input end triggered?

*

*After a time?

*When user hits enter?

*When user taps anywhere to close software keyboard?

Instead of
onEndEditing={AddItemHandler}

Use:
onBlur={(e) => {AddItemHandler(e.nativeEvent.text)}}

And ensure that AddItemHandler can handle the value in e.nativeEvent.text.


text:
Q: Accessing environment variables of another machine in Ruby I am writing ruby script which accesses folders on other networked machines (windows). I need to know the environment variables on that machine, how do I do this? Once I get access to the remote environment variables, It will help me know where the software has been installed.
Thanks
N.I

A: Does your solution need to be pure Ruby? If not, you could use the PsExec command. The following will output the environment variables on remote (for the current user):
psexec \\remote cmd /C set

This works by executing cmd remotely and passing it the command set to run.
The following Ruby code will run PsExec and return the remote environment variables as a Hash:
Hash[*`psexec \\\\remote cmd /C set`.split("\n").
  collect {|i| i.split('=', 2)}.flatten]

A: You need to deploy simple HTTP-server with helper script that print to the output stream information you need (i.e environment variables, etc).
Next you have to call that script from remote machine, and parse results.
Or, without server, add scheduled task to your remote machine, that writes once per day required information to some known file (I mean to file at fixed path). It's much simpler, however you'll see delayed information changes.

A: I would recommend the ruby WMI interface.  As long as you have a fairly modern Windows (XP and up IIRC), you can fetch environment variables from remote machines easily.  Google for more information.