text:
Q: How to render a UIView whose subview's layer has a `compositingFilter` I want to render a UIView into a UIImage, but some subviews of that UIView have set blend mode using layer.compositingFilter, these views will render without blend mode, such as:
view.layer.compositingFilter = "multiplyBlendMode"

According to Apple's documentation:

The OS X v10.5 implementation of this method does not support the entire Core Animation composition model. QCCompositionLayer, CAOpenGLLayer, and QTMovieLayer layers are not rendered. Additionally, layers that use 3D transforms are not rendered, nor are layers that specify backgroundFilters, filters, compositingFilter, or a mask values. Future versions of macOS may add support for rendering these layers and properties.

My render code:
let format = UIGraphicsImageRendererFormat.default()
format.scale = 1.0
let image = UIGraphicsImageRenderer(size: self.bounds.size, format: format).image { context in
    self.layer.render(in: context.cgContext)
}

How to render a view with blend mode like multiply blend mode?


text:
Q: Output of lsblk includes both pipes and back ticks sda
|-sda1 ntfs     Recovery       F49E60439E5FFD0C
|-sda2 vfat                    0E62-991B                              61.6M    36% /boot/efi
|-sda3
|-sda4 ntfs                    5EEC0B13EC0AE55D
|-sda5 ext4     Home           f142204b-a3c1-4ed4-b255-944659cef7bd  239.8G    59% /home
|-sda6 swap                    97399d72-dc57-4f90-a8c7-e9409582ccd9                [SWAP]
|-sda7 ext4     Backup         da05c9bb-d9f3-44dd-872d-ee106d971561   67.4G    44% /mnt/Backup
|-sda8 ext4                    093e80bf-e5f4-4b61-9f6c-26981b9710ab   29.9G    49% /
`-sda9 ext4     SwapPossible   115a401a-2c85-4b54-9d04-9a7051193249
sdb
|-sdb1 ntfs     PortableData   4E1AEA7B1AEA6007                       12.8G    98% /media/nikh/PortableData
`-sdb2 ext4     PortableBackup bcc13a36-eae7-4c36-a9b1-98e641d41fb4  256.8G    14% /media/nikh/PortableBackup1

My question is: Why sda9 and sdb2 starts with a backquote, while others starts with a pipe character? Does it have some special meaning?

A: It's just a layout-thing.
It makes it easier for the user to see that sda9 and sdb2 are the last ones in their respective lists.
Nothing to worry about.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facebook search with and without access_token I did this research (without access_token):
https://graph.facebook.com/search?q="il padrino"&type=page&fields=id,name
Among results I see the first one:
"id": "104130852958000",
"name": "Il padrino"
which is the most important page for "il padrino", as you can see when you search manually on Facebook.
Then I did this research (with an access_token with every permission):
https://graph.facebook.com/search?q=%22il%20padrino%22&type=page&fields=id,name&access_token=ACCESS_TOKEN
Among results someone disappeared and also the one before with id:104130852958000!!!
I tried this strange behavior with other strings different from "il padrino", but in many cases there is the same problem (or viceversa: some results disappear without the access_token).
How is it possible? How can I get a complete list of results?
Actually I think I have to join the research with and without access_token... but it seems strange.

A: That's annoying.  Please log it as a bug with Facebook:  https://developers.facebook.com/bugs and post a link to your report here too so others who find your question can see it's current bug.

A: No, this isn't possible. You cannot rely on what is being returned since it may and probably will. Trying to predict search results is just wrong, the results may (and really do) differ between users, geographical locations, content restrictions and probably other things too.
BTW, I'm not getting the page you speak about no matter using access_token or not.


text:
Q: Couldn't start client Clang Language Server in VS Code I just installed Visual Studio Code in my Windows 10 machine but I get the error "Couldn't start client Clang Language Server" ....
How can I solve this?
Regards,
Juan

A: This is likely because VS Code or an extension is trying to run clang and you do not have it installed or have not configured the path.
Start code from the command line with code --disable-extensions. Does the message still occur? If not, then one of your extensions is to blame. Find which one is related to C or C++ and read the documentation for it.

A: I found this thread when trying to solve this issue for Swift development on vscode. Yes disabling extensions will remove the error but here is the solution for Swift.
After building the Swift plugin for vscode you have to point it to the executable (which I neglected to do). To do this you have to add this JSON to your settings.json
"sourcekit-lsp.serverPath": "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/sourcekit-lsp"

For more information please see this article

A: Uninstalling my Java extensions and reinstalling them and clicking the correct prompts after installation, fixed the issue for me.

A: For Java developers who might encounter this kind of error this solution might work for you.
could you remove the georgewfraser.vscode-javac extension and install RedHat vscode-java - https://marketplace.visualstudio.com/items?itemName=redhat.java


text:
Q: UML class diagram reference: for group function of a webapp. (like facebook group) I am looking for some existing references of the UML class diagram that is model for "group function of a webapp system", like facebook group or meetup.com etc.
basically, creating groups, request joining groups, accept , reject, create events in the group, join events..etc.
I just want to see how ppl model that specific part of the web app (group functions), and see some common references of what would be a good way to model that!
I have hand draw a class diagram -
what I am trying to model is:

*

*User can join 0 to many groups

*Group can have 1 to many users

*Group has 0 to many events

*User can be invited to the event of their group, the user can accept / reject..etc.

*Group can send their event (activity) to other groups and they can also accept / reject .etc.

A: *

*Class diagrams are STRUCTURE diagrams. And you are talking about behaviour. It is extremely inconvenient to show behaviour in class diagrams. Start from use cases and go to activity diagrams.

*UML is a language set, supporting modelling. Not modelling in some specific language, let alone programming language or specific framework. I sometimes use class diagrams for modelling UI design or user guides. UML diagrams look the same, no regard to use of facebook.

*Facebook programming is a use of a framework, supporting creation some kinds of IS, with some ready functionalities. If you want to make a class diagram supporting such modelling, simply use the facebook classes as ready ones and derive your classes from them.

Edit.
As reaction to your diagram (please, put its reference into the question):

*

*Two-sided shared aggregation is forbidden in UML standard. I see, it HAS sense, but you must write it as two connections.

*Group-event connection has diamond on the wrong end.

*Group or User or both should have invite method

*What user can do is to be set in use case or state diagram, not in class diagram.  The same for your rule 5

Again - you should start from UC diagram or state diagram.

A: I can't access your drawing, so i can't see what you have done.
As a starting point, this shows the entities, relationships and cardinalities.

I have not included a relationship between user and event, because this is implicit through group. You may or may not want to visually draw in that relationship.
This only shows the static structure of the system and does not show the dynamic aspects.


text:
Q: Dynamically load specific User Control from postback I have a menu on a .aspx page, which will load a specific user control depending on which menu option is clicked.  This part is working fine.
The problem I'm running into is when I instantiate a post back from the dynamically loaded user control, the .aspx page is reloaded.  Now after researching a few of the other questions on here, I gathered that I have to recreate the User Control each time the post back is instantiated.  However, the question I have might be quite simple, but how do I reload the specific User Control (and fire an event such as OnClick) based on what is posted back to the server?
So my question is:  What exactly gets passed back to the server on post back, and is there something in the post back request that will allow me to load the specific control?  If there is, how would I get to it?

A: To do it the manual way, you would have to recreate the control(s) before ViewState is reloaded, like during OnInit for example.
There is a control called the DynamicControlsPlaceHolder that takes care of persisting dynamic controls for you. It's a definite time saver, and it makes persisting dynamic content easy.
Here is a link to the control:
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
To better understand what postbacks do, you need to understand the ASP.NET page lifecycle. Here is an MSDN article that explains it in detail:
http://msdn.microsoft.com/en-us/library/ms178472.aspx


text:
Q: Sessions not holding on AppFog / Laravel 3 Im not sure what could be causing this,
But my project has been working fine in development.
But when I uploaded it to AppFog, suddenly my sessions/Auth() wont hold.
Authentication works to login.
So a user can login, and will be redirected to their profile page...
and from there they can update stuff...
So Auth() is obviously holding their session, but wierdly when they click anywhere else on the site, away from their profile.....suddenly their session is lost.
And they have to re-login again if they want to navigate back to their profile.
Why would this happen in production but not development.
The codebase is exactly the same.
Only difference is im using Local/Production database settings, thats it.
Other than that everything else is exactly the same.
Any idea what could be causing this??
Normally I would check php.ini and such, but on appfog, I doubt you can access any of the deep admin stuff.
Should I just switch from session based auth, to Redis/Database auth??? Anybody else come across this problem on AppFog, with Laravel, or YII?
UPDATE
Switching from default, to database session storage produced a strange error, of multiple entries per login.  Which of course makes the Auth()attempt fail.   I fixed this, by removing auto_increment on the id column of the sessions table.  This fixed my one app....that was working before on the default settings.
The other app in question still does not work.  It at least is now only making 1 entry in the session table on login attempt, but for some reason it isnt creating a login cookie to cross reference with that table.
In Chrome Console, under resources on the working app I have...
laravel_session -> 6
Which is referring to the id 6 in the session table, hence why it works.
In the non-working app however.....I have
laravel_session - >  41g1D4390Sd223s etc etc
Which as far as I can tell, isn't referring to anything....
Any insight on this???

A: This could be because AppFog is a cloud based service without persistent data storage. By default, Laravel uses disk storage for it's sessions. Switch to storing your sessions in the database and they should be maintained correctly.

A: i had similiar problem with both laravel3 and laravel4.
The workaround (though not recommended) is,
use Session::save() manually after putting anything in the Session.
e.g.
Session::put('foo','bar');
Session::save();

As i found it, sometimes laravel fails to call Session::save() and does not throw any exceptions or errors.


text:
Q: Android in-app-purchase valid order but not exist in Google play store I have an application published in Google play store, its name is PainterSVG, main purpose is to help SVG designers to create/edit SVG vector images.
One item in the app is designed as paid feature (use downloaded fonts), so user needs to pay with Google in-app-purchase to buy it. I designed all in-app-purchase codes and tested successfully.
One week ago, there was a sudden burst of purchases in a very short time, from the same user. The purchases' state all became Purchase.PurchaseState.PURCHASED. The raw data in jason and the signature are all verified with my application's public key.
But in Google play store, there are no information on these purchases, they simply does not exist, and of course I have no income.
Here is one example purchase I logged:
Raw data:
{"orderId":"1788684269051654849.8163737331748355","packageName":"p.svg","productId":"paintersvg_point_100","purchaseTime":1622106599816,"purchaseState":0,"purchaseToken":"kslypocwqdttgxzhetcdskic.AO-J1OXwNhKHOWYKxGAGFZvXgslNtkhqCrpQBaxvFSzgcuE-ZLLKCev_hpKJTGlFEFCsXkWuJOXswCzOvadVljYnHiJkIygNoxawFQPaKePZppvbRZZUNToExOfEycRjxTsulwPClSAi"}
Signature:
bVYGfzqbt6uWKnmw5xSW5tQek+tSwP0GgUKXz6fNXBCmGEedUrffpKPOXaG2RyfVtYvICThcxumD7kVWNSVxvE9DBJrVDjo+ipTPB9hkYebVQKib1LMBFbSMTpaA9Av2ioP+T/pBQt2EuvRLKUpnZaz5C/2uX7OvOcJtjwYniH/I7oRHvNRBxD6R78Tp6DNySotp41XUwDPmeebC6A38PVM5MhtaY9czWNaa3j3OG7rPAp0j2V5nWsdmmahu8HqBxTyqWdfmf83m3oaHrTvH7vATaKJPMcXdm1aavYAsyHCPzhFGeglU7/KRgUCkzyZ8edcA81F/x9hUVC2QL+cdXw==
The raw data and signature can be verified correct for my application, with my app's public key. Raw data and signature will be logged only when purchase state is PURCHASED. And all order ids are different.
I have no idea what is happening here -- where are the orders from and what was happening? Did the user actually paid? and paid a lot of times? Should I refund him? Can anyone help me?
Thanks a lot!

A: What you're seeing are fraud attempts
I won't put links here, but on Android a malicious user can patch the Play Store application in order to bypass In-App Purchase. So when the user tries to buy something, a fake (but valid) receipt is returned to your app which thinks it's a valid one by default.
Fortunately, you don't trust the receipt as it is and you verify it by calling the Google APIs, which doesn't know the receipt.
Example of fraud attempt
Here is an example we've seen recently at Purchasely (we manage In-App Purchases for apps, so we see this kind of thing A LOT):

All these fraud attempts were made by the same user.
As you can see:

*

*they make different attempts in a short laps of time

*the receipt returned is generated randomly: the prices are incorrect. And worse, the monthly price sent ($1400) is greater than the yearly one ($500), which doesn't make any sense ^^'

Conclusion
Don't worry :)


text:
Q: CSS positioning at the bottom Is it somehow possible to have a DIV container always positioned at the end of a page and if the page content is not filling up the window to the bottom, the DIV is fixed at the window bottom?
See the following JSFiddle: http://jsfiddle.net/r4g98muw/
The bottom of the ".bottom" div is not allowed to move higher than the bottom of the window. With Javascript I could give the ".bottom"-DIV postion:fixed; bottom:0; if I have just a little text and if I have lots of text I could remove that.
Is there a trick without Javascript?

.bottom {
    background: yellow;
}

  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

    bottom

A: try this,

  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

    bottom

.main{
   min-height:600px;
   position:relative;
}
.bottom {
    background: yellow;
    position: absolute;
    width: 100%;
    bottom: 0;
}


text:
Q: Identifying comments from the same source What ideas can I try to find out if comments are from the same users. The assumption is that people will try to cheat and post comments under multiple pseudonyms. My environment is PHP and I can install any third party library as needed. What should I do to minimize this risk and identify comments posted by the same source (as much as possible).

A: You can identify the user by logging the IP address upon the users first comment, then checking to see if that IP address exists in the database on any subsequent comments. However, this data can be spoofed so it isn't fail-safe.

A: The only way you can realistically do this is to enforce a user login for comments, as IP addresses aren't sufficiently unique and cookies are trivial to erase at the client end.
That said, there is of course nothing to stop people creating multiple users accounts with a variety of email addresses (gmail/Yahoo, etc.) so you'll want to create your own tools/admin view so you can trivially check IP addresses if you suspect people are still misbehaving. (A tool for your armoury if nothing else.)  On a similar basis, you could also log the browser agent header.


text:
Q: How to Remove open bracket from JSON Response I have one json string like below.
oncomptetion({
  "competition": [
  {
      "CompetitionID": "7b47afgwi2017odi",
      "CompetitionName": "AFGHANISTAN IN WESTINDIES ODI SERIES 2017",
      "DivisionID": "1",
      "DivisionName": "1 Division",
      "MappingCompName": "",
      "CompetitionType": "One Day Match"
    },
    {
      "CompetitionID": "7b4785be057b448f",
      "CompetitionName": "AFGHANISTAN IN WESTINDIES T20I SERIES 2017",
      "DivisionID": "1",
      "DivisionName": "1 Division",
      "MappingCompName": "",
      "CompetitionType": "T20 Match"
    }]
})

I want to delete/remove the first and last open brackets and Including oncomptetion this name from string.
Please help me

A: Try this to get valid Json
    String json="your Srting"; //unformatted string

    String output = json.replace("oncomptetion(", ""); //removing  oncomptetion(
    String finalJson=  output.substring(0, output.length() - 1);   //removing last string )

    System.out.println(""+finalJson);

output :
    {  "competition": [
      {
          "CompetitionID": "7b47afgwi2017odi",
          "CompetitionName": "AFGHANISTAN IN WESTINDIES ODI SERIES 2017",
          "DivisionID": "1",
          "DivisionName": "1 Division",
          "MappingCompName": "",
          "CompetitionType": "One Day Match"
        },
        {
          "CompetitionID": "7b4785be057b448f",
          "CompetitionName": "AFGHANISTAN IN WESTINDIES T20I SERIES 2017",
          "DivisionID": "1",
          "DivisionName": "1 Division",
          "MappingCompName": "",
          "CompetitionType": "T20 Match"
        }]
    }


text:
Q: Adding emphasis (italics) to a word in a chapter title LyX I have a chapter title which contains a word which needs to be in italics. LyX allows me to add emphasis to it in the LyX window (with Ctrl+E) and it appears italicized in the LyX window. However, in both the table of contents and the chapter itself the word is not in italics. This seems odd because figure and table labels do appear in their respective lists with proper emphasis. Thanks!

A: Turns out the font I had used "AE (Almost European)" was causing the issue. It must not have both bold and italic fonts.
Changing it to Default (or other fonts) fixed this problem.


text:
Q: Image scaling inside div fails - background not following I am currently trying to fit an image into a div container, but it doesnt work. I have got a  complex div-tree on my page, that looks like this:

And the following CSS:
#a {
    height: 300px;
    background-color: red;
    position: relative;
    text-align: center;
}

#b {
    height: 100%;
    width: 100%;
    background-color: blue;
    position: absolute;
    top: 0;
    left: 0;
    text-align: center;
    padding: 20px;
}

#c {
    width: auto;
    height: auto;
    display: inline-block;
    max-height: 100%;
    background-color: black;
    padding: 20px;
}

#d {
    width: 400px;
    background-color:yellow;
    max-height: inherit;
}

img {
    max-width: 100%;
    opacity: 0.7;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    height: calc(100% - 80px);
    margin: auto;
}

I want the image to be fitted into the blue container. It should also take care on the given div containers. Currently the black one does not fill till the end plus padding of the container.
Demo Fiddle
I hope someone is able to help.

A: Here is a new concept for you. box-sizing: border-box incorporates the padding into the percentage width and heights automatically. The image no longer needs position: absolute.
The width and height of all the inner divs are controlled by the width on the #a container and their padding.
New Demo

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
#a {
  background-color: red;
  position: relative;
  text-align: center;
  width: 400px;
  padding: 20px;
}
#b {
  background: blue;
  padding: 20px;
}
#c {
  background-color: black;
  padding: 20px;
}
#d {
  background-color: yellow;
  padding: 20px;
}
img {
 width: 100%;
 display: block; /* remove inline gap */
}

Old Answer

*

*Remove width: auto; height: auto; and padding: 20px on #c

*Place height: 100% on #c
Reason this happens - The height: 100% of #c is affected by the padding on #b so any extra padding will blow up the height.
Demo

#a {
    height: 300px;
    background-color: red;
    position: relative;
    text-align: center;
}

#b {
    height: 100%;
    width: 100%;
    background-color: blue;
    position: absolute;
    top: 0;
    left: 0;
    text-align: center;
    padding: 20px;
}

#c {
    height: 100%;
    display: inline-block;
    background-color: black;
}

#d {
    width: 400px;
    background-color:yellow;
    max-height: 100%;
}

img {
    max-width: 100%;
    opacity: 0.7;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    height: calc(100% - 80px);
    margin: auto;
}

A: Here And try giving " #d" a height
#d > img {
width: 100%;
height: 100%;
text-align:center;
}


text:
Q: Como sacar una tupla de un JSON de acuerdo a una posición especifica en python? Eso pues, tengo este mensaje en JSON:
mensaje = {"13":"17.800","14":"75.000","15":"13.300","16":"17.800","17":"21.200","18":"58.000","19":"12.600","20":"765.600","21":"1038.400","22":"0.900","23":"1.300","24":"152.000","25":"152.000","26":"0.000","27":"72.000","28":"0.700","29":"127.000","30":"3.404","31":"17.800"}

Quiero obtener una tupla del mensaje, por ejemplo la primera, que saldría esto: "13:"17.800"
En pocas palabras, sería mensaje[0]si mensaje fuese una lista

A: Buen día, para acceder a ese datos escribe list(mensaje.items())[0], te devuelve una tuple:
type(list(mensaje.items())[0])
-> tuple

print(list(mensaje.items())[0])
-> ('13', '17.800')

A: Hay un problema inicial, lo que tienes serializado en un JSON es básicamente un diccionario y estos, dependiendo de la versión de Python, no siempre hay garantía de orden en os elementos, por que de hecho, el orden en sí no es algo fundamental para un diccionario. Si mal no recuerdo, desde la versión 3.6 ya podemos confiar en el orden de un diccionario, por lo que fácilmente podrías hacer algo así:
import json

d = json.loads(mensaje)
k, v = list(d.items())[0]
print('El primer elemento {0} tiene un valor de {1}'.format(k, v))

El primer elemento 13 tiene un valor de 17.800

En caso que estuviera con una versión anterior, podrías apoyarte en un OrderedDict:
from collections import OrderedDict
d = json.loads(mensaje, object_pairs_hook=OrderedDict)


text:
Q: JFrame appears blank instead of showing UI I want to open MainWindow (that I created and added UI) after some time but Java opens blank default Jframe instead. How can I open already created window after splashscreen (Start)?
public class Start extends JFrame{
        private JPanel panel1;

        public static void main(String[] args) {

            JFrame frame = new JFrame("Starting");
            frame.setContentPane(new Start().panel1);
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

            frame.setExtendedState(JFrame.NORMAL);
            frame.setUndecorated(true);
            //frame.setAlwaysOnTop(true);
            frame.setVisible(true);

            /*Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);*/

            frame.toFront();
            frame.pack();

            frame.setLocationRelativeTo(null);

            Timer timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                    new MainWindows().setVisible(true);
                    frame.setVisible(false);

                    //System.exit(0);
                }
            });

            timer.start();

        }

MainWindows.java
public class MainWindows extends JFrame{

    private JPanel panel;

    public static void main(String[] args)
    {

        boolean clicked = false;

        JOptionPane.showConfirmDialog(null, "Це перша вершія гри. Будь ласка, закрийте всі програми, щоб уникнути помилок.", "Увага!", JOptionPane.YES_OPTION);

        JFrame frame2 = new JFrame("Flying");
        frame2.setContentPane(new MainWindows().panel);
        frame2.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        frame2.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame2.setUndecorated(true);
        frame2.setAlwaysOnTop(true);
        frame2.setVisible(true);

        frame2.toFront();
        frame2.pack();

A: Your MainWindow class has a static main method that's never invoked. It looks a lot like the code in there should have gone intoa constructor instead.

A: You seem to have two main methods in this program. I would suggest removing the main method from MainWindows.java and move the code from it into the MainWindows constructor. This will ensure that when you initialize the new MainWindows() object, everything in the new JFrame should be set up correctly.
Code in MainWindows.java:
    public MainWindows()
{

    boolean clicked = false;

    JOptionPane.showConfirmDialog(null, "Це перша вершія гри. Будь ласка, закрийте всі програми, щоб уникнути помилок.", "Увага!", JOptionPane.YES_OPTION);

    JFrame frame2 = new JFrame("Flying");
    frame2.setContentPane(new MainWindows().panel);
    frame2.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    frame2.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame2.setUndecorated(true);
    frame2.setAlwaysOnTop(true);
    frame2.setVisible(true);

    frame2.toFront();
    frame2.pack();

A: I finally fixed it. frame2.setContentPane(panel); Thank you for all your answers!


text:
Q: AngularJS Bound Ng-Model Inside Directive Has Wrong Attribute Name This is a followup to a previous question. I have some questions on the rendering of a custom directive and the actual output in the DOM when the page is rendered.
Here is the definition of my directive:
angular.module('moduleName)
    .directive('selectValue', ['$timeout', function($timeout) {

    const directive = {
        restrict: 'E',
        replace: true,
        scope: {
            controlId: '@',
            model: '=?'
        },
        controller: 'selectValueCtrl',
        templateUrl: 'template.html'

    };

    return directive;
}

Here is the externalized template:
<!-- template.html -->
<input id="{{controlId}}" name="{{controlId}}" placeholder="Enter Value"
       type="text" ng-model="model" />

Given the following use of the directive:
<select-value controlId="selectValue" model="data.value"></selectValue>

Why does it render as the following:
<input id="selectValue" ng-model="model" />

Instead of:
<input id="selectValue" ng-model="data.value" />

Did I make a mistake in my code, or is this expected behavior?

A: {{controlId}} - this is an interpolation and Angular should calculate the expression behind the braces. That's why you get id="selectValue" instead of id="{{controlId}}"
ng-model="model" it's just a two-way binding which is handled by Angular under the hood, but Angular doesn't change the template in this case. Angular should know what model is binded, values are transferred behind the scenes.


text:
Q: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "Agent.onGuiEvent(jade.gui.GuiEvent)" because "the Agent" is null hello so I am trying to do a simulation using these two: jade Framework and cloudsim ToolKit
I am having this problem right here
what I am trying to do here is to get parameters to form the interface and then create my objects in this agent , then send them to another agent in ACLMessage which is another problem for me when it requires making the object I am trying to send( serialized ) please how can i do that i've got only 10 days left to give this project to my professor and this are not going well as u can see
    Agent container Container-3@192.168.0.145 is ready.
--------------------------------------------
************************************************
Agent initialisation ......
Agent :   AgentCME@192.168.0.145:1099/JADE is alive!
************************************************
Initialize the GridSim library
Starting The Interface
Interface Launched
************************************************
Starting SMA CME ...
Initialising...
Creating Cloud
data centre and broker created
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "Agent.AgentCME.onGuiEvent(jade.gui.GuiEvent)" because "this.ACME" is null
    at IHM.Configuration.jButton6ActionPerformed(Configuration.java:1099)
    at IHM.Configuration$10.actionPerformed(Configuration.java:543)

my agent class is here :
/**
 *
 * @author pc
 */
public class AgentCME extends GuiAgent {

    // ref a l'interface graphique
        transient protected StartingPage myGui ;
        transient protected Configuration Conf;
  @Override
    protected void setup() {
        if(getArguments().length==1){
           Conf=(Configuration) getArguments()[0];
           Conf.setACME(this);
       }
       System.out.println("************************************************");
       System.out.println("Agent initialisation ......   ");
       System.out.println("Agent :   "+this.getAID().getName() + " is alive!");
       System.out.println("************************************************");
       System.out.println("Initialize the GridSim library");
       System.out.println("Starting The Interface");
       myGui = new StartingPage(this);
       myGui.setSize(1024, 600);
       myGui.setVisible(true);
       Conf = new Configuration(this);
       System.out.println("Interface Launched");
       System.out.println("************************************************");
       Log.printLine("Starting SMA CME ...");
       CloudSim.init(1, Calendar.getInstance(), false);
       // creating datacenters
       Log.printLine("Creting Cloud");
      datacenter0 = createDatacenter("DataCenter_0");
      DatacenterBroker broker = createBroker("broker");
            int brokerId = broker.getId();
                         Log.printLine("data centre and broker created");

        }

     @Override
    @SuppressWarnings("empty-statement")
    public void onGuiEvent(GuiEvent params) {

    if (params.getType() == 3)
    {
            System.out.println("***************get Cloudlets configuration******************");
            int cloudletsnmbr=(int) params.getParameter(0);
            int length=(int) params.getParameter(1);
            int fileSize=(int) params.getParameter(2);
            int outputSize=(int) params.getParameter(3);
            System.out.println("***params :"+cloudletsnmbr+"****"+length+"****"+fileSize+"****"+outputSize+"****");
            System.out.println("***************Creating Cloudlet******************");
            UtilizationModel utilizationModel = new UtilizationModelFull();
            System.out.println("test");
            Cloudlet cloudlet =
                                new Cloudlet(cloudletsnmbr, length,1, fileSize,
                                        outputSize, utilizationModel, utilizationModel,
                                        utilizationModel);
           cloudletList =   createCloudlet(broker.getId(),cloudletsnmbr);
          System.out.println(cloudletList);
    }

    else if (params.getType() == 2)

    {

            System.out.println("***************get VM configuration******************");
            int NmbrVm=(int) params.getParameter(0);
            int RamVm=(int) params.getParameter(1);
            int StorageVm=(int) params.getParameter(2);
            int BwVm=(int) params.getParameter(3);
            int MipsVm=(int) params.getParameter(4);
            System.out.println("***************Creating VM list******************");
            Vm vm = new Vm(NmbrVm,1, MipsVm,1, RamVm, BwVm, StorageVm, "Xen", new CloudletSchedulerTimeShared());
             vmlist = createVM(broker.getId(), NmbrVm);
             System.out.println(vmlist);

    }else if (params.getType() == 1)

    {
     broker.submitVmList(vmlist);
        broker.submitCloudletList(cloudletList);
        CloudSim.startSimulation();
        List<Cloudlet> newList = broker.getCloudletReceivedList();
        CloudSim.stopSimulation();
        printCloudletList(newList);
    }

 }
 ........

the interface code here :
protected AgentCME ACME ;
public Configuration ( Agent.AgentCME ui){
initComponents();
ACME = ui ;
}

 private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
        //getting data frome interface...
        StorageVm = Integer.parseInt(StorageVM.getText());
        MipsVm = Integer.parseInt(MipsVM.getText());
        NmbrVm = Integer.parseInt(NmbrVM.getText());
        RamVm = Integer.parseInt(RamVM.getText());
        BwVm  = Integer.parseInt(BwVM.getText());
        /*AgentCME.Setcloudlets(StorageVm);
        AgentCME.Setcloudlets(MipsVm);
        AgentCME.Setcloudlets(NmbrVm);
        AgentCME.Setcloudlets(RamVm);
        AgentCME.Setcloudlets(BwVm);*/
        DefaultTableModel tblModel = (DefaultTableModel)VmTable.getModel();

        for (int i = 0;i<NmbrVm;i++){
            String data []= {"VM"+i,RamVM.getText(),StorageVM.getText(),BwVM.getText(),MipsVM.getText()};
            tblModel.addRow(data);
        }

        GuiEvent event = new GuiEvent(this,2);
        event.addParameter(NmbrVm);
        event.addParameter(RamVm);
        event.addParameter(StorageVm);
        event.addParameter(BwVm);
        event.addParameter(MipsVm);
        ACME.onGuiEvent(event);
    }


text:
Q: OR clause with subquery taking too much time Date Range query taking too much time.
Just i removed the one condition then it working fine taking 2 second. If adding
then 30 seconds.
SELECT UserName,COUNT ('t') TOTAL
FROM TRANSACTIONS E1
WHERE E1.START_DATE BETWEEN TO_DATE ('20130101', 'YYYYMMDD') AND TO_DATE ('20140101', 'YYYYMMDD')
AND
(
    TO_CHAR (E1.START_DATE, 'D') in ( 7)
    OR Exists(SELECT 1 FROM HOLIDAYS TT
    WHERE E1.START_DATE BETWEEN TT.DATE_FROM AND TT.DATE_TO )
)
AND EXISTS (SELECT 't' FROM TRANSACTIONS_ORG E2 WHERE E1.TRANTYPE = E2.tran_type)
GROUP BY UserName;

HOLIDAYS table
Id  FromDate    ToDate  Description
1   1-Feb-11    3-Feb-11    Maintance
3   2-Sep-09    5-Sep-09    Eid Holiday Fine Block
4   3-Dec-09    4-Dec-09    Due to System Problem
5   4-Dec-07    04-Dec-07   National Day

EIDTED
I figured out that the issue is not in the date range. but the OR clause in the
TO_CHAR (E1.START_DATE, 'D') in ( 5,6)
OR
Exists(SELECT 1 FROM HOLIDAYS TT
WHERE E1.START_DATE BETWEEN TT.DATE_FROM AND TT.DATE_TO )

if removed OR and put AND then fine and if shuffle conditions with OR still same issue.

A: The problem is likely with the OR <subquery> construct.
If there can only be one holiday for a particular date, then you could use the following:
select username
      ,count(*)
  from transactions  e1
  left join holidays tt on(e1.start_date between tt.date_from and tt.date_to)
 where e1.start_date between date '2017-02-01' and date '2018-02-01'
   and (   to_char(e1.start_date, 'D') in(5, 6)
        or tt.date_from is not null)
       )
   and exists(
      select *
        from transactions_org e2
       where e1.trantype = e2.tran_type
   )
 group
    by username;

This entire category of problems can be solved by implementing a Calendar table. If you had such a table with one record per date, you could easily add columns indicating day of week and holiday flags and such. If your calendar table looked something like this:
DAY        DAYNAME   IS_WEEKEND IS_WEEKDAY HOLINAME
---------- --------- ---------- ---------- ------------
2017-02-01 WEDNESDAY          0          1
2017-02-02 THURSDAY           0          1
2017-02-03 FRIDAY             0          1 Some holiday
2017-02-04 SATURDAY           1          0
2017-02-05 SUNDAY             1          0
2017-02-06 MONDAY             0          1
2017-02-07 TUESDAY            0          1
2017-02-08 WEDNESDAY          0          1

Your query could be rewritten as:
  from transactions  e1
  join calendar      c on(c.day = trunc(e1.start_date, 'DD')) -- Remove hours, minutes
 where e1.start_date between date '2017-02-01' and date '2018-02-01'
   and (   c.weekday in('THURSDAY', 'FRIDAY') -- Either specific weekdays
        or c.holiname is not null             -- or there is a holiday
       )
   and exists(
      select *
        from transactions_org e2
       where e1.trantype = e2.tran_type
   )


text:
Q: Making way for continuations from an apparent limitation of python reduce Let us consider a list with numbers like the following :
a_lst = [1,2,3,2,3,4,5,6,2,2]

Now I need to write a program in python  which counts the number of occurrences of let's say "2" using only "reduce" .
I went through the following question as well :
using Python reduce Count the number of occurrence of character in string
It has got a great answer , however I wanted to see if there is any way where
I could replace the "if" condition inside the lambda function with  like (x == 2) . I mean getting the same thing done by not using the "if"condition explicitly .
I thought of reaching up to  a solution  by passing a  lambda function,which takes another lambda function  as an argument to the reduce function .
But it turned out to be just a day-dream and nothing else as after passing a lambda function as an argument ,  calling it inside the outer lambda function body will defeat the purpose of making it a lambda function .
One more fiasco was about wishing for a construct where a lambda function could call itself at the end of its body . (I understand the above line sounds completely meaningless , but what I meant a construct which had  the equivalent power of a lambda calling itself )
I have been through the concept of continuation passing style ,where in pythonic terms , a  function returns a lambda function which takes the arguments that the function had received .But I am not sure if by definition of continuation is technically accurate . Can it be brought to use to solve this problem ?

A: Theres nothing stopping you from writing

the lambda function with like (x == 2)

from functools import reduce
a_lst = [1,2,3,2,3,4,5,6,2,2]
reduce(lambda x, y: x + (y == 2), a_lst, 0) #Output: 4

The reason this works is because bool is a subclass of int in python, and can be used for mathematical operations.
If that alone however does not satisfy you, you can get really involved with the operator and functools modules. Reference docs.
from functools import reduce, partial
import operator
reduce(operator.add,map(lambda x: operator.eq(x, 2), a_lst), 0) #Output: 4

and, replace the lambda with a partial function
equals_2 = partial(operator.eq, 2)
reduce(operator.add,map(equals_2, a_lst), 0) #Output: 4

A Word of caution
It may not be wise to get stuck with one paradigm of programming (functional) in this case. Python excels in allowing any programming paradigm, but practically beats purity. It is just much simpler and easier to iterate through the list and count the number of 2s yourself, using the .count method. No need to reinvent the wheel where it doesn't make sense. To future readers, this is just a demonstration, not a recommendation on how to count occurrences in a list.


text:
Q: KeyError: 'Close', I think I deleted a key for my dictionary! Algo Trading When I run the first two functions, CARG and Volatility, they work fine! When I run Sharpe, it runs into problems! I think I deleted a key in my dictionary somehow, it refers back to my CAGR function and point to the second line in there, saying KeyError: 'Close'. The return error info is at the very bottom
import yfinance as yf
import numpy as np
import pandas as pd

tickers = ["AAPL","AMC","SPY","BBBY"]

ohlcv_data = {}

for ticker in tickers:

temp = yf.download(ticker, period="7mo", interval="1d")
temp.dropna(how="any", inplace=True)
ohlcv_data[ticker] = temp

def CAGR(DF):

    df = DF.copy()
    df["return"] = DF["Close"].pct_change()
    df["cum_return"] = (1+df["return"]).cumprod()
    n = len(df)/252
    CAGR = (df["cum_return"][-1])**(1/n) - 1

    return CAGR

for ticker in ohlcv_data:
    print("GAGR for {} = {}".format(ticker, CAGR(ohlcv_data[ticker])))

def Volatility(DF):

    df = DF.copy()
    df["return"] = DF["Close"].pct_change()
    vol = df["return"].std() * np.sqrt(252)

    return vol

for ticker in ohlcv_data:
    print("Volatility of {} = {}".format(ticker, Volatility(ohlcv_data[ticker])))

def Sharpe(DF, rf=0.03):

    df = DF.copy()
    return (CAGR(df)- rf)/Volatility(df)

for ticker in ohlcv_data:
    print("Sharpe for {} = {}".format(ticker, Sharpe(ohlcv_data, 0.03)))

def Sortino(DF, rf=0.03):

    df= DF.copy()
    df["return"] = df["Close"].pct_change()
    neg_return = np.where(df["return"]>0,0,df["return"])
    neg_vol = pd.Series(neg_return[neg_return!=0]).std()

    return (CAGR(df)- rf)/neg_vol

for ticker in ohlcv_data:
    print("Sortino for {} = {}".format(ticker, Sortino(ohlcv_data, 0.03)))

File "c:\users\cryst\onedrive\documents\algotradingcode\untitled11.py", line 56, in <module>
print("Sharpe for {} = {}".format(ticker, Sharpe(ohlcv_data, 0.03)))

File "c:\users\cryst\onedrive\documents\algotradingcode\untitled11.py", line 53, in Sharpe
return (CAGR(df)- rf)/Volatility(df)

File "c:\users\cryst\onedrive\documents\algotradingcode\untitled11.py", line 26, in CAGR
df["return"] = DF["Close"].pct_change()

KeyError: 'Close'

A: I see the same mistake when you run Sharpe() and Sortino()
You send ohlcv_data but you have to send ohlcv_data[ticker]
Funny is you have it correctly when you run CAGR() and Volatility()
    Sharpe(ohlcv_data[ticker], 0.03)

    Sortino(ohlcv_data[ticker], 0.03)

    CAGR(ohlcv_data[ticker])

    Volatility(ohlcv_data[ticker])

Eventually you should use .items() to make it more readable
for ticker, data in ohlcv_data.items():
    result = Sharpe(data, 0.03)
    # result = Sortino(data, 0.03)
    # result = CAGR(data)
    # result = Volatility(data)

Full working code with:
import yfinance as yf
import numpy as np
import pandas as pd

# --- functions ---  # PEP8: all functions before main code

def CAGR(DF):

    df = DF.copy()

    df["return"] = df["Close"].pct_change()
    df["cum_return"] = (1+df["return"]).cumprod()
    n = len(df)/252
    CAGR = (df["cum_return"][-1])**(1/n) - 1

    return CAGR

def Volatility(DF):

    df = DF.copy()

    df["return"] = df["Close"].pct_change()
    vol = df["return"].std() * np.sqrt(252)

    return vol

def Sharpe(DF, rf=0.03):

    df = DF.copy()

    return (CAGR(df)- rf)/Volatility(df)

def Sortino(DF, rf=0.03):

    df = DF.copy()

    df["return"] = df["Close"].pct_change()
    neg_return = np.where(df["return"]>0,0,df["return"])
    neg_vol = pd.Series(neg_return[neg_return!=0]).std()

    return (CAGR(df)- rf)/neg_vol

# --- main ---

tickers = ["AAPL","AMC","SPY","BBBY"]

ohlcv_data = {}

for ticker in tickers:
    data = yf.download(ticker, period="7mo", interval="1d")
    data.dropna(how="any", inplace=True)
    ohlcv_data[ticker] = data

for ticker, data in ohlcv_data.items():
    result = CAGR(data)
    print(f"GAGR for {ticker} = {result}")

for ticker, data in ohlcv_data.items():
    result = Volatility(data)
    print(f"Volatility of {ticker} = {result}")

for ticker, data in ohlcv_data.items():
    result = Sharpe(data, 0.03)
    print(f"Sharpe for {ticker} = {result}")

for ticker, data in ohlcv_data.items():
    result = Sortino(data, 0.03)
    print(f"Sortino for {ticker} = {result}")

Result:
GAGR for AAPL = 0.11355213703707379
GAGR for AMC = -0.5829820257957625
GAGR for SPY = -0.05423536518372174
GAGR for BBBY = -0.4389927079102395
Volatility of AAPL = 0.3471946896720913
Volatility of AMC = 1.3227122428032356
Volatility of SPY = 0.24545485475277398
Volatility of BBBY = 1.5613839405009773
Sharpe for AAPL = 0.24064923664582766
Sharpe for AMC = -0.4634281032257359
Sharpe for SPY = -0.3431806849718452
Sharpe for BBBY = -0.30036988068403025
Sortino for AAPL = 5.847323456223871
Sortino for AMC = -11.478142948375877
Sortino for SPY = -8.132265719790464
Sortino for BBBY = -7.791889967534535

PEP 8 -- Style Guide for Python Code


text:
Q: How can I get the complete definition (sql) of system views like user_objects? I want to get the complete SQL code of the system views like USER_OBJECTS. However, when I execute the query below, it returns an error saying view not found in the SYS schema.
select dbms_metadata.get_ddl('VIEW', 'USER_OBJECTS', 'SYS') from dual;

When I execute the query below, it returns some codes in the text_vc column, but not the complete one. I cannot see the tables and where clause etc.
select * from ALL_VIEWS where VIEW_NAME  = 'USER_OBJECTS';

But with this query, I can see that it is in the SYS schema with that name.
So, what is the reason that I cannot see the whole query? And is there a way to see it all?

A: +1 for looking at the definitions of the system views!
The first problem (DBMS_METADATA empty) is a privilege problem. According to the documentation, normal users will see only their own objects. You'll need the role SELECT_CATALOG_ROLE or EXP_FULL_DATABASE to see other users objects.
The second problem (SQL is not complete) comes from the datatype LONG, which - according to Oracle - should not be used anymore. However, it is still used by Oracle for view definitions, defaults, constraint text etc. Because it is so hard to handle, the view ALL_VIEWS has the original text in the LONG column and a truncated text, mostly the first 4000 characters, in the column text_vc, presumably for "text in varchar".
EDIT:
I believe you use Oracle 12 as you mention the column text_vc, which is not available in Oracle 11. Presumably, you are using a containerized database. If so, then please have a look at Data Dictionary Architecture in a CDB. Apparently, the definition of Oracle supplied things like views and packages are only visible in the root container. Sigh!!

A: In SQL*Plus, you'd set long (I shortened the output):
SQL> set pagesize 0
SQL> set long 10000
SQL>
SQL> select text from all_views where view_name = 'USER_OBJECTS';
select o.name, o.subname, o.obj#, o.dataobj#,
       decode(o.type#, 0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER',
                      4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE',
                      7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE',
                      11, 'PACKAGE BODY', 12, 'TRIGGER',
<snip>
from sys."_CURRENT_EDITION_OBJ" o
where o.owner# = userenv('SCHEMAID')
  and o.linkname is null
  and (o.type# not in (1  /* INDEX - handled below */,
                      10 /* NON-EXISTENT */)
       or
<snip>
union all
select l.name, NULL, to_number(null), to_number(null),
       'DATABASE LINK',
       l.ctime, to_date(null), NULL, 'VALID', 'N', 'N', 'N', NULL, NULL
from sys.link$ l
where l.owner# = userenv('SCHEMAID')

SQL>

Also, your first query works in my database (11g XE) if I'm connected as SYS:
SQL> show user
USER is "SYS"
SQL> select dbms_metadata.get_ddl('VIEW', 'USER_OBJECTS', 'SYS') from dual;

DBMS_METADATA.GET_DDL('VIEW','USER_OBJECTS','SYS')
--------------------------------------------------------------------------------

  CREATE OR REPLACE FORCE VIEW "SYS"."USER_OBJECTS" ("OBJECT_NAME", "SUBOBJECT_N
AME", "OBJECT_ID", "DATA_OBJECT_ID", "OBJECT_TYPE", "CREATED", "LAST_DDL_TIME",
"TIMESTAMP", "STATUS", "TEMPORARY", "GENERATED", "SECONDARY", "NAMESPACE", "EDIT
ION_NAME") AS
  select o.name, o.subname, o.obj#, o.dataobj#,
       decode(o.type#, 0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER',
                      4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE',
                      7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE',
                      11, 'PACKAGE BODY', 12, 'TRIGGER',
<snip>


text:
Q: How can I generate a video from raw folder based on spinner selection? I was wondering if there was a way I can generate a video to play that's within a raw folder which is dependent on what is selected from two spinner drop-down menus? I'm trying to make a video navigation app for my school that asks the user to select a starting point for their navigation and their desired classroom. So far I've just got one video to successfully play back. Any help would be greatly appreciated!
Here's my main
public class MainActivity extends Activity {
public Spinner start, end;
private Button done;
public TextView start_display, end_display;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    addStartPoint();                                                    //Implements the start point spinner
    addEndPoint();                                                      //Implements the end point spinner
    start = (Spinner) findViewById(R.id.startingPoint_spinner);
    end = (Spinner) findViewById(R.id.endPoint_spinner);
    done=(Button)findViewById(R.id.done);
    done.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {                                   //Go to selected layout when done button is clicked
            Intent i = new Intent(MainActivity.this, SelectingItem.class);
            startActivity(i);
            start_display = (TextView)findViewById(R.id.txtStart);
            end_display = (TextView)findViewById(R.id.txtEnd);
            start = (Spinner) findViewById(R.id.startingPoint_spinner);
        };
    });
}

public void addStartPoint()
{
    Resources res = getResources();                                          //Refers to startpoint array created in strings.xml
    String[] startpoint = res.getStringArray(R.array.startpoint);
    }

public void addEndPoint()
{
    Resources res = getResources();                                         //Refers to endpoint array created in strings.xml
    String[] endpoint = res.getStringArray(R.array.endpoint);
}

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}
SelectingItem Screen
public class SelectingItem extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.selected_layout);
    VideoView videoView = (VideoView)this.findViewById(R.id.VideoView);
    MediaController mediaController=new MediaController(this);
    mediaController.setAnchorView(videoView);
    videoView.setMediaController(mediaController);
    String uri = "android.resource://" + getPackageName() + "/" + R.raw.meb2101;                //This line will need to be changed to an if/else statement for all routes
    videoView.setVideoURI(Uri.parse(uri));
    videoView.start();
}

}
strings.xml

<string name="app_name">FlemNav</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="title_activity_display_navigation">DisplayNavigationActivity</string>
<string name="title_activity_navigation_main">NavigationMain</string>
<string name="choose_starting_point">Choose Starting Point</string>
<string-array name="startpoint">
    <item>Main Entrance</item>
    <item>Electrical Wing</item>
    <item>Steel Centre</item>
    <item>Side Entrance</item>
    <item>Cafeteria</item>
    <item>Side Door</item>
    <item>New Building</item>
</string-array>
<string-array name="endpoint">
    <item>B2101</item>
    <item>B2102</item>
    <item>B2103</item>
    <item>B2104</item>
</string-array>

A: It looks like you can just add the data you need to the intent you are sending to SelectingItem.
    public class MainActivity extends Activity {
        //.....................

            @Override
            public void onClick(View v) {                                   //Go to selected layout when done button is clicked
                String startText = start.getSelectedItem().toString();
                String endText = end.getSelectedItem().toString();

                Intent i = new Intent(MainActivity.this, SelectingItem.class);
                i.putExtra("start_selection", startText);
                i.putExtra("end_selection", endText);

                startActivity(i);

                /*  Not sure what's going on here... probably not needed
                start_display = (TextView)findViewById(R.id.txtStart);
                end_display = (TextView)findViewById(R.id.txtEnd);
                start = (Spinner) findViewById(R.id.startingPoint_spinner);
                */
            };
        });
    }

And then in your SelectingItem.java:
public class SelectingItem extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.selected_layout);

    Intent intent = this.getIntent();
    String startSelection = intent.getStringExtra("start_selection");
    String endSelection = intent.getStringExtra("end_selection");

    VideoView videoView = (VideoView)this.findViewById(R.id.VideoView);
    MediaController mediaController=new MediaController(this);
    mediaController.setAnchorView(videoView);
    videoView.setMediaController(mediaController);
    String uri = null;

    if ( startSelection.equals("Main Entrance") && endSelection.equals("B2101") ){
         uri = "android.resource://" + getPackageName() + "/" + R.raw.meb2101;                //This line will need to be changed to an if/else statement for all routes
    }
    else if ( startSelection.equals("Main Entrance") && endSelection.equals("B2102") ){
         uri = "android.resource://" + getPackageName() + "/" + R.raw.meb2102;
    }
    //..... and so on......

    if (uri != null){
       videoView.setVideoURI(Uri.parse(uri));
       videoView.start();
    }
}

For more info on what I've used here, see these posts:
How to get Spinner value?
How do I get extra data from intent on Android?


text:
Q: Build my own Ubuntu ISO I'm running the daily Ubuntu image (Yakkety Yak) and I would like to build my own Ubuntu image (alternate right now but instructions for a live image also help) while adding a few PPAs. There are several guides on the Ubuntu Community Help wiki, but they all seem to be outdated. I've also attempted to read Ubuntu's and Debian's code for doing this, but I'm not seeing exactly how they are used.
How do I do this without installing the ancient Trusty Tahr?

A: Use Respin which is a current fork of Remastersys Packages and [source code] 3 is available for Ubuntu 14.04 through 16.04 versions of Ubuntu. Now that Yakkety is frozen I would expect a package for that to be available soon as well.
The below is the process I used to install respin in Xenial (16.04)
Respin depends on xresprobe  and isolinux neither is available in the repositories so we will have to add a couple of PPA'S, update the package list, and install them.
sudo add-apt-repository ppa:sergiomejia666/respin
sudo add-apt-repository ppa:sergiomejia666/xresprobe
sudo apt install xresprobe
sudo apt install respin

Further research indicates that we also need isolinux
sudo apt install isolinux

I decided to go with the live system (the script provides other options as well, but the live system with installer seemed more useful to me) respin without any parameters will provide   the following output:
Examples:

   sudo respin backup   (to make a livecd/dvd backup of your system)

   sudo respin backup custom.iso
                        (to make a livecd/dvd backup and call the iso custom.iso)

   sudo respin clean    (to clean up temporary files of respin)

   sudo respin dist     (to make a distributable livecd/dvd of your system)

   sudo respin dist cdfs
                        (to make a distributable livecd/dvd filesystem only)

   sudo respin dist iso custom.iso
                        (to make a distributable iso named custom.iso but only
                         if the cdfs is already present)

   cdfs and iso options should only be used if you wish to modify something on the
   cd before the iso is created.  An example of this would be to modify the isolinux
   portion of the livecd/dvd

Next we need to setup our respin
sudo respin dist cdfs (to make a distributable livecd/dvd filesystem) which we will use to create a custom ISO
This will be a fairly time consuming process (ETA dependent on hardware)
At this point we can modify the isolinux portion of the if the live media to our liking.
And now for the creation of the ISO
sudo respin dist iso custom.iso

Note:
As my 16.04 system has a number of additions/modifications and several VM's the resulting image is quite large.
Making custom.iso a hybrid iso
isohybrid: Warning: more than 1024 cylinders: 2547
isohybrid: Not all BIOSes will be able to boot this device
Creating custom.iso.md5 in /home/respin/respin
/home/respin/respin/custom.iso which is 2.5G in size is ready to be burned or tested in a virtual machine.

Launch  Startup disk Creator and select your custom.iso file and target location.(I used a 4GB Flash drive)
the custom.iso file will be found in the /home/respin/respin directory.
The resulting image works as expected. The stopper for Yakkety is that as of this wrinting, I can't find an installation candidate for xresprobe Perhaps you could build from source or wait. Personally I've found that most developers seem to focus on LTS versions. This makes sense to me as it doesn't seem very efficient to expend a great deal of effort on a 9 month release.
EDIT: The latest published respin deb package for Ubuntu can be found here.

A: Using Systembackup
One can backup and make live iso files with Systemback utility, you can install it from its PPA and it works the same as remastersys (no longer maintained), i think.  ubuntu 14.04 needs an extra package called unionfs-fuse too. It can also create live usb images. You can add your user files in iso which can then be installed on other machines, but other machines may have different graphics etc so make sure you have not uninstalled preinstalled xorg video packages. So all you need is add ppa and install
sudo add-apt-repository ppa:nemh/systemback
sudo apt-get update && sudo apt-get install systemback unionfs-fuse

After creating iso file, creating live usb and booting from it on same machine or different machine, you will find systemback installed.

Using remastersys
(I am not sure if it is supported yet today or not)
 sudo add-apt-repository ppa:kranich/remastersys
 sudo apt-get update

Follow on guide gui instructions.(best to make iso copy of ur current system)
Using Ubuntu Builder
sudo add-apt-repository ppa:f-muriana/ubuntu-builder
sudo apt-get update && sudo apt-get install ubuntu-builder

Follow gui instructions.
Using Pinguybuilder
Download .deb file from here and use dpkg or gedbi to install it .It is new type of remastersys.


text:
Q: how config to show MIME Types in IIS? How to show MIME Types because my IIS server didn't have MIME type like this.
and what must i do.
Because i need that to get image from URL then i hit the path and i got the image in other platform.
Problem is:

*

*There is not MIME Types in my iis server.

I have tried to turn windows features on or off and check all in internet information service(IIS) but still there is nothing MIME Types.
I have do a lot way but still can got a right way.


text:
Q: How to get currency in Indian format using python? I have following amounts:
1000
1234
123400
1900000

How can i convert these to:
1 Thousand
1.2 Thousand
1.2 Lakhs
19 Lakhs

I tried a function from this link Convert an amount to Indian Notation in Python.
def format_indian(t):
  dic = {
      4:'Thousand',
      5:'Lakh',
      6:'Lakh',
      7:'Crore',
      8:'Crore',
      9:'Arab'
  }
  y = 10
  len_of_number = len(str(t))
  save = t
  z=y
  while(t!=0):
    t=int(t/y)
    z*=10

  zeros = len(str(z)) - 3
  if zeros>3:
      if zeros%2!=0:
          string = str(save)+": "+str(save/(z/100))[0:4]+" "+dic[zeros]
      else:
        string = str(save)+": "+str(save/(z/1000))[0:4]+" "+dic[zeros]
        return string
  return str(save)+": "+str(save)

But this is giving me:
format_indian(100001)
>>> '100001: 100001'

How can I make that to:1 lakhs, the above solution only works for 10's of every category. For example: 10 Thousand, 10 Lakhs, 10 crore

A: You can use num2words package of Python. It converts numbers to words.
https://pypi.org/project/num2words/
This code will convert number to words in Indian format.
from num2words import num2words

print(num2words(100000, lang='en_IN'))

Output:

one lakh

A: Just like Ram said, you can use the package: https://pypi.org/project/num2words/ and you can use a dictionary and try except
num2words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \
             6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \
            11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', \
            15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', \
            19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', \
            50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', \
            90: 'Ninety', 0: 'Zero'}

>>> def n2w(n):
        try:
            print num2words[n]
        except KeyError:
            try:
                print num2words[n-n%10] + num2words[n%10].lower()
            except KeyError:
                print 'Number out of range'

>>> n2w(0)
Zero
>>> n2w(13)
Thirteen
>>> n2w(91)
Ninetyone
>>> n2w(21)
Twentyone
>>> n2w(33)
Thirtythree

A: !pip install inflect

Not in the Indian Currency but you can get it in strings
import inflect
p = inflect.engine()

so
p.number_to_words(1900000)
will give you
one million, nine hundred thousand

but if you only need in Indian Currency then you can modify 3rd answer of this SO thread

A: Just building up on your existing code, you can try something like this if you want the 1st part to still show numbers, else @Ram answer should work fine.
import math
def format_indian(t):
    num_count = {
        3 : 'Hundred',
        4 : 'Thousand',
        5 : 'Thousand',
        6 : 'Lakh',
        7 : 'Lakh',
        8 : 'Crore',
        9 : 'Crore',
        10: 'Arab'
    }
    num_len = len(str(t))
    power = num_len - 1 if (num_len % 2 == 0 or num_len == 3) else num_len - 2
    dig = t / math.pow(10, power)
    print("{} {}".format(round(dig,1), num_count[num_len]))

You can adjust the round-off value based on the precision you want.


text:
Q: Why does my useEffect() fetch data unreliably. I cannot map through the data because I am getting some undefined responses - ReactJS I have a sidebar which sets a category Id on click and shows product information based on this Id.
In order to display each product's details, I make an api post call using axios in a useEffect() hook and setData with useState hook.
However, when I try to console.log the data, I get unreliable data back, that is, some undefined and some data.
import { useState, useEffect, useCallback, useMemo } from "react";
import axios from "axios";

import ProductCard from "../Product-cards/_medium-product-card";

const ProductDisplay = ({ subCategorySkus, categoryId, allSkus }) => {

  const [data, setData] = useState();
  const [isLoading, setIsLoading] = useState();

  const apiRequest = { product_skus: allSkus };

  const productData = useProductData(apiRequest);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.post("/products", apiRequest);

        setData(response.data);
        setIsLoading(false);
      } catch (err) {
        console.log(err.message);
      }
    };
    fetchData();
  }, [categoryId]);

  console.log(data);

  return isLoading ? (
    " data is loading ..."
  ) : (

Child component Id: {categoryId}

      <ProductCard categoryId={categoryId} />

  );
};

export default ProductDisplay;

You can see here what I get in the console:
.
I have tried adding an if condition, but I am not sure that addresses the issue. I have tried with different dependencies in the useEffect. But I feel there is something I am not understanding.
The api is sending the information correctly, but I get several responses in the console.log and some of them come in as undefined.
This means that I can do a data.map because it crashes the component.
Any help?
UPDATE:
@moonwave99 provided the answer (see below). For the benefit of others who may browse through this question and to clarify what the solution entails, I am including an image below, showing where I changed my code. I think that most importantly, I had not initialised my useState() to an empty array, like this: useState([]).
Any further clarification of the issues here by anyone who knows more, is welcomed. As this is only a quick fix without enough context to understand the logic.


text:
Q: HTML Forms - when the text box value changes I'm trying to figure out how to call a method everytime a text box in a form's value changes.
For example,

Is there a parameter I can add that is called everytime the user types something new in the box? I know there is an "onchange" but that is only called once the user is done typing in that box.
Thanks!

A: What you need to us is an onkeyup event.  Without a js library your code should look similar to this (syntax is unchecked):
<html>
<head>
<script type="text/javascript">
function keyup(x)
{
  //code
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname"  onkeyup="keyup(this)">

</body>
</html>

You can also use onblur if you want to check it when the user changes focus from the text box.
For more detail:
http://www.w3schools.com/jsref/event_onkeyup.asp
http://www.w3schools.com/jsref/event_onblur.asp


text:
Q: Android: Pressing ad causes Activity with locked orientation to change orientation All of the Activities in my app are locked into portrait orientation using:
android:screenOrientation="portrait"

I have ads showing at the top of a few of my Activities, and if I tilt the phone sideways and press the ad, it changes the underlying Activity into landscape orientation! I tried to override
onConfigurationChanged(Configuration newConfig)

by setting the configuration to portrait and calling through to super, but it has no effect. Any clue on how to fix this, or what's going on?

A:     @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

Did the trick.


text:
Q: Powershell - Where LastLogonDate is over 90 days from today I'm looking to use the Search-ADAccount cmdlet to get all users where the LastLogonDate is over 90 days from today's date.  This script is to be ran each day and the requirements are to use Search-ADAccount and LastLogonDate that is over 90 days from today's date.  I know there are other ways to get the same info, but that's what I've been asked for from the team.
I pretty much just don't know how to do the math part on LastLogonDate but any sample scripts would be awesome.
Thanks!

A: Got it figured out. Was looking for:
where-object {$_.LastLogonDate -lt (Get-Date).AddDays(-90)}

A: The best way to do this, is not with Search-ADAccount but use Get-ADUser instead.
Using the answer provided by Rob in response to his own answer, I would recommend the following:
Get-ADUser -Filter * -Properties LastLogonDate | Where-Object {$_.LastLogonDate -lt (Get-Date).AddDays(-90)}

This way we are searching all users, and asking AD to return the LastLogonDate variable of the object and identify the ones that have not logged on for the past 90 days.


text:
Q: Notion of infinity in categories Please excuse me if the question is too vague or uninteresting.
Let $\mathcal{C}$ be a category and $A$ an object in $\mathcal{C}$. Motivated by the equivalence of Dedekind-finiteness and finiteness for sets (assuming Choice), let us define that an object $A$ is $\mathcal{C}$-infinite if there is an object $A'$ in $\mathcal{C}$ corresponding to a proper subobject of $A$ and an isomorphism $f: A \to A'$ in $\mathcal{C}$.
In the category Set, we have the property that ($B$ is Set-infinite and $B \subseteq A) \implies A$ is Set-infinite. The analogous property does not hold (with this definition of infinity) over arbitrary categories. For instance, the additive group $\mathbb{Q}$ has $\mathbb{Z}$ as a proper subgroup, is finite in the category Grp (since any homomorphism $f: \mathbb{Q} \to \mathbb{Q}$ must actually be an isomorphism), but $\mathbb{Z}$ is Grp-infinite by $g:\mathbb{Z} \to 2\mathbb{Z}$ with $z \mapsto 2z$.
In which categories would a version of this transitivity property hold? What about other properties depending on a notion of infinity? Or determining whether a given object in a category is infinite or not?
A result somewhat related to this notion is that a Banach space isomorphic to all its infinite-dimensional closed subspaces is isomorphic to a separable Hilbert space. Any such Banach space is obviously Ban-infinite.
I don't know much Category Theory or Logic, but this has been troubling me for a while (I'm an undergraduate student). Thanks in advance for your contributions.

A: This is an enlarged comment. See section $8.2$ of $[1]$.
Transitivity Property: Let $B$ be $\mathscr{C}$-infinite, and let $B\hookrightarrow A$. Then $A$ is $\mathscr{C}$-infinite. This is not satisfied for all $\mathscr{C}$; e.g., let $\mathscr{C}$ be the category of presheaves on $(\mathbb{N},\leq)$ (Counterexample $8.2.4$, $[1]$).
The following theorem gives a sufficient condition (there might be many more) for the transitivity property to hold.
Theorem 1 (Proposition $8.2.3$, $[1]$): Let $A$ be an object of a topos $\mathscr{C}$ such that there is a complemented subobject $B$ of $A$ that is $\mathscr{C}$-infinite. Then $A$ is itself $\mathscr{C}$-infinite.
Proof (taken from $[1]$): Let $C\hookrightarrow B$ be a subobject of $B$ not containing the global element $b:\mathbf{1}\to B$ and an isomorphism $C\to B$. As $\models b\in B$, it follows that $\models\neg(b\in \overline{B})$; hence $\models\neg(b\in S\cup\overline{B})$. Thus $S\coprod\overline{B}$ is a proper subobject of $A$. There is an isomorphism $A\to S\coprod \overline{B}$. Hence $A$ is $\mathscr{C}$-infinite. $\square$
Bibliography
$[1]$ Francis Borceux, Handbook of Categorical Algebra: Volume $3$, Sheaf Theory. $522$ pp. Cambridge University Press. Published $1994$.


text:
Q: sudo subl - como abrir o sublime 3 pelo terminal no Ubuntu? Realizei a instalação do Sublime Text 3 no Ubuntu 17.10.
Consigo abrir o Sublime utilizando o comando subl no terminal. Porém não funciona abrir como sudo, ao utilizar o comando nada acontece.
Porém funciona rodar os comandos sudo subl -h para acessar o help do sublime e sudo subl -v para ver a versão.
Abaixo o conteúdo do arquivo sublime_text.desktop
--------------------------------------------------------

rodolfo@rodolfo-ntb:/usr/share/applications$ cat sublime_text.desktop
[Desktop Entry]
Version=1.0
Type=Application
Name=Sublime Text
GenericName=Text Editor
Comment=Sophisticated text editor for code, markup and prose
Exec=/opt/sublime_text/sublime_text %F
Terminal=false
MimeType=text/plain;
Icon=sublime-text
Categories=TextEditor;Development;
StartupNotify=true
Actions=Window;Document;

[Desktop Action Window]
Name=New Window
Exec=/opt/sublime_text/sublime_text -n
OnlyShowIn=Unity;

[Desktop Action Document]
Name=New File
Exec=/opt/sublime_text/sublime_text --command new_file
OnlyShowIn=Unity;
rodolfo@rodolfo-ntb:/usr/share/applications$

A: Eu recebi ajuda em um grupo no Telegram, e isto não é um bug. O Ubuntu 17.10 está utilizando Wayland, e o Wayland não permite a execução de programas como sudo. Antes de iniciar a sessão com o usuário eu troquei para iniciar o Ubuntu com Xorg e agora está funcionando o comando sudo subl.


text:
Q: Can anyone recommend books for self learning calculus which focus on developing understanding? I am trying to learn a little basic mathematics by myself with help from a few books and this site. So far I have read 3 excellent books: Algebra, Trigonometry and Method of Coordinates by Gelfand et al. Since finishing them I am left wondering what to try reading next.
What I liked about these books is that they combined clear explanation with challenging problems. Perhaps it was the influence of a great mathematician like Gelfand which resulted in real passion and love for the subject shining through. They were definitely not dry or boring. They were slim volumes, not phone directories. Best of all I felt I learnt and understood something, and was not memorising 'recipes', which was how I remember maths from school.
I would like to learn some basic calculus. Many years ago I was taught this at school, with the emphasis on rote learning a few 'rules' to pass an exam. I would like to understand calculus this time. I think I need to learn something about limits first.
Can anyone recommend any fairly basic to intermediate books about limits and calculus which are in the same style as the Gelfand books? That is which really emphasise understanding, as my exam taking days are long gone.

A: Spivak's Calculus is great. May be a bit challenging at times but you will really learn calculus.


text:
Q: filter and sort columns with groupby pandas I have this df:
   Date                  Plate     Route     Speed   VehiceType
0  2020-11-03 13:54:00   0660182   Route 66   32      Wagon
1  2020-11-03 13:25:03   939CH003  Route 35   24      Truck
2  2020-11-03 09:27:11   WH3457    Route 02   41      Bus

and so on. I need time differences between same plate vehicles, which I easily obtain as:
df.groupby('Plate').Date.diff( )

then, I sort (otherwise I would have differences between different dates/plates, which I dont need) and group like this:
df2 = df.sort_values(by=['Plate', 'Date']).groupby('Plate').Date.diff().dt.total_seconds().reset_index()

i end up with a df (after renaming one column) like this:
      index   Difference (s)
0     34517   NaN
1     377539  33.0
2     119714  34.0
3     300900  765.0

that's not what I need ("index" column is supposed to be that of plates'). What I want is something like:
    Plate   Difference
0   WH3457  54.0
1   9W432T  24.0
2   947CH05 33.0

so that this df can be merged in the original one (left_on and right_on) by plate number for some filters. Pandas says merge cant be done because "index" column is just numbers, while plate column is clearly a string (I miss plate objects somehow when sorting).
So, how can I obtain this plate/difference df? (sort by plate and date is a must, otherwise differences makes no sense).
I've been struggling with this and cant get it. Thank you in advance.
EDIT:
This is a bigger chunk of original df (sorry about alignment and vehicle type in spanish):
    Date                        Plate       Route       Latitude    Longitud    Speed   VehicleType
0   2020-11-17 13:54:00+00:00   0660182     RUTA 66     19.333958   -99.199240  10  AUTOBUS LARGO (MAYOR A 10 M DE LONGITUD)
1   2020-11-17 13:54:00+00:00   939CH001M   RUTA 51     19.256760   -98.955510  22  AUTOBUS LARGO (MAYOR A 10 M DE LONGITUD)
2   2020-11-17 13:54:00+00:00   596NZ008M   RUTA 102    19.448385   -98.952400  0   VAGONETA
3   2020-11-17 13:54:00+00:00   0790024     RUTA 79     19.429462   -99.150820  0   MICROBUS (MENOR A 7.5 M DE LONGITUD)
4   2020-11-17 13:54:01+00:00   947CH045M   RUTA 50     19.282007   -99.009000  28  MICROBUS (MENOR A 7.5 M DE LONGITUD)
...     ...     ...     ...     ...     ...     ...     ...
1279721     2020-11-18 05:59:57+00:00   0120414     RUTA 12     19.357872   -99.077920  0   MICROBUS (MENOR A 7.5 M DE LONGITUD)
1279722     2020-11-18 05:59:58+00:00   1090016     CETRAM XOCHIMILCO 200826    19.295107   -99.102936  0   MICROBUS (MENOR A 7.5 M DE LONGITUD)
1279723     2020-11-18 05:59:59+00:00   0350144     RUTA 35     19.297995   -99.061150  0   VAGONETA
1279724     2020-11-18 05:59:59+00:00   006908      RUTA 106    19.490650   -99.174640  0   AUTOBUS CORTO (ENTRE 7.5 Y 10 M DE LONGITUD)
1279725     2020-11-18 05:59:59+00:00   0340071     RUTA 34     19.324417   -99.165500  1   MICROBUS (MENOR A 7.5 M DE LONGITUD)

A: If you desire to place your calculation (diff in seconds) back to the original dataframe, you can use pandas groupby.transform instead:
df['diff_in_sec'] = df.groupby('Plate').Date.transform(lambda x: x.diff().dt.total_seconds())

Furthermore, since your apply function doesn't perform any aggregation, df2 has the same original row shape as df so that index can be used to map the values back to df like this:
df2 = df.sort_values(by=['Plate', 'Date']).groupby('Plate').Date.diff().dt.total_seconds()
# this
df.loc[df2.index, 'diff_in_sec'] = df2
# or this
df2.name = 'diff_in_sec'
df.merge(df2, left_index=True, right_index=True)


text:
Q: MPI_Iprobe not setting flag correctly I've recently been having trouble with using MPI_Iprobe. I have attached some code below to try and demonstrate the issue (note: the code I'm using is different, the code is purely to create a minimal reproducible example of my issue).
What I want to do is make the process with the rank of 0 send a request message to the process with rank 1. Rank 0 can send this message at an arbitrary point in the loop (hence why I have used an if-statement - if(i == 1)). It is possible that rank 0 never sends this message, that's why I'm using Iprobe in handleReplies(). Once rank 1 is is done with the loop (which is almost immediate as it has no work to do within the loop), I want it to call handleReplies() after five seconds. This is to ensure that the process 0 has used send() by the time handleReplies() is called.
The issue is, that when handleReplies() is called, it should use MPI_Iprobe to set the flag variable to true (ie: 1) as the rank 0 process has sent a message of TAG_REQ. However, for some reason the flag is never set to 1, and remains 0. As a result, my MPI_Recv in my rank 0 remains blocked.
int main(int argc, char *argv[]) {
    int rank, size;

    // Call MPI_init, MPI_Comm_rank, MPI_Comm_size...

    int i = 0;
    while(i <= 3) {
        if(rank == 0) {
            int fav;
            int linked = 1; // the rank send/recv messages from

            if(i == 1) { // at some point in the loop, send a request to the linked process
                printf("Sending msg request to %d\n", linked);
                MPI_Send(&rank, 0, MPI_INT, linked, TAG_REQ, MPI_COMM_WORLD);

                printf("waiting for receieve\n");
                MPI_Recv(&fav, 1, MPI_INT, linked, TAG_REP, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
                printf("%d's favourite number is %d\n", linked, fav);
            }
        }
        i++;
    }

    sleep(5); // sleep 5 secs to ensure that the other node is waiting for a reply
    handleReplies(MPI_COMM_WORLD, 1); // before we quit, handle any replies which may be waiting still
    printf("[%d] Finished...\n", rank);
    MPI_Finalize();
    return 0;
};

void handleReplies(MPI_Comm comm, int debug) {
    int linked = 0;
    int flag = 0; // gets set to 1 if message received
    MPI_Iprobe(linked, TAG_REQ, comm, &flag, MPI_STATUS_IGNORE);
    printf("Is there a requesting message: %s\n", flag ? "yes" : "no");
    if(flag) {
        int recvVal;
        int fav = 11;
        MPI_Recv(&recvVal, 0, MPI_INT, linked, TAG_REQ, comm, MPI_STATUS_IGNORE);
        MPI_Send(&fav, 1, MPI_INT, linked, TAG_REP, comm);
    }
}

Below is the output of my code when I run it with 2 processes:
Sending msg request to 1    // shows that message has been sent
waiting for receive  // left hanging as no reply ever sent
Is there a requesting message: no  // 5 seconds after above line (expected "yes" instead of "no")
[1] Finished...

after the [1] Finished... it continues to hang as MPI_Send(&fav, 1, MPI_INT, linked, TAG_REP, comm); because flag never gets set to true.
Why is MPI_Iprobe not picking up that rank 0 sent a message five seconds ago?
I have also looked at this answer but the issue there seems to be that they're using MPI_Isend instead of MPI_Send.


text:
Q: Automatically restart a Python program if it's killed I run a Python Discord bot. I import some modules and have some events. Now and then, it seems like the script gets killed for some unknown reason. Maybe because of an error/exception or some connection issue maybe? I'm no Python expert but I managed to get my bot working pretty well, I just don't exactly understand how it works under the hood (since the program does nothing besides waiting for events). Either way, I'd like it to restart automatically after it stops.
I use Windows 10 and just start my program either by double-clicking on it or through pythonw.exe if I don't want the window. What would be the best approach to verify if my program is still running (it doesn't have to be instant, the verification could be done every X minutes)? I thought of using a batch file or another Python script but I have no idea how to do such thing.
Thanks for your help.

A: for problem you stated i prefer to use python subprocess call to rerun python script or use try blocks.
This might be helpful to you.
check this sample try block code:
try:
  import xyz # consider it is not exist or any error code
except:
  pass # go to next line of code to execute

A: You can write another python code (B) to call your original python code (A) using Popen from subprocess. In python code (B), ask the program to wait for your python code (A). If 'A' exits with an error code, recall it from B.
I provide an example for python_code_B.py
import subprocess

filename = 'my_python_code_A.py'
while True:
    """However, you should be careful with the '.wait()'"""
    p = subprocess.Popen('python '+filename, shell=True).wait()

    """#if your there is an error from running 'my_python_code_A.py',
    the while loop will be repeated,
    otherwise the program will break from the loop"""
    if p != 0:
        continue
    else:
        break

This will generally work well on Unix / Windows systems.  Tested on Win7/10 with latest code update.
Also, please run python_code_B.py from a 'real terminal' which means running from a command prompt or terminal, and not in IDLE.


text:
Q: User is unable to install android app at the same time on play store. How to resolve this? Hello all I've three play store app with the package name
com.gohiggs.cboxapp https://play.google.com/store/apps/details?id=com.gohiggs.cboxapp
com.gohiggs.luvduv https://play.google.com/store/apps/details?id=com.gohiggs.luvduv
com.gohiggs.yostatus https://play.google.com/store/apps/details?id=com.gohiggs.yostatus
but I'm unable to install three of the app at the same time. it is showing this following error.

A: it happen only when your apps are using same File Provider path.
try to change name tag of your file provider path
<paths>
<external-path name="use_uniq_name_here" path="." />
<root-path path="/" name="use_uniq_name_here" />

A: Whenever we want to access files from device SD-card, we need to add 'provider' in android manifest of app as following.
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.mywebsite.myapp.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths_public" />
    </provider>

We need to give different unique names for each app. ( eg. android:authorities = "com.mywebsite.myapp.provider" ) If same name is used for multiple apps then it may only allow to install single app at a time from all these multiple apps.


text:
Q: How to convert ipv4 address to ipv6 use AFNetworking? I've a problem with IPV6.
Apple reject my app with error:

We discovered one or more bugs in your app when reviewed on iPad and iPhone running iOS 10.0.2 on Wi-Fi connected to an IPv6 network.
Specifically, your app stayed static at the launch screen and there was no further content loaded.
We've attached screenshot(s) for your reference.

But my sever is not supporting IPV6. I use library AFNetworking to connect server. Please help me some solution? Thank you for any support!

A: I got this error a month ago, then I updated AFNetworking to last version and Apple's Reachability class too, my problem solved, you can try this, I hope it'll work.

A: Please see this link:
Supporting IPv6 DNS64/NAT64 Networks
This may be helpful:
Transitioning to IPv6-only networks
It covers the topic you described.


text:
Q: D3 .merge function I'm struggling with understanding the merge function in D3, despite reading through the D3 API countless times.
The API says: "This method is commonly used to merge the enter and update selections after a data-join. After modifying the entering and updating elements separately, you can merge the two selections and perform operations on both without duplicate code."
Here's an example of the supposedly straightforward use of it, in a force directed chart, where the ticked function is called with every tick:
var simulation = d3.forceSimulation(nodes)
    .force("charge", chargeForce)
    .force("center", centerForce)
    .on("tick", ticked);

    function ticked() {

    var u = d3.select("svg").selectAll("circle").data(nodes)

    u.enter().append("circle").attr("r",5)
        .merge(u) // What is the merge function doing here?
        .attr("cx", d => d.x)
        .attr("cy", d => d.y)

    u.exit().remove() // Why is it necessary to remove excess objects w/ the exit selection?

    }

I understand how data-binding works, and how enter() and exit() selections work. However, I've never had to use a "merge" before, and I don't understand it is doing here. If someone could briefly walk through what is going on in this function step-by-step, that would be extremely useful. I'm sure others have similar questions.

A: You actually have two issues here:

*

*Understanding the merge() method;

*Understanding that piece of code you shared;

Regarding #1 you already received an answer. Regarding #2, these are my two cents: that code does not make sense.
This is simple to understand: the ticked function runs dozens of times per second. Why would you re-bind the data and reassign the update, enter and exit selections dozens of times per second, if the data doesn't change? (it's worth mentioning that the author of that code is a good programmer, something strange has happened here... after all, we all make mistakes)
The ticked function just need to compute the positions of the elements, that's all.
Here is that same code you linked with the ticked function simplified to just this:
function ticked() {
    u.attr('cx', function(d) {
            return d.x;
        })
        .attr('cy', function(d) {
            return d.y;
        })
}

And here the running code:

var width = 600,
  height = 400;

var colorScale = ['orange', 'lightblue', '#B19CD9'];
var xCenter = [100, 300, 500]

var numNodes = 100;
var nodes = d3.range(numNodes).map(function(d, i) {
  return {
    radius: Math.random() * 25,
    category: i % 3
  }
});

var u = d3.select('svg g')
  .selectAll('circle')
  .data(nodes);

var enter = u.enter()
  .append('circle')
  .attr('r', function(d) {
    return d.radius;
  })
  .style('fill', function(d) {
    return colorScale[d.category];
  });

u = enter.merge(u);

u.exit().remove();

var simulation = d3.forceSimulation(nodes)
  .force('charge', d3.forceManyBody().strength(5))
  .force('x', d3.forceX().x(function(d) {
    return xCenter[d.category];
  }))
  .force('collision', d3.forceCollide().radius(function(d) {
    return d.radius;
  }))
  .on('tick', ticked);

function ticked() {
  u.attr('cx', function(d) {
      return d.x;
    })
    .attr('cy', function(d) {
      return d.y;
    })
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="content">
  <svg width="700" height="400">
    <g transform="translate(50, 200)"></g>
  </svg>
</div>

A: The documentation explains very well what that function does, so what it does is instead of you having to do this
u.attr("cx", d => d.x)
 .attr("cy", d => d.y);

u.enter().append("circle").attr("r",5)
        .attr("cx", d => d.x)
        .attr("cy", d => d.y);

You can just call attr once like
u.enter().append("circle").attr("r",5)
        .merge(u) // after this point, any updates will apply to both u and u.enter() selections
        .attr("cx", d => d.x)
        .attr("cy", d => d.y)

It will set attributes cx and cy on both u-the update selection and u.enter()-the enter selection

Why is it necessary to remove excess objects w/ the exit selection?

Because the exit selection contains any extra DOM elements that were not bound to the elements in the array you passed to data(), you can do whatever you need on the exit colllection, for example setting the styles by calling u.exit().style(...), etc. instead of calling remove to delete them from the DOM

A: In view of the comments I should alert readers that this answer may be wrong. So please read the comments first
TL;DR - merge makes two node collections into one
var x = d3.selectAll(".node");
var y = d3.selectAll(".link");
var z = x.merge(y);

z now contains all the elements in x AND all the elements in y.


text:
Q: Loading asset with custom extension not working I'm trying to implement my first application in react-native and I need to open database from a static file saved in my project folder.
I read that i need to allow loading custom extensions files from assets so i added following fragment into my app.json file:
"packagerOpts": {
    "assetExts": ["sqlite", "db"]
},

Next I'm trying to import this static file with .sqlite or .db extension inside my App.js component in componentDidMount() method:
componentDidMount = async () => {
  await Expo.FileSystem.downloadAsync(
    Expo.Asset.fromModule(require("./assets/db/local.db")).uri,
    `${Expo.FileSystem.documentDirectory}SQLite/local.db`
  );

  SQLite.openDatabase("local.db");
};

but expo builder keep saying Unable to resolve "./assets/db/local.db" from "App.js". Any suggestion please?

A: The following code is from 2 answers above
create metro.config.js in project root directory:
const defaultAssetExts = require("metro-config/src/defaults/defaults").assetExts;

module.exports = {
  resolver: {
    assetExts: [
      ...defaultAssetExts,
      // 3D Model formats
      "dae",
      "obj",
      "mtl",
      // sqlite format
      "db",
      "sqlite"
    ]
  }
};

Optionally install metro-dependency: npm i metro-config --save-dev

A: I found that expo has some kind of bug but there is PR raised/approved for this one. For anyone who can't wait for official bug fix there is also workaround for this one:
Create a metro.config.js file with assetExts fixed the problem for me:
module.exports = {
  resolver: {
    assetExts: ["db", "mp3", "ttf"]
  }
}

and import this file lets say in your App.js? I'm now able to open SQLite database from file.

A: Go to node_modules metro-config defaults.js ad extend type to the assetExts section Done~

A: In Expo 40 - here was how I was able to get it running!
Expo website source.
Note you'll have to put the files in the assets directory, and make sure your app.json specifies all of the needed extensions, mine includes everything: "assetBundlePatterns": ["**/*"],
First, I'll split it into two parts - getting Expo to work, then getting typescript to work.
Expo was simple, but only once I realized it was the issue. I followed the above guide. In summary:

*

*expo install @expo/metro-config

*create a metro.config.js and call the push method with whatever extension you are trying to add, in my case it was md (markdown):

const { getDefaultConfig } = require('@expo/metro-config');

const defaultConfig = getDefaultConfig(__dirname);

defaultConfig.resolver.assetExts.push('md');

module.exports = defaultConfig;

*Reset cache on expo (shift + r in the terminal window running it, on Mac)

Typescript (4) was more documented but I did:

*

*Create a declaration (*.d.ts) file, specifying markdown as a valid extension.

*Made sure that file was in one of my tsconfig.json, "include" directories

*Add that file to typeRoot under compilationOptions in tsconfig.json

*import/require the md in my component

For me these steps were:

*

*add file ./app/declaration.d.ts

*My "include" had the app directory in it, and looked like this:   "include": ["App.js", "app", "test", "storybook"]

*I added this to compilationOptions: "typeRoots":["./app/declaration.d.ts"],

*import newborn from './../../../assets/resources/MY_MD_DOC.md'
Tada!


text:
Q: Autocomplete (jQuery UI) and localstorage I just get a strange bug when using those two tools.
I'm making an AJAX query to an API, then retrieving JSON data which is stored within localStorage and displayed into an autocomplete panel. The problem is that according to the origin of the autocomplete source, the panel will react differently.
Here is the callback function called on AJAX success :
function _company_names(data)
{
    localStorage.setItem('ac_source', JSON.parse(data).Result);

    // Works fine
    $("#search_input").autocomplete( "option", "source", JSON.parse(data).Result);
    // Send an AJAX request
    $("#search_input").autocomplete( "option", "source", localStorage.getItem('ac_source'));
}

If i pass JSON.parse(data).Result as result to the autocomplete source, it will be fine. However if I pass localStorage.getItem('ac_source'), the ac widget will send an AJAX request (not using my own function) blowing in the wind (my node.js will try to parse it, etc.).
I'm using localstorage to access these data from an other part of my code (store it to compare with other user research and displaying it if the request is the same).

A: You can store only string data in Local Storage:
localStorage.setItem('ac_source', '{"key":"data","key1":"data1"}');

$("#search_input").autocomplete( "option", "source", JSON.parse(localStorage.getItem('ac_source')).Result);


text:
Q: Java HttpConnection/HttpsConnection input/error stream In java how do you know whether you have an error stream from a Http(s)connection or if it is an InputStream? The only way I can tell to do it is go for both, check for null and catch any exceptions.
    HttpConnection con = (HttpConnection)URL.openConnection();
    //Write to output
    InputStream in = con.GetInputStream();
    //Vs
    InputStream error = con.getErrorStream();

How does java determine which stream it has? Is it based solely on response code of the connetion? So if its >=200 and <300 then its inputStream otherwhise its an errorStream?
Thanks.

A: HTTP_INTERNAL_ERROR (500) isn't the only response code that can create an error stream, there are many others: 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 501, 502, 503, 504, 505, etc.
Not only that, but connection.getResponseCode() may throw an exception if it initiated the connection and the HTTP response status code was an error-class status code. So checking for 500 (HTTP_INTERNAL_ERROR) immediately after connection.getResponseCode() may actually be unreachable code, depending on how you're accessing connection.
The strategy I have seen implemented is to use the error stream if an exception was thrown, otherwise use the input stream.  The following code provides a basic structural starting point.  You'll probably want to add to it.
InputStream responseStream = null;
int responseCode = -1;
IOException exception = null;
try
{
    responseCode = connection.getResponseCode();
    responseStream = connection.getInputStream();
}
catch(IOException e)
{
    exception = e;
    responseCode = connection.getResponseCode();
    responseStream = connection.getErrorStream();
}

// You can now examine the responseCode, responseStream, and exception variables
// For example:

if (responseStream != null)
{
    // Go ahead and examine responseCode, but
    // always read the data from the responseStream no matter what
    // (This clears the connection for reuse).
    // Probably log the exception if it's not null
}
else
{
    // This can happen if e.g. a malformed HTTP response was received
    // This should be treated as an error.  The responseCode variable
    // can be examined but should not be trusted to be accurate.
    // Probably log the exception if it's not null
}

A: You can do it as following:
InputStream inStream = null;
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
    inStream = connection.getErrorStream();
}
else{
    inStream = connection.getInputStream();
}

The HTTP return code signifies what is the kind of stream to read back.