text:
Q: Flutter huge app size in iOS compared with React Native original I've recreated a simple app that was originally made in React Native with 5MB file size on the app store. The app has no images or anything of any particular size, but it does use Admob ads.
After uploading it to the app store the build is showing as 35MB...not sure what the reason is but it when opening the package contents of the build archive it seems that a bunch of dylib files in SwiftSupport/iphoneos are created that are very large. that's the biggest folder in the archive anyway. I think it has to do with the Pods folder created in order to use Admob.
I'm guessing it can never be as small as the React Native original app but surely it should not be seven times the size...is there some way to remove the SwiftSupport files or another way to shrink it?
EDIT: Also in the Runner project folder in the build archive in Frameworks there are loads of Swift dylib files in there too that are large. Really all the space is being taken up by these Swift support dylib files...
Just built the app for Android and it's 8.33MB so quite a difference there, even though both versions of course use Admob.

A: This isn't really related to Flutter. Every iOS app containing code that wants to support iOS 11 and lower, needs to contain additional flutter libraries.
You can disable this in Xcode by setting "Always Embed Swift Standard Libraries" to false, and raising the deployment target to iOS 12.
Example of my flutter app with respect to different deployment targets. There is no change in build setting but deployment target only. iOS 13 does not include swift libraries with the build.
iOS version -> App build size
10 -> 127.8 MB
11 -> 127.8 MB
12 -> 90.9 MB
13 -> 49.6 MB

A: I have two sources: first [1] is titled 'Flutter vs Swift' and second [2] 'How to enable swift support for existing project in flutter'. Reading the both we observe flutter and swift do not have to co-exist and observing the latter we can see how it is enabled with a flag when creating the IOS package. I would first check that IOS folder is created without swift reference.
Third link [3] shows that Admob usage can be done in dart only.
About size, I am not sure though if using dart and disabling Swift would 100% make the trick. Flutter vs Swift link [1] has a native Swift app and 'comparison' equal Flutter app and conclusion was the size of flutter app was doubled about that of Swift app. And sizes where around 20 and 50 MB respectively, Flutter being the biggest.
Edit
It shows up the Swift is part of the plugin / module you use and thus cannot be easily just removed. About the size, Flutter app is normally already bigger than app with Swift and now the solution combines the both. Rise in size is as espected.
[1] https://blog.codemagic.io/flutter-vs-swift/
[2] How to enable Swift support for existing project in flutter
[3] https://flutterawesome.com/easily-implement-ads-into-a-flutter-app/


text:
Q: airflow using billiard for multiprocessing stuck I found in answer that can use billiard for multiprocessing in airflow, as python multiprocessing cannot pickle and joblib Parallel can only use threading mode. I tried billiard Pool map. The program just stuck when running this part and no error raised.
I'm using the newest version 2.5.0 airflow.
How to make it work and what is the right way to do multiprocessing in airflow tasks? Thanks very much!
import pendulum
from billiard import Pool
from airflow import DAG
from airflow.decorators import task

with DAG(dag_id='ttest',
         schedule_interval="40 * * * *") as dag:
    @task(task_id='te')
        def test_task(ds=None, **kwargs):
            def test(l):
                return sum(l)

            a = [[1,2], [2,3], [3,4]]
            print('start pool')
            with Pool(2) as pool:
                res = pool.map(test, a)
            print(res)

        t = test_task()
        t

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the simplest way to backup a large (Aperture) photo library automatically to a different physical location (presumably through the cloud)? I have about 10k pictures, (close to 50GB) on my MacBook Pro, all stored in an Aperture Library.
I run time machine (on Snow Leopard if it matters), so they're backed up hourly to my time capsule, plus I burn DVDs annually.   But we had a fire scare recently, and it reminded me that both the DVDs and the Capsule are in the same physical location as the laptop, making them useless if the apartment getting destroyed is the problem (rather than the drive failure I was focused on originally).
I can obviously store the DVDs in a location outside the house, but really don't want to risk a year's data, and it's too annoying to burn all those disks monthly, etc.
Is there an automatic solution that will back up this much data automatically somewhere offsite?   I'm willing to pay something in theory, but the paid idisk solution on MobileMe doesn't seem scalable, and I don't trust its longevity.  Ideally, I want something I don't have to run myself periodically.

A: If you're going to pay you can also go with Dropbox. They have 50GB for $100 a year. I love how fast they synch.

A: Try jungle disk https://www.jungledisk.com/personal/ it backs up to amazon and/or rackspace cloud.

A: Take a look at Carbonite or Mozy.  I have used Mozy on a PC and Mac and have >1TB backed up offsite for $5 a month.

A: Many people carry their laptops regularly between home and work. In those cases there is a very simple off-site backup solution: Just buy another external hard drive and keep it in your office. Whenever you are at work, plug it in and use it for backups. This way you will have full up-to-date backups in two different physical locations.


text:
Q: PHP:preg_replace function $text = "
<tag>
<html>
HTML
</html>
</tag>
";

I want to replace all the text present inside the tags with htmlspecialchars(). I tried this:
$regex = '/<tag>(.*?)<\/tag>/s';
$code = preg_replace($regex,htmlspecialchars($regex),$text);

But it doesn't work.
I am getting the output as htmlspecialchars of the regex pattern. I want to replace it with htmlspecialchars of the data matching with the regex pattern.
what should i do?

A: You're replacing the match with the pattern itself, you're not using the back-references and the e-flag, but in this case, preg_replace_callback would be the way to go:
$code = preg_replace_callback($regex,'htmlspecialchars',$text);

This will pass the mathces groups to htmlspecialchars, and use its return value as replacement. The groups might be an array, in which case, you can try either:
function replaceCallback($matches)
{
    if (is_array($matches))
    {
        $matches = implode ('', array_slice($matches, 1));//first element is full string
    }
    return htmlspecialchars($matches);
}

Or, if your PHP version permits it:
preg_replace_callback($expr, function($matches)
{
    $return = '';
    for ($i=1, $j = count($matches); $i<$j;$i++)
    {//loop like this, skips first index, and allows for any number of groups
        $return .= htmlspecialchars($matches[$i]);
    }
    return $return;
}, $text);

Try any of the above, until you find simething that works... incidentally, if all you want to remove is <tag> and </tag>, why not go for the much faster:
echo htmlspecialchars(str_replace(array('<tag>','</tag>'), '', $text));

That's just keeping it simple, and it'll almost certainly be faster, too.
See the quickest, easiest way in action here

A: If you want to isolate the actual contents as defined by your pattern, you could use preg_match($regex,$text,$hits);. This will give you an array of hits those bits that were between the paratheses in the pattern, starting at $hits[1], $hits[0] contains the whole matched string). You can then start manipulating these found matches, possibly using htmlspecialchars ... and combine them again into $code.


text:
Q: Why doesn't this object attribute print as a list? My class definition:
class node:
    def __init__(self, parent, daughters, edge):
        self.parent = parent
        self.daughters = daughters
        self.edge = edge
        trie.append(self)
        self.index = len(trie) - 1
        trie[parent].daughters.append(self)

When I do:
    trie = [node(0, [], 0)]
    currentNode = trie[0]
    print('Current Node: ', currentNode.parent, currentNode.daughters, currentNode.edge, currentNode.index)

it prints everything correctly except the 'daughters'. Index is an integer, edge is an integer, parent is an integer, but 'daughters' should be a list. Instead it gives me some sort of object syntax:
Current Node:  0 [<__main__.node object at 0x100786dd8>] 0 0

Why is it having difficulty with passing a list?

A: It is printing a list you can see the square brackets in the output, [<__main__.node object at 0x100786dd8>], which is a list with 1 node object in it
You can also confirm by looking into the type of that attribute with type(currentNode.daughters) e.g. by printing the type out

A: To fix this problem , to have a meanningful text instead of <main.node object at 0x100786dd8> , you can provide the class with a __str__ function :
class node:
def __init__(self, parent, daughters, edge):
    self.parent = parent
    self.daughters = daughters
    self.edge = edge
    trie.append(self)
    self.index = len(trie) - 1
    trie[parent].daughters.append(self)
def __str__(self):
    return "some string !"


text:
Q: On generical domains: Riemann integrable $\Rightarrow$ Lebesgue integrable? If I have correctly understood and been able to generalise the proof that I found in Kolmogorov-Fomin's Элементы теории функций и функционального анализа for the case of $n=1$, I know that, if $R=\prod_{i=1}^n[a_i,b_i]\subset\mathbb{R}^n$ and $f:R\to\mathbb{R}$ is Riemann integrable on the bounded set $R$, then it also is Lebesgue integrable and the two integrals are the same:$$(R)\int_R f(x_1,\ldots,x_n)dx_1\ldots dx_n=\int_R fd\mu$$where $\mu$ is the usual Lebesgue measure defined on measurable subsets of $\mathbb{R}^n$.
$f:D\to\mathbb{R}$ is defined as Riemann integrable on a generical domain $D\subset\mathbb{R}^n$ when the function $\bar{f}:R\to\mathbb{R}$ (with $R$ as above and such that $D\subset R$) defined by $$\bar{f}(\boldsymbol{x}) = \begin{cases} f(\boldsymbol{x}), & \boldsymbol{x}\in D \\ 0, &\boldsymbol{x}\in R\setminus D \end{cases}$$is Riemann integrable on $R$. My question is: if $f$ is Riemann integrable on a generical domain $D$, can we say that it also is Lebesgue integrable on $D$? I think the only obstacle to overcome is veryfying whether $D$ is $\mu$-measurable, because Lebesgue integrals are only defined on measurable subsets, as far as I know, but I cannot overcome that. A search in this site gives many related results, but I have only found cases where $D=[a,b]\in\mathbb{R}$. I thank any answerer very much!

A: It is a matter of definition.
Let's decide, as for Riemann, that $f$ is called $\,$ L-integrable over $D\,$ if $\,\bar f \,$ is $\,$L-integrable over $R$ (according to the usual definition) and that $$\int_D f=\int_{R} \bar f$$ Then the statement (R-integrability $\Rightarrow$ L-integrability) is true also for arbitrary (bounded) sets.
The set $D$ doesn't need to be measurable !
All this because of the validity of the following statement:
Let $E$ and $E'$ be measurable sets with $E \subset E'$. Let $f$ be a function on $E$ and let $g$ be the function defined on $E'$ by $$g(\mathbf x) = \begin{cases} f(\mathbf x)\quad\text {if} \quad \mathbf x\in E \\ 0 \;\,\qquad\text {if}\quad\mathbf x\in E'\setminus E \end{cases}$$ then $f$ is L-integrable on $E\,$ iff $\,g$ is L-integrable on $E'$ and, if so, $$\int_E f=\int_{E'} g$$ So the above definition is independent of $R$ and reduces to the usual one if $D$ is measurable.


text:
Q: Naming convention for context-manager classes ("with" blocks) Is there a general naming convention for classes or functions that are meant to be used in with block such as
with CreateSomeContext() as x:
    ...

? Something that signals that the class or the result of a function should be used with with?

A: In the respective PEP 0343, there is a mention of two conventions:

The tense used in the names of the example contexts is not
      arbitrary. Past tense ("-ed") is used when the name refers to an
      action which is done in the __enter__ method and undone in the
      __exit__ method. Progressive tense ("-ing") is used when the name refers to an action which is to be done in the __exit__ method.

A: There's no naming convention (open, socket.create_connection, urllib.request.urlopen all return context managers which can be used with with) but context managers will have the  __enter__  and __exit__ methods.
Note: in the case of open("file", "w"), the return value (the file object) is the context manager, not open.


text:
Q: Why does my Ruby thread demo not use both cores? Hopefully this screenshot will explain my question:
a = Thread.new { loop {} }
b = Thread.new { loop {} }
a.join

Ruby threads demo CPU usage http://img7.imageshack.us/img7/9858/rubycores.png
So how come both of my cores aren't maxed out? No matter how many threads I use, it's the same each time; the total CPU usage never seems to exceed 52%.
>ruby -v
ruby 1.8.6 (2010-02-04 patchlevel 398) [i386-mingw32]

A: It looks like you are using MRI, which is incapable of running threads in parallel. At the moment, the only production-ready Ruby implementations which can run threads in parallel are JRuby and IronRuby.
Remember, if you want threads to actually run in parallel, then every layer in the stack must be able to do that. Take JRuby, for example: JRuby can run Ruby threads in parallel. However, it implements threads by mapping them to JVM threads, so if the JVM is incapable of running threads in parallel (and there are some for which this is the case), then the fact that JRuby can run Ruby threads in parallel doesn't help you one bit. Many JVMs, in turn, map JVM threads to OS threads. And again: if the OS isn't capable of running threads in parallel, there's nothing the JVM can do. And last but not least: if there's only one processor, the whole exercise is pointless anyway.

A: I think this answer is awesome.
Does ruby have real multithreading?
Since your are using Ruby 1.8.6, the MRI Implementation. This quotation form the URL above explain why only one core is used.

MRI implements Ruby Threads as Green Threads within its interpreter. Unfortunately, it doesn't allow those threads to be scheduled in parallel, they can only run one thread at a time.

Note that MacRuby (sort of a port of YARV) removed the GIL recently. So your demo code will use both cores with MacRuby 0.5 or later version. For now it is the only Ruby Implementation that can run in parallel that not depending on JVM or CLR.

A: The main thing to remember is that there is a difference between Ruby (language) and Ruby (implementation). You don't make it clear which you mean, but as you are having problems I assume you mean Ruby (implementation).
Looking at some previous answers :
Ruby 1.9.1: Native threads in Ruby 1.9.1, whats in it for me?

The ruby threads in 1.9 are native, but they have been "slowed down" to allow only one thread to run at a time. This is because it would confuse existing code, if the threads really ran in parallel.

Does ruby have real multithreading?
This gives a fantastic explanation of Ruby Threading on various Ruby VMs.

A: What version of ruby are you using, and which interpreter?  (JRuby, "regular ruby", etc?)
Not all ruby interpreters can take advantage of multiple cores/processors.


text:
Q: Content Tagging
I'm trying to create a small Web App to categorize certain type of YouTube videos, when users submits a video they will choose what categories this video falls under and they will tag it with ready-made tags, for example:
Video one - Category: Ad - Tags: cute, funny, has animal in it.
I'm trying to sketch my Database for that (I'm using MySQL), so far I have two ideas.

Idea 1:
Table Videos with ID and Category columns, another table Tags with ID and Tag columns while Videos.ID and Tags.ID are linked together. So when the user tries to filter search results by tags, the query will have more conditions (AND Tag = 'something' AND Tag = 'other thing').

Idea 2:
One table Videos with Category and Tags columns, tags are stored as a string separated by commas, when the user tries to filter search results by tags, the query will more conditions (AND Tags LIKE '%something%' AND Tags LIKE '% other thing%).

 So the question is: Is there any better method? I already think that the 1st one is wasteful (Each video might have up to 40 ready-made tags) and the 2nd one is clumsy. If not, which one do you think is better?

A: Creating a additional table linking video id and tag id together is the correct solution. Filtering is done by creating additional INNER JOIN conditions. A comma separated list just won't do - it drastically limits your selection and query possibilities.

A: Idea 1 looks good. Creating a separate table for storing tags helps in selection.


text:
Q: An upper bound of the probability involving Bernoulli on the power I would like to find an upper bound of
$\text{Pr}\{a^{u_1+u_2+u_3+u_4}+a^{l_1+l_2+l_3+l_4}\leq a^{u_1+u_2+l_1+l_2}+a^{u_3+u_4+l_3+l_4}\}$,
where $a>1$ and $l_1,\cdots,l_4$ follows i.i.d Bernoulli$(p)$, $u_1,\cdots,u_4$ follows i.i.d. Bernoulli$(p(1+\delta))$ with $\delta>0$.
I tried Chernoff bound, but it looks very messy. Are there any specific concentration bounds that can be applied to this type of problem?


text:
Q: graphics.h programs not running in Dosbox Windows 7 environment I have installed Dosbox to run Turbo C in it. But my graphics.h programs are not executing in it. I am getting Linker Error which says"Undefined sumbol initgraph in module..." and so on.

A: The problem you are facing is quite simple to solve.
Open your Turboc IDE
Click on options
click on linker
click on libraries
mark the graphics option(a cross mark usually)
now run.

A: You are not linking the required graphics library. It has been quite a while since I last used Turbo C, but if I remember correctly, you can simply configure the toolchain to link the graphics lib in the linker options which are easily accessible from the Turbo C "IDE".

A: If You are getting Error in Windows XP that Undefined symbol initgraph in module
then follow the Steps :

*

*Go to Console

*Go to Options

*Go to Linker

*Go to Libraries

*Make "X" Mark on Graphics Library


text:
Q: C++ shader question I am using Nvidia CG and Direct3D9 and have the question about the following code.
It compiles, but doesn't "loads" (using cgLoadProgram wrapper) and the resulting failure is described simplyas D3D failure happened.
It's a part of the pixel shader compiled with shader model set to 3.0
What may be interesting is that this shader loads fine in the following cases:
1) Manually unrolling the while statement (to many if { } statements).
2) Removing the line with the tex2D function in the loop.
3) Switching to shader model 2_X and manually unrolling the loop.

Problem part of the shader code:
float2 tex = float2(1, 1);
float2 dtex = float2(0.01, 0.01);

float h = 1.0 - tex2D(height_texture1, tex);
float height = 1.00;

while ( h < height )
{
    height -= 0.1;
    tex += dtex;

    // Remove the next line and it works (not as expected,
    // of course)
    h = tex2D( height_texture1, tex );
}

If someone knows why this can happen or could test the similiar code in non-CG environment or could help me in some other way, I'm waiting for you ;)
Thanks.

A: I think you need to determine the gradients before the loop using ddx/ddy on the texture coordinates and then use tex2D(sampler2D samp, float2 s, float2 dx, float2 dy)
The GPU always renders quads not pixels (even on pixel borders - superfluous pixels are discarded by the render backend). This is done because it allows it to always calculate the screen space texture derivates even when you use calculated texture coordinates. It just needs to take the difference between the values at the pixel centers.
But this doesn't work when using dynamic branching like in the code in the question, because the shader processors at the individual pixels could diverge in control flow. So you need to calculate the derivates manually via ddx/ddy before the program flow can diverge.


text:
Q: HTML canvas changing colors unexpectedly I am trying to make a grid with HTML canvas. I have written the following code. Everything works correctly at first, but as soon as the window is resized, the color of the grid lines changes color for some reason.
If you are unable to reproduce the behavior, here is a video of the behavior.

var canvas = document.querySelector('canvas');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var ctx = canvas.getContext('2d');

window.addEventListener('resize', function() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
});

var xOffset = 0;
var yOffset = 0;
var gridSize = 75;

ctx.lineWidth = 2;

function draw() {

  ctx.fillStyle = '#e8e8e8';
  ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);

  ctx.strokeStyle = '#7a7f7e';
  ctx.beginPath();
  ctx.moveTo(0, 0);
  for (var i = 0; i < window.innerWidth + gridSize; i += gridSize) {

    ctx.moveTo(i + xOffset % gridSize, 0);

    ctx.lineTo(i + xOffset % gridSize, window.innerHeight);
  }

  for (var i = 0; i < window.innerHeight + gridSize; i += gridSize) {

    ctx.moveTo(0, i + yOffset % gridSize);

    ctx.lineTo(window.innerWidth, i + yOffset % gridSize);
  }
  ctx.stroke();

  window.requestAnimationFrame(draw);
}

window.requestAnimationFrame(draw);
<canvas></canvas>

A: I think the solution is to move the ctx.lineWidth = 2 inside the requestAnimationFrame. When I change the width manually I see the same behavior, the line width defaults. So here is working fiddle that solves your problem:
https://jsfiddle.net/ibowankenobi/skgn9q51/2/
function draw() {

  ctx.fillStyle = '#e8e8e8';
  ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
 ctx.lineWidth = 2;
......

I think this behavior is intended. So to get your lineWidth out you might need to resort to save() restore();


text:
Q: ASP.Net CascadingDropDown and EnableEventValidation="false" I have just got a CascadingDropDown from the AJAX Toolkit working with SelectedIndexChanged to redirect to a page passing a querystring of the selected value. I'm well chuffed!
However, I only got the SelectedIndexChanged event working by adding  EnableEventValidation="false" to the page. The problem is the CascadingDropDown will be placed in the MasterPage of my website as a product selector.
I'm not keen on adding EnableEventValidation="false" to my MasterPage! I've looked at the ClientScriptManager.RegisterForEventValidation method on MSDN and it's gone right over my head.
What's the best thing to do? Is there a simple example of using ClientScriptManager.RegisterForEventValidation?
Cheers...
EDIT: Here's the code:
<asp:ScriptManager ID="asm" runat="server" />

    Series:     <asp:DropDownList ID="SeriesList" runat="server" />

    Printers:   <asp:DropDownList ID="PrinterList" runat="server"
                 onselectedindexchanged="PrinterList_SelectedIndexChanged"
             AutoPostBack="True" />

    <asp:CascadingDropDown ID="ccd1" runat="server"
        ServicePath="CascadingDropdown1.cs.asmx" ServiceMethod="GetSeries"
        TargetControlID="SeriesList" Category="Series"
        PromptText="Select Series" />
    <asp:CascadingDropDown ID="ccd2" runat="server"
        ServicePath="CascadingDropdown1.cs.asmx" ServiceMethod="GetPrintersForSeries"
        TargetControlID="PrinterList" ParentControlID="SeriesList" Category="Printer"
        PromptText="Select Printer" />

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="PrinterList" EventName="SelectedIndexChanged" />
        </Triggers>
    </asp:UpdatePanel>

And here's the event:
protected void PrinterList_SelectedIndexChanged(object sender, EventArgs e)
        {
            int printerID = Convert.ToInt32(PrinterList.SelectedValue);
            System.Web.HttpContext.Current.Response.Redirect("Default.aspx?PID="+printerID);
        }

A: The answer to this pain in the neck problem is custom dropdown controls!
So to close off this question and hopefully help  someone else get round this issue here is what I did:
I created a cs file called NoValidationDropDownList.cs with the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace My.Namespace.Controls
{
    public class DdlNoEventValidation : DropDownList
    {
    }
}

Then on the aspx page where the dropdown controls reside (in my case a MasterPage) I placed this:
<%@ Register TagPrefix="asp" Namespace="My.Namespace.Controls" %>

Next I amended the cascade dropdown boxes like so:

<asp:DdlNoEventValidation ID="DD1" runat="server" />

<asp:DdlNoEventValidation ID="DD2" runat="server"
   onselectedindexchanged="My_SelectedIndexChanged"
   AutoPostBack="True"
   />

As I understand it, creating a custom dropdown control circumvents event validation. In this way you don't need to switch off event validation for the entire page. In my case as the controls are sitting in the MasterPage, event validation would have been switched off for the entire site!
Alas this is not my original work so here is the original reference: http://johanleino.wordpress.com/2009/11/17/cascadingdropdown-casues-invalid-postback-or-callback-argument-error/
Thanks Johan!
Hope this helps...


text:
Q: Clicking on Image Link with Selenium webdriver java I have looked at the answers to similar questions and it seems like the code that I have should work but I get "Cannot click on element" error when the code invokes click on the web element.
Following is html markup segment

    Manage Users

        ...

Java code to locate the link is:
By xpath=By.xpath("//a[contains(@title,'Manage Users')]/img");
WebElement manageUsers = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(xpath));
manageUsers.click();

It finds the element but I get error:
org.openqa.selenium.ElementNotInteractableException: Cannot click on element
The ids are generated dynamically so we can't find by id and image source is used by multiple links.
Thank you for your help.
* Update *
The problem was solved with help from JeffC and Xwris. JeffC's last comment showed that there are multiple nodes being found. So, I added following code:
       List<WebElement> manageUserImages=driver.findElements(xpath);
   for (WebElement manageUserImage:manageUserImages) {
       if (manageUserImage.isDisplayed()) {
           manageUserImage.click();
       }
   }

Since there is only element displayed at one time with "Manage Users" as title, this finds the correct elements and delivers the desired results.
@JeffC, if you can post an answer with your comment, we can mark that answer as the correct answer.
Thanks again to everyone who helped.

A: It looks your xpath is wrong.
Personally I would start from the div and the drill down to the actual  tag.
In some cases where your web-element sits under a
 tag, I would go even further up the tree and select a div which is not hidden.
i.e you instruct it to search for  under the specific

Who told you you can select only by id? You can use anything! :)
This should work.
//div[@class='x-tree-node-item']//a[@title='Manage Users']

This should work as well. Correct usage of 'contains' is as follows:
//div[@class='x-tree-node-item']//a[text()[contains(.,'Manage Users')]]

Hope this helps!
PS. notice that text contains is case-sensitive and will match partial text.
So if you searched for:
//a[text()[contains(.,'age User')]]

it will still be a successful match!

Update after OP's comments:

You don't actually need xpath helper. You just hit F12 in your browser and then CTRL+f so you open a search field at the bottom. Please see my example on how I locate the title of your question with partial text match ('Image').
Also notice next to xpath where it says 1 of 1 (meaning that our element is unique). Try to do the same for your case. I suspect that you need to go higher up the tree and start from an earlier
 so you can locate the rest.

A: Leave off the "/img" part of your locator.  You want to click the anchor (a) not the image itself.
  By xpath=By.xpath("//a[contains(@title,'Manage Users')]");
   WebElement manageUsers = (new WebDriverWait(driver, 10))
           .until(ExpectedConditions.presenceOfElementLocated(xpath));
   manageUsers.click();

Alternatively, the locator could be: //a[@id='m-22']


text:
Q: how to add proportion label on the stacked bar chart in python bar chart I have plotted stacked bar chart and want to add text indicating its proportion on the bar but do not know how I can add those labels on.
My codes are,
tps = df3[df3['Action Type_new']!='NA'].pivot_table(values=['Column'],
                  index='year',
                  columns='Action Type_new',
                  aggfunc='sum')

tps = tps.div(tps.sum(1), axis=0)
tps.plot(kind='bar', stacked=True)

and my tps looks like, (it is pivot table so, it has multi index)
MultiIndex(levels=[['Column'], ['Less Severe', 'Severe']],
           labels=[[0, 0], [0, 1]],
           names=[None, 'Action Type_new'])

Column
Action Type_new Less Severe Severe
year
1990    0.208409    0.791591
1991    0.276577    0.723423
1992    0.281479    0.718521
1993    0.402501    0.597499
1994    0.430871    0.569129
1995    0.445519    0.554481
1996    0.509341    0.490659
1997    0.604371    0.395629
1998    0.716450    0.283550
1999    0.578597    0.421403

My current bar chart is like below.

A: Update using matplotlib 3.4.2
Thanks @TentonMcKinney
df1 = df['Column']
ax = df1.plot(kind='bar',stacked=True)
for c in ax.containers[::2]:
    ax.bar_label(c, label_type='edge', fmt='%0.1f', padding=10)
ax.legend(loc='lower right')

Output:

I think you want something like this:
Where df:
                     Column
Action Type_new Less Severe    Severe
Year
1990               0.208409  0.791591
1991               0.276577  0.723423
1992               0.281479  0.718521
1993               0.402501  0.597499
1994               0.430871  0.569129
1995               0.445519  0.554481
1996               0.509341  0.490659
1997               0.604371  0.395629
1998               0.716450  0.283550
1999               0.578597  0.421403

import matplotlib.pyplot as plt

df1 = df['Column']
ax = df1.plot(kind='bar',stacked=True)
for rec, label in zip(ax.patches,df1['Less Severe'].round(1).astype(str)):
    height = rec.get_height()
    ax.text(rec.get_x() + rec.get_width() / 2, height + .05, label,
           ha = 'center', va='bottom')
plt.legend(loc='lower right')

Output


text:
Q: Using MEF in a class library with ASP.NET MVC 3 I am in the process of extending a solution based on MVC 3.
Basically, The solution consists of an MVC 3 project along with some class library projects to manage Business/Data Access.
I'm trying to use MEF to make the application plugin-based. for example, I have a UserManager class in the dll project and I have defined my plugins as follows:
[ImportMany]public List<IUserHooks> Plugins {get; set;}
foreach (var plugin in Plugins)
{
    Plugin.DoTheJob();
}

As you can see, the class is separated from MVC project and controllers. The list is defined my UserManager class.
I know the best approach would be to make UserManager use MEF as well (Probably initialize it in controller's ctor like public MainController(IUserManager UserManager)), But since I just want to add plugin support to the solution, and not writing from scratch, I prefer the fastest shortcut.
How should I define my MEF container object to be able to use it in my class library. Is it necessary to make MVC application using MEF as well? I'd prefer the approach where minimum modification would be necessary to the MVC application.

A: MVC3 has baked in support for service location. If you don't want to redefine some of your base classes, but simply want to extend, you could add an instance of a IDependencyResolver that uses MEF. That way you can use that as a base to extend your application. I've written an example on my blog.
Using MVC3's built in architecture allows you to configure your CompositionContainer in your startup and expose it to the rest of the infrastructure.
But, the reality is you probably don't want to be exposing your container in your library. In fact, the only thing you should be doing is simply marking your exports. The reason you can get away with this with MEF is that it is included in the BCL for .NET 4.0. By not coupling your classes to MEF (or infact, coupling your classes to a service locator or inversion-of-control container either), it makes your code more portable, testable and decoupled.


text:
Q: Cache a product collection by a key? I have added a collection to buff out related products with extra "most viewed" products from a products top level category.
This is a slow query and takes about 0.2 seconds so was wondering if this collection can be cached with a key based on top level category so I can query if this collection exists and add products to the current related products collection from the cached collection instead of rerunning it each time?
Something like below but this was for Magento 1:
https://stackoverflow.com/questions/3755104/how-to-cache-a-collection-in-magento
There could be anything up to 4000 products that could benefit from pulling products from this cached collection in some cases.
    if($this->_cacheType->load($categoryMain)) {
        $collection = unserialize($this->_cacheType->load($categoryMain));
    } else {
        $collection = $this->mostViewedCollection->addAttributeToSelect(
            ['name','sku','price']
        )->addViewsCount()->setStoreId(
            $storeId
        )->addStoreFilter(
            $storeId
        )->setPageSize(
            $count
        )
        ->addCategoriesFilter(array('in' => $categoryIds));
        $this->_cacheType->save(serialize($collection), $categoryMain, [\Harrigo\AutoAssociatedProducts\Model\Cache\Type::CACHE_TAG], 86400);
    }

The collections however throw an error when being sereialized which leaves me stuck. I do not want to turn it into an array as guess i'll have to rebuild items.phtml to render the collection. I have actually noticed that the main slow down seems to be elsewhere after timing the collections but I am still interested in this and what the proper way to achieve something like above would be.

A: Cache an array of entity ids and reload the collection from that. Also, if the page size is variable, add that to the identifier. See below.
$cache_id = $categoryMain . '_' . $storeId . '_' . $count;
if($this->_cacheType->load($cache_id)) {
    $entity_ids = unserialize($this->_cacheType->load($cache_id));
    $collection = $this->mostViewedCollection
      ->addAttributeToSelect(['name','sku','price'])
      ->addFieldToFilter('entity_id', ['in' => $entity_ids])
      ->addViewsCount();
} else {
    $collection = $this->mostViewedCollection->addAttributeToSelect(
        ['name','sku','price']
    )->addViewsCount()->setStoreId(
        $storeId
    )->addStoreFilter(
        $storeId
    )->setPageSize(
        $count
    );

    $entity_ids = [];
    foreach ($collection as $c) {
        $entity_ids[] = $c->getId();
    }

    $this->_cacheType->save(serialize($entity_ids), $cache_id, [\Harrigo\AutoAssociatedProducts\Model\Cache\Type::CACHE_TAG], 86400);
}

Though I'm having some thoughts that the speed issue might be related to addViewsCount. Might be a good idea to add a cache to that method. Alternatively, a second cache_id with an array of view counts matched to entity_ids and looped into that collection could do the trick if you don't want to plugin to Harrigo\AutoAssociatedProducts.


text:
Q: Is this code broken or is there a bug in g++? For some strange reason g++ (versions 4.5.0 and 4.5.2) cannot compile this code:
bool somefunc() {
    return false;
}

class C {
  public:
    static const int a = 0;
    static const int b = 1;
};

class myclass {
  public:
    int check() {
        return somefunc() ? C::a : C::b;
        // if(somefunc()) return C::a; else return C::b;
    }
};

int main() {
    myclass obj;
    obj.check();
    return 0;
}

It gives me this error:
/tmp/ccyvvTUy.o:/home/mati/test.cpp:14: undefined reference to `C::a'
/tmp/ccyvvTUy.o:/home/mati/test.cpp:14: undefined reference to `C::b'
collect2: ld returned 1 exit status

What's strange if I change problematic line to the commented line it compiles fine.
Is it something wrong with my code and something I don't understand about C++ or is it just a bug in G++ ?

A: See 9.4.2/4:

If a static data member is of const integral or const enumeration
  type, its declaration in the class definition can specify a constant
  initializer which shall be an integral constant expression (5.19). In
  that case, the member can appear in integral constant expressions
  within its scope. The member shall still be defined in a namespace
  scope if it is used in the program and the namespace scope definition
  shall not contain an initializer.

There is some contention (I believe) as to the precise meaning of "used" although my understanding is roughly that the if program requires the address of the variable then it's "used" in this context. It doesn't seem unreasonable in my mind at all that changing the ternary to an if/else or changing optimization level could change the view of the program as seen by g++ thus causing the failure or success. Also note that it doesn't say anything about a required diagnostic if you violate the requirement here.
You can't go wrong by always defining your static members.

A: There is an ongoing debate on whether this code is actually legal or not.
Either way, according to some readings the constants actually do need to be defined before usage, not just declared. That is,
class C {
  public:
    static const int a = 0;
    static const int b = 1;
};

const int C::a;
const int C::b;

Or just use the enum hack that was used to accomodate older compilers (but which may after all be the only legal way):
class C {
  public:
    enum { a = 0, b = 1 };
};

A: Try defining it globally without optimisation.
const int C::a = 0;

A: change the following line
     return somefunc() ? C::a : C::b;
to
    return (somefunc() ? C::a : C::b);
It should compile.


text:
Q: How to handle identical ranks when performing quantile normalization? I have been looking at Wikipedia Wikipedia to understand quantile normalization algorithms and I have noticed, on their example, a difference between their results and the ones given by bioconductor's package preprocessCore.
In fact, when two values have the same rank, Wikipedia take the lowest index in the reference distribution, while preprocessCore seem to take a sort of average.
However, when used on big matrices, I have noticed that it is not the average of all the values of the reference distribution occupied by this "rank range" (of equal ranks).
How is this adressed? Why would one method be better than the other?
I understand that for small matrice, it has a huge impact on the variance of the samples, but for big matrice, the distribution should be much smoother and result in less discrepancy, right?


text:
Q: C# List of splitted strings I have the following problem.
I have these strings with whitespace between them.
"+name:string"            "+age:int"

I split them with this code:
List<string> stringValueList = new List<string>();
stringValueList = System.Text.RegularExpressions.Regex.Split(stringValue, @"\s{2,}").ToList<string>();

now the elements of List looks like this
"+name:string"
"+age:int"

Now I want to split these strings and create Objects.
This looks like this:
// Storing the created objects in a List of objects
List<myObject> objectList = new List<myObject>();
for(i = 1; i < stringValueList.Count ; i+=2)
{
   myObject object = new myObject();

   object.modifier = '+';
   object.name = stringValueList[i-1].Trim('+');   // out of the example the object.name should be "name"
   object.type = stringValueList[i];   // out of the example the object.type value should "string"

   objectList.Add(object);
}

At the end I should get two objects with these values:
List<myObject> objectList{ myObject object1{modifier = '+' , name ="name" , type="string"}, myObject object2{modifier='+', name="age" type="int"}}

But my result looks like this:
List<myObject> objectList {myObject object1 {modifier='+', name="name:string" type="+age:int"}}

So instead of getting 2 Objects, I am getting 1 Object. It puts both strings into the elements of the first object.
Can anyone help me out? I guess my problem is in the for loop because i-1 value is the first string in the List and i is the second string but I cant change this.

A:
I guess my problem is in the for loop because i-1 value is the first string in the List and i is the second string but I cant change this.

I don't know why you do i += 2, because apparently you want to split each string in two again. So just have to change that.
Use foreach(), and inside your loop, split your string again:
foreach (var stringValue in stringValueList)
{
    myObject object = new myObject();

    var kvp = stringValue.Split(':');

    object.modifier = '+';
    object.name = kvp[0].Trim('+');
    object.type = kvp[1];

    objectList.Add(object);
}

Of course this code assumes your inputs are always valid; you'd have to add some boundary checks to make it more robust.

A: Alternatively, you could expand your Regex formula to do the whole thing in one go.
For example, with (?<=")[+](.*?):(.*?)(?="), all you'd have to do is assign the matched group values.
foreach (Match m in Regex.Matches(stringValue, "(?<=\")[+](.*?):(.*?)(?=\")"))
{
    myObject obj = new myObject
    {
        modifier = '+',
        name = m.Groups[1].Value,
        type = m.Groups[2].Value
    };
    objectList.Add(obj);
}

A: It's interesting to see how others approach a problem. I would have done something like this:
public class MyObject
{
    public char Modifier { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }

    public static IEnumerable<MyObject> Parse(string str)
    {
        return str
        .Split(' ')
        .Where(s => string.IsNullOrEmpty(s) == false)
        .ToList()
        .ForEach(i =>
        {
            var sections = i.Remove(0, 1).Split(':');
            return new MyObject()
            {
                Modifier = i[0],
                Name = sections[0],
                Type = sections[1]
            };
        });
    }
}


text:
Q: Error 'libudunits2.a not found' when installing ggraph, Additional Error : object 'scale_type' is not exported by 'namespace:ggplot2' I ran into these two errors
'libudunits2.a not found' and Error : object 'scale_type' is not exported by 'namespace:ggplot2'
on Ubuntu 17.10 during an install of ggraph in Rstudio via
install.packages("ggraph").
I tried to find a solution online but it seems that a lot of people are having the same problem. I suspect this is similar in other versions of Ubuntu.

A: I solved the first error 'libudunits2.a not found'
 by installing libudunits2 at command line :
sudo apt-get install libudunits2-dev

I next got a new error when I returned to Rstudio:
Error : object 'scale_type' is not exported by 'namespace:ggplot2'
I came across an old post from github which worked for me. Install in Rstudio with:
devtools::install_github(c("hadley/ggplot2", "GuangchuangYu/ggtree"))

with the following command to install ggraph in Rstudio:
install.packages("ggraph")


text:
Q: Outlier detection for generic time series In this case, "generic" being the entire gauntlet of macroeconomic time-series that private and government statistical offices put out.
Some background - I recently started working at a data provider - we collect data releases and repackage them in a presumably more convenient and accessible fashion for our clients, and we have tens of thousands of data series (wouldn't be surprised if we topped a million, actually). As part of our QA process, we run the following outlier detection:
$X_t-X_{t-1} = E_t$
$\sigma^2$ is estimated from the resulting sample of $E_t$, and a z-score is calculated based off $E_t\sim N(0,\sigma^2)$
I think we can do better - the math clearly falls apart for everything that isn't a random walk.
I initially thought of fitting an ARMA(m,n) based on the peak of the autocorrelation/autocovarience functions of the series and checking the residuals. I'm wary of the robustness of this, and a previous question seems to indicate that autocorrelation is not particularly robust.

A: You are quite right that the ARIMA Model you are using (first differences) may not be appropriate to detect outliers. Outliers can be Pulses, Level Shifts, Seasonal Pulses or Local Time Trends. You might want to google "INTERVENTION DETECTION IN TIME SERIES" or google "AUTOMATIC INTERVENTION DETECTION" to get some reading matter on INTERVENTION DETECTION. Note that this is not the same as INTERVENTION MODELLING which often assumes the nature of the outlier and does not empirically identify same. Following mpkitas's remarks one would include the empirically identified outliers as dummy predictor series in order to accommodate their impact. A lot of work has been done in identifying oultliers using a null filter and then identifying the appropriate ARIMA Model. Some commercial packages assume that you identify the arima model first ( possibly flawed by the outliers ) and then identify the outliers. More general procedures examine both strategies. Your current procedure follows the "use up front filter first" approach but is also flawed by the assumption of the upfront filter.
Some more reflections:
to detect an anomaly, you need a model which provides an expectation. Intervention Detection yields the answer to the question " What is the probability of observing what I observed before I observed it ? AN ARIMA model can then used to identify the "unusual" Time Series observations. The problem is that you can't catch an outlier without a model (at least a mild one) for your data. Else how would you know that a point violated that model? In fact, the process of growing understanding and finding and examining outliers must be iterative. This isn't a new thought. Bacon, writing in Novum Organum about 400 years ago said: "Errors of Nature, Sports and Monsters correct the understanding in regard to ordinary things,and reveal general forms. For whoever knows the ways of Nature will more easily notice her deviations; and, on the other hand, whoever knows her deviations will more accurately understand Nature, The Model you are imposing on all your series i clearly am inadequate way to go.

A: Winsorization replaces extreme data values with less extreme values.
http://www.r-bloggers.com/winsorization/


text:
Q: Ajax file upload without formdata when i try to upload a file, all data send to database but the input file is empty and won't upload the file how can i send file with my
actual ajax submit form ? without dataForm i'm new to ajax and mysql
here's my code:

  function getUsers(){
 $.ajax({
  type: 'POST',
  url: 'tpl/add.php',
  data: 'action_type=view&'+$("#userForm").serialize(),
  success:function(html){
   $('#userData').html(html);
  }
 });
}
function userAction(type,idb){
 id = (typeof idb == "undefined")?'':idb;
 var statusArr = {add:"ajouter",edit:"mises à jour",delete:"supprimer"};
 var userData = '';
 if (type == 'add') {
  userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&idb='+idb;

 }else if (type == 'edit'){
  userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
 }else if (type == 'view'){
  userData = $("#viewForm").find('.form').serialize()+'&action_type='+type;
 }else{
  userData = 'action_type='+type+'&idb='+idb;
 }

 $.ajax({
  url: 'tpl/add.php',
  cache: false,
  data: userData,
  type: 'POST',
  contentType: false,
  processData: false,
  success:function(msg){
   if(msg == 'ok'){
    alert('Le model a été '+statusArr[type]+' avec succès.');
    getUsers();
    $('.form')[0].reset();
    $('#myModal2').modal('hide');
    $('#myModal').modal('hide');
   }else{
    alert('Un probleme à été detecter, veuillez reessayer.');
   }
  }
 });
}
function editUser(idb){
 $.ajax({
  type: 'POST',
  dataType:'JSON',
  url: 'tpl/add.php',
  data: 'action_type=data&idb='+idb,
  success:function(data){
   $('#idbEdit').val(data.idb);
   $('#modelEdit').val(data.model);
   $('#urldemoEdit').val(data.urldemo);
   $('#modelfichEdit').val(data.modelfich);
   $('#etatEdit').val(data.etat);
   $('#editForm').slideDown();

  }
 });
}

         <button type="button" class="close" data-dismiss="modal">×</button>

Ajouter un modele

         <form class="form form-horizontal" method="post" id="userForm" enctype="multipart/form-data">

        Modele HTML

        <input type="text" class="form-control" name="model" id="model"/>

        Aperçu

        <input type="text" class="form-control" name="urldemo" id="urldemo"/>

        Fichier HTML

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

        Etat

        <select name="etat" id="etat" class="form-control">
         <option value="0">activé</option>
         <option value="1">désactivé</option>
        </select>

       Ajouter
         <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>

       </form>


text:
Q: How does an index work/relate to FK? I know this is very basic and given where I'm at with Databases I should probably understand this by now, but I do not fully comprehend what an index really is.
To make it concrete, the following is the T-SQL generated by an ORM - it creates an FK and then creates an index for it.
What does having the index do (in the posative sense) and what does excluding it do (in the negative sense)?
-- Creating foreign key on [item_id] in table 'CakeStats'
ALTER TABLE [dbo].[CakeStats]
ADD CONSTRAINT [FK_CakeStat_Item]
    FOREIGN KEY ([item_id])
    REFERENCES [dbo].[Items]
        ([id])
    ON DELETE NO ACTION ON UPDATE NO ACTION;

-- Creating non-clustered index for FOREIGN KEY 'FK_CakeStat_Item'
CREATE INDEX [IX_FK_CakeStat_Item]
ON [dbo].[CakeStats]
    ([item_id]);
GO

A: An index is a balanced tree that allows faster searching for specific data.  Indexing something in a general sense is marking it for easy finding.  Visualize an index in the back of a reference book.  It's alphabetically sorted to allow for quick finding of where the actual information is at the cost of extra pages in the back of the book making it larger/thicker.  The more stuff you index, the larger that is.  There is also a difference between a clustered and nonclustered index.  The example I gave above is a nonclustered index so it's in addition to the normal book contents.  A clustered index is the actual content itself sorted by the keys of the index.
In the foreign key case, if you foreign key something, the way the key is enforced is by doing a check on the referenced table/column to see if it exists.  Having an index on the foreign key greatly speeds up the look up (log(n) time) rather than require looking at every single row one at a time (n time).
In your example, the index only helps if a query searches CakeStats based on item_id.  It actually is very important that Items(id) also has an index or the check on foreign key is going to be expensive every time item_id is inserted/deleted/updated in CakeStats.


text:
Q: app crahes onCreate, because of Timer I have a problem with my app crashing when i try this code?
I want i to constantly checking for if the MediaPlayer (MP) is playing, and if it is I want a Text to read "Now Playing" - But if it aint playing i want it to read "Not Playing".
I dont get any warnings from Eclipse, but still when i export it, it crashes on load.
I know the code for setting the TextView isnt there but that isnt the problem. ( i think )
If there is an other way to do this i would be glad for a push in the right direction.
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
                      //The Timer
                                Thread playingtimer = new Thread (){
                                    public void run() {
                                        try{
                                            int time = 1;
                                            while(time > 0) {
                                            sleep(100);

                                            if (MP.isPlaying()){
                                //set the TextView here "Now Playing"
                                            }
                                            else
                                //set the TextView to "NOT Playing"
                                            }
                                        }
                                        catch (InterruptedException e) {
                                        e.printStackTrace();
                                        }
                                        finally{

                                        }
                                    }
                                };
                                playingtimer.start();

A:
I know the code for setting the TextView isnt there but that isnt the problem. ( i think )

That is precisely the problem. You are trying to update a View from a background Thread. You should be using runOnUiThread(), Handler, or AsyncTask for updating the UI.
These answers talk about handler and asynctask
Example of runOnUiThread

A: The issue here is that if you are trying to modify your TextView from that timer it will crash, because one of the most important rules in android is that you just cannot modify any views from any thread other than the main, and you are trying to change it from your custom worker thread, in order to make it work, wrap the code that is modifying the view into a runOnUIThread method, or come up with your own Handler mechanism to run that code in the main Thread.
Hope this helps.
Regards!


text:
Q: VirtualBox on Ubuntu 20.04 RTR3InitEx failed with rc=-1912 (rc=-1912) OS Ubuntu 20.04
VirtualBox 6.1.32_Ubuntur149290
Running Windows 10
I got this following error and I have work inside my VirtualBox that I really do not want to lose.

dpkg --list virtualbox-*
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                           Version                       Architecture D>
+++-==============================-=============================-============-=>
un  virtualbox-2.0                 <none>                        <none>       (>
un  virtualbox-2.1                 <none>                        <none>       (>
un  virtualbox-2.2                 <none>                        <none>       (>
un  virtualbox-3.0                 <none>                        <none>       (>
un  virtualbox-3.1                 <none>                        <none>       (>
un  virtualbox-3.2                 <none>                        <none>       (>
un  virtualbox-4.0                 <none>                        <none>       (>
un  virtualbox-4.1                 <none>                        <none>       (>
un  virtualbox-4.2                 <none>                        <none>       (>
un  virtualbox-4.3                 <none>                        <none>       (>
un  virtualbox-5.0                 <none>                        <none>       (>
un  virtualbox-5.1                 <none>                        <none>       (>
un  virtualbox-5.2                 <none>                        <none>       (>
un  virtualbox-6.0                 <none>                        <none>       (>
un  virtualbox-6.1                 <none>                        <none>       (>
ii  virtualbox-dkms                6.1.26-dfsg-3~ubuntu1.20.04.2 amd64        x>
ii  virtualbox-ext-pack            6.1.32-1~ubuntu1.20.04.1      all          e>
un  virtualbox-guest-additions-iso <none>                        <none>       (>
un  virtualbox-guest-modules       <none>                        <none>       (>
un  virtualbox-modules             <none>                        <none>       (>
ii  virtualbox-qt                  6.1.32-dfsg-1~ubuntu1.20.04.1 amd64        x>
un  virtualbox-source              <none>                        <none>       (>
 ESCOC

I have found a similar problem here. But I am not sure if this will delete my current work the virtualBox and I do have enough rep to ask further questions on the original post. Please help.
I also run this and it seems like I have the correct architect for my OS
spock@spock-uss:~$ dpkg -l virtualbox* | grep ^i
ii  virtualbox                     6.1.32-dfsg-1~ubuntu1.20.04.1 amd64        x86 virtualization solution - base binaries
ii  virtualbox-dkms                6.1.26-dfsg-3~ubuntu1.20.04.2 amd64        x86 virtualization solution - kernel module sources for dkms
ii  virtualbox-ext-pack            6.1.32-1~ubuntu1.20.04.1      all          extra capabilities for VirtualBox, downloader.
ii  virtualbox-qt                  6.1.32-dfsg-1~ubuntu1.20.04.1 amd64        x86 virtualization solution - Qt based user interface

A: I found the solution to this problem. In Synaptic Package Manager I found that the package 6.1.26-dfsg-1~ubuntu1.20.04.1 was not of the right version (had an exclamation mark). I updated this package to 6.1.32-dfsg-1~ubuntu1.20.04.1 and now virtualbox is running without problems.

A: I ran into the same problem last Sunday (hadn't used the vm for a few weeks) however today it's solved :)
I've done the following actions:
Sunday

*

*apt remove virtualbox virtualbox-ext-pack

*apt install virtualbox virtualbox-ext-pack

*reboot, no effect

*apt-get install virtualbox-dkms

*reboot, no effect

*apt autoremove

*reboot, no effect

*shutdown laptop

Monday

*

*restart laptop

*executed the (daily) Ubuntu updates from today

and....  Virtualbox with my Windows vm starts without problems :)
no idea why.
Todays Ubuntu update
Upgrade: netplan.io:amd64 (0.103-0ubuntu5~20.04.5, 0.103-0ubuntu5~20.04.6), libxml2-dev:amd64 (2.9.10+dfsg-5ubuntu0.20.04.1, 2.9.10+dfsg-5ubuntu0.20.04.2), python-libxml2:amd64 (2.9.10+dfsg-5ubuntu0.20.04.1, 2.9.10+dfsg-5ubuntu0.20.04.2), libnetplan0:amd64 (0.103-0ubuntu5~20.04.5, 0.103-0ubuntu5~20.04.6), libxml2:amd64 (2.9.10+dfsg-5ubuntu0.20.04.1, 2.9.10+dfsg-5ubuntu0.20.04.2), libxml2:i386 (2.9.10+dfsg-5ubuntu0.20.04.1, 2.9.10+dfsg-5ubuntu0.20.04.2)
hope this helps you too.
best regards Lodewijk


text:
Q: Finding a basis for null and column space of a matrix I need help computing $\mathrm{null}(A)$ and $\mathrm{col}(A)$
$$A =
 \begin{bmatrix}
    1 & 2 & 1 & 4  \\
    1 & 1 & 1 & 3 \\
    -1 & 1 & -1 & \ -1
\end{bmatrix}$$
I think I did $\mathrm{null}(A)$ correctly. I found the row reduced echelon form and found that $x_{1} = -x_{3} - 2x_{4}$ and that $x_{2} = -x_{4}$. I also found that $x_3, x_4$ are free.
So my basis for $\mathrm{null}(A)$ was
$$\left\{\begin{bmatrix}
    -1 \\
    0 \\
    1 \\
    0 \\
\end{bmatrix},
\begin{bmatrix}
    -2 \\
   -1 \\
    0 \\
    1 \\
\end{bmatrix}\right\}.$$
I do not know how to proceed.

A: For the column space: note that the reduced row-echelon form of $A$ is given by
$$\mathrm{RREF}(A)=\begin{bmatrix}
    1 & 0 & 1 & 2  \\
    0 & 1 & 0 & 1 \\
    0 & 0 & 0 & 0
\end{bmatrix}.$$
To find the column space of $A$, we want to look at the columns in $A$ which have leading $1$'s in $\mathrm{RREF}(A)$. Since columns one and two have leading $1$'s, then that tells us that
$$\left\{\begin{bmatrix}
    1 \\
    1 \\
    -1
\end{bmatrix}, \begin{bmatrix}
    2 \\
    1 \\
    1
\end{bmatrix}\right\}$$
forms a basis for $\mathrm{col}(A)$.
Moreover, the entries in columns three and four tell us exactly how to write said columns as a linear combination of the basis:
$$\begin{bmatrix}
    1 \\
    1 \\
    -1
\end{bmatrix}=1\begin{bmatrix}
    1 \\
    1 \\
    -1
\end{bmatrix}+0\begin{bmatrix}
    2 \\
    1 \\
    1
\end{bmatrix},$$
$$\begin{bmatrix}
    4 \\
    3 \\
    -1
\end{bmatrix}=2\begin{bmatrix}
    1 \\
    1 \\
    -1
\end{bmatrix}+1\begin{bmatrix}
    2 \\
    1 \\
    1
\end{bmatrix}.$$
Thus, columns three and four are indeed in $$\mathrm{span}\left\{\begin{bmatrix}
    1 \\
    1 \\
    -1
\end{bmatrix}, \begin{bmatrix}
    2 \\
    1 \\
    1
\end{bmatrix}\right\},$$
and $\left\{\begin{bmatrix}
    1 \\
    1 \\
    -1
\end{bmatrix}, \begin{bmatrix}
    2 \\
    1 \\
    1
\end{bmatrix}\right\}$ is a linearly independent set (if not, $\mathrm{RREF}(A)$ would not have a leading $1$ in both of the first two columns).


text:
Q: Multiple list comprehensions in one line in python I have the following code in Python 3.9:
first_entries = [r[0] for r in result]
seconds_entries = [r[1] for r in result]
third_entries = [r[2] for r in result]

where result is a list of tuples of the following form:
result = [(x1,x2,x3),(y1,y2,y3),...]

Is there a way to write this into one line and iterate over result only once?

A: first_entries, seconds_entries, third_entries = zip(*result)
works as expected

A: tups = [(1,2,3), (4,5,6), (7,8,9), (10,11,12)]

first_entries, second_entries, third_entries = zip(*[(tup[0], tup[1], tup[2]) for tup in tups])

print(first_entries) # (1, 4, 7, 10)

Do you really need to separate those results into 3 lists though?


text:
Q: How to implement templating on UWP/UAP I need to generate HTML based off some models in an UWP/UAP project - written in C# entirely.
The problem is that no preexisting templating engines (I really wouldn't want to write one from scratch) are compatible with the platform. I looked up a few most popular alternatives, and none would work out of the box.
What would be your suggested solution for this substantive issue I am facing? I thought about porting one of available open-source libraries, but I'm not sure whether it would be worth the effort.
I'm not interested in opinionated answers, or recommendations of templating engines (that don't really work on UAP), only in the easiest route to solve the problem of templating in a Windows 10 universal app.

A: If you are developing, using HTML/JavaScript, you can use built-in WinJS library for templating in HTML. Also Microsoft created a number of adapters for Angular, React or Knockout to use them in UWP apps.
Usually most of JavaScript code should just work, the only thing you should take into consideration is security limitations while embedding iframes or external script. To bypass such limitations you should update logic of used library or manually enforce by using the execUnsafeLocalFunction method.
MSApp.execUnsafeLocalFunction(function() {
    var body = document.getElementsByTagName('body')[0];
    body.innerHTML = '
example
';
});

==
Update:
For C# there are two options:

*

*continue looking for library or impellent it yourself that will do such convertion, or

*build a wrapper around webview control, that will do it for you with already existing libraries.

In the second case it should be quite easy:
1) You should implement a converter from JSON to HTML (with template) using any library of your choose in JavaScript, it should be available for calling from external context (global function or object). Such function should receive data as a JSON-string and return a string (e.g. from innerHTML).
2) Use standard technics with InvokeScriptAsync/ScriptNotify event for the WebView control to transfer data between C# and JS environments. You don't need actually to display WebView inside your page. Just use it as environment for JS execution with access to DOM, required by corresponding libraries.
Here is code sample with WinJS:
HTML/JS. template.html file with WinJS library. Global js-function:
function convertFromJSON2HTML(jsonString, templateHTML) {
    var templateEl = document.createElement("div");
    templateEl.innerHTML = templateHTML;

    var jsonData = JSON.parse(jsonString);

    if (WinJS != undefined) {
        var template = new WinJS.Binding.Template(templateEl);

        //promise
        template.render(jsonData).done(function(output) {
            window.external.notify(output.innerHTML);
        });
    } else {
           // catch error
    }
}

C# Code
public async Task<string> GenerateTemplate(string jsonData, string template)
{
    var webView = new WebView();
    webView.Source = new Uri("ms-appx-web:///HTML/template.html");

    webView.DOMContentLoaded += async (o, e) =>
    {
        await webView.InvokeScriptAsync("convertFromJSON2HTML", new string[] { jsonData, template });
    };

    string output = "";

    // Simple trick to convert event result to async result
    TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
    webView.ScriptNotify += (o, e) =>
    {
        output = e.Value;
        tcs.SetResult(true);
    };
    await tcs.Task;
    return output;
}

Usage. I'm using WinJS-style templates here:
var result = await GenerateTemplate("{\"x\":\"test\"}","

");
resultBox.Text = result;

Also to simplify communications I would recommend to use the AddAllowedWebObject method to pass WinRT-objects between two environments instead of just text.


text:
Q: Framework7 virtual list searchAll function not being used I've got a PhoneGap application in development where I'm trying to use framework7's search bar to filter out my virtual list of products.
Current functionality is that the list works fine, but the search bar only searches through the rendered elements rather than the whole virtual list.
I've gone through framework7's documentation on getting their virtual list and searchbars to work together, but as far as I can tell the searchbar in my code completely ignores the virtual lists searchAll function which I put in. I can have searchAll() return anything and it makes no difference to the current functionality.
    var listObject = {
        items: selectProd,
        template: '

{{internal_descriptn}}

</script>',
        searchAll: function (query, items) {
            var foundItems = [];
            for (var i = 0; i < items.length; i++) {
                // Check if title contains query string
                if (items[i].title.indexOf(query.trim()) >= 0) foundItems.push(i);
            }
            // Return array with indexes of matched items
            return foundItems;
        }
    };
    console.log(listObject);
    var virtualList = myApp.virtualList('#product-list', listObject);
    var mySearchbar = myApp.searchbar('.searchbar', {
        searchList: '.list-block-search',
        searchIn: '.list-title'
    });

I feel like the only thing I could be missing is some way to put the virtualList into the searchbar as an attribute or similar to link them, it seems strange for me to expect them to just work together like magic. Yet that seems to be what the documentation suggests it does (not in my case apparently or it would work). Thanks for any help.

A: Solved it by looking at an example on their github. At first glance everything is the same, so I copy it over and slowly change it back to include my data to see where the problem occurs. For some godamn reason, you need to use the class virtual-list to identify the parent containing your list. Then specify that class for your virtual list and for your search bar. Using a different name instead won't work. Very frustrating that this isn't mentioned anywhere at all in documentation.


text:
Q: Italic Greek characters in Times New Roman I'm very new to LaTeX!  I'm trying to create a template for creating scientific reports as PDFs.  I'd like the whole of the document to be in Times New Roman.  I've used the package pslatex, which works well except for the fact that none of the Greek characters (including those in equations) are italic as they should be.
Is there a way to make these characters italic?  The standard {\it ?} has no effect.  Or is there a package other than pslatex that puts the document in Times New Roman but doesn't cause this problem?
I'm using TeXShop.
This illustrates the problem:
\documentclass[a4paper]{article}
\usepackage{pslatex}   %  This makes the font Times New Roman.
\usepackage{amsfonts,amssymb,amsmath,mathbbol}   % For maths symbols.

\usepackage{titlesec}
\titlespacing\section{0pt}{5pt plus 1pt minus 1pt}{5pt plus 1pt minus 1pt}
\usepackage{graphics,graphicx,epsfig,ulem}
\usepackage[top=2.0cm, bottom=2.0cm, left=2.0cm, right=2.0cm]{geometry}
\usepackage{multicol}
\usepackage[none]{hyphenat}

\begin{document}

Times New Roman.

${\beta=3\alpha}$

{\it${\beta }$} = 3{\it${\alpha}$}

${\alpha, \beta, \gamma, \delta, \epsilon, \lambda, \phi, \rho, \varphi, \omega}$

\begin{equation}{\it t}_{1/2} = \dfrac{\ln(2)}{{\lambda}}.
\end{equation}

\end{document}

A: pslatex is really an obsolete package. You can use mathptmx, as already suggested, or
\usepackage{newtxtext,newtxmath}

(which requires an updated TeX distribution).
mathptmx

newtxtext + newtxmath

Here is the source. Notice how the result is obtained more simply than you did (everybody must learn, when using a new tool).
\documentclass[a4paper]{article}

\usepackage{amsmath}   % For maths symbols.

%%% uncomment one of the following and comment the other
\usepackage{newtxtext,newtxmath}
%\usepackage{mathptmx}

\begin{document}

Times New Roman.

$\beta=3\alpha$

$\beta=3\alpha$

$\alpha, \beta, \gamma, \delta, \epsilon, \lambda, \phi, \rho, \varphi, \omega$

\begin{equation}
t_{1/2} = \frac{\ln(2)}{\lambda}.
\end{equation}

\end{document}

(The difference in size is an artifact of the image production.)

A: do not use the obsolete package pslatex. Use instead:
\usepackage[T1]{fontenc}

\usepackage{mathptmx}

and your greek letter should be in italic by default without \it which is already an old command, use \textit or \itshape instead.


text:
Q: NSLevelIndicator with text on It? How can I add text on top of a NSLevelIndicator? [the NSLevelIndicator is in my statusbar, if that matters]

A: The best way to add text to your NSLevelIndicator user interface is by adding a separate Label NSTextField.  The NSLevelIndicator control does not have a title or other text associated with it.
From within Interface Builder, just grab a Label and drag it to your window above or beside the NSLevelIndicator.

A: Contrary to the correct answer to your previous question, if you want to use an NSLevelIndicator as a background and draw text on top of it, you're better off creating a custom view that owns and uses an NSLevelIndicatorCell for the background drawing.
You might also consider drawing the background yourself; e.g., fill with your choice of green/yellow/red, and then draw a white gradient on top of it. This is more appropriate if you're not really indicating a level with your level indicator.
Also, don't forget to test your application with Sim Daltonism, to make sure that the text is still readable to color-blind users.


text:
Q: Returning HttpPostedFileBase to view on validation error When I attempt to upload images to my MVC controller action and there is a validation error, I have to click through each of the buttons and find all of my files again.
If I have a view that consists of
<input type="file" id="file0" name="Files[0]" />
<input type="file" id="file1" name="Files[1]" />

and a controller action like
public ActionResult Create(ModelClass model, IEnumerable<HttpPostedFileBase> Files)
{
    if(ModelState.IsValid)
    {
        //do work
        if(PhotoValidation.IsValid(Files))
        {
            //do work
        }
        else
        {
            ModelState.AddModelError("","Photos not valid");
        }
    }
    return view(model); // Way to return photos back to the view on modelstate error?
}

The files get posted to the server fine but if there is a model validation error, is there any way to return the model AND the Files so the user doesn't have to upload them again?

A: This is not possible. The value of a intput type="file" is never used on parsing an HTML page. That's a huge security risk, so no modern browser will allow them to 'retain' values.
If you are sure that your clients are using browser with HTML5 support, you can try using JavaScript File API in order to eliminate postbacks - check following articles:

*

*Working with files in JavaScript, Part 1: The Basics

*Working with files in JavaScript, Part 2: FileReader

*Working with files in JavaScript, Part 3: Progress events and errors

*Working with files in JavaScript, Part 4: Object URLs

*Working with files in JavaScript, Part 5: Blobs


text:
Q: Find and Remove an object from an array of objects I am a beginner.
I am trying to remove object "Bil' from 'zubi' (object array).
Could anyone guide me?
var zubi=[
{a:1,b:1,c:1},
{a:2,b:2,c:2}
]
var Bil={a:1,b:1,c:1}

// the methods I tried which donot work :(
zubi.splice(zubi.indexOf(Bil),1)
zubi=zubi.filter(d=> d!==Bil)

A: JavaScript objects cannot be compared with equality operator (==).
You can achieve the comparison using deep-equal library:
var equal = require('deep-equal');

zubi=zubi.filter(d=> equal(d, Bil) === false)

underscore.isEqual does the same, you might use that library if you prefer.
Alternatively, in case you do not want to add dependencies to your project, you can compare each property by yourself, as adviced in another answer.
The code would then be:
zubi=zubi.filter(d=> d.a !== Bil.a && d.b !== Bil.b && d.c !== Bil.c);

A: Each object is uniquely stored even they have same values means:
{a:1} === {a:1} // false

So, in your second case you can check the properties of the object to filter:
zubi=zubi.filter(d=> d.a !== Bil.a);

var zubi=[
{a:1,b:1,c:1},
{a:2,b:2,c:2}
]
var Bil={a:1,b:1,c:1}

// the methods I tried which donot work :(
zubi=zubi.filter(d=> d.a !== Bil.a)

console.log(zubi);

A: You can use filter and JSON.stringify like shown below, So the output will have the array element without Bil Object.
@Update
This approach can be used if the keys order has not changed. Thanks to mehdi for pointing out this one.

var zubi=[
{a:1,b:1,c:1},
{a:2,b:2,c:2}
]
var Bil={a:1,b:1,c:1}

let output = zubi.filter(o => JSON.stringify(o) !== JSON.stringify(Bil))

console.log(output)


text:
Q: Converting unfamiliar url encoding I'm using an api that's sending me url encoding like this:
https%3A%2F%2Fs3.amazonaws.com%2Fdocs.rightsignature.com%2Fassets%2...etc...
I can obviously see that %3A is likely : and %2F is / so that %3A%2F%2F resolves to ://.
My question is, how can I convert these in PHP. I am just not sure what to search for. Is there a function to convert these urls in PHP?
Maybe something like urldecode($thing).

A: You can use rawurldecode() for this.
echo rawurldecode("https%3A%2F%2Fs3.amazonaws.com%2Fdocs.rightsignature.com%2Fassets%2F"); // outputs https://s3.amazonaws.com/docs.rightsignature.com/assets/

A: Use urldecode($thing). It does work.
urldecode("https%3A%2F%2Fs3.amazonaws.com%2Fdocs.rightsignature.com%2Fassets...");
// https://s3.amazonaws.com/docs.rightsignature.com/assets...


text:
Q: When the OS is loaded, does the kernel continue to run as a normal program? There is a similar question to mine here: https://stackoverflow.com/questions/43819072/does-the-kernel-stop-running-on-its-own-when-the-os-is-fully-loaded, but it has conflicting answers (so please do not mark this question as a duplicate).

Back to my question. I know that when the computer is powered on, the BIOS starts running, and the BIOS will run the boot loader, and the boot loader will run the kernel.
Now the kernel starts running as a normal program (by "normal program" I mean that the kernel is not just a group of functions that other programs calls, but rather it is also a program that runs on its own). Now the kernel will perform tasks such as:

*

*Initializes hardware as well as kernel data structures.

*Switch to protected mode.

*Initialize Interrupt Descriptor Table.

*etc. (this article lists a lot more tasks that the kernel does).

After the kernel finishes these tasks, the OS becomes loaded and the user can start using it.
My question is: now that the OS is loaded, does the kernel continue to run as a normal program, or will it stop running in this way and only run when an interrupt happens?

A: Any kernel is pretty much the complete opposite of a "normal program". Even though microkernel folks might like the idea of OS services running as processes in the same level as user application, the kernel is always going to have to include some part that's not. If nothing else, there must be some part of the OS that handles scheduling of and switching between the processes, and communication between them.
Particularly, on Linux, the kernel is mapped to the address space of all processes, in the upper part of the address space. In a sense, it's part of each process, in that some processes might be running kernel code while at the same time some other process might be running user-space code.
I wouldn't say the kernel runs as a normal program, but it also doesn't run "only" on interrupts, as user-space code can also call into kernel routines: that's what system calls are. Quotes around "only", since interrupts aren't at all exceptional, some sort of a regular timer tick is quite common to have.

A: On a uniprocessing system, the processor can only run a single program at a time, so that either the OS or another program runs at a given time.
The os doesn't run as a normal program, as it is the entity in charge of scheduling the run of these programs. When a program runs, the OS doesn't do anything, and will be called back once an interrupt, a system call or a timeout happends. It can then either decide to work for itself, or run another program it is in charge of.
I don't understand why would the answer you're talking about be conflicting:
some processes the OS run can be kernel componnents, having a higher level of privilege.


text:
Q: How to pop duplications only once from a list by comparing to another list in Python 3 I'm trying to write a card game where the cards are assigned numerical values.
a = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
b = [1, 2]

How do I remove b (cards you draw from a deck) from a to get:
c = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]

Or... How do I take a random sample away from a to make a separate list b?

A: You can use .remove().

remove() - Remove first occurrence of value. Raises ValueError if the value is not present.

a = [1,1,1,1,2,2,2,2,3,3,3,3]
b = [1,2]
a.remove(b[0])
a.remove(b[1])
print(a)

Or:
a = [1,1,1,1,2,2,2,2,3,3,3,3]
b = [1,2]
for i in b:
    a.remove(i)
print(a)

If you want a separate list, you can create a copy of the list a
a = [1,1,1,1,2,2,2,2,3,3,3,3]
b = [1,2]
c=a.copy()
for i in b:
    c.remove(i)
print(c)

A: random.sample(a, n) will give you a sample where n is the sample size you want:
>>> a = [1,1,1,1,2,2,2,2,3,3,3,3]
>>> random.sample(a, 5)
[2, 1, 3, 2, 2]

Alternatively you can random.shuffle(a) and draw n cards from the beginning:
>>> random.shuffle(a)
>>> a
[2, 1, 2, 2, 1, 1, 1, 3, 2, 3, 3, 3]
>>> a[:5]
[2, 1, 2, 2, 1]

A: import random

Deck_lst = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
Deck_lst_sequence = [i for i, v in enumerate(Deck_lst)]
Draw_cards_index = random.sample(Deck_lst_sequence, 2)
Draw_cards_value = []
for Draw_card in Draw_cards_index:
    Draw_cards_value.append(Deck_lst[Draw_card])
    Deck_lst.remove(Deck_lst[Draw_card])

print(Deck_lst)
print(Draw_cards_value)


text:
Q: Removing an item from listbox in winform I am using VS2010, C#, .Net 4.0 and WinFormApplication.
I have a listbox which is populated from a datasource. I want to remove an item at a time when they are double clicked.
I read somewhere that if I populate my listbox from a datasource, no item can be removed. Is this true? If not, then how can I remove individual items?
I tried the following:
listbox1.Items.Remove(listbox1.SelectedIndex);

listbox1.Items.Remove(listbox1.SelectedIndex);

lbTableColumns.Items.Remove(lbTableColumns.SelectedItem);

which cause the following error:

ERROR: Items collection cannot be modified when the DataSource property is set.

A: When using a DataBinding you cannot remove items from the ListBox, just as the error states. What would happen if the object changes within the DataSource, but has been removed from the presentation?
If you are working with DataSources you need to remove the object from the DataSource itself. Try something like this:
IList<MyObj> myList = new List<MyObj>();

private void DataBind()
{
    myListBox.BeginUpdate();
    myListBox.DataSource = myList;
    myListBox.EndUpdate();
}

private void OnMyListBoxItemDoubleClicked(object sender, EventArgs e)
{
    myList.RemoveAt(myListBox.SelectedIndex);
    DataBind();
}


text:
Q: How to pull changes from svn repos after migration to mercurial Im working on a patch for an open source project that uses svn. I dont have commit access but I want to version track my own changes. I followed this guide to read and convert the svn repos into a hg one.
I want to be able to pull new changes from the official svn repos into my own local copy, how can that be achieved? After the import, my local folder contained an untracked .hgignore file. Should I add that one to be tracked by mercurial?
I also looked into this tool but it seems more geared towards just working locally in mercurial connected to svn repos. I want to put my mercurial repos on bitbucket and for that the former guide seemed to make more sense.
It might be to early to think about but later when my contribution is complete, whats the best way to generate a patch to send upstream? Are there any caveats I should be aware of straight away?
Edit: orip's answer (the edit part of it) sums up pretty much exactly what I want to do: local hg copy which can update from svn but also push to my online bitbucket repos.

A: Pulling new changes is easy: checkout the svn code, and regularly 'svn update' it, then check those downloaded files into your mercurial repo.
The .hgignore file is there to tell mercurial which file types not to track - ie to ignore. Do not add this to your mercurial repo, chances are it'll just contain the same exclusions as your subversion global-ignores.
Patch generation in SVN is easy, do svn diff > myPatch.diff (after updating the svn repo)

A: You could consider working with MQ. So, you would have a project managed by two VCS at the same time:

*

*SVN: used to stay up-to-date with the main repository

*HG: where you'll perform addremove commands after each update from SVN and where you'll use MQ to write your patches.

Doing so, it'll aslo be alot easier when the time will be to provide your patch to the main repository.

A: The guide you used converts svn to hg, but is meant for a one-time conversion, not for continued interoperability.
You want something like hgsubversion.
EDIT: just noticed you linked to it in the question. There shouldn't be a problem keeping a clone of your repository on bitbucket - interact with SVN with hgsubversion locally, and push to bitbucket as you normally would - you have a regular hg repo.

A: You could take a look at TortoiseHg wiki on SVN - Using TortoiseHg as a client for a Subversion server section, maybe it will help you make a decision about the tools presented in the Mercurial wiki you linked in your question.
Also, check out the answer given by VonC on this question: Mercurial from Subversion: moves, renames and tags


text:
Q: How to add html image in to velocity template file to send email? I include this in my velocity file. but it is not working,

A: You can follow the guide here.
For example, try this in your Velocity template file:

And in your Java code, try:
URL url = new URL("image.png");
String cid = email.embed(url, "Foo");
Map model = new HashMap();
model.put("cid", cid);

A: When your server is running you can get path till server from request.getContexPath();
So here you just need to provide rest path of the image. I have done this for my demo application like this.

Now you have to set value of projectPath to your projectPath which you can get by request.getContexPath();
Now create one Map in which you have to add Key which will keyword that you have used in .vm file. For this example, we have used projectPath.
 Map map = new HashMap<>();
 map.add("projectPath",request.getContexPath());
 map.add() // other value that you want to replace in vm file

After that create instance of VelocityContext load this map with constructor argument like this
 VelocityContext velocityContext = new VelocityContext(map);


text:
Q: Conditions for two critical points? For $f(x) = ax^3 - bx$, where $a,b ≠ 0$, what are the conditions for the values of $a$ and $b$ such that $f(x)$ has two critical points.
$f'(x) = 3ax^2 - b = 0$. Not sure how to solve from here.

A: Simply put, the derivative of the function must have two roots (when it is equal to zero).  You have calculated the derivative, and now what is left is to find values of $a$ and $b$ such that the discriminant of $3ax^2 - b =0$ is strictly positive.  In your case, it must hold that
$$Disc. = 12ab >0,$$
It is easy to see that both $a$ and $b$ must be either strictly positive or strictly negative.


text:
Q: Extracting the name of the file until the first space into a new column I am trying to create a automated flow which will copy the file name into a new column up until the first space in the name. For example:
The uploaded file name is **ZKAL12345-I RTR 123ml Product Label Region 61.PDF so i would like the column to be name ZKAL12345-I
I've found the below code, which works well, however, it stops the naming at the dash (-) and as i am sure you can still im not quite sure how to change it to the requirement above .
substring(triggerBody()?['{Name}'], 0, lastIndexOf(triggerBody()?['{Name}'],'-'))

Any help is appreciated.
Many thanks,
Artur

A: Could you not just do
substring(triggerBody()?['{Name}'], 0, indexOf(triggerBody()?['{Name}'],' '))

?
indexOf() returns the first index of the searched for value, in this case, a single space, which in your case would be the space between "ZKAL12345-I" and "RTR".


text:
Q: Using Event Sourced Aggregate Roots with the Specification Pattern I have a Aggregate Roots that use the event sourcing technique of being built from a series of events in a Repository. This is all great for when I just need to manage change of state etc, but when I come to using the Specification pattern to apply my app specific business rules, I am hitting a wall on what Entities to use, how to instantiate them etc etc.
I would want to run specific methods on my Repository, for example getProductByProductCode so I can check my current AR against it for uniqueness (simple example), but I am unsure how to do this, as my Repository is set up to get ARs by their ID from the event store.
I used to have a database backing my Repositories, now I only have an event store as I have no read models yet.

*

*Has anyone done this before, and how did you do it?

*Do I need a read model first?

*Should I query the read model, then use a resulting ID to get the AR from the event store?

*What if I need multiple AR results to be returned?

I am so confused as I thought I was doing it all the right way now as we need event sourcing, but I can't seem to marry up my old-school thinking with how to do it now it's event sourced :(

A:
Repository is set up to get ARs by their ID from the event store.

That should suffice. If you need to query a collection of ARs from the repository you should use a specially designed Read model.
Put it another way, you are using CQRS. This means that you cannot query the Aggregate to check it's product code and it's natural that you cannot query the repository either, which basically its a collection of Aggregates.

Has anyone done this before, and how did you do it?

I create a fast, light, specially designed Read model that answers to this question only: bool isThereAlreadyAProductWithThisCode(string productCode).

Do I need a read model first?

Yes. See above.

Should I query the read model, then use a resulting ID to get the AR from the event store?

Only if you need to send commands to it. Aggregates have only command methods (no query method whatsoever).

What if I need multiple AR results to be returned?

Then create a new one or modify the above Read model to answer to this query.

I am so confused as I thought I was doing it all the right way now as we need event sourcing, but I can't seem to marry up my old-school thinking with how to do it now it's event sourced :(

It is hard because there are two leaps that you must take:

*

*CQRS: there is a write model that only receive commands (methods that return void). It does not have any query method. In DDD, this is the Aggregate, with its entry point, the Aggregate root. There is also one or more Read models. They have query methods that answer any question from the other layers (i.e. Presentation, Application, Infrastructure). They have also methods that update their persisted state when events happen but these methods are not to be used by the other layers. After the events are applied to all the Read models, they are discarded (not used any more by the write side). When a command arrives, the Aggregate is loaded from a Repository where its plain state was persisted when the last command was handled.

*Event sourcing: the write model, in DDD the Aggregate, has no plain persisted state. Every time a command arrives, the Aggregate is rehidrated by the Event store by new-ing an Aggregate's class and then applying all its own previous emmited events (there is an optimisation called snapshoting but it acts just like a cache and it should be avoided if not really necessary). There is no database containing the Aggregates state other than the Event store.


text:
Q: Finding time remaining What would be the correct equation for finding out the variable timeRemaining in minutes.
$lockDate = $row['lockDate'];

                $currentDateTime = time();

                // Find out if user is locked out of their account
                if (($lockDate != "0000-00-00 00:00:00") && strtotime($lockDate) < $currentDateTime) {

                    $lockDate = strtotime($lockDate);
                    $diff = $currentDateTime - $lockDate;
                    echo $diff;

                    // Take minutes and perform tasks
                    if ($diff <= 600) {

                        // Calculate time remaining
                        $timeRemaining = 10 - $diff;

                        // Account locked error
                        $errors = true;
                        $message = "Your account is currently locked, we appologize for the inconvienence. You must wait " .$timeRemaining." minutes before you can log in again!";

                        $output = array('errorsExist' => $errors, 'message' => $message);

                    } else {

                        // Clear the lock
                      //  $query = "UPDATE manager_users_hacking SET lockDate = NULL, hackerIPAddress = NULL, failedLogins = 0 WHERE userID = '".$userID."'";
                        $result = mysqli_query($dbc,$query);

                    }

                }

A: $diff is in seconds. You can convert to minutes by dividing by 60. $diff=$diff/60.


text:
Q: Remove Image from image array React Native I need to remove or hide image from array after click on this image.
I'm trying to do this, but it's not work for me
I just study React Native, please help me
const [hiddenObject, setHiddenObject] = useState(false);
const findObjects = {
  postList: [
    { img: require("../obj1.png"), opacity: 1, w: 35, h: 50, left: 0, top: 0 },
    {
      img: require("../obj2.png"),
      opacity: 1,
      w: 35,
      h: 50,
      left: 170,
      top: 20,
    },
    {
      img: require("../obj3.png"),
      opacity: 1,
      w: 35,
      h: 50,
      left: 277,
      top: 50,
    },
    {
      img: require("../obj1.png"),
      opacity: 1,
      w: 35,
      h: 50,
      left: 510,
      top: 7,
    },
  ],
};

const hiddenObject2 = (item) => {
  item.opacity = 0;
  setHiddenObject(hiddenObject);
  findObjects.postList.splice(item, 1);
};

return (
  <View>
    {findObjects.postList.map((item) => {
      return (
        <TouchableOpacity
          onPress={hiddenObject2}
          key={Math.random()}
          style={{ width: "auto", opacity: hiddenObject ? 0 : item.opacity }}
        >
          <Image
            source={item.img}
            style={[
              gStyle.imgObject,
              {
                width: item.w,
                height: item.h,
                left: item.left,
                top: item.top,
                opacity: hiddenObject ? 0 : item.opacity,
              },
            ]}
          />
        </TouchableOpacity>
      );
    })}
  </View>
);


text:
Q: gpsd parsing GPRMC data incorrectly I've connected my Nokia N9 to my linux laptop via bluetooth-serial using the extGPS app from Ovi. Everything seems to work fine im able to connect gpsd to the serial device and get GPS output.
But theres a problem with the GPS output, the longitude is always 0.000E when, in my case the correct GPS longitude should be something like -9.13245
gpsd:IO: <= GPS: $GPRMC,184922.0,A,3842.126000,N,0-9-26.781000,E,000.10.0,131.15,211013,,,A*49
gpsd:IO: => client(0): {"class":"TPV","tag":"RMC","device":"/devrfcomm0","mode":3,"time":"2013-10-21T18:50:48.000Z","ept":0.005,"lat":38.702000000,"lon":0.000000000,"alt":74.000,"track":126.0800,"speed":0.000,"climb":0.000}\x0d\x0a

The problem might be with gpsd parsing the GPRMC data.
Is there a way to solve this or an alternitive to gpsd in linux ?

A: The fault is not the gpsd.
Look at the RMC sentence.
"$GPRMC,184922.0,A,3842.126000,N,0-9-26.781000,E,000.10.0,131.15,211013,,,A*49"

This is garbage! especially: 0-9-26.781000
What is that? This is not a coordinate, and for sure not in the format as specified in the RMC sentence.


text:
Q: STM32 PLL settings make my program crash I am following a course on USB programming on STM32 platform. My board is a STM32F746G-DISCO with a STM32F746NG microcontroller.
In the course, the teacher sets his board to these frequencies:

SYSCLK = 72MHz
HCLK = 72MHz
APB1 CLK = 36MHz
APB2 CLK = 72MHz

The settings he uses are:

So CubeMX also confirms that these settings are correct.
However when I try to set these settings on my board, It always crashes and goes into this infinite loop:

Here is my code:

I checked my oscillator on the scope and it works as expected with a 8MHz frequency, so this config is supposed to work according to the datasheet...
The problem seems to come from the P parameter of the PLL. See line 29 in my code, if I change P = 0 to P = 2, then there is no crashes.
(in the datasheet, it is written than a P = 0 value in the register sets PLL P parameter to 2, and a P = 2 value in the register sets PLL P parameter to 4).
Has someone encountered this problem? I've tried many things, I checked my oscillator, checked with the debugger than my configuration registers have the correct value, etc.
Edit: I forgot to say that the program crashes as soon as it exits the ClkConfig function.

A: Ok, I've finally fixed this problem, and it was really simple in fact, althought it took me a week to find the solution
The schematics and the BOM of my board have an error: the external oscillator frequency is 25MHz, but is written as 8MHz on the documents ...
I don't know what I've measured on the scope, but it was 8MHz so there was a coincidence ...


text:
Q: C# | Memory Leak in windows service I have a Web API which is hosted as a windows service. There is a suspected memory leak in the application.
When looking at the task manager, with every HTTP request, there i a certain amount of memory which is held by the application.
Example. ON start of the service the process in task manager is at 5000K memory, with first request the memory reaches to 40000K and once processed it comes down to around 30000K, with the next request onwards it increases from 30000K to 60000K and after processing comes down to around 45000K.
When i monitored service using perfmon, all the graphs eventually came down, but the graphs for

(#Gen 0 Collections, #Gen 1 Collections, #Gen 2 Collections)

are steadly increasing and never coming down.
Does Gen 0,1,2 collections holding the memory indicates memory leak in anyway.

I had a lot of referenced objects in the code, which i refactored and used a new instance of the objects. Will replacing the Classes with Structs help in this case. But as i understand Structs have instance size limits of 16 bytes, which won't work for me.


text:
Q: SQL Server T-Sql Convert filetime to datetime I need to convert a filetime field value to datetime format through t-sql in SQL Server
I have applied following formula to do so which works absolutely fine for positive values (>0). But somehow this formula does not work for negative values and it return null value.
SELECT LastModifiedTime,
       CASE WHEN LastModifiedTime <= 1 THEN NULL
       ELSE DATEADD(ms,
                    ((LastModifiedTime) / CAST(10000 AS bigint)) % 86400000,
                    DATEADD(day, (LastModifiedTime) / CAST(864000000000 AS bigint) - 109207, 0))
       END AS Expr1
FROM TableName

Sample value i had tried were:

*

*-9094352270227314699  (negative value which did not work)

*129046581660000000   (positive value which works)

A: CASE WHEN LastModifiedTime <= 1 THEN NULL
It's doing what  you told it to do.