text:
Q: How to recursively add after increasing index? I'm currently working on a homework assignment and the goal is to only do this recursively (no loops). I am pretty sure I can overload and add helper methods, that's the only way I can see myself finishing this.
So the problem is, I have an int array A = {1,2,3,4} (or something like that) and I need to make a returned array with {10,9,7,4}

10 = 1+2+3+4
9 = 2+3+4
7 = 3+4
4 = 4

I thought of using something like this (not working code)
int counter = 0;
public int[] r(int[] numbers){
    return r(number, counter);
}

public int[] r(int[] numbers, int index){
    int sum = 0;
    // base case to check if next value exists otherwise end it

    // this would be a helper method instead of a for loop
    for(int x=index; x<numbers.length; x++){
        sum += numbers[x];
    }

    numbers[index] = sum;
    index++;
    return r(numbers, index);
}

However, I'm not sure how to go about it. It is also my first week with recursion so it is kind of confusing for me. I get the right array but I have an ArrayIndexOutOfBoundsException on numbers[index] = sum and on my return statement return r(numbers, index) and I'm not sure how to fix it. Any thoughts?

A: You need a stop condition, and a way to retrieve the array afterwards
public int sum(int old, int[] numbers, int index) {
    if (index == numbers.length) return old;
    return sum(numbers[index] + old, numbers, index + 1);
}

public int[] r(int[] numbers, int[] output, int count) {
    if (count == numbers.length) {
        return output;
    } else {
        output[count] = sum(0, numbers, 0);
        return r(numbers, output, count + 1);
    }
}

public int[] r(int[] numbers) {
    return r(numbers, new int[numbers.length], 0);
}

EDIT: Changed code to remove the need of a for loop

A: I think this will give you the right answer:
public static int[] slideAndSumArrayElements(int[] array, int[] result, int index) {
    // base case - stop when the index is same as the array.length
    if (index == array.length) {
        return result;
    }
    else {
        // Add all elements of the array starting from the index position till length of the array and store the result in result[index]
        result[index] = addArrayElementsRecursively(array, index);

        // slide the main array by incrementing the index
        return slideAndSumArrayElements(array, result, index + 1);
    }
}

public static int addArrayElementsRecursively(int[] arr, int index){
    // base case - when the index is same as the original array len stop
    if (arr.length == index){
        return 0;
    }

    // add progressively each element of the given array
    return arr[index] + addArrayElementsRecursively(arr, index + 1);
}

public static void arraySum(){
    int[] array = {1, 2, 3, 4};
    int[] result = new int[array.length];

    result = slideAndSumArrayElements(array, result, 0);
}

Output array or result will be:
    [10, 9, 7, 4]

A: Your function is incorect
public int[] r(int[] numbers, int index){

    //--> needs a stop condition e.g. index==numbers.length, index==0

    int sum = 0;
    // base case to check if next value exists otherwise end it

    // this would be a helper method instead of a for loop
    for(int x=index; x<numbers.length; x++){
        //--> numbers has been overwritten by the sum
        // you should just do numbers[index] = numbers[index-1]+numbers[index]
        // this is opposite to the summation you wish for which starts adding
        // from the last position
        sum += numbers[x];
    }

    numbers[index] = sum;
    index++;
    return r(numbers, index);
}

A correct solution of your function would be
public int[] r(int[] numbers, int index){

    if (index == 0) {
          return numbers;
    }else{
        numbers[index] = numbers[index+1] + numbers[index]
        return r(numbers,index-1);
    }

    public int[] r(int[] numbers){
        return r(numbers, numbers.length);
    }

But you lose the initial array since you overwrite it
OR
You can build a function like this
public int sumRecursive(int[] input, int[] output,int pos){
    if (pos==0){
        output[pos] = input[pos]
        return input[pos]
    }else{
        output[pos] = input[pos] + sumRecursive(input,output,pos-1);
        return output[pos];
     }
}

And you need to call it like this
int[] output = new int[input.length];
sumRecursive(input,output,input.length);


text:
Q: Message not delivering when sending MFMessage to more than 15 numbers I'm trying to use MFMessage to send a text message from my app and I can send the message to around 15 people, but more than that, it successfully que's but the Messages app on the device says the text is not deliverable. There's not much information given to why it fails, it just does. Is there something different I should be doing, or a reason this would be happening?
Here's how I'm sending the message currently:
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            if(thread.smsMembers.count>0)
            {
                if(![MFMessageComposeViewController canSendText]) {
                    UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Your device doesn't support SMS!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [warningAlert show];
                    return;
                }
                    NSString *message = text;

                    self.messageController = [[MFMessageComposeViewController alloc] init];
                    [_messageController setMessageComposeDelegate:self];
                    [_messageController setRecipients:thread.smsMembers];
                    if(!type){
                        [_messageController setBody:message];
                    } else{
                        if([type isEqual: @"image"]){
                            NSData *imageData = [file getData];
                            [_messageController addAttachmentData:imageData typeIdentifier:(NSString *)kUTTypePNG filename:@"image.png"];
                        } else if([type isEqual: @"video"]){
                            NSData *videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:file.url]];
                            [_messageController addAttachmentData:videoData typeIdentifier:(NSString *)kUTTypeMovie filename:@"video.mov"];
                        }

                    }
                    [self presentViewController:_messageController animated:YES completion:nil];
            }
        });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invoke or BeginInvoke cannot be called Error when I never use Invoke or BeginInvoke I'm new to C# and async programming so the solution to the problem I have might be simple (or not?!).
Here is the issue:

*

*I have an onClick function that create a new UIControl and add it to the current Form as a new tab.

*I had it run synchronously first and had no crash but the UI was blocked for a few second as the data provided to this Tab require a lots of calculations.

*I moved the onclick to async and added an await on the Control's datprocessing function but I now get the infamous:

"Invoke or BeginInvoke cannot be called on a control until the window handle has been created".

private async void btnNewTab_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = true;
            openFileDialog.Filter = "*.test";
            DialogResult dialogResult = openFileDialog.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                //Display a basic loading Control while the other control is being prepared
                TabPage myTabPage = new TabPage("loading");
                LoadingControlPanel loadingPanel = new LoadingControlPanel();
                loadingPanel.Dock = DockStyle.Fill;
                myTabPage.Controls.Add(loadingPanel);
                tabControl.TabPages.Add(myTabPage);
                tabControl.SelectTab(myTabPage);

                //Load Data from files
                List<DataFile> result = await Task.Run(() => loadFiles(openFileDialog.FileNames));

                // create Control to display the data loaded
                MyTabControl newPanel = new MyTabControl();
                newPanel.Dock = DockStyle.Fill;

                // provide Data to new control (long processing)
                await Task.Run(() => newPanel.processData(result));

                // rename Tab, remove loading Control and display the tab with the processed Data
                myTabPage.Text = "Loaded";
                myTabPage.Controls.Remove(loadingPanel);
                myTabPage.Controls.Add(newPanel);
            }
        }

The crash always happen while I call the function "processData" but not alway at the same location. I have a few debug lines and they are not always the same processed.
The crash tells me the issue in on the line: "Application.Run(new FormMain());"
static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain());
        }

Here is the full stack trace:

System.Reflection.TargetInvocationException   HResult=0x80131604
Message=Exception has been thrown by the target of an invocation.
Source=System.Private.CoreLib   StackTrace:    at
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Delegate.DynamicInvokeImpl(Object[] args)    at
System.Delegate.DynamicInvoke(Object[] args)    at
System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry
tme)    at
System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)    at
System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry
tme)    at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(Message& m)    at
System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, WM msg,
IntPtr wparam, IntPtr lparam)    at
Interop.User32.DispatchMessageW(MSG& msg)    at
System.Windows.Forms.Application.ComponentManager.Interop.Mso.IMsoComponentManager.FPushMessageLoop(UIntPtr
dwComponentID, msoloop uReason, Void* pvLoopData)    at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(msoloop
reason, ApplicationContext context)    at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(msoloop
reason, ApplicationContext context)    at
System.Windows.Forms.Application.Run(Form mainForm)    at
Program.Main() in
Program.cs:line
22
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1: InvalidOperationException: Invoke or BeginInvoke
cannot be called on a control until the window handle has been
created.

What on earth am I doing wrong with all this?

A: The problem is Task.Run(() => newPanel.processData(result)), that could only work when processData() didn't touch any UI stuff (but then why would it be part of a panel?)
You can only use Task.Run() on processing stuff and then load the results in the UI on the main thread.
See if you can make it look like:
//await Task.Run(() => newPanel.processData(result));
var data = await Task.Run(() => ProcessData(result));
newPanel.AcceptData(data);

LoadData and ProcessData() should preferably be part of some service class, not your Form. But that is about architecture, not about the direct problem.

A: This code here
TabControl newPanel = new TabControl();
newPanel.Dock = DockStyle.Fill;

// provide Data to new control (long processing)
await Task.Run(() => newPanel.processData(result));

attempts to create a new TabControl, but never shows it, therefore it never has a window handle associated. This is completely independent of whether you do your data processing synchronously or asynchronously.
You seem to be missing some relevant code there as well, as System.Windows.Forms.TabControl does not have a processData method.

A: The heart of the issue I had is that creating a Control will not automatically ensure the handler connected to it is created.
I changed my code to display the panel first (with a loading message) while the data is processed and displayed asynchronously.
As pointed by @Henk Holterman, the architecture can/should be changed and improved to avoid the need for this solution.


text:
Q: Equation for probability amplitude of a free particle given a mean position, a mean velocity, and the mass of the free particle? The uncertainty principle can be expressed using the equation $\sigma_x\sigma_p\geq\frac{h}{4\pi}$ with $\sigma_x$ being the uncertainty in position, $\sigma_p$ being the uncertainty in momentum, and $h$ being the plank constant.  The uncertainty in velocity would be given by the equation $\sigma_v=\frac{\sigma_p}{m}$ with $\sigma_v$ being the uncertainty in velocity and $m$ being the mass.  So the uncertainty principle could also be expressed using the equation $\frac{\sigma_x\sigma_v}{m}\geq\frac{h}{4\pi}$.
Assuming that both the uncertainty in position and uncertainty in momentum are both at a minimum what is the equation for the probability amplitude of a free particle at a chosen position and momentum, given the mean position, and mean momentum of that particle?

A: A usual definition of the wavefunction of a free particle is simply $\psi(x) = \exp(-ikx)$. This of course corresponds to a particle with definite momentum that is infinitely 'smeared out' in space ($\delta p = 0$, $\delta x = \infty$). I assume you're asking about the wavefunction of a free particle with the constraint that it's localized in space. A unique localized particle wavefunction does not exist because it depends on how you write down your Hamiltonian. You can get for instance a 'wave packet'-like wavefunction, defined as (in 1D):
$$
 \Psi(x,t) = \left({a \over a + i\hbar t/m}\right)^{3/2} e^{- {x^2\over 2(a + i\hbar t/m)} }.
$$
Which gives a Gaussian wave packet, with width $a$.


text:
Q: What is the best approach to embed mp4 for the iPhone without using JavaScript? I am trying to troubleshoot this code and am running into a dead-end, so I thought I would ask my first question here. I have three questions:
1) What is the best approach to embed an mp4 for an iPhone specific view, preferably without using Javascript?
2) Are there any preferred practices to debug code on an iPhone?
3) Can anyone tell me what is wrong with my specific code below? I should mention upfront that the variable $fileName does indeed contain the correct info, I've just omitted that portion of the code. Also, the poster image does flicker for a brief moment before I receive the greyed out, broken QuickTime image so that is an indication that this is partially working.

Code:
<object width="448" height="335" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab">
    <param name="src" value="/libraries/images/$fileName.jpg" />
    <param name="href" value="/libraries/media/$fileName.mp4" />
    <param name="target" value="myself" />
    <param name="controller" value="true" />
    <param name="autoplay" value="false" />
    <param name="scale" value="aspect" />
    <embed src="/libraries/images/$fileName.jpg" href="/libraries/media/$fileName.mp4" type="video/mp4" target="myself" width="448" height="335" scale="aspect" controller="false" autoplay="false"> </embed>
</object>

A: You don't embed it, you link to it. Usually, the link is a thumbnail from the video itself. iPhones don't support embedding of movie files directly in a site.
Clicking the link will open Quicktime on the user's iPhone, then return them to the web page when they're done.
Even if embed works, a linked image is going to be easier to remember:

A: Starting with OS 3.0 you can use the <VIDEO> tag

A: Despite a common misconception, you can use a second object tag instead of the embed tag, while changing the parameters to  elements and using type="video/quicktime". The result will be the same on practically all browsers (I have yet to see a problem, although I am told IE6 screws it up), and the page will validate. The result on iPhone will be a little different than on desktop browsers. Unless you explicitly set a poster frame, it will use a black one. It will also put it's own play button on top of the poster frame. (if anyone knows how to disable either of those, I would love to know how) By doing this, you can do the whole thing without any Javascript at all. If you want to see an example, here one is: http://www.cdjunior.com/CD_JR/view.php?name=jehovahs_witnesses. The relevent part of the source is lines 94-100. I don't know if you can use an embed tag and make it work. Now that I think of it, I think this may be how the Apple Javascript does it.

A: Here's an implementation of what AlBeebe mentioned (HTML 5 video tag).
This will take an mp4 and embed it inside an iPhone frame without JS. However, you will probably run into resizing problems, so set a min-width: 758px; for your body.
Adjust with the video coordinates if things are misaligned.
HTML

      <video src='img/cloud.mp4' autoplay loop width="209" height="370" poster="img/first-frame.png"/>

CSS
#phone {
   position: relative;
}
#phone img {
   width: 300px;
   height: auto;
}
#phone video {
   position: absolute;
   width: 209px;
   height: 370px;
   top: 50%;
   left: 50%;
   margin-left: -182px;
   margin-top: -185px;
}


text:
Q: Write transit time equation in python code
I'm trying to write down the equation above in python code, already using math library to calculate cos.
I tried the following code, but it gave me the error: "TypeError: 'float' object is not callable"
def tempo_transito(periodo, raio_estrela, semieixo, raio_planeta, inclinacao):
    tempo = (periodo/sci.pi)*math.asin((raio_estrela/semieixo)*(((((1-(raio_planeta/raio_estrela))**2) - ((semieixo)/(raio_estrela*math.cos(math.radians(inclinacao))))**2))(1-(math.cos(math.radians(inclinacao)))**2))**(1/2))
    return tempo

when the fuction is called, gives the error
If anyone could write it down, sure would be enough, or point my error in the code


text:
Q: How to retrieve language specific movies using YouTube API? I need to retrieve only english videos from the YouTube but I've found the api is pretty inaccurate.
code.google.com/apis/youtube/2.0/developers_guide_protocol.html#lrsp (sorry, max 2 links for me)

In a video search request, the lr parameter restricts the search to videos that have a
title, description or keywords in a specific language. This parameter can be used when
requesting any video feeds other than standard feeds.
In a request to retrieve a list of the caption tracks available for a video, the lr
parameter filters the list of caption tracks to only include the specified language.
Valid values for the lr parameter are ISO 639-1 two-letter language codes. You can also
use the values zh-Hans for simplified Chinese and zh-Hant for traditional Chinese.

So I'm trying the following URL ("fotel" is a polish word):
http://gdata.youtube.com/feeds/api/videos?q=fotel&orderby=published&start-index=11&max-results=10&v=2&lr=en
and get lots of non-english results
but with the "ca" (catalonian):
http://gdata.youtube.com/feeds/api/videos?q=fotel&orderby=published&start-index=11&max-results=10&v=2&lr=ca
none result is returned.
Any ideas how can I get only english results? I can of course check the language on my own after retrieving the feed, but youtube api limits the NB of retrieved results to 1000 and I don't want to lose any.


text:
Q: Difference between Capistrano and Jenkins I can deploy JAVA web applications using both Jenkins and Capistrano. If my CI tool is Jenkins which has plug ins for remote deployments, why should I use Capistrano for deployment? I want to know about pros and cons of both Jenkins and Capistrano.

A: Capistrano gives you ability to deploy to servers outside of your CI system. CI/CD best practices recommends deploying build that has passed tests so adding a step to deploy green build is good practice.
Having said that there are times when you might need to do some ad hoc deployments, this is where tool like Capistrano helps.
I would suggest configure Jenkins to run cap commands for deployment instead of using jenkins plugins. This would give you ability to run deploy from both command line and CI.


text:
Q: Why is this query slow, it seems simple I have a very typical table of user information for my application, with an average set of columns (ints, varchars, etc).
In this table are two varchar(100) fields:  emailAddress and emailAddress2.
I'm extremely perplexed at why one of my queries is so slow (5+ seconds) and in testing some alternates they are so fast (<= 0.02 seconds).
This query is fast (matching on emailAddress field):
SELECT u.userId
FROM user AS u
WHERE u.isActive=1
AND u.emailAddress = 'user@domain.com'

This query is also fast (matching on emailAddress2 field):
SELECT u.userId
FROM user AS u
WHERE u.isActive=1
AND u.emailAddress2 = 'user@domain.com'

This query is NOT fast (matching on either emailAddress or emailAddress2 field):
SELECT u.userId
FROM user AS u
WHERE u.isActive=1
AND (u.emailAddress = 'user@domain.com' OR u.emailAddress2 = 'user@domain.com')

I have 2 indexes, each on the emailAddress and emailAddress2 field.
(EDIT) Here is the EXPLAIN output:
id                   1
select_type          SIMPLE
table                u
type                 ref
possible_keys        active,emailAddress,emailAddress2
key                  active
key_len              1
ref                  const
rows                 166808
Extra                Using where

Any idea why the 3rd query above is so slow? Suggestions for doing it another way? I need to match on a handful of fields and then get all users EXCEPT ones where their email address is in emailAddress or emailAddress2 (the queries above are simplified for my post).
This is driving me crazy! (and negatively affecting my app's performance).
Thanks

A: The query is slow because first, this query has an OR condition which cannot be optimized with a single index (while conditions with only AND can) and second, because besides the emails, it has to check the isActive=1 condition. So it prefers to do a table scan. The other possible path would be to use both email indexes with the Index Merge Union Access Algorithm but for some reason the optimizer does not choose this plan.
One solution would be to alter the two indexes you have, appending the isActive column at the end:
ALTER TABLE user
  DROP INDEX the_name_of_the existing_index,
  DROP INDEX the_name_of_the_other_index,
  ADD INDEX emailAddress_isActive_IX
    (emailAddress, isActive),
  ADD INDEX emailAddress2_isActive_IX
    (emailAddress2, isActive) ;

If it still slow (and/or does not do an index merge but prefers the table scan), you could try to rewrite the query with UNION:
SELECT u.userId
FROM user AS u
WHERE u.isActive=1
AND u.emailAddress = 'user@domain.com'

UNION

SELECT u.userId
FROM user AS u
WHERE u.isActive=1
AND u.emailAddress2 = 'user@domain.com' ;

Another option - without necessarily adding/altering indexes - is to nest the query into 2 layers, keeping only the email conditions in the internal layer, essentially forcing MySQL to consider using index-merge with the two available indexes:
SELECT userId
FROM
    ( SELECT userId, isActive
      FROM user AS u
      WHERE emailAddress = 'user@domain.com'
         OR emailAddress2 = 'user@domain.com'
    ) x
WHERE isActive=1 ;


text:
Q: Regular expression validation in Javascript I am looking to validate an input text against the following pattern in JS/JQuery: <some_string>:<some_string>.
Examples:

*

*A110:B120

*AB12C:B123
I know this might be too naive, but appreciate any help here.

A: You could use this:
^[A-Z0-9]+:[A-Z0-9]+$

That will match your examples and any other that has at least 1 character in each side and only has upper case letters and numbers.
You can refer to this answer in order to know how to test a regex against a string.

A: Try this
"A110:B120 AB12C:B123".match(/(\w+:\w+)/);

MATCH
1.  `A110:B120`
2.  `AB12C:B123`

or
"A110:B120".match(/(\w+)+:+(\w+)/);

MATCH
1.  A110
2.  B120


text:
Q: What is the convergence order of the numerical formula? $\int_0^2 e^x \cos (x) \sin (x) dx$,
What is the convergence order of the numerical formula?
I am confusing the question.
Do I have to use Trapezoidal rule or simpson rule or approximation rule?
If so then how to use approximation and finding order of convergence?
Help me

A: If you want to use a numerical method like the trapezoidal rule, based on a decomposition $0=x_0, x_1, \cdots, x_n=2$ of equally space points (spacing $h$), you just need to compute
$$
\frac h2 \left(f(x_0)  + f(x_n) + 2 \sum_{i=1}^{n-1} f(x_i) \right),
$$
where $f(x)=\sin x \cos x e^x$. Regarding the order of convergence, you have that the absolute error is given by
$$
\left|\frac{(b-a) h^2}{12} f''(\xi)\right|, \quad \xi \in [0,2]
$$
so, if the second derivative of $f$ is bounded (which is the case) the error will behave like $h^2$.

A: You can do this integral by doing integration by parts twice with $\cos x \sin x = \frac{1}{2}\sin 2x$. This will help you check your answer.


text:
Q: GROUP BY with OR/AND clause? Lets say my database looks like this:
Table: messages
+----+------+----+----------+----------+
| id | from | to | double_1 | double_2 |
+----+------+----+----------+----------+
| 1  | 1    | 2  | 0        | 0        |
| 2  | 1    | 0  | 1        | 2        |
| 3  | 2    | 0  | 2        | 1        |
| 4  | 2    | 1  | 0        | 0        |
| 5  | 2    | 3  | 0        | 0        |
| 6  | 2    | 0  | 1        | 3        |
+----+------+----+----------+----------+

Then in my selection from the table, I want to GROUP BY the following:

*

*group rows where double_1 and double_2 is the same, while to = 0

*group rows where from is the same, while to = $id and double_1 = 0 and double_2 = 0

*group rows where to is the same, while from = $id and double_1 = 0 and double_2 = 0

Anyone have any ideas how to do that?
EDIT: As it seems that i did make some people misunderstanding this. I will now explain better.
As I say the ways that I would like to GROUP BY, then when saying group rows where double_1 and double_2 is the same..., then its grouping the rows where double_1 and double_2 are the same. Like I have those two rows:
+----+------+----+----------+----------+
| id | from | to | double_1 | double_2 |
+----+------+----+----------+----------+
| 1  | 1    | 0  | 1        | 1        |
| 2  | 1    | 0  | 2        | 2        |
+----+------+----+----------+----------+

They should not be grouped, as ID 1's double_1 AND double_2 is not the same as ID 2's double_1 AND double_2. While this would group:
+----+------+----+----------+----------+
| id | from | to | double_1 | double_2 |
+----+------+----+----------+----------+
| 1  | 1    | 0  | 1        | 2        |
| 2  | 1    | 0  | 1        | 2        |
+----+------+----+----------+----------+

Im very sorry for the misunderstanding, hope that someone here are still willing to help me out.

A: You can generate a flag column for each group that you need to get:
 CREATE OR REPLACE VIEW vw_messages AS
 SELECT id
      , `from`
      , `to`
      , double_1
      , double_2
      , case when double_1 = double_2
              and `to` = 0
             then 1
        else 0
        end flag_1
      , case when double_1 = 0
              and double_2 = 0
              and `to` = $id
             then 1
        else 0
        end flag_2
      , case when double_1 = 0
              and double_2 = 0
              and `from` = $id
             then 1
        else 0
        end flag_3
 FROM messages

This way you can later get the rows that accomplish either one or any combinations of groups.


text:
Q: KVM is not installed on this machine (/dev/kvm is missing) I'm using Ubuntu 14.04. I recently installed Android Studio, but whenever I try to run a Hello World app, I get this error:
/home/praveen/Android/Sdk/tools/emulator -avd Nexus_6_API_21 -netspeed full -netdelay none
emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please ensure KVM is properly installed and usable.
CPU acceleration status: KVM is not installed on this machine (/dev/kvm is missing).

A: Use the below command to check whether the KVM is installed in the machine or not,
kvm-ok

Output:
INFO: /dev/kvm exists
KVM acceleration can be used

Output like the below means,
INFO: Your CPU does not support KVM extensions
KVM acceleration can NOT be used

In this scenario need to install KVM using the below command,
sudo apt-get install qemu-kvm libvirt-bin ubuntu-vm-builder bridge-utils

Hope this helps.

A: I had tried the command,
sudo apt-get install qemu-kvm libvirt-bin ubuntu-vm-builder bridge-utils

but unfortunately it didn't work. Then I changed owner (rohanverma is user in my case) by using,
sudo chown rohanverma:rohanverma -R /dev/kvm

which worked for me.

A: Either your CPU does not support virtualization, or it is disabled in the bios.  Go into your bios and see if you can find a setting to enable it.

A: I saw the same error. But I'm running Ubuntu on the VMware. Ubuntu is installed on the VMware. So the steps to resolve the problem is different from pure ubuntu machine. The complains went away with the following steps:

*

*sudo apt install cpu-checker

*In VMware, go setting->Processors->Virtualization Engine, check "Virtualize Intel VT-x/EPT or AMD-V/RVI.

*sudo kvm-ok

A: HP-EliteBook-820-G1:/opt/android-studio/bin$ sudo /usr/sbin/kvm-ok
INFO: /dev/kvm does not exist
HINT:   sudo modprobe kvm_intel
INFO: Your CPU supports KVM extensions
INFO: KVM (vmx) is disabled by your BIOS
HINT: Enter your BIOS setup and enable Virtualization Technology (VT),
      and then hard poweroff/poweron your system
KVM acceleration can NOT be used

Affter bios setting, I used the following command
sudo modprobe kvm_intel

Now is ok

A: Worked on Ubuntu 15.04, Intel's CPU

*

*sudo apt-get install qemu-kvm

*Enable Virtualization Technology in BIOS

*sudo kvm-ok

A: Close any other hypervisors before starting Android Studio. I received the same error message when I tried to run an Android Virtual Device and had a Virtual Box VM running at the same time.


text:
Q: Age calculation in Ruby I'm trying to write a rails application but presently the display for the date of birth is shown like the normal date format, but I wouldl love to show in views the age instead
The method I have in controller is below and I have a column DOb in my database for date of birthL
def age
  @user = user
  now = Time.now.utc.to_date
  now.year - @user.dob.year - (@user.dob.to_date.change(:year => now.year) > now ? 1 : 0)
end

It shows like DOB: 23/5/2011, but I would like it to be age in years instead.
How do I also put a validator that checks if age is below 18 years?

A: For the validator, you can use a custom method:
validate :over_18

def over_18
  if dob + 18.years >= Date.today
    errors.add(:dob, "can't be under 18")
  end
end

A: I ran across this question and thought I'd post a more modern answer that takes advantage of Rails convenience method syntax and custom validators.
Custom Age Validator
This validator will take an options hash for the field name you'd like to validate and the minimum age requirement.
# Include somewhere such as the top of user.rb to make sure it gets loaded by Rails.
class AgeValidator < ActiveModel::Validator

  def initialize(options)
    super
    @field = options[:field] || :birthday
    @min_age = options[:min_age] || 18
    @allow_nil = options[:allow_nil] || false
  end

  def validate(record)
    date = record.send(@field)
    return if date.nil? || @allow_nil

    unless date <= @min_age.years.ago.to_date
      record.errors[@field] << "must be over #{@min_age} years ago."
    end
  end

end

Example Usage
class User < ActiveRecord::Base
  validates_with AgeValidator, { min_age: 18, field: :dob }
end

User#age convenience method
And to calculate the user's age for display, you'll want to be careful to calculate around leap years.
class User < ActiveRecord::Base
  def age

    return nil unless dob.present?
    # We use Time.current because each user might be viewing from a
    # different location hours before or after their birthday.
    today = Time.current.to_date

    # If we haven't gotten to their birthday yet this year.
    # We use this method of calculation to catch leapyear issues as
    # Ruby's Date class is aware of valid dates.
    if today.month < dob.month || (today.month == dob.month && dob.day > today.day)
      today.year - dob.year - 1
    else
      today.year - dob.year
    end

  end
end

And the spec!
require 'rails_helper'
describe User do
  describe :age do
    let(:user) { subject.new(dob: 30.years.ago) }
    it "has the proper age" do
      expect(user.age).to eql(30)

      user.birthday += 1.day
      expect(user.age).to eql(29)
    end
  end
end

A: You should be careful when calculating age. Here's a correct method:
def age(as_at = Time.now)
  as_at = as_at.utc.to_date if as_at.respond_to?(:utc)
  as_at.year - dob.year - ((as_at.month > dob.month || (as_at.month == dob.month && as_at.day >= dob.day)) ? 0 : 1)
end

After that, as per @Baldrick:
validate :check_over_18

def check_over_18
  errors.add(:dob, "can't be under 18") if age < 18
end

A: You have a few different questions here.

*

*Where does the age calculation belong?
The age calculation should either be a helper method or a model method.  I've always made it a model method but have recently seen the advantages of having these display elements in decorators or even helper methods.  In your case, start with putting it in the model then progress from there:
def age
    now = Time.now.utc.to_date
    now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
end

*How do you validate that the person is over 18 years old?
Are you really restricting someone from being saved to the database if they are under 18? Or are you limiting there viewing ability?
def is_over_18?
    age >= 18
end

And this write a custom each validator or use a Proc, but I really question the decision to validate in this way.

A: To find age you can use the gem adroit-age
age = AdroitAge.find_age("23/01/1990")
=> 23

A: I had to deal with this too, but for months. Became way too complicated. The simplest way I could think of was:
def month_number(today = Date.today)
  n = 0
  while (dob >> n+1) <= today
    n += 1
  end
  n
end

You could do the same with 12 months:
def age(today = Date.today)
  n = 0
  while (dob >> n+12) <= today
    n += 1
  end
  n
end

This will use Date class to increment the month, which will deal with 28 days and leap year etc.


text:
Q: Java: Writing array to text file inconsistencies For a class project, a group and I have been working on an application that reads in lines of text from a text file and can encrypt it, decrypt it (both using DES), and calculate an MD5 hash.  The program reads in text and encrypts it just fine, writing the array of now encrypted strings back into the text file in the order in which they were read, line by line with all requisite carriage returns.
However, when decrypting these strings, the program writes the plaintext to the file all on one line, with no spaces or carriage returns.  Both the encrypt and decrypt methods use the same fileWrite class, which uses a buffered writer.  I have added a System.out.println statement for debugging purposes to print out the contents of the arrays as they are being encrypted and decrypted to check for errors in storage, but I can't find any.
Even when I artificially insert carriage returns by way of the "\n" symbol, the text file is all one line after it's decrypted.  I cannot for the life of me figure out why the same class would behave in two different ways at different times. The code to write the array to the file is simple enough, and just proceeds element by element and probably doesn't really need to be included, but here it is anyway.
    for(int i=0;i<s.length;i++){
    bufferedWriter.write(s[i]);
    }

From what I can gather, the issue potentially stems from how java and notepad handle new lines differently.  When it is reading the plaintext strings from the file, I'm assuming it receives the line breaks from the text file and prints out the encrypted text in this manner, but here java denotes a new line differently than it was originally in the file, leading to this spacing issue when these encrypted lines are then read and processed, but again, I'm not really sure, which is why I'm here. Any help would be appreciated.

A: Try using a PrintWritter, if you can, using the method println().
I believe the write() method does not change lines, you can force that by using the newLine() method.
Also careful that when reading from the file most methods do not return the line feed.

A: My guess is that you are using BufferedReader (which removes newline characters) and writing back the String's read without attempting to rebuild the newlines. (Or adding the newlines doesn't work because you say they are not here)
Instead of using BufferedReader you are better off treating the file as binary, reading blocks at a time and if it happens to be text, it will be unaltered. With text you have no way to guarentee \r\n or \n or \r will be recreated as they were in the original file.  If you encode and decode the text on different systems, the character encoding could be different. ;)

A: Perhaps you forget to flush and/or close the Writer at the end?


text:
Q: Python xlwt - looping through sales (works with csv.writer) I am trying to transfer my .csv output to .xslx as well but am having a bit of a trouble understanding how to loop through my sales with xlwt. I've read the following tutorials but no help there:
https://toricode.com/python-write-excel-file-using-xlwt/ and
https://tutorialmeta.com/question/understanding-for-loop-with-xlwt
The way it's done with csv.writer is as follows:
fieldnames = [
        _("Date"),
        _("Type"),
        _("Price")
        _("CustomerFName"),
        _("CustomerLName"),
    ]

    writer = csv.writer(output)
    writer.writerow(fieldnames)

    for s in sales:
        for sale in s.sales.all():
            row = [
                s.date,
                sale.type,
                sale.price,
                s.fName,
                s.lName,
            ]
     return output

Any ideas or good examples I could look into?
Thanks in advance.


text:
Q: How to request from a different server URL using JavaScript I need to send some of my data into another server. Actually to post into facebook. So here i already have an API which works by an URL.
So if i set the parameters from the URL and if i try it in web browser it works. But when i try it as a AJAX call it do not work. (Because its not hosted in the same server as my web pagers are).
Is there any way to send this URL in the background??

A: You cannot. For security reasons, Javascript can't initiate requests to sites in different domains.
The only way to do that would be query your own server and have it query the external API, and then respond to your page.

A: You will have to write a proxy routine on your own domain that communicates with your JS on the one hand and with third party domain (Facebook) on the other.

A: I created a iframe dynamically. It seems working.


text:
Q: How to get future time difference of 1 hour from NSDate I want to enable a feature to the user to execute a functionality only AFTER 1 hour from current time. What exactly shall I pass in toDate parameter in below code to get the 1 hour future time difference from current time? I have no idea how to set future time in NSDateFormatter OR NSDateComponents. So couldn't write what I have tried.
- (NSInteger)timeDifference:(NSDate *)fromDate ToDate:(NSDate *)toDate
{

    NSLog(@" FromDate: %@, ToDate: %@",fromDate,toDate);

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *differenceValue = [calendar components:NSHourCalendarUnit
                                                    fromDate:fromDate toDate:toDate options:0];
    NSLog(@"Calculated hour difference : %d",[differenceValue hour]);
    NSInteger hourDifference = [differenceValue hour];

    NSLog(@" HourDifference: %d",hourDifference);
    return hourDifference;
}

A: If you want to create a date that is one hour later the a specific date, you can use the dateByAddingTimeInterval method, like:
NSDate *date = [NSDate date];
NSDate *plusOneHour = [date dateByAddingTimeInterval:60.0f * 60.0f];

NSLog(@"%@, %@", date, plusOneHour);

UPDATED
As @uchuugaka stated, you can find the version using calendar methods here.

A: See the NSCalendar header for convenience methods. Also watch the WWDC video from 2013 on the topic of calendrical calculations.
This stuff has been really slow to make it into the docs and simply adding a time interval is many times a mistake. All of the components are important to get this right. You need to have a calendar and a timezone to have a semantically meaningful hour increase.
It's a trap when dealing with midnight, leap year and daylight savings time which is different everywhere.
Specifically in this case I would recommend this from NSCalendar.h
/*
    This API returns a new NSDate object representing the date calculated by adding an amount of a specific component to a given date.
    The NSCalendarWrapComponents option specifies if the component should be incremented and wrap around to zero/one on overflow, and should not cause higher units to be incremented.
*/
- (NSDate *)dateByAddingUnit:(NSCalendarUnit)unit value:(NSInteger)value toDate:(NSDate *)date options:(NSCalendarOptions)options NS_AVAILABLE(10_9, 8_0);

But there are several methods in that header that would suffice. Please watch the WWDC video carefully a few times. Well worth your time and your users' experience will be better.


text:
Q: Entity Framework table updates not working due to trigger calling CLR I have a table with a trigger that points to an assembly:
CREATE TRIGGER [dbo].[triggername] ON [dbo].[tablename]
WITH EXECUTE AS CALLER
AFTER DELETE, UPDATE
NOT FOR REPLICATION

AS EXTERNAL NAME [Namofassembly].[blahblah].[blahblah]
We also using code first EF in .net 4.
When I use delete everything works fine but the trigger does not get called.
dataRepo.UsersPermanentAuditAssignments.Remove(isInsertFound)

When I use update I get a permissions error. This is either when I try it through the object model or a dataRepo.Database.ExecuteSqlCommand(updateSql)
System.Data.SqlClient.SqlException: The context transaction which was active before entering user defined routine, trigger or aggregate "name" has been ended inside of it, which is not allowed. Change application logic to enforce strict transaction nesting.

Everything works fine when I run the queries via the sql management studio.
I also am not able to change this configuration so while I don't care for this design I am not able to change it.
My questions are:
1> Why would the delete not get logged but work?
2> Do I need to add something extra to my repo configuration object that will allow this to work? Do I need to add some transaction like unitofwork before I start this since it has a trigger maybe?

A: I have figured out the causes of this issue.
It relates to having a composite primary key (station,user) and trying to update one of the values.
I could not update any column of the primary key, ie change the user assigned to a station.
The trigger failure masked the issue of not being able to update a value inside the key.
My experiments show the following for the compositekey/pk update:
Method          History Trigger            Result
EF.SaveChanges              Enabled        Fail at trigger
EF.SaveChanges              Disabled        Fail at trigger
EF.ExecuteSQLCommand(sql)   Enabled        Fail at trigger
EF.ExecuteSQLCommand(sql)   Disabled       Works

Unfortunately, I don't have the ability to change to a surrogate with a unique index which would work. Also, the trigger CLR prevents me from using DataBase.ExecuteSQLCommand(sql) also which I believe is actually a problem with the CLR of which I have not ability to modify.
So my advise (that I can't take) is if you get this use a surrogate key and a unique index instead of combining the 2.
If anyone knows any way to allow EF to allow you to change a value inside a composite/primary key please comment.


text:
Q: I am getting the error code CS0411 What does the following error message mean?

Error CS0411
  The type arguments for method
  'Component.GetComponent()' cannot be inferred from the usage. Try
  specifying the type arguments explicitly

This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Mover : MonoBehaviour
{
    private Rigidbody rb;
    private float speed;

    void Start()
    {
        rb = GetComponent();
        rb.velocity = transform.forward * speed;
    }
}

A: Problem here
rb = GetComponent();

Fix is
rb = GetComponent<RigidBody>();


text:
Q: State history with browser back button vue.js I am developing an application with Vue and Laravel. Laravel is controlling my routes and I'm not using the vue-router.
I am conditionally loading some components based on the state of an object in my parent components data.
I have this method in my parent component:
  activateListingForm: function() {
    this.listingFormActive = !this.listingFormActive;
  }

This method is triggered by a button that will change this.listingFormActive to true or false.
I then have this in the template of the component:
  <transition name="slide-fade">
    <create-listing-form v-if="listingFormActive"></create-listing-form>
    <listings-table v-else></listings-table>
  </transition>

A problem that I am having is that some users are clicking the browser back button expecting the last component to load. I'm wondering if there is a way to change the state based on the back button?
Thanks

A: It's doable. My colleagues and I had to do something similar while working on this page.
For it to work,

*

*url is the source of truth of what the value of listingFormActive should be

*the state of listingFormActive should be stored in url everytime it
changes.

*the initial state of listingFormActive should be retrieved
from url

First, watch listingFormActive. Everytime the state change, perform pushState to store  its state as a url query.
watch: {
    listingFormActive: {
        handler(v) {
            history.pushState({
                listingFormActive: v
            }, null, `${window.location.pathname}?listingFormActive=${v}`);
        }
    }
}

Add some utility method for getting url query
methods: {
    currentUrlQuery() {
        return window.location.search
            .replace("?", "")
            .split("&")
            .filter(v => v)
            .map(s => {
                s = s.replace("+", "%20");
                s = s.split("=").map(s => decodeURIComponent(s));
                return {
                    name: s[0],
                    value: s[1]
                };
            });
    },
    getListingFormActive() {
        return this.currentUrlQuery().filter(obj => obj.name === 'listingFormActive').value;
    }
}

the initial state of listingFormActive should be based on what you saved in the url
data() {
    return {
        listingFormActive: this.getListingFormActive() == 'true' ? true : false
    }
},


text:
Q: Handlers and Databases GoLang So I have a local database that uses mongoDB, and I want to print values from that DB to the localhost http server but for some reason I can't figure out how to get the values from it. This is what I've tried for my handler so far:
func outputHandler(w http.ResponseWriter, r *http.Request) {
    session, err := mgo.Dial("localhost")
    if err != nil {
        panic(err)
    }
    c := session.DB("foo").C("WOO")
    countTemp := c.Find(nil)

    outputString, err := json.Marshal(countTemp)
    if err != nil {
        panic(err)
    }
    w.Write(outputString)
}

The reason I have it as c.Find(nil) is because I know that the database only has 1 value at any given time, and that is the value I want to retrieve. When the output below is ran, my response on localhost/:8080/foo is {}.
Thanks for your help!

A: c.Find returns a query.  You need to execute the query to get the data:
var countTemp interface{}
if err := c.Find(nil).One(&countTemp); err != nil {
   // handle error
}


text:
Q: Undefined index: UsernamesInput in When I try to upload a text file I get 'Undefined index: UsernamesInput in'
I tried lookin up the issue I found some examples but I they didn't make any sense to my specific code
This is my HTML code:

           <form action="verify.php" method="POST">

                <fieldset class="form-group">
                    Emails
                    <textarea class="form-control" id="exampleTextarea" rows="5" placeholder="Emails here..."></textarea>
                </fieldset>
                <fieldset class="form-group middle">
                    Email input
                    <input type="file" class="form-control-file" id="exampleInputFile">
                    Upload the E-mail adresses for registering
                </fieldset>

                <fieldset class="form-group">
                    Passwords
                    <textarea class="form-control" id="exampleTextarea" rows="5" placeholder="Passwords here..."></textarea>
                </fieldset>
                <fieldset class="form-group middle">
                    Password input
                    <input type="file" class="form-control-file" id="exampleInputFile">
                    Upload the Passwords for registering
                </fieldset>

                <fieldset class="form-group">
                    Usernames
                    <textarea class="form-control" id="exampleTextarea" rows="5" placeholder="Usernames here..."></textarea>
                </fieldset>
                <fieldset class="form-group middle">
                    Username input
                    <input type="file" name="UsernamesInput" class="form-control-file" id="exampleInputFile">
                    Upload the Usernames for registering
                </fieldset>

            <input type="submit" name="submit" value="Create Accounts!" class="btn btn-info btn-block">
           </form>

and my PHP code:
            <?php

            $_SERVER['REQUEST_METHOD'];

            $name      = $_FILES['UsernamesInput']['name'];
            $extention = strtolower(substr($name, strpos($name, '.') + 1));
            $type      = $_FILES['UsernamesInput']['type'];

            //$size = $_FILES['UsernamesInput']['size'];

            $tmp_name = $_FILES['UsernamesInput']['tmp_name'];

            if (isset($name)) {
                if (!empty($name)) {

                    if (($extention == 'txt') and ($type == 'text/plain')) {

                        $location = 'uploads/';

                        if (move_uploaded_file($tmp_name, $location . $name)) {
                            echo 'Uploaded!';
                        } else {
                            echo 'There was an error';
                        }

                    } else {
                        echo 'Error, file must be in text format.';
                    }
                }
            }

            ?>

Thanks in advance,

A: Add name for each type='file' inputs and also try adding enctype="multipart/form-data in the form
 <form action="verify.php" method="POST" enctype="multipart/form-data">
 <input type="file" name="UsernamesInput" class="form-control-file" id="exampleInputFile">
 </form>

A: You need to add enctype="multipart/form-data" in your HTML form becuase you are using input type file in your HTML.
<form action="actionFile" method="post" enctype="multipart/form-data">

HTML Form Enctype


text:
Q: How can I understand the 2nd solution of this equation? (theoretically correct, but doesn't work while being verified) I'm trying to solve these two equations:
$$
\cos\left(\frac{\gamma'}{2}\right) = g_0\qquad e^{i\beta'}\sin\left(\frac{\gamma'}{2}\right) = g_1
$$
Where $g_0$ is real and $g_1$ is complex. From the discussions on the math channel, we can find that
$$
\gamma'=2\cos^{-1}(g_0),\qquad e^{i\beta'}=\pm\frac{g_1}{\sqrt{1-g_0^2}}\qquad\beta'=-i\log\frac{g_1}{\sqrt{1-g_0^2}}+k\pi,\ \text{where}\ k\in\mathbb{Z}$$
However, I'm still having trouble understanding the solution when $k$ is an odd number, say if it equals $1$, then I'm trying to verify the solution using Mathematica:

Given that
g_0 = 0.8974187611347583, g_1= -0.33540402107889095+0.28660723962849705*I
We can find $\gamma' = 0.913825694123124 , \beta_1'= 2.434484141132717 , \beta_2'=5.5760767947225105$ (differ by $1*\pi$).
However, when I tried to use Mathematica to verify the solutions, only $\beta_1'$ and $\gamma'$ works, by which I mean $e^{i\beta'}\sin\left(\frac{\gamma'}{2}\right)-g_1=0$.
When I plug $\beta_2', \gamma'$ into the equation, it returns 0.670808 - 0.573214 I. Why the second answer doesn't work? Thanks a lot for the help!!
PS: This is what I tried:
Exp[I*5.5760767947225105]* Sin[0.913825694123124/2] - (-0.33540402107889095 +  0.28660723962849705*I) // Simplify

A: Clear["Global`*"]

eqns = {Cos[γ/2] == g0, Exp[I*β] Sin[γ/2] == g1};

sol = Solve[eqns, {β, γ}] // Simplify

Alternatively,
sol // TrigToExp

Verifying the solutions,
Assuming[Element[{C[1], C[2]}, Integers],
 eqns /. sol // Simplify]

(* {{True, True}, {True, True}} *)

For your specific values,
val = {g0 -> 0.8974187611347583,
   g1 -> -0.33540402107889095 + 0.28660723962849705*I};

sol2 = sol /. val

Assuming[Element[{C[1], C[2]}, Integers],
 eqns /. val /. sol2 // Simplify]

(* {{True, True}, {True, True}} *)


text:
Q: C# - Problem with generics and inheritance I've got a problem with inheritance and generics.
This is the code that illustrates my problem:
namespace TestApplication
{
    public class MyClass<T>
    {
        private T field;

        public MyClass(T field)
        {
            this.field = field;
        }
    }

    public class MyIntClass : MyClass<int>
    {
        public MyIntClass(int field)
            : base(field)
        {
        }
    }
}

And when I try to do something like this:
MyClass<int> sth = new MyClass<int>(10);
MyIntClass intsth = (MyIntClass) sth;

I receive cast exception: Invalid cast exception. Unable to cast 'TestApplication.MyClass`1[System.Int32]' to 'TestApplication.MyIntClass'.
What is more I cannot create cast operator:
public static implicit operator MyIntClass(MyClass<int> myClass)

because: 'TestApplication.MyIntClass.implicit operator TestApplication.MyIntClass(TestApplication.MyClass)': user-defined conversions to or from a base class are not allowed
I need to create casts as described above. I don't know why I cannot cast from a type that is the base class. How can I solve this problem?
Thanks in advance.
Edit
Thanks for Your answers.
Now I see that i cannot convert from a base class to derived class and i see that it doesn't have anything to do with generics.
But why i cannot create user-defined conversions from a base class? I have a method that returns the base class. I am able to define a conversion method but creating a cast operator imho would be a better solution.

A: In the comments you asked:

But why conversion from a base class is not allowed?

Simple - it would make no sense. Consider the example:
class BaseClass
{
    public int x;

    public BaseClass(int StartX)
    {
        this.x = StartX;
    }
}
class ChildClass: BaseClass
{
    public int Y;

    public BaseClass(int StartX, StartY): base(StartX)
    {
        this.y = StartY;
    }
}

class Program
{
    public static void Main()
    {
        BaseClass B = new BaseClass(3);
        ChildClass C = (ChildClass)B;
        Console.WriteLine(C.y);
    }
}

What do you suppose this program would output, assuming the cast worked? Even worse - imagine that BaseClass has two child classes - ChildClassA and ChildClassB. Do you want this to work?
ChildClassA A = new ChildClassA();
   BaseClass bc = (BaseClass)A;
   ChildClassB B = (ChildClassB)bc;
This would effectively allow to cast ChildClassA instances to ChildClassB - completely wrong.

A: You can only cast from a base class to a derived class if the object is actually of type derived class. I mean, you can't cast an instance of base (MyClass<int>) to MyIntClass. You can, however cast it if it was actually of type MyIntClass stored as an MyClass<int> instance.
MyClass<int> foo = new MyIntClass();
MyIntClass bar = (MyIntClass)foo; // this works.

Assume:
class Base {
   int x;
}

class Derived : Base {
   int y;
}

Base foo = new Base();
Derived bar = (Derived)foo;

if it was allowed, what would the value of bar.y be?
In fact, converting from Derived to Base is not a conversion at all. It's just telling the compiler to let the variable of type Base to point to an object of type Derived. It is possible since derived has more or equal features than Base which is not the case in the other way around.
If you were able to create a conversion operator between base and derived classes, the C# compiler would be unable to distinguish it from the built in relationships defined for them. This is why you cannot create cast operators along inheritance hierarchies.

A: The other answers so far are correct, but I'd like to point out that your example has nothing to do with generics. It's the equivalent of:
using System;

class Base {}
class Child : Base {}

class Test
{
    static void Main()
    {
        Base b = new Base();

        // This will throw an exception
        Child c = (Child) b;
    }
}

A: As Mehrdad stated, you cannot downcast an object. Upcasting is implicit, therefore you cannot overwrite it.
As for the implicit operator, you can still create a constructor in the derived class which receives a parameter of type baseclass.
If you need to cast freely, define the variable as baseclass, but instantiate derived classes.

A: As has been said, you're trying to cast an object into a type that it doesn't derive from. Did you perhaps want to do this:
MyClass<int> sth = new MyIntClass(10);
MyIntClass intsth = (MyIntClass) sth;

A: Instead of creating an MyIntClass, try an alias:
using MyClass<int> = What.Ever.Namespace.MyIntClass;

This is now valid:
MyClass<int> foo = new MyClass<int>();
MyIntClass bar = (MyIntClass)foo;

Just understand that when doing the using alias, you have to qualify your namespace on the alias type name (What.Ever.Namespace).

A: Regarding your second question:

But why i cannot create user-defined conversions from a base class?

Well, suppose you have this scenario
class Base {
}

class Derived {
    public static operator Derived(Base b) { ... }
}

and you tried to do this
Base x = new Derived();
Derived y = (Derived)x;

should the conversion be called? Of course not! The value inside x is actually of type Derived, so the cast is direct, without conversion. But if the value was not of type Derived, but a concrete Base, then the user-defined conversion has to happen because otherwise we'd have a compiler error. This all makes no sense; user-defined conversions are found in compile-time, and the type of the value of x is only known in runtime. Therefore, the compiler would not know what to do - call the user-defined conversion or simply cast the value...
Hope this makes a bit of sense to you.

A: Answering to your last edit.
This code does already compile, it only fails at runtime:

MyIntClass intsth = (MyIntClass) sth;

So, the following cast operator would be redundant if left explicit:

public static implicit operator MyIntClass(MyClass myClass)

So, the compiler should prevent you from adding that conversion. I think the error might be confusing, but I think it just forbids converting class B to class A if B is derived from A (the warning seemed to me to prevent any conversion to A, at first).
If the operator is made implicit, it is also dangerous, because a downcasting can always fail, so you have to:

*

*show the compiler that you know that, by adding an explicit cast;

*show the reader (which includes yourself, minutes later) that the operation might fail.

A: Assignment/conversion of a base class to a derived class makes sense if you consider assignment or conversion to be a value by value copy. What's confusing about c# for
newbies is the inconsistent way it does things:
'int' is a 'simple' type:
int i = 5;   // <- this creates an int.
int j = i;    // <- this creates another int and copies the value of i into j.

'Object' is not a simple type:
Object a;                            // <- this does not create a copy of 'Object', only a reference to one
Object b = new Object();   // <- this actually creates an Object
a = b;                                 // <- this sets the reference to an object a to the reference to an object b.
                                          // both of them reference the same Object. No values were copied.

If it were doing a copy of values then copying to base class to a derived class would
work. C# doesn't work like other languages.
I think that might be what's confusing you.


text:
Q: Applying apply in Scheme What am I missing here?  I was playing with apply in Scheme, and wrote:
(apply apply '(+ (1 2 3)))

The way I understand it, the first apply should do:
(apply + '(1 2 3))

and the second should do:
(+ 1 2 3)

But both Ypsilon and Gauche give about the same error (this is Ypsilon's):
error: attempt call non-procedure: (+ 1 2 3)

backtrace:
  0  (apply apply '(+ (1 2 3)))
  ..."/dev/stdin" line 1

What have I failed to understand?

A: The problem with '(+ (1 2 3)) is that the + is quoted and thus interpreted as a symbol.
You would have to use eval to get a value for the + symbol.
In other words, what you are trying to do, is not going to work.
Edit: Another option is quasiquote. Eg:
(apply apply `(,+ (1 2 3))) ; => 6

Or (without quasiquote)
(apply apply (list + '(1 2 3))); => 6


text:
Q: IndexedDb login function I have been working with indexedDB for a few hours now. I am attempting to create a registration and login system. Registration has worked well but the following code for login doesn't work. The error comes at the first alert after onsuccess. Can anyone help me identify where the error is? Thanks.
function getUser(e) {

 var email = document.querySelector("#email").value;
 var password = document.querySelector("#password").value;

 console.log("About to login "+email);

 var transaction = db.transaction(["users"]); //readonly
 var objectStore = transaction.objectStore("users");
 var request = objectStore.get(email);

 request.onerror = function(e) {
  alert("Unable to retrieve data from database!");
  return;
 };
 request.onsuccess = function(e) {
  alert(password " " + request.result.password);
  if(password != request.result.password) {
   alert("Could not log you in");
   return;
  }
  console.log("You are logged in");

 };

A: IndexedDb in javascript: I got a solution.
This solution is working for me. you need to use the index to read the data by calling the get() method.
Code snippet:
function(e) {
    var email = document.querySelector("#email").value;
    var password = document.querySelector("#password").value;
    db = e.target.result;
    var tx = db.transaction(["users"], "readonly");
    var store = tx.objectStore("users");
    // get the index from the Object Store
    const index = store.index('email');
    // query by indexes
    var query = index.get(key);
    query.onsuccess = function(e) {
        console.log(query.result)
        if(query.result)
        {
            if(password != query.result.password) {
                alert("In-correct Credentials... Please check and try
                again!!!");
            }
         else{
             alert('success');
          }
       }
    };
};

For reference you may visit: https://www.javascripttutorial.net/web-apis/javascript-indexeddb/


text:
Q: Problem with taking data from a table using Execute Scalar (C#) I have two tables, one called DogContract and one called WeeklyBooking. They both share two columns, called ContractLength and DogID.
I am currently programming a function for the user to use the GUI to input a new WeeklyBooking object into the table.
I am attempting to retrieve the ContractLength value. I have a textbox where the user inputs the DogID and in theory my code is to take the ContractLength Value from DogContract and then assign it as the ContractLength for the weeklybooking object. I have a function in my WeeklyBookingDataAccess class to do this:
        public int getContractLength(string dogID, WeeklyBooking week)
    {
        SqlCommand getCLength = new SqlCommand("SELECT ContractLength FROM WeeklyBooking WHERE DogID =" + dogID);
        try
        {
            db.Conn.Open();
            week.contractLength = (int)db.Cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return week.contractLength;
    }

This method is called in the function I'm using to create the WeeklyBooking object. The problem is, when I check the table data the ContractLength Value is always set to zero. Has anybody any ideas as to fix this problem?
-Thanks

A: You are doing something weird with Connection and SqlCommand. This should work:
public int getContractLength(string dogID, WeeklyBooking week)
{
    SqlCommand getCLength = new SqlCommand("SELECT ContractLength FROM WeeklyBooking WHERE DogID = @DogId", db.Conn);
    try
    {
        getCLength.Parameters.Add("@DogId", SqlDbType.NVarChar, 64);
        getCLength.Parameters["@DogId"].Value = dogID;
        db.Conn.Open();
        week.contractLength = (int)getCLength.ExecuteScalar();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return week.contractLength;
}

You need to associate your Connection and your SqlCommand. You can do that by passing the Connection to the constructor of the SqlCommand, or by asking the Connection to create the command.
Apart from that you should take a look at the using pattern and make sure your Connection and SqlCommand are created and destroyed in the right way.
Note also that I'm using a named parameter, it's best practice, so you're not open to SQL-injection.
You can also use the simpler version, where you add the parameter with value:
public int getContractLength(string dogID, WeeklyBooking week)
{
    SqlCommand getCLength = new SqlCommand("SELECT ContractLength FROM WeeklyBooking WHERE DogID = @DogId", db.Conn);
    try
    {
        getCLength.Parameters.AddWithValue("@DogId", dogID);
        db.Conn.Open();
        week.contractLength = (int)getCLength.ExecuteScalar();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return week.contractLength;
}


text:
Q: Visualforce render as pdf not displaying correct Devnagiri words I am using Arial Unicode MS font in the html. I need to render it as pdf.
The html contains Devnagari words. HTML is displayed properly but the words are broken in the generated pdf. e.g "आपल्या" => आपल् या
Has anybody faced this problem? Any pointers will help

A: According to the documentation, Salesforce fully supports Hindi. I understand Devanagari is the Sanskrit alphabet used for Standard Hindi. I'd expect the font to be in SF's cache when they produce the PDF so all the glyphs needed (including ligatures) will be there for it to render properly. Have you checked the PDF document to see if they were embedded in it?
Its possible the SF PDF generator may not "understand" the rules of the Hindi language, thus breaking apart words as it did in your example. In the latter case, I think you probably need to look at adding "Unforced Breaks" code to your CSS to the HTML you're using that helps prevent any words from being hyphenated or inadvertently broken up by the PDF generator. The W3 CSS Fragmentation Module covers those properties and will hopefully help you figure out how to implement a solution that will solve the issue you're having.


text:
Q: UITabBarItem delete glossy from image
You can see that house picture with shadow and like prerendered icon. How can I delete this effect?

A: You need to set both finished and unfinished images on your UITabBarItem otherwise framework will automatically add the shine on it. Here is how you can do it.
[barItem setFinishedSelectedImage:[UIImage imageNamed:@"myimage.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"myimage.png"]];

Please note that both finished and unfinished images are same.


text:
Q: Android - Hide first activity before parseloginui I am starting to study Parse with Android, and i found ParseLoginUI, but i am having some problems, when I am using ParseLoginUI Dispatcher, one empty screen open before starts login screen,how can i do to hide this, please?!
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.com.appstudy"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:name=".AppApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/AppTheme" >
        <activity
            android:name=".MainActivity" /* dispatcher */
            android:label="@string/app_name"
            android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.parse.ui.ParseLoginActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop" >
            <meta-data
                android:name="com.parse.ui.ParseLoginActivity.PARSE_LOGIN_ENABLED"
                android:value="true" />
            <meta-data
                android:name="com.parse.ui.ParseLoginActivity.PARSE_LOGIN_EMAIL_AS_USERNAME"
                android:value="true" />
            <meta-data
                android:name="com.parse.ui.ParseLoginActivity.FACEBOOK_LOGIN_ENABLED"
                android:value="true" />
        </activity>
        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop" />

        <meta-data

MainActivity (dispatcher)

    public class MainActivity extends ParseLoginDispatchActivity {
    @Override
        protected Class<?> getTargetClass() {
            return AppActivity.class;
        }
    }
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name=".AppActivity"
            android:label="@string/title_activity_app"
            android:launchMode="singleTop" >
        </activity>
    </application>

</manifest>

MainActivity (dispatcher)
package br.com.dietshare;

import com.parse.ui.ParseLoginDispatchActivity;

public class MainActivity extends ParseLoginDispatchActivity {

    @Override
    protected Class<?> getTargetClass() {
        return DietActivity.class;
    }

}

Best Regards,
Rodrigo


text:
Q: Ubuntu is there any frame by frame video editor software which can allow to place a picture? I have this video : http://www.youtube.com/watch?v=f8iOQ9zWP6A
Where i have to place two picture of my girl-friend, i have to replace the existing baby faces by those two pictures, which i will make a special DVD for one surprise / gift to my girl-friend. To make her smile.
But so far i have tried openShot but i can not edit frame by frame there. Then i tried Gimp with gimp-gap plugin, but still using Gimp is like i can spend 1 year to make this video.
Is there any frame by frame editing software available for Ubuntu? (for example, in Flash for Windows its easy to do such thing)
Any idea?

A: You may wish to give a chance to kdenlive, which includes several keyframable plugins like those you may need in order to do that work.
It comes to my mind the track plugin "MaskOMate" to "cut" the part of the image that you wish to put overlaying the video. Of course, it will be useful if you first prepare the images in order to fit the project's size, with transparency, then simply use the "Composite" track's transition in order to put the images over the video.
Both "MaskOMate" and "Composite" plugins are keyframable, so you can choose where to place your video elements in a certain moment of the video play.
See the official kdenlive site and the Creative effects page for further information.
In the next screenshot, I am using a pre-made transparency image with an amazed girl in order to place it on the background video where a man is appearing over a green screen wall. Of course, I also used the "Pan and Zoom" Plugin in order to make the image bigger. Remember: The best your sources are, the best results you'll get.

What you wish to achieve is complicated and a hard work but with patience and creativity you can create an awesome video.
Good luck!

A: You could of course try with LiVES.
sudo apt-get install lives


text:
Q: $L_2$ norm for matrix of funtion In Audin's book Morse theory and Floer homology, they claimed

Proposition 6.1.5. Let $H$ be a function on $\mathbb{R}^{2n}$, so that $X_H$ is a vector
field on $\mathbb{R}^{2n}$. If      $|dX_H|_{L_2} < 2π$, then the only solutions of period 1 of the
Hamiltonian system associated with $H$ are the constant solutions (critical
points of H).

I wonder what is the $L_2$ norm here for a matrix of funtion in $||dX_H||_{L_2} < 2π$. Here, $dX_H=(\partial f_i/\partial x_j )_{i,j}$ for $X_H=(f_1,...f_n)^T$. In fact, in the book there is also
$||x'(t)||_{L2}$, I think it is same as what I want to ask.


text:
Q: RowNumber Window Query for Hiscores Ranking - Django I'm trying to build a game hiscore view with rankings for my Django site, and I'm having some issues.
The query I have is the following:
row_number_rank = Window(
    expression=RowNumber(),
    partition_by=[F('score_type')],
    order_by=F('score').desc()
)

hiscores = Hiscore.objects.annotate(rank=row_number_rank).values()

The query above works perfectly, and properly assigns each row a rank according to how it compares to other scores within each score type.
The result of this is the following:
{ 'id': 2, 'username': 'Bob', 'score_type': 'wins', 'score': 12, 'rank': 1 }
{ 'id': 1, 'username': 'John', 'score_type': 'wins', 'score': 5, 'rank': 2 }
{ 'id': 4, 'username': 'John', 'score_type': 'kills', 'score': 37, 'rank': 1 }
{ 'id': 3, 'username': 'John', 'score_type': 'kills', 'score': 5, 'rank': 2 }
{ 'id': 5, 'username': 'Bob', 'score_type': 'kills', 'score': 2, 'rank': 3 }

The issue comes in when I want to retrieve only a specific user's scores from the above results. If I append a filter(username="Bob") the query is now:
row_number_rank = Window(
    expression=RowNumber(),
    partition_by=[F('score_type')],
    order_by=F('score').desc()
)

hiscores = Hiscore.objects.annotate(rank=row_number_rank).filter(username='Bob').values()

Unexpectedly, adding this filter step has yielded the following incorrect results:
{ 'id': 2, 'username': 'Bob', 'score_type': 'wins', 'score': 12, 'rank': 1 }
{ 'id': 5, 'username': 'Bob', 'score_type': 'kills', 'score': 2, 'rank': 1 }

Randomly, the rank on the id=5 entry has decided to change to 1 instead of its correct value of 3.
Why would adding this filter step modify the values of the fields in the QuerySet, instead of just excluding the proper elements from it?
Thanks.


text:
Q: Why colorbar cannot work with heatmap fuse to scatter? I work with two graphics, and they are fuse. It's a heatmap fuse to a scatter but the heatmap doesn't have colorbar and I want to show this color. When I try to do it it give me an error:
RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).
Here's the code:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("data/forestfires.csv")

x_number_list = df.X.tolist()
y_number_list = df.Y.tolist()
x_number_list = np.array(x_number_list)
y_number_list = np.array(y_number_list)

area_number_list = df.area.tolist()
area_number_list = [int(round(x+1,0)) for x in area_number_list]
temperature_number_list = df.temp.tolist()
temperature_number_list = np.array(temperature_number_list)

heatmap, xedges, yedges = np.histogram2d(y_number_list, x_number_list, weights=temperature_number_list)
fig, ax1 = plt.subplots(figsize=(7,7))
ax1.imshow(heatmap, interpolation='bicubic', cmap='hot', origin='lower')
ax1.scatter(x_number_list, y_number_list, s=area_number_list, color=(157/255, 173/255, 245/255, 0.9))
ax1.set_ylim(y_number_list.min()-0.5, y_number_list.max()+0.5)
ax1.set_xlim(x_number_list.min()-0.5, x_number_list.max()+0.5)

cb = plt.colorbar()

plt.show()

here's the result of the plot:

All data I use in this program are number. I work on jupyter and I use the lastest version on python.

A: You need to specify where you want to have to colorbar and what you want the colorbar to show. I would do it in the following fashion.
Change
ax1.imshow(heatmap, interpolation='bicubic', cmap='hot', origin='lower')

to
im = ax1.imshow(heatmap, interpolation='bicubic', cmap='hot', origin='lower')

and then specify the colorbar as
cb = fig.colorbar(im, ax=ax1)


text:
Q: How to use arrow keys on Menu shortcuts in vb 6 Using vb6's menu editor wizard I am able to create a menu for my window easily and with shortcut keys like CTRL + A to Z keys, SHIFT + F1-F12 keys, SHIFT + CTRL + F1 -F12 keys. However I am not able use other keys e.g Arrow leys like Up, Down, Left, Right, Page Down or Page Up.
I have observed the auto generate code on my frmMenu.frm file as below:
Begin VB.Form frmMenu
   Caption         =   "Form1"
   ClientHeight    =   3015
   ClientLeft      =   225
   ClientTop       =   870
   ClientWidth     =   4560
   LinkTopic       =   "Form1"
   ScaleHeight     =   3015
   ScaleWidth      =   4560
   StartUpPosition =   3  'Windows Default
   Begin VB.Menu mnuProjection
      Caption         =   "&Projection"
      Begin VB.Menu mnuArrowRight
         Caption         =   "Arrow &Right"
      End
      Begin VB.Menu mnuArrowLeft
         Caption         =   "Arrow &Left"
      End
      Begin VB.Menu mnuArrowUp
         Caption         =   "Arrow &Up"
      End
      Begin VB.Menu mnuArrowDown
         Caption         =   "Arrow &Down"
      End
      Begin VB.Menu mnuExit
         Caption         =   "E&xit"
         Shortcut        =   ^Q
      End
   End
End
Attribute VB_Name = "frmMenu"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Sub mnuExit_Click()
    Unload Me
End Sub

Any help would be appreciated like the code for such keys because they are lacking in the menu editor wizard


text:
Q: calculate the score with respect to the group it was assigned or other I'm beginner in python, I have two dataframes as below. The first dataframe represents the user with their vectors and group number.
    df1 = pd.DataFrame({'user': ['user 1', 'user 2', 'user 3', 'user 4', 'user 5'], 'x1': [[0.2, 0.3, 0.5],[0.3, 0.3, 0.4],[0.4, 0.4, 0.2],[0.2, 0.1, 0.7],[0.5,0.3,0.2]],'group': [1, 0, 0, 2, 1]})

df1

output:
 user   x1  group
    0   user 1  [0.2, 0.3, 0.5] 1
    1   user 2  [0.3, 0.3, 0.4] 0
    2   user 3  [0.4, 0.4, 0.2] 0
    3   user 4  [0.2, 0.1, 0.7] 2
    4   user 5  [0.5, 0.3, 0.2] 1

the second dataframe represents the group number with its vector and variable (p2) and its threshold
df2 = pd.DataFrame({'group': [0, 1, 2],
                   'x2': [[0.4, 0.2, 0.4],[0.5, 0.1, 0.4], [0.5, 0.1, 0.4]],
                   'p2': [0.231, 0.342, 0.411],
                   'threshold': [0.9, 0.6, 0.8]})
df2

output:
group   x2  p2  threshold
0   0   [0.4, 0.2, 0.4] 0.231   0.9
1   1   [0.5, 0.1, 0.4] 0.342   0.6
2   2   [0.5, 0.1, 0.4] 0.411   0.8

I am trying to calculate for each user, the score (S) with respect to the group it was assigned by using:

where k= group size and T is the transport matrix of (x2 -x1).
How could I do that for all users?

A: First, count up the members of each group to get the k term:
df2['count'] = df1.groupby('group')['user'].count()

Then merge df1 and df2 so that we have a frame with all necessary parameters for each user in a single row:
joined = df1.join(df2[['x2', 'p2', 'threshold', 'count']], on='group')
print(joined)

>>>      user               x1  group               x2     p2  threshold  count
0  user 1  [0.2, 0.3, 0.5]      1  [0.5, 0.1, 0.4]  0.342        0.6      2
1  user 2  [0.3, 0.3, 0.4]      0  [0.4, 0.2, 0.4]  0.231        0.9      2
2  user 3  [0.4, 0.4, 0.2]      0  [0.4, 0.2, 0.4]  0.231        0.9      2
3  user 4  [0.2, 0.1, 0.7]      2  [0.5, 0.1, 0.4]  0.411        0.8      1
4  user 5  [0.5, 0.3, 0.2]      1  [0.5, 0.1, 0.4]  0.342        0.6      2

Now define functions to calculate the S score:
def l_delta(z1, z2):
    return [a1 - a2 for (a1, a2) in zip(z1, z2)]

def inner(z1, z2):
    return sum([a1 * a2 for (a1, a2) in zip(z1, z2)])

def s_score(row):
    delta = l_delta(row['x2'], row['x1'])
    num = inner(delta, delta)
    return 1/row['count'] + num / row['p2']

Finally, apply these functions to each row in the joined matrix:
joined['s_score'] = joined.apply(s_score, axis=1)
print(joined[['user', 's_score']])

Result:
     user   s_score
0  user 1  0.909357
1  user 2  0.586580
2  user 3  0.846320
3  user 4  1.437956
4  user 5  0.733918

A: Similar answer to @The Photon, where we (1) merge df1 and df2, (2) calculate k with groupby (3) calculate (x2-x1) inner product with itself
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'user': ['user 1', 'user 2', 'user 3', 'user 4', 'user 5'],
                    'x1': [[0.2, 0.3, 0.5],[0.3, 0.3, 0.4],[0.4, 0.4, 0.2],[0.2, 0.1, 0.7],[0.5,0.3,0.2]],
                    'group': [1, 0, 0, 2, 1]})

df2 = pd.DataFrame({'group': [0, 1, 2],
                    'x2': [[0.4, 0.2, 0.4],[0.5, 0.1, 0.4], [0.5, 0.1, 0.4]],
                    'p2': [0.231, 0.342, 0.411],
                    'threshold': [0.9, 0.6, 0.8]})

#merge df1 and df2 into a single table
merged_df = df1.merge(df2)

#calculate the number of unique users per group (k)
merged_df['k'] = merged_df.groupby('group')['user'].transform('nunique')

#calculate x2-x1 for each user (convert to numpy array for vectorized subtraction)
x2_sub_x1 = merged_df['x2'].apply(np.array)-merged_df['x1'].apply(np.array)

#calculate (x2-x1)T(x2-x1) for each user (same as squaring each term and summing)
numerator = x2_sub_x1.pow(2).apply(sum)

#calculate S from your formula and add it as a column to the merged table
merged_df['S'] = (1/merged_df['k'])+(numerator/merged_df['p2'])

Final merged table
    user    x1  group   x2  p2  threshold   k   S
0   user 1  [0.2, 0.3, 0.5] 1   [0.5, 0.1, 0.4] 0.342   0.6 2   0.909357
1   user 5  [0.5, 0.3, 0.2] 1   [0.5, 0.1, 0.4] 0.342   0.6 2   0.733918
2   user 2  [0.3, 0.3, 0.4] 0   [0.4, 0.2, 0.4] 0.231   0.9 2   0.586580
3   user 3  [0.4, 0.4, 0.2] 0   [0.4, 0.2, 0.4] 0.231   0.9 2   0.846320
4   user 4  [0.2, 0.1, 0.7] 2   [0.5, 0.1, 0.4] 0.411   0.8 1   1.437956


text:
Q: How to set a Swift Package in Debug Configurations only using Swift Package Manager With CocoaPods, we can set the following configurations:
pod 'SourceModel', :configurations => ['Debug']

Is there any way to do the same with Swift Package Manager?

A: I remember a proposal request that was supposed to support it and was supposed to be implemented in Swift 5.3 but I'm not sure it was fully implemented. Nevertheless, here the link to the proposal request
SE‐0273


text:
Q: Is it possible to use *args in a dataclass? I recently started using dataclasses and they will be a nice addition to 3.7.  I'm curious if or how it is possible to recreate the same functionality of this class using dataclasses.
class Nav(object):
    def __init__(self, name:str, menu, page, *submenus):
        self.name = name
        self.menu = menu
        self.page = page
        self.submenus = submenus

foo = Nav("name", "menu", "page")

This doesn't work. Raises Exception TypeError: __init__() missing 1 required positional argument: 'submenus'
@dataclass
class Nav(object):
    name:str
    menu: Any
    page: Any
    submenus: tuple

foo = Nav("name", "menu", "page")

I assume this is because the class doesn't have the instructions to do the unpacking of the arguments.  Is there some way to instruct the dataclass decorator that submenus needs to be unpacked?

A: I see in the PEP an example of how to override the __init__.

Sometimes the generated init method does not suffice. For example,
  suppose you wanted to have an object to store *args and **kwargs:
@dataclass(init=False)
class ArgHolder:
    args: List[Any]
    kwargs: Mapping[Any, Any]

    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

a = ArgHolder(1, 2, three=3)


text:
Q: Modify my code - which takes the first sentence of the post and use it as a h2 tag - to work outside the loop My code takes the first sentence of a post and places it's content inside a variable. The problem is it works only inside the loop.
I need help making this code outside the loop, becouse I want to use the posts first sentace as description in the header.php
Here it is:
<? ob_start();
the_content();
$old_content = ob_get_clean();
$content = strip_tags($old_content);
$match = null;
preg_match('/(.*?[?\.!]{1,3})/', $content, $match);
$first_sentence = $match[1];
$the_rest = substr($content, strlen($first_sentence));
if ( $first_sentence != '' && $the_rest != '' ){
   echo '
'.$first_sentence.'
';
   echo '
'.$the_rest.'
';
} ?>

One more thing, it would be perfect to keep the posts formating in this code. Any ideea how I can do that?
Ty very much, take care!

A: To get post info outside the regular loop, you can use WP Query
Reference
In your example you can try something like;
$firstsentance = new WP_Query();
$firstsentance->query('posts_per_page=-1');  // add additional  query parameters as needed, this will query all posts
$old_content = the_content()';

//do your php stuff here

endwhile;


text: Q: How to display number of remaining days in Temporary Login Without Password plugin? I Use Temporary Login Without Password plugin in wordpress. I need to display number of remaining days in front end to users. Please help me.


text:
Q: Как получить значение по ключу из строки (String)? Всем доброго времени суток!
После сканирования QR-кода, и раскодирования данных я получаю такую строку (String):
D/vResult: {"Command":"101","ContractorGUID":"{29545D4D-7AC9-4FCB-9E5C-B7AF4D9A70B5}"}
Мне необходимо извлечь значение ключа ContractorGUID. В данный момент, для этого я использую обрезание строки (.substring):
vResult.substring(35, vResult.length() - 2)
Вопрос: Есть ли какое-то более простое решение этой задачи? Что-то по типу метода .getString, как в JSONObject.

A: Можно воспользоваться любой удобной библиотекой работы с JSON и получить результат:
String vResult = "{\"Command\":\"101\",\"ContractorGUID\":\"{29545D4D-7AC9-4FCB-9E5C-B7AF4D9A70B5}\"}";
System.out.println("vResult: " + vResult);

try {
    org.json.simple.parser.JSONParser parser = new org.json.simple.parser.JSONParser();
    org.json.simple.JSONObject result = (org.json.simple.JSONObject) parser.parse(vResult);
    String value = (String) result.get("ContractorGUID");

    System.out.println("value: " + value);

} catch (org.json.simple.parser.ParseException e) {
    System.out.println("Error: " + e);
}

Консоль:
vResult: {"Command":"101","ContractorGUID":"{29545D4D-7AC9-4FCB-9E5C-B7AF4D9A70B5}"}
value: {29545D4D-7AC9-4FCB-9E5C-B7AF4D9A70B5}

A: String[] parts = vResult.split("ContractorGUID":"{:", 2);
System.out.println(parts[1]);

A: Можно регуляркой вытащить:
String vResult = "{\"Command\":\"101\",\"ContractorGUID\":\"{29545D4D-7AC9-4FCB-9E5C-B7AF4D9A70B5}\"}";
System.out.println("vResult: " + vResult);

java.util.regex.Pattern p = java.util.regex.Pattern.compile("^.+ContractorGUID\":\"(\\{.+\\})\"}$");
java.util.regex.Matcher m = p.matcher(vResult);

String value = m.matches() ? m.group(1) : null;
System.out.println("value: " + value);

Консоль:
vResult: {"Command":"101","ContractorGUID":"{29545D4D-7AC9-4FCB-9E5C-B7AF4D9A70B5}"}
value: {29545D4D-7AC9-4FCB-9E5C-B7AF4D9A70B5}


text:
Q: Reload listview when insert into database is complete or on back button Android Hi guys i'm really stuck on this and i'd appreciate help .I am inserting into a mysql database and when completed inside the button i am calling finish and it's going back to main activity but the list is not refreshing ?i tried to dothe OnResume and onRestart but the list is not showing at all ?
this is my  insert button  (main activity is called businessSide.java)
 //Add offer when button is clicked  and send  business id and business email to business side
        Button button = (Button) findViewById(R.id.btnOffer);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String serverURL = "http://10.0.2.2/Codes/AddOffer.php";
                offerName = editNameText.getText().toString();
                offerLocation = editLocationText.getText().toString();
                offerDescription = editDescriptionText.getText().toString();
                offerType=type;
                Intent i = getIntent();
                businessId = i.getStringExtra("number");
                businessEmail = i.getStringExtra("email");

                new SummaryAsyncTask().execute((Void) null);
                Toast.makeText(getApplicationContext(), "You have successfully placed a new offer ", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Add_offer.this,BusinessSide.class);
                intent.putExtra("number", id);
                intent.putExtra("email", businessEmail);
                startActivity(intent);
                finish();
            //    onBackPressed();

            }
        });
    }