text:
Q: Removing null or blank values of array I have an array, I just print it as-
print_r($data);
It shows output as-
Array
(
    [0] => Array
        (
            [0] => Title
            [1] => Featured Image
            [2] => Catagories
            [3] => Tags
            [4] => Content
        )

    [1] => Array
        (
            [0] => title 1
            [1] => img1.jpg
            [2] => cat 1
            [3] => tag 1
            [4] => post 1 content
        )

    [2] => Array
        (
            [0] => title 2
            [1] => img2.jpg
            [2] => cat2
            [3] => tag 2
            [4] => post 2 content
        )

    [3] => Array
        (
            [0] => title 3
            [1] => img3.jpg
            [2] => cat3
            [3] => tag3
            [4] => post 3 content
        )

    [4] => Array
        (
            [0] =>
            [1] =>
            [2] =>
            [3] =>
            [4] =>
        )

    [5] => Array
        (
            [0] =>
            [1] =>
            [2] =>
            [3] =>
            [4] =>
        )

    [6] => Array
        (
            [0] =>
            [1] =>
            [2] =>
            [3] =>
            [4] =>
        )

)

I just want to remove blank or null values from array.
I tried array_dif() and array_filter() but still I couldn't remove null values.
How is this possible?
Thanks.

A: You can loop through the array, look for empty variables and use unset to remove them.

This code will loop through and check if the length of the first value in each array is at least one character long and unset it if its not.
<?php
foreach($data as $key => $value) {
    if(!isset($value[0][0]))
        unset($data[$key]);
}

This code will loop through the array in a similar way, except to check every value of every array to determine if its parrent array should be kept or left to be unset.
<?php
foreach($data as $key => $values) {
    foreach($values as $value) {
        if(isset($value[0]))
            continue 2;
    }
    unset($data[$key]);
}

A: You should use array_filter with a function that also runs array_filters against the subarrays and returns false if the filtered subarrays become empty.
<?php

$array = Array(
    Array(1, 2, 3),
    Array(null, null, null),
    Array(false, false, false),
    Array(3, 2, 1)
);

$filtered = array_filter($array, function($elem) {
    return count(array_filter($elem));
});

print_r($filtered);

?>


text:
Q: Buttons changing Tabs I want to make buttons change Tabs but i want the tabcontrol to be invisible (Only the page visible not the tabcontrol buttons).
I have 2 buttons Home and Settings and when the Form starts the Home page is visible and when the user clicks Settings button it changes to the Settings page and the same goes for Home button.
So what i need is for the Home and Settings tab buttons to be invisible and i want to only be able to use the buttons i created to change the pages. Hope someone understands. I use Visual Studio 2015 and C#.

A: Going by the name of your control (TabControl1) I am assuming this is WinForms.
You can achieve what you are describing without using a tab control at all, just move the contents of each of your tabs to seperate UserControls and then swap the visibility or positioning (or both) upon each button click.
For Home button click handler:
settingsUserControl.Visible = false;
homeUserControl.Visible = true;

Then repeat the reverse, in the Settings button click handler.
If you are using TabControl for its border, then use a Panel as a container to the UserControls.
In fact, this is similar to how Tab Controls worked in VB6, the control being hidden would be shoved 30,000 Twips off to the left, outside the view port of the tab control.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wordpress PerfectPixel theme I have a problem with my wordpress theme, I have been translating an english page into French, on  the english page, the pictures appear properly on the mainfrontpage but it doesn't appear on the french homepage.
Here is the english page: http://www.interactioncamps.org/
Here is the french page:

A: However you're calling your jquery.cycle plugin, the French page does not appear to be passing it any slides. Take a look at your browser's JavaScript console on the French page:
[cycle] terminating; too few slides: 0
jquery.cycle.all.js:33

Without seeing some reference code it's tough to say exactly what the problem is, but that should point you in the right direction.


text:
Q: How to send an email by My Android App without showing confirmation popup? I need some assistance please. I have Googled it but cannot seem to find an answer. I have an Android application, it has a process wizard that guides the user through different steps. Once all steps have been completed it needs to send a confirmation email based on the client email address saved in the local database. Getting the email address is not difficult but I have no idea how to send the email automatically without the app asking to use the email client.
Is there a way to do this?
This is the only code I have sofar:
private boolean sendEmail()
{
    boolean result = false;

    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setType("plain/text");

    return result;
}


text:
Q: Setting C++ debug environment in Visual Studio 2012 Express The application I need to debug expects environment variables to be set.
This seems ridiculously complicated in Visual Studio 2012. I'd like to do something like:
set path=c:\foo;c:\bar;c:\windows;c:\program files\application
set port=12345
set server=hulligulli

Microsoft tells me I should just "Use standard environment variable syntax". So I expected I could just open Configuration Properties/Debugging/Environment and write
set path=c:\foo;c:\bar;c:\windows;c:\program files\application
set port=12345
set server=hulligulli

Or:
path=c:\foo;c:\bar;c:\windows;c:\program files\application
port=12345
server=hulligulli

But both variants don't work. The upper doesn't set the path at all. In the lower version Visual Studio splits the entry on each space, so the three lines above become the four lines below:
path=c:\foo;c:\bar;c:\windows;c:\program
files\application
port=12345
server=hulligulli

These two variants below prevent the split-up, but they also prevent the path to be correctly formatted. Viz. the application won't find files in the path:
path=c:\foo;c:\bar;c:\windows;"c:\program files\application"
path="c:\foo;c:\bar;c:\windows;c:\program files\application"

After working around the space-in-path-problem by copying everything to paths without spaces, I found out, that seemingly only the first line of the environment is actually used. Viz. port and server are not set.
path=c:\foo;c:\bar;c:\windows;c:\alternative_path\application
port=12345
server=hulligulli

How do I set more than one environment variable in the Visual Studio debugging environment?
Bonus question: How do I use standard path entries (with spaces) in the Visual Studio debugging environment?

A: Visual Studio doesn't allow more than one environment variable to be set.
It's a known bug. And Microsoft has no intention to fix it.
Someone suggested to manually edit the vcproj.user-file and replace line-breaks by & #xD; & #xA; (that's: CRLF). But that fixes only the appearance in the environment Field, not the behavior.
Setting the variables in a <PropertyGroup> in the vcxproj-file as proposed in How to set environment variables in vs2012? doesn't help either.
Workaround: set the variables at the shell and then start Visual Studio from that shell.
Update:
This problem seems to be fixed in Visual Studio 2015.


text:
Q: Passing objects as parameters to other objects - null I'm building a railway simulator, with the classes simulator, station, train, route and passenger. I'm having a problem with passing a route object as a parameter to a train object - it keeps coming up as null. I've included my code as the best way to explain my problem.
import java.util.ArrayList;

public class Simulator {
int numStations;
Route route1;
ArrayList<Station> stations;
ArrayList<Train> trains;
Route[] routes;

public static void main(String[] args) {

    //set up network
    Simulator sim = new Simulator();
    ArrayList<Station> stations = new ArrayList<Station>();
    stations = sim.generateStations();
    Route[] routes;
    routes = sim.generateRoutes(stations);
    System.out.println("Route array " + routes);
    ArrayList<Train> trains = new ArrayList<Train>();
    trains = sim.generateTrains(routes);

    //start simulator
    sim.generatePassengers(stations);
    Train currentTrain = trains.get(0);
    System.out.println("current train " + currentTrain);
    //route null here
    System.out.println("Route of current train " + currentTrain.route);

}

public Route[] generateRoutes(ArrayList<Station> stations){
    //initialise routes between stations

    Station[] stationList1 = {stations.get(0), stations.get(1), stations.get(2), stations.get(3), stations.get(4), stations.get(5)};
    int[] stationDist1 = {200,100,200,300,200,300};
    Route route1 = new Route(true, stationList1, stationDist1);
    System.out.println("route1 " + route1);

    //make list of all routes
    Route[] routeList;
    routeList = new Route[1];
    routeList[0] = route1;

    return routeList;
}

public ArrayList<Train> generateTrains(Route[] routes){
    //initialise trains
    ArrayList<Train> trainList = new ArrayList<Train>();
    trainList.add(new Train(routes[0], 100, 0, true, 5));
    trainList.add(new Train(routes[0], 100, 4, false, 10));

    System.out.println("first train in list " + trainList.get(0));
    System.out.println("first route in array " + routes[0]);
    //route is null here
    System.out.println("route of first train " + (trainList.get(0)).route);

    return trainList;
}
}

Here is my output:

route1 Route@addbf1
Route array [LRoute;@42e816
Route1 in array Route@addbf1
first train in list Train@190d11
first route in array Route@addbf1
route of first train null
current train Train@190d11
Route of current train null

Can anyone explain where I'm going wrong?
Edit:
Train class declaration:
public class Train {
Route route;
int capacity;
int recentLoc;
boolean forwards;
boolean atStation;
int speed;
Train currentTrain;
int timeAtStation;

//train constructor
public Train(Route r, int c, int i, boolean f, int s){
    r = route;
    c = capacity;
    i = recentLoc;
    f = forwards;
    s = speed;
    atStation = true;
    timeAtStation = 0;
}

A: You're not assigning values to your instance variables. Default value for object is null. Change "r = route" into "route = r" inside your Train constructor (the same for all the other fields).
public class Train {
Route route;
int capacity;
int recentLoc;
boolean forwards;
boolean atStation;
int speed;
Train currentTrain;
int timeAtStation;

//train constructor
public Train(Route r, int c, int i, boolean f, int s){
    route = r;
    capacity = c;
    recentLoc = i;
    forwards = f;
    speed = s;
    atStation = true;
    timeAtStation = 0;
}

A: route = r;
capacity = c;

etc.

A: You have three issues in your output.
First is that when you want to print conntent for array you must iterate through its elemnts, otherwise you just print the memory adress. To help you out hava API have method to that:
Arrays.toString(Object[]);
Same problem is in your Train, you do not override the toString() method, that is why Java print it address as this is its default behaviour.
Try to add this method to your route class and see what happen,
@Override
public String toString(){
   return "This is message from rout"
}

Ant the last in the construtor of Train
You assing the parameters to variable. You should do vice versa.
public Train(Route r, int c, int i, boolean f, int s){
    this.route = r;
    this.capacity = c;
    this.recentLoc = i;
    this.forwards = f;
    this.speed = s;
    this.atStation = true;
    this.timeAtStation = 0;
}

A: These assignments should be the other way round, the thing on the left side is the thing getting assigned.
r = route;
c = capacity;
i = recentLoc;
f = forwards;
s = speed;

should be
 route = r;
   capacity = c;
   recentLoc = i;
    forwards = f;
    speed = s;

A: You are doing assignments wrong.
r = route;

it means that value of route will be assigned to r.
Change you constructor to following:
public Train(Route r, int c, int i, boolean f, int s)
{
     route = r;;
     capacity = c;;
     recentLoc = i;
     forwards = f;
     speed = s;
     atStation = true;
     timeAtStation = 0;
}


text:
Q: How to know whether late init has been initialized in dart(flutter)? I am fetching data from url in Flutter. I have a late init Map called tables. I am fetching data inside initState() function. When I first launch the app, I am getting LateInizialization error on the red screen. I want to detect whether late init is initialized and display spinner if it is not initialized. This is my code.
class TablesTab extends StatefulWidget {
  @override
  _TablesTabState createState() => _TablesTabState();
}

class _TablesTabState extends State<TablesTab> {
  late List<dynamic> tables;
  var refreshKey = GlobalKey<RefreshIndicatorState>();
  GetUriData tablesInstance = new GetUriData(url: '/api/table/getAllTables');

  void getTables() async {
    tables = await tablesInstance.getData();
  }

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

  Future<void> refreshList() async {
    refreshKey.currentState?.show(atTop: false);
    // await Future.delayed(Duration(seconds: 2));
    var updatedTables = await tablesInstance.getData();
    setState(() {
      tables = updatedTables;
    });

    //network call and setState so that view will render the new values
    print(tables);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
          child:  GridView.count(
            crossAxisCount: 4,
            children: List.generate(this.tables.length, (index) {
              return Center(
                child: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, '/tableReview', arguments: {'table': this.tables[index]});
                  },
                  child: Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                          border: Border.all(color: Theme.of(context).primaryColor, width: 2.0),
                          borderRadius: BorderRadius.all(Radius.circular(70))
                      ),
                      padding: const EdgeInsets.all(14.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            '${this.tables[index]['tableNum']}',
                            style: TextStyle(
                                color: Theme.of(context).primaryColor,
                                fontSize: 23
                            ),
                          ),
                        ],
                      )
                  ),
                ),
              );
            }),
          ),
          onRefresh: refreshList
      )
    );
  }

A: You can't check the initialization state of a late variable.  If that's something you need to know, you either will need to add and maintain a separate flag or make the variable nullable and compare to null instead.

I want to detect whether late init is initialized and display spinner if it is not initialized.

In your case you probably should use a FutureBuilder.

A: You can't know whether late field initialized or not.
I don't think you should use late in that case. Adding late to field means that the field will be initialized when you use it for the first time. In your code the field can be not initialized, so you'd better to use tables without late, initialize it with empty list and use boolean flag to indicate loading:
  var tables = [];
  var loading = false;

  ...

  Future<void> refreshList() async {
    ...
    setState(() {
      loading = true;
    });
    var updatedTables = await tablesInstance.getData();
    setState(() {
      tables = updatedTables;
      loading = false;
    });
    ...
  }

A: I think I found the answer, in my case, it is not about the mapController, it is about size
I added Flexible as parent of FlutterMap and map showing perfect
Try below code:
Flexible(
  child: FlutterMap(
    options: MapOptions(
      center: LatLng(51.5, -0.09),
      zoom: 5.0,
    ),
    layers: [
      TileLayerOptions(
        urlTemplate:
            'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
        subdomains: ['a', 'b', 'c'],
        tileProvider:
            NonCachingNetworkTileProvider(),
      ),
      MarkerLayerOptions(markers: [])
    ],
  ),
),

A: You can give any default value in the constructor if you are using late initializer or you can make them nullable but making nullable is hectic


text:
Q: executing a job containing a rest request from another job in talend So im working with talend esb 8 and i have a job let's call it "restjob" that contains a trestrequest some work and a trestresponse . i want to execute this job in another so i made a new job and i called the "restjob" with the component trunjob .
but i have a probleme when executing the job i have a lot of errors can someone help me maybe i have configured something wrong or something .
the log of errors :
    org.talend.designer.runprocess.ProcessorException: java.lang.Exception: [ERROR] [ERROR] Some problems were encountered while processing the POMs:
[ERROR] Unresolveable build extension: Plugin org.apache.felix:maven-bundle-plugin:5.1.1 or one of its dependencies could not be resolved: The following artifacts could not be resolved: org.codehaus.plexus:plexus-utils:jar:3.3.0, org.codehaus.plexus:plexus-classworlds:jar:1.2-alpha-9: Cannot access central (https://repo1.maven.org/maven2/) in offline mode and the artifact org.codehaus.plexus:plexus-utils:jar:3.3.0 has not been downloaded from it before. @
[ERROR] Unknown packaging: bundle @ line 14, column 14
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project org.example.api_discovery.service:create_user:0.1.0 (C:\Users\ASUS\Desktop\Studio\workspace\API_DISCOVERY\poms\jobs\process\api_discovery\create_user_0.1\pom.xml) has 2 errors
[ERROR]     Unresolveable build extension: Plugin org.apache.felix:maven-bundle-plugin:5.1.1 or one of its dependencies could not be resolved: The following artifacts could not be resolved: org.codehaus.plexus:plexus-utils:jar:3.3.0, org.codehaus.plexus:plexus-classworlds:jar:1.2-alpha-9: Cannot access central (https://repo1.maven.org/maven2/) in offline mode and the artifact org.codehaus.plexus:plexus-utils:jar:3.3.0 has not been downloaded from it before. -> [Help 2]
[ERROR]     Unknown packaging: bundle @ line 14, column 14
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/PluginManagerException

    at org.talend.designer.runprocess.ProcessorUtilities.generateBuildInfo(ProcessorUtilities.java:818)
    at org.talend.designer.runprocess.ProcessorUtilities.generateCode(ProcessorUtilities.java:706)
    at org.talend.designer.runprocess.ProcessorUtilities.generateCode(ProcessorUtilities.java:2029)
    at org.talend.designer.runprocess.RunProcessContext$2.run(RunProcessContext.java:663)
    at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:436)
    at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:352)
    at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:468)
    at org.eclipse.ui.internal.progress.ProgressMonitorJobsDialog.run(ProgressMonitorJobsDialog.java:228)
    at org.eclipse.ui.internal.progress.ProgressManager.run(ProgressManager.java:984)
    at org.talend.designer.runprocess.RunProcessContext.exec(RunProcessContext.java:610)
    at org.talend.designer.runprocess.ui.ProcessComposite.exec(ProcessComposite.java:1447)
    at org.talend.designer.runprocess.ui.views.ProcessView$RunAction.run(ProcessView.java:736)
    at org.talend.designer.runprocess.ui.actions.RunProcessAction.run(RunProcessAction.java:63)
    at org.talend.designer.core.debug.JobLaunchConfigurationDelegate$1$1.run(JobLaunchConfigurationDelegate.java:98)
    at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:40)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:185)
    at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4001)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3629)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1157)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1046)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:155)
    at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:644)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:551)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:156)
    at org.talend.rcp.intro.Application.start(Application.java:303)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:203)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:401)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:255)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:654)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1462)
Caused by: java.lang.Exception: [ERROR] [ERROR] Some problems were encountered while processing the POMs:
[ERROR] Unresolveable build extension: Plugin org.apache.felix:maven-bundle-plugin:5.1.1 or one of its dependencies could not be resolved: The following artifacts could not be resolved: org.codehaus.plexus:plexus-utils:jar:3.3.0, org.codehaus.plexus:plexus-classworlds:jar:1.2-alpha-9: Cannot access central (https://repo1.maven.org/maven2/) in offline mode and the artifact org.codehaus.plexus:plexus-utils:jar:3.3.0 has not been downloaded from it before. @
[ERROR] Unknown packaging: bundle @ line 14, column 14
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project org.example.api_discovery.service:create_user:0.1.0 (C:\Users\ASUS\Desktop\Studio\workspace\API_DISCOVERY\poms\jobs\process\api_discovery\create_user_0.1\pom.xml) has 2 errors
[ERROR]     Unresolveable build extension: Plugin org.apache.felix:maven-bundle-plugin:5.1.1 or one of its dependencies could not be resolved: The following artifacts could not be resolved: org.codehaus.plexus:plexus-utils:jar:3.3.0, org.codehaus.plexus:plexus-classworlds:jar:1.2-alpha-9: Cannot access central (https://repo1.maven.org/maven2/) in offline mode and the artifact org.codehaus.plexus:plexus-utils:jar:3.3.0 has not been downloaded from it before. -> [Help 2]
[ERROR]     Unknown packaging: bundle @ line 14, column 14
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/PluginManagerException

    at org.talend.designer.maven.launch.MavenCommandLauncher.execute(MavenCommandLauncher.java:401)
    at org.talend.designer.maven.launch.MavenPomCommandLauncher.execute(MavenPomCommandLauncher.java:57)

    at org.talend.designer.maven.tools.BuildCacheManager.build(BuildCacheManager.java:230)
    at org.talend.designer.runprocess.maven.MavenJavaProcessor.build(MavenJavaProcessor.java:422)
    at org.talend.designer.runprocess.ProcessorUtilities.generateBuildInfo(ProcessorUtilities.java:815)
    ... 38 more

A: 1- Make sure in maven settings "offline" is unchecked and try again.
2- Have you tried to stop studio -> rename the .m2 folder under your <studio_installation_dir>\configuration -> start studio to regenerate the .m2 folder?


text:
Q: MVVM pattern: IDataErrorInfo validation doesn't work if we have wrapped model inside another model The problem is that the red rectangle is not shown on the UI.
I use Caliburn.Micro and this is is what I have in my View:
<StackPanel Grid.Row="0">
     <Label>Customer name:</Label>
     <TextBox x:Name="txtName" Text="{Binding Target.Model.Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Width="136" HorizontalAlignment="Left"/>
</StackPanel>

Here is the ViewModel:
internal class ShellViewModel : Screen
{
    private EditableCustomer _Target;
    public EditableCustomer Target
    {
        get { return _Target; }
        set { if (_Target != value) { _Target = value; NotifyOfPropertyChange(nameof(Target)); } }
    }
}

This is what I have in the Model:
internal class EditableCustomer : PropertyChangedBase, IDataErrorInfo
{
    private CustomerInfo _Model;
    public CustomerInfo Model
    {
        get { return _Model; }
        set { if (_Model != value) { _Model = value; NotifyOfPropertyChange(nameof(Model)); } }
    }

}

And this is another Model:
internal class CustomerInfo : PropertyChangedBase
{
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set { _Name = value; NotifyOfPropertyChange(nameof(Name)); }
    }
}

I know I can move IDataErrorInfo interface from EditableCustomer to CustomerInfo model and everything will work perfectly if I do so, but the problem is that I'm not allowed to make any change in the CustomerInfo model,
Does anybody have any idea what else I can do?

A:
Does anybody have any idea what else I can do?

Since it is the class of the data bound property that should implement the IDataErrorInfo interface you will then need to bind to a property of the EditableCustomer class that wraps the Name property of the CustomerInfo model:
<TextBox x:Name="txtName" Text="{Binding Target.NameWrapper, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Width="136" HorizontalAlignment="Left"/>

internal class EditableCustomer : PropertyChangedBase, IDataErrorInfo
{
    private CustomerInfo _Model;
    public CustomerInfo Model
    {
        get { return _Model; }
        set { if (_Model != value) { _Model = value; NotifyOfPropertyChange(nameof(Model)); } }
    }

    //bind to this one instead of binding directly to the Name property of the model:
    public string NameWrapper
    {
        get { return _Model.Name; }
        set { _Model.Name = value; NotifyOfPropertyChange(nameof(NameWrapper)); }
    }

}

You will either have to do this or make the CustomerInfo class implement the IDataErrorInfo interface. Pick and choose.

A: Use Fluid Validations will be easy in xaml.
public class ModelValidator : AbstractValidator<Customer>
{
 public ModelValidator(){
   RuleFor(model => model.Name).NotEmpty().WithMessage("Name is Requried");
   RuleFor(model => model.Age).NotEmpty().WithMessage("Age is Required");
   RuleFor(model => model.Designation).NotEmpty().WithMessage("Choose Your Designation");
 }
}

This will be help for validations in wpf.
Once you refer about fluidValidations.


text:
Q: Apache Reverse Proxy with "or" Statement I have my apache2 .conf file for my site. Is it possible to have an "or" statement, so that the user who wants to access the api have either the required IP OR the certificate? It looks like this at the moment.
    <LocationMatch ^/api/devices/.+/stuff$>
      SSLVerifyClient require
    </LocationMatch>

    <LocationMatch ^/api/devices/.+/otherStuff$>
      SSLVerifyClient require

    </LocationMatch>

#possible OR statement here?

        <LocationMatch "/(api|websocket|admin|consulting)">
                 <RequireAny>
                     #IPs
                     Require ip XXX.XXX.XXX.XXX
                 </RequireAny>
         </LocationMatch>

Thanks!


text:
Q: Insert value in textfield - struts2+liferay in my jsp I have this code:
.....
    // get userid
    long userid = com.liferay.portal.util.PortalUtil.getUserId(request);
    String userName = com.liferay.portal.util.PortalUtil.getUserName(userid , "guest");
    %>

    <s:textfield name="user" value="<%=userName%>"></s:textfield>

I am not able to display in the textfield the username value.
Can you help me,please.
Thanks.

A: Scriptlets are not allowed to use with the Struts tags. And you cannot access the the scripting variable userName because it's not on the value stack. To make it available just create a new variable in the value stack that has a value of the scripting variable.
<s:set var="userName"><%=userName%></s:set>
<s:textfield name="user" value="%{#userName}"/>

Another approach that is not expected is to make use of known containers like request that are accessible to the struts tags.
<% request.setAttribute("userName", userName); %>
<s:textfield name="user" value="%{#request.userName}"/>

You may notice the difference that in the first example the new variable is created and scripting variable passed by value as string printed to the out. In the second example the scripting variable passed by reference.


text:
Q: Problems by ConvertToJson in Powershell I've written a script in Powershell showing the performance of the computer.
If I want to import the file via js, comes an error like: Uncaught SyntaxError: Unexpected token
I've tried much things, changed the output parameta 3 times and created psobjects nothing worked...
My Code:
    <#
Project: Statistik-Dashboard
Class: Get-Value

created by Nicolai
#>

#Disks
$ComuterSystem = Get-CimInstance -ClassName Win32_ComputerSystem
$storage = foreach ($Computer in $ComuterSystem) {
    $LogicalDisk = Get-CimInstance -ClassName win32_logicaldisk -ComputerName $ComuterSystem.Name
    $diskHash = @{}
    foreach ($disk in ($LogicalDisk | ? {$null -ne $_.DeviceId})) {
        $diskHash.Add($disk.DeviceID, $disk.Size)
    }

    [PSCustomObject]@{
        Name = $Computer.Name
        Model = $Computer.Model
        Manufacturer = $Computer.Manufacturer
        LogicalDisk = $LogicalDisk
        Disks = $diskHash
        Selection = $LogicalDisk | Select-Object DeviceID, VolumeName, Size, FreeSpace
    }
}

$disksum = $diskHash.count
$platte = (Get-PhysicalDisk)
$ssds = (Get-PhysicalDisk | ? model -Match 'ssd')
$ssdsum = 0
foreach($platte in $ssds) {
        $ssdsum++
}

#RAM
$ram_freephysical=0
$ram_totalvisible=0
$ram_freephysical=Get-WmiObject Win32_OperatingSystem | fl *freePhysical* | Out-String
$ram_totalvisible=Get-WmiObject Win32_OperatingSystem | fl *totalvisiblememory* | Out-String
$ram_freephysical = $ram_freephysical -replace '\D+(\d+)','$1'
$ram_totalvisible = $ram_totalvisible  -replace '\D+(\d+)','$1'
$ram = $ram_totalvisible - $ram_freephysical
$ram = [math]::Round($ram/$ram_totalvisible*10000)/100

#CPU
$cpu = (Get-WmiObject win32_processor | Measure-Object -Property LoadPercentage -Average | Select Average).Average

#Ojects
$Diskinfo = [PSCustomObject]@{
    CPUusage = $cpu
    RAMusage = $ram
}

$Utilization = [PSCustomObject]@{
    SSDsum = $ssdsum
    HDDsum = $hddsum
    Disksum = $disksum
}

$disks = [ordered]@{}
for ($i=1; $i -le $storage.Selection.Count; $i++) {
    $disks["Disk${i}"] = $storage.Selection[$i-1]
}

#collector
$stats = [ordered]@{
    Utilization = $Utilization
    Diskinfo = $Diskinfo
    $Computer.Name = $disks
}

#convertor
$file = "C:\Temp\$($ComuterSystem.Name).json"
ConvertTo-Json @($stats) | Add-Content -Path $file

The output of the convert:
{
    "Utilization":  {
                        "SSDsum":  2,
                        "HDDsum":  1,
                        "Disksum":  6
                    },
    "Diskinfo":  {
                     "CPUusage":  8,
                     "RAMusage":  81.84
                 },
    "W10-NICO":  {
                     "Disk1":  {
                                   "DeviceID":  "C:",
                                   "VolumeName":  "System",
                                   "Size":  63020462080,
                                   "FreeSpace":  31977562112
                               },
                     "Disk2":  {
                                   "DeviceID":  "D:",
                                   "VolumeName":  null,
                                   "Size":  null,
                                   "FreeSpace":  null
                               },
                     "Disk3":  {
                                   "DeviceID":  "F:",
                                   "VolumeName":  "Daten",
                                   "Size":  499529019392,
                                   "FreeSpace":  480264626176
                               },
                     "Disk4":  {
                                   "DeviceID":  "G:",
                                   "VolumeName":  "SSD",
                                   "Size":  63020462080,
                                   "FreeSpace":  62914928640
                               },
                     "Disk5":  {
                                   "DeviceID":  "H:",
                                   "VolumeName":  "System",
                                   "Size":  106779635712,
                                   "FreeSpace":  70762377216
                               },
                     "Disk6":  {
                                   "DeviceID":  "U:",
                                   "VolumeName":  "System",
                                   "Size":  106779635712,
                                   "FreeSpace":  70762377216
                               }
                 }
}

I hope somebody can help me :)

A: First of all, the JSON you provided (before editing) is invalid. The issue is that in
"Utilization":  [
                    "SSDsum":  2,
                    "HDDsum":  1,
                    "Disksum":  3
                ],

there should be curly brackets {} instead of square brackets []. Here's useful site to validate your JSON.

Another important thing is that it's not possible to get such output from ConvertFrom-JSON. The output will be:
{
    "Utilization":  {
                        "SSDsum":  2,
                        "HDDsum":  1,
                        "Disksum":  3
                    },
    "Diskinfo":  {
                     "CPUusage":  12,
                     "RAMusage":  60.45
                 },
    "W10-NICO":  {
                     "Disk1":  {
                                   "DeviceID":  "C:",
                                   "VolumeName":  "System",
                                   "Size":  63020462080,
                                   "FreeSpace":  35543621632
                               },
                     "Disk2":  {
                                   "DeviceID":  "F:",
                                   "VolumeName":  "Daten",
                                   "Size":  499529019392,
                                   "FreeSpace":  481141452800
                               },
                     "Disk3":  {
                                   "DeviceID":  "G:",
                                   "VolumeName":  "SSD",
                                   "Size":  63020462080,
                                   "FreeSpace":  62914928640
                               }
                 }
}

As @Ansgar Wiechers pointed out, you might also want to consider specifying -Depth parameter in your script so that the result is not trimmed unexpectedly (from what I see it default value, which is 2, will be enough in that particular case so I'm leaving it here as a reminder/best practice).

If the machine has only one disk your $disks will be empty. This is because:
$i -le $storage.Selection.Count

Will never evaluate to $true (as there's no .Count parameter for single object). You could fix it by using
$i -le @($storage.Selection).count

Credits to this answer.


text:
Q: How do I create and store a new object of a different type in to a specific Array list from the set methods? I am working on creating a GUI for a Gadget Shop that stores details of gadgets such as Mobile phones and MP3 players but I do not know how to return and store the values of these details as a new object of its type into the ArrayList of type Gadget.
I have done a lot of trial & error but could not be sure as to whether I was actually making any progress or not.
import java.util.ArrayList;
import java.awt.event.*;
import javax.swing.*;
public class GadgetShop implements ActionListener
{
    // instance variables - replace the example below with your own
    private JTextField modelTextField;
    private JTextField priceTextField;
    private JTextField weightTextField;
    private JTextField sizeTextField;
    private JTextField initialCreditTextField;
    private JButton addMobileButton;
    private JFrame frame;
    private ArrayList<Gadget> gadgets;

    /**
     * The GUI is created in the constructor.
     */
    public GadgetShop()
    {
        // initialise instance variables

        ArrayList<Gadget> gadgets = new ArrayList<Gadget>();

        frame = new JFrame("The Gadget Shop");
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new FlowLayout());

        modelTextField = new JTextField(15);
        contentPane.add(modelTextField);

        priceTextField = new JTextField(15);
        contentPane.add(priceTextField);

        weightTextField = new JTextField(15);
        contentPane.add(weightTextField);

        sizeTextField = new JTextField(15);
        contentPane.add(sizeTextField);

        initialCreditTextField = new JTextField(15);
        contentPane.add(initialCreditTextField);

        addMobileButton = new JButton("Add Mobile");
        contentPane.add(addMobileButton);
        addMobileButton.addActionListener(this);

        frame.pack();
        frame.setVisible(true);
    }

    /**
     * The main method allows the program to be run without BlueJ.
     */
    public static void main(String[] args)
    {
        GadgetShop calculator = new GadgetShop();
    }

    /**
     * Find which button triggered the event and call the appropriate method.
     */
    public void actionPerformed(ActionEvent event)
    {
        String command = event.getActionCommand();
        if (command.equals("Add Mobile")) {
            addMobile();
        }
    }

Below are the getMethods for the details of an object
    public String getModel()
    {
        String model
           = modelTextField.getText();
        return model;
    }

    public String getSize()
    {
        String size
           = sizeTextField.getText();
        return size;
    }

    public int getWeight()
    {
        int weight
           = Integer.parseInt(weightTextField.getText());
        return weight;
    }

    public double getPrice()
    {
        double price
           = Double.parseDouble(priceTextField.getText());
        return price;
    }

    public int getCredit()
    {
        int credit
           = Integer.parseInt(initialCreditTextField.getText());
        return credit;
    }

Below is my setMethod for storing the object of type Mobile into the Gadget ArrayList which I believe is wrong
    public void addMobile()
    {
        String mobile =
           getModel();    //Is this how I call the get Methods??
           getPrice();
           getWeight();
           getSize();
           getCredit();
        gadgets = new Mobile();
        gadgets.add(mobile);   //I get an error with the .add part
    }

}

I expected errors because I was not sure whether I had created the ArrayList correctly in the first place.


text:
Q: DirectoryNotFoundException - while uploading photos to facebook I am developing a windows phone app using facebook c# sdk. I am having a problem uploading a photo to a facebook wall. The exception occurred on the line "var imageStream = File.OpenRead(imagepath);". What i did wrong here??
void cameraCaptureTask_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult == TaskResult.OK)
        {
            Uri uri = new Uri(e.OriginalFileName, UriKind.RelativeOrAbsolute);
            //Code to display the photo on the page in an image control named myImage.
            WriteableBitmap bmp = PictureDecoder.DecodeJpeg(e.ChosenPhoto);

            myImage.Source = bmp;

            imageSource = this.SaveImageToLocalStorage(bmp,System.IO.Path.GetFileName(e.OriginalFileName));
        }
    }

    private string SaveImageToLocalStorage(WriteableBitmap image, string imageFileName)
    {

        if (image == null)
        {
            throw new ArgumentNullException("imageBytes");
        }
        try
        {
            var isoFile = IsolatedStorageFile.GetUserStoreForApplication();

            if (!isoFile.DirectoryExists("MyPhotos"))
            {
                isoFile.CreateDirectory("MyPhotos");
            }

            string filePath = System.IO.Path.Combine("/" + "MyPhotos" + "/", imageFileName);
            using (var stream = isoFile.CreateFile(filePath))
            {
                image.SaveJpeg(stream, image.PixelWidth, image.PixelHeight, 0, 80);
            }

            return new Uri(filePath, UriKind.Relative).ToString();
        }
        catch (Exception)
        {
            throw;
        }
    }

    private void ApplicationBarIconButton_Click(object sender, EventArgs e)
    {
        postImage(App.AccessToken,titleBox.Text + descriptionBox.Text, imageSource);
    }

    private void postImage(string p1, string p2, string imagepath)
    {
        FacebookClient fb = new FacebookClient(p1);
        var imageStream = File.OpenRead(imagepath);
        dynamic res = fb.PostTaskAsync("/me/photos", new
        {
            message = p2,
            file = new FacebookMediaStream
            {
                ContentType = "image/jpg",
                FileName = Path.GetFileName(imagepath)
            }.SetValue(imageStream)
        });

    }

A: You shouldn't pass a forward slashes (/) to Path.Combine. Path.Combine adds slahes for you.
string filePath = System.IO.Path.Combine("MyPhotos", imageFileName);

This will make the correct the correct path: MyPhotos/imageFileName where your original code makes the wrong path: /imageFileName
Edit:
In postImage() method use IsolatedStorageFile's OpenFile method instead of File.OpenRead.
var isf = IsolatedStorageFile.GetUserStoreForApplication();
var imageStream = isf.OpenFile(imagepath, FileMode.Open);


text:
Q: How to get values from the Cloned TextBox I am creating a Questionnaire like input form where I am asking the question of peoples favourite game consoles and games (as you can see from the code below) all this is in an outer div called duplicator. When I click the 'gamebut' button this calls the Jquery method duplicate() which clones that div so now there will be two divs, similar divs with the smilar textboxes in them. Because its being cloned I am unable to get the data out of it, it only gives me the data for the 1st(orginal) div. How can I get the values from the cloned div, any Suggestions?
MARKUP:

        Consoles
        Games

         <%=Html.TextBox("Consoles", ViewData["Consoles"] ?? "") %>

        <%=Html.TextBox("Games", ViewData["Games"] ?? "") %>

<button id="gamebut" type="button" onclick="duplicate()">Add new entry</button>

Javascript:
  document.getElementById('gamebut').onclick = duplicate;

  var i = 0;
  var original = document.getElementById('duplicator');

  function duplicate() {
      var clone = original.cloneNode(true);
      clone.id = "duplicator" + ++i;
      original.parentNode.parentNode.appendChild(clone);
  }

Controller Class:
[AcceptVerbs("POST")]
public ActionResult Game(string consoles, string games)
{
    ViewData["Consoles"] = consoles;
    ViewData["Games"] = games;
    ViewData["Forename"] = forename;

    if (ViewData.ModelState.IsValid)
    {

    }
    return View();
}

A: use classes and then iterate through them, so instead of accessing objects with their ID you use the jquery class selector aka
$(".CLASS_NAME");

make your input have a class and select via that class
lets say your input has
class="duplicated_input"

then you select and iterate like this.
var _inputs = $(".duplicated_input");

for(var i = 0; i < _inputs.length; i++)
{
    var _input = _inputs[i];
    //do your logic here.

}

example JSFIDDLE


text:
Q: Environment variable not set, from Netbeans I am calling an external program from my c program in netbeans, where I had to set a environment variable!
I did that by using this command:
export MY_VARIABLE=/exampe/path/

And then I run the program from the command line and it works, but when I start netbeans and run it, he is still complaining that the MY_VARIABLE is not set..
Am I missing something here?? I have netbeans 8.0 and OSX System

A: CommandLine exports only last for the active session ..
That said, you have to make sure it's set when the program is running.
You can run:
// will set only if $MY_VARIABLE isn't set
system("[[ -n $MY_VARIABLE ]] || export MY_VARIABLE=/example/path");

or
// will set anyways
system("export MY_VARIABLE=/example/path");

to make sure it is set
Alternatively, if that didn't work, you can set the environment variable from within netbeans.

Properties->Actions->Run Project->Set Properties: Add
  Env.MY_VARIABLE=/example/path


text:
Q: Stop Divs text from overlapping Does anyone know how I can stop two divs from overlapping?
I have a .box.active div however the text on this is overlapping into another div
thanks for any help in advance!

A: If DIVS are overlapping then the general principles is your code has made them do that in the first place. Add position relative to the classes on your div tags to start with along with Display block.
.yourdivclass {display:block}
.yourdivclass {display:inline-block}

Some other possibilities:

*

*Set widths on elements?

*Have you used FLEX? This can cause this often if your code has not been completed correctly?

Generally, we need more code to solve issues so if this does not help - provide some code in your question and I can help further.
Hope this helps.


text:
Q: Pb installig winehq on 20.04 (focal) Following the instructions from wiki.winehq.org/Ubuntu, I removed all traces of a previous version of wine (the apt key, all programs and associated programs, all previous references to repositories). I added the new repository for version 20.04, its key and enabled the 32-bit architecture. I ran apt update.
winhq-stable refuses to install, complaining about an unresolved dependency of wine-stable. The latter refuses to install, complaining of an unresolved dependency of wine-stable-i386. The installation of wine-stable-i386 complains of eight unresolved dependencies:
The following packages have unmet dependencies:
 wine-stable-i386:i386 : Depends: libgphoto2-6:i386 (>= 2.5.10) but it is not going to be installed
                         Depends: libgstreamer-plugins-base1.0-0:i386 (>= 1.0.0) but it is not going to be installed
                         Depends: libgstreamer1.0-0:i386 (>= 1.4.0) but it is not going to be installed
                         Depends: libldap-2.4-2:i386 (>= 2.4.7) but it is not going to be installed
                         Depends: libsane:i386 (>= 1.0.24) but it is not going to be installed
                         Recommends: libcups2:i386 but it is not going to be installed
                         Recommends: libfontconfig1:i386 but it is not going to be installed
                         Recommends: libfreetype6:i386 but it is not going to be installed
                         Recommends: libgnutls30:i386 but it is not going to be installed or
                                     libgnutls28:i386 but it is not installable or
                                     libgnutls26:i386 but it is not installable

In the case of winhq-devel, the pattern is the same, the list for wine-devel-i386
is a bit shorter (only the last five direct dependencies).
I did some research, on this site (askubuntu.com/questions/tagged/wine+20.04) and others;
I found similar questions (less detailed), but NO PROPOSED SOLUTION.
I've tried to resolve the dependencies of *-i386 packages, but it seems to be endless...
At some level, sudo apt --fix-broken install offers more destructive than constructive solutions
and do not (as far as I have tried) lead to a positive outcome.
If no one knows the answer, I will try first an upgrade to Ubuntu 22.04 (Jammy Jellyfish).(Translated from french with www.DeepL.com/Translator)
Thanks for your help.


text:
Q: Ignore Empty Cells I wonder if someone could help me.
I have set up the script coding below to generate a Google Doc Template based on data in a Google Sheet.
The issue I'm having is that when I run the AutoFill Docs process within google sheets, it's creating the letter and adding spaces in the letter for any cells that are empty.
So for example, I have 4 headings (Address 1, Address 2, Address 3 and Address 4) based on the customer's details not all of these are filled.
When the letter/ google doc is generated, it's putting spaces in for the empty cells (See below)
Bob  Smith
32 Bob Road
Bobbington
B23 4YH
for empty cells, I need it to ignore these and generate the letter as below:
Bob  Smith
32 Bob Road
Bobbington
B23 4YH
Any help would be much appreciated.
Thanks
Chris
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  const menu = ui.createMenu('AutoFill Docs');
  menu.addItem('Create New Docs', 'createNewGoogleDocs')
  menu.addToUi();

}

function createNewGoogleDocs() {

  const googleDocTemplate = DriveApp.getFileById('1oa-BtAhFKsvJ37Dl26Xvt2QTe9HjSz8vE9YVhtXjPA8');
  const destinationFolder = DriveApp.getFolderById('1kPVjBvCrdtb6k3bafl-g-s64b40-oH6I')
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Daysavers')
  const rows = sheet.getDataRange().getValues();

  rows.forEach(function(row, index){
  if (index === 0) return;
  if (row[10]) return;

  const copy = googleDocTemplate.makeCopy(`${row[1]}, ${row[2]} Customer Details` , destinationFolder)
  const doc = DocumentApp.openById(copy.getId())
  const body = doc.getBody();

  body.replaceText('{{Case Reference}}', row[0]);
  body.replaceText('{{First Name}}', row[1]);
  body.replaceText('{{Last Name}}', row[2]);
  body.replaceText('{{Address 1}}', row[3]);
  body.replaceText('{{Address 2}}', row[4]);
  body.replaceText('{{Address 3}}', row[5]);
  body.replaceText('{{Address 4}}', row[6]);
  body.replaceText('{{Postcode}}', row[7]);
  body.replaceText('{{First Name 2}}', row[8]);
  body.replaceText('{{Number}}', row[9]);

  doc.saveAndClose();
  const url = doc.getUrl();
  sheet.getRange(index + 1, 11).setValue(url)

  })

}

A: I guess it is not the script putting space, but just the space between the address items leaving there.
body.replaceText(' {{Address 2}}', row[4] ? ' ' + row[4] : '');

Do this with 3 and 4 also

A: If the row of the spreadsheet always holds the data you want to insert, in the correct order, you could avoid the multiple placeholders in your template and just put a single placeholder, then replace all of your body.replaceText(...) lines with a single line:
body.replaceText('{{Single Placeholder}}', row.filter(Boolean).join(' '));

row.filter(Boolean) produces an array with only the cell values that have non-empty strings or non-zero number values, and .join(' ') joins them all into one space-separated string.
If you still get the line breaks, it's possible there are newline characters in your spreadsheet cells.  Eliminate them with .replace(/\n/g,'')
body.replaceText('{{Single Placeholder}}', row.filter(Boolean).join(' ').replace(/\n/g,'');


text:
Q: Counter and accumulator in a java loop I'm doing this program: Given an integer, n, if the sum of its divisors (not counting itself) equals n, that number is said to be perfect. If the sum is lower, it is said to be decient, and if it is higher it is said to be abundant. For example:
6 has divisors 1,2,3: they add 6, therefore 6 is perfect. 8 has divisors 1,2,4: they add 7, therefore 8 is deciente. 24 has divisors 1,2,3,4,6,8,12: they add 36, therefore 24 is abundant.
Write a program that reads two positive integers and displays, on the screen, how many numbers there are of each type in that interval (including the extremes).
I have the following code and I know where it fails, for example if I enter a single number, I do it well, example of entries 6 and 7. If I then enter 6 and 9 the output is Perfect 1 Deficient 0 Abundant 2, when I should to be Perfect 1 Deficient 2 Abundant 0. Variable j stores the divisors of all in the variable j and then that's why it's abundant but I have not been able to correct it for more than I've tried.
import java.util.Scanner;

public class PerfectNumbers {

public static void main(String[] args) {

System.out.println("Enter two numbers for the interval:");
Scanner teclado = new Scanner(System.in);
int x = teclado.nextInt();
int y = teclado.nextInt();

int cont1 = 0;
int perfect = 0;
int deficient = 0;
int abundant = 0;

for (int i = x; i < y; i++) {
    for (int j = 1; j < i; j++) {

        if (i % j == 0) {

            cont1 += j;
        } else {
            cont1 += 0;
        }

    }
    if (cont1 == x) {
        perfect += 1;
    } else if (cont1 < x) {
        deficient += 1;
    } else if (cont1 > x) {
        abundant += 1;
    }
}

System.out.println("Perfect"+ perfect);
System.out.println("Deficient"+ deficient);
System.out.println("Abundant"+ abundant);
}
}

A: One problem is that you didn't reset cont1.
Another problem is that instead of comparing to x to decide perfect/deficient/abundant, you need to compare to i.
for (int i = x; i < y; i++) {
    cont1 = 0;
    for (int j = 1; j < i; j++) {
        if (i % j == 0) {
            cont1 += j;
        }
    }

    if (cont1 == i) {
        perfect += 1;
    } else if (cont1 < i) {
        deficient += 1;
    } else {
        abundant += 1;
    }
}

I think the second problem was easy to overlook because of the poor naming of variables. I suggest to improve that, and it will be easier to read and harder to make such mistakes:
for (int n = start; n < end; n++) {
    sum = 0;
    for (int j = 1; j < n; j++) {
        if (n % j == 0) {
            sum += j;
        }
    }

    if (sum == n) {
        perfect++;
    } else if (sum < n) {
        deficient++;
    } else {
        abundant++;
    }
}


text:
Q: Special characters in document names in SharePoint Online To test support of special characters in document names we created test files and uploaded them to document library:

When we try to open such file, an error message appears:

Of course, the file is valid JPG, which can be viewed very fine in the same SharePoint instance under another name. Preview breaks only when the file is renamed.
Is it a bug of SharePoint? What characters are allowed in file names to enable preview?
Any advice will be highly appreciated. Thank you.

A: I did the test just now but i am able to see the preview.I uploaded into a document library. here are the results.

But what i am thinking, may be your jpg is corrupted, can you upload a new jpg without any spl character and see if that works. In which list / library you uploaded the file?

A: If a file or folder you're trying to upload to contains any of the characters listed below, it may prevent files from being previewed. Rename the file or folder to remove these characters.
Characters that aren't allowed in file and folder names in SharePoint Online
" * : < > ? / \ |

Characters that aren't allowed in file and folder names in SharePoint Server 2013
~ " # % & * : < > ? / \ { | }.

Invalid file names and file types in OneDrive, OneDrive for Business, and SharePoint


text:
Q: Switching between two background colors of a web page with CSS Switch my code works fine I just need to switch between two colors white and black I need help to modify the JavaScript code to turn switch between white and black colors.
-CSS

-HTML
       <input class='checkbox' id='switch' type='checkbox'/>

ON   OFF

-Javascript

again
my code works fine I just need to switch between two colors white and black I need help to modify the JavaScript code to turn switch between white and black colors.
any ideas ??? thank!

A: getElementByClassName returns collection
So code should be
//add [0] to both getElementByClassName
document.getElementsByClassName("mainWrapper")[0].style.backgroundColor

Also there isn't any class mainWrapper here so you should create a parent div with class mainWrapper

A: getElementsByClassName() returns an html collection object. It is a collection. If you want to find the first element with the class, you need to use the index [0] like below -
document.getElementById("tog-bg").addEventListener('click', function(){
    document.getElementsByClassName("mainWrapper")[0].style.backgroundColor = document.getElementById("tog-bg").checked ? "white" : "black";
});

If you want to do this for all elements with the specified class, then you can loop it like below -
document.getElementById("tog-bg").addEventListener('click', function(){
    for(let i = 0; i < document.getElementsByClassName("mainWrapper").length; i++){
        document.getElementsByClassName("mainWrapper")[i].style.backgroundColor = document.getElementById("tog-bg").checked ? "white" : "black";
    }
});

I am using the ternary operator instead of if else condition in the above snippet. Also, I have replaced the change event with click event in the listener.

A: This worked for me in firefox (not styled, but functional) :
document.getElementById("tog-bg").onclick = function(){
      var e;
    if( (e = document.getElementById("tog-bg")).hasAttribute('checked')) {
      var w = document.getElementsByClassName("mainWrapper ");
      for(i=0;i<w.length;++i)
      {
        w[i].style.backgroundColor = "black";
      }
      e.removeAttribute('checked');
    } else {
      var w = document.getElementsByClassName("mainWrapper ");
      for(i=0;i<w.length;++i)
      {
        w[i].style.backgroundColor = "white";
      }
      e.setAttribute('checked','');
    }
  };


text:
Q: My dogs won't stand up in Minecraft In Minecraft for Wii U, my dogs had been working fine for ages. However, one time one of my dogs was in a boat that I destroyed, and following this the dog wouldn't stand up. Then, none of my other dogs would stand up either.
Does anyone know how to fix this?


text:
Q: match count from neo4j and python given this code block
                parent_node_count = db.run(f"MATCH(parentNode) WHERE "
                              f"parentNode.LC = '{x[4]}' "
                              f"AND parentNode.U = '{x[5]}' "
                              f"AND parentNode.R = '{x[6]}' "
                              f"AND parentNode.Type = 'Parent' "
                              f"AND parentNode.Deck_Set = '{outline}' "
                              f" return parentNode")
            n = 0

            for record in parent_node_count:
                print(record["parent_node_count"]["id"])
                n = n + 1

            print("total number of records : " + str(n))
            total = int(n)

How do I get the number of matches from the MATCH query?
In the code provided, it always returns 0,
and I've check it in the browser, and the count from the match does not equal zero.

A: The variable parent_node_count is a neo4j.work.result.Result object and it does not contain the object id. You need to add it in the cypher query and access it via record.data() object.  See example below:
    parent_node_count = tx.run(f"MATCH(parentNode) WHERE "
                          f"parentNode.LC = '{x[4]}' "
                          f"AND parentNode.U = '{x[5]}' "
                          f"AND parentNode.R = '{x[6]}' "
                          f"AND parentNode.Type = 'Parent' "
                          f"AND parentNode.Deck_Set = '{outline}' "
                          f" return parentNode, ID(parentNode) AS id")
    print(parent_node_count)
    n = 0

    for record in parent_node_count:
        print(record.data()["parentNode"])
        print(record.data()["id"])
        n = n + 1

    print("total number of records : " + str(n))
    total = int(n)

Result:
<neo4j.work.result.Result object at 0x7ff6cd035f60>    <- parent_node_count
{'Latitude': 28.5553263, 'Longitude': 68.2132128, 'Name': 'Dayna'} <- record
321  <- id
{'Latitude': 54.1863169, 'Longitude': 19.7204087, 'Name': 'Dione'} <- record
333  <- id
total number of records : 2


text:
Q: gnuplot postscript+eps linewidth How to adjust linewidth in the postscript+eps terminal? I need to get linewidth=1.0 (border or axis), linewidth=1.8 (data-file1), linewidth=1.0 (data-file2)
set terminal postscript eps enhanced font 'Times-Roman,14' lw 1.5
    set output 'figure.eps'
...

plot 'P-Density.txt' u 1:(0.415+$2) axes x1y2 title '(1,0,0)' w line lt 1 lc 9 lw 1.8, 'P-Density.txt' u 1:(0.472+$3) axes x1y2 title '(1,1,0)' w line lt 1 lc 1 lw 1.8, 'P-Density.txt' u 1:(0.658+$4) axes x1y2 title '(1,2,0)' w line lt 1 lc 3 lw 1.8, 'Potential.txt' u 1:2 title '' w line ls -1 lw 1.2, 'enerji2_7_1.txt' u 1:2 title '' w line lt 2 lc 9 lw 1.0, 'enerji2_7_2.txt' u 1:2 title '' w line lt 2 lc 1 lw 1.0, 'enerji2_7_3.txt' u 1:2 title '' w line lt 2 lc 3 lw 1.0

A: In the "postscript" terminal, the thickness of the tick marks will follow the line width set by the set border command, but the border is designed to be twice as thick.
Then, if you want the border line to be 1.0 thickness, you can set it as follows.
set border lw 0.5

Instead, the tick marks thickness will be set to 0.5.
If you want the line width of the border and tick marks to match, you need to change the contents of the file "prologue.ps", which is embedded in the header of the output postscript file. gnuplot provides a mechanism to replace this header with your own customized "prologue.ps" file. See help set psdir for details.
You can try it by copying the 'prologue.ps' file that comes with gnuplot to the current directory, and changing the line,
/LTB {BL [] LCb DL} def

to the following.
/LTB {PL [] LCb DL} def

Then, change your script as,
set terminal postscript eps enhanced font 'Times-Roman,14'
set psdir '.'
set output 'figure.eps'

set border lw 1.0

... your plot command ...


text:
Q: RHEL 8 manage server boot order We run RHEL 8 servers we need to ensure NFS share is available or service running before start another service that depend on NFS share because that service need R/W into/from NFS share.
what our options to achieve this request ? can we control which service will run on which order?
I understand there is an option to add 'Required' entry into service.
please assist.
BR
Shlco

A: A systemd shortcut for depending on a certain path be mounted is RequiresMountsFor. Convenient as only the path is required, it will figure out the mounts needed.
Making up an example, say service thing requires NFS share /srv/data to be mounted. Taking advantage of drop-in directories, this override can be applied separately from the rest of the unit:
# /etc/systemd/system/thing.service.d/mount.conf
[Unit]
RequiresMountsFor=/srv/data


text:
Q: DLookup When Trying Use Form Field as Criteria I am new to Access and also to VB. I have a report that displays information on transformers, the report displays data from a query that queries data from two different tables. I would like to use a button to open a PDF document saved in one of the tables.
The code I have so far is this:
Private Sub Command70_Click()

    Dim hypa As String

    hypa = DLookup("[TestReport]", "TransformerPics", "TxID =  " & [Reports]![TransformerInfoSheet]!TXID)

    Application.FollowHyperlink [hypa]

End Sub

The error i get is Run-time error '2471' The expression you have entered as a parameter produced this error: 'TP00686'
TP00686 is the transformer number that is displayed on the report.

A: You need to have some quotes in there:
hypa = DLookup("[TestReport]", "TransformerPics", "TxID =  '" & [Reports]![TransformerInfoSheet]!TXID & "'")

Please also see:

*

*DLookup Usage Samples

*Dlookup using a string variable as criteria parameter


text:
Q: Keyboard Shortcuts no longer working on ALL Delphi versions on this Windows 10 PC One of my favorite Delphi IDE keyboard shortcuts is the handy Ctrl-K-I, that let's me indent a block of code that contains existing indents, and which indents the selected set to the right, while keeping all lines in the block at their same relative indent.
I was using this shortcut, but I apparently hit a wrong key on the keyboard.  Suddenly I found that ALL keyboard shortcuts had stopped working -- in ALL versions of Delphi on this Windows 10 PC.
Windows shortcuts like Ctrl-V still work, and GExperts shortcuts also still work, but the Delphi key mapping shortcuts in the IDEs no longer work.
I would think this would be some sort of Windows connection used between all Delphi IDEs and Windows, but I haven't found anything to fix this yet.
Any clues?


text:
Q: Laravel authorization call wrong policy I created all the policies with command artisan, php artisan make:policy ModelPolicy --model=ModelName, created UserPolicy and ProfilePolicy, the first one works fine, but the second one (ProfilePolicy) is calling UserPolicy.
ProiflePolicy.php
<?php

namespace App\Policies;

use App\Models\Profile;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Auth\Access\Response;

class ProfilePolicy {

    use HandlesAuthorization;

    // I'm use this to know what policy is being called
    protected $template = '[ProfilePolicy] you cannot %s this resource!';

    /**
     * Determine whether the user can view any models.
     *
     * @param  \App\Models\User  $user
     * @return mixed
     */
    public function viewAny(User $user) {
        return in_array( $user->profile->slug, ['administrator'] )
            ? Response::allow()
            : Response::deny( sprintf( $this->template, 'LIST') );
    }

    ...

AuthServiceProvider.php
<?php

namespace App\Providers;

use App\Models\Profile;
use App\Policies\ProfilePolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // \App\Models\User::class => \App\Policies\UserPolicy::class,
        Profile::class => ProfilePolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

ProfileController.php
<?php

namespace App\Http\Controllers\v0;

use App\Models\Profile;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;

class ProfilerController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index( Request $request ) {

        $query =  Profile::query();

        // UserPolicy is being called even commented
        \Gate::authorize('viewAny', auth('staff')->user() );

        query_page( $query, $request );

        query_embed( new Profile, $query, $request );

        $query->when( in_array(auth('staff')->user()->profile->slug, ['seller-manager']), function( $query ) {
            return $query->whereSlug( 'seller' );
        });

        $data = $query->limit( $request->limit ?: config('app.limit_per_page') )->get();

        return response()->json( responseFormat( false, $data ) );
    }
    ....

API Response:


text:
Q: MIP/LP - Modelling "if b=1 then x=y" constraint I have a Mixed Integer Programming (MIP) problem, currently modelled in Python's PuLP library. My issue is however very generic, syntax doesn't play a role here.
I want to add a constraint to my model that works like this:
if b=1 then x=y

The variable b is a binary variable taking values 0 or 1. x and y are variables that represent the current stock level. x as a continuous variable, y as an integer variable.
I know constraints can only be modelled in the following format:
a*x+c <= y    # a, c are constants, x, y variables

I hope there is some workaround how I can model the above described if b then x equals y constraint.
Here are my approaches so far:
b*y <= x
y >= x*b   # works in theory, but multiplication of 2 variables is not allowed

For 2 binary variables x and y the following is true:
M*y > x    # represents: if x then y (M is a sufficient large constant)

I guess the solution involves a large M constant, maybe even further helper variables.
A little background: I want to model an inventory problem, with continuous stock levels. However, order decisions should only be possible in integer numbers. I therefore need the stock level to be modelled with float numbers. At the point of order (b==1) however in integer.
I hope someone can help here, even if this is rather theoretic than directly coding related. Hints to further resources that might help are also highly appreciated.

A: b=1 => x=y

can be modeled as:
y-M(1-b) <= x <= y+M(1-b)


text:
Q: how to fix tab bar to bottom of mobile screen while scrolling without animation I have a tab bar that is fixed to the bottom of the screen in mobile.
When I scroll the page up, there is a 'glitch' - the tab bar hangs in its position for 1sec before suddenly dropping to the bottom of the screen.
How do I remove this glitch or animation ?
Below is my code:
.mobile-nav-overlay {
    position: fixed;
    bottom: 0px;
    left: 0px;
    width: 100%;
    z-index: 99999;
    background: #ebe7dd;
    display: -webkit-box;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    border-top: 1px solid #d2cec5;
}


text:
Q: How to allow Web Workers to receive new data while it still performing computation? I want to sort an array, using Web Workers. But this array might receive new values over time, while the worker is still performing the sort function.
So my question is, how can I "stop" the sorting computation on the worker after receiving the new item, so it can perform the sort on the array with that item, while still keeping the sorting that was already made?
Example:
let worker = new Worker('worker.js');
let list = [10,1,5,2,14,3];
worker.postMessage({ list });
setInterval(() => worker.postMessage({ num: SOME_RANDOM_NUM, list }), 100);

worker.onmessage = event => {
  list = event.data.list;
}

So lets say that, I've passed 50, the worker made some progress in the sorting before that and now I have something like this:
[1, 2, 3, 10, 5, 14, 50]. Which means the sorting stopped at index 3. So I pass this new array back to the worker, so it can continue the sorting from position 3.
How can I accomplish that, since there is no way to pause/resume a web worker?

A: Even though the Worker works on an other thread than the one of your main page, and can thus run continuously without blocking the UI, it still runs on a single thread.
This means that until your sort algorithm has finished, the Worker will delay the execution of the message event handler; it is as blocked as would be the main thread.
Even if you made use of an other Worker from inside this worker, the problem would be the same.
The only solution would be to use a kind of generator function as the sorter, and to yield it every now and then so that the events can get executed.
But doing this will drastically slow down your sorting algorithm.
To make it better, you could try to hook to each Event Loop, thanks to a MessageChannel object: you talk in one port and receive the message in the next Event loop. If you talk again to the other port, then you have your own hook to each Event loop.
Now, the best would be to run a good batch in every of these Event loop, but for demo, I'll call only one instance of our generator function (that I borrowed from this Q/A)

const worker = new Worker(getWorkerURL());
worker.onmessage = draw;

onclick = e =>     worker.postMessage(0x0000FF/0xFFFFFF); // add a red pixel

// every frame we request the current state from Worker
function requestFrame() {
  worker.postMessage('gimme a frame');
  requestAnimationFrame(requestFrame);
}
requestFrame();

// drawing part
const ctx = canvas.getContext('2d');
const img = ctx.createImageData(50, 50);
const data = new Uint32Array(img.data.buffer);
ctx.imageSmoothingEnabled = false;

function draw(evt) {
  // converts 0&1 to black and white pixels
  const list = evt.data;
  list.forEach((bool, i) =>
    data[i] = (bool * 0xFFFFFF) + 0xFF000000
  );
  ctx.setTransform(1,0,0,1,0,0);
  ctx.clearRect(0,0,canvas.width,canvas.height);
  ctx.putImageData(img,0,0);
  // draw bigger
  ctx.scale(5,5);
  ctx.drawImage(canvas, 0,0);
}

function getWorkerURL() {
  const script = document.querySelector('[type="worker-script"]');
  const blob = new Blob([script.textContent]);
  return URL.createObjectURL(blob);
}
body{
  background: ivory;
}

 click to add red pixels

<canvas id="canvas" width="250" height="250"></canvas>

Note that the same can be achieved with an async function, which may be more practical in some cases:

const worker = new Worker(getWorkerURL());
worker.onmessage = draw;

onclick = e =>     worker.postMessage(0x0000FF/0xFFFFFF); // add a red pixel

// every frame we request the current state from Worker
function requestFrame() {
  worker.postMessage('gimme a frame');
  requestAnimationFrame(requestFrame);
}
requestFrame();

// drawing part
const ctx = canvas.getContext('2d');
const img = ctx.createImageData(50, 50);
const data = new Uint32Array(img.data.buffer);
ctx.imageSmoothingEnabled = false;

function draw(evt) {
  // converts 0&1 to black and white pixels
  const list = evt.data;
  list.forEach((bool, i) =>
    data[i] = (bool * 0xFFFFFF) + 0xFF000000
  );
  ctx.setTransform(1,0,0,1,0,0);
  ctx.clearRect(0,0,canvas.width,canvas.height);
  ctx.putImageData(img,0,0);
  // draw bigger
  ctx.scale(5,5);
  ctx.drawImage(canvas, 0,0);
}

function getWorkerURL() {
  const script = document.querySelector('[type="worker-script"]');
  const blob = new Blob([script.textContent]);
  return URL.createObjectURL(blob);
}
body{
  background: ivory;
}

 click to add red pixels

<canvas id="canvas" width="250" height="250"></canvas>

A: There are two decent options.
Option 1: Worker.terminate()
The first is just to kill your existing web worker and start a new one. For that you can use Worker.terminate().

The terminate() method of the Worker interface immediately terminates the Worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once.

The only downsides of this approach are:

*

*You lose all worker state. If you had to copy a load of data into it for the request you have to do it all again.

*It involves thread creation and destruction, which isn't as slow as most people think but if you terminate web workers a lot it might cause issues.

If neither of those are an issue it is probably the easiest option.
In my case I have lots of state. My worker is rendering part of an image, and when the user pans to a different area I want it to stop what it is doing and start rendering the new area. But the data needed to render the image is pretty huge.
In your case you have the state of your (presumably huge) list that you don't want to use.
Option 2: Yielding
The second option is basically to do cooperative multitasking. You run your computation as normal, but every now and then you pause (yield) and say "should I stop?", like this (this is for some nonsense calculation, not sorting).
let requestId = 0;

onmessage = event => {
  ++requestId;
  sortAndSendData(requestId, event.data);
}

function sortAndSendData(thisRequestId, data) {
  let isSorted = false;
  let total = 0;

  while (data !== 0) {
    // Do a little bit of computation.
    total += data;
    --data;

    // Check if we are still the current request ID.
    if (thisRequestId !== requestId) {
      // Data was changed. Cancel this sort.
      return;
    }
  }

  postMessage(total);
}

This won't work though because sortAndSendData() runs to completion and blocks the web worker's event loop. We need some way to yield just before thisRequestId !== requestId. Unfortunately Javascript doesn't quite have a yield method. It does have async/await so we might try this:
let requestId = 0;

onmessage = event => {
  console.log("Got event", event);
  ++requestId;
  sortAndSendData(requestId, event.data);
}

async function sortAndSendData(thisRequestId, data) {
  let isSorted = false;
  let total = 0;

  while (data !== 0) {
    // Do a little bit of computation.
    total += data;
    --data;

    await Promise.resolve();

    // Check if we are still the current request ID.
    if (thisRequestId !== requestId) {
      console.log("Cancelled!");
      // Data was changed. Cancel this sort.
      return;
    }
  }

  postMessage(total);
}

Unfortunately it doesn't work. I think it's because async/await executes things eagerly using "microtasks", which get executed before pending "macrotasks" (our web worker message) if possible.
We need to force our await to become a macrotask, which you can do using setTimeout(0):
let requestId = 0;

onmessage = event => {
  console.log("Got event", event);
  ++requestId;
  sortAndSendData(requestId, event.data);
}

function yieldToMacrotasks() {
  return new Promise((resolve) => setTimeout(resolve));
}

async function sortAndSendData(thisRequestId, data) {
  let isSorted = false;
  let total = 0;

  while (data !== 0) {
    // Do a little bit of computation.
    total += data;
    --data;

    await yieldToMacrotasks();

    // Check if we are still the current request ID.
    if (thisRequestId !== requestId) {
      console.log("Cancelled!");
      // Data was changed. Cancel this sort.
      return;
    }
  }

  postMessage(total);
}

This works! However it is extremely slow. await yieldToMacrotasks() takes approximately 4 ms on my machine with Chrome! This is because browsers set a minimum timeout on setTimeout(0) of something like 1 or 4 ms (the actual minimum seems to be complicated).
Fortunately another user pointed me to a quicker way. Basically sending a message on another MessageChannel also yields to the event loop, but isn't subject to the minimum delay like setTimeout(0) is. This code works and each loop only takes ~0.04 ms which should be fine.
let currentTask = {
  cancelled: false,
}

onmessage = event => {
  currentTask.cancelled = true;
  currentTask = {
    cancelled: false,
  };
  performComputation(currentTask, event.data);
}

async function performComputation(task, data) {
  let total = 0;

  let promiseResolver;

  const channel = new MessageChannel();
  channel.port2.onmessage = event => {
    promiseResolver();
  };

  while (data !== 0) {
    // Do a little bit of computation.
    total += data;
    --data;

    // Yield to the event loop.
    const promise = new Promise(resolve => {
      promiseResolver = resolve;
    });
    channel.port1.postMessage(null);
    await promise;

    // Check if this task has been superceded by another one.
    if (task.cancelled) {
      return;
    }
  }

  // Return the result.
  postMessage(total);
}

I'm not totally happy about it - it relies on postMessage() events being processed in FIFO order, which I doubt is guaranteed. I suspect you could rewrite the code to make it work even if that isn't true.

A: You can do it with some trick – with the help of setTimeout function interrupting. For example it is not possible without an addition thread to execute 2 functions parallel, but with setTimeout function interrupting trick we can do it like follows:
Example of parallel execution of functions

var count_0 = 0,
    count_1 = 0;

function func_0()
{
    if(count_0 < 3)
        setTimeout(func_0, 0);//the same: setTimeout(func_0);

    console.log('count_0 = '+count_0);
    count_0++
}

function func_1()
{
    if(count_1 < 3)
        setTimeout(func_1, 0);

    console.log('count_1 = '+count_1)
    count_1++
}

func_0();
func_1();

You will get this output:

count_0 = 0
count_1 = 0
count_0 = 1
count_1 = 1
count_0 = 2
count_1 = 2
count_0 = 3
count_1 = 3

Why is it possible? Because the setTimeout function needs some time to be executed. And this time is even enought for the execution of some part from your following code.
Solution for you
For this case you have to write your own array sort function (or you can also use the following function from me) because we can not interrupt the native sort function. And in this your own function you have to use this setTimeout function interrupting trick. And you can receive your message event notification.
In the following example I have the interrupting in the half length of my array, and you can change it if you want.
Example with custom sort function interrupting

var numbers = [4, 2, 1, 3, 5];

// this is my bubble sort function with interruption
/**
 * Sorting an array. You will get the same, but sorted array.
 * @param {array[]} arr – array to sort
 * @param {number} dir – if dir = -1 you will get an array like [5,4,3,2,1]
 *                 and if dir = 1 in opposite direction like [1,2,3,4,5]
 * @param {number} passCount – it is used only for setTimeout interrupting trick.
 */
function sortNumbersWithInterruption(arr, dir, passCount)
{
    var passes = passCount || arr.length,
        halfOfArrayLength = (arr.length / 2) | 0; // for ex. 2.5 | 0 = 2

    // Why we need while loop: some values are on
    // the end of array and we have to change their
    // positions until they move to the first place of array.
    while(passes--)
    {
        if(!passCount && passes == halfOfArrayLength)
        {
            // if you want you can also not write the following line for full break of sorting
            setTimeout(function(){sortNumbersWithInterruption(arr, dir, passes)}, 0);
            /*
                You can do here all what you want. Place 1
            */
            break
        }

        for(var i = 0; i < arr.length - 1; i++)
        {
            var a = arr[i],
                b = arr[i+1];

            if((a - b) * dir > 0)
            {
                arr[i] = b;
                arr[i+1] = a;
            }
        }

        console.log('array is: ' + arr.join());
    }

    if(passCount)
        console.log('END sring is: ' + arr.join());
}

sortNumbersWithInterruption(numbers, -1); //without passCount parameter
/*
    You can do here all what you want. Place 2
*/
console.log('The execution is here now!');

You will get this output:

array is: 4,2,3,5,1
array is: 4,3,5,2,1
The execution is here now!
array is: 4,5,3,2,1
array is: 5,4,3,2,1
END sring is: 5,4,3,2,1

A: You can do it with insertion sort (kind of).
Here is the idea:

*

*Start your worker with an internal empty array (empty array is sorted obviously)

*Your worker receives only elements not the entire array

*Your worker insert any received element right in correct position into the array

*Every n seconds, the worker raises a message with the current array if it has changed after the last event. (If you prefer, you can send the array on every insertion, but is more efficient to buffer somehow)
Eventually, you get the entire array, if any item is added, you will receive the updated array to.
NOTE: Because your array is always sorted, you can insert in correct position using binary search. This is very efficient.

A: I think the case comes down to careful management of postMessage calls and amount of data passed to be processed at a time. Was dealing with problem of this kind - think about not sending all new data into the function at once but rather creating your own queue and when small enough portion of the task has been acomplished by webworker thread send a message back to the main thread and decide to send the next portion, wait or quit.
In Your case, e.g. one time You get 9000 new items, next 100k - maybe create a queue/buffer that adds next 10k new elements each time webworker is done processing last data change.
const someWorker = new Worker('abc.js');

var processingLock = false;
var queue = [];

function newDataAction(arr = null) {

    if (arr != null) {
        queue = queue.concat(arr);
    }

    if (!processingLock) {
        processingLock = true;
        var data = [];
        for (let i = 0; i < 10000 && queue.length > 0; i++) {
            data.push(queue.pop());
        }

        worker.postMessage(data);
    }
}

someWorker.addEventListener('message', function(e) {
    if (e.data == 'finished-last-task') {
       processingLock = false;
       if (queue.length > 0) {
           newDataAction();
       }
    }
});

Worked through many sorting algorithms and I don't see how sending new data into an sorting algorithm with partially sorted array makes much difference in terms of compuation time from sorting them both sequentially and performing a merge.


text:
Q: Why won't my iPad app project "start" in landscape mode out of the box? This is a weird question inasmuch as I've definitely had projects that work fine, possibly because I've been doing something differently. But now I'm confounded.
I create a new View-based iPad app with Xcode (3.2.3 fwiw). This gets me a default view controller with a default view which gets unarchived and displayed at startup.
When I start the app while the simulator is in landscape mode, I expect that default view to size to be 1024 wide. But it's not-- If I add just one line to the default project:
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"width: %f", [[self view] bounds].size.width); // add this line
}

I can see that the width is 768, whether the app starts in portrait or landscape mode. Out of the box, the autoresize mask of that default view should definitely relayout to fit the container. Why isn't this number 1024 when I start in landscape mode? I know this works in other projects I have but I'm confounded by what the difference is. What am I missing?
Thanks!

A: viewDidLoad is called immediately after the view loads from the xib, before it's rotated to the initial device orientation. Try this:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    NSLog(@"rotated to width: %f", self.view.bounds.size.width);
}


text:
Q: lateinit property locationRequest has not been initialized I am following raywenderlich's tutorial  Introduction to Google Maps API for Android with Kotlin. All works as expected when the code is in an Activity, but when I put it into a Fragment, I get an error lateinit property locationRequest has not been initialized.
Here is my code:
XyzFragment.kt
package my.package.fragments

import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import my.package.R
import androidx.core.app.ActivityCompat
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.*
import com.google.android.gms.maps.*
import java.io.IOException

class XyzFragment : Fragment(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

    private lateinit var mMap: GoogleMap
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var lastLocation: Location
    private lateinit var locationCallback: LocationCallback
    private lateinit var locationRequest: LocationRequest
    private var locationUpdateState = false

    companion object {
        private const val LOCATION_PERMISSION_REQUEST_CODE = 1
        private const val REQUEST_CHECK_SETTINGS = 2
    }

    override fun onMarkerClick(p0: Marker?) = false

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        var rootView = inflater.inflate(R.layout.fragment_xyz, container, false)

        val mapFragment = childFragmentManager?.findFragmentById(R.id.fGoogleMap) as SupportMapFragment
        mapFragment.getMapAsync(this)

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this@XyzFragment.activity!!)

        return rootView
    }

    override fun onMapReady(googleMap: GoogleMap?) {
        mMap = googleMap!!
        mMap.getUiSettings().setZoomControlsEnabled(true)
        mMap.setOnMarkerClickListener(this)

        setUpMap()
    }

    private fun setUpMap() {
        if (ActivityCompat.checkSelfPermission(this@XyzFragment.context!!,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this@XyzFragment.activity!!,
                arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)
            return
        }

        mMap.isMyLocationEnabled = true

        fusedLocationClient.lastLocation.addOnSuccessListener(this@XyzFragment.activity!!) { location ->
            // Got last known location. In some rare situations this can be null.
            if (location != null) {
                lastLocation = location
                val currentLatLng = LatLng(location.latitude, location.longitude)
                placeMarkerOnMap(currentLatLng)
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 12f))
            }
        }

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(p0: LocationResult) {
                super.onLocationResult(p0)

                lastLocation = p0.lastLocation
                placeMarkerOnMap(LatLng(lastLocation.latitude, lastLocation.longitude))
            }
        }

        createLocationRequest()
    }

    private fun placeMarkerOnMap(location: LatLng) {
        val markerOptions = MarkerOptions().position(location)

        val titleStr = getAddress(location)
        markerOptions.title(titleStr)

        mMap.addMarker(markerOptions)
    }

    private fun getAddress(latLng: LatLng): String {

        val geocoder = Geocoder(this@XyzFragment.context)
        val addresses: List<Address>?
        val address: Address?
        var addressText = ""

        try {
            addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)

            if (null != addresses && !addresses.isEmpty()) {
                address = addresses[0]
                for (i in 0 until address.maxAddressLineIndex) {
                    addressText += if (i == 0) address.getAddressLine(i) else "\n" + address.getAddressLine(i)
                }
            }
        } catch (e: IOException) {
            Log.e("MapsActivity", e.localizedMessage)
        }

        return addressText
    }

    private fun createLocationRequest() {
        locationRequest = LocationRequest()
        locationRequest.interval = 10000
        locationRequest.fastestInterval = 5000
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest)

        val client = LocationServices.getSettingsClient(this@XyzFragment.activity!!)
        val task = client.checkLocationSettings(builder.build())

        task.addOnSuccessListener {
            locationUpdateState = true
            startLocationUpdates()
        }
        task.addOnFailureListener { e ->
            if (e is ResolvableApiException) {
                try {
                    e.startResolutionForResult(this@XyzFragment.activity,
                        REQUEST_CHECK_SETTINGS
                    )
                } catch (sendEx: IntentSender.SendIntentException) {
                }
            }
        }
    }

    private fun startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this@XyzFragment.context!!,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this@XyzFragment.activity!!,
                arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
                LOCATION_PERMISSION_REQUEST_CODE
            )
            return
        }
        fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)
    }
}

What am I doing wrong?

A: locationRequest is initialized in createLocationRequest(). This has to be done before the property is ever used elsewhere. In the tutorial, they call createLocationRequest() in onCreate(). In your Fragment, you should call it onCreateView() before you return the view.

A: Approach 1:
Please initialize locationRequest before using it.
Approach 2:

private lateinit var locationRequest: LocationRequest

could be changed to

private var locationRequest: LocationRequest? = null

and use it by locationRequest?.someMethod()
Thank you


text:
Q: how to download a file from given url to buffer with got library? I want to download a file from an url with got library, this is my current code:
    var data
    try
    {
        var stream = got.stream (url)
        stream.on ('data', d => data += d)
        stream.end ()
    }
    catch (error)
    {
        console.error (error)
    }

But i'm getting this error:
TypeError: The payload has been already provided

A: got.stream() makes a GET request by default, you need to set allGetBody to true to avoid the TypeError.
So do this instead:
var data
try {
  var stream = got.stream (url, { allowGetBody: true })
  stream.on ('data', d => data += d);
  stream.end()
} catch (error) {
  console.error (error)
}

See Got Documentation  on this
Here's a working example on Javascript Runkit


text:
Q: Hodrick Standard Errors in R? Does anyone know how to implement Hodrick Standard errors in R? I could not find any package for it in R. Is anyone aware of the same or any open source code that implements it? I want to use Hodrick Standard errors after the estimation of e-GARCH and DCC-GARCH models in R. I am not sure how to approach this?
The code to estimate Hodrick standard errors after a regression model I use is:
kernHAC(r, kernel = "Truncated", bw = 1,
  prewhite = FALSE, adjust = FALSE, sandwich = FALSE)

Where r is a regression object.
However, the sandwich package does not support GARCH estimator. How do I estimate Hodrick standard errors after a GARCH regression?


text:
Q: Indentation issue in RStudio Like many others, I like writing my codes on several lines and I appreciate the auto-indent feature offered by RStudio. The issue suddenly started when the word undefined showed up in the code editor whenever I pressed Enter as I expected an automatic indentation. It is important to mention that this does not affect the proper running of the code.
my_fun <- function(xxx){
undefined
}

NB: Actually, when I copied and pasted the code here, undefined was not copied to! I had to manually add it. Here is another example.
library(magrittr)
mtcars %>%
undefinedhead()

A: Basically this is just RStudio telling you that you have not preset your tab spaces, but it is not actually dropping commands into your code.
You have the option of setting tabs to however many spaces you feel is appropriate and it allows teams to work with consistent spacing.
If you go to the main menu and click on Tools > Global Options and on the second tab in the left column click onCode . There you can set the spaces to meet your personal needs (or teams profile) and the undefined message will disappear.
This photgraph shows where you can find the preferences.


text:
Q: Java Implementing math log function properly? so i have just this Math.log function in Java at this link http://www.tutorialspoint.com/java/lang/math_log.htm
On its example :
  Math.log(60984.1) = 11.018368453441132

I tried it on a calculator (i was actually just using windows scientific calculator) and typed in 60984.1 then log, which shows that it is equivalent to log(60984.1). But then the result was
  4.785216618906530669507

instead of the the 11.018368 of math.log function in java. What causes this inconsistency?
I am not really good at math an i am trying to implement an algorithm which uses a log sig function and a simple log. I don't even know how to do a simple log. The equation i am basing upon has no base. Just simple log.
What is the right equivalent of log in Java?
Thank you :)

A: Math.log uses log base e, which is the natural log. Windows calc maps Log to log base 10.

A: Probably you want base 10 logarithm
 Math.log10

A: Yes, there is an implied base in each of those methods.  The natural log (base e) is the result 11.018368453441132, but the common log (base 10) yields the result 4.785216618906530669507.
The Math class supports both bases:

*

*Math.log - base e

*Math.log10 - base 10.

Windows Calculator's button "ln" supports the natural log ("ln" is the mathematical function name for the natural log), and it supports the button "log" for the common log.