text:
Q: How would I clip a continuous action in an actor-critic agent? Let's say we have a bot that has some money and some shares. The input is a list of prices for the last 30 days. It doesn't use an RNN and the prices are entered all at the same time. The output is a continuous action where a positive number is to buy and a negative number is to sell the amount of the stock. How can I restrict the action space so that it is clipped between how many shares it has(the lower bound) and how much money it has(the upper bound)?
Should I have it clipped or just penalize an illegal action? Which option would create the best results?

A: You can penalise illegal actions, but in my experience it hasn't shown to have a good effect on the AI (one more thing to worry about). Just clip the output so that if it tries to use more money that it has available it spends all its money. If it tries to sell more of a stock than it has, it sells all of it's stock. The network will learn what happens when it tries to use more resources than it has quite quickly, so it wont cause any degrade in performance.

A: The AI cannot sell a share amount it doesn't have or buy a share which is worth more than the money it has, so you should not allow this kind of transaction at all. However, if your AI looks at the trends and prefers shares which are expected to be more valuable in the near future, then there is a good chance that the total amount of property will be higher the next day. Let's say share1 had a starting value of s1 and an ending value of e1 and share2 had a starting value of s2 and an ending value of e2, then in the case when
e1 / s1 > e2 / s2
it is better to give share1 a higher priority. If any si / ei is smaller than 1, then the AI should not invest into it.
Also, you should value stability, if a share's value has increased continously in the last few days, then it has an increasing trend. If a share's initial value is smaller than the ending value, but in the last few days its value decreased, then it might be a decreasing trend and the share should not be preferable. Such rules need to be implemented and when they are conflicting, the AI must be able to intelligently choose its priorities.


text:
Q: When does first win of the day bonus reset? At what time does the daily bonus reset?

I am personally mostly interested in EU region's reset.

A: Information from the Beta and around the net would seem to indicate that the First Win of the day does not have a daily reset time (a la World of Warcraft Daily Quests), but rather a rolling timer, 22 hours after your previous win (a la World of Warcraft Transmutation timers).
Unfortunately, there is not yet a way to track how close you are to the counter expiring and becoming eligible again

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jest not finding root after upgrading to Angular 13 I upgraded my project to Angular 13 and jest needed some changes too.
Now any reference to 'src' can not be resolved.
For example:
Cannot find module 'src/app/app.component/app.component.test' from 'src/dashboard/reports/modules/tables/matrix-table/matrix-table.test.ts'

This is my jest.config.js
const { compilerOptions } = require('./tsconfig.test.json');
const { pathsToModuleNameMapper } = require('ts-jest/utils');

module.exports = {
  preset: "jest-preset-angular",
  testMatch: ["**/*.test.ts"],
  coverageReporters: ["json", "lcov", "text", "clover", "cobertura"],
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
  globals: {
    "ts-jest": {
      tsconfig: "tsconfig.test.json"
    }
  }
};

What should I change in my jest config in order for it to resolve the root to src?

A: The error seems to hint at Typescript and Jest builder not transpiling the tests to ESM, a recent change with the Angular v13 upgrade. From the ts-jest ESM support doc:
// jest.config.js
module.exports = {
  // [...]
  extensionsToTreatAsEsm: ['.ts'],
  globals: {
    'ts-jest': {
      useESM: true,
    },
  },
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
}

A: Have you tried adding
"moduleDirectories": [
    "node_modules",
    "src"
]

to your jest.config.js
This looks like a similar issue


text:
Q: Facebook , OSX and FB Requests We are in the process of converting one of our games from iOS over to the OSX app market. A big part of our game is the social features which we use the iOS sdk for our game.  We are starting to run into a problem where we cannot find any details on whether fb requests can be done via OSX. We have the auth process down and access to the graph API.
So just to be clear, we are looking to:
Pull a list of friends (which is easy via graph api)
Select a friend
Then send that friend an app request (which we cant seem to find any details on how to do this on osx)
Any thoughts?

A: See the "Direct URL Example" in https://developers.facebook.com/docs/reference/dialogs/requests/
It also appears to be covered in the "Requests" section of the Facebook iOS tutorial
THis has also been asked before: iPhone - How to send apprequests using facebook iOS sdk


text:
Q: How to split doctrine entity into more domain entities in different bounded contexts? I am trying my first steps in DDD (Domain-driven design) field. I love the wise rule, that you should split your entities into many smaller, context-specific entities (for example User entity tends to overgrow almost in every non-ddd or poorly designed application). But what are common options on how to do it (effectively) in php using Doctrine?
Let's say I have two Bounded contexts: Store and Invoicing
Each of them has two domain entities:
for Store BC it's FirstTimeCustomer and RecurrentCustomer
for Invoicing BC it's VatCustomer and NonVatCustomer
Now, in my infrastructure layer I want them all be saved in same (at least base) table to be able to reference them by general UserId (Uuid). The problem for me is, how to do that, so I can use advantage of doctrine automapping in my repository implementations.
I read about Single Table Inheritance or Class Table Inheritance that may be solution, but:
I need to be able to work with User of same Uuid as it was different type in each context.
I need to be able to return some AbstractStoreCustomer aka FirstTimeCustomer or RecurrentCustomer on $storeCustomerRepository->find(1); in Store BC.
And to return some AbstractInvoicingCustomer aka VatCustomer or NonVatCustomer on $invoicingCustomerRepository->find(1); in Invoicing BC.
But it seems that I am forced here to chose what BC I want specific identity of entity bound to. So it does not make sense in context of DDD to me at all.
I also read about Mapped Superclasses, that looks like option too, but:

This means that One-To-Many associations are not possible on a mapped
  superclass at all.

And I need Customer to have relation to orders, that should be available in both entities (an also possibly not want it to be available is some new type of User entity in new BC).
I came to conclusion that I should be suspicious that I am missing something, is that? How should I achieve breaking god entity into smaller context specific ones?

A: I will start with some general rules.
When thinking DDD you must reject any thoughts about persistence (tables and primary keys and the like). You must design your aggregate roots and entities as if you will store them in a file. When you design the models, if a thought about tables or ORM comes to your mind you fail to do DDD; take a step back and restart.
As I see, you started OK by splitting your models by the bounded contexts. If you do not split them by BCs you end up with gigantic models that try to encompass all the behavior and then the persistence will affect the performance, because, in DDD, the aggregates are persisted in one single transaction. One other thing, try to avoid inheritance and use composition.
That being said, lets talk about your business.
In the Authentication BC, there are Users that can authenticate, with some credentials. In the Store BC there are Customers that buy things. In the Invoice BC, there are also Customers but a different model (a different class if you want). In the Shipping BC there are also Customers but again, a different model. These Customer models share some properties along the BCs, like name and id. So, you use the id to identify a person from the real life but use different models to encapsulate their behavior depending on the context.
I think that you should not have a AbstractStoreCustomer, you should have only Customer and try to isolate what differentiate them in abstract class/interface, like BuyingHistoryProfile with 2 implementation FirstTimeCustomer and RecurrentCustomer. This class should contain only behavior regarding buying profile and it should be referenced by everyCustomer in the Store BC. Similarily, try to extract a class in the Invoicing BC for the price calculation.
Now that we've created the models, we can think about persistence. For every bounded context create a Customer table, that contains the shared properties (name and  id) and the specific properties (buyingHistoryProfile for the Store BC, priceCalculationStrategy for the Invoicing BC etc).
If you wonder that there is a degree of data duplication then you are right, but it is normal, it is necessary to decouple the models. This duplicate data is synchronized when the User in the Authentication BC change its name: you update all the other models right then. From this point of view, Invoice and Store BC are down-streams, they use data from the Authentication BC; it depends on your business when the update is initiated.
Being a fan of Event-driven architectures, I recommend you to take a look at CQRS (and even Event Sourcing). I think that these architectures fit well in this application. CQRS could make your models 10 times cleaner, I tell you from my experience. With Event Sourcing it is very probable that you won't even have to use an ORM. You could use an ORM on the read side, if you really like them or you can't leave them. I personally don't like (and don't use) ORMs.


text:
Q: How to use an iterator within an ES6 class method I'm experimenting with iterators within ES6 classes and am running into a reference error: ReferenceError: vertex is not defined when creating an each method for my class. I'm able to add my vertexes to the graph and the graph instance prints with the correct data. Is the use of this iterator correct?
class Vertex {
  constructor(key) {
    this.id = key
    this.connectedTo = {}
  }
}

class Graph {
  constructor() {
    this.vertexList = {}
    this.numVerticies = 0
  }

[Symbol.iterator]() {
     // Reflect.ownKeys() === Object.keys()
  const vertexListKeys = Reflect.ownKeys(this.vertexList)
  let index = 0
  return {
    next: () => {
         // Reflect.get(myObj, key) === Object[key]
      let value = Reflect.get(this.vertexList, vertexListKeys[index])
      index++
      return {
        done: index > vertexListKeys.length ? true : false,
        value: value
        }
      }
    }
  }

// Iterate through vertexList values
 each(callback) {
  for (vertex of this) {
    callback(vertex)
    }
  }

 addVertex(key) {
   const newVertex = new Vertex(key)
     this.vertexList[key] = newVertex
     this.numVerticies++
   return newVertex
  }

}

const graph = new Graph()

for (var i = 0; i < 6; i++) {
  g.addVertex(i)
}

graph.each((vert) => console.log(vert))
// ReferenceError: vertex is not defined
// for (vertex of this) {
//               ^

I have also tried changing my each method to a generator, however nothing prints to the console when I do so
*each(callback) {
  for(vertex in this) {
    yield callback(vertex) // omitting yield doesn't work either
  }
}

A: The error is just what it says
for (vertex of this) {

uses a variable vertex that isn't declared anywhere. It should be
for (var vertex of this) {

or let or const.

A:     class Vertex {
  constructor(key) {
    this.id = key
    this.connectedTo = {}
  }
}

class Graph {
  constructor() {
    this.vertexList = {}
    this.numVerticies = 0
  }

[Symbol.iterator]() {
     // Reflect.ownKeys() === Object.keys()
  const vertexListKeys = Reflect.ownKeys(this.vertexList)
  let index = 0
  return {
    next: () => {
         // Reflect.get(myObj, key) === Object[key]
      let value = Reflect.get(this.vertexList, vertexListKeys[index])
      index++
      return {
        done: index > vertexListKeys.length ? true : false,
        value: value
        }
      }
    }
  }

// Iterate through vertexList values
 each(callback) {
  for (var vertex of this) {
    callback(vertex)
    }
  }

 addVertex(key) {
   const newVertex = new Vertex(key)
     this.vertexList[key] = newVertex
     this.numVerticies++
   return newVertex
  }

}

const g = new Graph()

for (var i = 0; i < 6; i++) {
  g.addVertex(i)
}

g.each((vert) => console.log(vert))

In the each function it should be var vertex because  vertex is not declared yet .


text:
Q: Bring the UWP app to the front of current window How can i use
await Windows.System.Launcher.LaunchUriAsync(new Uri("protocol://"));

to navigate to specific view of uwp application.
Is there any way to bring the app in front of the screen, if app was minimized or hidden behind other apps?
Thanks in advance

A:
How can i use await Windows.System.Launcher.LaunchUriAsync(new Uri("protocol://")); to navigate to specific view of uwp application

For this, firstly you need to add the Protocol declaration in your Package.appxmanifest file . (Go to declarations tab and add Protocol from the available protocols). ( MSDN Doc )
Here i am using "app-protocol" as the protocol name.

Once this is done, you need to override the OnActivated() method in your App.xaml.cs. This method will be called when the app is launched using the protocol.
The arguments that we pass when calling the protocol can be retrieved here and based on that you can show your page or maybe pass that parameter to your page and let it handle the navigation .
For instance, if our Uri is app-protocol:login?param1=true, when you receive the ProtocolActivatedEventArgs eventArgs in the onActivated() method you will have access to the whole Uri.
You can use eventArgs.Uri to access all the Uri properties.
In any case your code should look something like this :
C#
protected override void OnActivated(IActivatedEventArgs args)
{
     if (args.Kind == ActivationKind.Protocol)
     {
         ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;

         // Get the root frame
         Frame rootFrame = Window.Current.Content as Frame;

         // Do not repeat app initialization when the Window already has content,
         // just ensure that the window is active
         if (rootFrame == null)
         {
             // Create a Frame to act as the navigation context and navigate to the first page
             rootFrame = new Frame();

             rootFrame.NavigationFailed += OnNavigationFailed;

             if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
             {
                 //TODO: Load state from previously suspended application
             }
             // Place the frame in the current Window
             Window.Current.Content = rootFrame;
         }

         //URI : app-protocol:login?param1=true
         //Logic for showing different pages/views based on parameters passed
         if (eventArgs.Uri.PathAndQuery != string.Empty)//PathAndQuery:login?param1=true
         {
             var absolutePath = eventArgs.Uri.AbsolutePath;//AbsolutePath:login
             if (absolutePath.Equals("login"))
             {
                 rootFrame.Navigate(typeof(LoginPage));
             }
             else
             {
                 rootFrame.Navigate(typeof(MainPage));
             }
         }
         else
         {
             rootFrame.Navigate(typeof(MainPage));
         }
     }
     // Ensure the current window is active
     Window.Current.Activate();
 }

Is there any way to bring the app in front of the screen, if app was minimized or hidden behind other apps?

We are calling Window.Current.Activate(); to ensure this.

A: To bring any UWP window to the front use this snippet (works if window with given viewId was already created and is either minimized or behind other windows:
private async Task TryActivateViewAsync(viewId)
{
    if (Window.Current.Dispatcher != null)
    {
        await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
        {
            if (await ApplicationViewSwitcher.TryShowAsStandaloneAsync(viewId))
            {
                await ApplicationViewSwitcher.SwitchAsync(viewId);
            }
        });
    }
}

Just as a reminder, viewId is an Identifier of a window which you can get when you create that window using:
var coreView = CoreApplication.CreateNewView(); // creates new view
await coreView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    _someViewId = ApplicationView.GetForCurrentView().Id; // gets that view's id
}


text:
Q: How to receive SMTP mails like a python wsgi server on port 25 how can i implement a server that receives and parse mails, like using the library
from smtpd import SMTPServer
but running forever like i do with wsgi http://webpython.codepoint.net/wsgi_environment_dictionary
(i know it cant be done with wsgi, but is there a way to to this?)
Thanks :)

A: See the link below for info on how to setup a mail server that will pipe incoming emails to a script:  http://harrybailey.com/2009/02/send-or-pipe-an-email-to-a-php-script/.  This article is specific to PHP scripts, but the same thing can be done with python.


text:
Q: inserting new data into database, then displaying all the data doesnt show the new entry I created a database using SQLite in the MainActivity and added example data into it. The MainActivity is used to retrieve and show the data using a list and recyclerview
For inserting the example data, my code looks like this
// simplified version
db = new MyDBHandler(this);
rList = new ArrayList<>();
rList = db.GetRecipes();
if (rList.size() == 0) { CreateExampleRecipes(db); }

I went to a different activity, Activity2, to create a new data to be inserted into the database.
For the code, it looks like this
// simplified version
db = new MyDBHandler(this);
db.InsertData(String.valueOf(etRecipeName), Integer.valueOf(String.valueOf(etDuration)), ingred, desc, steps);
finish();

The issue is, after using finish(); in Activity2, the new data isnt displayed in the MainActivity.
Edit 1
Is there a way to share databases between activities? Or is sharing databases the only solution?


text:
Q: extreme bounds package in R I am new in R and I need to learn to use the Package 'ExtremeBounds'. I am using the tutorial mtcars dataset to learn and as I am doing different exercises I continuously get this error
Error in reg.summary$coefficients[variable.label, 1] :
  subscript out of bounds

If i do
eba(data = mtcars[1:32,], y = "mpg", free = "wt", doubtful = c("cyl","disp","hp","drat","qsec","vs","am","gear","carb"), focus = c("hp","gear"), k = 0:3, mu = 0, leve = 0.85)

I don't get the error, but when I try to do the following, i get the error
eba(data = mtcars[1:8,], y = "mpg", free = "wt", doubtful = c("cyl","disp","hp","drat","qsec","vs","am","gear","carb"), focus = c("hp","gear"), k = 0:3, mu = 0, leve = 0.85)

Can someone tell me what I am doing wrong? I would really appreciate it as I need to use this package for a school project.
Thank you

A: This is a collinearity problem. When you use only the first 8 data points cyl and vs exactly determine the value of gears, which causes an internal error in the function code. There is no way of getting around this issue. You either have to use more data or you cannot have gears as a focus variable. Alternatively, you could remove either cyl or vs from the doubtful variables and the function will work then as well.


text:
Q: JS SweetAlert2 not working in Safari Browser I have implemented sweetalert2, in chrome, firefox, and in microsoft edge they work great! However in safari the alert never even shows and also jams up the site and makes it unusable. Is there any known issues with this or workarounds that I should be doing?
Its essential to the functionality of the site since they contain buttons and actions. So I cant just bypass it if the browser is safari.
EDIT: Turns out I am getting ReferenceError: Can't find variable: Promise in sweetalert.js on line 827.
Any ideas? Thank you!
My current code implementation:
welcome.blade.php
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.css"/>
.
..
...
function loadalert(){
        swal({
            title: 'Welcome to my website!',
            html: 'test message!',
            type: 'info',
            showCancelButton: false,
            confirmButtonText: 'Proceed'
        }).then(function () {

        });
    }
.
..
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.js"></script>
<script src="{{asset('/plugins/sweetalert/sweetalert2.js')}}" type="text/javascript"></script>

A: Ok after some digging and testing I found the answer. If sweetalert2 does not work for safari they have a include you can call for more browser support which is:
<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/core.js"></script>

Please read for more information

https://github.com/sweetalert2/sweetalert2#usage

A: Interestingly it was happening to me because I was using minified versions
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.10/dist/sweetalert2.all.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.10/dist/sweetalert2.min.css">

After I removed '.min' part, it started to work on mobile phones
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.10/dist/sweetalert2.all.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.10/dist/sweetalert2.css">


text:
Q: Need to use SimpleXML and JaxB together In my scenario, I need to use SimpleXML and JaxB annotations together on an object so that I can use this object to make different kind of REST webservices which we do not want to make any updates.
I have a class below:
@Root(strict=false)
@XmlRootElement
@XmlAcessorType(XmlAccessType.NONE)
public class Patient{

    @Element(name ="id", required = false)
    @XmlElement(name="id")
    private int patno;

    @Element(required = false)
    private String lastName;

    @Element(required = false)
    private String firstName;

// not displaying the getters/setters to save space - but no annotations on those methods.

}

I use an object of this class to serialize and send a REST POST request.
The REST service's interface method is annotated as below: (this is outside of my area)
@POST
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public StreamingOutput generatePatientData(final Patient patient);

Someone else uses my same patient object to do the simple xmlSerialization for another REST service.
But an exception as below occurs:
org.simpleframework.xml.core.PersistenceException: Duplicate annotation of name 'id' on method 'patno'


text:
Q: How to change the ListView element text color based on text Displaying textview as list element, for this textview getting values by returning values from a method getValues()so setting text fot textview like this t1.setText(getValues());these values are like (123 kms,12 kms,13 kms,15 kms,198 kms,135 kms,456 kms,12 kms,135 kms,147 kms,....)i want to compare all elements with first one and if it is grater than first element that text color is RED ,if it it less than first element it is BLUE ,i tried something like this and got two lists.
What i tried
 List<Integer> myList = Arrays.asList(12,34,45,23,45,7,68,4,345,56,67,4,999,454,6,76,0);
        Iterator<Integer> iter = myList.iterator();
        List<Integer> lessList = new ArrayList<Integer>(), biggerList = new ArrayList<Integer>();
        Integer firstItem = iter.next();
        while (iter.hasNext()) {
            Integer currElement = iter.next();
            if (firstItem.compareTo(currElement) > -1) {
                lessList.add(currElement);
            } else {
                biggerList.add(currElement);
            }
        }

here i am not getting how to set text of textview and two colors for same textview. help me.
tried code something like this
 if(odo_chk_num>400)
                       {

                              if(t2!=null)
                              {
                                  t2.setTextColor(Color.RED);
                                t2.setText(getValues());
                              }

                       }

 else
                       {
                           t2.setTextColor(Color.BLACK);
                       }

but here first if condition executes then all texts color changing to RED,but what i need text should be RED based on condition only.
ADAPTER CLASS
public class FileArrayAdapter extends ArrayAdapter<Option>{

    private Context c;
    private int id;
    private List<Option>items;

    public FileArrayAdapter(Context context, int textViewResourceId,
            List<Option> objects) {
        super(context, textViewResourceId, objects);
        c = context;
        id = textViewResourceId;
        items = objects;
    }
    public Option getItem(int i)
     {
         return items.get(i);
     }
     @Override
       public View getView(int position, View convertView, ViewGroup parent) {
               View v = convertView;
               if (v == null) {
                   LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                   v = vi.inflate(id, null);
               }
               final Option o = items.get(position);
               if (o != null) {
                       TextView t1 = (TextView) v.findViewById(R.id.TextView01);
                       TextView t2 = (TextView) v.findViewById(R.id.TextView02);

                       if(o.getDDS().equals("Odometer reading:"))
                       {

                           int odo_num, odo_chk_num = 0;
                           System.out.println("");
                           String odo_str=o.getSpans();

                           for(int i = 0 ; i<o.getSpans().length();i++)
                           {
                               char xyz=odo_str.charAt(i);
                               System.out.println("");
                               if(xyz >= '0' && xyz <= '9')
                               {
                               odo_num=(int)xyz;

                               odo_chk_num=  odo_chk_num*10 + odo_num;

                               }

                           }

                         //  System.out.println("after digit" + odo_chk_num);

                           if(odo_chk_num>40000)
                           {
                               if(t1!=null)
                                    t1.setText(o.getDDS());
                                  if(t2!=null)
                                  {
                                     // t2.setTextColor(Color.RED);
                                      SpannableStringBuilder sb = new SpannableStringBuilder(o.getSpans());
                                      ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158));
                                      sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                                    t2.setText(sb);
                                  }

                           }

                       }

                       else
                       {
                           t2.setTextColor(Color.BLACK);

                       if(t1!=null)
                        t1.setText(o.getDDS());
                       if(t2!=null)
                        t2.setText(o.getSpans());
                       }

               }
               return v;
       }

}

A: Make one wrapper class take all varible in that class and one additional varible which is color code which is int type and calculate this condition in one method and fill all data and color code in wrapper after that you fill your list with this wrapper and your color code is also constant or not changing while you scroll you view.


text:
Q: Google Play Games Services Signin Problems I've been banging my head on my desk the past few days trying to figure out how to setup the sign-in for Google Play Games Services.
I am able to start an activity for an interactive signin, but the window just hangs and loads forever with no error:

Here is the code I have.  It checks to see if the user has signed in before, if they have, it attempts to login silently.  If not, it brings up interactive signin:
final GoogleSignInOptions signInOption =
    new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
    // Add the APPFOLDER scope for Snapshot support.
    .requestScopes(Games.SCOPE_GAMES_SNAPSHOTS)
    .requestIdToken(activity.getString(R.string.debug_client_id))
    .requestEmail()
    .build();

signInClient = GoogleSignIn.getClient(this, signInOption);

GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (account != null) {
    // The user has signed in before

    signInClient.silentSignIn().addOnCompleteListener(new OnCompleteListener < GoogleSignInAccount > () {
        @Override
        public void onComplete(@NonNull Task < GoogleSignInAccount > task) {
            if (task.isSuccessful()) {
                // Silent signin successful
                onConnected(task.getResult());
            } else {
                // Player will need to sign-in explicitly using via UI
                // Interactive sign-in
                activity.startActivityForResult(signInClient.getSignInIntent(), AndroidLauncher.RC_SIGN_IN);
            }
        }
    });

} else {
    //The user has never signed in
    // Interactive sign-in
    this.activity.startActivityForResult(signInClient.getSignInIntent(), AndroidLauncher.RC_SIGN_IN);
}

I also have the onActivityResult() handler:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            signedIn = true;
            // The signed in account is stored in the result.
            GoogleSignInAccount signedInAccount = result.getSignInAccount();
        } else {
            signedIn = false;
            String message = result.getStatus().getStatusMessage();
            if (message == null || message.isEmpty()) {
                message = "Sign in error!";
            }
            new AlertDialog.Builder(this).setMessage(message)
                    .setNeutralButton(android.R.string.ok, null).show();
        }
    }
}

What I've Tried/Done

*

*I added the required metadata tags in the AndroidManifest.xml file (with correct values)

*I've added the Google Play Games account as a tester on the Google Play Console for the app, for Google Play Services, and on the OAuth consent screen for the API on Google Cloud Platform.

*I've checked that the SHA-1 hash of the signature on the app matches the SHA-1 hash of the OAuth credential in use on Google Play Games, and that the client ID is correct and is of the selected OAuth credential.

*I have enabled all of the non-sensitive data scopes (which is all I need) on the Google Cloud Platform OAuth consent screen
More Info
If I try to call signInSilently(...) before the interactive signin, I get API exception code 4 (SIGN_IN_REQUIRED).  When I execute the interactive signin, it just hangs like above.  I actually am able to get the signin to work, but only if I use signin options like so:
final GoogleSignInOptions signInOption = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).build();

(with no snapshots permissions and no passed client ID.  But I need to be able to access snapshots)
The only possibly relevant exception I see in Logcat when running the interactive signin is:
E/ExecutionCriteria: Package unavailable for task: com.google.android.apps.tachyon/com.firebase.jobdispatcher.GooglePlayReceiver{u=0 tag="duo-analytics-summary-report" trigger=window{start=82080s,end=86401s,earliest=-97027894s,latest=-97023574s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=-97109975s last_run=N/A exec_window_multiplier=1.0000 jid=N/A status=PENDING retries=0 client_lib=FIREBASE_JOB_DISPATCHER-1} [CONTEXT service_id=218 ]

...but it seems like it might be a benign error.
I've been stuck on this for a while; any suggestions/help would be appreciated.


text:
Q: TypeError only occurring in while loop I am getting a TypeError in this code
import requests
import json

orders_collected = 1
all_orders_collected = False

all_orders = requests.get(
    'API location').json()

while all_orders_collected == False:
    if all_orders[orders_collected - 1]['status'] == "processing":
        orders_collected += 1
        all_orders.append(requests.get('API location next page').json())
    else:
        all_orders_collected = True

for order in all_orders:
    print(order)

output:
    if all_orders[orders_collected - 1]['status'] == "processing":
    TypeError: list indices must be integers or slices, not str

However this line will only give this error when its within the while loop. it will work perfectly fine when outside the while loop and I am stumped as to why the while loop will be changing that condition. the output of the API is dictionary inside a list.
it would be much appreciated if someone could give an explanation as to why that's happening.
An example of the data is:
[{'id': 5339, 'parent_id': 0, 'status': 'processing', 'currency': 'ZAR', 'version': '5.0.0', 'prices_include_tax': False, 'date_created': '2021-03-04T18:06:28', 'date_modified': '2021-03-04T16:09:20', 'discount_total': '0.00', 'discount_tax': '0.00', 'shipping_total': '3.00', 'shipping_tax': '0.00', 'cart_tax': '0.00', 'total': '228.00', 'total_tax': '0.00', 'customer_id': 1, 'order_key': 'wc_order_g6StHaZMVIuoV', 'billing': {'first_name': 'redacted', 'last_name': 'redacted', 'company': '', 'address_1': 'redacted', 'address_2': '', 'city': 'redacted', 'state': 'redacted', 'postcode': '', 'country': 'redacted', 'email': 'redacted', 'phone': 'redacted'}, 'shipping': {'first_name': 'redacted', 'last_name': 'redacted', 'company': '', 'address_1': 'redacted', 'address_2': '', 'city': redacted', 'state': 'redacted', 'postcode': '', 'country': 'redacted'}, 'payment_method': 'cod', 'payment_method_title': 'Pay With EFT', 'transaction_id': '', 'customer_ip_address': 'redacted', 'customer_user_agent': 'redacted', 'created_via': 'checkout', 'customer_note': '', 'date_completed': '2021-02-20T06:28:43', 'date_paid': '2021-02-20T06:28:43', 'cart_hash': 'redacted', 'number': '5339', 'meta_data': [{'id': 44882, 'key': 'is_vat_exempt', 'value': 'no'}, {'id': 44887, 'key': '_new_order_email_sent', 'value': 'true'}], 'line_items': [{'id': 3159, 'name': 'Salads', 'product_id': 4278, 'variation_id': 4280, 'quantity': 1, 'tax_class': '', 'subtotal': '45.00', 'subtotal_tax': '0.00', 'total': '45.00', 'total_tax': '0.00', 'taxes': [], 'meta_data': [{'id': 45521, 'key': 'bases', 'value': 'Quinoa', 'display_key': 'Bases', 'display_value': 'Quinoa'}, {'id': 45522, 'key': 'proteins', 'value': 'Steak Strips', 'display_key': 'Proteins', 'display_value': 'Steak Strips'}, {'id': 45523, 'key': 'first-component', 'value': 'Mixed Peppers', 'display_key': 'First Component', 'display_value': 'Mixed Peppers'}, {'id': 45524, 'key': 'second-component', 'value': 'Organic Sprouts', 'display_key': 'Second Component', 'display_value': 'Organic Sprouts'}, {'id': 45525, 'key': 'third-component', 'value': 'Carrots', 'display_key': 'Third Component', 'display_value': 'Carrots'}, {'id': 45526, 'key': 'fourth-component', 'value': 'Pumpkin Seeds', 'display_key': 'Fourth Component', 'display_value': 'Pumpkin Seeds'}, {'id': 45527, 'key': 'fifth-component', 'value': 'Feta', 'display_key': 'Fifth Component', 'display_value': 'Feta'}, {'id': 45528, 'key': 'sixth-component', 'value': 'Roast Butternut', 'display_key': 'Sixth Component', 'display_value': 'Roast Butternut'}, {'id': 45529, 'key': 'size', 'value': 'Medium', 'display_key': 'Size', 'display_value': 'Medium'}, {'id': 45607, 'key': '_reduced_stock', 'value': '1', 'display_key': '_reduced_stock', 'display_value': '1'}], 'sku': '', 'price': 45, 'parent_name': 'Salads - SOLD OUT'}, {'id': 3160, 'name': 'Salads', 'product_id': 4278, 'variation_id': 4280, 'quantity': 1, 'tax_class': '', 'subtotal': '45.00', 'subtotal_tax': '0.00', 'total': '45.00', 'total_tax': '0.00', 'taxes': [], 'meta_data': [{'id': 45539, 'key': 'bases', 'value': 'Baby Spinach', 'display_key': 'Bases', 'display_value': 'Baby Spinach'}, {'id': 45540, 'key': 'proteins', 'value': 'Grilled Chicken', 'display_key': 'Proteins', 'display_value': 'Grilled Chicken'}, {'id': 45541, 'key': 'first-component', 'value': 'Feta', 'display_key': 'First Component', 'display_value': 'Feta'}, {'id': 45542, 'key': 'second-component', 'value': 'Carrots', 'display_key': 'Second Component', 'display_value': 'Carrots'}, {'id': 45543, 'key': 'third-component', 'value': 'Pumpkin Seeds', 'display_key': 'Third Component', 'display_value': 'Pumpkin Seeds'}, {'id': 45544, 'key': 'fourth-component', 'value': 'Chickpea and Red beans', 'display_key': 'Fourth Component', 'display_value': 'Chickpea and Red beans'}, {'id': 45545, 'key': 'fifth-component', 'value': 'Roast Butternut', 'display_key': 'Fifth Component', 'display_value': 'Roast Butternut'}, {'id': 45546, 'key': 'sixth-component', 'value': 'Organic Sprouts', 'display_key': 'Sixth Component', 'display_value': 'Organic Sprouts'}, {'id': 45547, 'key': 'size', 'value': 'Medium', 'display_key': 'Size', 'display_value': 'Medium'}, {'id': 45608, 'key': '_reduced_stock', 'value': '1', 'display_key': '_reduced_stock', 'display_value': '1'}], 'sku': '', 'price': 45, 'parent_name': 'Salads - SOLD OUT'}, {'id': 3161, 'name': 'Salads', 'product_id': 4278, 'variation_id': 4280, 'quantity': 1, 'tax_class': '', 'subtotal': '45.00', 'subtotal_tax': '0.00', 'total': '45.00', 'total_tax': '0.00', 'taxes': [], 'meta_data': [{'id': 45557, 'key': 'bases', 'value': 'Quinoa', 'display_key': 'Bases', 'display_value': 'Quinoa'}, {'id': 45558, 'key': 'proteins', 'value': 'Chickpea and red beans', 'display_key': 'Proteins', 'display_value': 'Chickpea and red beans'}, {'id': 45559, 'key': 'first-component', 'value': 'Sugar Snap Peas', 'display_key': 'First Component', 'display_value': 'Sugar Snap Peas'}, {'id': 45560, 'key': 'second-component', 'value': 'Red Onion', 'display_key': 'Second Component', 'display_value': 'Red Onion'}, {'id': 45561, 'key': 'third-component', 'value': 'Carrots', 'display_key': 'Third Component', 'display_value': 'Carrots'}, {'id': 45562, 'key': 'fourth-component', 'value': 'Pumpkin Seeds', 'display_key': 'Fourth Component', 'display_value': 'Pumpkin Seeds'}, {'id': 45563, 'key': 'fifth-component', 'value': 'Roast Butternut', 'display_key': 'Fifth Component', 'display_value': 'Roast Butternut'}, {'id': 45564, 'key': 'sixth-component', 'value': 'Feta', 'display_key': 'Sixth Component', 'display_value': 'Feta'}, {'id': 45565, 'key': 'size', 'value': 'Medium', 'display_key': 'Size', 'display_value': 'Medium'}, {'id': 45609, 'key': '_reduced_stock', 'value': '1', 'display_key': '_reduced_stock', 'display_value': '1'}], 'sku': '', 'price': 45, 'parent_name': 'Salads - SOLD OUT'}, {'id': 3162, 'name': 'Salads', 'product_id': 4278, 'variation_id': 4280, 'quantity': 1, 'tax_class': '', 'subtotal': '45.00', 'subtotal_tax': '0.00', 'total': '45.00', 'total_tax': '0.00', 'taxes': [], 'meta_data': [{'id': 45575, 'key': 'bases', 'value': 'Baby Spinach', 'display_key': 'Bases', 'display_value': 'Baby Spinach'}, {'id': 45576, 'key': 'proteins', 'value': 'Steak Strips', 'display_key': 'Proteins', 'display_value': 'Steak Strips'}, {'id': 45577, 'key': 'first-component', 'value': 'Roast Butternut', 'display_key': 'First Component', 'display_value': 'Roast Butternut'}, {'id': 45578, 'key': 'second-component', 'value': 'Feta', 'display_key': 'Second Component', 'display_value': 'Feta'}, {'id': 45579, 'key': 'third-component', 'value': 'Carrots', 'display_key': 'Third Component', 'display_value': 'Carrots'}, {'id': 45580, 'key': 'fourth-component', 'value': 'Pumpkin Seeds', 'display_key': 'Fourth Component', 'display_value': 'Pumpkin Seeds'}, {'id': 45581, 'key': 'fifth-component', 'value': 'Chickpea and Red beans', 'display_key': 'Fifth Component', 'display_value': 'Chickpea and Red beans'}, {'id': 45582, 'key': 'sixth-component', 'value': 'Organic Sprouts', 'display_key': 'Sixth Component', 'display_value': 'Organic Sprouts'}, {'id': 45583, 'key': 'size', 'value': 'Medium', 'display_key': 'Size', 'display_value': 'Medium'}, {'id': 45610, 'key': '_reduced_stock', 'value': '1', 'display_key': '_reduced_stock', 'display_value': '1'}], 'sku': '', 'price': 45, 'parent_name': 'Salads - SOLD OUT'}, {'id': 3163, 'name': 'Salads', 'product_id': 4278, 'variation_id': 4280, 'quantity': 1, 'tax_class': '', 'subtotal': '45.00', 'subtotal_tax': '0.00', 'total': '45.00', 'total_tax': '0.00', 'taxes': [], 'meta_data': [{'id': 45593, 'key': 'bases', 'value': 'Wholewheat protein pasta', 'display_key': 'Bases', 'display_value': 'Wholewheat protein pasta'}, {'id': 45594, 'key': 'proteins', 'value': 'Bacon', 'display_key': 'Proteins', 'display_value': 'Bacon'}, {'id': 45595, 'key': 'first-component', 'value': 'Mini Broccoli', 'display_key': 'First Component', 'display_value': 'Mini Broccoli'}, {'id': 45596, 'key': 'second-component', 'value': 'Baby Cob', 'display_key': 'Second Component', 'display_value': 'Baby Cob'}, {'id': 45597, 'key': 'third-component', 'value': 'Carrots', 'display_key': 'Third Component', 'display_value': 'Carrots'}, {'id': 45598, 'key': 'fourth-component', 'value': 'Pumpkin Seeds', 'display_key': 'Fourth Component', 'display_value': 'Pumpkin Seeds'}, {'id': 45599, 'key': 'fifth-component', 'value': 'Feta', 'display_key': 'Fifth Component', 'display_value': 'Feta'}, {'id': 45600, 'key': 'sixth-component', 'value': 'Roast Butternut', 'display_key': 'Sixth Component', 'display_value': 'Roast Butternut'}, {'id': 45601, 'key': 'size', 'value': 'Medium', 'display_key': 'Size', 'display_value': 'Medium'}, {'id': 45611, 'key': '_reduced_stock', 'value': '1', 'display_key': '_reduced_stock', 'display_value': '1'}], 'sku': '', 'price': 45, 'parent_name': 'Salads - SOLD OUT'}], 'tax_lines': [], 'shipping_lines': [{'id': 3164, 'method_title': 'Distance Rate (1.5 km; 4 mins)', 'method_id': 'distance_rate', 'instance_id': '3', 'total': '3.00', 'total_tax': '0.00', 'taxes': [], 'meta_data': []}], 'fee_lines': [], 'coupon_lines': [], 'refunds': [], 'date_created_gmt': '2021-03-04T18:06:28', 'date_modified_gmt': '2021-03-04T16:09:20', 'date_completed_gmt': '2021-02-20T06:28:43', 'date_paid_gmt': '2021-02-20T06:28:43', 'currency_symbol': 'R', '_links': {'self': [{'href': 'redacted'}], 'collection': [{'href': 'redacted'}], 'customer': [{'href': 'redacted'}]}}]

A: "the output of the API is dictionary inside a list"
quote from this, maybe you add a list in a list ?
after this code: all_orders.append(requests.get('API location next page').json()) , the all_orders will have inner list.
maybe get the value by:
all_orders[orders_collected - 1][some index]['status']

bugfix:
change append to extend
all_orders.extend(requests.get('API location next page').json())


text:
Q: Unable to handle volley response as JsonObject I have an API which returns the response like "[{"VideoReferenceURL":"x0DE_VDEEAw"}]"
I need to capture the value of "VideoReferenceURL" variable into a string variable "videoURL"
But when i use below code, the method is not getting into onResponse.
 JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                requestUrl, null, new Response.Listener<JSONObject>()
        {

            @Override
            public void onResponse(JSONObject response)
            {
                try {
                    String videoURL = response.getString("VideoReferenceURL");
                    Log.d("VideoURL",videoURL);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                progressDialog.hide();
                Log.d("myerror","I got some error");
                NetworkResponse networkResponse = error.networkResponse;
                Log.d("myerror1",error.getMessage());
                // Toast.makeText(getApplicationContext(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
            }
        })
        {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError
            {
                Map<String, String> headers = new HashMap<>();
                String credentials = Constants.WS_Username+":"+Constants.WS_Password;
                String auth = "Basic "
                        + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
                headers.put("Content-Type", "application/json");
                headers.put("Authorization", auth);
                return headers;
            }

        };

        RequestHandler.getInstance(_context).addToRequestQueue(jsonObjReq);

When i use above with StringRequest, i am getting into onResponse, but response is having entire String rather than JSON. I need to write custom string logic to extra the required value.
StringRequest stringRequest=new StringRequest(
                Request.Method.GET, requestUrl, new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response)
            {
                Log.d("VideoURL",response);
            }
        }

Tried below to handle as JSON, but it is still not getting into onResponse method
StringRequest stringRequest=new StringRequest(
                Request.Method.GET, requestUrl, new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response)
            {
                try {
                    JSONObject object=new JSONObject(response);
                    Log.d("VideoURL",object.getString("VideoReferenceURL"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }

Can someone tell me what i am missing here?


text:
Q: How can I serve multiple sites with apache based on the URL I have two separate Django projects that I want to serve up from the same machine. I'm trying to set up my VirtualHost configurations in apache to serve them up. I know I can serve them up on separate ports, but I'd rather do it based on the request URL. So example.com/app1 would go to one app and example.com/app2 would go to the other. ServerName and ServerAlias won't work since they only look at the Host, which in both cases would just be example.com. Is there any way to do this?
The ServerPath directive looked promising but it looks like, since it was only meant as a fallback for older browsers, apache only looks at ServerPath if the browser doesn't supply the Host field in the request.
Update: Here is what the VirtualHost configuration for my first app looks right now.
<VirtualHost *:80>
  ServerAlias *
  WSGIScriptAlias /app1 /home/eyuelt/app1/app1/wsgi.py
  Alias /app1/static /home/eyuelt/app1/staticfiles

  <Directory /home/eyuelt/app1/app1>
    <Files wsgi.py>
      Order deny,allow
      Require all granted
    </Files>
  </Directory>

  <Directory /home/eyuelt/app1/staticfiles>
    AllowOverride None
    Order deny,allow
    Require all granted
  </Directory>
</VirtualHost>


text:
Q: Building complex JSON in Javascript Just started using JavaScript and need some guidance on how best to create /build the JSON below on the fly/dynamically.
Some of the keys will need to be from variables.  For example in the JSON below, keys called 'variable_key_*' will need to be from a variable.
{
  "static_key_1": "value",
  "static_key_2": [{
    "static_key_3": {
      "id": "1097274153"
    },
    "static_key_4": "value",
    "static_key_5": {
      "static_key_6": {
        "variable_key_1": "value",
        "variable_key_2": "value",
        "variable_key_3": "value"
      },
      "static_key_7": {
        "static_key_8": [
          "value"
        ]
      }
    }
  }]
}

A: You can set keys in an object with variables by using bracket notation.
let theVariable = 'useful_name';
let theValue = 12345;
let myObj = {};

myObj [ theVariable ] = theValue;

Will result in:
{ useful_name : 12345 }

And stringify as you'd expect.
Edit based on request for more info:
Say you wanted to create a nested object with an array of objects, we'll use the object we already have.
myObj [ someOtherVar ] = {};
let myObjSomeOtherVar = myObj [ someOtherVar ];
myObjSomeOtherVar [ someOtherKey ] = [ ].push ( { } );
let theArrayOfObjects = myObjSomeOtherVar [ someOtherKey ];
theArrayOfObjects [ 0 ] [ anotherKeyName ] = 'hello';

This would result in (provided you actually declared all the vars etc)
{ useful_name : 12345,
  valOfSomeOtherVar :
      { valOfSomeOtherKey :
          [ { valOfAnotherKeyName : 'hello' } ]
      }
}

The trick is to just develop your data schema abstractly (so the skeleton you want), then write a routine that builds it. I rarely build an object by hand this way unless it's just a small util obj, I usually feed an empty object into a routine to build it out (using loops, recursion, conditionals, whatever). And as for practice, it is always a good idea to have a skeleton at least documented for a data structure, which can also be used as reference to write the function that can generate the whole thing just by passing it some variables for keynames and values. You would write a test for that function that would give you back the objects you'd predict, etc.

A: If you don't need to create it in one statement (and there is few chance you do), you'd do as follow:
var yourObject = {
  "static_key_1": "value",
  "static_key_2": [{
    "static_key_3": {
        "id": "1097274153"
    },
    "static_key_4": "value",
    "static_key_5": {
        "static_key_6": {},
        "static_key_7": {
            "static_key_8": [
                "value"
            ]
         }
     }
  }]
}

/* Get their value from wherever you want */
var variable_key_1 = 'something';
var variable_key_2 = 'something_else';
var variable_key_3 = 'another_one';

yourObject.static_key_2[0].static_key_5.static_key_6[variable_key_1] = 'value';
yourObject.static_key_2[0].static_key_5.static_key_6[variable_key_2] = 'value';
yourObject.static_key_2[0].static_key_5.static_key_6[variable_key_3] = 'value';

The strategy is to build the objects with properties with variables names after the ones with static names, using the brackets notation.
This will result in:
{
  "static_key_1": "value",
  "static_key_2": [{
    "static_key_3": {
        "id": "1097274153"
    },
    "static_key_4": "value",
    "static_key_5": {
        "static_key_6": {
          "something": "value",
          "something_else": "value",
          "another_one": "value"
        },
        "static_key_7": {
            "static_key_8": [
                "value"
            ]
         }
     }
  }]
}


text:
Q: How can I call methods within a nested class using new()? Right now, I have a nested class as so:
class Outer{

public:
    class Inner{

    public:
        void display(){
             cout << "You are in inner class" << endl;
        }
     };
     void display(){
         cout << "You are in outer class" << endl;
     }
};

I have to create an instance of each class Outer and Inner so I can invoke each of their display() methods. I have to use new in order to invoke them as part of my requirement. I can invoke the Outer class fine and point to its method as so:
Outer *pOuter = new Outer();
pOuter->display();

But, I'm having troubles doing the same to the Inner class. I've tried:
 Outer:Inner *pInner = new Outer:Inner();
 pInner->display();

but, that doesn't work. So I'm wondering what I can do to invoke the inner method while using new?

A: Use the fully qualified path:
Outer::Inner* p = new Outer::Inner;
p->display();
delete p;

Without pointers:
Outer::Inner o;
o.display();

Or mark the function static and call as:
Outer::Inner::display();

That being said, as-is this is better suited for a (Outer) namespace instead of a class.


text:
Q: How do I get python code to execute properly from a button click when an alert is included as action from the button click? I have been having trouble getting alerts to work with an html button press that also calls a url. Describing the problem in more detail, I have a button that when pressed calls a url which from my urls.py file and views.py file calls some python code that plays a video but when I include an alert to trigger when the button is pressed, the python code does not get executed but the alert shows up without any problem. My question is how do I make these two actions compatible on a single button click so that both are executed properly? Also using the Django framework if that provides more information.
This is the html and javascript

Play Video

A: if you want to execute server side and client side code you need to use XHR or simply Ajax
 will redirect page to href's url, for this you need to add 'return false' to your JavaScript click method
like this
`function click(){
   alert();
   // call your ajax here
   return false;
}`

hopefully this can help you


text:
Q: Displaying number of items according to parameters passed xaml windows phone ok I have a MainPage.xaml
This passes a parameter to NextPage.xaml like this NextPage.xaml?count=10
Now i want to display 10 items on a long list selector, this number depends on the parameter passed how do i do this, can i bind data dynamically?

A: NavigationService.Navigate(new Uri("/Pagina2.xaml?count=10", UriKind.Relative));

What you do. If you want do pass a varibale that contain the integer 10:
int getInteger= 10;
NavigationService.Navigate(new Uri("/Pagina2.xaml?count="+getInteger, UriKind.Relative));

A: You can get the navigation parameter like this:
if (NavigationContext.QueryString.ContainsKey("count"))
        {
            var countString = NavigationContext.QueryString["count"];
            var count = Int32.Parse(countString);
            // Create list
            for(int i = 0; i < count; i++)
            {
                 MyLLSList.Add(new Item());
            }
        }

where MyLLSList is a property in your ViewModel to which you can bind as the LLS ItemSource.
Hope this helps a bit.


text:
Q: Convergence in r-mean Let $(X_{n})_{n \in \mathbb N}$ be a sequence of random variables such that
$X_{n}$ converges to $X$ in r-mean. I want to prove that, if $\lim_{n} c_{n} = c$, then $c_n X_n$ converges in r-mean to $cX$. I know that $\lim_{n} E[|X_n-X|^r] = 0$ and $\lim_{n} c_n = c$, but don't know how to prove that $\lim_n E[|c_n X_n - cX|^r]=0$.

A: In case $E[|X|^r] = \infty$, then the result is generally false. For example, let $X \sim \text{Cauchy}$ and $X_1=X_2=\ldots=X$. Clearly, $X_{n}$ converges in r-mean to $X$. However, by taking $c_n=1-n^{-1}$, note that, for every $n$, $E[|c_n X_n-cX|^r]=\infty$. Therefore, the result does not hold.
In case $E[|X|^r] < \infty$, then
\begin{align*}
 \lim_{n} E[|c_n X_n - cX|^r]
 &= \lim_{n} E[|c_n X_n -cX_n +cX_n -cX|^r] \\
 &\leq \lim_{n} (E[|c_n X_n-cX_n|^r]+E[|cX_n -cX|^r]) \\
 &= \lim_{n} ((c_n-c)^r E[|X_n|^r]+c^r E[|X_n-X|^r]) \\
 &= \lim_{n} (c_n-c)^r E[|X_n-X+X|^r] \\
 &\leq \lim_{n} (c_n-c)^r (E[|X_n-X|^r])+E[|X|^r]) \\
 &= 0
\end{align*}
That is, $\lim_{n}E[|c_n X_n - cX|^r]=0$.


text:
Q: How to make a very simple countdown timer in Javascript? I'm making a simple game which generates random numbers and user has to enter a value, if users value matches the random value generated, the user wins basically this is a beginner project. I want to make a small counter so that user has a limited time to put in the value and I want that limited time to show on the screen in a label. Lets say that you have to put the value under 30 secs and the timer will count from 1 to 30 every second. The counting from 1 to 30 will update in the label every second. This is the logic I'm trying to work on right now and I can't figure out any other way... If I've done some mistake in code please comment or if you have much more simpler way please post it down below. (pls dont vote down im at threat of account suspension)
Heres the part of my timer code:
if(timer <= 30)
    {
        for(var i = 0;i >= 30;i++)
        {
            setInterval(null,1000);
            timer++;
            document.getElementById("counter").innerHTML = timer+" seconds wasted";
        }
        alert("Time is over, you lost by "+s);
    }

A: The setInterval function has 2 parameters, a callback (an anomynous function in javascript thats triggered) and the milliseconds between each trigger of the interval.
What you are doing in your script is making an interval with nothing to do each second (this runs indefinately), then increment the timer integer and updating the DOM. However, this all executes within seconds.
I'd suggest (before you use a function) you look at the documentation to see how you can improve your script to work as you intent to ;-) Here are a few links that might help you get started:
http://www.w3schools.com/js/js_timing.asp
https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/
I wont be doing the work for you, since this is a good exercise for a beginner programmer ;-)
If you can't figure it out, leave a comment below this answer and I'll get back to you to help you if you need further assistance.

A: You could create a recursive function.
Say var countDown function(){ time = time--;
setTimeout(countDown, 1000);}
Then you need a variable time that is accessible for the countDown function.
var time = 30;
In the countDown function you could create an updateTimeElement.
Try it out.


text:
Q: Why are particles different sizes? Is it correct in saying that a particles size is it's rest energy, and that particles don't actually have size (in the way you get different size objects)?
What defines what sizes a particle can be? Why do particles have discrete sizes, and there's not a continuous spectrum of particles varying in size?
I ask because I was told that particles mass depends on its size, as the bigger a particle is the more it interacts with the Higgs boson and so the more mass it has. So why are there so few particles with specific masses/sizes?

A:
Is it correct in saying that a particles size is it's rest energy,

No

and that particles don't actually have size (in the way you get different size objects)?

Not really.

Why do particles have discrete sizes, and there's not a continuous spectrum of particles varying in size?

They don't have discrete sizes.

OK, let me explain:
Fundamental particles are point particles by the Standard Model (String theory gives them a size, which seems to be somewhat correlated with mass, but I'm keeping String theory aside here).
Of course, we have fundamental particles of varying rest energies, so size is not related to mass.
Now, let's look at composite particles. Say, a proton. Protons are made of three quarks, along with some virtual gluons that are being exchanged. The size of the proton is thus the volume in which all its constituent particles are confined.
But, the constituent particles are not confined--there is a very slim chance of finding one of the quarks a few meters away{*}, due to the wave nature of the particles. So, we define size as the volume where you will find all the particles in <some arbitrary percentage> of the time (where that arbit percentage will be somewhat like 99.999%)
The definition need not be "all the particles will be found here x% of the time"; we can have fundamentally similar, but different definitions. For example, as @dmckee noted, the charge radius of a nucleus is where the charge density drops to $e^{-1}$ of the central density.
Similarly, for an atom, you could define size via the boundary of the electron cloud. But, the electron cloud stretches to infinity, so you have to arbitrarily define size via a percentage(or something similar).
In fact, for an atom, going across a period, size decreases as mass increases (but not when going down a group). So, for composite particles, size and mass have no fixed relation.
*I'm not too sure of this, color confinement may prevent the quark from going so far without pair production.

A: The rest energy of a particle determines its mass but not its size.
Although it is often said that elementary particles are points, the correct statement is to say that they are pointlike, because due to renormalization corrections, the point particles that correspond to the bare fields in the defining Lagrangian become slightly extended.
The size of a particle is determined by how the particle responds to scattering experiments, and therefore is (like the size of a ballon) somewhat context-dependent.
My theoretical physics FAQ contains two chapters with several entries related to questions of particle size (and shape, which is related), where much more detail can be found:
Chapter A6: The structure of physical objects
   - Does an atom mostly consist of empty space?
   - How do atoms and molecules look like?
   - When is an object macroscopic?
Chapter B2: Photons and Electrons
   - Are electrons pointlike/structureless?
   - The shape of photons and electrons


text:
Q: How to reset a silverlight control's visual state back to "Normal" on change of visibility I have a problem with a button control with rolloever effect. I am collapsing the button on click and later it becomes visible again, but the Mouse Hover state doesn't change back to Normal when the button becomes visible. However the issue can be resolved by changing the visual state in code but I w'd like to know if there is a way to do it in the control template?
Here is my template:
<Style x:Key="replayButton" TargetType="Button">
        <Setter Property="Background" Value="#FF1F3B53"/>
        <Setter Property="Foreground" Value="#FF000000"/>
        <Setter Property="Padding" Value="3"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="BorderBrush">
            <Setter.Value>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FFA3AEB9" Offset="0"/>
                    <GradientStop Color="#FF8399A9" Offset="0.375"/>
                    <GradientStop Color="#FF718597" Offset="0.375"/>
                    <GradientStop Color="#FF617584" Offset="1"/>
                </LinearGradientBrush>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Cursor="Hand" Height="48" Margin="0,0,0,0" Width="48">
                        <vsm:VisualStateManager.VisualStateGroups>
                            <vsm:VisualStateGroup x:Name="CommonStates">
                                <vsm:VisualState x:Name="Normal">
                                    <Storyboard Storyboard.TargetName="bgImg" Storyboard.TargetProperty="Source">
                                        <ObjectAnimationUsingKeyFrames>
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="images/repeat.png"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </vsm:VisualState>
                                <vsm:VisualState x:Name="MouseOver">
                                    <Storyboard Storyboard.TargetName="bgImg" Storyboard.TargetProperty="Source">
                                        <ObjectAnimationUsingKeyFrames>
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="images/repeat-hover.png"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </vsm:VisualState>
                                <vsm:VisualState x:Name="Pressed">
                                    <Storyboard Storyboard.TargetName="bgImg" Storyboard.TargetProperty="Source">
                                        <ObjectAnimationUsingKeyFrames>
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="images/repeat-hover.png"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </vsm:VisualState>
                                <vsm:VisualState x:Name="Disabled">
                                    <Storyboard/>
                                </vsm:VisualState>
                            </vsm:VisualStateGroup>
                            <vsm:VisualStateGroup x:Name="FocusStates">
                                <vsm:VisualState x:Name="Focused">
                                    <Storyboard/>
                                </vsm:VisualState>
                            </vsm:VisualStateGroup>
                        </vsm:VisualStateManager.VisualStateGroups>
                        <Border Height="48" Margin="0,0,0,0" x:Name="Background" Width="48" Background="{x:Null}" CornerRadius="0,0,0,0">
                            <Grid Height="48" Margin="0,0,0,0" Width="48">
                                <Image x:Name="bgImg" Height="48" Margin="0,0,0,0" VerticalAlignment="Bottom" Source="images/repeat.png" Stretch="Fill" Width="48"/>
                            </Grid>
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

A: VisualStateManager.GoToState(myControl, "Normal", true) on visibility change.
You can subscribe to the VisibilityChanged event


text:
Q: MySql prepared statement is not working for SELECT,but works for all other statement I have found same question at SO
Prepared statement works for INSERT but not for SELECT
and tried to follow it,but no luck.One more thing, that question is on OOP structure,but my one is procedural style
Here is my code
$stmt = mysqli_stmt_init($connect_dude);

if(mysqli_stmt_prepare($stmt,"SELECT headx FROM main_page WHERE user_id=?")){

  mysqli_stmt_bind_param($stmt, "i", $idx);
  mysqli_stmt_execute($stmt);
  mysqli_stmt_bind_result($stmt, $head);
  printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

  ...................
  ...................
}

It shows Number of rows:0 where it should be 1.That's why,I cannot proceed further to fetch data from database.I tried my best to fix the problem,but couldn't make it.
Your help would be really appreciated.
Thanks for your time.

A: I have figured it out.
Need to use mysqli_stmt_store_result($stmt)
mysqli_stmt_bind_param($stmt, "i", $idx);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

gives me Number of rows:1
As of php.net
You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN)
BUT
NOT MUST for UPDATE,DELETE AND INSERT.
Thanks everyone.


text:
Q: override layout file 3rd party extension in magento 2 I want to override xml file of 3rd party extension in my custom theme in magento 2.1.13 . Till now i did following steps:-
1) path of the xml which i want to override is app/code/Namespace/ModuleName/view/frontend/layout/layoutfile.xml
2) i had changed layout file and uploaded at app/design/frontend/packageName/themename/Namespace_ModuleName/layout/layoutfile.xml
after step 2. i had deleted pub/static/* and deployed static content again using php bin/magento setup:static-content:deploy . Then i cleared and flushed cache. still my css has not been changed. please help me

A: Try below code to remove CSS :
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
    <remove src="name.css"/>
</head>
</page>

No need to copying full XML just put what you want to remove.


text:
Q: Meaning of ST and OP fields in dumpsys netstats output I am running the adb shell dumpsys netstats detail command to obtain details of the network usage, however, I do not know the meaning of all the acronyms that has the result of this command.
In the documentation of the dumpsys tool they explain the meaning of rb, rp, tb and tp, but not that of st or op.
Anyone know what it means?
This is a fragment of command output.
defaultNetwork=true}] uid=10127 set=DEFAULT tag=0x0
    NetworkStatsHistory: bucketDuration=3600
      st=1567522800 rb=1275 rp=5 tb=876 tp=5 op=0
      st=1567526400 rb=6697 rp=41 tb=7359 tp=38 op=0

A: st is the bucketStart timestamp and op is number of operations.


text:
Q: In Javascript, what does num = +thenum || false mean? I was self learning JavaScript by reading a book. I can't understand one of the code
var thenum = document.getElementById("sr_num").value;
thenum = +thenum || false

The last line is never explain throughout the book. I could't understand what is this about. Anyone could explain this to me will greatly appreciate. Thank you.

A: thenum = +thenum || false

is to make sure that thenum is really a valid number. If it is not, then thenum will be assigned false.
The +thenum would try to convert the string value in thenum (document.getElementById("sr_num").value would give a string value) to a number. If it fails, it would return NaN, which is considered as falsy. You can confirm that like this
console.log(+"All hail lelouch");
// NaN

So, if thenum is not a valid number, then the expression becomes
thenum = NaN || false

Since NaN is falsy, the false will be assigned in thenum.
Note: The only valid numeric input for which this expression won't work is 0. Because when the input is "0", the expression becomes
thenum = +"0" || false
       = 0 || false

So, thenum will still be assigned false.

A: HTMLInputElement.value returns a string. +thenum is called the Unary plus operator and converts any value to a Number or NaN. Since NaN is falsy, the OR (||) operator would evaluate the second half of the expression, assigning false to thenum. Another exception is if +thenum happens to return 0, the only falsy number. This would assign false to thenum as well, though this does not appear to be intentional behavior. Aside from these two exceptions, since all other numbers are truthy, the second half of the OR expression will not be evaluated, and the number would be assigned to thenum. The following snippets will demonstrate what is going on.
Equivalent behavior:
if(+thenum) {
    thenum = +thenum;
else {
    thenum = false;
}

(Probably) intended behavior:
if(isNaN(+thenum)) {
    thenum = false;
} else {
    thenum = +thenum;
}

Shorthand of the above (probably) intended behavior:
thenum = (isNaN(thenum = +thenum) ? false : thenum);

Hope this helps clarify things.


text:
Q: how to read multiple csv and merge i have 39 csv files which have a lot of memory size. I want to load this file by Java and set as one variable. Below paragraph is my coding which works for small size file, but doesn't work for large size file. Size of file is usually around 100mb to 800mb. I want to load 39 file in directory and put them into one 2d array.
public static String readCSV(File csvFile) {
    BufferedReader bufferedReader = null;
    StringBuffer stringBuffer = new StringBuffer();

    try {
        bufferedReader = new BufferedReader(new FileReader(csvFile));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try {
        String temp = null;
        while((temp = bufferedReader.readLine()) != null) {
            stringBuffer.append(temp+","); // temp 에 저장되어있는 한 줄을 더한다.
        }

        System.out.println(stringBuffer);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // -10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,,,,,,,,,,1,2,3,4,5,6,7,8,9,10, 반환
    return stringBuffer.toString();
}

public static String[] parse(String str) {
    String[] strArr = str.split(","); // 쉼표가 1개인 것을 기준으로 나누어서 배열에 저장

    return strArr;
}

public static void main(String[] args) throws IOException {

    //mergeCsvFiles("sample", 4, "D:\\sample_folder\\" + "merge_file" + ".csv");

    String str = readCSV(new File("D:/sample_folder/sample1.csv"));
    String[] strArr = parse(str); // String 배열에 차곡차곡 담겨서 나온다.
    int varNumber = 45;
    int rowNumber = strArr.length/varNumber;

    String[][] Array2D = new String[varNumber][rowNumber];
    for(int j=0;j<varNumber;j++)
    {
        for(int i=0; i<rowNumber;i++)
            {
                String k = strArr[i*varNumber+j];
                        Array2D[j][i]= k;
        }
    }                       //2D array 배열을 만들기

    //String[][] naArray2D=removeNA(Array2D,rowNumber,varNumber); //NA 포함한 행 지우기

//      /*  제대로 제거 됐는지 확인하는 코드
    for(int i=0;i<varNumber;i++){
        for(int j=0;j<16;j++){
                            System.out.println(Array2D[i][j]);
        }
                        System.out.println("**********************NA제거&2차원 배열**********************");
    }
//      */

    }
}

A: With the file sizes you are mentioning, you either are going to likely run out of memory in the JVM.
This is probably why your largest file of 800 some MB isn't loading into memory. Not only are you loading that 800MB into memory, but you are also adding the overhead of the arrays that you are using. In other words, you're using 1600MB + all of the extra overhead cost of each array, which becomes sizeable.
My bet is that you are exceeding memory limits under the assumption that file format is perfect in both cases. While I cannot confirm as I do not know your JVM, your memory consumption, nor have the required assets to figure any of this out, it is up to you to decide whether or not that is the case.
Also, I don't know - maybe I'm reading your code right, but it doesn't seem like it's going to do what I think you want it to do. Maybe I'm wrong, I don't know exactly what you're trying to do.


text:
Q: Probability of a combination drawing from multiple distribution I want to find a formula for the probability of a combination of $K$ balls. For examples, $K=9$, and I want to find the probability of having $2$ red, $3$ blue, and $4$ white balls. There are three possible type of balls.
$K_1$ balls draw from distribution $1$, $K_2$ balls draw from distribution $2$, and $K_3$ balls draw from distribution $3$. Obviously, $K_1+K_2+K_3 = K$. All draws are with replacement and each distribution has different density. For example, in distribution $1$, the probability of getting a red, blue, and white balls are $p^1_r$, $p^1_b$, $p^1_w$. And so on.
I believe this problem must be solved somewhere but I couldn't find it after a lot of Googling. Your answer will be much appreciated!

A: Defining $K:=K_1+K_2+K_3$, there are $\frac{K!}{K_1!K_2!K_3!}$ different orders to draw $K_1$ red, $K_2$ blue and $K_3$ white balls. Let the probability in each drawing for "red" be $p_1$, for "blue" be $p_2$ and for "white" be $p_3$, then the probability for $K_1$ red, $K_2$ blue and $K_3$ white balls is:
$$P(K_1, K_2, K_3) = \frac{K!}{K_1!K_2!K_3!}p_1^{K_1}p_2^{K_2}p_3^{K_3}$$


text:
Q: Set line as variable then execute script I'm working on a script:
@Echo off
for /f "tokens=*" %%f in (filenames.txt) do set filename=%%f
echo %filename%
pause

The problem is that it only echos the last line in "flienames.txt" and I need it to do them all in order one by one.

A: Here you can read more about loops in batch-file. In your case the code should look like this:
@Echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /f "tokens=*" %%f in (filenames.txt) do (
  set filename=%%f
  echo !filename!
)
pause


text:
Q: Assetss from wwwroot cannot be found on Docker Image I have got Linux VM Docker Image up and running but I have encountered one difficulity.
All assetss that were in my wwwroot folder cannot be found

Failed to load resource: the server responded with a status of 404 (Not Found)

I have included
 "webroot": "wwwroot"

In project.json file but that doesn't fix the problem. One more thing is thaht running from VS 2015 (on ISS Express) everything works - is there something that I should include in Dockerfile as well?.
EDIT:
I added VOLUME to docker file but that did not help:
FROM microsoft/aspnet

COPY . /app
WORKDIR /app
RUN ["kpm", "restore"]

VOLUME ["/wwwroot"]

EXPOSE 5004
ENTRYPOINT ["k", "kestrel"]

A: are you working through the example here:  asp ? I don't know much about asp, but, I think you are pretty close.  First, I don't think you need to modify the Dockerfile.  You can always mount a volume, the VOLUME keyword just declares it as necessary.  But, you do need to modify your project.json file like you have shown, with one difference:
"webroot": "/webroot"

I am assuming that the name is "webroot" and the directory to look in (for the project) is "/webroot".  Then, build it, like the example shows:
docker build -t myapp .

So, when you run this do:
docker run -t -v $(pwd)/webroot:/webroot -d -p 80:5004 myapp

What this docker run command does is takes your webroot directory from the current directory ($pwd) and mounts it in the container and calls that mount /webroot.  In other words, you container must reference /webroot (not webroot, that would be relative to WORKDIR I think).
I think the bottom line is there are two things going on here.  The first one is 'building' the image, the second one is running it.  When you run it you provide the volume that you want mounted.  As long as you application repects the project.json file's "webroot" value as the place to look for the web pages then this will work.


text:
Q: Transformation of functions under bijections of domain and codomain Let $f:X\to Y$ be a function, for simplicity, of sets. I want to understand how the function transforms under a transformation of domain/codomain.
Let me start from what I deem to understand well enough: assume $g:X\to X$ is a bijection. If I view the function as a section,
$\sigma : X\to X\times Y$, then I have the fundamental equations
$$
\pi_X\circ \sigma = \mathbb{1}_X \  \ \text{and} \ \ \pi_Y\circ \sigma = f,
$$
where a section, by definition always satisfies $\pi_X\circ \sigma =\mathbb{1}_X$. I see my goal as constructing a new section given the old section and $g:X\to X$.
Acting with $g$ on the left of $\pi_X\circ \sigma =\mathbb{1}_X$, I get
$$
g\circ \pi_X\circ \sigma =g,
$$
in order to get the fundamental relation that sections satisfy, I act with $g^{-1}$ on the right of the above equation, getting
$$
g\circ \pi_X\circ \sigma \circ g^{-1} =\mathbb{1}_X.
$$
The other equation gives us
$$
\pi_Y\circ \sigma \circ g^{-1}=f\circ g^{-1}
$$
Defining $g\circ \pi_X = \tilde{\pi}_X$, I see that the transformed section is
$$
\tilde{\sigma}=\sigma \circ g^{-1}.
$$
In other words, under a bijection of the domain, a function transforms as
$\sigma \mapsto \tilde{\sigma}(x)=(x,f(g^{-1}(x)))$.
As an example of the above, if $g:x\mapsto x+\epsilon$ is a bijection of the domain, then any function $$f(x) \mapsto \tilde{f}(x):=f(x-\epsilon)$$.
Similarly if I also transform the codomain Y, seperately from the domain, X; namely, if I have along with $g:X\to X$ also an $h:Y\to Y$ then following the same reasoning as above I get that
$$
\sigma \mapsto \tilde{\sigma}(x)=(x,h(f(g^{-1}(x)))).
$$
In other words if $g:x\mapsto x+\epsilon$ and $h:y\mapsto e^\epsilon y$, then a function $f$ transforms according to
$$
f(x)\mapsto \tilde{f}(x):=e^\epsilon f(x-\epsilon).
$$

Here is my question, how does a function transform if we have a bijection $$
G:X\times Y \to X\times Y
$$
  where because the domain is a product, there is no way to "seperate" the mixing of $X$ and $Y$.

A: This is basically what you did in the first part of the question:
Given a diagram:
$$\begin{array}{c}
X & \overset f \longrightarrow & Y \\
{\small \sim} {\Large\downarrow} {\small g} && {\small \sim} {\Large\downarrow} {\small h} \\
X && Y
\end{array}$$
Construct the new morphism $\tilde f : X \to Y$ that fills in the gap of the commuting diagram:
$$\begin{array}{c}
X & \overset f \longrightarrow & Y \\
{\small \sim} {\Large\downarrow} {\small g} && {\small \sim} {\Large\downarrow} {\small h} \\
X & \overset {\tilde f} \longrightarrow & Y
\end{array}$$
And it is explicitly constructed:
$$\tilde f = h \circ f \circ g^{-1}$$
And the reasoning through products is summarized in this diagram:
$$\begin{array}{c}
& X & \\
& {\small \sim} {\Large\downarrow} {\small g^{-1}} & \\
& X & \\
& {\small \sim} {\Large\downarrow} {\small \sigma} & \\
& X \times Y & \\
\pi_X \swarrow && \searrow \pi_Y \\
X && Y \\
{\small \sim} {\Large\downarrow} {\small g} && {\small \sim} {\Large\downarrow} {\small h} \\
X && Y
\end{array}$$
where $\pi_Y \circ \sigma = f$ and $h \circ \pi_Y \circ \sigma \circ g^{-1} = \tilde f$.
In particular, a function $X \overset f \longrightarrow Y$ is identified with a morphism $X \overset \sigma \longrightarrow X \times Y$ where $\pi_X \circ \sigma = 1_X$ and $\pi_Y \circ \sigma = f$.

The problem is that when you transform the domain and the codomain together, the resulting graph might not be that of a function.
Just take $Y = X$ and $G : (x,y) \mapsto (y,x)$. Then, what you want is equivalent to "the inverse of every function is a function", which is demonstrably false.
And in the product jargon:
$$\begin{array}{c}
& X & \\
& {\small \sim} {\Large\downarrow} {\small \sigma} & \\
& X \times Y & \\
\pi_X \swarrow & {\small \sim} {\Large\downarrow} {\small G} & \searrow \pi_Y \\
X & X \times Y & Y \\
\pi_X \swarrow && \searrow \pi_Y \\
X && Y \\
\end{array}$$
Even if $\pi_X \circ \sigma = 1_X$ and $\pi_Y \circ \sigma = f$, it is not necessarily true that $\pi_X \circ G \circ \sigma$ is an isomorphism.
However, $\pi_Y \circ G \circ \sigma$ might be a function you want, since its domain is $X$ and its codomain is $Y$.
Here, if $G(x,y) = (G_X(x,y),G_Y(x,y))$, then the new function $\tilde f : X \to Y$ would send $x$ to $G_Y(x,f(x))$.

For example, if $G : (x,y) \mapsto (x+2y,2x+y)$, then $f(x) \mapsto \tilde f(x) := 2x+f(x)$.
However, what seems to be the inverse of this construction (applying $G^{-1}$ instead of $G$) doesn't actually get you back to what you started with.


text:
Q: javascript loop through li in div of paginate Below is the code I'm using. The top part $('div.pagination... works fine, I can alert(length) and it gives me the correct value of pages in the pagination section. The bottom part appears not to work. This is for a scraper that will open each page on a forum. If I leave the loop out of it it successfully retreaves the url for page here. The length -=2 is to remove the next/previous li from the total count.
$('div.pagination').each(function() {
    var length = $(this).find('li').length;
    length -= 2;
});

for (var i = 0; var <= length; i++) {
  var pageToOpen = 'http://someWebsite.com/index/page:' + i;
  alert(pageToOpen);
  page.open(pageToOpen, function (status) {
      if (status == 'success') {
          logAuctions();
      }
  }});
}

A: Define your var length outside (before) the.each()
Using .lentgh method you might miss the real page indexes. So I would suggest to grab the real anchor hrefs.
FIDDLE DEMO
var pages = [];

// skipping the "Next" and "Last" get all A ahchors
$('div.pagination li').slice(0,-2).find('a').each(function(){
   pages.push( $(this).attr('href') );
});

$.each(pages, function(i, v){
    $('<div>'+ ("http://someWebsite.com"+v) +'</div>').appendTo('#output');
});

/* WILL RESULT IN:

http://someWebsite.com/auctions/index/page:2
http://someWebsite.com/auctions/index/page:3
http://someWebsite.com/auctions/index/page:4

*/


text:
Q: OBIEE 11g installation stuck I am new to OBI. I was trying to install OBIEE 11g Oracle Business Intelligence, v. 11.1.1.9.0. But when my installation reached to step 13 of 14, Deploying Financial Reporting JEE Application. It seems that the installation is stuck.
Is there any way to solve this problem?

A: Please make sure to install OBIEE on Server OS (Windows 2012, Linux etc) and not desktop OS (Windows 7/10 etc).

A: Installing a whole farm of servers - which is what OBI is - on  a Windows DESKTOP operating system never was, is not and will never bea good idea!
https://dimensionality.ch/2017/05/06/installing-oracle-bi-on-windows-7-8-10/


text:
Q: Regex double new line What I want to do is to take the left and right parts of double line.
Example
LEFT_PART\r\n\r\nRIGHT_PART

Left and right part can be anything but they will not contain double new line.
What I'm doing is not working (doesn't match the string I give it). This is what I've done so far.
^(.*)[\r\r|\n\n|\r\n\r\n]{1,1}(.*)$

It can start with anything, followed by exactly one double-new line, followed by anything.
I group the right and left because I need to use them aftewards.
EDIT
I use OR to cover all three types of new-line

A: Square brackets are used for character class and not grouping. Try using parens:
^(.*)(\r\r|\n\n|\r\n\r\n)(.*)$

And to avoid capturing the double newlines;
^(.*)(?:\r\r|\n\n|\r\n\r\n)(.*)$

The {1,1} is also redundant. I removed it.

A: It's not working because you have used a character class, which matches just a single character. You should use parenthesis. Also, you can simplify your regex by using {n} quantifier. To match \r\r, use \r{2}:
^(.*)(?:\r|\n|\r\n){2}(.*)$

Apart from that, I would rather get the line separator for my system using:
String lineSeparator = System.getProperty("line.separator");
String regex = "^(.*)" + Pattern.quote(lineSeparator) + "{2}(.*)$

A: Try this:
(?m)^(.*)$[\r\n]{1,2}^$[\r\n]{1,2}^(.*)$

The switch (?m) has the effect that caret and dollar match after and before newlines for the remainder of the regular expression
Here's a live demo of this regex working.

A: Try the next:
^(.*)(?:(\r|\r?\n){2})(.*)$


text:
Q: How to receive notification of HTTP access I have a web server running on my Mac and I'd like to be notified (via Growl for example) when someone accesses my server.
I searched for something like that in Automator but found nothing.
Do you know if this is possible ?
Thank you.

A: The key is your access logs.  Assuming your webserver is properly configured, each time a page is served it should provide some level of detail in the access logs.  This can be turned off for sites with enourmous traffic loads, but for your bog standard (assuming) apache install on a local machine I imagine you are not looking as a massive load.
So, what you need is a method to examine the access log periodically (or real time) either by checking timestamps, or tailing the content etc.  Once this is sorted, you need a way to push it into growl.  Growlnotify is a command line utility that will accept output from other commands and use it as the basis to provide a graphical growl notification.
At this point you need to decide if you want a simple "You have visitors!" message, or something that includes the details, say which page was served to which IP address etc.  That's your choice, and makes the code you need to write that bit more complex or simple.
Check the following example (sorry, I use ksh, you may need to modify):
#!/bin/ksh
while read access
do
growlnotify -t "HTTP_Access" -m "You have visitors!
done < /http/access/log/folder/log1.log

Obviously this will churn out far too much info and be generic, so you need to add your own special blend of a) configuring Apache to only log to the level you need, and b) filter out the entries anyway, possibly formatting while you go, e.g.:
#!/bin/ksh
while read access
do
formatted_access=`echo $access | grep -v "unwanted strings" | awk '{print "Time "$1", IP"$4}'`
count =`echo $formatted_access | wc -l`
case $count in
(0)
# No line matched criteria
;;
(*)
growlnotify -t "HTTP_Access" -m $formatted_access
;;
esac
done < /http/access/log/folder/log1.log

Throw this into an automator service, and away you go.

A: One of the most powerful methods of getting notifications from a web server is to build in support for webhooks. The fine folks behind this software stack have a nice blog that helps describe how this might work if you wanted to code this into the web site.

A: Growl can probably do this for you automatically:


text:
Q: makefile and command line in terminal I have a command line which could run in terminal :
nwave nand_sim.fsdb -play hello.tcl

But when I add this line in my makefile, I got:
nwave command not found
Why is that? Isn`t comand in terminal and command in makefile execute the same way?

A: Finding a command is done by searching your PATH environment variable.  The setting for this isn't the same in the shell and in a makefile.  Its best to always include the whole path to a command, especially when its not in a standard directory.


text:
Q: Strange Conflict between Apache, CURL and MySQL outputs? I have very strange situation...
Platform: Win7, apache24, mysqld 5.6.x, php5.5.10
query1 = "SELECT abc FROM table1 WHERE id=123 " (result give me about 200 rows)
query2 = "SELECT abc FROM table2 WHERE id=555 " (result give me about 200 rows)
In short, PHP code looks like this:
step1. I'm using my own DB Wrapper and I make query1 to table1. In result I receive multiple rows from table1. I save it to php array using while loop.
step2. next I make curl requests to 3rd party API using foreach loop. Request are very simple and working fine at 150 other places in my script.
What is wrong?
Scripts are working fine.. but only one time after apache start/restart.
What going next?

*

*When I try reload page for test it again - curl response is empty. http_code for curl request is 200, but request is empty.

*After apache restart script working again - one time.

*Without step1 curl working fine all time.

*And one more... when I try query2 (similar to query1) but for different table (query2 to table2) script works fine everytime (after refreshing too).
What i tried:

*

*testing different headers in curl,

*curl options like curlopt_fresh_connect and all f... possible configurations.

*dumping printing all possible variables...

*googling, binging, yandexing....

*after step1 I tired connect to different websites than API, google, websites without ssl etc - result is the same. Crash after 1 run.

Browser cache is not a problem, API limits are fine.
I wasted for it 9 hours and I dont know what is wrong:)
If you have any ideas - please share with me.


text:
Q: Stop -Wall -Wextra popup so that a user can compile a program without having to press 'Enter' or 'Esc' I am trying to learn C++ using VS code in Ubuntu 19.10. I use two C/C++ extensions for this. Now the problem is I have to click the screen twice in order to view the terminal output. Its really getting my nerve. I don't know what that notification is trying to tell, but its really slowing down my performance. How to stop this Flags when its clearly not necessary for me now?

Two extensions which I used for C++ are:

*

*C/C++ Compile Run by danielpinto8zz6

*C/C++ by Microsoft

A: This is an option provided from the C/C++ Compile Run extension. It provides several different commands:

*

*Compile with default flags

*Compile with custom flags

*Compile with default flags and run with default arguments (F6)

*Compile with custom flags and run with custom arguments (F7)

*Run with default arguments

*Run with custom arguments

When custom flags or arguments are mentioned, such input will appear.
As you mentioned in the comment, you remapped one of such command on Ctrl-A, and since it is asking for you input I assume it is either 2 or 4 from above. Try using one of the other two compile commands ( depending on if you want to only compile or also run). You can also invoke them manually from the command palette (Ctrl-Shift-P and search for one of the commands above.)