text:
Q: WindowsMediaPlayer in Delphi I want to use a WindowsMediaPlayer in my Delphi Project with Delphi 7. I want to use some videos with this Windowsmediaplayer. I've got an openDialog and time to time I call the video files to open. But Windowsmediaplayer some times runs as fullscreen sometimes runs in a small rect (not full screen). I want it runs fullscreen in a Panel. So far I couldn't achieve it.
Could you help me please?

A: If you want to play videos using TMediaPlayer component you first have to set its Display property to some windowed controll like form or panel.
http://docwiki.embarcadero.com/Libraries/XE6/en/Vcl.MPlayer.TMediaPlayer.Display
This will render video output on the selected control. By default video will be streched to the controll size which is what you want.
But if the video aspect ratio isn't the same as the aspect ratio of the controll on which you are rendering then the video will get distorted. To overcome that TMediaPlayer has another propery called DisplayRect using which you can force the video to be rendered in desired rectangle inside the controll you are rendering on. By using this you can get those balck stripes that most modern media players make when video aspect ratio isn't the same as your screens aspect ratio.
http://docwiki.embarcadero.com/Libraries/XE6/en/Vcl.MPlayer.TMediaPlayer.DisplayRect


text:
Q: StarTeam and Visual Studio 2010 Integration I was searching for a plug-in that will integrate with StarTeam and allow user to check-in and check-out files directly through Visual Studio 2010 environment. I did found a StarTeam Visual Studio Client provides an integration that allows users of the Visual Studio IDE to manage their digital assets (files) and activities (requirements, tasks, defects) in their StarTeam repository from within the Visual Studio development environment.  Unfortunately this client works only with VS 2008 and not with Visual Studio 2010 and this is the vision of IDE that is I will be using for one of the project that I am workign on. I would really appreciate if someone could guide me in getting StarTeam integration with VS 2010.

A: There are two types of integration you can use:
SCC Integration: This is a standard that lets any development environment talk to any source control provider, if they both support the standard. (Visual Studio & StarTeam both do.)
StarTeam Visual Studio Integration: This is sort of a plug-in to Visual Studio that lets you access StarTeam and adds some additional features.
SCC Integration should let any version of StarTeam talk with any version of Visual Studio. However, with the StarTeam Visual Studio Integration, newer versions don't support older versions of StarTeam.
For instance, the version of StarTeam Visual Studio Integration for Visual Studio 2010 only supports (I think) StarTeam 2009.
Even if you aren't able to use StarTeam Visual Studio Integration, SCC Integration should still work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: About install ubuntu for devices on Chinese android tablet Is it possible to install ubuntu for devices (ubuntu touch) on a Chinese android tablet ?
I saw a guide on ubuntu website about how to install ubuntu for devices on android tablets/phones.
If its possible what is the worst case scenario ?

A: Ubuntu Touch also known as Ubuntu for devices or Ubuntu Phone, it's crucial to know that the process will completely erase your device, removing not only Android but also your apps, photos and all other data. You absolutely must back up everything you want to keep first.
Here are instructions for installing Ubuntu on devices (phone and tablet) installing-ubuntu-for-devices
There's a bigger list of devices  here
If you want to reinstall android reinstalling-android

NOTE: Some of the links in this post are no longer functioning as a result of Ubuntu Touch being discontinued; the links have been left in place for historical reasons.


text:
Q: "Plateau around 200k salary" is this correct usage of the word Plateau? I don't know where I first heard the word plateau used in a context to imply that the rate of growth decelerates and stops at X. I think it was in a Machine learning class(mathematics class) taught by an Indian professor. So I think it could have been invalid usage. I have been using this everywhere, so I thought I should confirm if it is a valid usage of the word plateau.
A typical sentence where I would use plateau is:

I am making X dollar amount a year right now, but the increments in my salary are not substantial. I think at this rate, I will plateau around Y dollar amount a year.

A: Yes, plateau can be used as an intransitive verb in just that sense:

[Merriam-Webster]
: to reach a level, period, or condition of stability or maximum attainment


text:
Q: Update value of a nested key by reference in python 3 I have the following dictionary:
  watch_list=  {'videos': [{'systemId': 'qre', 'duration': 19}, {'systemId': 'abc', 'duration': 19}]}

now I wanted to check if the systemId already exists in the dictionary and if yes then update duration by systemId.
hence I am trying the following code:
def update_duration(watch_list,system_id,duration):
watch_history= next((a for a in watch_list if a['systemId'] == system_id), None)
if watch_history:
    watch_history['duration'] =duration
    return watch_history

but this gives me an error:
*** TypeError: string indices must be integers

I am new to python, I have read stack overflow other solutions but couldnt made it work. can anyone help me a little here, on how to update the value by the systemId?
I am using python 3 and flask

A: When you iterate through a dictionary with something like
my_dictionary = { 'hello' : ['I', 'am', 'a', 'dictionary'] }

for entry in my_dictionary:
    print entry

The output will be hello, as it iterates through its keys by default. As it appears you're actually wanting to iterate through the dictionary's values, you'll want to call the values() function, or itervalues() in Python2.
Beyond that, you're then running into an issue with your generator comprehension's if statement. At that point, your a variable is holding a list of dictionaries---what used to be the value found by watch_list['videos'].


text:
Q: Evaluating the $H_0$ of a contigency table I have a 2 way contigency table with variables $A=\{a_1,a_2\}$ and $B=\{b_1,b_2\}$. I have the observed cell frequencies $O_1=a_1b_1$, $O_2=a_1b_2$, $O_3=a_2b_1$ and $O_4=a_2b_2$. My null hypothesis is that $A$ and $B$ are independent variables
I am interested to evaluate what is the probability of observing each of the cells given that $H_0$ is true, $\text{Pr}(O_1=a_1b_1|H_0)$. How can I calculate this probability? Is there a bayesian approach or a simulation procedure that could help me obtain this probability?


text:
Q: Difference between SELECT DISTINCT and SELECT UNIQUE
Possible Duplicate:
Unique vs distinct multi-column in Oracle 9i

Proper difference between SELECT DISTINCT and SELECT UNIQUE with points and examples.

A: Oracle official documentation
http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_10002.htm#sthref9346
States that:
DISTINCT | UNIQUE
Specify DISTINCT or UNIQUE if you want the database to return only one copy of each set of duplicate rows selected. These two keywords are synonymous. Duplicate rows are those with matching values for each expression in the select list.

A: SELECT DISTINCT and SELECT UNIQUE behave the same way in oracle.
While DISTINCT is ANSI SQL standard, UNIQUE is an Oracle specific statement.
Look here: http://psoug.org/definition/DISTINCT.htm


text:
Q: Installing gnuplot on jupyter I want to plot my bar chart by gnuplot. But I have problem with installing. I am using jupyter anaconda and the following codes don't work for installing.
!conda install gnuplot-py
!pip install gnuplot-py
!pip install gnuplot

Do you have any idea?

A: So first of all you need to load it as an extension
pip install gnuplot_kernel
%load_ext gnuplot_kernel

should do the job.
For further information see  documentation

A: gplot.py
can be used in Jupyter plot function and your data/array/lists.


text:
Q: Can I loop this? Having a heck of a time looping this; D2 is where the list starts. I would like to have it ran for d3, d4, d5, d6.... until a blank space.
Also, I will be placing the data into column E and that would need to also increase like column D; e2,e3,e4,e5,e6...
Sub james() 'Main Program
Dim celltxt As String
celltxt = ActiveSheet.Range("D2").Value

DELETE_EJ

If InStr(1, celltxt, "Christy", vbTextCompare) Then
    Range("E2").Value = "Christy"

ElseIf InStr(1, celltxt, "Kari", vbTextCompare) Then
    Range("E2").Value = "Kari"

ElseIf InStr(1, celltxt, "Sue", vbTextCompare) Then
    Range("E2").Value = "Sue"

ElseIf InStr(1, celltxt, "Clayton", vbTextCompare) Then
    Range("E2").Value = "Clayton"

A: Yes, define a range to loop over, and then you can do it like this using an inner loop over the list of names:
Sub foo() 'Main Program

Dim nmArr()
Dim i as Long
Dim loopRange as Range
Dim cl As Range

'## This is the range you will loop over
Set loopRange = ActiveSheet.Range("D2:D6") '## Modify as needed

'## This is the list of names built as an array
nmArr = Array("Christy", "Kari", "Sue", "Clayton")

DELETE_EJ

For Each cl in loopRange.Cells
    For i = LBound(nmArr) to Ubound(nmArr)
        If Instr(1, cl.Value, nmArr(i), vbTextCompare) Then
            cl.Offset(0,1).Value = nmArr(i)
            Exit For
        End If
    Next
Next

End Sub

Above requires hardcoding the range, but if you need to just do it until it finds a blank cell, then modify like so:
Option Explicit
Sub foo() 'Main Program

Dim nmArr()
Dim i As Long
Dim cl As Range

Set cl = ActiveSheet.Range("D2") '## This is the STARTING cell

'## This is the list of names built as an array
nmArr = Array("Christy", "Kari", "Sue", "Clayton")

DELETE_EJ

Do

    For i = LBound(nmArr) To UBound(nmArr)
        If InStr(1, cl.Value, nmArr(i), vbTextCompare) Then
            cl.Offset(0, 1).Value = nmArr(i)
            Exit For
        End If
    Next

    '## Get a handle on the NEXT cell
    Set cl = cl.Offset(1, 0)
Loop Until Trim(cl.Text) = vbNullString

End Sub

Second approach has been tested & working to produce outputs like:

A: Yes you can, put the names in an array then loop through the array.:
Sub james() 'Main Program
Dim celltxt As String
Dim nmArr()

nmArr = Array("Christy", "Kari", "Sue", "Clayton")
celltxt = ActiveSheet.Range("D2").Value

DELETE_EJ
For i = LBound(nmArr) To UBound(nmArr)
    If InStr(1, celltxt, nmArr(i), vbTextCompare) Then
        Range("E2").Value = nmArr(i)
        Exit For
    End If
Next i

End Sub


text:
Q: Access lightning calendar on Home record page I have a requirement to display out of box calendar on the home record page. So does lightning feature allows us to display lightning custom calendar as a component on record page?
Thanks


text:
Q: WCF Service with different amount of methods ( Endpoints) I'm working on a project that uses WCF,but I'm unable to solve a problem.
I have two solutions Project A and Project B. The actual error is the following : when it tries to create an instance of the OAuthServiceClient inside of project B, it generates the following error

Could not find default endpoint element that references contract 'SSOWebService.IOAuthService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

This happens, I believe, because of the difference in methods of the WCF Service of Project B(30 endpoints) and Project B(15 endpoints)
I can add the code here if that is of use.

A: Hello I ended up fixing the problem already, All I had to do was remove the old reference file, and add it again. That fixed it
Image


text:
Q: How to get a value from a div tag using cheerio's nodeJS I'm making a webscraper using cheerio and request in NodeJS and I can't get a special value from a div.
I would get the 'idproduit' value (223) from this div :

For this I'm doing : (EDITED)
$('.vignettes_produit li').each(function(i, element) {

        var jsObject = { id: id++, idProduit: null};

        jsObject.idProduit = $(this).find('.vignette_footer).attr('idproduit');
});

But it's gaving me an undefined result.
Does anyone know how I have to do ?

A: Update: Following your edit, changing $('.vignettes_produit li') to $('li[class="vignettes_produit"]') should solve your issue. For example:
let cheerio = require('cheerio')

let $ = cheerio.load('

1

2

3

')

$('li[class="vignettes_produit"]').each(function(i, element) {
    console.log($(this).find('.vignette_footer').attr('idproduit'))
})


text:
Q: Relational Algebra: Problems with division operator I am writing a query, where I am using the division operator. For some reason I can't get it to work properly, and I can't see why.
pol = pi allergen (sigma allergy_type = 'pollen' (allergies))
tmp =  (patient_allergies/pol)
tmp

The above is my query. In pol I am retrieving all allergens, who has the allergy type pollen. This gives me a 1 column, two rows table, which content is the two allergens who has allergy_type pollen.
tmp:
Patient_allergies is a 2 column, 23 row table. The first column is allergens, second column is ssn for the people with those allergens.
What I am trying to do, is to get everyone in patient_allergies, who has the two allergens I found in pol. I'm pretty sure I need to division operator for this, but it returns an empty list, which is incorrect for what I am trying to do.

EDIT: I am using this relational algebra calc, provided by our university: dbis-uibk.github.io/relax/calc/local/uibk/local/0 There is a division operator with another symbol, but yields the same result


text:
Q: Get specific object from specific Id JSON I have a little problem with my json file, what I am trying to do is get the specific object from my json file,  so in this json above when i add this parameter  stream_id= and for example i add this id stream_id=200 it should show only the object with that id, so to be more clear it should show id:200, name:Ravi Tamada, email:ravi@gmail.com etc etc ,with PHP, thanks
{
        "contacts": [
            {
                    "id": "200",
                    "name": "Ravi Tamada",
                    "email": "ravi@gmail.com",
                    "address": "xx-xx-xxxx,x - street, x - country",
                    "gender" : "male",
                    "url": "http://149.202.196.143:8000/live/djemal/djemal/592.ts"
            },
            {
                    "id": "201",
                    "name": "Johnny Depp",
                    "email": "johnny_depp@gmail.com",
                    "address": "xx-xx-xxxx,x - street, x - country",
                    "gender" : "male",
                    "url":"http://149.202.196.143:8000/live/djemal/djemal/592.ts"
            },
            {
                    "id": "202",
                    "name": "Leonardo Dicaprio",
                    "email": "leonardo_dicaprio@gmail.com",
                    "address": "xx-xx-xxxx,x - street, x - country",
                    "gender" : "male",

    "url":"http://149.202.196.143:8000/live/djemal/djemal/592.ts"
            }
        ]
    }

A: You could iterate through your JSON and look for the Id you need. Simple as that.
<?php
$json = /* your json */;
$array = json_decode($json, true);

$result = getInfo(200, $array);

function getInfo($id, $array) {
    foreach($array AS $index=>$json) {
        if($json['id'] == $id) {
            return $json;
        }
    }
}

A: May be you can use json_decode with $assoc=true (this option converts the json to an array, even to nested arrays) and then loop through the array to find the desired element.

A: You should be able to loop through the JSON with a simple js/jquery function like below, where you just pass the specified id.
function getJsonById(id){
var json = {
        "contacts": [
            {
                    "id": "200",
                    "name": "Ravi Tamada",
                    "email": "ravi@gmail.com",
                    "address": "xx-xx-xxxx,x - street, x - country",
                    "gender" : "male",
                    "url": "http://149.202.196.143:8000/live/djemal/djemal/592.ts"
            },
            {
                    "id": "201",
                    "name": "Johnny Depp",
                    "email": "johnny_depp@gmail.com",
                    "address": "xx-xx-xxxx,x - street, x - country",
                    "gender" : "male",
                    "url":"http://149.202.196.143:8000/live/djemal/djemal/592.ts"
            },
            {
                    "id": "202",
                    "name": "Leonardo Dicaprio",
                    "email": "leonardo_dicaprio@gmail.com",
                    "address": "xx-xx-xxxx,x - street, x - country",
                    "gender" : "male",

    "url":"http://149.202.196.143:8000/live/djemal/djemal/592.ts"
            }
        ]
    };

var l= json['contacts'].length;
var c = 0;
while(c<l){
  if(json['contacts'][c]['id']==id){
    console.log(json['contacts'][c]);
     return json['contacts'][c];
  }
  c++;
}
}
return "";
});

A: You may need to get the data by id more often and not loop through the array every time. So you can
foreach($users_array as $user_object){
    $users[$user_object->id]=$user_object;
}

and then access:
echo $users[202]->email;


text:
Q: How does Fiddler work with HTTPS I made HTTP proxy server. But the problem that I can't decrypt SSL traffic.
I found that Fiddler install Trust Root Certificate. I did the same and now I don't have error that certificate untrusted but I got other error: wrong Common Name (CN). How fiddler change the CN of installed trusted certificate?
Will appreciate any answer.

A: Fiddler acts as an SSL termination proxy.
I.e. the connection goes like this:
Browser ---(SSL handshake)---> Fiddler  --- (SSL handshake) ---> Actual Site
So your connection is first time encrypted and sent to Fiddler, where it is first decrypted by Fiddler and then again encrypted to be sent to the actual site that you access.
Additionally when you access a site Fiddler automatically generates a server certificate with a CN that is equal to the host name of the site and this certificate is signed by the CA of fiddler That's why Fiddler needs to install a set of trusted CAs in your browser so that the first SSL handshake can be made against a trusted authority.


text:
Q: Netbeans 7.2.1 - Default project directory per project category First of all, I have already saw the question How to change the default project directory (folder) in Netbeans 6.9? I have edited the value of projectsFolder variable in projectui.properties file to change the default project directory, and it worked.
The problem with this is that it is a global change, meaning that, every project category (Java, Android, PHP, etc., ) will now use this directory as the default projects directory. But, I would like to have separate default directories, such as ~/Development/Andoid for Android projects, ~/Development/Java for Java projects, ~/Development/PHP for PHP projects. I know that most probably I am here for a disappointment, but who knows!
So, is there any trick or hack that you aware of to do this?


text:
Q: pycharm interpreter using cygwin version python I am running django python2.7 using Pycharm in windows.
Now I have some issue with redis queue not working in windows because of this
I am trying to do what this person did here. Use a cygwin version of python as pycharm interpreter.
(not sure if I downloaded all the packages or did correct steps)
I downloaded cygwin and install packages python2.7 + python-setuptools and then try to point my Pycharm interpreter to c:/cygwin/bin/python27.exe
see image
After that it seem ok and ask me to install packing tools pip, I clicked it and it give me this error:
see image
"Cannot start process, the working directory '\cygdrive\c\Users\User1G~1.SIS\AppData\Local\Temp\1\tmpYpudf2pycharm-management\pip-7.1.0' does not exist"

A: According to the error message it looks like pip can't be found... Are you sure you have installed pip?
Take a look here, how you can install pip: Installing Pip-3.2 on Cygwin
You can open a cygwin command line window and try to manually install the packages you want to.


text:
Q: iPhone Getting Location Periodically
Possible Duplicate:
Time based GPS location in background (iphone)

I am trying to get the iPhone's location periodically. When the app goes into background, a new thread is created and wants to get user's location, and then goes to sleep for X minutes. Then wakes up, gets user's location again and goes back to sleep.
When the thread wakes up, I need to get the location. I can't user the CLLocationMangerDelegate because that updates on its own and calls the delegate method whenever it wants. I need to somehow get the user's location whenever the thread wakes up.
Can anyone help me please? I would really appreciate it!
Thanks!

A: as far as i know it's not possible to achieve this through a scheduled method call (as you mentioned). i had similar problem and i solved it by having a CLLocationManager that triggers whenever the user's location is changed for about 1 KM.
the drawback of this implementation is the battery consumption.


text:
Q: Erro ao abrir a platafoma V10 - Cannot perform runtime binding Ao executar o codigo
            Dim objAplConf As StdBSConfApl = New StdBSConfApl()
            Dim Plataforma As StdPlatBS = New StdPlatBS()

            objAplConf.Instancia = Instance
            objAplConf.AbvtApl = "ERP"
            objAplConf.LicVersaoMinima = "10.00"

            Plataforma.AbrePlataforma(CType(Line, EnumTipoPlataforma), objAplConf)

A: Esta questão resolve-se com a aplicação de um AssemblyResolver:
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string assemblyFullName;

    System.Reflection.AssemblyName assemblyName;

    const string PRIMAVERA_FOLDER = @"C:\Program Files (x86)\PRIMAVERA\SG100\Apl\";

    assemblyName = new System.Reflection.AssemblyName(args.Name);
    assemblyFullName = System.IO.Path.Combine(PRIMAVERA_FOLDER, assemblyName.Name + ".dll");

    if (System.IO.File.Exists(assemblyFullName))
        return System.Reflection.Assembly.LoadFile(assemblyFullName);
    else
        return null;
}

Que deve evocar no seu método Main da class Program:
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

Confirme se todas as DLL específicas do PRIMAVERA estão com a propriedade Copy Local = False.


text:
Q: Validate string is base64 format using RegEx? I have been looking how to validate a base64 string and came across this.
 ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$

I need a little help to make it allow "==" aswell as "=".
Thanks

A: I've updated the above code a bit to meet few more requirements:

*

*check for correct string size (should be multiple of 4)

*check for pad character count (should be up to 2 character at the end of the string only)

*make it work in .NET 2.0 (well, the HashSet<T> should be implemented or use Dictionary<T, U>)

The code is a part of my assertion library, so this is why there are two check methods and the param parameter...
    private const char Base64Padding = '=';

    private static readonly HashSet<char> Base64Characters = new HashSet<char>()
    {
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    };

    public static void CheckBase64String(string param, string paramName)
    {
        if (CheckBase64StringSafe(param) == false)
        {
            throw (new ArgumentException(String.Format("Parameter '{0}' is not a valid Base64 string.", paramName)));
        }
    }

    public static bool CheckBase64StringSafe(string param)
    {
        if (param == null)
        {
            // null string is not Base64 something
            return false;
        }

        // replace optional CR and LF characters
        param = param.Replace("\r", String.Empty).Replace("\n", String.Empty);

        if (param.Length == 0 ||
            (param.Length % 4) != 0)
        {
            // Base64 string should not be empty
            // Base64 string length should be multiple of 4
            return false;
        }

        // replace pad chacters
        int lengthNoPadding = param.Length;
        int lengthPadding;

        param = param.TrimEnd(Base64Padding);
        lengthPadding = param.Length;

        if ((lengthNoPadding - lengthPadding) > 2)
        {
            // there should be no more than 2 pad characters
            return false;
        }

        foreach (char c in param)
        {
            if (Base64Characters.Contains(c) == false)
            {
                // string contains non-Base64 character
                return false;
            }
        }

        // nothing invalid found
        return true;
    }

I've not tested the code extensively, so there no functionality guarantees at all!

A: This should perform extremely well.
private static readonly HashSet<char> _base64Characters = new HashSet<char>() {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/',
    '='
};

public static bool IsBase64String(string value)
{
    if (string.IsNullOrEmpty(value))
    {
        return false;
    }
    else if (value.Any(c => !_base64Characters.Contains(c)))
    {
        return false;
    }

    try
    {
        Convert.FromBase64String(value);
        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}


text:
Q: Select nested fields in spark, cassandra, scala does not work as expected I am not able to select a nested field from a cassandra column using Spark + Scala. I have a nested field called category that looks like this:
category (
    industry text,
    category text,
    sector text,
    score double
    );

When I run the following code:
sitesDf.select("domain",  "category.category").filter(col("name").isin("CanSpace Solutions")).show(100, 0)

The value printed for the category.category column is the value from the category.industry column. In fact if I try to select sector or score I get the same thing, which is the value from the category.industry column.
The only thing that I can deduce is that maybe the fact that I have a field called category and also the sub-field with the same name somehow affects spark.


text:
Q: Solving integral with Leibniz' rule I'm trying to prove the following integral with Leibniz' rule: $\int_{0}^{1}{\frac{x}{(1+50x)^2}dx}$. Firstly I wrote:  $\int_{0}^{1}{\frac{x}{(1+bx)^2}dx}$ then I need to find a function $f$ that $\frac{\partial f}{\partial b}(x,b)= {\frac{x}{(1+bx)^2}}$ but now what?

A: If you insist on using Leibniz' rule for differentiating under the integral sign it can be done as follows.
Let
$$I(b) = \int_0^1 \frac{dx}{1 + bx}, \quad b > 0.$$
Note that
$$I(b) = \frac{1}{b} \ln (1 + bx) \Big{|}_0^1 = \frac{1}{b} \ln (1 + b).$$
Also, on applying Leibniz' rule to $I(b)$ we have
$$I'(b) = -\int_0^1 \frac{x}{(1 + bx)^2} \, dx,$$
and we see that the required integral comes from setting $b = 50$ in the above integral. Now
$$I'(b) = \frac{d}{db} \left (\frac{\ln (1 + b)}{b} \right ) = \frac{1}{b(1 + b)} - \frac{1}{b^2} \ln (1 + b),$$
yielding
$$\int_0^1 \frac{x}{(1 + bx)^2} \, dx = \frac{1}{b^2} \ln (1 + b) - \frac{1}{b(1 + b)}.$$
Finally, setting $b = 50$ gives
$$\int_0^1 \frac{x}{(1 + 50 x)^2} \, dx = \frac{1}{2500} \ln (51) - \frac{1}{2550}.$$


text:
Q: Modify columns width from code android I would like to know if there is a way to modify the width of two columns in a table layout (with three columns in total).
The problem is that every column has the same width and a lot of space is wasted because the first two only contain an id and a date meanwhile the last one contains a multiline description.
This is the code in which the table layout is populated:
tr_head.setLayoutParams(new LayoutParams(
    LayoutParams.MATCH_PARENT,
    LayoutParams.WRAP_CONTENT));

    tr_head.setBackgroundColor(Color.rgb(0, 230, 230));

    TextView lblSystemStoricalHeaderId = new TextView(this);
    lblSystemStoricalHeaderId.setText("ID      ");

    tr_head.addView(lblSystemStoricalHeaderId);

    TextView lblSystemStoricalHeaderData = new TextView(this);
    lblSystemStoricalHeaderData.setText("Data");

    tr_head.addView(lblSystemStoricalHeaderData);

    TextView lblSystemStoricalHeaderDescription = new TextView(this);
    lblSystemStoricalHeaderDescription.setText("      Descrizione");

    tr_head.addView(lblSystemStoricalHeaderDescription);

    tr_head.setMinimumHeight(30);

    tlSystemStorical.addView(tr_head, new TableLayout.LayoutParams(
       LayoutParams.MATCH_PARENT,
           LayoutParams.WRAP_CONTENT));

    for(int i=0;i<reportList.length;i++){

        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));

        TextView lblSystemStoricalId = new TextView(this);
        lblSystemStoricalId.setText(""+reportList[i].getId()+"");

        tr.addView(lblSystemStoricalId);

        TextView lblSystemStoricalData = new TextView(this);
        long dataC = reportList[i].getDate()*1000;
        java.util.Date df = new java.util.Date(dataC);
        String vv = new SimpleDateFormat("dd/MM/yyyy").format(df);
        lblSystemStoricalData.setText(vv);

        tr.addView(lblSystemStoricalData);

        TableRow.LayoutParams tv3Params = new TableRow.LayoutParams();
        tv3Params.width=0;
        tv3Params.weight=1;
        TextView lblSystemStoricalDescription = new TextView(this);
        lblSystemStoricalDescription.setText(""+reportList[i].getReportDescription());
        lblSystemStoricalDescription.setLayoutParams(tv3Params);

        tr.addView(lblSystemStoricalDescription);

        tr.setBackgroundResource(R.drawable.border);
        tr.setMinimumHeight(40);

        tlSystemStorical.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
    }

and this is the xml file:

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/scroll_view_system_description"
     >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
         >

        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:stretchColumns="*"
            android:id="@+id/tl_system_storical"
            >

        </TableLayout>
    </FrameLayout>

</ScrollView>

A: You can set width property to 0 for TableRow children, but specify layout_weight for them. So you'd write:

float[] weights = new float[] { 0.2f, 0.2f, 0.6f};

TextView lblSystemStoricalId = new TextView(this);
lblSystemStoricalId.setLayoutParams(new TableRow.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, weights[0]))

Where 0 is no width for view (because you're using weights), and weights array contains weights for your three views.
These weights should sum up to 1, and each weight is percent of the width that the column should take. So you need to assign weights to your TableRow children - lblSystemStoricalId would get weights[0], lblSystemStoricalData would get weights[1] and lblSystemStoricalDescription would have weights[2].


text:
Q: Public ,Private,классы, для чего они нужны именно в c# дайте пример Для чего служат классы? Дайте пожалуйста наглядный пример работы класса,не понимаю для чего он.
Как можно поподробнее пж.Только начал обучаться,многого не знаю!
 public class/public string name/для чего они именно нужны,можно же просто создать переменную в program /зачем в классе делать это?

A: Вы в конструктор (LEGO например) когда-нибудь играли?
Ну, так вот и создание программ подобно сборке конструктора, только в отличие от готового конструктора, купленного в магазине, детальки и кубики которого создает и продает производитель, вы самостоятельно придумываете и создаете виртуальные кубики и детальки. Класс - это, считай, чертеж кубика, а Объект - кубик созданный по этому чертежу. По одному чертежу может быть создано необходимое количество одинаковых кубиков. Объект - это считай функциональный блок программы
Язык C# изначально спроектирован так, чтоб программист работал в парадигме объектно-ориентированного программирования. Потому вам, волей-неволей придется перестроить способ своего мышления под использование классов.
Private, public - разграничение доступа к членам класса, подробнее читайте в книгах или документации.


text:
Q: How to return previous version of Sublime Text 3? I downloaded the new build 3103(from 9 February) and found, that my favourite theme Spacegray was changed. Specifically, symbols which were white color now are red - http://i.stack.imgur.com/EBWYh.png. Html and Css wasn't changed. Just JS. It is awful and ugly! Help me, please. Thanks you!

A: Sakuto's example is for Windows, for OSX, if you want to download, say, build 3126, you would change the current build # (which is 3143, as of this post date):
https://download.sublimetext.com/Sublime%20Text%20Build%203143.dmg
to
https://download.sublimetext.com/Sublime%20Text%20Build%203126.dmg

A: You can take the link from the official website and change the version number in the URL.
For example, if you want the 3100 version instead of 3103 version


text:
Q: Sequence within SQL Select I'm having a bit of a problem with using my sequence within a SELECT statement.
SELECT
     c.cust_name,
     c.site,
     customer_id_seq.nextval
FROM
     customer c
WHERE
     c.customer_id IS NULL
ORDER BY
     c.site_code ASC
;

Is giving me an error:

*00000 -  "sequence number not allowed here"
  *Cause:    The specified sequence number (CURRVAL or NEXTVAL) is
  inappropriate
         here in the statement.
  *Action:   Remove the sequence number.

It's probably something obvious I'm doing wrong so hopefully this will be an easy answer.

A: You cannot use sequences in queries with ORDER BY.
Remove the ORDER BY or put in into a subquery:
SELECT  q.*, customer_id_seq.nextval
FROM    (
        SELECT  c.cust_name,
                c.site
        FROM    customer c
        WHERE   c.customer_id IS NULL
        ORDER BY
                c.site_code ASC
        ) q

A: for IBM Imformix
In a SELECT statement, you cannot specify NEXTVAL or CURRVAL in the following contexts:

*

*In the projection list when the DISTINCT keyword is used

*In the WHERE, GROUP BY, or ORDER BY clauses

*In a subquery

*When the UNION operator combines SELECT statements

A: Why don't you use rownum instead of fetching values from sequence?


text:
Q: Getting error while installing laravel installer in window 10 I am using Windows 10 and composer is installed. When I try to install laravel installer globally using this command:
composer global require laravel/installer

[Composer\Downloader\TransportException]
The "https://repo.packagist.org/packages.json" file could not be downloaded:
failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

It means package not downloaded. I am not using any proxy server.
Composer diagnose result is listed below:
Checking platform settings: OK
Checking git settings: OK
Checking http connectivity to packagist:
[Composer\Downloader\TransportException] The "http://repo.packagist.org/packages.json" file could not be downloaded: failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Checking https connectivity to packagist:
[Composer\Downloader\TransportException] The "https://repo.packagist.org/packages.json" file could not be downloaded: failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Checking github.com rate limit: FAIL
[Composer\Downloader\TransportException] The
"https://api.github.com/rate_limit" file could not be downloaded: failed to
open stream: A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection failed
because connected host has failed to respond.

Checking disk free space: OK
Checking pubkeys:
Tags Public Key Fingerprint: 57815BA2 7E54DC31 7ECC7CC5 573090D0  87719BA6 8F3BB723 4E5D42D0 84A14642
Dev Public Key Fingerprint: 4AC45767 E5EC2265 2F0C1167 CBBB8A2B  0C708369 153E328C AD90147D AFE50952 OK
Checking composer version: OK
Composer version: 1.8.0
PHP version: 7.2.1
PHP binary path: E:\xampp\php\php.exe

A: To resolve this, configure composer to use the https repository by running the following command on the cli before installing Laravel

composer config -g repo.packagist composer https://packagist.org

A: Do you use any antivirus?
 If yes try to disable then check.
Sometime Mcafe prevent to download packagist.

A: The following steps will fix most "packages.json file could not be downloaded" issue with Composer:

*

*Verify your firewall setting. Disable Firewall for starters

*Enable PHP OpenSSL Extension

*Enable PHP allow_url_fopen directive

Note: Make sure you are working with the right PHP version and Environment (apache, CLI, etc.) when you modify the php.ini file.

A: I believe you are facing the same issue as this and
this. Composer recommends the following:

We recommend you fix your IPv6 setup. If that is not possible, you can try the following workarounds:

sadly, for the Windows workaround it says that if your setup cannot be fixed or if that didn't solve the issue then you should outright disable IPv6 which is a common answer and is also suggested here (however the video has been deleted so I've made this post to have a reliable answer).

(I've purposely aligned the windows as such so you can see the steps to the screen)

*

*Open Control Panel

*Navigate to Network and Internet

*Click on Network and Sharing Centre

*On the left hand side of the window click on Change adapter settings

*Find your adapter and open the properties by right clicking on it

*Find Internet Protocol Version 6 (TCP/IPv6) and uncheck it

*Click OK
Edit #1
What is suggested here is:

Install a Windows level VPN or proxy switcher that acts as the default route if you need to change your IP (effectively). Try CyberGhost

and that seemed to solve the issue for the OP.

A: I noticed this is also happening when changing networks (moving from office to office for example).
How I managed to solve it is to restart the docker container.
I had this situation happening 2 times already and the same solution helped.

A: All you need to do is to run your cmd/git as Administrator, no need to uninstall anything.


text:
Q: Remove field from composite key and collate duplicate data I'm looking for the best way to go about changing the primary key on a table in my DB without having to completely reinsert data from files again.  The modification I'm going to make is going to remove part of the primary key, which will result in tens of thousands of rows which need to be collated.
The part of the key being removed is a date field, which originally was needed to help uniquely identify incoming data.  However, the way this field is assigned at the source (outwith my control) has since changed and we now want to only keep the earliest occurrence of a particular record and discard the later occurrences.
The rest of the fields in the key (4 FK's) will produce unique records.
I'm assuming I'll need to transfer the data to another table, make the change and then re-insert?  Or is there a better way?

A: If the four records dictate a unique and you want the first one by date, then why not insert into another table, truncate, then insert back once you finish the table reconfigure (or create a new table with the right columns, insert into, then rename after dropping?) I don't think this can be improved upon, unless you want to delete from where not equal to, but the insert into should be faster (needs to be tested to prove for sure)

A: --Drop existing Primary Key
ALTER TABLE [<table>] DROP CONSTRAINT [<pk_constraint>];
GO

--Delete all rows except the first for each <Id>, ordered by <MyDateCol>
WITH delCTE AS (
  SELECT <Id>, ROW_NUMBER() OVER(PARTITION BY Id ORDER BY <MyDateCol>) AS RowNum
  FROM dbo.<Table>
)
DELETE a
FROM <table> a
JOIN delCTE b
  ON b.<Id> = a.<Id>
WHERE b.RowNum > 1;
GO

--Create the new Primary Key
ALTER TABLE [<table>] ADD CONSTRAINT [<pk_constraint>] PRIMARY KEY (<cols>);
GO

A: You can copy your table's data to a file using BCP (bulk copy), truncate the table, remove the old PK, create new PK (only 4 columns), import data from bcp file using a script (like Eric's script) that ignores the duplicates.
For many rows nothing can beat bulk copy :).


text:
Q: Nodejs crypto in typescript file I have created my own hash.js file that requires crypto and exports two functions that use crypto. It works fine in my api.js file when I hash passwords. However Now I am trying to import this file in my user.service.ts file so that I can send the hashed version of the password as a query parameter instead of the password itself. When I try to do so I always get a TypeScript error telling me that the functions crypto uses are not functions. However I can still console log the object I import and it looks legit to me. I looked at other java script files in the node_modules folder and I cannot see anything that should be wrong with my file.
I have also found out that there seems to be some definition file that I need to create but I have also had many attempts at creating such a file but nothing seems to work
A few hours of googling and the lack of knowledge amongst lack of time on this project led me to this post, it is my first stackoverflow post and I hope that it is not to unclear and I am glad to provide any information needed to help me resolve this issue.
Error code from console
LoginComponent.html:18 ERROR TypeError: crypto.randomBytes is not a function
at Object.genRandomString (hash.js:12)
at UserService.loginUser (user.service.ts:82)
at LoginComponent.getUser (login.component.ts:54)
at LoginComponent.onSubmit (login.component.ts:44)
at Object.eval [as handleEvent] (LoginComponent.html:18)
at handleEvent (core.es5.js:12014)
at callWithDebugContext (core.es5.js:13475)
at Object.debugHandleEvent [as handleEvent] (core.es5.js:13063)
at dispatchEvent (core.es5.js:8607)
at core.es5.js:10775

LoginComponent.html:18 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 31, nodeDef: {…}, elDef: {…}, elView: {…}}

the hash.js file

   'use strict';
    var crypto = require('crypto');

    /**
     * generates random string of characters i.e salt
     * @function
     * @param {number} length - Length of the random string.
     */
    function genRandomString (length){
        return crypto.randomBytes(Math.ceil(length/2))
                .toString('hex') /** convert to hexadecimal format */
                .slice(0,length);   /** return required number of characters */
    };

    /**
     * hash password with sha512.
     * @function
     * @param {string} password - List of required fields.
     * @param {string} salt - Data to be validated.
     */
    function sha512(password, salt){
        var hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */
        hash.update(password);
        var value = hash.digest('hex');
        return {
            salt:salt,
            passwordHash:value
        };
    };

    module.exports = {
        genRandomString: genRandomString,
        sha512: sha512
    };

A: There seems to be some confusion mixing JavaScript and TypeScript, but since I came across this issue myself, here is how I solved it.
First, your hash.js file should be hash.ts. Then you can import crypto and use it normally. Related code below:
import * as crypto from "crypto";

  public setEncryptionKeyDES(sKey: string) {
    const desIV = Buffer.alloc(8);
    this.encLobby.cipher = crypto.createCipheriv(
      "des-cbc",
      Buffer.from(sKey, "hex"),
      desIV,
    );
    this.encLobby.cipher.setAutoPadding(false);
    this.encLobby.decipher = crypto.createDecipheriv(
      "des-cbc",
      Buffer.from(sKey, "hex"),
      desIV,
    );
    this.encLobby.decipher.setAutoPadding(false);

    this.isSetupComplete = true;
  }

Edit1: Adding @attdona's answer from below, make sure you install @types/node into your project as well, or you will receive many errors related to node modules not being found.

A: Just hitted this issue (node v13.12.0, tsc v3.8.3). In my case the import:
import * as crypto from "crypto";

gives the error:
error TS2307: Cannot find module 'crypto'

because I have to install types definition for node: it includes crypto ambient declarations.
npm install @types/node

Note: If you have a global install of @types/node then you have to explicitly declare the path where @types
are located with --typesRoot option.
See here for details.

A:
When I try to do so I always get a TypeScript error telling me that the functions crypto uses are not functions.

This is happening because TypeScript statically analyzes your files and tries to help you with types of data that you're working with. If you're using a function written in JavaScript without any hint to TypeScript about what this function is using as arguments and what is the type of its return value, it simply cannot do its job, which is why you're getting an error.
You could create a decalration file, but you do not need to if you want a quick fix and if you won't be using these raw JS functions in other files. You just need to declare it anywhere in the file. You can read more about using declare keyword in TypeScript.

However I can still console log the object I import and it looks legit to me.

Judging by your screenshot, the function randomBytes is called properly (as you can see from the stack trace printed below the error). The problem is that the crypto object does not contain a method named randomBytes. This is because crypto is a global object in newer browsers.

Your crypto.js file is probably assuming existence of a different crypto global object than what browser has. Either provide this object in the proper scope so your function can see it, or inline those functions using a bundler such as Rollup.

A: Well this turned out to be a rather horrific rabbit hole to go down.  I followed a bunch of recommended suggestions but ultimately the solution that worked for me was (as always...) super-simple, ONCE you know how.
The answer was to use the browser built-in crypto functionality.  I only wanted to check a one-way digest of a password as being sufficient for a very lightweight app.  However most guides were only partial suggestions, or didn't work with my app's setup of using Angular 7 and babel.  So here's the final code I ended up with, with the following notes:

*

*Need to encode into an array buffer to perform the digest

*The digest function is returning a promise, so had to unwrap its value using .then

*Did not require adding any NPM modules or imports

Anyway here's the code, hope it helps other Stack Overflowers.
I also found Daniel Roesler's Github page very useful for implementations of various web cryptography examples.
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-user-create',
  templateUrl: './user-create.component.html',
  styleUrls: ['./user-create.component.css']
})
export class UserCreateComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    sha256("hello").then(digestValue => {
      console.log(digestValue);
    });
  }
}

async function sha256(str) {
  const encoder = new TextEncoder();
  const encdata = encoder.encode(str);
  const buf = await crypto.subtle.digest("SHA-256", encdata);
  return Array.prototype.map.call(new Uint8Array(buf), x=>(('00'+x.toString(16)).slice(-2))).join('');
}


text:
Q: How to scroll a LinearLayout horizontally? I have a LinearLayout that I do larger than the screen. I want to scroll that in horizontal. I have the next code but it doesn't work. Can anybody help me?
<HorizontalScrollView
    android:id="@+id/horizontalScrollView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:id="@+id/gm_movimientos"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:orientation="horizontal" >

    </LinearLayout>
</HorizontalScrollView>

A: Your HorizontalScrollView width needs to be set to either match_parent or a fixed size.  Right now the ScrollView is expanding to the same dimensions of the LinearLayout (i.e. its bounds are also going off of the screen).


text:
Q: Discussion in CSV file I am having a CSV file with three columns as below and I want to count the value of 'AT' and both 'AT + LH' for each Type and Date, then put it in a separate column in another CSV file.
Input CSV file:
╔═══════╦═══════╦═══════╗
║ Date  ║ Type  ║ Value ║
╠═══════╬═══════╬═══════╣
║ Nov-2 ║ M2222 ║ AT    ║
║ Nov-2 ║ M2222 ║ LH    ║
║ Nov-3 ║ M2222 ║ LH    ║
║ Nov-3 ║ M2223 ║ LH    ║
║ Nov-3 ║ M2223 ║ AT    ║
╚═══════╩═══════╩═══════╝

I need the output like this:
Output CSV file:
╔═══════╦═══════╦═════════════════════════╦═════════════╗
║ Date  ║ Type  ║ Total (Total = AT + LH) ║ Value of AT ║
╠═══════╬═══════╬═════════════════════════╬═════════════╣
║ Nov-2 ║ M2222 ║                       2 ║           1 ║
║ Nov-3 ║ M2222 ║                       1 ║           0 ║
║ Nov-3 ║ M2223 ║                       2 ║           1 ║
╚═══════╩═══════╩═════════════════════════╩═════════════╝

I have tried using dictionaries for this and am unable to get the desired output. But in the output I am getting the columns of Date and Type into a single column.
Code:
from collections import Counter
import csv
from collections import defaultdict
from collections import OrderedDict
import collections
import pandas as pd

with open(r'file1','wb') as crack,open(r'file2','wb') as crack1:

  w = csv.writer(crack,delimiter=',', quoting = csv.QUOTE_ALL)
  w1 = csv.writer(crack1,delimiter=',', quoting = csv.QUOTE_ALL)

  for row in zip(['DATE & BASIC TYPE'],['Total Triggerred']):
    w.writerow(row)

  for row in zip(['DATE & BASIC TYPE'],['No of LOH']):
   w1.writerow(row)

 with open(r'inputfile, 'rb') as infile:
  reader = csv.reader(infile)
  next(reader, None)
  dict1=defaultdict(list)

  for row in reader:
   dict1[(row[0],row[1])].append(int(row[3]))

  for key, value in dict1.iteritems():
   for row in zip([key], [sum(dict1[key])]):
    #print key, sum(dict1[key])
      w.writerow(row)

 with open(r'inputfile', 'rb') as infile:
   reader = csv.reader(infile)
   next(reader, None)
   dict2=defaultdict(list)

 for row in reader:
   if row[2]=='AUTO RELEASE':
      dict2[(row[0],row[1])].append(int(row[3]))

 for key, value in dict2.iteritems():
   for row in zip([key], [sum(dict2[key])]):
    #print key, sum(dict2[key])
     w1.writerow(row)

 a = pd.read_csv(r'file1.csv')
 b = pd.read_csv(r'file2.csv')
 merged = a.merge(b, on='DATE & BASIC TYPE')
 merged.to_csv(r'outputfile.csv', index=False)

I am getting Output like this:
╔═══════════════════╦═══════╦═════════════╗
║    Date & Type    ║ Total ║ Value of AT ║
╠═══════════════════╬═══════╬═════════════╣
║ ('Nov-2','M2222') ║     2 ║           1 ║
║ ('Nov-3','M2222') ║     1 ║           0 ║
║ ('Nov-3','M2223') ║     2 ║           1 ║
╚═══════════════════╩═══════╩═════════════╝

A: I think this can help you:
import pandas as pd

df = pd.read_csv('input_csv.csv', sep=';')
print df.groupby(['Date','Type'])['Type','Value'].count()

Here's the additional code that Albe originally submitted in the comments.
import pandas as pd

#read csv file using data frame
df = pd.read_csv('input_csv.csv', sep=',')

#count how many "AT" values in a data frame
df['Value AT'] = (df['Value'] == 'AT').astype(int)

#sum "AT" and "LH" of a data frame
df['TOT'] = (df['Value'] == 'AT').astype(int) + (df['Value'] == 'LH').astype(int)

#grouping by data and type
print df.groupby(['Date', 'Type'])['TOT', 'Value AT'].sum()

...At the end you can add this piece of code to create the csv output file:
#print df_grouped
df_grouped.to_csv(r'outputfile.csv', index=True)

A: I think you're overcomplicating the task. It is much simplier to use T-SQL in such situation. For instance you can use MySQL, create table for the CSV file, load data into it using this approach: LOAD DATA INFILE Syntax. Then select aggregated data you need using query like this:
SELECT
t.Date,
t.Type,
(
    SELECT COUNT(*)
    FROM table as t1
    WHERE t1.Date = t.Date and t1.Type = t.Type and t1.Value IN ('AT', 'LH')
) as `Total (Total = AT + LH)`,
(
    SELECT COUNT(*)
    FROM table as t2
    WHERE t2.Date = t.Date and t2.Type = t.Type and t2.Value IN ('AT')
) as `Value of AT`
FROM table as t
GROUP BY t.Data, t.Type;

And load data back to CSV: SELECT ... INTO Syntax


text:
Q: java - mvc implementing JProgressBar with observer/observable So far i managed to grip how it all works i have gotten every module working whit no problem:

*

*View: Builds UI and provides methods for addressing JComponents on the main frame

*Controller: Provides action listeners and links the View and Model

*Model: Contains all the logic as it's changed View is notified via Observer / Observable

Now my dilemma here is how would you implement JProgressBar in to this design pattern. The problem is i paint my JProgressBar like so:
bar = new JProgressBar();
bar.setString(consumed + " / " + total);
bar.setStringPainted(true);
Anyhow any way i choose to implement JProgressBar in to this design pattern if yields some kind of problem either error or it simply updateds the consumed value but does not paint the consumed part of the JProgressBar.
Here is my shortened code:
View >> Update method:
public void update(Observable servlet, Object argument)
{
    if(argument.equals("cap-cons-add")) {
        cap_bar.setValue(model.getConsumedCap());
    }
}

Controller >>
class moduleBrowserAction implements MouseListener
{
    public void mouseClicked(MouseEvent arg0)
    {
        if(arg0.getClickCount() == 2 && model.getTower() != null)
        {
            String module = view.getModuleTree().getLastSelectedPathComponent().toString();
            model.addModule(module);
            model.incModulesCount(1);
            model.incConsumedCap(5000);
        }
    }
    public void mouseEntered(MouseEvent arg0){}
    public void mouseExited(MouseEvent arg0){}
    public void mousePressed(MouseEvent arg0){}
    public void mouseReleased(MouseEvent arg0){}
}

class towerBrowseAction implements ActionListener
{
    public void actionPerformed(ActionEvent arg0)
    {
        String tower = view.getTowerBrowser().getSelectedItem().toString();
        String[] data = dataStream.serializeData(tower);
        Integer s = Integer.valueOf(data[3]).intValue();
        Integer a = Integer.valueOf(data[4]).intValue();

        Double  em = Double.valueOf(data[5]).doubleValue();
        Double  th = Double.valueOf(data[6]).doubleValue();
        Double  kn = Double.valueOf(data[7]).doubleValue();
        Double  ex = Double.valueOf(data[8]).doubleValue();

        Integer cap = Integer.valueOf(data[1]).intValue();

        if(model.getTower() == null && model.validateTower(tower) == true)
        {
            model.setTower(tower);
            model.setCapacitorBar(view.getCapBar(), cap);
            model.setHardners(em, th, kn, ex);
            model.setSieldAndArmor(s, a);
        } else {
            integrity.towerSelectedWarning();
        }
    }
}

And my model:
private int cap_total = 0;
private int cap_consumed = 0;

public void incConsumedCap(int amount)
{
    this.cap_consumed += amount;
    this.setChanged();
    this.notifyObservers("cap-cons-add");
}

public int getConsumedCap()
{
    return this.cap_consumed;
}

public void setCapacitorBar(JProgressBar bar, int max)
{
    this.cap_total = max;
    bar.setMaximum(max);
    bar.setString(cap_consumed + " / " + max);
    bar.setStringPainted(true);
}

So the application works like this: And element is selected from JComboBox it changes few labels and sets the JProgressBar by calling setCapacitorBar().. Now as additional modules are added to to main element the function model.incConsumedCap(5000); that increments the consumed amount and sets the setChaned() flag and calls notifyObservers() in update method the mentioned JProgressBar is addressed directly setting a consumed value however to no effect.

*

*I know this is a hell of a read so i would just ask for a direct suggestion how would you implement a JProgressBar if you were making a GUI application building it upon Observer - Observable design


text:
Q: what is alternative of .attrs in material ui 5 with styled-components as styled-engine This is how we add className to a styled-component
import styled from 'styled-components';
export const FieldsColumnWrapper = styled.div.attrs({
  className: 'components-list column',
})`
  grid-area: components-list;
  display: flex;
`

We can use attrs function to pass this className = components-list column, whenever this component is rendered., the classname component-list column is present in the div
However if use styled-component as styled engine for mui 5, and then code is modified as below
import { styled } from '@mui/material/styles';
export const Wrapper = styled('div', {
  name: 'form-builder',
  slot: 'form-builder',
}) `
  display: grid;
  grid-template-areas: 'components-list forms-list field-config-editor';
  grid-template-columns: 300px 1fr 450px;
`

I want to know what should I use on the styled coming from @mui/material/styles, that will allow me to add className on the HTML element created by the component?

A: '.attrs' API is not yet added in MUI v5. If you want to achieve the same behaviour, you can do this,
import { styled } from '@mui/material/styles';

export const Wrapper = styled('div')`
  display: grid;
  grid-template-areas: 'components-list forms-list field-config-editor';
  grid-template-columns: 300px 1fr 450px;
`;

Wrapper.defaultProps = {
  name: 'form-builder',
  slot: 'form-builder',
};

You can refer more about this issue here
https://github.com/mui/material-ui/issues/29492


text:
Q: Centering one out of multiple elements using text-align: center Looking to center only one out of multiple elements within a div. The problem with assigning the div with text-align: center is that it targets them all. Is there an easy way of doing this?
HTML

    Span 1

    Span 2

CSS
div {background: gray; width: 250px;}

A: Put the styling on the span, or give it an id/class and add display:block like so:

  Span 1

  Span 2

#span1 {
  text-align: center;
  display:block;
}

http://jsfiddle.net/3wHH9/1/

A: you can target :first-child or :last-child on the span or use nth-of-type(value-here) if it's not the first or last but another one in the order
JSFIDDLE


text:
Q: How to join queries (not collections) in MongoDB? I have multiple queries which all have a shared id.
I am trying to join these queries into a single output but can not seem to figure it out.
Any ideas? Thank you!

Collection contains customers and sellers (id of each, date of sale, etc.).
The intended output is one that contains (seller id, buyer id, number of time seller has sold an item, number of distinct customer seller has sold to, array of distinct customers seller has sold to, array of transaction id).
I've been able to query each component, for example:
Array of seller ids seller has sold to
db.completedSessions.aggregate([
{
  $group:
  {
    _id: {seller: "$sellerId"}, customer_id_array: {$push: "$customerId"}
   }
}
])

Count of sales by seller
db.completedSessions.aggregate([
{
  $group:
  {
    _id: {user: "$sellerId"}, count: {$sum: 1}
  }
}
])

I'm trying to join these queries together using the sellerId.


text:
Q: hint didn't work in edittext in android I use Hint and it works in emulator, but when I install the code in the phone, Hint doesn't work.
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="نام"
    android:gravity="right"
    android:id="@+id/fname"
    android:singleLine="true"
    android:imeActionLabel="Next">
</EditText>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="نام خانوادگی"
    android:gravity="right"
    android:id="@+id/lname"
    android:singleLine="true"
    android:imeActionLabel="Next">
</EditText>

Any idea?

A: Copy the String in the strings.xml (means your relevant language) and then give the hint as
android:hint="@string/strname"

<resources>

  <string name="strname">نام خانوادگی</string>

</resources>

The above will be work if the device will support your language.
android:singleLine="true" remove this from your edittexts then you can see the hints

A: This issue is actually an infamous bug in android EditText. When using singleLine="true" or maxLines="1" or generally anything that trigger android:scrollHorizontally="true" the EditText in Layout stage fail to render RtL hint correctly..
If your language layout direction is RtL you can simply solve this problem by setting gravity="right|center_vertical" to your EditText.
P.S: This Issue has been on IssueTracker for a long time but there hasn't been any fix since. You can help this issue resolves faster by starring this issue:
https://issuetracker.google.com/issues/36924615

A: the hint as Persian or other Unicode language
when you define InputType for EditBox doesn't
show. you should delete the
android:inputType="..."


text:
Q: RedirectToAction() generates wrong URL I'm having a problem with MVC 4, and I guess it's something really trivial, but it's been bugging me for the last day and I can't seem to figure it out.
I have this url:
http://www.example.com/my-dashed-url

I have a Controller named:
public class MyDashedUrlController: Controller
{
}

I have only two Routes like this:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute("my-dashed-url",
               "my-dashed-url/{action}",
               new { controller = "MyDashedUrl", action = "Index" });

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home",
                            action = "Index",
                            id = UrlParameter.Optional }
        );

I get to the index just fine. However, when I do this:
   public ActionResult Index()
    {
        if (NoUserIsLoggedOn)
            return RedirectToAction("Logon", "MyDashedUrl");

        return View();
    }

    public ActionResult Logon()
    {
        Contact c = GetContact();

        return View(c);
    }

It doesn't redirect me to the "Logon" action properly.
It should redirect me to:
 http://www.example.com/my-dashed-url/logon

but instead it tries to redirect me to:
 http://www.example.com/logon

... which doesn't work (404 Not Found)
I'm missing something. Can anyone spot it? If anyone needs any more information, let me know.
And it's EVERY RedirectToAction that does the same thing in this controller. A Html.BeginForm("Logon", "MyDashedUrl") would also generate:
http://www.example.com/logon
I guess it has to do something with the Routes I defined, but I can't find the faulty one, seeing as they're all the same. If I disable all of my Routes besides the default one from MVC, the problem remains the same

A: Make sure that you have declared this custom route BEFORE the default one:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "my-dashed-url",
        "my-dashed-url/{action}",
        new { controller = "MyDashedUrl", action = "Index" }
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
}

Remember that routes are evaluated in the order you declared them. So the first route that matches a request will be used. If you declare your custom route after the default one, it is the default route that will match the request.


text:
Q: Output message from java process to JTextArea I have tried the others link on this portion, but still unable to get what I need. Thus I would like to seek help from the group here.
Below is my code:
try {
                String file = new File("iperf3.exe").getCanonicalPath();
                String cmd1[] = {file,"-c","ping.online.net","-P","10","-w","710000"};
                Process p1 = Runtime.getRuntime().exec(cmd1);

                BufferedReader input1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));

                String line1;
                while ((line1 = input1.readLine()) != null) {
                    txtConsole1.setText(line1);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

The output message to the textArea is only the last message from executing the command. May I know how can I stream all the output messages into the textArea?
Thank you.

A: You are overriding previous content of txtConsole1 by calling txtConsole1.setText(line1);. Get all your output in variable and at last set content in txtConsole1
String line1;
String content;
while ((line1 = input1.readLine()) != null) {
    content += line1;
}
txtConsole1.setText(content);


text:
Q: Question on notations for second covariant differentiation of a tensor I would like to get a better understanding on the concept of $\nabla T$, where $T$ is a tensor field not covector field or vector field.
Could anybody explain why or not the following relation holds or if even makes any sense?
$$
\nabla_X\nabla_YZ = \nabla\nabla Z(X,Y)
$$
I believe it would be useful to derive the LHS into an equivalent form which unfortunately I can't deduce at the moment.
Thanks!

A: Let $T$ be an $(r,s)$-type tensor field, then the covariant derivative $\nabla T$ is the $(r,s+1)$-type tensor field is given by
$$\nabla T(X,\vec{Z})=(\nabla_XT)(\vec{Z})=\nabla_X(T(\vec{Z}))-\sum_{i=1}^{s}T(Z_1,\dots,\nabla_XZ_i,\dots,Z_s),$$
where $\vec{Z}=(Z_1,\dots,Z_s)$ is a $s$-tuple of vector fields on $M$.
Now it is easiest to compute the second covariant derivative of a vector field, i.e. when $T$ is a $(1,0)$-type tensor field. We simply have
$$(\nabla\nabla T)(X,Y)=\nabla(\nabla T)(X,Y)=\nabla_X(\nabla T(Y))-\nabla T(\nabla_XY)=\nabla_X\nabla_YT-\nabla_{\nabla_XY}T.$$
Now we try and do the same computation for arbitrary $(r,s)$-type tensor fields.
\begin{align}
(\nabla\nabla T)(X,Y,\vec{Z})=\nabla_X(\nabla T(Y,\vec{Z}))-\nabla T(\nabla_XY,\vec{Z})-\sum_{i=1}^{s}\nabla T(Y,Z_1,\dots,\nabla_XZ_i,\dots,Z_s),
\end{align}
where $\vec{Z}=(Z_1,\dots,Z_s)$ is an $s$-tuple of vectors. We also compute
\begin{align}
\nabla_X(\nabla_YT)(\vec{Z})-(\nabla_{\nabla_XY}T)(\vec{Z}) & = \nabla_X(\nabla_YT(\vec{Z}))-\sum_{i=1}^{s}(\nabla_YT)(Z_1,\dots,\nabla_XZ_i,\dots,Z_s)\\
& \quad - \nabla_{\nabla_XY}(T(\vec{Z}))+\sum_{i=1}^{s}T(Z_1,\dots,\nabla_{\nabla_XY}Z_i,\dots,Z_s) \\
& = \nabla_X(\nabla T(Y,\vec{Z}))-\sum_{i=1}^{s}\nabla T(Y,Z_1,\dots,\nabla_XZ_i,\dots,Z_s)\\
& \quad - \nabla T(\nabla_XY,\vec{Z}).
\end{align}
So we have shown
$$(\nabla\nabla T)(X,Y,\vec{Z})=\nabla_X(\nabla_YT)(\vec{Z})-(\nabla_{\nabla_XY}T)(\vec{Z}).$$
Now we can use the Hessian of the tensor field to simplify things a bit. Define the Hessian of $T$ with respect to $X,Y\in\Gamma(TM)$ to be the $(r,s)$-type tensor field $\nabla\nabla_{(X,Y)}T$ characterized by
$$(\nabla\nabla_{(X,Y)}T)(\vec{Z})=\nabla\nabla T(X,Y,\vec{Z}).$$
Then we see that
$$\nabla\nabla_{(X,Y)}T=\nabla_X\nabla_YT-\nabla_{\nabla_XY}T.$$ (Alternatively you could write by a bit of abuse of noation $\nabla\nabla T(X,Y)=\nabla_X\nabla_YT-\nabla_{\nabla_XY}T$).
An interesting side note that might help with the intuition of $\nabla\nabla T$: if $X,Y,Z\in\Gamma(TM)$ then $\nabla\nabla Z(X,Y)-\nabla\nabla Z(Y,X)=R(X,Y)Z$, where $R$ is the $(1,3)$-type Riemann curvature tensor.


text:
Q: How do I go about finding the bottleneck in a slow web based chat application I am working on a one-to-one chat application running in production. It uses StropheJS to connect to Ejabberd server over BOSH (using ejabberd's default connection manager). The main problem we are facing is that sometimes it takes a long time for messages to reach the other end (~30 secs or so) while otherwise they reach in no time. Something like this --
User A sends a message
User B receives instantly
---- [some more message exchange that happens instantly] -----
User A sends message
No message received by B
User A sends another message
Still no message received by B
...
...
(20-30 secs later) B receives the two messages together (not as a single message but without any noticeable time interval between them)
Apart from the chat, the other parts of the web application work fine.
I am having a hard time figuring out what is the exact bottleneck. It's running on a Ubuntu 10.04 instance (2 GB memory + 4 GB Swap).
One thing I should mention is that a single machine is used for hosting everything -- apache2, mysql, ejabberd, rabbitmq, mongodb, the message queue workers and the python web app served by apache2 using mod_wsgi. Besides, apache also serves some (very few) static files and proxies the BOSH requests to ejabberd. At any time apache has the max process count (around 40) and using 700-800 MB of memory so my guess is that it's doing most of the work. Per day, it's serves an average of 200k requests (this figure is obtained from access logs)
We have moved static files to be served from CDN (which had improved performance significantly) and had also logged slow queries and optimized by creating indexes which again resulted in overall perf gain although I plan to do the exercise tomorrow again.
Is there a systematic approach that can be followed to arrive at the bottleneck.
I am also confused as to,

*

*whether switching to nginx will improve performance

*whether it's time to move stuff to their own servers, probably they may be competing for resources on the single machine?

*upgrade the memory on the machine

*load balancing the http server (although I am a bit doubtful about this since New Relic shows almost negligible time spent in request queuing.)

*What kind of measurements can be done on the frontend/backend to get an idea?

PS: It would also be great to have some suggestions on books to read for understanding the basics of server management/architecture/tuning.

A: I'd say you're putting a lot on a single box. Memory is just one metric. You could be hitting CPU bottlenecks when you get traffic, or you're limiting I/O. iostat will give an idea on the disk activity. You'll probably see the issue go away if you move services to their own servers (have your web server separate from the jabber one).


text:
Q: JavaScript / Three.js - Adding mooving transition curve to changing camera position in z axis I'm trying to make my first steps into Three.js, But I have a slight problem.
I have a rotating icosahedron in the middle of my scene and when I click a button it should start rotating a bit faster, and the camera should get closer to it so it seems bigger. The problem is that I'm changing the distance / rotation speed in a linear fashion. What I want to achieve is to add some kind of acceleration curve to this animation.
Howewer... I'm lost. I've looked at tons of tutorials and examples but none of them explained to me how to achieve a cubic-bezier like effect.
I'm also trying to use GSAP to get it working but I've got no effects.
If you're not able to help then maybe know any good articles where I can learn such stuff from? Or maybe a tutorial that covers such transitions?
So here's my code:

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 5000 );

let renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

window.addEventListener('resize',() => {
  let width = window.innerWidth;
  let height = window.innerHeight;
  renderer.setSize( width, height );
  camera.aspect = width / height;
  camera.updateProjectionMatrix();
});

camera.position.z = 10;

var pointL1 = new THREE.PointLight( 0xffffff, 2, 30);
pointL1.position.x = -4;
pointL1.position.y = 7;
pointL1.position.z = 8;
scene.add( pointL1 );

var geometry1 = new THREE.IcosahedronGeometry(5, 1);
var material1 = new THREE.MeshBasicMaterial( { color: 0x222222, wireframe: true } );
var icosahedron = new THREE.Mesh( geometry1, material1 );
scene.add( icosahedron );

icosahedron.rotation.y -= 1;

let maxCameraDist = 10;
let minCameraDist = 8;
let cameraDist = 10;

let duringChange = false;

function render () {
  if (duringChange == false) {
    icosahedron.rotation.y += 0.001;
    icosahedron.rotation.z += 0.001;
      if (cameraDist < maxCameraDist) {
        cameraDist += 0.05;
        camera.position.z = cameraDist;
      }
    } else {
      icosahedron.rotation.y += 0.003;
      icosahedron.rotation.z += 0.003;
      if (cameraDist > minCameraDist) {
        cameraDist -= 0.05;
        camera.position.z = cameraDist;
      }
  }
}
let loop = function() {
  requestAnimationFrame(loop);
  render();
  renderer.render(scene, camera);
}
loop();

document.querySelector('button').addEventListener('click',() => {
  if (duringChange == false) duringChange = true; else duringChange = false;
})
button {
  padding: 20px;
  position: absolute;
  z-index: 2;
}
canvas {
  position: absolute;
  z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
<body>
<button>Change it</button>
</body>

`

A: An example with a non-deprecated library - GSAP 3.
Eases are here: https://greensock.com/docs/v3/Eases

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 5000);

let renderer = new THREE.WebGLRenderer({
  alpha: true,
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

window.addEventListener('resize', () => {
  let width = window.innerWidth;
  let height = window.innerHeight;
  renderer.setSize(width, height);
  camera.aspect = width / height;
  camera.updateProjectionMatrix();
});

camera.position.z = 15;

var pointL1 = new THREE.PointLight(0xffffff, 2, 30);
pointL1.position.x = -4;
pointL1.position.y = 7;
pointL1.position.z = 8;
scene.add(pointL1);

var geometry1 = new THREE.IcosahedronGeometry(5, 1);
var material1 = new THREE.MeshBasicMaterial({
  color: 0x222222,
  wireframe: true
});
var icosahedron = new THREE.Mesh(geometry1, material1);
scene.add(icosahedron);

icosahedron.rotation.y -= 1;

let cameraDistFrom = 15;
let cameraDistTo = 8;
let rotSpeed = 0.1;
let clock = new THREE.Clock();

function render() {
  let t = clock.getDelta();
  icosahedron.rotation.y += rotSpeed * t;
  icosahedron.rotation.z += rotSpeed * t;
}
let loop = function() {
  requestAnimationFrame(loop);
  render();
  renderer.render(scene, camera);
}
loop();

document.querySelector('button').addEventListener('click', () => {
  rotSpeed = 0.3;
  gsap.fromTo(camera.position, {
    z: cameraDistFrom
  }, {
    z: cameraDistTo,
    duration: 1,
    ease: "back.out(3)"
  });
})
body {
  overflow: hidden;
  margin: 0;
}

button {
  padding: 20px;
  position: absolute;
  z-index: 2;
}

canvas {
  position: absolute;
  z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.4/gsap.min.js"></script>

<body>
  <button>Change it</button>
</body>


text:
Q: Prove that $(1-\frac{1}{2^2}\cdots 1-\frac{1}{9\,999^2})(1-\frac{1}{10\,000^2})=0.500\,05$ Prove that $\displaystyle\left(1-\frac{1}{2^2}\right)\left(1-\frac{1}{3^2}\right)\cdots\left(1-\frac{1}{9\,999^2}\right)\left(1-\frac{1}{10\,000^2}\right)=0.500\,05$

Here are all my attempts to solve this problem:
So the first thing I thought about is to transform the expression of the form $$\left(1-\frac{1}{n^2}\right)$$
To the expression: $$\left(\frac{n^2-1}{n^2}\right)$$
But in evaluating the product $$\prod_{k=2}^n    \frac{n^2-1}{n^2}$$ seems way complicated than what I'm capable of, I don't know how to evaluate products even if I know that notation.
The other idea is to transform again $$\left(1-\frac{1}{n^2}\right)\to \left(1-\frac{1}{n}\right)\left(1+\frac{1}{n}\right)$$
But this isn't helpful in any way.
My other attempts were to try to see what happens when I start evaluating this sum, and it turns out that a lot of things cancel out but again no result.
I'll be happy if someone could guide me to solve this problem. (I feel that there is some kind of symmetry that I should remark, a symmetry that would allow me to cancel things out and to have my final)

A: Note that you can factor $n^2 - 1 = (n - 1)(n + 1)$ to find something like
\begin{align*}
\left(1 - \frac 1 {2^2}\right)&\left(1 - \frac 1 {3^2}\right) \cdots \left(1 - \frac 1 {10000^2}\right) \\ & =\left(\frac 1 2 \cdot\frac 3 2\right) \left(\frac 2 3 \cdot\frac 4 3\right) \left(\frac 3 4 \cdot \frac 5 4\right) \left(\frac 4 5 \cdot \frac 6 5 \right)\cdots \left(\frac{10000 - 1}{10000} \cdot \frac{10000+1}{10000}\right)
\end{align*}
Convince yourself that everything cancels (i.e. the product telescopes), except for a factor of $1/2$, and the final factor of $10001/10000$.

A: $$
\begin{align}
\prod_{k=2}^n\left(1-\frac1{k^2}\right)
&=\prod_{k=2}^n\frac{(k-1)(k+1)}{k^2}\\
&=\prod_{k=2}^n\frac{k-1}{k}\hspace{1.2cm}\prod_{k=3}^{n+1}\frac{k}{k-1}\\
&=\frac12\left(\prod_{k=3}^n\frac{k-1}{k}\right)\frac{n+1}{n}\left(\prod_{k=3}^n\frac{k}{k-1}\right)\\
&=\frac12\frac{n+1}{n}\\
&=\frac{n+1}{2n}
\end{align}
$$

A: $$\left(\frac{3}{2}\frac{4}{3}\frac{5}{4}\cdots\frac{n}{n-1}\frac{n+1}{n}\right)\cdot\left(\frac{1}{2}\frac{2}{3}\frac{3}{4}\cdots\frac{n-2}{n-1}\frac{n-1}{n}\right)$$
After mass cancellations, pull the $$\frac{n+1}{2}\text{ and }\frac{1}{n}$$
$$\frac{n+1}{2}\cdot\frac{1}{n}$$
Substitute the value of n=10000
and get the result


text:
Q: Installed extensions are not showing extension manager open cart I'd installed Paytm extension in my Open cart website, it says extension is installed and i can view in install history but i can not view in extension manager,
install history
i have refreshed modification still no luck.
i have tried razor payment gateway too and the same happens
i'm on opencart version 3.0.2.0
Please help. Thank you


text:
Q: Элементы коллекции как параметр метода У меня есть коллекция с некоторыми значениями типа int. Есть метод который принимает один параметр типа int.
Как я могу выполнить метод для каждого значения из коллекции?

A: В языке Java интерфейс Collection наследует интерфейс Iterable, поэтому вы можете воспользоваться циклом For-Each:
Collection<Integer> collection = ...;
for (Integer item : collection) {
    myFavoriteMethod(item);
}

Таким образом, метод myFavoriteMethod() будет вызван последовательно для каждого элемента из коллекции.


text:
Q: Keep the sites-available/enabled structure when compiling Nginx I am using nginx on ubuntu which by default has the sites-available/enabled directory structure similar to Apache to store the sites configuration files. I have compiled nginx (because I need a third party module) using the below configuration:
./configure \
    --prefix=/opt/nginx/version \
    --http-log-path=/var/log/nginx/access.log \
    --error-log-path=/var/log/nginx/error.log \
    --pid-path=/var/run/nginx.pid \
    --with-http_ssl_module \
    --user=nginx \
    --group=nginx \
    --add-module=...

Nginx is working fine, but right now I need to configure all my sites in /opt/nginx/version/conf/nginx.conf which isn't as maintainable as with the sites-available/enabled directory structure whereby I can create 1 file per site and decide which ones are enabled with symlinks.
I had a look at the install options but all I see is --conf-path to specify the path to nginx.conf.
Is there a way to reuse the sites-available/enabled directory structure with a compiled nginx?

A: If you look inside the default Ubuntu /etc/nginx/nginx.conf you ought to find the following line.
http {
    ...
    include /etc/nginx/sites-enabled/*;
}

That is what you need to get the sites-enabled magic happen.

A: I haven't nginx installed on any machine, but I guess that this is handled the same way as in Apache, where the main configuration file just includes all files located in /etc/apache/sites-enabled. These files are in turn just symlinks to files in /etc/apache/sites-available and these links are either manually mananged or with the help of the a2enable script family.
It should be very easy to recreate a similar structure with your self-compiled nginx.


text:
Q: (hyper) elliptic curve in characteristic two and the Jacobian criterion Let $k$ be a field of characteristic two and let $E$ be a curve given by
$$
y^2=x*(x+1)*(x^2+x+1)*(x^3+x+1)\quad\text{or}\quad y^2=f(x)
$$
Now we have $dy^2/dy=2y=0$ and consider the Jacobian criterion:
$$
J=(f'(x),\:\:\:0\:)
$$
what does this imply for $E$? Where is this curve regular?
I thought that $E$ is regular except at the zeros of $f'$. Is this true?

A: One must be careful here: first, one has to distinguish between regular points of the curve and smooth points. $x\in E$ is regular, if the local ring $O_{E,x}$ is regular, that is a discrete valuation ring. $x\in E$ is smooth if $x$ is regular and remains regular after every purely inseparable base change $E\times_k\ell$ of the curve. So regularity and smoothness coincide if $k$ is a perfect field.
The Jacobian criterion (as You apply it) gives the smooth points of $E$, provided $k$ is a perfect field. Under this additional assumption you are right that the regular points $(a,b)\in E$ are precisely the ones satisfying $f^\prime(a)=0$.
Consider the point $(0,0)\in E$: its local ring is $k[x,y]_{(x,y)}$, which is a local extension of the local ring $k[x]_{(x)}$. Except $x$ itself all the polynomial factors appearing on the right hand side of the defining equation of $E$ are units in $k[x]_{(x)}$ and therefore in $k[x,y]_{(x,y)}$. Hence $(x,y)k[x,y]_{(x,y)}=yk[x,y]_{(x,y)}$, because $y^2=ux$ with a unit $u$ of $k[x,y]_{(x,y)}$. We have shown that the maximal ideal $(x,y)k[x,y]_{(x,y)}$ of the local ring in $(0,0)$ is generated by one element, thus it is a regular local ring and $(0,0)$ is a regular point.


text:
Q: Where to store the result of the computation on each element visited in the Visitor pattern? I am trying to use a visitor (in the sense of "separating algorithm from data structure"). All of the examples I see do something like a sum - where the visitor is SumVisitor and stores an ivar "Sum" that simply adds the value of each element that it visits. However, what if you want to associate the result of the computation with each element? As an easy case, say you want the algorithm (the visitor) to square each element that it visits. Where do you store the results? The only thing I can think of is something like a vector > that is stored in the visitor, but that seems strange. Any suggestions on how to do something like this?

A: You have four options:
1) Store them in the original data structure somehow if there's somewhere to put them.
2) Store them in the visitor (e.g. use a map from elements to results).
3) Store them elsewhere, and pass 'elsewhere' to the visitor so it knows where to put the results.
4) Create a new data structure to store them as you go along.
Which you pick depends on what you're trying to achieve.


text:
Q: Compute the difference of three series (motivated by an integral formula) Let
\begin{align}
L&=2^{3 / 2} \pi^{4} \frac{1}{4} \sum_{n, m, k=1}^{\infty} n^{2} m a_{n} a_{m} b_{k}\left(\delta_{m, n+k}+\delta_{n, m+k}-\delta_{k, n+m}\right) \\[5pt]
R_{1}&=2^{3 / 2} \pi^{4} \frac{1}{4} \sum_{n, m, k=1}^{\infty} n^{3 / 2} m^{3 / 2} a_{n} a_{m} b_{k}\left(\delta_{m, n+k}+\delta_{n, m+k}+\delta_{k, n+m}\right) \\[5pt]
R_{2}&=\frac{1}{2} 2^{3 / 2} \pi^{4} \frac{1}{4} \sum_{n, m, k=1}^{\infty} n^{1 / 2} m^{1 / 2} k^{2} a_{n} a_{m} b_{k}\left(\delta_{m, n+k}+\delta_{n, m+k}-\delta_{k, n+m}\right),
\end{align}
where the $\delta$ denote the Kronecker delta.
How can we compute $$L-R_1-R_2 \ ?$$
The motivation for this computation comes from an integration by parts formula analyzed on MathOverflow.

A: With the help of the Kronecker delta's we can carry out the summation over $k$,
$$L-R_1-R_2=2^{3/2}\pi^4 \frac{1}{4}\sum_{n=1}^\infty\sum_{m=1}^\infty a_na_m\biggl[\bigl(m n^2-(m n)^{3/2}-(m-n)^2 \sqrt{m n}\bigr) b_{|n-m|}$$
$$-\bigl(m n^2+(m n)^{3/2}-(m+n)^2 \sqrt{m n}\bigr) b_{n+m}\biggr].$$
Without further knowledge of the coefficients this cannot be evaluated further.


text:
Q: This script wont sort correctly by age My script asks for a name, phone number, and date of birth and then amends these details to a comma separated value file called "birthday.csv".
It then Sorts "birthday.csv" by date of birth. The newly sorted file is then be displayed. It also calculates the age of each person and the number of entries in the file.
My problem is, it takes in all the information, but it then will not sort the file before printing the contents.
Here is the code:
a=0
while [ $a -lt 2 ];
do
    echo Please enter a first name
    read firstName
    echo Please enter last name
    read lastName
    echo Please enter phone number
    read phoneNumber
    echo Please enter date of birth - format dd/mm/yyyy
    read dob
    echo "$firstName,$lastName,$phoneNumber,$dob" >> Birthdays.csv
    echo If you would like to add another person press 1 or enter 2 to proceed
    read a
done

INPUT=./Birthdays.csv
OLDIFS=$IFS
IFS=","
[ -f ${INPUT} ] && while read Name Surname Telephone DOB
do
    birthMonth=${DOB:0:2}
    birthDay=${DOB:3:2}
    birthYear=${DOB:6:4}

    currentDate=`date +%d/%m/%Y`

    currentMonth=${currenDate:0:2}
    currentDay=${currentDate:3:2}
    currentYear=${currentDate:6:4}

    if [[ "$currentMonth" -lt "$birthMonth" ]] || [[ "$currentMonth" -eq "$birthMonth" && "$(currentDay)" -lt "$($birthDay)" ]]
    then
        let Age=currentYear-birthYear-1
    else
        let Age=currentYear-birthYear
    fi

    echo "Name : $Name"
    echo "Surname : $Surname"
    echo "Telephone : $Telephone"
    echo "DOB : $DOB"
    echo "Age : $Age"
    echo "##########################################"
done < $INPUT
IFS=$OLDIFS
    echo $DATE

exit 0;

I think the problem lies with
if [[ "$currentMonth" -lt "$birthMonth" ]] || [[ "$currentMonth" -eq "$birthMonth" && "$(currentDay)" -lt "$($birthDay)" ]]
then
    let Age=currentYear-birthYear-1
else
    let Age=currentYear-birthYear
fi

But I'm not sure what is causing that to not sort?

A: Firstly remove the brackets around "$(currentDay)" and "$(currentDay)"

A: One bug you have, at least:
if [[ "$currentMonth" -lt "$birthMonth" ]] || [[ "$currentMonth" -eq "$birthMonth" && "$(currentDay)" -lt "$($birthDay)" ]]

"$(currentDay)" should be just "$currentDay" and "$($birthDay)" should be just "$birthDay".
You also have a typo here:
currentMonth=${currenDate:0:2}

That should be currentDate. Put set -u at the top of your script to catch such mistakes.
Also, like Mat said, I don't see any sorting code :)


text:
Q: Calculating residue of $f(z)=\frac{z^2+z^3}{({\sin z})^3}$ at its singularities So the singularities would be at $n\pi$, $n\in \mathbb{Z}$.
The residue in $z=0$, I have already calculated (through shifting the series) and it equals $1$ however for the others $n\pi$ I am stuck. Help would be appreciated

A: Hint:-
$z^{2}=(z-n\pi)^{2}+2n\pi(z-n\pi)-2n^{2}\pi^{2}$ and
$z^{3}=(z-n\pi)^{3}+3n\pi(z-n\pi)^{2}+3n^{2}\pi^{2}(z-n\pi)+n^{3}\pi^{3}$
Use these and write $\frac{z^{2}+z^{3}}{\sin(z)}=(-1)^{n}\frac{(z-n\pi)^{2}+2n\pi(z-n\pi)-2n^{2}\pi^{2}+(z-n\pi)^{3}+3n\pi(z-n\pi)^{2}+3n^{2}\pi^{2}(z-n\pi)+n^{3}\pi^{3}}{(\sin(z-n\pi))^{3}}$.
And now calculate the residue as you would by computing the coefficient of $\frac{1}{z-n\pi}$ in the Laurent Series expansion.
Another hint:- This whole thing can be done by calculating the residue at $0$ of
$$(-1)^{n}\frac{z^{2}+2n\pi z-2n^{2}\pi^{2}+z^{3}+3n\pi z^{2}+3n\pi^{2} z+n^{3}\pi^{3}}{\sin^{3}(z)}$$
Caution:- I often make errors in calculation so the expressions might not be entirely accurate but I think the hint is enough to provide you with a method to proceed by!!!.
I wish you a succesful dig for the residue.

A: The computation is simpler if you set $z=n\pi+w$.
$$f(n\pi+w) = (-1)^n [(n\pi+w)^2 + (n\pi+w)^3]\sin^{-3}(w).$$
You develop the numerator and you use twice Taylor-Young formula, first for $\sin(w)$, next for $(1+h)^{-3}$ as $h \to 0$, to get an asymptotic expansion
\begin{eqnarray*}
f(n\pi+w)
&=& (-1)^n \big(a+bw+cw^2+o(w^2)\big) \Big(w-\frac{w^3}{3}+o(w^3)\Big)^{-3} \\
&=& (-1)^n \big(a+bw+cw^2+o(w^2)\big) w^{-3}(1-w^2+o(w^2)) \\
&=& (-1)^n w^{-3}\big(a+bw+(c-a)w^2+o(w^2)\big) \\
&=& (-1)^n \big(aw^{-3}+bw^{-2}+(c-a)w^{-1}+o(w^{-1})\big).
\end{eqnarray*}
The residue of $f$ at $n\pi$ is $(-1)^n(c-a)$.


text:
Q: when append a , my click function doesnt work when you click on my link #addScnt, a new child appears. Everything works fine so far but I append another  tag and when you click on it, there is supposed to be something happen but as you can guess, nothing happens...but when I create another link inside my page (so outside my jquery function) my click function works... So I doesn't understand what's going on there.
$(function() {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents p').size() + 1;

    $('#addScnt').click(function() {
        $('
<input type="file" id="p_scnt" name="p_scnt_' + i +'"> Remove
').appendTo(scntDiv);
        i++;
        return false;
    });

    $('#remScnt').click(function() {
        alert();
    });

});

my html

Ajoutez une nouvelle photo

            <input type="file" id="p_scnt" name="p_scnt">

So, $('#remScnt').click(function() doesnt work at all when I add another child...but If I literally put a  tag with the id #remScnt on my page, my alert will work...

A: Two things are going on here...
First, it looks like you're re-using id values.  If you're adding this multiple times to the page:
Remove

Then you have multiple elements with the same id, which is invalid.  So the behavior of things like jQuery selectors ($('#remScnt')) are undefined.  (They may coincidentally work, but it's still invalid and undefined.)  Instead, try using classes instead:
Remove

and:
$('.remScnt')

Second, the click binding here happens only once when the page loads:
$('.remScnt').click(function() {
    // etc.
});

Bindings are attached to elements, not to selectors.  So it will only work for elements which exist at the time the binding is created.  Elements added to the page afterward won't have anything attached to their click events.
You can get around this by delegating the event handler to a common parent, and filtering events based on the selector.  jQuery provides the .on() function for this:
$(document).on('click', '.remScnt', function() {
    // etc.
});

What this does is actually bind to the click event of the entire document, and respond to that event any time something matching the provided selector invokes such an event.  So put it simply, in this version the '.remScnt' selector is evaluated when the click event happens, rather than when the event handler is defined.
You don't need to use document to hold the event, any common parent would work.  As long as that parent element isn't dynamically added/removed like the target elements.  For example, if all of the target a class="remScnt" elements are going to be in the same div, then you can target that div instead:
$('#someParentDiv').on('click', '.remScnt', function() {
    // etc.
});

A: You need to make sure you only use each ID once, and use event delegation for dynamically created elements. Try:
$('#p_scents').on('click', '#remScnt', function() {
    alert();
});

A: When you append an element you need to use .on like this,
$('#p_scents').on('click', '#remScnt', function(){
    // Some Stuff
});