text:
Q: Cannot read property 'hashedPassword' of undefined This is the code for the "login" process and I want to return a "token", but when I send the request I see this error, How can I solve it
in Console (with the Error):
     LogIn
    , NourGeorge@gmail.com
    , 1923552
    ,✖ TypeError: Cannot read property 'hashedPassword' of undefined
    , POST /user/login 401 48.376 ms - 87
I send This request from postman:
    POST http://localhost:4000/user/login
    Content-Type: application/json
    {
         "email":"NourGeorge@gmail.com",
          "password":"1923552"
    }

I get this answer from Postman:
     {
         "accessToken": null,
         "message": "User login error,Invalid Information(Invalid Password)"
     }

userController.js:
////Login
const login = async (req, res, next) => {
console.log('LogIn');
let { email, password } = req.body;
console.log(email)
console.log(password);
// in findUserByEmail Compaire password with password in database
const result = await User.findUserByEmail(email, password);
//if the password is correct => generate a token using JWT
if (result == 1) {
    res.status(200).json({
        message: 'Process succeeded'
    });
    // generate a token using JWT
    const accessToken = jwt.sign({ id: user.uid }, process.env.ACCESS_TOKEN_SECRET,
        {
            expiresIn: 3600   //1 hour
        })
    // res.json({accessToken:accessToken})
    // return user information & access token
    res.status(200).send({
        id: user.uid,
        email: user.email,
        // password: user.password,
        accessToken: accessToken
    })
}
else {
    res.status(401).json({
        accessToken: null,
        message: 'User login error,Invalid Information(Invalid Password)'
        // error: 'User login error,Invalid Information(Invalid Password)'
    });
}
}

userModel.js:
 static async findUserByEmail(email, password) {
    const Log_I=await SingletonSqlHandler.instance.sendQuery(`SELECT * FROM
              GetUserByEmail('${email}')`)
    .then(result => {
        let userData = result.recordset[0];
        const areMatched = PasswordHasher.verify(password, userData.hashedPassword);
        if (areMatched) {
            Printer.Logger.print("Successfully logged in", Printer.Colors.green,
  Printer.Symbols.ok, true);

           return 1;
        } else {
            Printer.Logger.print('Password is incorrect', Printer.Colors["error message"],
  Printer.Symbols.err, true);
        }
        return 0;
    }).catch(err => {
        Printer.Logger.print("" + err, Printer.Colors["error message"], Printer.Symbols.err,
  true);
            return -1;
    });
    return Log_I;
   }
   }

userRouter.js:
  const router = require('express').Router();
  const userController = require('../Controllers/userController');
  router.post('/login',userController.login);
  module.exports = router;

app.js:
     const express = require('express');
     const morgan = require('morgan');
     const bodyParser = require('body-parser');
     const https=require('https');
     const request=require('request');
     // Modules Variable
     const app = express();
     // User import
     const usersRoutes = require('./routes/userRoute');
     const productsRoutes=require('./routes/productRoute')
     app.use(express.json())
     app.use(morgan('dev')); // Logger middleware
     app.use(bodyParser.urlencoded({extended: false})); // Parsing body middleware
     app.use(bodyParser.json({limit: '500mb'})); // Parsing JSON objects
     // Adding headers
     app.use((req, res, next) => {
     res.header('Access-Control-Allow-Origin', '*'); // Allowing reqeusts from everywhere
     res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,
     Authorization');
     if (req.method === 'OPTIONS') {
     res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
     return res.status(200).json({});
     }
     next();
     });
     // Detecting routes
     app.use('/user', usersRoutes);
     app.use('/product', productsRoutes);
     // Handling invalid routes
     app.use((req, res, next) => {
     const error = new Error('Not found');
     error.status = 404;
     next(error);
     });
     app.use((error, req, res, next) => {
     res.status(error.status || 500);
     res.json({
     error: {
        message: error.message
     }
     });
     });
     module.exports = app;


text:
Q: How to compare two hashmaps in java? I have two hash maps like the following:
1.=============Employee=================

Key : 1_10 : Value : 13/04/2012
Key : 1_11 : Value : 18/04/2012
Key : 1_12 : Value : 19/04/2012
Key : 1_14 : Value : 23/04/2012
Key : 1_13 : Value : 20/04/2012
Key : 1_16 : Value : 25/04/2012
Key : 1_1  : Value : 02/04/2012
Key : 1_15 : Value : 24/04/2012
Key : 1_18 : Value : 27/04/2012
Key : 1_3  : Value : 04/04/2012
Key : 1_17 : Value : 26/04/2012
Key : 1_2  : Value : 03/04/2012
Key : 1_5  : Value : 06/04/2012
Key : 1_19 : Value : 30/04/2012
Key : 1_4  : Value : 05/04/2012
Key : 1_7  : Value : 10/04/2012
Key : 1_6  : Value : 09/04/2012
Key : 1_9  : Value : 12/04/2012
Key : 1_8  : Value : 11/04/2012

2.=============Working day=================

Key : 27 : Value : 27/4/2012
Key : 02 : Value : 02/4/2012
Key : 26 : Value : 26/4/2012
Key : 19 : Value : 19/4/2012
Key : 11 : Value : 11/4/2012
Key : 04 : Value : 04/4/2012
Key : 30 : Value : 30/4/2012
Key : 06 : Value : 06/4/2012
Key : 13 : Value : 13/4/2012
Key : 09 : Value : 09/4/2012
Key : 03 : Value : 03/4/2012
Key : 23 : Value : 23/4/2012
Key : 20 : Value : 20/4/2012
Key : 16 : Value : 16/4/2012
Key : 10 : Value : 10/4/2012
Key : 18 : Value : 18/4/2012
Key : 25 : Value : 25/4/2012
Key : 17 : Value : 17/4/2012
Key : 12 : Value : 12/4/2012
Key : 24 : Value : 24/4/2012
Key : 05 : Value : 05/4/2012

Keys are not same but the values are same and sometime the values are not same.
i want to find out the value which are not present in employeemap when  comparing with workingdaymap
if (!employeeMap.containsValue(workingdayMap.get(wKey))) {
    //take the value which is not present in employeeMap which is present in workingdayMap
}

but it gives me null from employeeMap.
Could you please help me to solve this?
Regards
Tony

A: Are the Values Date objects? If so you're attempting to see if the map contains the same object (well its hash, which will be different unless you stored the EXACT same instance in both maps) rather than the value of the object.

A: Something like this should work:
Set workingValues = new HashSet(workingdayMap.values());
workingValues.removeAll(employeeMap.values());

We get all the values out of workingdayMap using the values() method.  We don't want to modify this Collection directly as this will modify workingdayMap so we create a Set of our values called workingValues.
We then remove all the values found in employeeMap which will leave the values which are in workingdayMap but not in employeeMap in workingValues.

A: Can you please try like this.
    HashMap<String, Date> employeeMap = new HashMap<String, Date>();

    HashMap<String, Date> workingdaymap = new HashMap<String, Date>();

    Set<String> values1 = new HashSet<String>(employeeMap.values());
    Set<String> values2 = new HashSet<String>(workingdaymap.values());
    boolean equal = values1.equals(value2);

A: below is the code which works perfectly, the reason why the comparison failed is the map value is different .
Key : 27 : Value : 27/4/2012, Key : 1_18 : Value : 27/04/2012

if we see the dates, the difference is clearly seen.  27/4/2012 is different from  27/04/2012 since i stored it as a string.
Iterator<Map.Entry<String,String>> holyDayiterator = workingdayMap.entrySet().iterator();

                 while (holyDayiterator.hasNext()) {
                    Map.Entry holiDayEntry = holyDayiterator.next();
                    if(!employeeMap.containsValue((holiDayEntry.getValue()))){
                        System.out.println("works perfect");
                    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: vba - error when working with worksheet situated in a closed workbook I would like to work on a worksheet situated in another excel file without opening it. To do that, I use an Excel.Application object instead of a workbook object
I need to sort that worksheet by 2 columns with the sub program trieTableau2Colonne(ByRef w As Worksheet, ByRef colonne1, ByRef colonne2)
When I give any worksheet (ActiveWorkbook.Worksheets, or worksheet in a open workbook declared with a workbook object), it is working perfectly. But when I use an Excel.Application object to work on a closed workbook, it does not work.
The error is about the SortFields object of the Add method.
Below, you can see the sub procedure that I wrote, the main program and also a screenshot to show you the error.
An error occurs at the second line of the trieTableau2Colonne procedure (w.Sort.SortFields.Add). I put a spy in the w variable to see what there is inside.
In the second screenshot, we can see the difference between 2 worksheets I use.

*

*ws_cible is a worksheet object obtained from a workbook object
Dim ws_cible As Worksheet

Set ws_cible = ThisWorkbook.Worksheets("Liste Réclas")

-->we can read that its type is Worksheet/Feuil1

*w is a worksheet object but obtain from an Excel.Application object instead of a workbook object
Dim wb_src As Excel.Application
Set wb_src = CreateObject("Excel.Application")

Set ws_src = wb_src.Worksheets("Sheet1")

-->we can read that its type is Worksheet/Worksheet
I am convinced that the problem come from that difference but I do not see any difference in the properties or the methods of each object.
Sub trieTableau2Colonne(ByRef w As Worksheet, ByRef colonne1, ByRef colonne2)

  w.Sort.SortFields.Clear
  w.Sort.SortFields.Add Key:=Range((colonne1 & ":" & colonne1)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
  w.Sort.SortFields.Add Key:=Range( _
    (colonne2 & ":" & colonne2)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
  With w.Sort
    .SetRange Range("A:AZ")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
  End With
End Sub

' main program'

    Dim ws_src As Worksheet
    Dim wb_src As Excel.Application
    Set wb_src = CreateObject("Excel.Application")
    ChDir Workbooks(ActiveWorkbook.Name).Path
    stfile = Application.GetOpenFilename

    If stfile = False Then
        Exit Sub
    End If
    With wb_src
        .Workbooks.Open (stfile)
        .Visible = False
    End With
    Set ws_src = wb_src.Worksheets("Sheet1")
    'MsgBox (ws_src.Cells(1, 1).Value)
    Call trieTableau2Colonne(ws_src, "E", "B")

IDE window screenshot

variable watch window screenshot

A: In this code, you reference Worksheet before you open a workbook. You can't get a Worksheet from Excel.Application. You get a Worksheet from a Workbook object.
Dim wb_src As Excel.Application
Set wb_src = CreateObject("Excel.Application")

Set ws_src = wb_src.Worksheets("Sheet1")

Try adding wb_src.Workbooks.Open() or wb_src.Workbooks.Add() before you reference a Worksheet.

A: Thank you for your answer.
Indeed, in my main program I have well opened the workbook
With wb_src
  .Workbooks.Open (stfile)
  .Visible = False
End With

I can see that I access correctly to that file by putting a msgbox to check a the content of a cell inside and it works well :
MsgBox (ws_src.Cells(1, 1).Value)


text:
Q: Gremlin - wait for schema.drop() to finish before executing next line of script I'm trying to run a Gremlin schema creation script against our Datastax DSE Graph database, and the first line of the script is schema.drop(), but the script seems to immediately go to the next line in the script and throws an error saying the new object it's trying to create is still there.  Normally the schema.drop() takes about a minute or so, so it looks like it isn't waiting for it to finish dropping the schema before running the next line of script.
Is there a way to force the script to wait after the schema.drop() line and let it finish dropping the schema before trying to run the next line of script to create the new schema?

A: The general recommendation I have given is to avoid making schema changes programatically because it has often been problematic in the enterprises I have worked with. If you provide the details of how you have scripted it, I'd be happy to review it and revise my response.
I am note aware of adding a pause or wait in Gremlin but a possible workaround is to break up your operation so that the schema.drop() is performed independent of the rest of the schema creation. With this workaround, you can either (a) manually pause between operations, or (b) if you are running shell scripts then add a sleep in between.
One thing to note is that it's important to perform checks when making schema changes to make sure that each DDL is successful prior to executing the next DDL. Cheers!
P.S. I've reached out to the Graph team here at DataStax for the recommended way of handling this.


text:
Q: Jasper reports pdf export java I am sort of new to jasper reports, I'm trying to call a .jrxml I have already created and compiled but I'm getting this record when trying to read the .jrxml Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException
here is my code:
private void saveAsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
    JasperPrint jp;
    JasperReport jr;
    try {
        Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Database", "user", "password");

        jr=JasperCompileManager.compileReport("Reports/Cierre de Caja.jrxml");

        jp=JasperFillManager.fillReport("Reports/Cierre de Caja.jasper", new HashMap(), con);
        System.out.println("got jasper");
        JasperViewer jv=new JasperViewer(jp);
        jv.setVisible(true);
    }
    catch (JRException e){
        System.out.println("Jasper: "+e.getLocalizedMessage());
    }
    catch (SQLException e){
        System.out.println("SQL: "+e.getLocalizedMessage());
    }
}

A: I'm using maven, so adding groovy as a dependency made the trick
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>2.4.10</version>
</dependency>


text:
Q: Cannot convert Array into String (Ruby) I'm having trouble with this code (again).
I'm trying to get Ruby to check if tree is equal to any of the items in $do_not_scan and all I'm getting is a "cannot convert Array into String" error. Any way to fix such a thing?
My code:
#filesniffer by Touka, ©2015
$filecount = 0
$trees = Dir.entries("C:\\")
$do_not_scan = ["bootmgr", "BOOTNXT", "USER", ".", "Documents and Settings", "PerfLogs", "System Recovery", "System Volume Information", "$RECYCLE.BIN"]
def scan
    $trees.each do |tree|
        unless tree.include?($do_not_scan[0...8])
            puts "scanning #{tree}"
            entries = Dir.entries("c:\\#{tree}")
            entries.each do |filename|
                if filename == "**\*.dll"
                    puts "Found #{filename} in #{tree}"
                end
            end
        end
    end
end
def scan_loop
    $trees.each do |tree|
        scan
        unless tree.include?($do_not_scan[0...8])
            subtrees = Dir.entries("#{tree}")
            subtrees.each do |tree|
                scan
                scan_loop
            end
        end
    end
end
scan_loop
sleep

A: It looks like the following have to change in the scan and scan_loop methods:
$do_not_scan[0...8].include?(tree)

In place off:
tree.include?($do_not_scan[0...8])


text:
Q: How to structure classes such that I can easily inherit from a "Persistor" class which pickles the inherting object? I'm writing a new library and I want to persist some objects. I want to use a mixin or some sort of adapter so I don't have to implement a database right away. I'm using pickle right now to store objects.
Let's say I have a User class. I want to load a User from the folder if the pickle exists. I wrote a Persistor class which takes an object and writes it to a specified location. Do I make the User class inherit from the Persistor class? If so, when the User class is instantiated, how then do I replace the object with the loaded object if a pickle eists? Or do I create a UserPersistor class? I'm simply looking to abstract away the loading and saving of state from the User class.
class User(Persistor???):
    """
    Central class to hold all user attributes and relationships.
    """

    def __init__(
        self,
        first_name: str,
        username: str,
        date_of_birth: datetime.date
    ):
        self.first_name = first_name
        self.username = username
        self.date_of_birth = date_of_birth

import pickle
import os

class Persistor:
    """
    Class whose job is to save and load state until we need a database.
    """

    def __init__(
        self,
        persistence_key
    ):
        self.persistence_key = persistence_key
        self.persistence_path = "data/" + persistence_key

    @property
    def save_exists(self):
        return os.path.exists(self.persistence_path)

    def save(self):
        outfile = open(self.persistence_path, 'wb')
        pickle.dump(self, outfile)
        outfile.close()

    def load(self):
        if self.save_exists:
            infile = open(self.persistence_path, 'rb')
            db = pickle.load(infile)
            infile.close()
            return db

    def delete(self):
        if self.save_exists:
            os.remove(self.persistence_path)

A: Simple answer (and it's nothing Python-specific FWIW, this is just plain OO design): semantically, inheritance denotes a "is a" relationship - so if B inherits from A, then B is a A too (cf the Liskov substitution principle too). So the real question is: would you consider that a User is a Persistor ?
Another common, sensible and widely accepted design principle is the single responsability principle, which states that each component should have a single, well-defined responsability. So ask yourself if you really want persistance implementation details to become part of your User class responsabilities...
As for a last couple OO design guidelines, which are repeated all over the (long) introduction of the GoF's "Design patterns" book (actually one of the best texts on OO design FWIW - the introduction I mean, even if the patterns catalog is of interest too): you should favor composition/delegation over inheritance (inheritance being, technically speakin, a restricted form of composition/delegation), and you should always program to an interface ("interface" in the Java term - in most languages this means an abstract base class), never to an implementation (a concrete class). By combining both, you get well decoupled code that's easy to test, maintain and evolve. For example, if you make your User class inherit from Persistor (which is a concrete class), you cannot easily switch to other Persistor implementation, while if you use composition/delegation and an abstract base class defining the only the Persistor API, you can (theoretically...) use any Persistor implementation  your User class.
Now that's for the theory, and reality is that some abstractions tend to be kind of leaky - for example, to be persisted using the pickle protocol, your User class has to be pickleable, so this is not totally transparent, so take the above principles with a grain of salt - more as food for thought than golden rules, that is. As far as I'm concerned I would probably use composition/delegation as the safest choice here, and eventually reconsider the whole design during implementation progress, as implementation often hilights design flaws (if you can spot them at least).
EDIT

From what I recall, you don't need to use interfaces in Python due to multiple inheritance. Does that change the "is a" rule just for Python?

Actually, inheritance serves two purposes: subtyping (as explained above), but also code reuse - which is why the GoF describes inheritance as "a restricted form of composition/delegation" (in that the child class has a reference to it's parent(s) and automagically delegates parts of it's operations).
Subtyping is a very important part of OO, since it forms the basis for generic code and polymorphic dispatch - so a given piece of code can work just the same with a collection of objects that are from different concrete type (implementation), as long as they implement the same interface.
Semantically, an "interface" is a defined set of (public) features (methods, attributes, properties etc). Now how an interface is technically defined depends on the language.
Statically typed languages need a formal definition of the interfaces a class implements so it can perform compile-time checks and eventually optimizations. Note that I wrote "interfaceS" - a class can implement more than one single interface, and that's actually a rather common case.
For (static) languages that support multiple inheritance, the obvious solution is to use abstract base classes for interface definitions. Java doesn't support multiple concrete inheritance (that's a design choice) so it has a distinct construct named "interfaces" - but it's really another name for pure abstract base classes ("pure": only definitions, no implementation at all)
In dynamic languages, there's actually no (technical) need for formal interface definitions (since there's no formal typechecking), so "interfaces" are quite often informal - you'll often find in dynamic languages docs terms like "list-like", "file-like" etc (to denote objects that behaves like lists or files).
Now while this works well in practice (most of the times at least), there are still good things to be said about formal interface definitions, if only for documentation (and also for the cases where simple polymorphic dispatch is not enough and you have to inspect your objects to find out what you should do with them - think recursing over a structure of arbitrarly nested dicts and lists of various objects) - so Python also have abstract base classes, and they are actually recommended for any non-trivial project.
In all cases, the "is a" relationship still holds to a certain degree (even if the child class is not necessarily a proper subtype according to Liskov's definition) since a subclass does inherit it's parent(s) class(es) implied interface(s).
NB : Python also have "protocols", which are more formally defined sets of special methods a class can implement and that will give instances of this class some special behaviours (cf descriptors or iterators).

Can I have my User inherit from object and Persistor and that would be python's way of saying that it gets that functionality?

Well of course yes you can - there's no technical restriction on this, it's just a design question: should your User class also BE a Persistor, or would it be "better" (depending on the definition of "better") to have two clearly distinct classes - one for the domain model (User), and a technical one for persistance (UserPersistor for example).

If I delegate the persistence logic to the Persistor class, I still need to call that from my User class code

Not necessarily... If you decide that persistance is not the User's responsability, then you can just see things the other way round: it's the Persistor that calls on your User object -and in this case, you actually don't even need composition/delegation at all.
If you got yourself the GoF, I strongly suggest you take some time reading it before you go on with your design decisions, paying attention to the first part. Just a warning though : once you're done, avoid the tentation to use each and all of the patterns in your project, always ask yourself if it makes sense for the concrete problem at hand and whether the extra complication (if any) will ever be of any use for this particular part of your code ;-)


text:
Q: QGIS GPS Connection with PyQgis causes minidump After some experimenting and reading source codes I tried to connect to my GPS device as follows (from a QGIS plugin):
self.pushButton_conGPS.clicked.connect(self.connectGPS)

[...]
def connectGPS(self):
    port = u'\\\\.\\COM4'
    #port = u'localhost:2947:'
    self.detector = QgsGPSDetector(port)
    print 'detected, connection functions'
    self.detector.detected[QgsGPSConnection].connect(self.connectionSucceed)
    print '---'
    self.detector.detectionFailed.connect(self.connectionFailed)
    print 'advance'
    self.detector.advance()

def connectionSucceed(self, connection):
    print 'connection Succeed'
    QgsGPSConnectionRegistry.instance().registerConnection(connection)
    print QgsGPSConnectionRegistry.instance().connectionList()[0].currentGPSInformation().utcDateTime.toString()

def connectionFailed(self):
    print 'connection failed.'

Pressing my above referred button results in

Note the output on the python console, minidump occurs at QgsGPSConnectionRegistry.instance().registerConnection(connection)
Related post: Connect / Disconnect GPS device via PyQGIS
What is it that causes the minidump? I think similiar c++ code of the GPS Information panel works pretty well...


text:
Q: how many hidden layers are required in neural network if i have 1600 input in input layer? I am working on image processing project. In which, I have to recognize a text from image. So I have segmented the image in letters image. So, I have image of 40*40. So, I am giving a input of 1600 pixels. So can anyone suggest me, how many hidden layers are required? And also suggest, how many neurons are required in hidden layer?

A: It depends. Are you going to use a convolutional network or a regular fully connected network?
But for either - you have to really find this through trial and error. We have no idea about the complexity of your images, and the size of the text.
What have you tried? 1600 inputs is not too much so you could easily run some testcases (start with óne layer of 60 neurons perhaps).

A: As @Thomas W said, it depends. But there are some experiences you could refer to.

*

*How many hidden layers should I use?

*How many hidden units should I use?


text:
Q: Equation of a straight line Why is the image of $g(w)=\log\left({1+w\over 1-w}\right)$ for $0<\arg(w)<\pi$ all lie on a straight line?
Sorry about the confusing statement in the beginning.

A: By the open mapping theorem, since $\log({1 + w \over 1 - w})$ is analytic, the image of any open set under $\log({1 + w \over 1 - w})$ will be open and therefore not be on a line.
So I'll guess you mean just the image of the $0 < arg(w) < \pi$ portion of unit circle $|w|= 1$ under this map. In that case, write $w = e^{i\theta}$. Then
$${1 + w \over 1 - w} = {1 + e^{i\theta} \over 1 - e^{i\theta}}$$
$$ = {e^{i\theta \over 2} + e^{-{i\theta \over 2}} \over {e^{i\theta \over 2} - e^{-{i\theta \over 2}}}} $$
$$= -i\cot({\theta\over 2})$$
Taking logs of this you get $\ln(\cot({\theta \over 2}))-i{\pi \over 2}$. This is on the line $y = -i{\pi \over 2}$ in the complex plane.

A: My notation is a bit different from yours,
and you would do well to check this for mistakes,
but here's what I have so far.
We are taking the complex logarithm of a linear fractional
or Möbius transformation, so there is probably a good
geometric-complex analytic perspective on our function.
If $w=g(z)=\log\left(\frac{1+z}{1-z}\right)$
and $z=re^{i\theta}$, so that $\theta=\arg z$,
then
$$
e^w=\frac{1+z}{1-z}\quad\implies\quad
z=\frac{e^w-1}{e^w+1}=\sinh\tfrac{w}{2}.
$$
If we treat $w=u+iv$ as a function from
$(r,\theta)\in R$ to $(u,v)\in R$ for
$R=[0,\infty)\times(-\pi,\pi]\subset\mathbb{R}^2$,
then
$$
e^u(\cos v+i\sin v)=
e^w=
\frac{
(1-r^2)+i(2r\sin\theta)
}{
(1+r^2)-(2r\cos\theta)
}.
$$
Note that the denominator is always nonnegative
since it equals $(1\mp r)^2$ for $\cos\theta=\pm1$.
Furthermore,
$$
e^u=|e^w|
=\frac{\sqrt{(1-r^2)^2+(2r\sin\theta)^2}}{1+r^2-2r\cos\theta}
=\sqrt{\frac{1+r^2+2r\cos\theta}{1+r^2-2r\cos\theta}}
$$
and
$$
\tan v=\frac{2r\sin\theta}{1-r^2},
\qquad
\sin v=\frac{2r\sin\theta}{R}
\quad
\&
\quad
\cos v=\frac{1-r^2}{R}
$$
for
$$
R^2
=(1+r^2)^2-(2r\cos\theta)^2
=(1-r^2)^2+(2r\sin\theta)^2
=1+r^4-4r^2\cos2\theta.
$$
If we are expecting the image of $g$
to be a straight line for $\theta\in(0,\pi)$,
that would mean that some linear combination of $u$ and $v$ is constant,
or that $\frac{\partial u}{\partial \theta}$
and $\frac{\partial v}{\partial \theta}$ are proportional,
or that $\frac{du}{dv}$ (or its reciprocal) is constant.
I got
$$
\frac{\partial u}{\partial \theta}=
\frac{4r^2\sin\theta\cos\theta}
{(1+r^2)^2-(2r\cos\theta)^2}
$$
and
$$
\frac{\partial v}{\partial \theta}=
\frac{2r(1-r^2)\cos\theta}
{(1+r^2)^2-(2r\cos\theta)^2}
$$
or
$$
\frac{du}{dv}=\frac{2r}{1-r^2}\sin\theta=\tan v,
$$
which would give
$$
u=\int du=\int\tan v\,dv=-\ln|\cos v|+c_1
\quad\implies\quad
e^u \cos v=\text{constant}
$$
and contradicts what we already have above, namely
$$
e^u \cos v = \frac{ 1-r^2 }{ 1+r^2-2r\cos\theta }
$$
which exhibits a dependence on $\theta$.
So there must be an error in this somewhere
(can anyone find it?).
However, when $r=1$, we have $\frac{dv}{du}=0$,
which is a horizontal line (or a symmetric square wave
on $(-\pi,\pi)$ with dirac/delta derivative)
$v=\pm\frac{\pi}{2}$ (with the same sign as $\theta$).
I have checked some of this symbolically and graphically
in a sage workbook, published here.


text:
Q: Print backwards in c++ Here is a program where I enter a sentence and print it backward...
#include<iostream>
#include<string>
using namespace std;

int main(int argc, char* argv[]) {
    string scrambleWords;
    cout << "Please enter a sentence to scramble: ";
    getline(cin, scrambleWords);

    for (int print = scrambleWords.length() - 1; print >= 0; print--)
    {
        if (isspace(scrambleWords[print]))
        {
            for (unsigned int printIt = print + 1;
                         printIt < scrambleWords.length(); printIt++)
            {
                cout << scrambleWords[printIt];
                if (isspace(scrambleWords[printIt]))
                    break;
            }
        }
    }

    for (unsigned int gotIt = 0; gotIt < scrambleWords.length(); gotIt++)
    {
        cout << scrambleWords[gotIt];
        if (isspace(scrambleWords[gotIt]))
            break;
    }
    cout << endl;
}

// OUTPUT
// Please enter a sentence: birds and bees
// beesand birds
// Press any key to continue . . .

As you can see there was no space between bees & birds, so how can I add the space in there?

A: The cleanest and easiest solution is to rely on the standard libraray:
// 1. Get your input string like you did

// 2. Save the sentence as vector of words:
stringstream sentence {scrambleWords};
vector<string> words;
copy(istream_iterator<string>{sentence},istream_iterator<string>{},
    back_inserter(words));

// 3 a) Output the vector in reverse order
for (auto i = words.rbegin(); i != words.rend(); ++i)
    cout << *i << " ";

// 3 b) or reverse the vector, then print it
reverse(words.begin(),words.end());
for (const auto& x : words)
    cout << x << " ";

A: You may use something like (C++11 for auto): (http://ideone.com/mxOCM1)
void print_reverse(std::string s)
{
    std::reverse(s.begin(), s.end());
    for (auto it = s.begin(); it != s.end(); ) {
        auto it2 = std::find(it, s.end(), ' ');
        std::reverse(it, it2);
        it = it2;
        if (it != s.end()) {
            ++it;
        }
    }
    std::cout << s << std::endl;
}

A: Add a space when you reached the end of the original input line:
if printIt == scrambleWords.length()-1
    cout << " ";

Put this code in the inner for loop, after
if (isspace(scrambleWords[printIt]))
    break;

Note that breaking out of a for loop is not going to win you any programming beauty contests.


text:
Q: How to place labels to the right in Bootstrap 5 I would like to know, how I could place the labels to the right in Bootstrap 5 and correctly place the button at the same alignment as the inputs, please?
I thank you in advance for your explanations.

<!DOCTYPE html>

      <title>HTML CSS JS</title>

   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

Title

         <form>

                  Portfolio holder
                  <input type="text" class="form-control" name="exampleInputEmail1" style="width: 70%" aria-describedby="emailHelp" required>

                  Country
                  <select class="form-select">
                     <option>Belgium</option>
                     <option>France</option>
                     <option>Italy</option>
                  </select>

                  Client file number
                  <input type="text" class="form-control" name="exampleInputEmail1" style="width: 70%" aria-describedby="emailHelp" required>

                  Type of account
                  <select class="form-select">
                     <option >All agencies</option>
                     <option>ATH - Ath</option>
                     <option>BAU - Baudour</option>
                  </select>

            <button type="submit" class="btn btn-primary">Opening an account</button>
         </form>

A: Here you go...
Add this to all your label classes: d-flex justify-content-end align-items-end pe-3
To explain you shortly:

*

*d-flex is essential in order for justify-content- and align-items- to work

*justify-content-end moves your labels to the right

*align-items-end moves your labels down so that they're aligned with forms

*pe-3 sets padding-right

<!DOCTYPE html>

  <meta charset='UTF-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Document</title>
  <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css' integrity='sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU' crossorigin='anonymous'>

Title

    <form>

          Portfolio holder
          <input type="text" class="form-control" name="exampleInputEmail1" style="width: 70%" aria-describedby="emailHelp" required>

          Country
          <select class="form-select">
            <option>Belgium</option>
            <option>France</option>
            <option>Italy</option>
          </select>

          Client file number
          <input type="text" class="form-control" name="exampleInputEmail1" style="width: 70%" aria-describedby="emailHelp" required>

          Type of account
          <select class="form-select">
            <option>All agencies</option>
            <option>ATH - Ath</option>
            <option>BAU - Baudour</option>
          </select>

      <button type="submit" class="btn btn-primary">Opening an account</button>
    </form>


text:
Q: /system/bin/app_process stack corruption detected: aborted ? What is this? I'm running some native code, and there are many JNI calls
Application crashes without a clue on why its crashing except for the message /system/bin/app_process stack corruption detected: aborted in logcat if I try to debug
How to go about nailing culprit in this case? Any one ou there who can help here

A: I am not an expert of C/C++, and ran into a similar problem in NDK.(App crash with a log: "/system/bin/app_process stack corruption detected: aborted").
I find out the cause of my error is array access violation.
Just in case someone new like me run into this issue, following are some common mistakes:
1.
char  aa[6];
strcpy(aa,"abcdefghijk123457890");//out of bounds

2.
char aa[6];
sprintf(aa,"the value is : %d", 123);//out of bounds


text:
Q: Join and Grouping Results Summary; Joining some of tables has similar results by some columns. How can we group them and select max(column).
My query is;
SELECT DISTINCT TOP (1000) LG_070_ITEMS.CODE AS PRODCODE,
                LG_070_01_SERILOTN.CODE AS CODE,
                LG_070_01_SLTRANS.OUTCOST,
                LG_070_01_SLTRANS.LOGICALREF AS LREF,
                LG_070_01_SLTRANS.INSLTRANSREF,
                LG_070_01_SLTRANS.INVENNO,
                LG_070_01_SLTRANS.INTRANSREF,
                LG_070_01_SLTRANS.STTRANSREF
FROM LG_070_01_SERILOTN
INNER JOIN LG_070_01_SLTRANS ON LG_070_01_SLTRANS.SLREF = LG_070_01_SERILOTN.LOGICALREF
INNER JOIN LG_070_ITEMS ON LG_070_ITEMS.LOGICALREF = LG_070_01_SERILOTN.ITEMREF
WHERE [TIGERDB].[dbo].[LG_070_01_SERILOTN].CODE = '868328002749220'

And also answer from database is;
Prodcode code---------------COST--LREF ------one twho three four
K-3773  868328002749220 50,85   46255------- 0    10    0   33584
K-3773  868328002749220 50,85   46504-------    46255   10  33584   33639
K-3773  868328002749220 50,85   46524-------    46504   11  33639   33640
K-3773  868328002749220 50,85   51273-------    46524   11  33640   38581
K-3773  868328002749220 50,85   51285-------    51273   9   38581   38587
K-3773  868328002749220 50,85   52275-------    51273   11  38581   39823
K-3773  868328002749220 50,85   52276-------    52275   9   39823   39824
And now my problem is, how can i select last row. It can be bigger of LREF Column or column-one.
My queries are same. I am using numbers in where stuation and results are as same as this one.
I Tried to use max(columname) with group by othercolumns etc.
I used query designer with microsoft sql server management tool.
In that three table, non-selected columns are not important for me.With mysql i can do this with select ...max(lref) from ... joins ... group by code but i must do this with mssql.

A: Query (Probably will be expensive):
SELECT DISTINCT TOP (1000) t3.CODE AS PRODCODE,
                t.CODE AS CODE,
                t2.OUTCOST,
                t2.LOGICALREF AS LREF,
                t2.INSLTRANSREF,
                t2.INVENNO,
                t2.INTRANSREF,
                t2.STTRANSREF
FROM LG_070_01_SERILOTN t
INNER JOIN LG_070_01_SLTRANS t2 ON t2.SLREF = t.LOGICALREF
INNER JOIN LG_070_ITEMS t3 ON t3.LOGICALREF = t.ITEMREF
WHERE t.CODE = '868328002749220'
AND t2.LOGICALREF = (SELECT MAX(tt2.LOGICALREF)
                         FROM LG_070_01_SERILOTN tt
                         INNER JOIN LG_070_01_SLTRANS tt2
                          ON tt2.SLREF = tt.LOGICALREF
                         INNER JOIN LG_070_ITEMS tt3
                          ON tt3.LOGICALREF = tt.ITEMREF
                          WHERE tt.CODE = t.CODE)

Example query SQLFIDDLEExample:
SELECT DISTINCT TOP (1000) t.*
FROM Table1 t
WHERE t.LREF = (SELECT MAX(tt.LREF)
                FROM Table1 tt
                WHERE tt.CODE = t.CODE)

Result:
| PRODCODE |            CODE |  COST |  LREF |   ONE | TWHO | THREE |  FOUR |
-----------------------------------------------------------------------------
|   K-3773 | 868328002749220 | 50,85 | 52276 | 52275 |    9 | 39823 | 39824 |


text:
Q: getrusage returns rounded numbers I am trying to measure the resource usage time (user and system) for various function calls using rusage.
I find that the results I am getting are in the order of 10s of milliseconds like 0s 70000us, 10000us etc. Please let me know if there is a way to set precision/ granularity for getrusage.
My program is simple:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>

int main(){
  struct rusage usage;
  struct timeval start, end;
  int i, j, k = 0;

  getrusage(RUSAGE_SELF, &usage);
  start = usage.ru_utime;
  printf("buffer check\n");
  char *str = "---";
  int arr[100],ctr;

  for(ctr = 0;ctr<100;ctr++){

    arr[ctr] = ctr + 1000;

  }

  for (i = 0; i < 10000; i++) {
     for (j = 0; j < 10000; j++) {
      k += 20;
  }
 }

 getrusage(RUSAGE_SELF, &usage);
 end = usage.ru_utime;

 printf("Started at: %ld.%lds\n", start.tv_sec, start.tv_usec);
 printf("Ended at: %ld.%lds\n", end.tv_sec, end.tv_usec);

 return 1;
}

Result
Started at: 0.0s
Ended at: 0.2000000s
I added another for loop and got result like:
Started at: 0.0s
Ended at: 0.7000000s
I browsed a lot to find a possible way to get accurate timings. Came across 3 parameter getrusage in linux sources etc. but I am not sure how to use it since it required the task pointer as the first param. One of the link suggested it has got to do with linux version. Regardless, please let me know if there is any way to set the precision/granularity. If not, let me know if there is any alternative to getrusage. gettimeofDay does not seem to give the resource usage details so looking for actual implementation of getrusage if somehow I am not able to set precision.

A: Many operating systems don't do precise accounting of time used by processes. In many cases it's too expensive to read clocks on every context switch and system call, in other cases the hardware might not even have a clock that's allows you to time things with any precision.
A very commonly used method for accounting that you get from getrusage is to have a 100Hz (it's most often 100Hz, although 64Hz and 1024Hz are common too) timer interrupt that samples what's happening on the system at the time of the interrupt. So 100 times per second the kernel checks what is currently running and where (user space for ru_utime or kernel space for ru_stime) and increments a counter. That counter is then interpreted as your program running for 10ms.
You can experiment with clock_gettime on your system, see if it has per-process counters, sometimes those can be more precise than the getrusage counters. But I wouldn't get my hopes up, if 10ms resolution is the best getrusage can do, it's likely that clock_gettime won't have a better resolution either or any per-process clocks at all.
If the clocks in the operating system aren't good enough for your measurements your only option is to repeat your test run for several minutes and divide whatever result you get by the number of runs.
The fact that gettimeofday is more precise doesn't mean much. gettimeofday might be relatively expensive. Think about the work the kernel would have to do to accurately keep track of user and system time for a process. Every time you make a system call it would have to take a time stamp twice (one for the start of the system call and once at the end) just to keep track of how much system time you use. For keeping track of user time you'd need time stamps on every time the system switches to another process. Many systems do keep track of the second one, but not the first one since system calls are much more common than process context switches (that's why I suggest checking clock_gettime since it can have a timer that accumulates total system and user time for a process).
Clocks in modern systems are quite annoying because even though taking time stamps is one of the most common system calls we still often need to trawl through a slow bus and do heavy locking to get them. Other solutions like cycle counters on the cpu have been used but those are notoriously inaccurate because they might be not synchronized between CPUs, might have a variable frequency, can stop outside of the control of the operating system, etc. and you need to know the exact model of your CPU to be able to reliably use them. The operating system has a lot of heuristics to figure out which clocks to use, but it might mean that there's a huge difference between two machines that are almost the same. One might get a cycle counter with sub-nanosecond precision that costs one instruction to read while the other needs to go through the ISA bus to a 30 years old chip design with microsecond precision or worse which takes thousands of cycles to read.

A: My new program:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
//int clock_gettime(clockid_t clk_id, struct timespect *tp);

#define BILLION  1000000000L;

void testClockGetTime(clockid_t clk_id , struct timespec *start , struct timespec  *stop){

   long temp = 0,i;
   unsigned long accumsec,accumns;
   if( clock_gettime( clk_id, start) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
   }
   for ( i = 0; i< 24222000; i++)
       temp+=temp;

   if( clock_gettime( clk_id, stop) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }
    accumsec = stop->tv_sec - start->tv_sec;
    accumns =  stop->tv_nsec - start->tv_nsec;
    if(stop->tv_nsec<start->tv_nsec){
       accumsec = accumsec - 1;
       accumns = start->tv_nsec - stop->tv_nsec;
    }

    printf( " sec %ld\n", accumsec );
    printf(" ns %ld\n", accumns );

  }

int main( int argc, char **argv )
 {
   struct timespec start, stop;
   struct timeval tds,tdse;
   memset(&tds,0,sizeof(struct timeval));
   memset(&tdse,0,sizeof(struct timeval));
   unsigned long accumsec,accumns;
   long timesec, timeusec;
   printf("checking on various timers gives by clockGetTime \n");
   printf("cpu time\n");
   memset(&stop,0,sizeof(struct timespec));
   memset(&start,0,sizeof(struct timespec));
   testClockGetTime(CLOCK_PROCESS_CPUTIME_ID , &start,&stop);
   memset(&start,0,sizeof(struct timespec));
   memset(&stop,0,sizeof(struct timespec));
   printf("real time\n");
   testClockGetTime(CLOCK_REALTIME,&start,&stop);
   memset(&start,0,sizeof(struct timespec));
   memset(&stop,0,sizeof(struct timespec));
   printf("monotonic\n");
   testClockGetTime(CLOCK_MONOTONIC,&start,&stop);
   memset(&start,0,sizeof(struct timespec));
   memset(&stop,0,sizeof(struct timespec));
   printf("thread\n");
   testClockGetTime(CLOCK_THREAD_CPUTIME_ID,&start,&stop);
   memset(&start,0,sizeof(struct timespec));
   memset(&stop,0,sizeof(struct timespec));
   gettimeofday(&tds, NULL);
   long temp,i;
   for ( i = 0; i< 24222000; i++)
      temp+=temp;
   gettimeofday(&tdse, NULL);
   if( clock_gettime( CLOCK_PROCESS_CPUTIME_ID, &stop) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }

    //   accumsec = stop.tv_sec - start.tv_sec;
    //   accumns =  stop.tv_nsec - start.tv_nsec;
    //   if(stop.tv_nsec<start.tv_nsec){
    //     accumsec = accumsec - 1;
    //     accumns = start.tv_nsec - stop.tv_nsec;
    //   }

    //   printf( "proc sec %ld\n", accumsec );
    //   printf( "proc ns %ld\n", accumns );
    //    printf("before day =%ld,%ld\n",tds.tv_sec,tds.tv_usec);
    //    printf("after day=%ld,%ld\n",tdse.tv_sec, tdse.tv_usec);
    timesec =  tdse.tv_sec - tds.tv_sec;
    timeusec=  tdse.tv_usec- tds.tv_usec;
  if(tdse.tv_usec < tds.tv_usec){
    timesec = timesec - 1;
    timeusec= tds.tv_usec - tdse.tv_usec;
   }
   printf("daytime sec =%ld\n",timesec);
   printf("daytime usec=%ld\n",timeusec);
   return( EXIT_SUCCESS );
 }

Results:
first run > gcc getclk.c -o dfkj -lrt
getclk.c: In function 'main':
getclk.c:40: warning: incompatible implicit declaration of built-in function 'memset'

./dfkj

checking on various timers gives by clockGetTime
cpu time
sec 0
ns 54502537
real time
sec 0
ns 53748970
monotonic
sec 0
ns 55456758
thread
sec 0
ns 58649229
daytime sec =0
daytime usec=56991
second run>./dfkj
checking on various timers gives by clockGetTime
cpu time
sec 0
ns 54220021
real time
sec 0
ns 52774966
monotonic
sec 0
ns 53636163
thread
sec 0
ns 53357492
daytime sec =0
daytime usec=56176

A: On 2013-10-01 4:48 PM, Saurabh wrote:

Hi Douglas,
  I am Saurabh. I saw your responses at stack overflow . Somehow when I run getrusage, it does not give results in microseconds. But in milliseconds. Please let me know if you have a fix for this. Else kindly suggest me API to replace getrusage.

Yes, getrusage has ms precision on my Linux system as well.  It returns with µs precision only on my OS X workstation.  It says this in my post that you reference, if you look carefully: "The precision on my system is 1 µs, but I also tested it on a Linux system (Red Hat 4.1.2-48 with GCC 4.1.2) and there the precision was only 1 ms."
With regards to your request of an alternate function, I agree with Art. As far as I know, clock_getTime provides by far the best clocks for Linux.  The only issue is that it's relatively new, so it's not very portable (OS X doesn't have it, for example).  Nevertheless, if you want precise timing and you're using Linux, I recommend clock_gettime.


text:
Q: Keyboard layout grayed out? I tried installing the Logitech keyboard layout using this guide.
It appears in the Language Menu, so I added it as a possible layout, but it is grayed out in the Input menu so I can't switch to it.

I am using OS X El Capitan 10.11.3. I downloaded the Logitech layout file from their website, version 3.9.3.
Any idea what the cause of this could be and what I can do to make it work? I have no idea what else to search for to fix this issue.


text:
Q: On the Principle of marginality If we include only the square of a covariable x as an explanatory variable but not x in a glm (glmm) do we violate the  Principle of marginality?

A: This is going to come down to semantics.  The principle of marginality, as I am used to seeing it discussed (and as it is discussed on the Wikipedia page), pertains to interactions between two (or more) different variables.  In your case, you don't have interactions, so that specific term does not apply.  However, I have also seen using power terms to represent curvature as metaphorically described as 'a variable interacting with itself'.  Indeed, this seems almost like a literal truth to me, rather than just a metaphor.  What's important to note here is that the same underlying issues apply, whether or not we want to call it the "principle of marginality".  To see this, it may help to read, Does it make sense to add a quadratic term but not the linear term to a model?, especially, um, @whuber's answer.  Moreover, the underlying issues apply when other methods of trying to capture curvature (e.g., including $\log(X)$ as a variable) where the metaphor of a variable interacting with itself is less obvious.


text:
Q: ffmpegthumbnailer on Windows 10 [Ruby on Rails] Hi I recently startet a Ruby on Rails project on a Windows 10 x64 machine.
In this project I've got an uploadform with Carrierwave to upload some videofiles.
To get a thumbnail from the uploaded videos I want to use the carrierwave-video-thumbnailer gem.
https://rubygems.org/gems/carrierwave-video-thumbnailer
I already installed FFMPEG on my computer.
As I understood correctly, to use the gem I need to install FFMPEGthumbnailer to, but i can't figure out how I can install it on a windows machine.
(Just found installation guides for Linux and OS X)
Did I miss something?
In my uploader file i've got following code:
class VideoUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  include CarrierWave::Video::Thumbnailer

  version :thumbail do
    process thumbnail: [{format: 'jpg', quality: 8, size: 360, logger: Rails.logger}]
    def full_filename for_file
      jpg_name for_file, version_name
    end
  end
  def jpg_name for_file, version_name
    %Q{#{version_name}_#{for_file.chomp(File.extname(for_file))}.jpg}
  end

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def extension_white_list
    %w(mp4)
  end

  def filename
    if original_filename
      @name ||= Digest::MD5.hexdigest(File.dirname(current_path))
      "#{@name}.#{file.extension}"
    end
  end
end

By now the videos are being uploaded succesfully but without thumbnail and without error code.

A: You may be fighting an uphill battle. ffmpegthumbnailer doesn't appear to officially support Windows. However, it looks like at least one person managed to get it to compile in Cygwin. From this issue thread:

I managed to compile it...

*

*download fffmpegthumbnailer 2.0.6†

*apply the two patches here :  https://github.com/dirkvdb/ffmpegthumbnailer/issues/78

*download a working version of moviedecoder.cpp†† :  http://code.google.com/p/ffmpegthumbnailer/source/browse/trunk/libffmpegthumbnailer/moviedecoder.cpp?r=225
replace it in libffmpegthumbnailer folder

*download ffmpeg here : http://www.ffmpeg.org/

*extract and put the folders starting with lib to the lib folder in  cygwin root folder

*./configure then make and make install

*enjoy!

†You can find releases here: https://github.com/dirkvdb/ffmpegthumbnailer/releases
††Since the project has been migrated to GitHub this link is broken and I have no idea which revision of moviedecoder.cpp this link corresponds to. Maybe the version tagged 2.0.7 is a good bet?
Supposing that works for you, once you've compiled it (and confirmed that it works by testing it on the command line) you need to make sure carrierwave-video-thumbnailer knows where to find the executable, either by making sure it's in your $PATH or setting the FFMpegThumbnailer.binary option. I think it'd look something like this:
CarrierWave::Video::Thumbnailer::FFMpegThumbnailer.binary = "C:/path/to/ffmpegthumbnailer.exe"

Note that I haven't tested any of this and your mileage will vary.


text:
Q: Is there a better way to write a vector of strings as a function's optional parameter? I have a function where I want a const std::vector<std::string>* parameter to have a default parameter value of nullptr:
// Definition. Includes a default parameter.
void func(std::vector<std::string>* my_strings = nullptr);

// Call site. Is there a better way?
func(&std::vector<std::string>({"abc"}));

Is there a better way to write an optional vector of strings as a parameter?

A: If func() doesn't need to modify the vector, and you don't need to differentiate between "no vector" and "an empty vector", you could do it this way:
void func(const std::vector<std::string> & my_strings = std::vector<std::string>());

... then you can just call it naturally:
func(std::vector<std::string>({"abc"}));
func();


text:
Q: Simple Neural Network from scratch using NumPy I added learning rate and momentum to a neural network implementation from scratch I found at: https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6
However I had a few questions about my implementation:

*

*Is it correct? Any suggested improvements? It appears to output adequate results generally but outside advice is very appreciated.

*With a learning rate < 0.5 or momentum > 0.9 the network tends to gets stuck in a local optimum where loss = ~1. I assume this is because step size isn't big enough to escape this but is there a way to overcome this? Or is this inherent with the nature of the data being solved and unavoidable.
import numpy as np
import matplotlib.pyplot as plt

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def sigmoid_derivative(x):
    sig = 1 / (1 + np.exp(-x))
    return sig * (1 - sig)

class NeuralNetwork:
    def __init__(self, x, y):
        self.input      = x
        self.weights1   = np.random.rand(self.input.shape[1], 4)
        self.weights2   = np.random.rand(4, 1)
        self.y          = y
        self.output     = np.zeros(self.y.shape)
        self.v_dw1      = 0
        self.v_dw2      = 0
        self.alpha      = 0.5
        self.beta       = 0.5

    def feedforward(self):
        self.layer1 = sigmoid(np.dot(self.input, self.weights1))
        self.output = sigmoid(np.dot(self.layer1, self.weights2))

    def backprop(self, alpha, beta):
        # application of the chain rule to find derivative of the loss function with respect to weights2 and weights1
        d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))
        d_weights1 = np.dot(self.input.T,  (np.dot(2*(self.y - self.output) *
                                            sigmoid_derivative(self.output), self.weights2.T) *
                                            sigmoid_derivative(self.layer1)))
        # adding effect of momentum
        self.v_dw1 = (beta * self.v_dw1) + ((1 - beta) * d_weights1)
        self.v_dw2 = (beta * self.v_dw2) + ((1 - beta) * d_weights2)
        # update the weights with the derivative (slope) of the loss function
        self.weights1 = self.weights1 + (self.v_dw1 * alpha)
        self.weights2 = self.weights2 + (self.v_dw2 * alpha)

if __name__ == "__main__":
    X = np.array([[0, 0, 1],
                  [0, 1, 1],
                  [1, 0, 1],
                  [1, 1, 1]])
    y = np.array([[0], [1], [1], [0]])
    nn = NeuralNetwork(X, y)

    total_loss = []
    for i in range(10000):
        nn.feedforward()
        nn.backprop(nn.alpha, nn.beta)
        total_loss.append(sum((nn.y-nn.output)**2))

    iteration_num = list(range(10000))
    plt.plot(iteration_num, total_loss)
    plt.show()
    print(nn.output)

A: first thing, in your "sigmoid_derivative(x)", input to this function is already output of a sigmoid, but you get the sigmoid again and then computed derivative, that is one problem, it should be :
return x * (1 - x)

second problem, you are not using any bias, how do you know your decision boundary would cross the origin in the problem hypothesis space? so you need to add a bias term.
And last thing I think your derivatives are not correct, you can refer to Andrew Ng deep learning course 1, week 2 at coursera.org , for a list of general formulas for computing back propagation in neural networks to make sure you are doing it right.


text:
Q: JQuery Tabs: How to get a list of the tab titles As the title suggest, my question is what is the best way to get or build a list of the titles for the set of tabs. I was thinking I would have to build the list in a for loop, but there does not appear to be any 'name' or 'title' property where you could do something like this:
var $tabs = $('contentContainer').tabs();
$tabs.tabs( 'title', index );

A: $('contentContainer ul li a').each(function(){alert($(this).text())})

(assuming the selector is used when creating the tabs is 'contentContainer'... if it's a class or an id it will need a . or a #.)

A: Tom's answer looks pretty good, except that it searches recursively; so, if you had any lists nested inside of your tabs this would pick those up too. I would propose a slight modification
 $('> ul > li > a', tabSelector).each(function () { alert($(this).text()) })

This will tell jquery to only select direct descendants.


text:
Q: Django-tables2 Row Selection How do I select a row from a table generated from django-tables2? I'd prefer not to have to select a row by checking a checkbox cell (selection = tables.CheckBoxColumn(accessor='pk'))  in the row.

A: Depending on what you want to do, you can format the cell as an href, so that the user clicks on it to get the appropriate action- or detail-view. You can accomplish this easily by defining a method on the model to return the appropriate text, including self.id or other row-identification from the instance.
Example:
class Customer( models.Model):
...
    @property
    def td_inspect(self):
        dest = reverse('customers:detail', args=(self.id,) )
        return format_html('🔎 	', dest=dest ) # 1f50e is magnify glass

You can also work client-side using JQuery or suchlike, passing the necessary id information via something like <td data_id={id}...


text:
Q: What do you call this kind of entrance with a roof? I have recently become fascinated in observing these "towers" used as a front-gate entrance for a house.
Do these have any special kind of name?

(For a slightly larger picture, click on this link)
They of course vary in appearance, especially the styling of the roof (i.e., roof angle and material).

A: In this instance, a Brit would probably describe it as a porch (the word has a slightly different connotation in American English).
Something more substantial like the one below, though, would be called a gatehouse.

© Copyright Clive Perrin and licensed for reuse under CC-SA Link

A: Maybe there's a special name that I'm unaware of, but I'd simply call that a "sheltered entrance", or an "entrance shelter".
That seems to be a widely recognized term for such a structure.

A: In the U.S. this would probably be called a portico. The American Heritage Dictionary defines it as:

A porch or walkway with a roof supported by columns, often leading to the entrance of a building.

Where these entrances are surrounded by plantings, they are often called arbors.

A: It's a lychgate, formally used for such a structure outside a Church but has expanded to the general. I don't think it is used much nowadays.

Lychgate: a small gate with a small, sloping roof over it that leads into the area around a church
[Cambridge English Dictionary]


text:
Q: How can we use Apache POI library for .xls file in iOS I want to read, write and edit .xls files in iOS,
There are some libraries like JXSL(for writing) and DHXLS (for reading),
But I want to edit the existing file.
Any help will be appreciated


text:
Q: How can i add a co-orgainizer or co-host while creating an event by using Microsoft Graph API? We have almost 50 users (tutors) and daily we create some events with meeting for their classes with students
, so the Problem is that in case if any user(tutor) is not available at the time of meeting or event so we want that in place of that not available user(tutor) any other user(tutor) could take the class , so for that purpouse i want to add a co-host or co-organizer for every event or meeting How can i do that using graph api ?
endpoint i am calling to create event is (userId is email of the orgainizer in the endpoint)
axios.post(`https://graph.microsoft.com/v1.0/users/${userId}/calendar/events`,requestBody,options)

request body is
requestBody = {
    subject:MeetSubject,
    start:{
        dateTime:isoStart,
        timezone:'UTC'
    },
    end:{
        dateTime:isoEnd,
        timezone:'UTC'
    },

    recurrence: recurrenceData,
    attendees: [
      {
        emailAddress: {
          address: attendeEmail,
          name: attendeName,
        },
        type: 'required',
      },
    ],
    isOnlineMeeting: true,
    onlineMeetingProvider: 'teamsForBusiness'
  };


text:
Q: How can I build an inline documentation utility? I often have a large function to which I add inline comments, but then I can't see the forest for the trees. How can I make a tool that extracts the comments and tokens within them to generate an overview or structured outline of the large complex function? For instance:
 BigNastyFunction[input_List, xSpecArg_, ySpecArg_, OptionsPattern[]] :=
 Module[
 {
    (*1:1 Local variables*)
   data, ySpecContinousQ, xSpecContinousQ, groupsQ, joinedCounts, colors, ymin, ymax, xmin,

   (*1:2 Option variables*)
   axesLabelsQ, barOrigin, background, diskSizeScaling, displayFunction, frameQ
 }

  (*2:1 Check for null Input*)
  If[times === {}, Return[$Failed]];

  (*2:2:1 Check for groups *)
  check1 = Depth[input] === 4;
  (*2:2:2 Check for nongroups *)
  check2 = Depth[input] === 3;

  etc...

Would be transformed into something like:
Outline of BigNastyFunction
Part 1.
.....Step 1. Local variables
.....Step 2. Option variables
Part 2.
.....Step 1. Check for null Input
.....Step 2.
..........a) Check for groups
..........b) Check for nongroups

A: I would suggest something more simple-minded than Rolf's sophisticated implementation:
Clear[extractComments];
extractComments[boxes_] :=
  StringJoin@
    Riffle[
      Cases[boxes,
          r : RowBox[{"(*", ___, "*)"}] :>
              StringJoin@Cases[r, _String, Infinity], Infinity],
      "\n"];

and the palette:
CreatePalette[
  Button["Comments",
    With[{read = NotebookRead[SelectedNotebook[]]},
      SelectionMove[SelectedNotebook[], After, Cell];
      NotebookWrite[SelectedNotebook[], Cell[extractComments[read]]]
    ]
  ]]

You select your function's cell and press the "Comments" button. This seems to work in simple cases I tested. You can modify the extractComments function to implement more complex logic that would categorize the comments according to their hierarchy etc.

A: OK, FrontEnd:
After creating the "overview" button below just click first on your function definition and then on the button and under the function definition you will get (nearly) what you want, i.e. :
Part 1.
Step 1. Local variables
Part 1.
Step 2. Option variables
Part 2.
Step 1. Check for null Input
Part 2.
Step 2.:1 Check for groups
Part 2.
Step 2.:2 Check for nongroups
  CreatePalette@Cell[BoxData[
 ButtonBox["overview",
  ButtonFunction:>Block[{$CellContext`com}, SelectionMove[
          SelectedNotebook[], All, CellContents]; $CellContext`com =
     ExportString[
       StringDrop[
        Apply[StringJoin,
         StringCases[
          Apply[StringJoin, $CellContext`RER = ReplaceRepeated[
                 NotebookRead[
                  InputNotebook[]], RowBox[
                   Condition[
                    Pattern[$CellContext`x,
                 BlankSequence[]],
                Not[
                 FreeQ[$CellContext`x, RowBox]]]] :> Apply[RowBox,
                   ReplaceAll[{$CellContext`x}, RowBox[{
                       Pattern[$CellContext`y,
                        BlankSequence[]]}] :> $CellContext`y]]]], {
          StringExpression["(*",
             Shortest[
              Pattern[$CellContext`i,
                   Blank[]]], ":",
                 Shortest[
                  Pattern[$CellContext`j,
               BlankSequence[]]],
             Shortest[
              Pattern[$CellContext`str,
                   BlankSequence[]]], "*)"] :> {
                 StringExpression["\nPart ", $CellContext`i,
                  StringJoin[".\n", "Step "], $CellContext`j,
                  "."], $CellContext`str}}]], 1], "Text"]; SelectionMove[
          SelectedNotebook[], After, Cell]; NotebookWrite[
          SelectedNotebook[],
          Cell[$CellContext`com, "Text"]]],
  Evaluator->Automatic]]]


text:
Q: Got this error 26 - error locating server/instance specified in client machine My application works fine in my pc but not working in clients . I am tired of googling. Please anyone help me :(
I made following changes in my computer-
1.Remote access is stared
2.Sqlbrowser is started and running
3.tcp 1433 and udp 1433 exception added to windows firewall
4.tcp/ip-- IPALL port-1433


text:
Q: How to set default value for row labels in pivot table using poi I am working with excel reports. I need to generate pivot table with some particular field as default value in row labels rather selecting all fields. I am using apache POI.
This what I am getting automatically when I load excel sheet
This is what I need
AreaReference source = new AreaReference("A1:D5", SpreadsheetVersion.EXCEL2007);
        CellReference position = new CellReference(10,0);

         XSSFPivotTable pivotTable = sheet1.createPivotTable(source, position,wb.getSheet("1econtent"));

         pivotTable.addReportFilter(2);
         pivotTable.addRowLabel(0);

         pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
         pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1,"% of value");

         pivotTable.getCTPivotTableDefinition().getDataFields().getDataFieldArray(1).setShowDataAs(org.openxmlformats.schemas.spreadsheetml.x2006.main.STShowDataAs.PERCENT_OF_COL);
         DataFormat dataformat = wb.createDataFormat();
         short numFmtId = dataformat.getFormat("0.00%");
         pivotTable.getCTPivotTableDefinition().getDataFields().getDataFieldArray(1).setNumFmtId(numFmtId);
         pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo().setName("PivotStyleMedium10");

I tried many ways but I didn't find any answer.

A: The pivot table creation in apache poi is only rudimentary until now.
Apache poi adds as much pivot field items of type "default" (<item t="default"/>)  as rows are in the data source. This is because they don't want have a look at the data and so they are assuming as much different values as rows are in the data source. This is fine because Excel will rebuild its pivot cache while opening.
But if we want preselect items, then this is not fine. Then we must know what items there are that can be preselected.
So we need at least as much items as we want preselect being numbered items: <item x="0"/><item x="1"/><item x="2"/>.... And we must build a cache definition which has shared elements for those items.
To fulfill that requirement we need determine the unique labels all over the rows in data source. Then for each unique label take the item as numbered item. Then build a cache definition which has shared elements for those items. Then set all not wanted items hidden.
Let's have a complete example which creates what you have shown in your question's pictures. Your code in your question is incomplete, so I had must predict what data you have as data source. Please try avoiding that in further questions and always provide Minimal, Reproducible Example. Else you will not get answers further.
import java.io.FileOutputStream;

import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;

class CreatePivotTablePercentAndFilter {

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

  try (Workbook workbook = new XSSFWorkbook();
       FileOutputStream fileout = new FileOutputStream("ooxml-pivottable.xlsx") ) {

   Sheet pivotSheet = workbook.createSheet("Pivot");
   Sheet dataSheet = workbook.createSheet("Data");

   setCellData(dataSheet);

   AreaReference areaReference = new AreaReference("A1:D5", SpreadsheetVersion.EXCEL2007);

   XSSFPivotTable pivotTable = ((XSSFSheet)pivotSheet).createPivotTable(areaReference, new CellReference("A4"), dataSheet);

   pivotTable.addRowLabel(0);

   pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
   pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1,"% of value");

   pivotTable.getCTPivotTableDefinition().getDataFields().getDataFieldArray(1).setShowDataAs(
    org.openxmlformats.schemas.spreadsheetml.x2006.main.STShowDataAs.PERCENT_OF_COL);
   DataFormat dataformat = workbook.createDataFormat();
   short numFmtId = dataformat.getFormat("0.00%");
   pivotTable.getCTPivotTableDefinition().getDataFields().getDataFieldArray(1).setNumFmtId(numFmtId);

   /*
   Apache poi adds 5 pivot field items of type "default" (<item t="default"/>) for each row label here.
   This is because there are 5 rows (A1:D5) and, because they don't want have a look at the data,
   they are assuming max 5 different values.
   This is fine because Excel will rebuild its pivot cache while opening.

   But if we want preselect items, then this is not fine. Then we must know what items there are that can be preselected.

   So we need at least as much items as we want preselect being numbered items: <item x="0"/><item x="1"/><item x="2"/>...
   And we must build a cache definition which has shared elements for those items.

   To fulfill that we need determine the unique labels in column.
   Then for each unique label take the item as numbered item.
   Then build a cache definition which has shared elements for those items.
   Then set all not wanted items hidden.
   */

   //determine unique labels in column 0
   java.util.TreeSet<String> uniqueItems = new java.util.TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
   for (int r = areaReference.getFirstCell().getRow()+1; r < areaReference.getLastCell().getRow()+1; r++) {
    uniqueItems.add(dataSheet.getRow(r).getCell(areaReference.getFirstCell().getCol()).getStringCellValue());
   }
   System.out.println(uniqueItems);
   int i = 0;
   for (String item : uniqueItems) {
    //take the items as numbered items: <item x="0"/><item x="1"/><item x="2"/>
    pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemArray(i).unsetT();
    pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemArray(i).setX((long)i);
    //build a cache definition which has shared elements for those items
    //<sharedItems><s v="Jack"/><s v="Jane"/><s v="Tarzan"/><s v="Terk"/></sharedItems>
    pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(0)
    .getSharedItems().addNewS().setV(item);
    i++;
   }

   //Now we can predefinite a filter.
   //If the need is selecting multiple items, first MultipleItemSelectionAllowed needs to be set.
   pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).setMultipleItemSelectionAllowed(true);
   //Then set H(idden) true for all items which not shall be selected. All except "Jane" in this case.
   i = 0;
   for (String item : uniqueItems) {
    if (!"Jane".equals(item))
     pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(0).getItems().getItemArray(i).setH(true);
    i++;
   }

   workbook.write(fileout);
  }
 }

 static void setCellData(Sheet sheet) {
  Row row;
  Cell cell;
  Object[][] data = new Object[][]{
   new Object[]{"Names", "Values", "ColC", "ColD"},
   new Object[]{"Jane", 10d, "?", "?"},
   new Object[]{"Tarzan", 5d, "?", "?"},
   new Object[]{"Terk", 10d, "?", "?"},
   new Object[]{"Jack", 10d, "?", "?"}
  };
  for (int r = 0; r < data.length; r++) {
   row = sheet.createRow(r);
   Object[] rowData = data[r];
   for (int c = 0; c < rowData.length; c++) {
    cell = row.createCell(c);
    if (rowData[c] instanceof String) {
     cell.setCellValue((String)rowData[c]);
    } else if (rowData[c] instanceof Double) {
     cell.setCellValue((Double)rowData[c]);
    }
   }
  }
 }
}


text:
Q: Trying to understand dual space / dual vectors / 1-forms I am new to this differential geometry business.  I am trying to understand the concept of the dual space and dual vectors.  I found this great answer on another stack exchange post here, but I have a few questions.
I know that if two sets of vectors $V^{\mu}$ and $W_{\nu}$ are duals of each other, then $V^{\mu}W_{\nu} = \delta^{\mu}_{\;\;\nu}$.  So let us say that $V = (1,x,x^2)$ and $W = (a,b,c)$, then the inner product defines $a + bx + cx^2 = 0$. Which is now an element of $\mathbb{R}$.
So here lies my confusion.  I would say that $W$ is a dual vector, however in the answer I linked, he defines the process of bringing $V$ to $\mathbb{R}$ as a map.  So is the map the actual dual vector $W$? Or is the map defined through the inner product of $V$ and $W$?  I know that dual vectors are also called 1-forms.  Is that because of this mapping process?  Can a regular vector be defined as a 1-form in relation to its dual vector?
I hope all this make sense!

A: The dual space of a vector space, is the space of all linear functionals (that is, maps from the vector space to its scalar field that satisfy Linearity).
It is a non-trivial fact that for finite dimensional vector spaces, the dual space of the dual space of that vector space is isomorphic to that vector space (structurally the same space; this result does not hold in general for infinite dimensional vector spaces).
Note: Linearity is the property that the function 'commutes' with scalars, and 'distributes' over vector addition.
The one of the main theorems about dual spaces is this:
Given a pair of vector spaces, $V,W$ and a linear map, $T:V\rightarrow W$, then there exists a corresponding linear map, $T^{*}:W^{*}\rightarrow V^{*}$ called the transpose or dual or adjoint of that linear map. (e.g. https://en.wikipedia.org/wiki/Transpose_of_a_linear_map)


text:
Q: Finding Sum of Prime Numbers between interval (C++ program doesn't work for large numbers) My code is below. it works perfectly while the interval in not very big. However whenever I go over a million the program stops. for instance for interval 2 to 2000000 the sum of primes should be 142913828922 (from the back of the book) whereas my application shows 1179908154. can someone please point out where have I gone wrong.
#include <iostream>
#include <math.h>
#define BELOW 2000000;

using namespace std;
bool isPrime(int num)
{
    int i;

    for (i = 2; i <= sqrt(num); i++) {
        if (num % i == 0) {
            return 0;
        }
        else {
            ;
        }
    }
}

int main()
{
    long sum = 0;
    for (int i = 2; i < BELOW i++) {
        if (isPrime(i)) {
            sum = sum + i;
            printf("sum: %ld\n", sum);
        }
    }

    cin.get();
    return 0;
}

A: The problem you are dealing with is integer overflow.
(signed) long can on most machines have values between -2147483647 and 2147483647.
You should use larger data type, I would suggest unsigned long long, which, on most machines, can hold values between: 0 to 18446744073709551615 (on at least 64 bits) or uint64_t type.

A: You should replace all occurrences of 'int' and 'long' with 'uint64_t'


text:
Q: nextjs firebaseauth redirect before render page if logged in I have a login page and an auth provider as follow
import * as yup from "yup";

import { useState } from 'react'

import { AuthErrorCodes } from 'firebase/auth'
import Cover from '../../components/Cover'
import Head from 'next/head'
import Headingblock from '../../components/Headingblock'
import Section from '../../components/Section'
import { authErrorCodesTranslation } from '../../config/firebase';
import { siteTitle } from '../_app'
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { useRouter } from 'next/router';
import { useAuth } from "../../contexts/auth";
import { auth } from '../../config/firebase';
import { signInWithEmailAndPassword } from "firebase/auth";
import {useEffect} from 'react'

export default function Login() {

  const [response, setResponse] = useState({});
  const [user, userLoading] = useAuth();
  const router = useRouter();

  console.log(userLoading);

  if (!userLoading && user)
    router.push('/');

  const schema = yup.object().shape({
    email: yup.string().email('Adresse email invalide').required('Veuillez renseigner votre adresse email.'),
    password: yup.string().required('Veuillez renseigner votre mot de passe')
  });

  const { register, handleSubmit, formState } = useForm({
    resolver: yupResolver(schema),
  });

  const { errors } = formState;

  const onSubmit = async (data) => {

    await signInWithEmailAndPassword(auth, data.email, data.password)
        .then(userCredential => {
          router.push("/profile");
        }).catch(error => {
            const authErrorCode = Object.keys(AuthErrorCodes).find(k => AuthErrorCodes[k] === error.message);

            let errorTranslation = authErrorCodesTranslation.GLOBAL_AUTH_ERROR;

            if (authErrorCode !== undefined)
              errorTranslation = authErrorCodesTranslation[authErrorCode];

            setResponse({ status: 'error', message: errorTranslation });
        })
  }

  return (
    <>

        <title>{siteTitle} - Connexion</title>

      <Cover />

            <Headingblock main="Connexion" />
            <form onSubmit={handleSubmit(onSubmit)}>

                  Adresse email
                  <input {...register("email")} type="text" className='form-control' style={formcontrolStyle} />

{errors.email?.message}

                  Mot de passe
                  <input {...register("password")} type="password" className='form-control' style={formcontrolStyle} />

{errors.password?.message}

                <button type="submit" style={Object.assign(btnStyle, btnprimaryStyle)}>
                  Connexion
                </button>

              {
                response.status === 'error' &&
{response.message}

              }
            </form>

    </>
  )
}

import { createContext, useState, useEffect, useContext } from 'react';
import { onAuthStateChanged } from 'firebase/auth';
import { auth } from '../config/firebase'

const AuthContext = createContext({ user: null, userLoading: true });

export const AuthProvider = ({ children }) => {
    const [userLoading, setUserLoading] = useState(true);
    const [user, setUser] = useState();

    useEffect(() => {

        return onAuthStateChanged(auth, (user) => {

            console.log('autstatechanged');
            if (user) {
                console.log("1");
                setUser(user);
                setUserLoading(false);
                // ...
            } else {
                console.log("2");
                setUser(null);
            }
        });
    }, []);

    return (
        <AuthContext.Provider value={[user, userLoading]}>
            {children}
        </AuthContext.Provider>
    );
};

export const useAuth = () => useContext(AuthContext);

Once user is logged in I would like that page being not available anymore so I made a redirect once user is set and userloading is false but the page is rendering before redirect that causes a blink effect.
I wouldn't like return a loading screen I think It should be possible to not render login page if user is logged in


text:
Q: Android Button Not moving onclick I have an up button which I want to move up onClick but when I click on it it moves way to far and gets to the end of the screen and then shrinks down untill you cant see it. It moves up too much, but why? I only increase it by one unit?
final Button upbutton = (Button)findViewById(R.id.upbutton);

    upbutton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams)

            upbutton.getLayoutParams();

            mParams.bottomMargin += 1;
            upbutton.setLayoutParams(mParams);

        }
    });
}

A: Because you're not assigning mParams to your buttons params.
mParams = upbutton.getLayoutParams();

A: You seem to be increasing parameters for your RelativeLayout then assigning those to your button. So the button gets  confused. Try looking for a set margin option or something on the actual button view.


text:
Q: does HierarchicalDataTemplate.Triggers support conditional binding to ItemsSource and ItemTemplate? The following xaml generates  compile time error: Cannot find the Template Property 'ItemsSource' on the type 'System.Windows.Controls.ContentPresenter'
    <HierarchicalDataTemplate x:Key="tvTemplate">
        <TextBlock Text="{Binding Path=Name}"/>
        <HierarchicalDataTemplate.Triggers>
            <DataTrigger Binding="{Binding HasSubCat1}" Value="True">
                <Setter Property="ItemsSource" Value="{Binding SubCategories1}" />
                <Setter Property="ItemTemplate" Value="{Binding subCat1Template}" />
            </DataTrigger>
            <DataTrigger Binding="{Binding HasSubCat1}" Value="False">
                <Setter Property="ItemsSource" Value="{Binding SubCategories2}" />
                <Setter Property="ItemTemplate" Value="{Binding subCat2Template}" />
            </DataTrigger>
        </HierarchicalDataTemplate.Triggers>
    </HierarchicalDataTemplate>
</UserControl.Resources>

Basically, i have data that when displayed will be two levels or three levels deep...the type of data objects will differ depending with it is destined to be part of the 2 or 3 level branch.  This is why i need to conditionally set the template and items source.  can this be done

A: Not quite sure from your description exactly what your data looks like but I think what you want is different HierarchicalDataTemplates with a DataTemplateSelector to choose between them at each item. The selector just needs to switch between the templates depending on some value on the data item, like what your DataTriggers are trying to do:
public class CategoryTemplateSelector : DataTemplateSelector
{
    public DataTemplate Cat1Template { get; set; }
    public DataTemplate Cat2Template { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        return ((CategoryBase)item).HasSubCat1 ? Cat1Template : Cat2Template;
    }
}

You then need 2 simple templates, each with a different ItemsSource binding:
<HierarchicalDataTemplate x:Key="tvTemplate1" ItemsSource="{Binding SubCategories1}">
    <TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="tvTemplate2" ItemsSource="{Binding SubCategories2}">
    <TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>

And then on your TreeView, instead of setting the ItemTemplate, use the selector:
<TreeView.ItemTemplateSelector>
    <local:CategoryTemplateSelector Cat1Template="{StaticResource tvTemplate1}" Cat2Template="{StaticResource tvTemplate2}"/>
</TreeView.ItemTemplateSelector>


text:
Q: HTML: how to adjust width of disabled INPUT <input type="text" name="email" size="some size" disabled="true/false">

Form allows me to provide up to 35 characters long ID, which is read-only in edit mode (its rendered as disabled in such a case). How can I determine its width depending on text length? I want to be able to display the field wide enough so that whole text shows off. Tried it with size attribute but it is preety much useless, because it doesn't take font width into account.
Like its to narrow for:
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwxxxxx
and too wide for:
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
any help will be appreciated

A: If you want the width of each letter to be taken into account then you could just use a monospaced font. Monospaced fonts have all characters at equal width:
input[type="text"] {
    font-family:monospace;
}

http://jsfiddle.net/JamesD/q7NRb/

A: <input type="text" name="email" size="some size" disabled="true/false" onkeypress="Adjustwidth(this);">

you have to adjust the width of your control with the help of some javascript like...
function Adjustwidth(obj)
{
     obj.style.width = ((obj.value.length + 1) * 8) + 'px';
}

A: You could have something like this
<input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">

Also adding the Mono-space font will take care of the trailing whitespace
WORKING DEMO

A: If you want the input's width to adjust the size of its contents then you'll have to do some js. An option is to create a temporary span with identical styling, fill it with the same text and measure its size:
 function UpdateWidth() {
        var input = $('#yourInputId');
        $('<span id="width">').append( input.val() ).appendTo('body');
        input.width( $('#width').width() + 1 );
        $('#width').remove();
    }

Note, that you have to ensure that the span has the same styling (font and etc).


text:
Q: SQL Fast counting of deep quantity (relationship one to many 2x) There are 3 sqlalchemy tables.
Gardeners (a gardener can have many trees):
class Gardener(Base):
    __tablename__ = 'gardeners'

    gardener_id = Column(Integer, primary_key=True, autoincrement=True)
    name = sqlalchemy.Column(sqlalchemy.String(15))
    apple_trees = relationship('AppleTrees', backref='gardener_trees')

+------------------+--------------+------+-----+---------+----------------+
| Field            | Type         | Null | Key | Default | Extra          |
+------------------+--------------+------+-----+---------+----------------+
| gardener_id      | int          | Yes  | PRI | NULL    | auto_increment |
| name             | varchar(15)  | Yes  |     | NULL    |                |
+------------------+--------------+------+-----+---------+----------------+

+------------------+--------------+
| gardener_id      | name         |
+------------------+--------------+
| 1                | Steve        |
| 2                | Ronald       |
+------------------+--------------+

Trees belong to different gardeners (there can be many apples on the tree)
class AppleTrees(Base):
    __tablename__ = 'trees'

    tree_id = Column(Integer, primary_key=True, autoincrement=True)
    gard_id = Column(Integer, ForeignKey('gardeners.gardener_id'))
    apples = relationship('Apples', backref='tree_apples')

+------------------+--------------+------+-----+---------+----------------+
| Field            | Type         | Null | Key | Default | Extra          |
+------------------+--------------+------+-----+---------+----------------+
| tree_id          | int          | Yes  | PRI | NULL    | auto_increment |
| gard_id          | int          | Yes  | MUL | NULL    |                |
+------------------+--------------+------+-----+---------+----------------+

+------------------+--------------+
| tree_id          | gard_id      |
+------------------+--------------+
| 1                | 1            |
| 2                | 2            |
| 3                | 2            |
+------------------+--------------+

Apples belong to different trees
class Apples(Base):
    __tablename__ = 'apples'
    apple_id = Column(Integer, primary_key=True, autoincrement=True)
    ap_tree_id = Column(Integer, ForeignKey('trees.tree_id'))

+------------------+--------------+------+-----+---------+----------------+
| Field            | Type         | Null | Key | Default | Extra          |
+------------------+--------------+------+-----+---------+----------------+
| apple_id         | int          | Yes  | PRI | NULL    | auto_increment |
| ap_tree_id       | int          | Yes  | MUL | NULL    |                |
+------------------+--------------+------+-----+---------+----------------+

+------------------+--------------+
| apple_id         | ap_tree_id   |
+------------------+--------------+
| 1                | 1            |
| 2                | 2            |
| 3                | 3            |
| 4                | 1            |
| 5                | 3            |
+------------------+--------------+
/* As you can see, Steve has 2 apples */

And this is a dilemma how it is reasonable to find out the number of apples of a particular gardener.
Wrote this:
gardener = session.query(Gardener).filter_by(name='Steve').first()
apple_counter = 0
for tree in gardener.apple_trees:
    for apple in tree.apples:
        apple_counter += 1

But I am 100% sure that this is a very bad and slow technique.
A huge request to help. I would really like to see and understand how this problem is being solved by working with sqlalchemy objects and | or an ordinary SQL request. I apologize in advance for stupidity and thank you very much for any of your decisions and tips!


text:
Q: MultipleMatchesException while using react webjar I was using react with play-framework from webjar. While running the code MultipleMatchesException exception is thrown. After looking into the issue, I find react.production.min.js file in two locations. One in cjs and other in umd.
build.sbt line:   "org.webjars" % "react" % "16.3.2"
What is the difference between cjs and umd? Why are both being downloaded and how to specify only one to use???
Thanks in advance

A: CJS = Common JS
UMD = Universal Module Definition
You need to be more specific in your webjars-locator usage, so something like:
@webJarsUtil.locate("umd/react.production.min.js").script()


text:
Q: Clarification of how Typescript with useState works Hi I'm still learning Typescript and I'm trying to get rid of all my any types. No matter what I do I always get this error. My app works fine but I know using any isn't good so I'm trying to clean it up a bit. If you can point me in the right direction that would be helpful. Or an explanation of what I'm doing wrong. Thank you
Argument of type 'Dispatch<SetStateAction<[] | undefined>>' is not assignable to parameter of type 'Dispatch<string[]>'.
  Type 'string[]' is not assignable to type 'SetStateAction<[] | undefined>'.
    Type 'string[]' is not assignable to type '[]'.
      Target allows only 0 element(s) but source may have more.

App.tsx
const [userData, setUserData] = useState<any>();
fetchData('user', setUserData);

return
<Profile content={userData} />

Firebase.tsx
export const fetchData = async (storage: string, setData: React.Dispatch<string[]>) => {
  const q = query(collection(db, storage));
  const unsubscribe = onSnapshot(q, (querySnapshot) => {
    let array: string[] = [];
    querySnapshot.forEach((doc: any) => {
      array.push({ ...doc.data(), id: doc.id });
    });
    setData(array);
  });
  return () => unsubscribe();
};

Profile.tsx
type Props = {
  content?: {
    firstName: string;
    lastName: string;
  }[];
  location?: string;
  image?: string;
};

const Profile: React.FC<Props> = ({ content, image }) => {}

A: For your error, just change React.Dispatch<string[]> by Dispatch<SetStateAction<[] | undefined>>
As the state is not defined directly, Typescript must know that it can possibly be undefined.


text:
Q: How do I got about mocking UIApplication.sharedApplication to test shortcutItems? I'm trying to write XCTests for my 3D Touch code for quick actions (when you 3D Touch on the icon and launch the app). However, I can't seem to figure out a good way to write a protocol that would allow me to mock UIApplication.sharedApplication() so that, when the tests are running and that is called, the test data goes to the mock class instead of the actual shortcutItems. Any suggestions?
Originally I was thinking
protocol MockShortcutItems {
  var shortcutItems: [UIApplicationShortcutItem] { get set }
}

extension UIApplication: MockShortcutItems {}


text:
Q: Can't specify headers in request in AngularJS I have 2 parts in my app - Angular frontend and rails server. And because it's different domains, requests doesn't work by default. There are a lot of staff about that, including stack, but it doesn't works for me.
This is my method in angular controller:
$scope.test =->
  # transform = (data) ->
  #   $.param data

  $http.post('http://localhost:3000/session/create', 'token=some',
    headers:
      'Access-Control-Allow-Origin': 'http://localhost:9000',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
    # transformRequest: transform
  ).success (responseData) ->
    console.log(responseData)

I commented transform data, there is no difference in server response.
And I configured app (saw this in some post) like that:
.config ["$httpProvider", ($httpProvider) ->
  $httpProvider.defaults.useXDomain = true
  delete $httpProvider.defaults.headers.common["X-Requested-With"]
]

I guess that makes request not ajax like (but i'm not sure).
But there is no headers in my request. They all in some field Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-headers, access-control-allow-methods, content-type:
    Request URL:http://localhost:3000/session/create
    Request Method:OPTIONS
    Status Code:404 Not Found

    Request Headers

    Accept:*/*
    Accept-Encoding:gzip,deflate,sdch
    Accept-Language:en-US,en;q=0.8,ru;q=0.6
    Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-headers, access-control-allow-methods, content-type
    Access-Control-Request-Method:POST
    Connection:keep-alive
    DNT:1
    Host:localhost:3000
    Origin:http://localhost:9000
    Referer:http://localhost:9000/
    User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.8 Safari/537.36

    Response Headers

    Content-Length:12365
    Content-Type:text/html; charset=utf-8
    X-Request-Id:2cf4b37b-eb47-432a-ab30-b802b3e33218
    X-Runtime:0.030128

Chrome console:
OPTIONS http://localhost:3000/session/create 404 (Not Found) angular.js:6730
OPTIONS http://localhost:3000/session/create No 'Access-Control-Allow-Origin' header is     present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. angular.js:6730
XMLHttpRequest cannot load http://localhost:3000/session/create. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. localhost/:1

Other insignificant information:
On the server:
class ApplicationController < ActionController::Base
  before_filter :allow_cross_domain_access

  protected

  def allow_cross_domain_access
    headers['Access-Control-Allow-Origin'] = '*'# http://localhost:9000
    headers['Access-Control-Allow-Headers'] = 'GET, POST, PUT, DELETE'
    headers['Access-Control-Allow-Methods'] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(',')
    headers['Access-Control-Max-Age'] = '1728000'

  end
end

Routes is obvious post "session/create". And session controller:
class SessionController < ApplicationController
  respond_to :json, :html, :js

  def create
    respond_with "logged in"
    # render nothing: true
  end
end

I use latest version of angular 1.2.0.rc-2. this is my project on github

A: You mix up the request and response headers in your example.
When doing a cross domain request (CORS) and you want to make anything different than a plain GET - so for example a POST or adding custom headers - the browser will first make an OPTIONS request.
This is what you see in your developer console:
OPTIONS http://localhost:3000/session/create 404 (Not Found) angular.js:6730

The server then should add the appropriate headers to the response of the OPTIONS request.
So you can remove the custom headers from the Angular call.
Next you need to make sure that your server/application answers the OPTIONS request, not returning a 404.