text:
Q: POST multiple files using Django test client in same request I am trying to build some tests for uploads on my Django site. It allows multiple files to be uploaded so I need to test when multiple files are uploaded.
Testing one file works great:
from django.test import Client

def test_stuff(self):
    with open('....\file.csv','rb') as fp:
        c = Client()
        response = c.post('/', {'name': 'Some Name', 'email': 'some@email.com', 'file': fp})

But trying it with a list of files doesn't work.
def test_stuff(self):
    file_list = # get list of file paths to open
    myfiles = []
    for file in file_list:
        with open('....\file.csv','rb') as fp:
            myfiles.append(fp)
    c = Client()
    response = c.post('/', {'name': 'Some Name', 'email': 'some@email.com', 'file':myfiles})

And neither does:
def test_stuff(self):
    file_list = # get list of file paths to open
    myfiles = []
    for file in file_list:
        with open('....\file.csv','rb') as fp:
            myfiles.append(fp)
    c = Client()
    response = c.post('/', {'name': 'Some Name', 'email': 'some@email.com',}, files={'file':myfiles})

or
def test_stuff(self):
    file_list = # get list of file paths to open
    myfiles = []
    for file in file_list:
        with open('....\file.csv','rb') as fp:
            myfiles.append(fp)
    c = Client()
    response = c.post('/', {'name': 'Some Name', 'email': 'some@email.com'}, files=myfiles)

My view gets the files from request.POST.get('myfiles'), but FILES is empty.
Is there a way to POST multiple files with django test client or should I use something else?

Edited to make more accurate

A: Part of the problem was that with with, the file is immediately closed exiting the statement. Unsurprisingly, the other part was getting the data in the correct format. Django's test client wants ALL the data as a dictionary so, since i was also sending the username and email, it needed to be formatted like:
def test_stuff(self):
    file_list = # get list of file paths to open
    data = {}
    files = []
    for file in file_list:
        fp = open('....\file.csv','rb')
        files.append(fp)
    data['myfiles'] = files
    data['name'] = 'Some Name'
    data['email'] = 'some@email.com'
    c = Client()
    response = c.post('/', data)

A: Also, if you use SimpleUploadedFile you can pass multiple files:
file1 = SimpleUploadedFile('file1.txt', b'file-1')
file2 = SimpleUploadedFile('file2.txt', b'file-2')

response = self.client.post('some url', data={
  'file': [ file1, file2]
})

And in the view it could be smth like:
class UploadFormView(FormView):
    template_name = '...'
    form_class = YourForm

    # We require to override the post method to manage multiple files.
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist('file')
        if form.is_valid():
            for f in files:
              # do smth with file
            return self.form_valid(form)
        else:
            return self.form_invalid(form)


text:
Q: Merging one-by-many CSV files in Python I have the output of a series of stochastic simulations in the form of a .csv file that look something like this:
Run,ID,Var
1,1,7
1,2,9
1,3,4
2,1,3
2,2,4
2,3,8

etc.
Along with that, I have another data file, also a .csv, formatted like so:
ID, Var2, Var3
1,0.89,0.10
2,0.45,0.98
3,0.27,0.05
4,0.98,0.24

Note: There are some values in the data file that do not appear in the simulation file. I'd like these to be ignored.
What I'd like to do is write a script that takes each value ID from the first .csv file, and finds Var2 and Var3 and puts it together, to end up with something like:
Run, ID, Var, Var2, Var3
1,1,7,0.89,0.10
1,2,9,0.45,0.98
1,3,4,0.27,0.05
2,1,3,0.89,0.10
2,2,4,0.45,0.98
2,3,8,0.27,0.05

Any suggestions on a way to do this? I confess this is at the limits of my understanding for data handling in Python. I'd got a fair sense of how to do it in SAS, but I'd prefer to keep this a one-language task so that they can be processed as a single script.

A: ouput.csv:
Run, ID, Var
1, 1, 7
1, 2, 9
1, 3, 4
2, 1, 3
2, 2, 4
2, 3, 8

data.csv:
ID, Var2, Var3
1, 0.89, 0.10
2, 0.45, 0.98
3, 0.27, 0.05
8, 0.4, 0.5

NOTE that even if we have entries within data.csv, not present in ouput.csv it won't affect the end result, since while we parse output.csv we only lookup the ID's that we know off from output.csv, though the opposite is not true data.csv at a minimun must contain all the IDs from output.csv, though this can be easily taken care of if you need to.
code:
import csv
from pprint import pprint

data = dict([(row['ID'], row) for row in csv.DictReader(open('data.csv', 'rb'), skipinitialspace = True)])
values = []
for row in csv.DictReader(open('output.csv', 'rb'), skipinitialspace = True):
    values.append(row)
    values[-1].update(data[row['ID']])

>>> pprint(values)
[{'ID': '1', 'Run': '1', 'Var': '7', 'Var2': '0.89', 'Var3': '0.10'},
 {'ID': '2', 'Run': '1', 'Var': '9', 'Var2': '0.45', 'Var3': '0.98'},
 {'ID': '3', 'Run': '1', 'Var': '4', 'Var2': '0.27', 'Var3': '0.05'},
 {'ID': '1', 'Run': '2', 'Var': '3', 'Var2': '0.89', 'Var3': '0.10'},
 {'ID': '2', 'Run': '2', 'Var': '4', 'Var2': '0.45', 'Var3': '0.98'},
 {'ID': '3', 'Run': '2', 'Var': '8', 'Var2': '0.27', 'Var3': '0.05'}]
>>>

now to save back into a csv file.
fieldnames = ['Run', 'ID', 'Var', 'Var2', 'Var3']
f = open('combined.csv', 'wb')
csvwriter = csv.DictWriter(f, fieldnames = fieldnames)
csvwriter.writerow(dict((fn,fn) for fn in fieldnames)) # 2.7 has writeheader, which is cleaner
[csvwriter.writerow(row) for row in values]
f.close()

$ cat combined.csv
Run,ID,Var,Var2,Var3
1,1,7,0.89,0.10
1,2,9,0.45,0.98
1,3,4,0.27,0.05
2,1,3,0.89,0.10
2,2,4,0.45,0.98
2,3,8,0.27,0.05

I hope this helps.

A: solution without using csv module:
with open('data.txt') as f1,open('data1.txt') as f2,open('data3.txt','w') as f3:
    header1=f1.readline().strip().split(',') #header from file 1 i.e Run,ID,Var

    header2=f2.readline().strip().split(',')[1:] #header from file 2 ,i.e Var2, Var3

    dic={x.strip().split(',')[0]:x.strip().split(',')[1:] for x in f2 if x.strip()} #use dict to save data as per ID from file 2

    f3.write(','.join((header1+header2))+'\n') #write the new header(header1+header2) to file 3

    for x in f1:
        f3.write(x.strip()+','+','.join(dic[x.split(',')[1]])+'\n') #fetch results from dic as per the ID obtained from the current line in data.txt

output:
data3.txt contains
Run,ID,Var, Var2, Var3
1,1,7,0.89,0.10
1,2,9,0.45,0.98
1,3,4,0.27,0.05
2,1,3,0.89,0.10
2,2,4,0.45,0.98
2,3,8,0.27,0.05

A: Simple and easy:
f = open('one.csv', 'r')
one = f.read()
f.close()

f = open('two.csv', 'r')
two = f.read()
f.close()

one = one.split('\n')[1:-1]
two = two.split('\n')[1:-1]
output = 'Run, ID, Var, Var2, Var3\n'

for o in one:
  for t in two:
    row = t.split(',')
    if o.split(',')[1] == row[0]:
      output += '%s,%s,%s\n' % (o, row[1], row[2])

# or save it to a file
print output

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mac Based Python GUI Libraries I am currently building a GUI based Python application on my mac and was wondering could anyone suggest a good GUI library to use?
I was looking at python's gui programming faq and there was a lot of options making it hard to choose.
I am developing on snow leopard and cross-platform is not essential (if it makes a difference).

A: If you're not concerned about cross-platform compatibility, then PyObjC (also see Apple's info about PyObjC) provides a direct bridge to the native OS X Cocoa interfaces.

PyObjC (pronounced pie-obz-see) is the key piece which makes it possible to write Cocoa applications in Python. It enables Python objects to message Objective-C objects as if they're fellow Python objects, and likewise facilitates Objective-C objects to message Python objects as brethren.

Note that Apple tends to support and then not support these non-native interfaces to Cocoa; it's a good sign that there are recent releases of PyObjC.

A: wxPython and Qt (via PyQT or PySide) provide native OS X widgets and work across all major platforms.

A: There's a relatively new project active now called PyGUI which aims to provide a more modern cross-platform GUI for Python apps.  On OS X, it uses PyObjC to provide native GUI elements.  It might be easier to get started using it rather than delving directly into PyObjC and Interface Builder.


text:
Q: Create a list of strings from A to BBB in C# Morning all,
I have a simple question that I could do with some help with.
I need to create a list of strings that will start with A and finish at some other point e.g BBB, but I am not sure the best and fastest way of doing it.
Thanks in advance.
Ok as requested more information.
I need to create a simple way of creating a list of bays for a warehouse.  This wareshouse can have a variable number of Aisles in it, a variable number of rows in each aisle and a variable number of bins for the row.  So when the user comes to setup their particular warehouse they can specify the start letter of the Aisle and the end letter of the Aisle.
As you can now see the hardcoded list from A to ... isn't going to work.

A: No error checking (start number could be greater than end number in which case you would get an infinite loop) but the code works fine.
Hope you at least understand it before submitting it!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testList
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write((int)'A');
            Console.Write((int)'Z');
            Console.WriteLine("Whats the starting string?");
            string start = Console.ReadLine().ToUpper();
            Console.WriteLine("Whats the end string?");
            string end = Console.ReadLine().ToUpper();

            List<string> retVal = new List<string>();
            retVal.Add(start);

            string currentString = start;
            while (currentString != end)
            {
                currentString = IncrementString(currentString);
                Console.WriteLine(currentString);
                retVal.Add(currentString);
            }
            retVal.Add(end);
            Console.WriteLine("Done");
            Console.ReadKey();
        }

        private static string IncrementString(string currentString)
        {
            StringBuilder retVal = new StringBuilder(currentString);
            char endChar= currentString[currentString.Length - 1];
            for (int x = (currentString.Length - 1); x >= 0; x--)
            {
                char c = currentString[x];
                if (TryIncrementChar(ref c))
                {
                    retVal[x] = c;
                    break;
                }
                else
                {
                    retVal[x] = 'A';
                    if (x == 0)
                    {
                        retVal.Insert(0,'A');
                    }
                }
            }
            return retVal.ToString();

        }
        private static bool TryIncrementChar(ref char currChar)
        {
            if (currChar != 'Z')
            {
                currChar++;
                return true;
            }
            return false;
        }
    }
}


text:
Q: how to run a selenium webdriver script using .bat file? I have scripted a program in selenium web driver using java in eclipse and jre compiler.
now I need to run this code using .bat file.
Could you please guide, how to proceed with it? so that the selenium web driver program can be run using this bat file.

A: set projectLocation=F:\Selenium\TestNGBatchExample
cd %projectLocation%
set classpath=%projectLocation%\bin;%projectLocation%\lib*
java org.testng.TestNG %projectLocation%\testng.xml


text:
Q: How can I get the name only to show in the MessageBox using C# windows form .NET framework? I have already a class that contains name and id and I'm also using lists method and including the name and id of each student.I'm also selecting a course from the combo box and selecting an index from the list box that contains names and id. The i.Name is generating an error, I have also tried writing All students.SelectedItem instead of i.Name ( That worked but It showed the name and id )
attached below is the screenshot of that [![enter image description here][1]][1]
This is my code below
 if (comboBox1.SelectedIndex != -1 && Allstudents.SelectedIndex != -1)

        {

            var query3 = from i in prod
                         where i == Allstudents.SelectedItem
                         select i.Name;
            foreach(var i in query3)
            {
                var b = query3  ;
            }

            MessageBox.Show("The student" + i.Name +
                "Has registered in the course" + comboBox1.SelectedItem);

How Can I only show the name ?
[1]: https://i.stack.imgur.com/ehQ6K.png

A: You could use the split string method to split the selected string.
Assuming spaces in between, use the following code as a demonstration:
if (listBox1.SelectedIndex != -1)
{
    string[] s = listBox1.SelectedItem.ToString().Split(' ');
    MessageBox.Show(s[1]);
}


text:
Q: The X angle between two 3D vectors? I have two 3D vectors called A and B that both only have a 3D position. I know how to find the angle along the unit circle ranging from 0-360 degrees with the atan2 function by doing:
EDIT: (my atan2 function made no sense, now it should find the "y-angle" between 2 vectors):
toDegrees(atan2(A.x-B.x,A.z-B.z))+180

But that gives me the Y angle between the 2 vectors.
I need to find the X angle between them. It has to do with using the x, y and z position values. Not the x and z only, because that gives the Y angle between the two vectors.
I need the X angle, I know it sounds vague but I don't know how to explain. Maybe for example you have a camera in 3D space, if you look up or down than you rotate the x-axis. But now I need to get the "up/down" angle between the 2 vectors. If I rotate that 3D camera along the y-axis, the x-axis doens't change. So with the 2 vectors, no matter what the "y-angle" is between them, the x-angle between the 2 vectors wil stay the same if y-angle changes because it's the "up/down" angle, like in the camara.
Please help? I just need a line of math/pseudocode, or explanation. :)

A: atan2(crossproduct.length,scalarproduct)

The reason for using atan2 instead of arccos or arcsin is accuracy. arccos behaves very badly close to 0 degrees. Small computation errors in argument will lead to disproportionally big errors in result. arcsin has same problem close to 90 degrees.

A: Computing the altitude angle
OK, it might be I finally understood your comment below about the result being independent of the y angle, and about how it relates to the two vectors. It seems you are not really interested in two vectors and the angle between these two, but instead you're interested in the difference vector and the angle that one forms against the horizontal plane. In a horizontal coordinate system (often used in astronomy), that angle would be called "altitude" or "elevation", as opposed to the "azimuth" you compute with the formula in your (edited) question. "altitude" closely relates to the "tilt" of your camera, whereas "azimuth" relates to "panning".
We still have a 2D problem. One coordinate of the 2D vector is the y coordinate of the difference vector. The other coordinate is the length of the vector after projecting it on the horizontal plane, i.e. sqrt(x*x + z*z). The final solution would be
x = A.x - B.x
y = A.y - B.y
z = A.z - B.z
alt = toDegrees(atan2(y, sqrt(x*x + z*z)))
az = toDegrees(atan2(-x, -z))

The order (A - B as opposed to B - A) was chosen such that "A above B" yields a positive y and therefore a positive altitude, in accordance with your comment below. The minus signs in the azimuth computation above should replace the + 180 in the code from your question, except that the range now is [-180, 180] instead of your [0, 360]. Just to give you an alternative, choose whichever you prefer. In effect you compute the azimuth of B - A either way. The fact that you use a different order for these two angles might be somewhat confusing, so think about whether this really is what you want, or whether you want to reverse the sign of the altitude or change the azimuth by 180°.

Orthogonal projection
For reference, I'll include my original answer below, for those who are actually looking for the angle of rotation around some fixed x axis, the way the original question suggested.
If this x angle you mention in your question is indeed the angle of rotation around the x axis, as the camera example suggests, then you might want to think about it this way: set the x coordinate to zero, and you will end up with 2D vectors in the y-z plane. You can think of this as an orthogonal projection onto said plain. Now you are back to a 2D problem and can tackle it there.
Personally I'd simply call atan2 twice, once for each vector, and subtract the resulting angles:
toDegrees(atan2(A.z, A.y) - atan2(B.z, B.y))

The x=0 is implicit in the above formula simply because I only operate on y and z.
I haven't fully understood the logic behind your single atan2 call yet, but the fact that I have to think about it this long indicates that I wouldn't want to maintain it, at least not without a good explanatory comment.
I hope I understood your question correctly, and this is the thing you're looking for.

A: Just like 2D Vectors , you calculate their angle by solving cos of their Dot Product

You don't need atan, you always go for the dot product since its a fundamental operation of vectors and then use acos to get the angle.
double angleInDegrees = acos ( cos(theta) ) * 180.0 / PI;


text:
Q: Which of the following is more appropriate? Cambridge dictionary says :

They have three children UNDER the age of five.

While Learners dictionary.com says :

The game is suitable for children BELOW the age of ten.

I am really confused about UNDER and BELOW in the reference of age.
Please recommend me a site to go for.
Thanks I advance.

A: You can trust both dictionaries. It's perfectly fine if you use "under" to talk about age:

It is illegal to sell alcohol to children under the age of 18.
Health-care services are free for pregnant mothers and for children under the age of 6.

And you can also use "below" to mean the same thing:

Children below the age of 12 are the main target group of beneficiaries.
Most industrialized countries have less than 20 per cent of their populations below the age of 15.

A: The game is suitable for children below (younger than, under) the age of 10 (MW Learners).
The dictionary has put "under" in parenthesis, which means you can use either below or under in the sentence i.e. both are correct.
However, the "under" is more idiomatic and common than "below" when it's used in the sense of lower number, amount, or size than something.

A: There is very little difference between under and below.  They are both prepositions meaning something is lower or less than something else.  Generally under is used more widely than below and if there is some concern as to which word to use the safe choice is under.
The word under can be used when someone or something is under control, under new management or under the command of.  These scenarios give one person authority over someone and the other person is under that authority.  One item is lower or beneath the control of another. Under is used to mean less than in numerical terms.  For example, there were under five students in the class.
There are numerous expressions using the word under before another word:

Under stress – feeling pressured by an emotional situation.
Under someone's influence – being controlled by someone else.
Under construction – building works that are not completed.
Under a spell – being bewitched or controlled by magic.
Under pressure – feeling pushed into making a decision.
Below is very close in meaning to under and as they are both prepositions they are both used in the same way to describe the position of something or someone.  Below is used more often to describe objects on different levels for instance pictures on a wall.  One picture may be below the other.  Temperatures and water levels are registered below a certain height.
Below is used with words like sea level, surface and poverty line all measures of numerical levels.
Below the surface – just under the top level
Below the poverty line – just under the line of being poor and needy.
Below sea level – land that is below the level of the sea.
The opposite of below is above showing again how this word is linked to distance between things while the opposite of under is over showing the word to be part of a covering.  When you go to sleep you lie under the covers.
Both words have some interesting idioms.
Below the Salt: If you are 'below the salt' you are being placed in a position below your value.  In Medieval times the salt, a valued commodity, was placed in the middle of the table.  The head of the table was the highest ranking person so if you were placed lower down at the table below the salt you were less important.


text:
Q: How to use WebListenerCommunicationListener in Service Fabric ASP.NET Core 2 I just created my first ASP.NET Core 2 Stateless Service Fabric Reliable service but the first thing I notice is that now, by default uses the KestrelCommunicationListener insted of the WebListenerCommunicationListener used in core 1.X. It seems it has been removed from the  service fabric aspnetcore libraries.
This won't let me configure multiple processes on the same physical or virtual machine to host web applications on the same port, disambiguated by either a unique URL path or hostname. These features are useful in Service Fabric for hosting multiple websites in the same cluster.
Does anybody know if I´m missing something or is there a workaround?
Thanks

A: According to the release notes of the SDK 2.7.198, Weblistener is not yet supported for asp.net Core 2.0.
https://blogs.msdn.microsoft.com/azureservicefabric/2017/08/09/release-of-sdk-2-7-198-and-runtime-5-7-198-for-windows/

A: Answer provided by a PM
"in ASP.NET Core 2.0 the Microsoft.AspNetCore.Server.WebListener package has been merged with Microsoft.Net.Http.Server into a new package called Microsoft.AspNetCore.Server.HttpSys (aspnet/Announcements#211). Service Fabric does not yet have an integration package for this, so if you're using WebListener, you will need to remain on version 1.x.x for the time being. Support for the new Microsoft.AspNetCore.Server.HttpSys package will arrive in the next SDK feature release (Azure/service-fabric-aspnetcore#15)."

A: According to the release notes for SDK version 2.8.0 from September 25, 2017 at https://msdnshared.blob.core.windows.net/media/2017/10/Microsoft-Azure-Service-Fabric-Release-Notes-SDK-2.8.0-Runtime-6.0.0.pdf, this is now available.
Per the release notes:

In ASP.NET Core 2.0, the WebListener server was repacked and renamed
  to HttpSys. A Service Fabric integration package for the HttpSys
  server is now available: Microsoft.ServiceFabric.AspNetCore.HttpSys.
  This package contains a renamed ICommunicationListener implementation
  for HttpSys: HttpSysCommunicationListener.
If you are currently using WebListener and want to upgrade to ASP.NET
  Core 2.0, use the Microsoft.ServiceFabric.AspNetCore.HttpSys package
  instead of the Microsoft.ServiceFabric.AspNetCore.WebListener package.
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners() {
  return new ServiceInstanceListener[]
  {
    new ServiceInstanceListener(serviceContext =>
      new HttpSysCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
        new WebHostBuilder()
          .UseHttpSys()
          .ConfigureService(
            service => services
              .AddSingleton<StatelessServiceContext>(serviceContext))
          .UseContentRoot(Directory.GetCurrentDirectory())
          .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
          .UseStartup<Startup>()
          .UseUrls(url)
          .Build()))
  };
}

A: According to the updated docs, see ASP.NET Core in Service Fabric Reliable Services

HttpSys is built on the Windows HTTP Server API. This uses the http.sys kernel driver used by IIS to process HTTP requests and route them to processes running web applications. This allows multiple processes on the same physical or virtual machine to host web applications on the same port, disambiguated by either a unique URL path or hostname. These features are useful in Service Fabric for hosting multiple websites in the same cluster.


text:
Q: The geometry of linear systems I found it in book "Linear Algebra and its Application" by Gilbert Strang. It is given as:
Suppose we have a system containing $n$ unknowns and $n$ dimensions.
$\Rightarrow $ The first equation provides $n-1$ dimensional plane in $n$  dimensions.
$\Rightarrow$ The second plane intersects it in smaller set of dimension  $n-2$ .
$\Rightarrow$ Assuming all goes well, every new plane reduces the dimension by one.
At the end, when all the $n$ planes are accounted for.
The intersection has dimension 0.
$\Rightarrow$ It is a point, it lies on all the planes, and its coordinates satisfy all $n$ equations. It is the solution.
I am not able to get the following statements. I would be grateful if someone please understand with a example...or figure ...

A: Take $n=3$ with a first equation $x=1$, which means all points of the form $(1,a,b)=(1,0,0)+a(0,1,0)+b(0,0,1)$ which is two dimensional. Then we intersect with $y=3$, it remains the points $(1,3,b)=(1,3,0)+b(0,0,1)$, one dimensional. And then a last step with intersection, for example, with $z=7$; it remains a single point $(1,3,7).$

A: Consider the case where you have three equations and three unknowns.
$$a_1x + b_1y + c_1z = d_1$$
$$a_2x + b_2y + c_2z = d_2$$
$$a_3x + b_3y + c_3z = d_3$$
Each of these equations define a plane in $\mathbb R^3$.
Take the first two. If we equate them there are three possibilities.

*

*They are the same plane. Since they are equal they have all points in common. This is a degenerate case.

*They are parallel planes. Therefore, they have no points in common so the system has no solutions.

*They intersect. They are neither of the above two cases so they intersect in a straight line. This line is one dimensional which is one dimension less than the two dimensions of a plane. This is the case referred to in the book.

Let's assume we are dealing with case 3 above and consider the third plane. Once again there are three cases.

*

*The third plane and the line of intersection of the first two planes do not intersect. Therefore, the system has no solutions.

*The line of intersection of the first two planes lies completely in the third plane. This case has an infinite number of solutions. This is a degenerate case and once again, not what is referred to in the book.

*The line of intersection of the first two planes cuts through the third plane in which case it intersects at exactly one point. That point is the solution and has zero dimensions.


text:
Q: How to interpret results for a moderating model? I have a moderation model, but the results look a bit wired.
A is DV, which is a binary variable.
B is M, also a binary variable.
C is IV, which is a continuous variable.
If I ran the regression of A only on B, the coefficient on B is positive and significant (e.g., 0.1418). When I add C in the model and the interactive term of B and C, the coefficient on B is still positively significant, but the number is lower (the coefficient on B is 0.1376). And the interactive term between B and C is significantly positive (0.0222).
Can I explain the results in this way?
The higher the C, the more likelihood that A presents. However, this tendency is weaker when M is present.


text:
Q: Please select a certificate to authenticate yourself to Got this pop up message this morning on my computer:
Please select a certificate to authenticate yourself to
us-prod-asyncgw.teams.microsoft.com:443
-George Bennitt
-George Bennitt

A: Looks like Microsoft has confirmed this issue. Check out this reddit thread: https://www.reddit.com/r/MicrosoftTeams/comments/nwozrs/select_a_certificate_message/


text:
Q: Joomla user registration plugin I am interested in customizing the authentication method for a Joomla website.
There is a comprehensive tutorial on how to make a custom authentication plug-in, however a plug-in of that sort customizes the behavior on each log-in.
The behavior I need to implement should occur only once during registration. Is there any way to implement this?

A: You'll want to create a user plugin that responds to the onBeforeStoreUser event instead of an authentication plugin. The plugin creation process is much the same for user plugins. The onBeforeStoreUser event receives two arguments: the user object and a boolean flag indicating whether or not the user is a new one.
You can look at plugins/user/example.php to see all of the user plugin event handlers.


text:
Q: How to trigger DataGridevents DataGridBeginningEdit, DataGridCellEditEnding with a Combobox in Silverlight? / CellTemplate for a Combobox I want to use the DataGridevents (DataGridBeginningEdit, DataGridCellEditEnding, ..etc) to handle and detect changes. As far as I understood, without a "CellTemplate" these are not triggered. So I am trying to create an appropriate celltemplate using a TextBlock, but I guess it is not very straightforward with the binding I am using for the Combobox in the CellEditingTemplate, because I am using "DisplayMemberPath"..
There are examples of simpler cases but I couldn't find smth for this scenario. See Xaml snippet below;
<data:DataGridTemplateColumn Width="100">
                                    <data:DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBlock HorizontalAlignment="Center" />
                                        </DataTemplate>
                                    </data:DataGridTemplateColumn.CellTemplate>
                                    <data:DataGridTemplateColumn.CellEditingTemplate>
                                        <DataTemplate>
                                            <ComboBox HorizontalAlignment="Stretch"
                                                        ItemsSource="{Binding DurationTypeList, Source={StaticResource itemSourceProvider}}"
                                                        SelectedValuePath="Code"
                                                        SelectedValue="{Binding Path=DurationTypeCode, Mode=TwoWay}"
                                                        DisplayMemberPath="Template"  />
                                        </DataTemplate>
                                    </data:DataGridTemplateColumn.CellEditingTemplate>
                                </data:DataGridTemplateColumn>

Thank you

A: It turns out, i have two options..
Solution #1
<data:DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBlock HorizontalAlignment="Left" Text="{Binding Path=DurationType.Template,  Mode=OneWay}"  />
                                        </DataTemplate>
                                    </data:DataGridTemplateColumn.CellTemplate>
                                    <data:DataGridTemplateColumn.CellEditingTemplate>
                                        <DataTemplate>
                                            <ComboBox HorizontalAlignment="Stretch"
                                                        ItemsSource="{Binding DurationTypeList, Source={StaticResource itemSourceProvider}}"
                                                        SelectedValuePath="Code"
                                                        SelectedValue="{Binding Path=DurationType, Mode=TwoWay}"
                                                        DisplayMemberPath="Template"  />
                                        </DataTemplate>
                                    </data:DataGridTemplateColumn.CellEditingTemplate>

I changed the binding path from string to the object with Code and Template properties..
This blog helped a lot..


text: Q: Cannot find data in the content management - AWS amplify I was building the basic blog application using Amplify and I have added several posts. But there's this one post which I had added at the start, I want to delete it. But I cannot find it in content management. Where can I find it. Why is it not updated in content management.


text:
Q: How do I cure Sanguinare Vampiris? I have Sanguinare Vampiris. I don't really want to become a vampire. How can I cure myself?

A: There was a great walkthrough on how to cure Vampirism on Gamefront: due to that site's redesign, it's been lost, but here's the list, distilled:

*

*If it's within three days of becoming a vampire, you can cure the disease with a Cure Disease Potion.

*Activate any Shrine.  The Shrine of Talos outside Whiterun will do. Shrines will cure you of all diseases.

Since it sounds like you're a Stage 4 vampire, you should feed so that you're no longer stage 4. To do this:

wait until night and drink the blood of a sleeping person. Even sleeping beggars will do. Just crouch/sneak and interact with a sleeping NPC to drink their blood.
NB:  If you're still having trouble drinking blood, remember that you have two useful abilities as a Stage 4 vampires — Embrace of Shadows, and Vampire Seduction. Embrace of Shadows turns you invisible, while Vampire Seduction will make an NPC calm and cease wanting to attack you.

Once you have contracted vampirism (e.g., gone beyond Day 4), you need to do the following:

*

*Speak with any Inn Keeper or Bartender about rumors. They'll tell you that a man named Falion in Morthal is studying vampires.

*Find Morthal east of Fort Snowhawk. Once there, talk to Falion and he'll discuss how to cure vampirism.

*He'll tell you to get a Black Soul Gem. If you don't have one, Falion will sell you one. Before being cured, you'll need to fill the Black Soul Gem.

To fill a Black Soul Gem, you'll need to cast a Soul Trap spell on a human, then kill them. Any human will work, including bandits and enemies.

*

*You'll need to obtain a Soul Trap spell, sold by any magic vendor.

If you're really desperate, try the College of Winterhold, or explore Whiterun to find a shop. If you don't have high magic skills, just purchase a Soul Trap scroll. NOTE: The Mage for the Jarl of Whiterun, the Jarl's Court Mage, should have a Soul Trap spell.

With a filled Black Soul Gem, return to Falion and talk to him to complete the ritual.

A: If you're fast, you can chug a Cure Disease potion or pray at a shrine.
Once Vampirism has set in however, you only have two options:
You can become a Werewolf.
or
If you harass enough bartenders for rumors, they will tell you about a fellow named Falion in Morthal who is working on a cure. He'll want Black Soul Gems though, so it won't be cheap or easy!

A: In Dawnstar I think next to the mine there is a hidden chest (under ground) which when you look at you can open, it is FULL of goodies, which you can sell. One of them is a weapon which when you kill someone with it it actually fills the soul gem for you, a quick short cut. The vampirism is very annoying.
One other thing, when you go to be cured, make sure you have fed on blood before hand otherwise he won't cure you and will instead fight you. Best go to a farm wait to dark, take off your armour and sneek in whislt they are asleep

A: 1:try not to go to sleep or else you will transform
2:shrines and potions of cure disease can get rid of it
3:if you do transform, there is a quest in dawnstar to remove vampirism


text:
Q: Display chosen text on JavaScript button I have been searching to the internet, but could not find the right answer on this question. How could I fix a JavaScript button that display the chosen text. For example when I click on Germany. The text of this button will be changed to Language: Germany. Check photo and codes below to better understand this issue.

$(function() {
$("button").click(function(){
 $(".choose").toggle();
 });
});
<button type="button"> Language:</button>

This changes the language of the site.

 Brazil

 China

 France

 Germany

 Hong Kong

 India

 Indonesia

 Malaysia

 Netherlands

 Philippines

 Singapore

 Taiwan

A: You need a container into which to write the chosen language, so wrap a  around the word Language, and give it an ID so it is easy to select.
Then, some code like this should do the trick:
jsFiddle Demo
Updated jsFiddle Demo
Updated jsFiddle Demo
$('ul li').click(function(e){
        e.stopPropagation(); //prevent firing twice (once for li, once for ul)
        var t = $(this).data('type');
        $('#lang').text( t );
        $('.language').fadeOut();
});

A: I have finally find the answer partly due gibberish who helped me solving this issue. After a long try the final answer is:

$(function() {
$('button, li').click(function(){
 var t = $(this).data('type');
    $('#lang').text( t );
    $('.language').toggle();
 });
});
<button type="button"> Country: England</button>

This changes the language of the site.

 Brazil

 China

 England

 Germany

 Hong Kong

 India

 Indonesia

 Malaysia

 Netherlands

 Philippines

 Singapore

 Taiwan


text:
Q: how to pass tuple as function arguments Got a function that takes three arguments.
f(a, b, c) = # do stuff

And another function that returns a tuple.
g() = (1, 2, 3)

How do I pass the tuple as function arguments?
f(g()) # ERROR

A: Answer outdated as of Julia version 0.4, released in 2015:
In modern versions of Julia, use the ... operator f(g()...).

Use apply.
julia> g() = (1,2,3)
g (generic function with 1 method)

julia> f(a,b,c) = +(a,b,c)
f (generic function with 1 method)

julia> apply(f,g())
6

Let us know if this helps.

A: Using Nanashi's example, the clue is the error when you call f(g())
julia> g() = (1, 2, 3)
g (generic function with 1 method)

julia> f(a, b, c) = +(a, b, c)
f (generic function with 1 method)

julia> g()
(1,2,3)

julia> f(g())
ERROR: no method f((Int64,Int64,Int64))

This indicates that this gives the tuple (1, 2, 3) as the input to f without unpacking it.  To unpack it use an ellipsis.
julia> f(g()...)
6

The relevant section in the Julia manual is here: http://julia.readthedocs.org/en/latest/manual/functions/#varargs-functions


text:
Q: IsolatedStorage, trying to demonstrate the different isolation levels - can't for domain isolation I've edited and trimmed this to try and get it closed because the site is prompting me to accept an answer or add a bounty.
I did an experiment which had calls to GetUserStoreForAssembly and GetUserStoreForDomain in a library referenced by a console app but didn't understand why I was getting more stores than I expected in one case and less in another.
Preet helped me tune my experiment and I ended up with two slightly differnt issues:

*

*when I copied the console app to another directory (so the name remained the same), I got two user/assembly stores i.e. one per copy when I expected them to share

*when I loaded my library into multiple domains within the console app they all still used the same user/assembly/domain store when I expected them to not share
By then, the question was cold.  I did my own reading and I thought I found the answers so answered the question myself hoping someone would confirm/correct.  But it was so far down the list there was no chance.  I was just going to leave it but then got prompted to accept or add bounty.
So I've moved my answer here and now just need someone to add some helpful comment either confirming or correcting so I can accept it and know that this will actually be useful to anyone else wanting to better understand isolated storage:
Possible answer to first question:
Strong named assemblies are of course identified by their strong name. Weakly named (not sure if that's an official term but whatever) are identified by their URL or file location. So the same weakly named assmebly copied to a different directory will have it's own separate isolated store.
Possible answeranswer to second question (less certain about this one):
The scope returned by GetUserStoreForDomain is restricted to the machine, user, application and assembly, specifically that assembly running within a specific application.
My experiment created multiple additional domains but they are all in the same application. Therefore, they are all using the same domain store.
Therefore, to simulate domain isolation, I actually need to reference the library from two different console applications.
And this will only work properly if the library (and hence both console applications) are strong named. Referencing an assembly results in it being copied meaning if it's weakly named it will have a seperate isolation store.
I just tried the whole experiment out with strong naming I now get 2 domain stores and 1 assembly store as expected.

A: You can create multiple app domains in a single program/process. Inside the appdomain you can load the assembly. The call the methods in each app domain/assembly
There are examples here (appdomains) and here (AssemblyIdentity)  and here

A: You can create multiple app domains in a single program/process. Inside the appdomain you can load the assembly. The call the methods in each app domain/assembly
There are examples here


text:
Q: LDAP filter syntax to compare two object's properties I want to know if this is possible to compare two object's properties with the LDAPfilter ?
Something like (This is not working - return nothing every time): -LDAPfilter {sAMAccountName=userPrincipalName}
I tried to find a clue in this Microsoft's documentation about the LDAPfilter, but I found nothing.
Some explanations about my goal :
I want to get every user with the User logon name different than the User logon name (Pre Windows 2000).
I am using the command "Get-ADUser"
The two properties I want to compare are : "User logon name" (userPrincipalName) and "User logon name (Pre Windows 2000)" (sAMAccountName)
I don't know if this is possible with the LDAP filter, if not, is there an other way to do it ?

A: No, it's not possible with an LDAP filter. You can only compare an attribute with a value, not two attributes with each other. You need something like this for the latter:
Get-ADUser -Filter * -Properties * |
  ? { $_.SamAccountName -eq $_.UserPrincipalName }

Note that these two properties are practically guaranteed to be different, because the UPN normally includes the FQDN of the domain whereas the sAMAccountName does not. Your comparison will effectively look somewhat like this:
'user' -eq 'user@domain.example.com'

so you may want to do something like this instead:
Get-ADUser -Filter * -Properties * |
  ? { "$($_.SamAccountName)@$env:USERDNSDOMAIN" -eq $_.UserPrincipalName }


text:
Q: SQL check if data is sampled I have a database with data that has x different filters and an angle between -180 to 180. I'd like to check if a certain filter has atleast one datapoint in a range of 5 degrees. So yes or 1 if there is a datapoint between -180 and -175 for filter 1.
I've managed to count the amount of items per filter in total
'SELECT COUNT(data),filt FROM database GROUP BY filt ORDER BY filt'

This gives:
(11093, 'R1')
(24067, 'R2')
(12234, 'R3')
(4, 'RH2')
(12888, 'SIC')
(7557, 'SI')
(1570, 'SI2')
(2922, 'SI3')

But I have no idea how to take the next step

A: Here's a solution that relies on the fact that the points are always in the range -180 to +180
SELECT distinct ( (id -180) div -355) as d, filt
FROM database
WHERE ( (id -180) div -355) = 1
ORDER BY filt;

The point is that only values -175 to -180 will give d=1.


text:
Q: How to include Google Maps JS library locally and not from CDN Currently I am loading the google maps JS API from the google CDN like this in my hybrid mobile app.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry"></script>

Is there a clean, official, way to include this library locally in my resources? I cannot for exmaple find an official bower component, etc...
eg
<script type="text/javascript" src="lib/maps/api/js?libraries=places,geometry"></script>

Can I just download the JS file from the above URL and include it in the relevant folder in my web app?

A: No.  The Terms state:

10.1 Administrative Restrictions.
No access to APIs or Content except through the Service. You will not access the Maps API(s) or the Content except through the Service.
For example, you must not access map tiles or imagery through
interfaces or channels (including undocumented Google interfaces)
other than the Maps API(s).
10.5 Intellectual Property Restrictions.
No use of Content outside the Service. You will not use any Content outside of the Service
except as expressly permitted to do so in Subsection (d). For example,
you will not export or save the Content to a third party's platform or
service. No caching or storage. You will not pre-fetch, cache, index,
or store any Content to be used outside the Service, except that you
may store limited amounts of Content solely for the purpose of
improving the performance of your Maps API Implementation due to
network latency (and not for the purpose of preventing Google from
accurately tracking usage), and only if such storage:

*

*is temporary (and in no event more than 30 calendar days);

*is secure;

*does not manipulate or aggregate any part of the Content or Service; and

*does not modify attribution in any way.


text:
Q: Spring MVC binding nested list with checkboxes I have a class User which has a list of objects Roles:
   public class User{

    List<Role> roles;
    ...

Role class has following properties:
    public class Role{

    private int id;
    private String shortcut;
    private String name;
    private String description;
    ...

In my controller I have a full list of roles that I pass to the JSP file.
In JSP file I want to create a new user using form with checkboxes to the roles.
The role should be added to the list of roles if the appropriate checkbox is checked.
Following code doesn't work:
<form:form method="post" action="users/add"
name="addForm" modelAttribute="newUser">

    <c:forEach items="${listOfRoles}" var="r">
        <form:checkbox path="roles" value="${r}"
                    label="${r.name}" />
    </c:forEach>

<input type="submit" id="add" value="Add" />

I have a model attribute "newUser" that contains list of objects called "roles". After submiting the form I want to have in that list objects(checkboxes) that were checked.
Method in the controller to handle the form:
@RequestMapping(value = "/users/add", method = RequestMethod.POST)
public final String addNewUser(@ModelAttribute User newUser, final BindingResult result) {

    if (result.hasErrors()) {

    } else {
        persistence.addUser(newUser);
    }
    return "redirect:/users";
}

How can I solve it?


text:
Q: Verificar si un email existe en la base de datos: PHP y MySQL Esta es la funcion que estoy utilizando
function emailExiste($email){

    global $mysqli;

    $stmt = $mysqli->prepare("SELECT id FROM usuarios WHERE correo = ? LIMIT 1");
    $stmt->bind_param("s", $email);

    $stmt->execute();
    $stmt->store_result();
    $num = $stmt->num_rows;
    $stmt->close();

    if ($num > 0){
        return true;
        } else {
        return false;
    }
}

Pero al correlo me arroja el siguiente error:
Fatal error: Uncaught Error: Call to a member function bindparam() on bool in C:\xampp\htdocs\Mi-pagina\DBusuarios.php:62 Stack trace: #0 C:\xampp\htdocs\Mi-pagina\registrate.php(29): emailExiste('') #1 {main} thrown in C:\xampp\htdocs\Mi-pagina\DBusuarios.php on line 62

La linea 62 es el "bind_param()"
Alguien podría orientarme sobre como resolverlo? Soy muy nueva en esto, es la primera que lo hago.

A: El error: Fatal error: Uncaught Error: Call to a member function bind_param() on bool ...  está indicando que el objeto sobre el que quieres invocar a bind_param es un booleano.
Lo que ocurre en este caso es que $stmt es false (booleano) y no un objeto Prepared Statement que es lo que debería ser.
Y, ¿por qué es false? Pues porque algo ha fallado en el código. Por tanto, debes controlar todo aquello que pueda fallar, escribiendo así un programa robusto que te informará en todo momento de la situación.
Vamos a ello:
function emailExiste($email){

    global $mysqli;
    /*
     *1. Controlamos que haya conexión
    */
    if($mysqli) {
        #Para este caso es mejor usar COUNT
        $sql="SELECT COUNT(*) FROM usuarios WHERE correo = ? LIMIT 1";
        /*
         *2. Controlamos la preparación
        */
        if( $stmt = $mysqli->prepare($sql) ) {
            $stmt->bind_param("s", $email);
            $stmt->execute();
            #Se agrega el resultado de COUNT a $num
            $stmt->bind_result($num);
            $stmt->close();
            #Se puede usar operador de comparación
            $mData=array( 'msg'=>'success', 'status'=>($num > 0) );
        } else {
            $mData=array('msg'=>'Error preparando: '.$mysqli->error,'status'=>false);
        }
    } else {
        $mData=array('msg'=>'Error de conexión','status'=>false);
    }
    return $mData;
}

En la llamada del método puedes hacer un var_dump o leer la clave msg del mismo. Yo he usado para este caso un array $mData donde voy poniendo en la clave 'msg' un eventual mensaje (sobre todo para los errores) y en la clave 'status' el booleano que pudieras necesitar. Es algo que he hecho ad libitum pero que puedes modificar a tu gusto.
Si no entiendes algo puedes decirlo en comentarios.


text:
Q: how to split a wmv file im doing a application in which i split a wmv file and transfer it to otherlocation(in 'x' kbs) .after the transfer gets completed the file doesnt play,it gives a message as the format is not supported.is there anyother way to do it.
sory i will explain what im doing now
i wrote an remote application,i want to transfer a .wmv file from one machine to other,i want to split the .wmv and send it to the remote machine and use it there.if i try to send the complete file means it will take lot of memory that seems very bad.so i want to split it and send it.but the file doesnt gets played it raises an exception the format is not supported.
the following is the code im doing i just done it in the local machine itself(not remoting):
try
        {
            FileStream fswrite = new FileStream("D:\\Movie.wmv", FileMode.Create);
            int pointer = 1;
            int bufferlength = 12488;
            int RemainingLen = 0;
            int AppLen = 0;
            FileStream fst = new FileStream("E:\\Movie.wmv", FileMode.Open);
            int TotalLen = (int)fst.Length;
            fst.Close();
            while (pointer != 0)
            {
                byte[] svid = new byte[bufferlength];
                using (FileStream fst1 = new FileStream("E:\\Movie.wmv", FileMode.Open))
                {
                    pointer = fst1.Read(svid, AppLen, bufferlength);
                    fst1.Close();
                }
                fswrite.Write(svid, 0, pointer);
                AppLen += bufferlength;
                RemainingLen = TotalLen-AppLen;
                if(RemainingLen < bufferlength)
                {
                    byte[] svid1 = new byte[RemainingLen];
                    using (FileStream fst2 = new FileStream("E:\\Movie.wmv", FileMode.Open))
                    {
                        pointer = fst2.Read(svid1, 0, RemainingLen);
                        fst2.Close();
                    }
                    fswrite.Write(svid, 0, pointer);
                    break;
                }

            }

            fswrite.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

A: You'll probably find Good way to send a large file over a network in C# helpful.

A: Im going to make the assumtion your spliting the file when your sending it, and not trying to have the wmv in 3 different files on the remote machine.

When your sending the file what you basicly do is this:
Local machine
1) Read 16k bytes ( Or whatever number you prefere )
2) Send those 16k bytes over the network
3) Repeat above steps untill done

Remote machine
1) Listen for a connection
2) Get 16k bytes
3) Write 16k bytes
4) Repeat untill done.

This method will work, but your kind of inventing the wheel again, i would recommend using either something as simple as File.Copy ( Works fine over the network ) or if that does not meet your needs perhaps using a FTP client / server solution ( Plenty of C# examples on the net that can be hosted inside your application ).

A: i tried this
 private void Splitinthread()
    {
        int bufferlength = 2048;
        int pointer = 1;
        int offset = 0;
        int length = 0;
        byte[] buff = new byte[2048];
        FileStream fstwrite = new FileStream("D:\\TEST.wmv", FileMode.Create);
        FileStream fst2 = new FileStream("E:\\karthi.wmv", FileMode.Open);
        int Tot_Len = (int)fst2.Length;
        int Remain_Buff = 0;
        //Stream fst = File.OpenRead("E:\\karth.wmv");

        while (pointer != 0)
        {
            try
            {

                fst2.Read(buff, 0, bufferlength);
                fstwrite.Write(buff, 0, bufferlength);
                offset += bufferlength;
                Remain_Buff = Tot_Len - offset;
                Fileprogress.Value = CalculateProgress(offset, Tot_Len);
                if (Remain_Buff < bufferlength)
                {
                    byte[] buff1 = new byte[Remain_Buff];
                    pointer = fst2.Read(buff1, 0, Remain_Buff);
                    fstwrite.Write(buff1, 0, pointer);
                    Fileprogress.Value = CalculateProgress(offset, Tot_Len);
                    fstwrite.Close();
                    fst2.Close();
                    break;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        MessageBox.Show("Completed");
    }


text:
Q: First Child of Ancestor CSS I have an HTML structure like so:

       Words!

       Words!

I am trying to target the first occurrence of the .child class in the HTML. I have tried
.child:first-child

But that targets both child classes. I have also tried
.outter > .child:first-child

But that doesn't seem to target the div at all. Any suggestions?

A: Unfortunately, that isn't quite available in css. You can however do this:
.parent:first-child .child:first-child { //css here }

There is an assumption here that the first child element in inside the first parent element. If it isn't, and the first parent element is empty, this will target nothing.

A: You can use multiple pseudo classes (just not on the same element)
.outer .parent:first-child .child:first-child {
     //css here
}

A: You need to target it based on the parent class like so:
.outer  > .parent:first-child > .child:first-child

A: Get the first child of outer then get the first child of that parent.

A: :first-child targets the first occurence of an element within the parent.  Because both .child classes are the first child of their parents, they'll both be targeted by the css you have.
For your desired effect, use this:
.outer .parent:first-child .child:first-child

A: .parent:first-child

seems to work


text:
Q: Cloud Functions hidden after uploading to github? I have downloaded node.js, and have created the firebase-function files at the website directory (firebase.json, the functions folder and others).
If I was to write javascript cloud functions inside the project/functions/index.js file, it won't be private when I upload it to my Github repository for my static website. (something.github.io)
So how would I go about calling the firebase cloud functions in my index.js to my static website without uploading the index.js (to keep certain functions private)?
Edit:
I understand now that there are environmental variables, but how can I incorporate that with Github Pages website with firebase Admin SDK and cloud functions?
How do I upload my GitHub pages project and still link my client-side to the environmental variables? Would I need to upload my index.js containing my cloud functions? But also doesn't upload the index.js defeat the purpose of the client not being able to see the functions/data?
The comment below mentioned a software calledHeroku, what exactly is the purpose of it when I already have GitHub and firebase interacting with my website and database?
Also I saw a method of using dotenv, to create a .env file to put secret data (such as API keys) and use gitignore to prevent the file being uploaded? Would that be able to work on Github Pages, and if so, would the client be able to see the .env? And if they can't, can the client-server website link it to the .env even if it isn't pushed to Github

A: This is a good use of environment variables. Essentially, say you had an API key of 12345. And you had a function as such:
async function fetchResults() {
    await fetch("myapi.com/lookup?key=12345")
}

You could do instead:
async function fetchResults() {
    await fetch("myapi.com/lookup?key=${process.env.API_KEY}")
}

The environment variable is kept on your machine so it never goes to GitHub, hence allowing you to expose the code as open source while maintaining confidentiality of your sensitive keys.
Edit: So I reread your question and I see you're talking about publishing to GitHub pages. The key thing to note is that anything that is hosted client-side the user will be able to see. GitHub Pages only hosts the "client" portion of your application. So if your client (browser) website makes an API call to myapi.com/lookup?key=12345, they will be able to see it no matter what, since it's their browser making a request and they can see anything their browser does.
However, the best practice here is to write server-side code to run your application as well. For this, you can use what I suggested above, where you add environment variables to whichever server you use to host (for example, you can do this easily with [Zeit Now][2] or Heroku). That way, you can share your code but your environment variables stay secret on the machine that runs your server-side code.


text:
Q: Segfault when I rake (Ruby on Rails) EDIT: Here's the solution (in case the thread linked to below disappears):

*

*Install ruby 1.8.6 (down from 1.8.7)

*gem install rails -v=2.3.8 (same as before)

*gem install mysql (version 2.8.1, same as before)

*Download libmysql.dll from http://instantrails.rubyforge.org/svn/trunk/InstantRails-win/InstantRails/mysql/bin/libmySQL.dll and deposit it in Ruby186/bin.  (Before, I had copied over the libmysql.dll file from Mysql/bin.)

When I attempt rake db:migrate with the database.yml file configured for mysql (not sqlite3) I get the following segfault error:
C:/Ruby187/lib/ruby/1.8/benchmark.rb:306: [BUG] Segmentation fault
ruby 1.8.7 (2010-12-23 patchlevel 330) [i386-mingw32]
I have already looked at this thread: Ruby on Rails Rake Error and don't see any help there.***  It appears that my rails app is configured correctly because when I run rake db:create, rails successfully creates the mysql schema dictated for the development environment in database.yml (or returns a "schema already exists" message).
I'd guess I had mysql configured incorrectly, but the fact that rake db:create works on it makes me think otherwise.  I have successfully set up rails and mysql (working together) on three other machines; I don't know what the problem is on this one.
Ruby v. 1.8.7 -
Rails v. 2.3.8 -
Mysql v. 5.1.54
***The user who posted that thread indicated that he solved the problem thanks to a post on aptana.  The link to that post, however, points to the home page, so the answer thread appears to have either been moved or removed.

A: Does this describe the solution as well? http://rubyat.com/blog/2010/06/rails-2-3-8-segmentation-fault/

A: I found that the last step, using the instantrails dll, solved my problem on Win 7 x64 without my having to change ruby or rails versions.
ruby -v
ruby 1.9.2p290 (2011-07-09) [i386-mingw32]

rails -v
Rails 3.2.0

gem search mysql
mysql (2.8.1 x86-mingw32)


text:
Q: Can't access localhost with wamp and Chrome from today, when I go to localhost (http://localhost) after launch WAMP, in Firefox, as usual, everything is normal, but Chrome says "Forbidden, You don't have permission to access / on this server."
Anyone can help me please ?

A: For anyone running into this problem this is what worked for me on apache 2.4.17

*

*host file is here: C:\Windows\System32\drivers\etc

*httpd.conf is here: C:\wamp64\bin\apache\apache2.4.17\conf

*httpd-vhosts.conf is here: C:\wamp64\bin\apache\apache2.4.17\conf\extra
I made sure that localhost was enabled in my hosts file:
127.0.0.1       localhost
::1             localhost

just remove the # at the beginning of the line.
make sure this line in un-commented in your httpd.conf
Include conf/extra/httpd-vhosts.conf

In my file it was line 518.
then add this to your httpd-vhosts.conf file:
<VirtualHost *:80>
    ServerAdmin somerandomdude@whaaat.com
    DocumentRoot "c:/wamp64/www"
    ServerName localhost
</VirtualHost>

Then restart WAMP.
I don't know if that's the cleanest way of doing it(probs not). but it worked pretty well for me.

A: Edit: Solved it for me.
This is an IPv6 problem. Google must have just updated Chrome.
First of all ensure that your hosts file has the following line and that it is uncommented.
::1 localhost

Next, open up your Apache config (httpd.conf) and add the following to the listen section:
Listen [::1]:80

Next, you need to edit you Directory statements in httpd.conf or your vhosts files. They probably look something like this.
<Directory "C:\path">
    Options Indexes FollowSymLinks
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
    AllowOverride All
</Directory>

Add an extra line after the 'Allow from 127.0.0.1' so it looks like this
<Directory "C:\path">
    Options Indexes FollowSymLinks
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
    Allow from ::1
    AllowOverride All
</Directory>

A: It happens the same to me. From today I can not access with http://localhost to my wamp files with chrome.
In Firefox or Explorer I have no problems.
You can use 127.0.0.1 while the problem is solved.

A: I had the same problem. This is how I solved it out:

*

*I first added ::1 to host file,usually found at C:\Windows\System32\drivers\etc

*Then I went ahead an opened my Chrome browser. I went to settings>advanced settings>Open proxy settings (under the title system)

*In the new window that pops up go to 'LAN settings' then make sure you check 'Automatically detect settings'


text:
Q: Embedding integers in the inverse limit Let $S=(R_m,f_{mn})_{m\geq n\geq 0}$ be an inverse system of polynomial rings over the integers and unital ring homomorphisms between them. Let $R_S$ be the inverse limit of $S$ in the category Ring of rings, with the projection maps $\pi_m:R_S \to R_m$ for all $m \geq 0$. I want to show that there is an embedding of $\mathbb{Z}$ in $R_S$. I argue as follows. Let $R$ be the canonical inverse limit of $S$. That is,
\begin{equation}
R=\bigg\{(x_m)_{m \geq 0} \in \displaystyle \prod_{m \geq 0} R_m:f_{mn}(x_m)=x_n \; \forall \; m\geq n \geq 0 \bigg\},
\end{equation}
equipped with canonical projections. We have that $(k)_{m \geq 3} \in R$ for all $k \in \mathbb{Z}$ and so there is a canonical embedding $f:\mathbb{Z} \to R$ which sends $k$ to $(k)_{m \geq 0}$, which is unique (since $\mathbb{Z}$ is a cone over $S$). Now, let $u:R_S \to R$ be the unique ring isomorphism from $R_S$ to $R$. Then $g:\mathbb{Z} \to R_S$, where $g=u^{-1}f$, is a unique embedding of $\mathbb{Z}$ in $R_S.$ Is this correct?


text:
Q: Conditional Statement - check if post has an attachment image I'm working on a conditional statement (in a loop) that looks for a featured image then grabs a default image if there is none, which I have figured out. But, I also wanted a way to pull the first image (or any image) attachment before going the route of the default image.  Having trouble finding the right way to check for an attachment image, then display it.
I have added a specific thumbnail size, "featured-thumbs" in the functions.php file of my theme. It would be great if I could utilize this when displaying the attachment image.
Here's what I have so far:
<?php $count=0; if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

                        <div class="span-9 subfeature append-bottom <?php if(++$count%2==0) echo 'last'?>">

              <?php $thumb = get_the_post_thumbnail(); //Hack for Sitewide Tags Thumbnail process: assigns variable for use in conditional statement below ?>

              <?php if (has_post_thumbnail()) {

             the_post_thumbnail('thumbnail');

              } else

              if ( $thumb ) { //if not checks to see if there's a Sitewide Tags created thumbnail and uses that if there is

             the_post_thumbnail();

              } else {

               echo '';
              }

              ?>

Thanks very much.

A: I'm using this code
   <?php
    $args = array(
        'post_type' => 'attachment',
        'numberposts' => -1,
        'post_mime_type' => 'image',
        'post_status' => null,
        'post_parent' => get_the_ID(),
        'orderby' => 'menu_order',
        'order' => 'ASC',
    );
    $attachments = get_posts($args);
    if ($attachments):
            foreach($attachments as $key => $image):

                $attached_image = wp_get_attachment_metadata ( $image->ID);
                $upload_dir = wp_upload_dir();

        ?>

                    <div class="thumb <?php echo ($attached_image['sizes']['thumbnail']['width'] == "200") ? "hor" : "ver"; ?>">
                        <a href="<?php echo $upload_dir['baseurl'] . "/" . $attached_image['file']; ?>" rel="colorbox"><img src="<?php echo $upload_dir['baseurl'] . "/" . $attached_image['sizes']['thumbnail']['file']; ?>" alt="" width="<?php echo $attached_image['sizes']['thumbnail']['width'] * .6; ?>" height="<?php echo $attached_image['sizes']['thumbnail']['height'] * .6; ?>" />

        <?php endforeach; endif; ?>

A: I'm using this code below, it's quite a bit, but it basically loops through post thumbnail, attached image, image in content and then to an image per category (which is a fixed set on my site, hence the naming scheme of the images in get_post_category_image. The main usage is through the last function, simply do echo get_post_image():
function get_post_content_thumbnail($num, $width='', $height='') {
    $content = get_the_content();
    $count = substr_count($content, '<img');
    $start = 0;
    for($i=1;$i<=$count;$i++) {
        $imgBeg = strpos($content, '');
        $postOutput = substr($post, 0, $imgEnd+1);
        $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/',
                                   '',
                                   $postOutput);
        $postOutput = str_replace(array('class="alignright"', 'class="alignleft"'), '', $postOutput);
        $postOutput = preg_replace('/title="([\w-_]+)"/',
                                   '',
                                   $postOutput);
        $image[$i] = $postOutput;
        $start=$imgEnd+1;
    }

    if(isset($image) && stristr($image[$num],'<img')) {
        return str_replace('<img ', '<img ' . image_hwstring($width, $height), $image[$num]);
    }
}

function get_post_attachment_thumbnail($width='', $height='') {
    $files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
    if($files) {
        $keys = array_reverse(array_keys($files));
        $j=0;
        $attachment_id = $keys[$j];
        $image = image_downsize($attachment_id, 'thumbnail');
        $image[0] = str_replace('http://yoast.com', 'http://cdn.yoast.com', $image[0]);
        return '';
    }
}

function get_post_category_image($p_id=null, $width='', $height=''){
    global $post_id, $top_category;
    if (!$p_id)
        $p_id = $post_id;

    if ( isset($top_category) )
        return $top_category;

    $post_categories = get_the_category( $p_id );

    $slug = count($post_categories) ? $post_categories[0]->slug : '';

    if ($slug && file_exists(TEMPLATEPATH . '/img/post-img/'.$slug.'.png')){
        return 'cat_name.'"/>';
    } else {
        return '';
    }
}

function get_post_image($string_size='post-thumbnail', $width=0){
    if ( has_post_thumbnail() ) :
        return get_the_post_thumbnail(NULL, $string_size, array('title'=>''));
    elseif( $attached_image = get_post_attachment_thumbnail($width)):
        return $attached_image;
    elseif( $post_content_thumbnail = get_post_content_thumbnail(1, $width)):
        return $post_content_thumbnail;
    else:
        return get_post_category_image(NULL, $width);
    endif;
}


text:
Q: Runtime error after reportedly successful cx_Oracle install I installed cx_Oracle for Python3.4 on Windows 7 64-bit using easy_install after both the binary and pip install attempts failed for various reasons.  Upon the install, I got a seemingly success confirmation:
Installed d:\homex\sftwr\python3.4\lib\site-packages\cx_oracle-5.1.3-py3.4-win32.egg
Processing dependencies for cx-Oracle
Finished processing dependencies for cx-Oracle

However, when I tried using it in my script (import cx_Oracle), I got the following error:
Traceback (most recent call last):
  File "process_office_headcounts.py", line 5, in <module>
    import cx_Oracle
ImportError: DLL load failed: %1 is not a valid Win32 application.

What could be wrong?  I've been struggling to enable Oracle access from Python all day.


text:
Q: mysql select distinct statement (strict version?) I'm running:
MySQL
Software version: 5.5.25 - Source distribution
I have a table like this:
Region | City
-----------------
quebec | montreal
_________________
quebec | montréal

The cities are written "montreal" and "montréal" with a french accent.
When I do 'select distinct City from table where Region="quebec"' it returns only
montreal

How do I get it to return both versions of montreal (with and without é)?
montreal
montréal

In other words how do I get sql to return both french and english spelling of the same word?

A: You can try:
SELECT DISTINCT city COLLATE UTF8_BIN AS city
FROM table
WHERE Region="quebec"


text:
Q: Assigning values to an unhashable list in pandas dataframe I have a column in dataframe which contains lists. As you can see from the below image.

I want to know how can I extract all the words from this column without any duplicate words and need to iterate over the list of unique words from 0 to len(uniquewordlist) and assign a value to each word based on which iteration I'm in.
Thanks for your help.

A: This is sort of how your data is!
import pandas as pd
df = pd.DataFrame([[['kubernetes', 'client', 'bootstrapping', 'ponda']], [['micro', 'insu']], [['motor', 'upi']],[['secure', 'app', 'installation']],[['health', 'insu', 'express', 'credit', 'customer']],[['secure', 'app', 'installation']],[['aap', 'insta']],[['loan', 'house', 'loan', 'customers']]])

df.columns = ['ingredients']

print(df)

Output:
                                 ingredients
0  [kubernetes, client, bootstrapping, ponda]
1                               [micro, insu]
2                                [motor, upi]
3                 [secure, app, installation]
4   [health, insu, express, credit, customer]
5                 [secure, app, installation]
6                                [aap, insta]
7              [loan, house, loan, customers]

Here is the code to bring out a list of unique words.
for i in df.index:

    df.at[i, 'string'] = " ".join(item for item in df.at[i, 'ingredients'])

df.drop(['ingredients'], axis = 1, inplace = True)

from sklearn.feature_extraction.text import CountVectorizer

countvec = CountVectorizer()

counts = countvec.fit_transform(df['string'])

vocab = pd.DataFrame(counts.toarray())
vocab.columns = countvec.get_feature_names()

print(list(vocab.columns))

Gives
['aap', 'app', 'bootstrapping', 'client', 'credit', 'customer', 'customers', 'express', 'health', 'house', 'insta', 'installation', 'insu', 'kubernetes', 'loan', 'micro', 'motor', 'ponda', 'secure', 'upi']

You now have a list of your unique vocabulary. If you can give further context as to how you want to assign values, I can continue this answer.
Extended answer:
wordlist = list(vocab.columns)

worddict = {}

for i in range(0, len(wordlist)):

    worddict[wordlist[i]] = i

print(worddict)

A: You can use enumerate and itertools.chain within a dictionary comprehension. set ensures mappings are unique.
Data from @Abhishek.
from itertools import chain

res = {v: k for k, v in enumerate(set(chain.from_iterable(df['ingredients'])))}

print(res)

{'aap': 15,
 'app': 3,
 'bootstrapping': 1,
 ...
 'ponda': 0,
 'secure': 17,
 'upi': 5}

A: You can obtain @jpp's answer with a different one liner (works for dataframes as well):
import pandas as pd
from collections import Counter
s = pd.Series([['apple', 'orange', 'raspberry'],
               ['apple', 'cucumber', 'strawberry', 'orange']])
s.apply(Counter).sum()

Counter({'apple': 2,
     'cucumber': 1,
     'orange': 2,
     'raspberry': 1,
     'strawberry': 1})

If you use
list(s.apply(Counter).sum().keys())

you get exactly @Abhishek's answer, which is in my opinion more readable. Applying set won't work, since + is not defined for sets


text:
Q: Why won't the program include the first input from the user in the calculation of the average? This code is meant to output an average of -1 if the first value entered by the user is -1. If the value entered is not -1, then it will calculate the average of the given values, and it will stop when the value -1 is entered and it will be the stopping signal for the program. The task is to modify an existing DoWhile loop - which I have done.
Now, after having written the code, I can't seem to understand why the program isn't including the first input from the user, for the calculation of the average.
Scanner input = new Scanner(System.in);

float grade;
float sumGrades, average;
int studentCount = 0;
sumGrades = 0;

final int STOP = -1;

System.out.printf("\nEnter a grade (%d to finish): ", STOP);
grade = input.nextFloat();
if(grade == STOP)
{
      sumGrades = sumGrades + grade;
      studentCount++;
}
else
    do
    {
    System.out.printf("\nEnter a grade (%d to finish): ", STOP);
    grade = input.nextFloat();

    if(grade != STOP)
      {
      sumGrades = sumGrades + grade;
      studentCount++;
      }
    } while(grade != STOP);

average = sumGrades / studentCount;
System.out.printf("The average obtained is %.1f\n", average);

OUTPUT:
Enter a grade (-1 to finish): 2

Enter a grade (-1 to finish): 3

Enter a grade (-1 to finish): 4

Enter a grade (-1 to finish): 5

Enter a grade (-1 to finish): 2

Enter a grade (-1 to finish): 3

Enter a grade (-1 to finish): -1

The average obtained is 3.4

OUTPUT 2:
Enter a grade (-1 to finish): 2

Enter a grade (-1 to finish): -1

The average obtained is NaN

Image of Compiled Code and Run
Code

A: Look carefully at what you have written.
System.out.printf("\nEnter a grade (%d to finish): ", STOP);
grade = input.nextFloat();

OK so far
if(grade == STOP)
{
      sumGrades = sumGrades + grade;
      studentCount++;
}

So ... if the grade means "stop" ... you add it to the sum, and count?!?
else
    do
    {

But if the previous grade was NOT a stop ... you throw it away and read the next grade!?!
    System.out.printf("\nEnter a grade (%d to finish): ", STOP);
    grade = input.nextFloat();

See the problem?

A: main issiue is here:
   final int STOP = -1;

        System.out.printf("\nEnter a grade (%d to finish): ", STOP);
      grade = input.nextFloat();
if(grade == STOP)
{
      sumGrades = sumGrades + grade;
      studentCount++;
}

here you read input, and just check if its STOP, bud you do nothing with input if isnt STOP
in next
else
    do
    {
    System.out.printf("\nEnter a grade (%d to finish): ", STOP);
    grade = input.nextFloat();

you again read input and then process it if isnt STOP and you lose your first input
solution by one cycle:
do
    {
    System.out.printf("\nEnter a grade (%d to finish): ", STOP);
    grade = input.nextFloat();
        if(grade != STOP)
          {
            sumGrades = sumGrades + grade;
            studentCount++;
          }

      } while(grade != STOP);


text:
Q: How execute command on server site? I have hosted my Magento site on the server.
My question is what I do after custom changes in Magento 2 on the server.
How will I execute the command on the server?

A: You can use a client like winSCP, for example!

A: As you have got ssh, now you simply need to login to ssh and navigate to the root of magento (the directory where you have installed magento) and execute required command.
You can find reference for all magento cli commands here - http://devdocs.magento.com/guides/v2.1/config-guide/cli/config-cli-subcommands.html
Feel free to ping me if you need any other help


text:
Q: Track number of new subscribers of a Telegram channel? I am using telethon in python, and I want to try to keep track of the number o new members who join a channel over time.
My first attempt was using the telethon.tl.functions.channels.GetFullChannelRequest function:
async def save_subs(channel_id):
    client = TelegramClient('anon', TELEGRAM_API_ID, TELEGRAM_API_HASH)
    await client.start()
    async with client:
        previous_count = None
        number_new_members = 0
        while True:
            res = await client(
                GetFullChannelRequest(
                    channel=channel_id
                )
            )
            channel_info = res.to_dict()
            count = channel_info['full_chat']['participants_count']
            print(f'current count: {count}')
            if previous_count is not None and count > previous_count:
                number_new_members += count - previous_count
                print(f'new subs: {number_new_members}')
            previous_count = count
            time.sleep(1)

def start(channel_id):
    asyncio.run(save_subs())

However, it seems that every 1 second it too much, and every 4 requests there is a delay of a few seconds. Perhaps this is being rate limited?
Then I tried using the events.ChatAction event because the docs say that a new user joining a channel should trigger, but nothing is getting triggered:
def check_new_user(channel_id):
    telegram_client = TelegramClient('anon', TELEGRAM_API_ID, TELEGRAM_API_HASH)

    @telegram_client.on(events.ChatAction)
    async def my_event_handler(event):
        # this never gets printed
        print('event caught')

    telegram_client.start()
    telegram_client.run_until_disconnected()

def start(channel_id):
    check_events(channel_id)

A: Many requests to Telegram include a count, accessible via Telethon's .total attribute on the returned lists:
participants = await client.get_participants(channel, 1)
print(participants.total)

This will fetch a single participant (you must have permission to do so), and as a byproduct, Telegram fills-in the total.

A: I'd advise a more straightforward approach. You can do it using Telegram's t.me application.
DEFAULT_TIMEOUT = 10

def scrap_telegram_members_count(slug: str) -> int:
    def parse_int(s: str) -> int:
        return int(re.sub(r"[^\d]+", "", s))

    r = requests.get(
        f"https://t.me/{slug}",
        timeout=DEFAULT_TIMEOUT,
    )
    r.raise_for_status()

    text = r.text
    m = re.search(r'
([^,]+),([^<]+)
', text)
    if not m:
        raise RuntimeError("Cannot find members count")
    members_count = parse_int(m.group(1))

    return members_count

From my experience, now you can send not less than ~1k requests per day this way.


text:
Q: Rebuild javacv.jar for Android I hate to sound like a n00b but I have been trying to figure this out for several hours now and could really use some help. I have successfully been able to use FFmpeg and OpenCV in my Android app by using javacv.jar and javacpp.jar provided here. This has been working great, but there has been some changes to javacv and javacpp and I need to rebuild these for my app. I have checked out both of these repositories to my home directory. I also have opencv-2.4.4 in my home directory. I was able to compile javacpp and get a jar file by running "mvn install" in the javacpp directory. When I try to do this in my javacv directory, I get this error:
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building JavaCV
[INFO]    task-segment: [install]
[INFO] ------------------------------------------------------------------------
[INFO] [dependency:properties {execution: properties}]
[INFO] [dependency:copy-dependencies {execution: copy-dependencies}]
[INFO] javacpp-0.4.jar already exists in destination.
[INFO] [resources:resources {execution: default-resources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 9 resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [exec:exec {execution: javacpp}]
Generating source file:     /home/marwfair/javacv/target/classes/com/googlecode/javacv/cpp/jnicvkernels.cpp
Building library file: /home/marwfair/javacv/target/classes/com/googlecode/javacv/cpp/linux- x86_64/libjnicvkernels.so
g++ -I/usr/lib/jvm/java-7-openjdk-amd64/include -I/usr/lib/jvm/java-7-openjdk-amd64/include/linux  -I/usr/local/include /home/marwfair/javacv/target/classes/com/googlecode/javacv/cpp/jnicvkernels.cpp  -msse3 -ffast-math -Wl,-rpath,$ORIGIN/ -march=x86-64 -m64 -Wall -O3 -fPIC -shared -s -o   /home/marwfair/javacv/target/classes/com/googlecode/javacv/cpp/linux-x86_64/libjnicvkernels.so - L/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/amd64/jamvm -Wl,-rpath,/usr/lib/jvm/java-7-openjdk- amd64/jre/lib/amd64/jamvm -ljvm
In file included from   /home/marwfair/javacv/target/classes/com/googlecode/javacv/cpp/jnicvkernels.cpp:58:0:
/home/marwfair/javacv/target/classes/com/googlecode/javacv/cpp/cvkernels.h:22:33: fatal error:   opencv2/core/core_c.h: No such file or directory
compilation terminated.

I have read the docs for javacpp for Android and the docs for javacv. I am running Ubuntu and am pretty new to Maven. Any help would be greatly appreciated. I feel like I am really missing some key points.

A: Yeah, missed a pretty key point. I didn't have OpenCV installed on my computer. I was able to build the file after following this guide to install OpenCV.


text:
Q: Transition Between Position and Momentum Basis I'm having some trouble following pages 55-56 of Sakurai's Modern Quantum Mechanics.
We're trying to transfer from position space into momentum space. Here's a quote:

Let us now establish the connection between the $x$-representation and the $p$-representation. We recall that in the case of the discrete spectra, the change of basis from the old set $\{ | a^{'} \rangle \}$  to the new set $\{ | b^{'} \rangle \}$ is characterized by the transformation matrix (1.5.7). Likewise, we expect that the desired information is contained in $\langle x^{'} | p^{'} \rangle$, which is a function of $x^{'}$ and $p^{'}$, usually called the transformation function from the $x$-representation to the $p$-representation. To derive the explicit form of $\langle x^{'} | p^{'} \rangle$, first recall (1.7.17), letting $|\alpha \rangle$ be the momentum eigenket $|p^{'} \rangle$, we obtain $$\langle x^{'} |P|p^{'}\rangle = -i \hbar \frac{\partial}{\partial x^{'}} \langle x^{'} | p^{'}\rangle$$ or $$p'\langle x' |p^{'}\rangle = -i \hbar \frac{\partial}{\partial x^{'}} \langle x^{'} | p^{'}\rangle$$
  The solution to this differential equation for $\langle x' | p' \rangle$ is $$\langle x' | p' \rangle = N \exp \left( \frac{ip'x'}{\hbar} \right)$$

I'm not sure where our differential equation is coming from. We have our momentum operator $P$  in the position basis, acting on our eigenket $|p'\rangle$, I can't see how we can find explicitly what the inner product of the position bra $\langle x'|$ and the momentum ket $|p'\rangle$ is.
What I'm thinking now is to rearange it like so: $$\int \langle x^{'} |p^{'}\rangle dx' = \int -\frac{i\hbar}{p'} \frac{\partial}{\partial x^{'}} \langle x^{'} | p^{'}\rangle dx'$$
But it doesn't seem to lead anywhere. What am I missing?


text:
Q: DIsplaying preview image from input file The problem lies in the "this", if i change that to "#photo1", the image will be able to display.
I have a few file input and that's why I need to edit my code. I have no idea what is happening.
$(".pro-set-up-photo-preview").hide();

    $("#photo1").change(function () {
        var reader = new FileReader();

        reader.onload = function (e) {
            // get loaded data and render thumbnail.
            $(this).next().next("img").attr('src', e.target.result);
        };

        // read the image file as a data URL.
        reader.readAsDataURL(this.files[0]);
        $(this).next().next("img").show();
    });

Here is my CODE

A: The this in the nested function is referencing the FileReader object. You should save the reference to #photo1 in a local variable before the reader.onload callback:
var photo = $(this);

and then use photo instead of $(this):
reader.onload = function (e) {
    // get loaded data and render thumbnail.
    photo.next().next("img").attr('src', e.target.result);
};


text:
Q: How to interpret the minimum spanning tree in a fully-connected graph? Can someone explain how the resulting graph is the minimum spanning tree (MST) from the fully-connected undirected graph?  I don't understand how this is interpreted in this context.
Definition according to Wikipedia:

A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight.

*

*https://en.wikipedia.org/wiki/Minimum_spanning_tree
# Toy Data (Iris dataset, pearson correlation, absolute value)
d = {'sepal_length': {'sepal_length': 1.0, 'sepal_width': 0.11756978413300088, 'petal_length': 0.8717537758865838, 'petal_width': 0.8179411262715758}, 'sepal_width': {'sepal_length': 0.11756978413300088, 'sepal_width': 1.0, 'petal_length': 0.42844010433053864, 'petal_width': 0.3661259325364377}, 'petal_length': {'sepal_length': 0.8717537758865838, 'sepal_width': 0.42844010433053864, 'petal_length': 1.0, 'petal_width': 0.962865431402796}, 'petal_width': {'sepal_length': 0.8179411262715758, 'sepal_width': 0.3661259325364377, 'petal_length': 0.962865431402796, 'petal_width': 1.0}}
g = nx.from_pandas_adjacency(pd.DataFrame(d))

# Remove self-loops
g.remove_edges_from(nx.selfloop_edges(g))

# Graph
print(g.edges(data=True))
# [('sepal_length', 'sepal_width', {'weight': 0.11756978413300088}), ('sepal_length', 'petal_length', {'weight': 0.8717537758865838}), ('sepal_length', 'petal_width', {'weight': 0.8179411262715758}), ('sepal_width', 'petal_length', {'weight': 0.42844010433053864}), ('sepal_width', 'petal_width', {'weight': 0.3661259325364377}), ('petal_length', 'petal_width', {'weight': 0.962865431402796})]

# MST
g_mst = nx.minimum_spanning_tree(g)
print(g_mst.edges(data=True))
# [('sepal_length', 'sepal_width', {'weight': 0.11756978413300088}), ('sepal_width', 'petal_width', {'weight': 0.3661259325364377}), ('sepal_width', 'petal_length', {'weight': 0.42844010433053864})]

A: In this graph, the minimum spanning tree will have three edges (to connect to all vertices without loops). A tree with four edges will not be possible, because it would lead to a loop. A tree with two edges will also not be possible, because it would not connect to all vertices.
Therefore, to find the MST, you have to compare the total weight of all trees with three edges and find the minimum.

Let's look at all possiblities (with rounded numbers):

*

*sepal_width -- petal_length (0.4284) , sepal_width -- petal_width (0.3661) , sepal_width -- sepal_length (0.1176) = 0.9121

*sepal_width -- petal_width (0.3661) , petal_width -- petal_length (0.9629) , petal_width -- sepal_length (0.8179) = 2.1469

*petal_width -- sepal_length (0.8179), sepal_width -- sepal_length (0.1176) , petal_length -- sepal_length (0.8718) = 1.8073

*petal_width -- petal_length (0.9629) , sepal_width -- petal_length (0.4284), petal_length -- sepal_length (0.8718) = 2.2631

*sepal_width -- petal_length (0.4284) , sepal_width -- petal_width (0.3661) , petal_width -- sepal_length (0.8179) = 1.6124

*sepal_width -- petal_width (0.3661) , petal_width -- sepal_length (0.8179) , petal_length -- sepal_length (0.8718) = 2.0558

*petal_width -- sepal_length (0.8179) , petal_length -- sepal_length (0.8718) , sepal_width -- petal_length (0.4284) = 2.1181

*petal_length -- sepal_length (0.8718) , sepal_width -- petal_length (0.4284) , sepal_width -- petal_width (0.3661) = 1.6663

*petal_length -- sepal_width (0.4284), sepal_width -- sepal_length (0.1176), sepal_length -- petal_width (0.8179) = 1.3639

*petal_length -- sepal_width (0.4284), sepal_width -- sepal_length (0.1176), petal_length -- petal_width (0.9629) = 1.5089

*petal_width -- sepal_length (0.8179), sepal_width -- sepal_length (0.1176), petal_length -- petal_width (0.9629) = 1.8984

*petal_length -- sepal_length (0.8718), sepal_width -- sepal_length (0.1176), petal_length -- petal_width (0.9629) = 1.9523

*sepal_width -- petal_width (0.3661), sepal_width -- sepal_length (0.1176), petal_length -- petal_width (0.9629) = 1.4466

*sepal_width -- petal_width (0.3661), petal_length -- sepal_length (0.8718), petal_length -- petal_width (0.9629) = 2.2008

*sepal_width -- petal_width (0.3661), petal_length -- sepal_length (0.8718), sepal_width -- sepal_length (0.1176) = 1.3555

*sepal_width -- petal_length (0.4284), petal_length -- petal_width (0.9629), sepal_length -- petal_width (0.8179) = 2.2092
The smallest weight of 0.9121 is achieved for the first combination. I.e., this is the tree with the smallest sum over its edges connecting to all vertices.


text:
Q: MySQL intermediary table error code 1005 (150) can't create foreign key I have two tables which i want to join with an intermediary table for a many to many relationship
the first table is booking
CREATE TABLE booking (
    bookingID INT NOT NULL AUTO_INCREMENT,
    customerID INT,
    runID INT,
    startDate DATE,
    endDate DATE,
    dateBookedOn  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (bookingID),
    INDEX idx_start (startDate),
    INDEX idx_end (endDate),
    FOREIGN KEY (runID) REFERENCES Run(RunID),
    FOREIGN KEY (customerID) REFERENCES customer(CustomerID));

the second is dog
CREATE TABLE dog(
    DogID int(6) NOT NULL,
    DogName varchar(15),
    medicalID int (6),
    Gender character(1) check(gender in ('m', 'f')),
    Age int(2),
    Breed varchar(15),
    size character (1) check(size in ('s', 'm', 'l')),
    primary key (DogID));

and the intermediary table is as follows which gives an error 1005(150) there is something wrong with the foreign key for bookingID. But can't see the problem. any help is welcomed.
CREATE TABLE isBooked(
    BookingID int not null,
    DogID int not null,
    foreign key (DogID) references Dog(dogID),
    foreign key (BookingID) references Booking(BookingID));


text:
Q: Bootstrap range slider combine onchange function instead of repeating the onchange function? I want to minimize my code I want to avoid repeating code on onchange can anyone help me to shorten my code?
$(document).ready(function(){

var realValues = [10, 20, 30, 40, 50];
var labelValues = ['10', '20', '30', '40', '50' ];

var realValues2 = [0, 8, 16, 24];
var labelValuesTwo = ['0', '8', '16', '24'];

var trueValue1 = 40;
var trueValue2 = 10;

var ex1 = $('#ex1').slider({
value : 0,

max: 4,

min: 0,

step: 1,

formatter: function(val) {
return labelValues[val];
}
});

$('#ex1').on('change', function(data){
var uno = $("#valOne").val(realValues[data.value.newValue]);
var valOne =  $("#valOne").val();
var valTwo =  $("#valTwo").val();
var totalValues =  parseInt(valTwo) * trueValue1;
var totalValues2 =  parseInt(valOne) * trueValue2;
var total = valOne + realValues2[data.value.newValue];
var totalAllin = parseInt(totalValues2) +  parseInt(totalValues);
$("#ex6SliderVal2").text(total);
$("#SumAll").text(totalAllin + '' +' MB');
$("#TotalAll").val(totalAllin);
$("#trueValue1").text(totalValues + '' + ' MB');
$("#trueValue2").text(totalValues2 + '' + ' MB');
});

var ex2 = $('#ex2').slider({
value : 0,
max: 3,
min: 0,
step: 1,
formatter: function(val) {
return labelValuesTwo[val];
}
});

$('#ex2').on('change', function(data){
var dos = $("#valTwo").val(realValues2[data.value.newValue]);
var valOne =  $("#valOne").val();
var valTwo =  $("#valTwo").val();
var totalValues =  parseInt(valTwo) * trueValue1;
var totalValues2 =  parseInt(valOne) * trueValue2;
var total = valOne + realValues2[data.value.newValue];
var totalAllin = parseInt(totalValues2) + parseInt(totalValues);
$("#ex6SliderVal2").text(total);
$("#SumAll").text(totalAllin + '' + ' MB');
$("#TotalAll").val(totalAllin);
$("#trueValue1").text(totalValues + '' + ' MB');
$("#trueValue2").text(totalValues2 + '' + ' MB');
});
})

A: Abstract the common callback functions into a single function. After the first lines, all other lines appear identical:
function updateTotals(data) {
    var valOne = $("#valOne").val();
    var valTwo = $("#valTwo").val();
    var totalBrowse = parseInt(valTwo) * webBrowse;
    var totalEmail = parseInt(valOne) * emailValue;
    var total = valOne + realValues2[data.value.newValue];
    var totalData = parseInt(totalEmail) + parseInt(totalBrowse);
    $("#ex6SliderVal2").text(total);
    $("#TheSumMB").text(totalData + '' + ' MB');
    $("#TotalAllocation").val(totalData);
    $("#webBrowse").text(totalBrowse + '' + ' MB');
    $("#emailValue").text(totalEmail + '' + ' MB');
}

Then reference that callback function when binding to the change event:
$(ex1).change(function(data) {
    $("#valOne").val(realValues[data.value.newValue]);
    updateTotals(data);
});
$(ex2).change(function(data) {
    $("#valTwo").val(realValues2[data.value.newValue]);
    updateTotals(data);
});

See this in action below, where the formatter function has also been abstracted into a common function (i.e. formatterFunction). It can be noted that 10 is passed as the second parameter to parseInt, as it is good practice in case the number parsed begins with a 0 (see the parseInt() description for more information).

var webBrowse = 40;
var emailValue = 1;
var realValues = [10, 20, 30, 40, 50];
var labelValues = ['10 MB', '20 MB', '30 MB', '40 MB', '50 MB'];
var realValues2 = [0, 8, 16, 24];
var labelValuesTwo = ['LOW', 'LOW', 'MEDIUM', 'HIGH'];
$(document).ready(function() {//wait until the DOM is ready before creating sliders
  var ex1 = $('#ex1').slider({
    value: 0,
    max: 4,
    min: 0,
    step: 1,
    formatter: formatterFunction
  });
  var ex2 = $('#ex2').slider({
    value: 0,
    max: 3,
    min: 0,
    step: 1,
    formatter: formatterFunction
  });

  $(ex1).change(function(data) {
    $("#valOne").val(realValues[data.value.newValue]);
    updateTotals(data);
  });

  $(ex2).change(function(data) {
    $("#valTwo").val(realValues2[data.value.newValue]);
    updateTotals(data);
  });
});
//abstract out this function from the two change callback functions
function updateTotals(data) {
  var valOne = $("#valOne").val();
  var valTwo = $("#valTwo").val();
  var totalBrowse = parseInt(valTwo, 10) * webBrowse;
  var totalEmail = parseInt(valOne, 10) * emailValue;
  var total = valOne + realValues2[data.value.newValue];
  var totalData = parseInt(totalEmail, 10) + parseInt(totalBrowse, 10);
  $("#ex6SliderVal2").text(total);
  $("#TheSumMB").text(totalData + '' + ' MB');
  $("#TotalAllocation").val(totalData);
  $("#webBrowse").text(totalBrowse + '' + ' MB');
  $("#emailValue").text(totalEmail + '' + ' MB');
}

function formatterFunction(val) {
  return labelValues[val];
}
.slider.slider-horizontal {
  width: 100% !important;
  height: 20px;
}
input[disabled] {
  text-align: right;
  cursor: default;
  width: 30%;
  border: 0px;
  background: transparent;
}
.tright {
  text-align: right;
}
.slideSmoth .slider-handle.round {
  border-radius: 50%;
  transition: [transition-property] [transition-duration] [transition-timing-function] [transition-delay];
  transition: all 0.5s ease;
}
.slideSmoth .slider.slider-horizontal .slider-track {
  height: 15px;
  -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
  box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
}
.slideSmoth .slider-track,
.slideSmoth .slider-handle,
.slider-selection.tick-slider-selection {
  background: rgba(251, 251, 251, 0.8);
}
.slideSmoth .slider-handle {
  margin-top: -3px !important;
}
.slideSmoth .slider-tick {
  display: none;
}
#TotalAllocation {
  width: 200px;
  font-size: 50px;
  display: none;
}
#TheSumMB {
  width: 200px;
  font-size: 50px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.0/css/bootstrap-slider.min.css" rel="stylesheet" />

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

      <input type="text" id="TotalAllocation" class="TotalAllocation" value="0" disabled/>
       0 MB

Internet

            <input class="valTwo" disabled id="valTwo" type="text" value="0">hr / 0

            <input data-slider-id='ex1Slider2' id="ex2" type="text">

Emails

            <input class="valOne" disabled id="valOne" type="text" value="0">hr / 0

            <input data-slider-id='ex1Slider' id="ex1" type="text">


text:
Q: How to connect to Sql Anywhere 9 from C# I have a project in which I need to get data a Database that is on Sql Anywhere v9, searching in Google I cant find to much information because its an old version(and I/the client cant upgrade the version of the database), in the few documents that I could find mention a .Net Driver but the links are broken. Anyone know if this Driver is the only way Or if there is another way to connect?

A: Have you tried creating an ODBC connection and talking to the database via ODBC?
ODBC Tutorial

A: Download and install any version of SQL Anywhere Developer Edition even if it's a newer version.  They are free.  This will contain all the .NET data providers and drivers.  In my experience newer versions of the Sybase client can connect to older DB Servers.
You then have to make sure you get the connection string right to connect with C#.

A: I'm using C# to connect to a version 10 server, here is the connection string I found that works for me:
Provider=SAOLEDB;LINKS=tcpip(host=1.2.3.4,PORT=123;DoBroadcast=None);ServerName=SQLANYWHERE9;Integrated Security = True; User ID = database; PWD = password