text:
Q: How are Firebase Cloud Functions invocations counted? I have plenty of functions in my program with Firebase Cloud Functions. But I'm not sure how the invocations are counted. I am asking this so that I can minimise my invocations as much as possible.
TO start off, I have a function:
export const fucntionOne = functions.auth.user().onCreate((user) => {
    console.log('1 invocation used!!')
})

When a new user joins, this function will be executed and ofcourse it will consume my 1 invocation.
So before asking the question here, I did a couple of experiments and found out that if I use another function functionTwo and call it in the first one like this:
export const fucntionOne = functions.auth.user().onCreate((user) => {
        console.log('1 invocation used!!')
        functionTwo()
    })

function functionTwo(){
    console.log('Second function worked. . .')
}

This time I was expecting my function invocation count by 2. But it did increased only by 1. This is fine.
But let's say I use a function with some relation with firebase-realtime-database, let's say save or retrieve data using either .onCreate() or .onDelete() and so one and call the function like:
export const fucntionOne = functions.auth.user().onCreate((user) => {
        console.log('1 invocation used!!')
    })

export const functionOnCreate = functions.database
    .ref('/path')
    .onCreate((snapshot, context) => {

     //Do any thing in the function
     console.log(`functionOnCreate executed.`)

     return <something>
   })

Now let's be clear, functionOnCreate() is executed when some nodes are created using functionOne() in the database using .onCreate() method.
BUT, this time it costed me 2 Invocations.
Okay, I'm clear that it's because functionOnCreate() is being called by [or invoked by] firebase functions so it might be the reason for it.
But if I manage to perform tasks on database by manually calling functions like functionTwo() did. Then will it SAVE me from some extra function invocations?

A: *

*You are charged for the number of times one of your Cloud Functions is invoked. In your second code snippet, you have only one Cloud Function. Calls inside this Cloud Function to other regular JavaScript functions are not charged operations.

*You are charged for the amount of time that your code runs, and for the memory it has allocated during that time. Calling multiple regular functions will increase the time the code runs, and may increase the memory required.

*Performing the additional database writes in your functions.auth.user().onCreate triggered Cloud Function will indeed prevent a charge for the functions.database.ref('/path').onCreate( triggered Cloud Function. I recommend that you do some calculations on the number of invocations though, as invocation count is seldom a major factor in their cost.


text:
Q: Persist firebase auth state react native i am building a react native app and i noticed that firebase does not persist auth state by default so a user has to login again any time they exit the app. So i tried doing it manually according to their documentation but it doesn't seem to work for me.
this is where i try to set persist state
import { getAuth, signInWithEmailAndPassword, sendPasswordResetEmail, setPersistence, inMemoryPersistence} from 'firebase/auth';

 onSignIn(props) {
    const auth = getAuth();
      const { email, password } = this.state
      setPersistence(auth,inMemoryPersistence).then(() => {

      if(email.trim().length == 0 && password.trim.length == 0){
        Alert.alert(
          "",
          "Fields can't be empty",
          [

            { text: "OK") }
          ])
     }else {

      signInWithEmailAndPassword( auth, email, password)
      .then((result) => {

      })
      .catch((error) => {
        console.log(error)

      })
    }
  })

}

and this is where i check for auth state
 componentDidMount() {

firebase.auth().onAuthStateChanged((user) => {

  if (!user){
    this.setState({
      loggedIn: false,
      loaded: true,

    })
  }else {
    this.setState({
      loggedIn: true,
      loaded: true,
    })
  }
})

please i have been on this for weeks and have even tried using async storage but none works for me. at this point i really need help. thank you

A: From looking at the documentation on inMemoryPersistence it means:

An implementation of Persistence of type 'NONE'.

Which the documentation guide on types of auth persistence further explains as:

firebase.auth.Auth.Persistence.NONE
'none'
Indicates that the state will only be stored in memory and will be cleared when the window or activity is refreshed.

According to last link, you should instead use:

firebase.auth.Auth.Persistence.LOCAL
'local'
Indicates that the state will be persisted even when the browser window is closed or the activity is destroyed in React Native. An explicit sign out is needed to clear that state. Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only.

So by checking back in the reference docs, you'll want to use reactNativeLocalPersistence for that

redpajama_set_name: RedPajamaStackExchange


text:
Q: API vk и загрузка фотографий Что мне нужно для того, чтобы залить фото в свой паблик ВК, и при этом использовать это фото в посте? Для последнего знаю, что можно использовать метод постинга на стену, но как прилепить изображение?
P.S - видел в сети куча библиотек, но я стараюсь их избегать - поэтому вариант не очень.

A: Для того, чтобы выложить на стену фотографию, необходимо выполнить следующую последовательность:

*

*При помощи метода wall.getPhotoUploadServer получить адрес, на которую можно будет загрузить изображение;

*POST'ом отправить изображение на полученную ссылку, в ответ прийдет hash сохраненного изображения;

*Через метод wall.savePost передать полученный ранее hash изображения.

Более подробно в спеке VK.


text:
Q: OSX Open Directory Network Users Problem and Kerberos I've got a Mavericks Server mostly working, but I still get some funkiness.  Main problem is that I've been having a great deal of trouble getting network user accounts with home directories on the server to function.
So, I've gone to http://yesdevnull.net/ and have been going through testing from the beginning.
I want your input on this DNS issue.  My router is providing DNS for the server.  When I did the initial setup, I ran this on the server
sudo changeip -checkhostname

and got this:
Primary address     = 192.168.12.3
Current HostName    = server.mydomain.net
DNS HostName        = server.mydomain.net

The names match. There is nothing to change.
dirserv:success = "success"

So, I figured DNS is working correctly.
But, since I still have issues, I decided to dig deeper and ran this on a client:
dig -x 192.168.12.3

and got this:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9219
;; flags: qr; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;3.12.168.192.in-addr.arpa.    IN    PTR

;; ANSWER SECTION:
3.12.168.192.in-addr.arpa. 3600    IN    PTR    server.mydomain.net.

;; Query time: 3 msec
;; SERVER: 192.168.12.1#53(192.168.12.1)
;; WHEN: Sun Jan 26 07:47:23 2014
;; MSG SIZE  rcvd: 75

Compared to Mr. Barrett's example at http://yesdevnull.net/, the differences are that my flags for AUTHORITY and ADDITIONAL are 0, while his are 1 and of course there is no AUTHORITY SECTION: or ADDITIONAL SECTION:
Do people see that as a cause for problems?
If so, I can certainly setup DNS on the server and change all the clients to use the server's IP for their DNS server.
Steps for that?  This would be my plan:
On server:

*

*Setup DNS

*Retest Lookups as above

Will I need to destroy Open Directory and start over?  If so, it might be faster for me to re-setup Mav Server, BUT i'd really like to do it without reinstalling since I have the server setup with some other services (its providing print services for ipads using something called Handyprint, its running a python based server to receive phots from eye-fi cards in my cameras, and a few other things that I'd like to avoid having to setup again).
On clients:

*

*unbind clients

*Change clients DNS Clean out old OD certificates from client keychains

*Ensure that previous computer records are not in OD and remove using WGM if necessary

*Rebind Clients


text:
Q: Signing pdf with external Signed Hash and certificate in c#? enter image description hereI have SignedHash and certificate to sign the pdf file.
The Signedhash and Certificate both received through external services.
How to embed SignedHash to the PDF and then verify it with certificate using C#?
// Here we are using Itextsharp
    public static void SignDoc(string inputFilePath, string outputFilePath)
            {
// Open pdf
                using (PdfReader reader = new PdfReader(inputFilePath))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
//Code to add new sig appearance
    BaseFont helvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
                        Font font = new Font(helvetica, 12, iTextSharp.text.Font.NORMAL);
                        PdfStamper stamper = PdfStamper.CreateSignature(reader, ms, '\0');
                        PdfSignatureAppearance sap = stamper.SignatureAppearance;
                        sap.Reason = "";
                        sap.Location = "";
                        sap.Contact = "";
                        sap.Layer2Font = font;
// Setting up Visible Sig
             sap.SetVisibleSignature(new iTextSharp.text.Rectangle(415, 100, 585, 40), 1, null);
                var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
                        dic.Reason = sap.Reason;
                        dic.Location = sap.Location;
                        dic.Contact = sap.Contact;
                        dic.Date = new PdfDate(sap.SignDate);
                        sap.CryptoDictionary = dic;
                        Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>();
                        exc.Add(PdfName.CONTENTS, (int)(8192 * 2 + 2));
                        sap.PreClose(exc);
                        Stream data = sap.GetRangeStream();
                        //Extract the bytes that need to be signed
                        // Creating hash of pdf with signature appearance
                        byte[] hash = DigestAlgorithms.Digest(data, DigestAlgorithms.SHA256);

// Calling third party digidenty service for Cert as well as SignHash
    var signedDocResp = SignUtility.GetSignHashAndCertificate(BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant());
                        X509Certificate2 cert2 = new X509Certificate2(Encoding.Unicode.GetBytes(signedDocResp.Certificate));
                        var cert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(cert2.GetRawCertData());
                        var chain = new List<Org.BouncyCastle.X509.X509Certificate>() { cert };
                       PdfPKCS7 sgn = new PdfPKCS7(null, chain, DigestAlgorithms.SHA256, false);
    byte[] sh = sgn.getAuthenticatedAttributeBytes(Encoding.Unicode.GetBytes(signedDocResp.SignedHash), null, null, CryptoStandard.CMS);
                        sgn.SetExternalDigest(Encoding.Unicode.GetBytes(signedDocResp.SignedHash), null, "RSA");
             byte[] encodedSig = sgn.GetEncodedPKCS7(sh, null, null, null, CryptoStandard.CMS);
                        byte[] paddedSig = new byte[8192];
                        encodedSig.CopyTo(paddedSig, 0);
                        PdfDictionary dic2 = new PdfDictionary();
                        dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
                        sap.Close(dic2);
                        byte[] signed = ms.ToArray();
                        File.WriteAllBytes(outputFilePath, signed);
                    }
                }
            }

A: There are multiple pdf libraries for C# (core or otherwise that can help you with that).
Example by IronPDF (paid for production/free for development)
// PM> Install-Package IronPdf
using IronPdf;

// Cryptographically sign an existing PDF in 1 line of code!
new IronPdf.Signing.PdfSignature("Iron.p12", "123456").SignPdfFile("any.pdf");

/***** Advanced example for more control *****/

// Step 1. Create a PDF
var Renderer = new IronPdf.ChromePdfRenderer();
using PdfDocument doc = Renderer.RenderHtmlAsPdf("
Testing 2048 bit digital security
");

// Step 2. Create a Signature.
// You may create a .pfx or .p12 PDF signing certificate using Adobe Acrobat Reader.
// Read: https://helpx.adobe.com/acrobat/using/digital-ids.html

var signature = new IronPdf.Signing.PdfSignature("Iron.pfx", "123456");

// Step 3. Optional signing options and a handwritten signature graphic
signature.SigningContact = "support@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "To show how to sign a PDF";
signature.LoadSignatureImageFromFile("handwriting.png");

//Step 4. Sign the PDF with the PdfSignature. Multiple signing certificates may be used
doc.SignPdfWithDigitalSignature(signature);

//Step 4. The PDF is not signed until saved to file, steam or byte array.
doc.SaveAs("signed.pdf");

Example by iTextSharp (free) - Adding a Digital signature to a PDF with iTextSharp
More options here. All libraries that sign, also have a method to validate. Just check the documentation.


text:
Q: How can I hide the console window and bring up a splash screen? I've used the Matlab Compiler to create a .exe file. The program takes 15 sec to start. I would like to hide the console window, and display a custom splash screen. How can I do that?

A: With regard to making a splash screen, there are a few submissions on The MathWorks File Exchange that deal with just that:

*

*Fancy splash screen for compiled .exe GUIs from W Thielicke

*splash.m from Qun Han.

*Splash Screen from Roy Schestowitz.

I haven't used any of them personally, but they should at the very least give you some guidance if you want to design your own splash screen functionality.

A: You can write a "launcher" program.
The launcher would

*

*Create the splash screen

*Launch the matlab exe using CreateProcess() or some other method.

*Wait until the matlab exe has opened properly

*Exit

The tricky bit will be determining when the matlab program has started.  One method might be to call EnumWindows() and GetWindowText() in a loop, looking for the matlab window title, but you might be able to come up with a better way given knowledge of what the matlab program does.
You would probably need to keep checking that the matlab process hasn't died, in case something goes wrong.

A: To get rid of the DOS window, use mcc -e instead of mcc -m. See "MATLAB Compiler > Function Reference" in the online documentation, brought up by doc(). You might not want to do that, though: the DOS window is the output of last resort; it's where unhandled exceptions, core dumps, and other diagnostic output go. At least make it an option so you can have a debug build that has the DOS window.
In my experience, the startup overhead for a compiled standalone Matlab program happens before control transfers to user M-code, so a splash screen will need to be done in an external program, or hooked in to the C wrapper that mcc generates. You could use Michael J's suggestion of writing a launcher. You're not looking for matlab.exe or a Matlab desktop window, though, since this is a standalone app. To detect when the Matlab program has started, have your M-code write out a little temp file as the first thing the program does, and have your launcher watch for that.


text:
Q: adding styles to gwt code using css i am using GWT , but i need to add some styles to the text boxes,buttons,labels and panels i want to know how to integrate CSS to my own code
like the following links:
https://www.blueworkslive.com/index.html#!gettingStarted:overview
http://www.gogrid.com/
http://www.whirled.com/#landing-bluelanding
so if there is a tutorial which explains these issues... it will be very helpful

A: Start by reading the documentation on GWT CSS styling.


text:
Q: The Sieve of Eratosthenes code in C The following program is to calculate the total of all primes less than 2 million by using The Sieve of Eratosthenes algorithm. The sum should be equal to 142913828922 while it is coming 1179908154. What is the error in this code?
#include<stdio.h>

#include<stdlib.h>

#define LIMIT 2000000

int main()
{
    unsigned long long int i,j;
    int *primes;
    int z=1,sum;

    primes = (int*)malloc(sizeof(int)*LIMIT);

    for(i=2;i<LIMIT;i++)
        primes[i]=1;

    for(i=2;i<LIMIT;i++)
        if(primes[i])
            for(j=i;i*j<LIMIT;j++)
                primes[i*j]=0;

    for(i=2;i<LIMIT;i++)
        if(primes[i])
            sum+=i;

    printf("total = %ld",sum);
    return 0;
}

A: You need to define sum as a 64bit integer
long long sum=0;

Otherwise it is a 32bit integer and the number overflows.
In hex:
hex(142913828922) = 0x214653f83a
hex(1179908154)   =   0x4653f83a


text:
Q: rotate gradient in DrawingBrush in XAML I have a drawingBrush defined and I want to rotate the gradient. The below does not work as it is rotated out of the object frame. How do I rotate this to the center of the object?
    <DrawingBrush x:Key="SteelBrush_Vert" Stretch="Fill">
    <DrawingBrush.Drawing RenderTransformOrigin="0.5, 0.5">
        <DrawingGroup>
            <GeometryDrawing Geometry="M114.000,293.847C114.000,280.324,114.045,269.362,114.100,269.362L391.900,269.362C391.955,269.362,392.000,280.324,392.000,293.847L392.000,485.878C392.000,499.400,391.955,510.362,391.900,510.362L114.100,510.362C114.045,510.362,114.000,499.400,114.000,485.878z">
                <GeometryDrawing.Brush>
                    <LinearGradientBrush StartPoint="114,389.862" EndPoint="392,389.862" MappingMode="Absolute" SpreadMethod="Pad">
                        <GradientStop Color="Black" Offset="0" />
                        <GradientStop Color="#FFDADADA" Offset="0.082" />
                        <GradientStop Color="#FF282828" Offset="0.854" />
                        <GradientStop Color="White" Offset="0.949" />
                        <GradientStop Color="Black" Offset="1" />
                    </LinearGradientBrush>
                </GeometryDrawing.Brush>
            </GeometryDrawing>
        </DrawingGroup>
    </DrawingBrush.Drawing>
    <DrawingBrush.RelativeTransform>
        <RotateTransform Angle="90"/>
    </DrawingBrush.RelativeTransform>
</DrawingBrush>

A: I found my answer with guess and check
   <DrawingBrush x:Key="SteelBrush_Vert" Stretch="Fill">
    <DrawingBrush.Drawing RenderTransformOrigin="0.5, 0.5">
        <DrawingGroup>
            <GeometryDrawing Geometry="M114.000,293.847C114.000,280.324,114.045,269.362,114.100,269.362L391.900,269.362C391.955,269.362,392.000,280.324,392.000,293.847L392.000,485.878C392.000,499.400,391.955,510.362,391.900,510.362L114.100,510.362C114.045,510.362,114.000,499.400,114.000,485.878z">
                <GeometryDrawing.Brush>
                    <LinearGradientBrush StartPoint="114,389.862" EndPoint="392,389.862" MappingMode="Absolute" SpreadMethod="Pad">
                        <GradientStop Color="Black" Offset="0" />
                        <GradientStop Color="#FFDADADA" Offset="0.082" />
                        <GradientStop Color="#FF282828" Offset="0.854" />
                        <GradientStop Color="White" Offset="0.949" />
                        <GradientStop Color="Black" Offset="1" />
                    </LinearGradientBrush>
                </GeometryDrawing.Brush>
            </GeometryDrawing>
        </DrawingGroup>
    </DrawingBrush.Drawing>
    <DrawingBrush.RelativeTransform>
        <RotateTransform CenterX=".5" CenterY=".5" Angle="90"/>
    </DrawingBrush.RelativeTransform>
</DrawingBrush>


text:
Q: Why to use NSData to Json Every time I make a call to Json, I need to use NSData and Json.deserialize.
Since Json is just a string, why cannot I just read it through rest and then use it at the other side, without using NSData, Json.Serialization, etc ?

A: JSON is a method for sending data through strings (not binary). Using as a string is possible, but you'd have to parse it yourself:
Here's a JSON string:
"{\"test\": \"foo\"}"

and it can be converted to
{test: "foo"}

and used like a Hash/Dictionary.
I mean, you can't get the use a string as a dictionary, can you?
"Nope.".get("Nope")

A: JSON is not a string. JSON is a binary format. That binary format is human readable but it's not a string. That's why we have to use NSData and why we have tools for JSON encoding and decoding instead of creating JSON data by appending strings together.


text:
Q: Does NIC Teaming in Windows increase bandwidth in case of MySQL server? I know that Windows server NIC teaming can increase the total bandwidth when used with SMB, and SMB multichannel plays a role in that.
For example, by having 4 x gigabit NICs teamed, you can have 4Gbit transfers with SMB.
However, I would like to know if that would be the case if the server with the NIC teaming is running a MySQL server.
Thanks
Alex


text:
Q: Getting some garbage text when tar-ing a file when I run the following command:
tar -c music.tar iTunes\ Music/

But I get the following garbage output.                                                                                b����n5���z��ԊV_o�P�O3|�b���i�Pl�jH��8��z5����ڕ?~D|_($�|b��:���š`�s7
�%z\��Jj����K����Z��V�)�A4
                             2��}�4�(�?#�P��ykX
                                                 �Q�e<�w�U����Y�8n��s�  1B��F.f�
�X9Lb=8��@����|�h�d�Dz�I��L�]������-����gx��l囧���n�cs{f���f���6�M(�u��6��|pX�nH�V���$�ь�����7��n�H���Yua��Xn�;{�JP�����7�@R�f_旾j�*����3M�z�s9���"��0�$1�ɂ7:w�������|D_�����EjtO��߉�����PޘY�-�    xVF���Uwky�u�Yt�h ���K
                                                                                �nJh�]K�J-�2��#Q̬���~�~B)OޑMĤ��
                                                                                "��6#�Q,uNG�~��4t�>=^C
I don't really care if I'm just missing some font library. But I haven't run this to completion because...well i'm not really sure what it's doing.
any help appreciated.

A: You have to use -cf, otherwise it just dumps the output to stdout (the window), which is exactly what you're seeing. You would use -c alone to pipe it to another program (though you can use > file.tar).


text:
Q: How to transform/merge config files in node.js / nconf? I have node.js app and conf.json file with application settings, i.e.:
{
  "settings": [
    {
      "name": "setting1",
      "connectionString": {
        "host": "mongodb://127.0.0.1:27017/db",
        "collection": "collection1"
      }
    },
    {
      "name": "setting2",
      "file": "/path/file",
      "token": "development token"
    }
  ]
}

Is there any way in nconf or another tool to have analog of .NET's configuration transformation so I may have production config file with overrides, i.e. conf.production.json:
{
  "settings": [
    {
      "name": "setting2",
      "token": "production token"
    }
  ]
}

Expected value of "setting2" in production mode is "production token" and rest from default config file. I tried to load base files with nconf, but it does not work:
nconf.file(process.env.NODE_ENV, './conf.' + process.env.NODE_ENV + '.json');
nconf.file('./conf.json');

A: The relevant part of my config script that I personally use to handle this:
nconf
    .argv    ()
    .env     ()
    .defaults( require( './_config.js' ) )
    .use     ( 'memory' )
    ;

...

nconf.set( 'env'     , nconf.get( 'environments:' + env ) );
nconf.set( 'env:name', env );

var includes = nconf.get( 'env:includes' );

if( {}.toString.call( includes ) === '[object Array]' ){
    var incs = {};

    includes.forEach( function( val ){
        incs[ val ] = val;
    } );

    includes = incs;
}

Object.keys( includes ).forEach( function( incName ){
    var incPath = includes[ incName ]
      , incData = nconf.get( 'environments:' + incPath );

    Object.keys( incData ).forEach( function( key ){
        var keyNm = ( incName.indexOf( '__local' === 0 ) )
            ? 'env:%s'   .sprintf( key )
            : 'env:%s:%s'.sprintf( incName, key )
            ;

        if( nconf.get( keyNm ) == null ){
            nconf.set( keyNm, incData[ key ] );
        }
    });
} );

I think the only dependency in there is sprintf, which you can either install with npm or just slightly re-factor the code.
Basically, I pass in an env param, and set .env to that object.  I then walk an includes object, and pull in any relevant JSON objects from the same config object.
I then access everything via config.get( 'env:<param>' )
One of the simplier config.js (I don't like .json since it can't have comments) files I use:
module.exports =

{
    environments : {
        libraries : {
            jQuery : '//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js'
        }

        , localLibraries : {
            jQuery : '/js/jquery-2.1.0.js'
        }

        , web_server : {
                      task : 'web_server'
            ,     includes : [ 'cdn', 'libraries' ]

            ,         port : 12567
            , csrfMaxAgeMs : 1000 * 60 * 60 * 24 * 30 // 30 days
            ,  csrfHashAlg : 'sha256'

            ,  apiHostName : '(^|\\.)api.*'

            ,     frontend : '/frontend'

            ,   jsonSpaces : 0
        }

        , local_web_server : {
                     task : 'web_server'
            ,    includes : { __local: 'web_server', libraries: 'localLibraries' }
            ,  jsonSpaces : 4
            ,         dev : true
        }
    }
};

You either include a list of objects (['cdn', 'libraries']), in which case they get mapped to env.cdn.param, for example.  Or you can include a mapping, and if the key is __local, it maps to the the current object.


text:
Q: How can I consume a specific REST API element in angular So I am working with an API connected to a MySQL Database with angular front-end but i have encountered a wall.
I want to access to the property startDate and deliveryDate, do some operations with Moment.js and finally change the color of a button with the difference in time.
Here is my api path and the return value
This is my Angular Service
 getStartDate(id:string): Observable<any>{
return this.http.get(`${this.API_URI}/tanks/startDate/${id}`)}

This is my Angular Component.ts, i get to here from a list of buttons, like the Hero tutorial on Angular Website
This is the method that returns an undefined but I need a string with the date "DD/MM/YYYY"
getStartDate(){
    const id = this.route.snapshot.paramMap.get('id');
    this.tankService.getStartDate(id)
    .subscribe(startDate => this.startDate = startDate);
    console.log(this.startDate)

  }

So that then i can do this which is simply get the difference between the two dates and return a string so i can change the color of a button.
getDuration(){
    var startDateMoment = moment(this.tank.startDate, "DD/MM/YYYY")
    var deliveryDateMoment = moment(this.tank.deliveryDate, "DD/MM/YYYY")
    console.log("Here")
    var diff = startDateMoment.diff(deliveryDateMoment, 'days')
    if (diff < 2 ) {
      this.semaphore = "danger"
    } else {
      if (diff > 4) {
        this.semaphore = "primary"
      } else{
        if (diff < 4 && diff > 2) {
          this.semaphore = "warning"
        }
      }

    }
  }

Maybe this is really simple but i can't get my head around it


text:
Q: HTTP Request PostAsync with HttpClient cancels request or Resource temporarily unavailable I have already written a post about this problem. I make HTTP Get and Post requests at regular intervals and some of these requests return an error that crashes my program (because no try-catch).
The error comes from this code :
using (var client = new HttpClient())
            {
                var response = await client.PostAsync(url, data);
                string result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(result);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Success send post : " + result);
                } else
                {
                    Console.WriteLine("Error send post");
                }
            }

This function crashe with 2 errors :
Unhandled Exception: System.OperationCanceledException: The operation was canceled.
nov. 18 04:36:08 raspberrypi wescan[8530]:    at System.Net.Http.HttpClient.HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts)
nov. 18 04:36:08 raspberrypi wescan[8530]:    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
nov. 18 04:36:08 raspberrypi wescan[8530]:    at Common.WebApi.SendHttpPost(String url, StringContent data)
nov. 18 04:36:08 raspberrypi wescan[8530]:    at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__7_1(Object state)
nov. 18 04:36:08 raspberrypi wescan[8530]:    at System.Threading.QueueUserWorkItemCallbackDefaultContext.<>c.<.cctor>b__5_0(Object state)
nov. 18 04:36:08 raspberrypi wescan[8530]:    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
nov. 18 04:36:08 raspberrypi wescan[8530]: --- End of stack trace from previous location where exception was thrown ---
nov. 18 04:36:08 raspberrypi wescan[8530]:    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
nov. 18 04:36:08 raspberrypi wescan[8530]:    at System.Threading.QueueUserWorkItemCallbackDefaultContext.ExecuteWorkItem()
nov. 18 04:36:08 raspberrypi wescan[8530]:    at System.Threading.ThreadPoolWorkQueue.Dispatch()
nov. 18 04:36:08 raspberrypi wescan[8530]:    at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
nov. 18 04:36:09 raspberrypi wescan[8530]: System.OperationCanceledException: The operation was canceled.
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Net.Http.HttpClient.HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at Common.WebApi.SendHttpPost(String url, StringContent data)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__7_1(Object state)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.QueueUserWorkItemCallbackDefaultContext.<>c.<.cctor>b__5_0(Object state)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
nov. 18 04:36:09 raspberrypi wescan[8530]: --- End of stack trace from previous location where exception was thrown ---
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.QueueUserWorkItemCallbackDefaultContext.ExecuteWorkItem()
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.ThreadPoolWorkQueue.Dispatch()
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
nov. 18 04:36:09 raspberrypi wescan[8530]: System.OperationCanceledException: The operation was canceled.
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Net.Http.HttpClient.HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at Common.WebApi.SendHttpPost(String url, StringContent data)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__7_1(Object state)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.QueueUserWorkItemCallbackDefaultContext.<>c.<.cctor>b__5_0(Object state)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
nov. 18 04:36:09 raspberrypi wescan[8530]: --- End of stack trace from previous location where exception was thrown ---
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.QueueUserWorkItemCallbackDefaultContext.ExecuteWorkItem()
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading.ThreadPoolWorkQueue.Dispatch()
nov. 18 04:36:09 raspberrypi wescan[8530]:    at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

2
Unhandled Exception: System.Net.Http.HttpRequestException: Resource temporarily unavailable ---> System.Net.Sockets.SocketException: Resource temporarily unavailable
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
nov. 19 04:00:51 raspberrypi wescan[14169]:    --- End of inner exception stack trace ---
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Threading.Tasks.ValueTask`1.get_Result()
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Threading.Tasks.ValueTask`1.get_Result()
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Threading.Tasks.ValueTask`1.get_Result()
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at Common.WebApi.SendHttpPost(String url, StringContent data)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__7_1(Object state)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Threading.QueueUserWorkItemCallbackDefaultContext.<>c.<.cctor>b__5_0(Object state)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
nov. 19 04:00:51 raspberrypi wescan[14169]: --- End of stack trace from previous location where exception was thrown ---
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Threading.QueueUserWorkItemCallbackDefaultContext.ExecuteWorkItem()
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Threading.ThreadPoolWorkQueue.Dispatch()
nov. 19 04:00:51 raspberrypi wescan[14169]:    at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

I found someone tell to change response.Content.ReadAsStringAsync().Result; to response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); but i can't test it for the moment.
If anyone has had this kind of randomly generated error, I'm interested! cya

A: Both errors looks like connection/network related errors.
Perhaps there is a temporary loss of connection to the endpoint.
It could be because you are sending to many requests and getting throttled.
You don't state why you are not wrapping the call in a try/catch and just handle the exception. I would suggest doing that to make the code more robust.


text:
Q: Quartic equation with integer solutions I am trying to find the solutions of the following quartic equation given that all the solutions are integers.
$$x^4+22x^3+172x^2+552x+576=0$$
Below is the original phrasing of the problem with hints building up to this equation. I can prove all of the results it asks for before the final part of the question, but I am struggling to actually find the solutions to the equation and require help with explaining the process as well.

I then know that:
(1) $k_1k_2k_3k_4 = 576 = (1)(2^6)(3^2)$
(2) $(k_1+1)(k_2+1)(k_3+1)(k_4+1) = 1323=(1)(3^3)(7^2)$
(3) $(k_1-1)(k_2-1)(k_3-1)(k_4-1) = 175 = (1)(5^2)(7)$
However, I do not know how to proceed from here and the solution to this problem didn't explain in enough detail for me to either understand the solution, or the approach.

A: This is an attempt to show how the method suggested in the question can be progressed.
Look at $1323$ with factors $3^3\times 7^2$. The size of $7$ will restrict the possibilities to investigate more quickly than the smaller primes. We have $576=24^2$
The available multiples of $7$ are $7, 21, 49, 63, 147$ (others are too large) giving possible factors of $576$ which differ by $1$ (can't tell the sign at this stage).
So the possible factors of $576$ are $6 , 8; 20, 22; 48, 50; 62, 64; 146, 148$ and the only ones which are actually factors are $6, 8, 48$
And the possible factors of $175$ differ by $2$ (in the same direction as the factors of $576$) so can be $5, 9; 47$ and this time only $5$ is possible, with two factors to match the two $7$s.
This means the factors we have for $576$ have numerical value $6$, and in fact we can tell that the roots are $-6$ by attention to signs [NB]. Then there are lots of ways to finish - having two solutions, we can, for example, identify and solve the quadratic for the remaining roots. Or alternatively the remaining factor $7$ from $175$ gives $-8$ and the final factor has to be $1$ which gives $-2$ (signs to be allocated with care, but since coefficients are all positive, roots must all be negative see NB below).
NB The $k_i$ are the negatives of the roots so the $k_i$ here would be $6$ with the factors $(x+6)^2$ and the double root $x=-6$. And then $8$ and $2$ similarly.

A: Observe that the given equations imply that $k_1,k_2,k_3$ and $k_4$ should be non-zero even integers. Now consider $$(k_1-1)(k_2-1)(k_3-1)(k_4-1)=1\times 5^2 \times 7.$$
Since, $k_i$'s are integers, one of the $k_i-1$ must be $1$ ($k_i-1 \neq -1$ as $k_i \neq 0$). Let $k_1-1=1 \implies \color{red}{k_1 =2}$.
We are now left with $$(k_2-1)(k_3-1)(k_4-1)= 5^2 \times 7.$$
Since we have $5^2$ on the RHS, at least one of the $k_i-1$ (say $k_2-1$) cannot be a multiple of $5$. Consequently, $k_2-1 = 1$ or $k_2-1=\pm 7$ (i.e., $k_2 =2,8$ or $-6$). But $k_2 + 1$ must be a multiple of $3$ or $7$ (due to the second constraint). So $k_2 \neq -6$. Therefore, $k_2=2$ or $k_2=8$.
Now suppose $k_2=2$. Then the constraints simplify to
$$k_3 k_4 = 2^4 \times 3^2$$
$$(k_3+1)(k_4+1) = 3 \times 7^2$$
$$(k_3-1)(k_4-1) = 5^2 \times 7$$
It can be verified that these equations do not have any solution.
Therefore, we are left with $\color{red}{k_2 = 8}$ only. In that case, the equations simplify to
$$k_3 k_4 = 2^2 \times 3^2$$
$$(k_3+1)(k_4+1) = 7^2$$
$$(k_3-1)(k_4-1) = 5^2$$
These equations can easily be solved to result in $\color{red}{k_3 =k_4 = 6}$.

A: Lemma:
Let
$
P(x)=
a_nx^n+
a_{n-1}x^{n-1}+
...
+
a_1x+
a_0
$
be a polynomail with integral coefficeint;
i.e. $a_i \in \mathbb{Z}$ and $a_n\neq 0$.
Let $\alpha=\dfrac{r}{s}$ be a rational root of this equation,
with $\gcd(r,s)=1$;
then we must have: $s \mid a_n$ and $r \mid a_0$ .
Proof: Let $\alpha=\dfrac{r}{s}$ be a rational root of $P(x)$,
with $\gcd(r,s)=1$; then we have:
$$
0=
P(\alpha)=
a_n\alpha^n+
a_{n-1}\alpha^{n-1}+
...
+
a_1\alpha+
a_0
\Longrightarrow
\\
\ \ \ \ \
\ \ \ \ \
0=
a_n(\dfrac{r}{s})^n+
a_{n-1}(\dfrac{r}{s})^{n-1}+
...
+
a_1(\dfrac{r}{s})+
a_0
\Longrightarrow
\\
\ \ \ \ \
\ \ \ \ \
\ \ \ \ \
\ \ \ \ \
\ \ \ \ \
\
0=
a_nr^n+
a_{n-1}r^{n-1}s+
...
+
a_1rs^{n-1}+
a_0s^n
\ \ \ \ \ \ \
\star
$$
note that $r$ divides the LHS of $\star$; so it must divides the RHS;
also notice that $r$ divides all terms except $a_0s^n$;
so it must divides $a_0s^n$;
by Euclid's lemma we can conclude that $r|a_0$.
note that $s$ divides the LHS of $\star$; so it must divides the RHS;
also notice that $s$ divides all terms except $a_nr^n$;
so it must divides $a_nr^n$;
by Euclid's lemma we can conclude that $s|a_n$.

In the special case of this question we know $576=2^63^2$, so we must have:
$$s|1 \ \ \ \ \text{and} \ \ \ \ r|2^63^2 $$
so it only suffices to check all the integers $\pm d$;
where $d$ is a positive divisor of $576$;
one can check by hand that the only posibilities are $-2$ and $-6$.

A: For $$f(x) = x^4+22x^3+172x^2+552x+576,$$
notice that if $x\geq0$ then $f(x) \geq 576 > 0,$
so all roots of the equation $f(x) = 0$ are negative.
Since the roots are $-k_1, -k_2, -k_3, -k_4,$
this tells us that $k_1, k_2, k_3, k_4$ are all positive.
That leaves only a few possible values of $k_i$ that could occur
in the equation
$$(k_1-1)(k_2-1)(k_3-1)(k_4-1) = 175 = 5^2 \cdot 7.$$
The factors of $175$ are $1, 5, 5^2 = 35, 7, 5\cdot7 = 35,$
and $5^2 \cdot 7 = 175.$
(I chose this equation to start with because $175$ has fewer factors to consider than either $576$ or $1323$.)
Since each factor $k_i - 1$ must be a factor of $175,$
the possible values of any $k_i$ can only be among the numbers
$2, 6, 26, 8, 36,$ and $176.$
From
$$k_1k_2k_3k_4 = 576 = 2^6 \cdot 3^2, \tag1$$
we know any of the $k_i$ can have only $2$ or $3$ as prime factors.
So $k_i \neq 26 = 2 \cdot 13$ and $k_i \neq 176 = 16 \cdot 11.$
From
$$(k_1+1)(k_2+1)(k_3+1)(k_4+1) = 1323 = 3^3 \cdot 7^2,$$
we know $k_i + 1$ must be divisible by $3$ or by $7.$
So $k_i + 1 \neq 37,$ and therefore $k_i \neq 36.$
Therefore the only possible values of any of the $k_i$ are $2,$ $6,$ or $8.$
But Equation $(1)$ implies either that one of the $k_i$ is divisible by $9$
(which we now know cannot be true) or that two of the $k_i$ are each divisible by $3.$ If $k_i$ is divisible by $3,$ its only possible value is $6$ (since neither $2$ and $8$ is divisible by $3$).
Without loss of generality, we can set $k_1 = k_2 = 6.$
Dividing both sides of Equation $(1)$ by $k_1k_2 = 36,$
we now have $k_3k_4 = 2^4.$ Each of $k_3$ or $k_4$ can then only be $2$ or $8$ (since $6$ is not a power of $2$), but if one is $2$ then the other is $8$ and vice versa. So without loss of generality we can set $k_3 = 2$ and
$k_4 = 8.$
The four roots therefore are
$-k_1 = -6,$ $-k_2 = -6,$ $-k_3 = -2,$ and $-k_4 = -8.$
In ascending order they are $-8, -6, -6, -2.$

A: Your equations (2) and (3) seem an over-complicated way to attack the problem.
The fact that $k_1k_2k_3k_4 = 576 = 2^6 3^2$ is useful. So is the fact that $k_1 + k_2 + k_3 + k_4 = -22$, which you can prove in a similar fashion. (Note, both of these are general results for any polynomial).
For a third useful result, by inspection the equation has no positive roots, since the sign of every term is positive. This is a particular case of "Descartes' rule of signs."
Those three facts are usually enough to guess the values of $k_i$. If not, it may be simpler to try to find two quadratic factors, rather than four linear ones - the fact that the quadratic factors are not unique can often make it easier to guess one pair of them.
For this specific polynomial, this means that $0< k_i < 22$ for each $k_i$. The only possible integer values in that range which are factors of $576$ are $1, 2, 3, 4, 6, 8, 9, 12, 16, 18$.
By trial and error $1$ does not give a root, but $2$ does. That eliminates $18$, because $18+2+2+2 > 22$.
So to get the $3^2$ factor in $576$, we need to include some of $3, 6, 9$, or $12$. Of those four, the only root is $6$.
So we must have  $k_1 = k_2 = 6$ and we already know $k_3 = 2$ gives a root. So $k_4 = 8$.

A: We set
$$f(x)=x^4+22x^3+172x^2+552x+576=0$$
and
$$f_0=f(0)=k_1k_2k_3k_4=2^6 3^2=576$$
$$f_{1}=f(1)=(k_1+1)(k_2+1)(k_3+1)(k_4+1)=3^3 7^2=1323$$
$$f_{-1}=f(-1)=(k_1-1)(k_2-1)(k_3-1)(k_4-1)=5^2 7 =175$$
We can check for each of the $42$ negative  or positive divisors $d$ of $f_0$  if $-d$ is a zero of the polynomial.
Easier is to check for the only $24$ negative  or positive divisors $d$ of $f_1$  if $-d+1$ is a zero of the polynomial.
More easier is to check for the only $12$ negative  or positive divisors $d$ of $f_{-1}$  if $-d-1$ is a zero of the polynomial.
The divisors of $f_{-1}$ can be found in column $d_1$ to $d_{12}$ of line $1$ of the following table. These numbers are possible candidates for the numbers  $k_1-1,k_2-1,k_3-1,k_4-1$.
$$\begin{array}{|r|l|c|r|r|r|r|r|r|r|r|r|r|r|r|}
\hline
\text{line}&\text{pfactors}&\text{type}&d_1&d_2&d_3&d_4&d_5&d_6&d_7&d_8&d_9&d_{10}&d_{11}&d_{12}\\
\hline
1&5^2 7&k-1&-175 & -35& -25& -7& -5& -1& 1& 5& 7& 25& 35& 175\\
\hline
2&2^6 3^2&k&-174& -34& -24&-6& -4& 0& 2& 6& 8& 26& 36& 176\\
\hline
3&&p^e&29&17&&&&0&&&&13&&11\\
\hline
4&3^3 7^2&k+1&-173& -33& -23& -5& -3& 1& 3& 7& 9& 27& 37& 177\\
\hline
5&&p^e&173&11&23&5&&&&&&&37&59\\
\hline
6&&\text{possible}&&&&&\checkmark&&\checkmark&\checkmark&\checkmark&&&\\
\hline
7&5^2 7&k-1&&&&&5&&1&5&7&\\
\hline
8&2^6 3^2&k&&&&&2^2&&2&2\phantom \cdot 3 &2^3&\\
\hline
9&3^3 7^2&k+1&&&&&3&&3&7&3^2&\\
\hline
\end{array}$$
If we add $1$ to them we get Line $2$ with the possible candidates for $k_1,k_2,k_3,k_4.$ If we add $2$ to them we get Line $4$ with the possible candidates for $k_1+1,k_2+1,k_3+1,k_4+1.$ The product of four the right $d_j$ values must be equal to the value $\text{pfactors}.$
On the one hand they are  $1$ larger than the numbers $k-1$ in line $1$ on the other hand they must be a divisor of $f_0$, which $2^6 3^2.$ For example $-175$ in column $d_1$ and line $1$ is a divisor of $f_{-1}$
So a possible candidate for $k$  satisfies $k_i-1=-175$ and therefore $k_i=-174.$ But $-174$ contains the prime factor $29$ and $29$ is not a prime factor of $f_0$, which $2^6 3^2.$ So $-174$ cannot be a divisor of $f_0$ and so $-174$ is not a possible $k_i.$ We can eliminate column $d_1$ can be eliminated. The prime factor that shows that $k$ is not a divisor of $2^6 3^2$ is shown in line $3.$
Line $5$ shows the prime factor that shows that $k_i+1$ is not a divisor of $f_{+1}$, which is $3^3 7^2.$
All columns can be eliminated except $d_5,d_7,d_8,d_9.$ Line $6$ puts a check mark in each of these columns. Line $7,8,9$ shows the the prime factorization of the values $k-1, k, k+1$
 but only the columns that were not eliminated.
Comparing the prime factor $7$ in the columns of line $7$ one sees that  $d_9$ is a necessary column. Comparing again the prime factor $7$ in the columns of line $9$ one sees that the divisor  $d_8$ is used twice.
So the last divisor can only be $d_7$ and the solution is $d_7 d_8^2 d_9.$ So we have
$$\begin{eqnarray}
k_1&=&2\\
k_2&=&6\\
k_3&=&6\\
k_4&=&8.
\end{eqnarray}$$

A: We have
$\displaystyle 576=2^6 \cdot 3^2$
The number $\displaystyle 3$ will be factor of at most two roots, so at least two roots will be powers of $\displaystyle 2$. So let's try the candidate roots
$\displaystyle \pm 2, \pm 4, \pm 8, \pm 16, \pm 32, \pm 64$
So we find two roots:
$\displaystyle x_1=-2, x_2=-8$
We will have now
$\displaystyle 22=-(-2)-(-8)-x_3-x_4 \Rightarrow$
$\displaystyle 12=-x_3-x_4$
and
$\displaystyle \frac{576}{(-2)(-8)}=36=x_3 x_4$
From the last two systems of equations we are easily led to the equation
$\displaystyle x_{3,4}^2+12x_{3,4}-36=0$
which is easily solved and gives us
$\displaystyle x_3=x_4=-6$


text:
Q: Crop part of an image and paste it into another with Imagemagick does not work I have two images and I want to crop a part of the first one, and paste it into the other one in a specific place using imagemagick. Also the crop part would be gray
I want this: http://imgur.com/3PomJ9k
But I got this: http://imgur.com/5XmhytN
I have tried:
convert source.jpg ( +clone -crop 240x270+595+140 -resize 112x146 -type Grayscale ) -geometry +10+200 -composite destiny.jpg

but as you see, it does not works as expected.
Although the crop part is cloned as gray, the whole first image is cloned too, but I need to keep in background the second image in color and the crop part in gray in front of it.
Some ideas?

A: From our discussion in chat, I think you need something along these lines - you may need to fiddle with the actual numbers but hopefully the concept is clear:
convert other.jpg \( source.jpg -crop 240x270+595+140 -colorspace gray -resize 116x150! \) -geometry +4+108 -composite result.png


text: Q: How should I interpret the results of the OLS regression I did for 2 cointegrated variables? So I've been doing cointegration between two variables that are both I(1). I run the OLS regression between the variables to possibly check the stationary of the residuals. However when I checked the coefficient of the regression, this is what it looks like. If i recall correctly, the coefficient in this would suppose to be the long run relationship if I follow Engle and Granger approach. Is this results still valid?


text:
Q: NO result found error Hi my site name is Stack. I just added some content with image.When I logged out from drupal  its not showing and giving message like no result found. But it is showing with image when I logged in to drupal. What is the problem? is my file path is wrong?.

A: I can't leave a comment so I'm posting this as an answer, sorry.
The "Extra" menu in the footer of your page is editable by anonymous users. Make sure sure you uncheck "anonymous user" on the "Administer menus and menu items" permission.

A: Check persmissions for anonymous users (admin/people/permissions) and/or clear all caches (admin/config/development/performance) if there are no permission issues.


text:
Q: Send (Load) a URL to web browser and run it in background in APEX Does Apex/Visualforce allow a URL which is stored as string in apex and run it in web browser in background.
Actually, that url is returned from a Docusign RestAPI callout for posting the envelope into "correction" status. The Envelope correction Status is not activated until i manually paste the url (link) in to a web browser and run it.
Does anyone know how to run a url programatically in a web browser through Apex/Visualforce in background ?
(or) Is there anyway that i could activate the "correction" status of envelope in Docusign other than running the URL in web browser?

A: You can use the HttpRequest class directly from Apex to make a GET request to the given URL. This would be equivalent to what the browse does. The only difference would be if the browser sends a specific cookie, which can also be replicated in Apex if you have the required cookie value.
You will need to add the domain in the remote site settings as well.


text:
Q: Change gridview column header's BackColor Successfully,placed an image on one of the column headers of my gridview.But its backcolor is all white now, unlike other column headers which are grey, the default back color.How can I change/paint the white to grey.
private void GridViewSale_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
  {
      if (e.RowIndex < 0 && e.ColumnIndex == 1)
      {
          Rectangle rec = new Rectangle(4, 5, 14, 14);
          e.Graphics.DrawImage(Properties.Resources.DelOn, rec);
          e.Handled = true;
          e.CellStyle.BackColor = Color.DeepPink; (//Not working)
      }
  }

A: First Set EnableHeadersVisualStyles="false" inside your DataGridView.Then,
    DataGridViewColumn gridviewColumnName = yourGridviewName.Columns[0]; // will set the first column
    gridviewColumnName .HeaderCell.Style.BackColor = Color.DeepPink;


text:
Q: How do access default parameters in Clojure cli? I am wondering how I can access the default parameters in my opts, after they've been parased by cli args. I am invoking my program
./rexfer --ifn1 --ifm1 --ofn1 --ofn3
(defn parse-args
  "Using the newer cli library, parses command line args."
  [args]
  (cli args
       ["-r" "--ifn1" ".csv input file"  :default "standfiletrans_acre.csv"]
       ["-p" "--ifn2" ".csv input file"  :default "pp_report_to_change.csv"]
       ["-m" "--ifm1" ".csv input file"  :default "columns.csv"]
       ["-v" "--ofn1" ".csv output file" :default "re_values.csv"]
       ["-x" "--ofn2" ".csv output file" :default "re_pp.csv"]
       ["-u" "--ofn3" ".csv output file" :default "re_mixed_use_ratio.csv"]
       ["-t" "--rpt"  ".csv pipe delimited output file" :default "xfer.csv"]))

(defn -main
  [& args]
  (let [[opts args banner] (parse-args args)

This is the output of opts after being parsed
{:rpt xfer.csv, :ofn3 re_mixed_use_ratio.csv, :ofn2 re_pp.csv, :ofn1 --ofn3, :ifm1 --ifn1, :ifn2 pp_report_to_change.csv, :ifn1 standfiletrans_acre.csv}
(:ifn1 opts) returns --ifn1, not standfiletrans_acre.csv.

A: The :default keyword is used when the argument is not given at all. If you add the argument, don't supply a value, and then supply the next argument it will read the next argument as the value supplied to the first argument:
arthur@a:~/args/src/args$ lein run --ifn1 --FOO --ifn2 --ifm1
All namespaces already :aot compiled.
options are:
{:rpt "xfer.csv"
 :ofn3 "re_mixed_use_ratio.csv",
 :ofn2 "re_pp.csv",
 :ofn1 "re_values.csv",
 :ifm1 "columns.csv",
 :ifn2 "--ifm1",
 :ifn1 "--FOO"}
arguments are:
[]
the banner text is:
 Usage:

 Switches    Default                  Desc
 --------    -------                  ----
 -r, --ifn1  standfiletrans_acre.csv  .csv input file
 -p, --ifn2  pp_report_to_change.csv  .csv input file
 -m, --ifm1  columns.csv              .csv input file
 -v, --ofn1  re_values.csv            .csv output file
 -x, --ofn2  re_pp.csv                .csv output file
 -u, --ofn3  re_mixed_use_ratio.csv   .csv output file
 -t, --rpt   xfer.csv                 .csv pipe delimited output file

In this example the :default value is only used for the values not on the list.


text:
Q: dynamic breadcrumb from parent to child in angular 2 I want to build a breadcrumb feature that is dynamic. While it works great, it gets rendered with the first element so child component receives the first link at first then the rest follows.
What I want is in the child component to show the correct length of the links passed to it from the parent component. Currently, it shows all links (can loop them well) but the length is equal only to the very first link(s) set on the oninit of parent component.
Child component :
export class BCComponent implements OnInit {
    @Input() breadcrumb:string[];

    last_link_index:number=0; //what is the array index of the last element?
    constructor() {}

    isActive(row){
     let reply:string='';
     //is it the last link in the breadcrumb?
     if(row==this.breadcrumb.length-1){
        reply='active';
     }
     return reply
    }

    ngOnInit() {

   this.last_link_index=this.breadcrumb.length;

   console.log(this.last_link_index,this.breadcrumb.length,this.breadcrumb);
    }
}

In the template, the output is supposed not to create link for the very last element in the array of links.

  {{link.name}}

Parent Component :
in parent component, the links will depend on the situation and depth. For example, I have this links:
links=[{link:'member/homes',icon:'fa fa-home',text:'Homes Owned'},{link:'#',icon:'fa fa-home-o',text:'RSD8987'}]

If it is fixed like this, the links and their length are correct thus renders well. But not if I have further modify the links inside a backend call as shown below :
Parent component :
 ngOnInit() {
    this.breadcrumb.push(
        {
        'name':"Plots",
        'link':'members/plots/',
        'icon':'fa-home'
        }
        );

    //get the plot we wanna work with here first
    this.sub = this.route.params.subscribe(params => {
    this.requested_home = params['home_id'];

    //Get home description first. build links only if it is found
    this.individual_service.homeDetail(this.requested_home,'n').subscribe(
          data => {

            //home found. So build the links
      this.breadcrumb.push(
        {
        'name':"Text",
        'link':'members/homes/',
        'icon':'fa-tree'
        },

        {
        'name':"Home Detail",
        'link':'#',
        'icon':'fa-sticky-note'
        }
        );

The issue now is the child components reports ALL links but the length is just 1 (which is set at the start of init).

A: Implement ngOnChanges
ngOnChanges(changes: SimpleChanges) {
  if(changes.breadcrumb) {
     this.last_link_index=this.breadcrumb.length;
  }
}


text:
Q: How to create a PixBuf from file with Gdk3? Environment: Python3
Libraries:
from gi.repository import Gtk, Gdk
import cairo

I want to create a 'pixbuf from file' but the method does not longer exist in Gdk3.
pb = Gdk.pixbuf_new_from_file('sunshine.png')
Gdk.cairo_set_source_pixbuf(cr, pb, 0, 0)

Result in: AttributeError: 'gi.repository.Gdk' object has no attribute 'pixbuf_new_from_file'
Does anybody know how to do this with Gdk3?
Seems that Gdk3 only support these methods:
gdk_pixbuf_get_from_window
gdk_pixbuf_get_from_surface

Update
Found it out myself:
image = Gtk.Image()
image.set_from_file('sunshine.png')
pixbuf = image.get_pixbuf()
Gdk.cairo_set_source_pixbuf(cr, pixbuf, 10, 10)

A: The question is old, but maybe it helps someone:
from gi.repository import GdkPixbuf
pixbuf = GdkPixbuf.Pixbuf.new_from_file('sunshine.png')

Tested on GdkPixbuf._version == '2.0'

A: I dont know much about python, but in general you should not using gtk image directly to load file. Use GdkPixbuf instead because of error handling. The reason there is no attribute (in python) "pixbuf new from file", is because for much of the GdkPixbuf handling, still using (in C) gdk-pixbuf-2.0. Why they haven't port or still keeping it, I have no idea. In python you have to find the "gdk pixbuf" module instead of using GDK3, as Schcriher pointed out.


text:
Q: Why wont redirect work after fetch call inside getserversideprops The main issue I am facing is whenever I call a redirect outside a fetch function it works but as soon as I put that redirect inside a response of a fetch function it wont redirect the page.your text.
I was trying to allow google sign up to create accounts for the users. If a user uses google sign in it allows the person to go to the newaccount.js file. Once inside that path it checks if that google username exists in the database . If it does,It redirects the user to the home page . If not it asks the user to enter a password and save that username and password on the database.
The code :
export async function getServerSideProps({ req, res }) {
    const session = await getSession({ req })
    // console.log("this first runs")
    // console.log(session)
    if (!session) {
        console.log("this not running")
        return {
            redirect: {
                destination: '/',
                permanent: false
            }
        }
    } else {

        let username = session.user.name
        let email = session.user.email
        let body = { username, email }
        await fetch("http://localhost:3000/api/checkuser", {
            method: "POST",
            body: JSON.stringify(body),
        }).then((res) => res.json())
            .then((result) => {
                console.log(result)
                if (result.success == true) {
                    if (result.exists == false) {
                        console.log("user added success fully")
                    } else {
                        return {
                            redirect: {
                                destination: '/',
                                permanent: false
                            }
                        }
                    }
                } else {
                    console.log("something went wrong")
                }
            });
    }

    return {
        props: { session }
    }
}

A: Your code does not return the redirect in your else statement. One way to solve this is by await-ing all asynchronous actions, like so:
} else {
  let username = session.user.name
  let email = session.user.email
  let body = { username, email }
  const response = await fetch("http://localhost:3000/api/checkuser", {
    method: "POST",
    body: JSON.stringify(body),
  })
  const result = await res.json()
  console.log(result)
  if (result.success == true) {
    if (result.exists == false) {
      console.log("user added success fully")
    } else {
      return {
        redirect: {
          destination: '/',
          permanent: false
        }
      }
    }
  } else {
    console.log("something went wrong")
  }
}


text:
Q: Image upload crop resize using jquery and servlet I am developing a web application where the user has to upload the pics.Is their any widget or plugin to upload a image to the store in the data base and display the same image in a given box, I am using jquery html5 in the front end and serlvet and my sql at the back end. I will very happy if I get image resizer and crop option along.

A: http://www.codeforest.net/how-to-crop-an-image-using-jquery-and-php
That might be of some use to you, they show a preview to the user and let them crop the image also.


text:
Q: Reindex pivot table to add missing days and times I try to make a heatmap out of an activitylog using pandas pivottable. To add missing times and dates I use the reindex function but I fail to reindex by columns.
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'Date':['2015-11-10 18:39:00','2015-11-14 11:30:00','2015-11-14 13:48:00','2015-11-15 16:06:00',
    '2015-11-16 21:08:00','2020-08-31 18:06:00','2020-09-18 11:17:00','2020-09-19 15:41:00',
    '2020-09-25 16:28:00','2020-09-25 19:45:00']})
df['Date'] = pd.to_datetime(df['Date'])

hm = df.pivot_table(columns=df['Date'].dt.hour, index=df['Date'].dt.day_name(), aggfunc='count', fill_value=0, dropna=False)
hm = hm.reindex(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], axis='index')
hm = hm.reindex(range(0,24), axis='columns', fill_value=0)

figg, ax2 = plt.subplots(figsize=(20,3))
im = ax2.imshow(hm)

I get the following error message
ValueError: Buffer dtype mismatch, expected 'Python object' but got 'long'

The expected output should be
           0   1   2   3   4   5   6   7   8   9       20  21  22  23
Monday     0   0   0   0   0   0   0   0   0   0  ...   0   0   0   0
Tuesday    0   0   0   0   0   0   0   0   0   0  ...   0   0   0   0
Wednesday  0   0   0   0   0   0   0   0   0   0  ...   0   0   0   0
Thursday   0   0   0   0   0   0   0   0   0   0  ...   0   0   0   0
Friday     0   0   0   0   0   0   0   0   0   0  ...   0   0   1   0
Saturday   0   0   0   0   0   0   0   0   0   0  ...   0   1   0   0
Sunday     0   0   0   0   0   0   0   0   0   0  ...   0   0   1   0

A: The output you're getting is a MultiIndex column index (the first level is "Date" then the second level are the hours). The reason this is happening is because you did not supply a values argument to your call to pivot_table
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'Date':['2015-11-10 18:39:00','2015-11-14 11:30:00','2015-11-14 13:48:00','2015-11-15 16:06:00',
    '2015-11-16 21:08:00','2020-08-31 18:06:00','2020-09-18 11:17:00','2020-09-19 15:41:00',
    '2020-09-25 16:28:00','2020-09-25 19:45:00']})
df['Date'] = pd.to_datetime(df['Date'])

# Note the addition of the `values` argument
hm = df.pivot_table(columns=df['Date'].dt.hour, index=df['Date'].dt.day_name(), values="Date", aggfunc='count', fill_value=0, dropna=False)

# you can also reindex both the index and columns in 1 call
hm = hm.reindex(
    index=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
    columns=range(24),
    fill_value=0
)

print(hm)
Date       0   1   2   3   4   5   6   7   8   9   ...  14  15  16  17  18  19  20  21  22  23
Date                                               ...
Monday      0   0   0   0   0   0   0   0   0   0  ...   0   0   0   0   1   0   0   1   0   0
Tuesday     0   0   0   0   0   0   0   0   0   0  ...   0   0   0   0   1   0   0   0   0   0
Wednesday   0   0   0   0   0   0   0   0   0   0  ...   0   0   0   0   0   0   0   0   0   0
Thursday    0   0   0   0   0   0   0   0   0   0  ...   0   0   0   0   0   0   0   0   0   0
Friday      0   0   0   0   0   0   0   0   0   0  ...   0   0   1   0   0   1   0   0   0   0
Saturday    0   0   0   0   0   0   0   0   0   0  ...   0   1   0   0   0   0   0   0   0   0
Sunday      0   0   0   0   0   0   0   0   0   0  ...   0   0   1   0   0   0   0   0   0   0

A: Welcome to StackOverflow.
Your index here is a MultiIndex, with the first level being "Date." Pandas thinks you're trying to change this part of the index, which doesn't work because it's a string. (I think. Not sure about this.)
If you drop the first level of the index using droplevel(), you'll have a regular integer index, and it will work. I also ended up with NaNs in the result, so I added a fillna() call too.
hm = df.pivot_table(columns=df['Date'].dt.hour, index=df['Date'].dt.day_name(), aggfunc='count', fill_value=0, dropna=False)
hm = hm.reindex(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], axis='index')
hm.columns = hm.columns.droplevel(0)
hm = hm.reindex(range(0,24), axis='columns', fill_value=0)
hm = hm.fillna(0)

I get the following plot as a result.


text:
Q: Disable E_STRICT errors in php.ini I am trying to disable E_STRICT errors directly in the php.ini. Here's what I put:
display_errors = On
error_reporting = E_ALL & ~E_STRICT

My question is:

*

*1 - why is it still (after restarting apache) reporting E_STRICT errors?

*2 - when display_errors is set to Off are the errors still being logged to apache error logs?

A: It is still doing so because I have added a custom error handler using set_error_handler. In that case, as the manual says:

error_reporting() settings will have no effect and your error handler
  will be called regardless

The second question still remains though ;)

A: in your script
error_reporting = E_ALL & ~E_STRICT

change to
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT

If you failed to  access to the php.ini, you can potentially put this in your .htaccess file:
php_value error_reporting 30711

i wish it will works ...Thank you

A: try
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT

using .htaccess file:
php_value error_reporting 30711

and restart your apache server


text:
Q: Creation of lua object from c++ base class I have exported from C++ into lua such base class:

class IState
{
    public:
        virtual ~IState() { }

        virtual void Init() = 0;
        virtual void Update(float dSeconds) = 0;
        virtual void Shutdown() = 0;
        virtual string Type() const = 0;
};

// Wraper of state base class for lua
struct IStateWrapper : IState, luabind::wrap_base
{
    virtual void Init() { call<void>("Init"); }
    virtual void Update(float dSeconds) { call<void>("Update", dSeconds); }
    virtual void Shutdown() { call<void>("Shutdown"); }
    virtual string Type() const { return call<string>("Type"); }
};

Export code:

        class_<IState, IStateWrapper>("IState")
            .def("Init", &IState::Init)
            .def("Update", &IState::Update)
            .def("Shutdown", &IState::Shutdown)

The next part: I have StateManager with function: void StateManager::Push(IState*) and it's export:
        class_<StateManager>("StateManager")
            .def("Push", &StateManager::Push)

Now, I want to create object of type IState in Lua and push it into StateManager:
-- Create a table for storing object of IState cpp class
MainState = {}

-- Implementatio of IState::Init pure virtual function
function MainState:Init()
    print 'This is Init function'
end

function MainState:Update()
    print 'this is update'
end

function MainState:Shutdown()
    print 'This is shutdown'
end

state = StateManager
state.Push(MainState)

Of course, this won't work. I don't know how to say that MainState if the object of type IState:
error: No matching overload found, candidates: void Push(StateManager&,IState*)

UPD
    module(state, "Scene") [
        class_<StateManager>("StateManager")
            .def("Push", &StateManager::Push),

        class_<IState, IStateWrapper>("IState")
            .def("Init", &IState::Init)
            .def("Update", &IState::Update)
            .def("Shutdown", &IState::Shutdown)
    ];

    globals(state)["StateManager"] = Root::Get().GetState(); // GetState() returns pointer to obj

After example:
class 'MainState' (Scene.IState)
function MainState:__init()
    Scene.IState.__init(self, 'MainState')
end
...
state = StateManager
state:Push(MainState())

error: no static '__init' in class 'IState'
And should state = StateManager has brackets? With them there is error that no such operator.

A: You can't just throw a table at Luabind. If you intend to derive from a Luabind-defined class, you have to follow the rules of Luabind. You have to create a Lua class with Luabind's tools, derived from your IState class. That would look like this:
class 'MainState' (IState) --Assuming that you registered IState in the global table and not a Luabind module.

function MainState:__init()
    IState.__init(self, 'MainState')
end

function MainState:Init()
    print 'This is Init function'
end

function MainState:Update()
    print 'this is update'
end

function MainState:Shutdown()
    print 'This is shutdown'
end

state = StateManager()
state:Push(MainState())

Also, take note of the changes to the last two lines. Specifically, how StateManager is called, not simply set into state). Also, how you use state: and not state.. I have no idea how this code even functioned in your example.


text:
Q: How to Read HTML out of a webpage and use it as body of HTML Auto-Responder E-Mail I am working on an HTML auto responder email. If there is a simpler way than what i am doing please let me know.
So far, i've built "pagename.aspx" and i read this page into a string variable, then use this variable as the BODY of the mail. This works.
The page optionally accepts a QueryString called "leadID". This is used to pull data from a database and populate fields on this page. This also works fine when i manually browse to the page - pagename.aspx?leadid=xyz
My Problem / Question is, how do i pass this querystring to the page and return the resulting HTML output of the page into a string , which can then be used as the body of my email.
Again, if there is a better way please let me know. I'm using LINQ to SQL, VB.NET and ASP.NET 3.5.
Thanks a million.

A: The easiest way is just to do a WebRequest to it:
string url = "...";
string result;

HttpWebRequest webrequest = (HttpWebRequest) HttpWebRequest.Create(url);
webrequest.Method        = "GET";
webrequest.ContentLength = 0;

WebResponse response = webrequest.GetResponse();

using(StreamReader stream = new StreamReader(response.GetResponseStream())){
    result = stream.ReadToEnd();
}

A: As described in this article, you could use the HttpWebRequest class to retrieve the stream of data from your page "pagename.aspx?leadID=1". But that could cause a bit of overhead to your application due to the additional HTTP request.
Wouldn't it be possible/better to generate your HTML content from a simple class? What content generates your page?
Edit:
As asked by Khalid here is a simple class to generate a dynamic HTML file using your leadID parameter and a gridview control. It's only an example, you would need to custom it and make more reusable:
using System;
using System.Text;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI;

public class PageBroker
{

    /*
     * How to use PageBroker:
     *
     *  string leadID = "xyz"; // dynamic querystring parameter
     *  string pathToHTML = Server.MapPath(".") + "\\HTML\\leadForm.html"; //more detail about this file below
     *  PageBroker pLeadBroker = new PageBroker(pathToHTML, leadID);
     *  Response.Write(pLeadBroker.GenerateFromFile()); // will show content of generated page
     */

    private string _pathToFile;
    private StringBuilder _fileContent;
    private string _leadID;

    public PageBroker(string pathToFile, string leadID)
    {
        _fileContent = new StringBuilder();
        _pathToFile = pathToFile;
        _leadID = leadID;
    }

    public string GenerateFromFile() {
        return LoadFile();
    }
    private string LoadFile()
    {
        // Grab file and load content inside '_fileContent'
        // I used an html file to create the basic structure of your page
        // but you can also create
        // a page from scratch.
        if (File.Exists(_pathToFile))
        {
            FileStream stream = new FileStream(_pathToFile, FileMode.Open, FileAccess.Read);
            StreamReader reader = new StreamReader(stream);
            while (reader.Peek() > -1)
                _fileContent.Append(reader.ReadLine() + "\n");
            stream.Close();
            reader.Close();

            InjectTextContent();
            InjectControlsContent();
        }
        return _fileContent.ToString();
    }

    // (Ugly) method to inject dynamic values inside the generated html
    // You html files need to contain all the necesary tags to place your
    // content (for example: '__USER_NAME__')
    // It would be more OO if a dictionnary object was passed to the
    // constructor of this class and then used inside this method
    // (I leave it hard-coded for the sake of understanding but
    // I can give you a more detailled code if you need it).
    private void InjectTextContent() {
        _fileContent.Replace("__USER_NAME__", "Khalid Rahaman");
    }

    // This method add the render output of the controls you need to place
    // on the page. At this point you will make use of your leadID parameter,
    // I used a simple array with fake data to fill the gridview.
    // You can add whatever control you need.
    private void InjectControlsContent() {
        string[] products = { "A", "B", "C", "D" };
        GridView gvProducts = new GridView();
        gvProducts.DataSource = products;
        gvProducts.DataBind();

        // HtmlTextWriter is used to write HTML programmatically.
        // It provides formatting capabilities that ASP.NET server
        // controls use when rendering markup to clients
        // (http://msdn.microsoft.com/en- us/library/system.web.ui.htmltextwriter.aspx)
        // This way you will be able to inject the griview's
        // render output inside your file.
        StringWriter gvProductsWriter = new StringWriter();
        HtmlTextWriter htmlWrit = new HtmlTextWriter(gvProductsWriter);
        gvProducts.RenderControl(htmlWrit);
        _fileContent.Replace("__GRIDVIEW_PRODUCTS__", gvProductsWriter.ToString());
    }
}


text:
Q: How to set support library snackbar text color to something other than android:textColor? So I've started using the new Snackbar in the Design Support Library, but I found that when you define "android:textColor" in your theme, it applies to the text color of the snackbar. This is obviously a problem if your primary text color is dark.

Does anyone know a way around this or have advice for how I should color my text?
EDIT January 2017: (Post-Answer)
While there are some custom solutions to fix the problem below, it's probably good to provide the correct way to theme Snackbars.
Firstly, you probably shouldn't be defining android:textColor in your themes at all (unless you really know the scope of what is using the theme). This sets the text color of basically every view that connects to your theme. If you want to define text colors in your views that are not default, then use android:primaryTextColor and reference that attribute in your custom views.
However, for applying themes to Snackbar, please reference this quality guide from a third party material doc: http://www.materialdoc.com/snackbar/ (Follow the programmatic theme implementation to have it not rely on an xml style)
For reference:
// create instance
Snackbar snackbar = Snackbar.make(view, text, duration);

// set action button color
snackbar.setActionTextColor(getResources().getColor(R.color.indigo));

// get snackbar view
View snackbarView = snackbar.getView();

// change snackbar text color
int snackbarTextId = android.support.design.R.id.snackbar_text;
TextView textView = (TextView)snackbarView.findViewById(snackbarTextId);
textView.setTextColor(getResources().getColor(R.color.indigo));

// change snackbar background
snackbarView.setBackgroundColor(Color.MAGENTA);

(You can also create your own custom Snackbar layouts too, see the above link. Do so if this method feels too hacky and you want a surely reliable way to have your custom Snackbar last through possible support library updates).
And alternatively, see answers below for similar and perhaps faster answers to solve your problem.

A: Currently (January 2020) with
com.google.android.material:material:1.2.0 and probably also 1.1.0
Is definitely the best way how to do it by overrides these styles:
<item name="snackbarStyle">@style/Widget.MaterialComponents.Snackbar</item>
<item name="snackbarButtonStyle">@style/Widget.MaterialComponents.Button.TextButton.Snackbar</item>
<item name="snackbarTextViewStyle">@style/Widget.MaterialComponents.Snackbar.TextView</item>

If you use a material theme with .Bridge at the end, for some reason, neither of these styles are defined. So Snackar will use some legacy layout without these styles.
I found in the source code that both snackbarButtonStyle and snackbarTextViewStyle must be defined otherwise it will be not used.

A: If you will migrate your code to AndroidX, the TextView property is now:
com.google.android.material.R.id.snackbar_text

A: The only way I see is using getView() and cycling through its child. I don't know if it's going to work, and it is bad as it looks. I hope they'll add some API about this issue soon.
Snackbar snack = Snackbar.make(...);
ViewGroup group = (ViewGroup) snack.getView();
for (int i = 0; i < group.getChildCount(); i++) {
    View v = group.getChildAt(i);
    if (v instanceof TextView) {
        TextView t = (TextView) v;
        t.setTextColor(...)
    }
}
snack.show();

A: I know this has been answered already but the easiest way I found was directly in the make using the Html.fromHtml method and a font tag
Snackbar.make(view,
       Html.fromHtml("Tap to open").show()

A: Use the Snackbar included in the Material Components Library and apply the

*

*setTextColor to define the text color

*setActionTextColor to define the text color used by the action. You can use a color or a color selector

*setBackgroundTint to define the background color of the Snackbar

Something like:
Snackbar snackbar = Snackbar.make(view, "My custom Snackbar", Snackbar.LENGTH_LONG);
snackbar.setTextColor(ContextCompat.getColor(this,R.color.xxxxx));
snackbar.setActionTextColor(ContextCompat.getColor(this,R.color.my_selector));
snackbar.setBackgroundTint(ContextCompat.getColor(this,R.color.xxxx));
snackbar.show();

With Jetpack Compose you can customize the SnackbarHost defining a custom Snackbar
    snackbarHost = {
        // reuse default SnackbarHost to have default animation and timing handling
        SnackbarHost(it) { data ->
            Snackbar(
                snackbarData = data,
                contentColor = Yellow,
                actionColor = Red.copy(alpha = 0.9f)
            )
        }
    }

Then just use it:
scope.launch {
    scaffoldState.snackbarHostState.showSnackbar(
        message = "Snackbar text  # ${++clickCount}",
        actionLabel = "Done")
}

A: I changed my theme
Theme.AppCompat.Light.NoActionBar

to
Theme.AppCompat.NoActionBar

It worked.Try to use simple theme instead of light or other theme.

A: You can use this library: https://github.com/SandroMachado/restaurant
new Restaurant(MainActivity.this, "Snackbar with custom text color", Snackbar.LENGTH_LONG)
    .setTextColor(Color.GREEN)
    .show();

Disclaimer: I made the library.

A: This is what I use when I need custom colors
    @NonNull
    public static Snackbar makeSnackbar(@NonNull View layout, @NonNull CharSequence  text, int duration, int backgroundColor, int textColor/*, int actionTextColor*/){
        Snackbar snackBarView = Snackbar.make(layout, text, duration);
        snackBarView.getView().setBackgroundColor(backgroundColor);
        //snackBarView.setActionTextColor(actionTextColor);
        TextView tv = (TextView) snackBarView.getView().findViewById(android.support.design.R.id.snackbar_text);
        tv.setTextColor(textColor);
        return snackBarView;
    }

And consumed as:
CustomView.makeSnackbar(view, "Hello", Snackbar.LENGTH_LONG, Color.YELLOW,Color.CYAN).setAction("DO IT", myAction).show();

A: If you decide to use the dirty and hacky solution with finding TextView in Snackbar by id and you already migrated to androidx, then here's the code:
val textViewId = com.google.android.material.R.id.snackbar_text
val snackbar = Snackbar.make(view, "Text", Snackbar.LENGTH_SHORT)
val textView = snackbar.view.findViewById(textViewId) as TextView
textView.setTextColor(Color.WHITE)

A: I found this at What are the new features of Android Design Support Library and how to use its Snackbar?
This worked for me for changing the text color in a Snackbar.
Snackbar snack = Snackbar.make(view, R.string.message, Snackbar.LENGTH_LONG);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.WHITE);
snack.show();

UPDATE: ANDROIDX:
As dblackker points out in the comments, with the new AndroidX support library, code to find the ID of Snackbar TextView changes to:
TextView tv = view.findViewById(com.google.android.material.R.id.snackbar_text);
tv.setTextColor(ContextCompat.getColor(requireContext(), R.color.someColor))

A: Created this kotlin extention function i use in my projects:
fun Snackbar.setTextColor(color: Int): Snackbar {
    val tv = view.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
    tv.setTextColor(color)

    return this
}

Usage like you would expect:

Snackbar.make(view,
R.string.your_string,Snackbar.LENGTH_LONG).setTextColor(Color.WHITE).show()

A: Alright so I fixed it by basically reorganizing the way I do text colors.
In my light theme, I set android:textColorPrimary to the normal dark text I wanted, and I set android:textColor to white.
I updated all of my text views and buttons to have android:textColor="?android:attr/textColorPrimary".
So because snackbar draws from textColor, I just set all of my other text to textColorPrimary.
EDIT JANUARY 2017: ----------------------------------------------------
So as the comments say, and as stated in the edited original question above, you should probably not define android:textColor in your themes, as this changes the text color of every view inside the theme.

A: Hacking on android.support.design.R.id.snackbar_text is fragile, a better or less hacky way to do that will be:
String snackText = getResources().getString(YOUR_RESOURCE_ID);
SpannableStringBuilder ssb = new SpannableStringBuilder()
    .append(snackText);
ssb.setSpan(
    new ForegroundColorSpan(Color.WHITE),
    0,
    snackText.length(),
    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Snackbar.make(
        getView(),
        ssb,
        Snackbar.LENGTH_SHORT)
        .show();

A: One approach is to use spans:
final ForegroundColorSpan whiteSpan = new ForegroundColorSpan(ContextCompat.getColor(this, android.R.color.white));
SpannableStringBuilder snackbarText = new SpannableStringBuilder("Hello, I'm white!");
snackbarText.setSpan(whiteSpan, 0, snackbarText.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

Snackbar.make(view, snackbarText, Snackbar.LENGTH_LONG)
                .show();

With spans you can also add several colors and styles inside one Snackbar. Here's a nice guide:
https://androidbycode.wordpress.com/2015/06/06/material-design-snackbar-using-the-design-support-library/

A: If you migrated to androidX use com.google.android.material.R.id.snackbar_text instead of
android.support.design.R.id.snackbar_text for changing color of text on snackbar.

A: Find by id did't work for me so I found another solution:
Snackbar snackbar = Snackbar.make(view, text, duration);//just ordinary creation

ViewGroup snackbarView = (ViewGroup) snackbar.getView();
SnackbarContentLayout contentLayout = (SnackbarContentLayout) snackbarView.getChildAt(0);
TextView tvText = contentLayout.getMessageView();
tvText.setTextColor(/*your color here*/);

//set another colors, show, etc

A: I have a simple code that will help to get an instance of both the textview of Snackbar, after that you can call all methods that are applicable on a textview.
Snackbar snackbar = Snackbar.make( ... )    // Create Snack bar

snackbar.setActionTextColor(getResources().getColor(R.color.white));  //if you directly want to apply the color to Action Text

TextView snackbarActionTextView = (TextView) snackbar.getView().findViewById( android.support.design.R.id.snackbar_action );

snackbarActionTextView.setTextColor(Color.RED);  //This is another way of doing it

snackbarActionTextView.setTypeface(snackbarActionTextView.getTypeface(), Typeface.BOLD);

//Below Code is to modify the Text in Snack bar
TextView snackbarTextView = (TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
snackbarTextView.setTextSize( 16 );
snackbarTextView.setTextColor(getResources().getColor(R.color.white));

A: Just to save your precious development time, here is the static method I am using:
public static void snack(View view, String message) {
    if (!TextUtils.isEmpty(message)) {
        Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_SHORT);
        snackbar.getView().setBackgroundColor(Color.YELLOW);
        TextView tv =  snackbar.getView().findViewById(android.support.design.R.id.snackbar_text); //snackbar_text
        tv.setTextColor(Color.BLACK);
        snackbar.show();
    }
}

This is how it looks:

A: If you are in Kotlin, you can create an extension :
fun Snackbar.withTextColor(color: Int): Snackbar {
    val tv = this.view.findViewById(android.support.design.R.id.snackbar_text) as TextView
    tv.setTextColor(color)
    return this
}

Usage :
yourSnackBar.withTextColor(Color.WHITE).show()

A: As per new AndroidX Jitpack components
implementation 'com.google.android.material:material:1.0.0'

Use this extension which i had created
inline fun View.snack(message: String, length: Int = Snackbar.LENGTH_LONG,
 f: Snackbar.() -> Unit) {
val snack = Snackbar.make(this, message, length)
snack.f()
snack.show()
}

fun Snackbar.action(action: String, actionColor: Int? = null, textColor: Int? = null, listener: (View) -> Unit) {
setAction(action, listener)
actionColor?.let {
    setActionTextColor(it)
    }
textColor?.let {
    this.view.findViewById<TextView>(R.id.snackbar_text).setTextColor(it)
    }
}

Use it like this
btn_login.snack(
        getString(R.string.fields_empty_login),
        ContextCompat.getColor(this@LoginActivity, R.color.whiteColor)
    ) {
        action(getString(R.string.text_ok), ContextCompat.getColor(this@LoginActivity, R.color.gray_300),ContextCompat.getColor(this@LoginActivity, R.color.yellow_400)) {
            this@snack.dismiss()
        }
    }

A: This is my workaround to solve this type of problem in androidx using kotlin
 fun showSnackBar(message: String) {
        mContent?.let {
            val snackbar = Snackbar.make(it, message, Snackbar.LENGTH_LONG)
            val snackbarView = snackbar.view
            val tv = snackbarView.findViewById<TextView>(R.id.snackbar_text)
            tv.setTextColor(Color.WHITE) //change the color of text
            tv.maxLines = 3 //specify the limit of text line
            snackbar.duration = BaseTransientBottomBar.LENGTH_SHORT //specify the duraction of text message
            snackbar.show()
        }
    }

You need initialize mContent inside onViewCreated method like below
var mContent: View? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mContent = view
    }

A: This worked for me
Snackbar.make(v, "Loading...", Snackbar.LENGTH_LONG).setTextColor(getColor(R.color.orange)).show();

Before that I declared my color in color.xml
<color name="orange">#FF9800</color>

A: You can try this code
Snackbar snackbar;
    snackbar = Snackbar.make(binding.getRoot(), "Hello World!", Snackbar.LENGTH_INDEFINITE);
    View snackBarView = snackbar.getView();
    snackBarView.setBackgroundColor(getColor(R.color.purple_700));
    snackbar.show();

    snackbar.setTextColor(ContextCompat.getColor(this, R.color.white));
    snackbar.setActionTextColor(ContextCompat.getColor(this, R.color.purple_200));
    snackbar.setBackgroundTint(ContextCompat.getColor(this, R.color.purple_700));
    snackbar.setAction("Ok", new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "Click", Toast.LENGTH_SHORT).show();
        }
    });
    snackbar.show();

A: I also noticed the same problem. Thanks to the answers here I've created a small class, which can help to solve this problem in more easily, just by replacing this:
Snackbar.make(view, "Error", Snackbar.LENGTH_LONG).show();

with this:
Snackbar2.make(view, "Error", Snackbar.LENGTH_LONG).show();

Here is my class:
public class Snackbar2 {
static public Snackbar make(View view, int resid, int duration){
    Snackbar result = Snackbar.make(view, resid, duration);
    process(result);
    return result;
}
static public Snackbar make(View view, String text, int duration){
    Snackbar result = Snackbar.make(view, text, duration);
    process(result);
    return result;
}
static private void process(Snackbar snackbar){
    try {
        View view1= snackbar.getView();

        TextView tv = (TextView) view1.findViewById(android.support.design.R.id.snackbar_text);
        tv.setTextColor(Color.WHITE);

    }catch (Exception ex)
    {
        //inform about error
        ex.printStackTrace();
    }
}

}


text:
Q: Nsight debugger doesn't hit breakpoints My current configuration :
Visual Studio 2010,
CUDA 5.5,
Nsight version 3.1,
Graphics card driver version 327.23 (latest)
The problem is that breakpoints in __global__ kernels are not hit when starting
"CUDA Debugging"
Anyone with the same problem? It was possible for me to have kernel breakpoints
on some older version of Nsight & CUDA, but I wouldn't want to downgrade to previous versions.
Thanks.

A: If a kernel launch fails for any reason, it's quite possible that any selected breakpoints in that kernel will not be hit.
It's always recommended to do proper CUDA error checking in your CUDA codes, especially when you are having difficulty.

A: I had the problem of breakspoints not beeing hit, after setting my graphics card to TCC mode ("compute-only"), just in case, You did the same.


text:
Q: Showing that g is integrable and $\int^b_a{f}$ = $\int^b_a{g}$ Let $f$ be integrable on $[a,b]$, and suppose g is a function on $[a,b]$ such that $g$($x$) = $f$($x$) except for finitely many $x$ in $[a,b]$. Show $g$ is
integrable and $\int^b_a{f}$ = $\int^b_a{g}$.
I started out solving this problem by letting a function $h = f - g$ such that $h(x) = 0$ expect at one point in [a,b]. Since $f$ is integrable, then there exists a partition P such that $U(f,P)-L(f,P)$ < $\epsilon$. I'm not really sure how to proceed from here. Any hints and help is much appreciated.

A: First of all you may prove the result for the case where there is only one point  say $c$ where the f and g have different values.
Note that  in that case for any partition of [a,b] the difference between Riemman Sum of $f$ and the Riemman Sum for $g$ is at most $$|f(c)-g(c)|\times \delta$$ where $\delta$ is the maximum length of your subpartition intervals.
Now you pick a partition such that $$ \delta <\frac {\epsilon}{|f(c)-g(c)|}$$
The rest is easy to complete.

A: Put $h (x)=f (x)-g (x) $ and let us prove that $h $ is integrable at $[a,b] $
Assume that $$\forall x\in (a,b] \; h (x)=0$$ and $$h (a)=c>0.$$
Let $\epsilon>0$ enough small given.
$h $ is continuous at $[a+\frac {\epsilon}{2c},b]$ and then integrable.
there exist a partition $\sigma_1$ of $[a+\frac {\epsilon}{2c},b] $ such that
$$U (h,\sigma_1)-L (h,\sigma_1)<\frac {\epsilon}{2}$$
put now $$\sigma=\sigma_1\cup \{0\}$$
$\sigma $ is a partition of $[a,b] $
now
$$U (h,\sigma)-L (h,\sigma)=$$
$$U (h,\sigma_1)-L (h,\sigma_1)+c\frac {\epsilon}{2c} <\epsilon.$$
This proves that $h $ is integrable at $[a,b] $.
$g=f-h $ is integrable since $f $ and $h $  are integrables at $[a,b] $.

A: Assuming $f\ne g$ so that $S=\{x: f(x)\ne g(x)\}$ is finite and not empty. Let $M=\max \{|f(x)-g(x)|:x\in S\}.$ Let $|S|$ be the number of members of $S.$
For a partition $P$ let $\|P\|$ be the length of the largest interval belonging to $P$. For  any $\epsilon >0$ there exists $\delta_{\epsilon}>0$ such that $\forall P\;(\|P\|<\delta_{\epsilon} \implies U(f,P)-L(f,P)<\epsilon/2).$
So if $\|P\|< \delta_{\epsilon}\cdot \min (1, \epsilon(M|S|)^{-1}/2)$ then $|U(f,P)-U(g,P)|<\epsilon$ and $|L(f,P)-L(g,P)|<\epsilon.$
The idea is simply that, since $S$ is finite, the contribution,  ( to a finite sum that approximates the integral of $f$ or of $g$ ), of  intervals containing members of $S, $ will be negligible if $\|P\|$ is small enough.


text:
Q: Rails ActiveRecord find User where Products equals 0 I have a model User that has_many Product(s), but some Users don't have any products yet. I want to write a query that gives me all the Users who don't current have any Products i.e. a User where Product is 0.
The only ways I can think to do this are pretty ugly. For example, getting all Users (User.all), then iterating through all the Users and checking @user.products < 1. Thanks for the help.

A: This should do the trick:
User.includes(:products)
     .select('users.*')
     .group('users.id')
     .having('COUNT(products.*) = 0')

Took from my other answer:

*

*How to return results filtered on relations count to a view in RAILS?
Edit #1:
This is an other solution:
User.where('users.id NOT IN (?)', Product.all.pluck(:user_id).uniq.compact)

It retrieves all the user_ids in the products table and select all User that are not in this user_ids list.


text:
Q: Mysql2 Installation in Ruby on Rails When i try to run the command rake db:create:all it's giving the following error:
rake db:create
Can't connect to MySQL server on 'localhost' (10061)
Couldn't create database for {"adapter"=>"mysql2", "database"=>"db/test", "username"=>"root", "password"=>nil, "host"=>"localhost", "pool"=>5, "timeout"=>5000}, charset: , collation:
Can't connect to MySQL server on 'localhost' (10061)
Couldn't create database for {"adapter"=>"mysql2", "database"=>"db/development", "username"=>"root", "password"=>nil, "host"=>"localhost", "pool"=>5, "timeout"=>5000}, charset: , collation:

A: Is the information in config/database.yml correct?  The "db/test" and "db/development" look suspicious for database names.
And never use root access in your programs, even in testing.  Go through the effort to create SQL users and GRANT appropriate access capabilities.

A: @dary7yl Thank you dary..it's able to creating the tables. The problem is solved by after installing the xamp and run the mysql server. And i also made one change in database.yml file ..i changed the database name from "db/development" to "development"..beacuse the mysql giving me the error when i try to given the database name with "db/name"...Once again thank's man..


text:
Q: Django Abstract Models vs simple Python mixins vs Python ABCs This is a question prompted by another question from me.
Django provides Abstract base classes functionality (which are not to same as ABC classes in Python?) so that one can make a Model (Django's models.Model) from which one can inherit, but without that Model having an actual table in the database. One triggers this behavior by setting the 'abstract' attribute in the Model's Meta class.
Now the question: why does Django solve it this way? Why the need for this special kind of 'Abstract base class' Model? Why not make a Model mixin by just inheriting from the object class and mixing that in with an existing Model? Or could this also by a task for Python ABCs? (mind you I'm not very familiar with ABC classes in Python, my ignorance might show here)

A: One of the reasons is because of the way fields are defined on a model.
Fields are specified declaratively, in a way that a normal class would treat as class attributes. Yet they need to become instance attributes for when the class is actually instantiated, so that each instance can have its own value for each field. This is managed via the metaclass. This wouldn't work with a normal abstract base class.

A: I'll try to be reasonably brief, since this can easily turn into a lengthy diatribe:
ABCs are out because they were only introduced in Python 2.6, and the Django developers have a set roadmap for Python version support (2.3 support was only dropped in 1.2).
As for object-inheriting mixins, they would be less Pythonic in more ways than just reducing readability. Django uses a ModelBase metaclass for Model objects, which actually analyses the defined model properties on initialisation, and populates Model._meta with the fields, Meta options, and other properties. It makes sense to reuse that framework for both types of models. This also allows Django to prevent abstract model fields from being overriden by inheriting models.
There's plenty more reasons I can think of, all of them minor in themself, but they add up to make the current implementation much more Pythonic. There's nothing inherently wrong with using object-inheriting mixins though.


text:
Q: Latest build in crashlytics is showing message that "investigation recommended" Our crashes are not reporting in Crashlytics, we are getting  message "investigation recommended"
Please find the attached screenshot.

A: Please Make sure the following things.
1) your debug information formate set to DWARF with dlsym File
  GoTo File Navigation -> select xcodeFile -> Build Settings -> Debug Information Format
2)
if any missing dsym warning appeared at server.
Please select respected version from same screen as shown in screenshot,
and disable that version