text:
Q: Built wsdl does not match wsdl.xml configuration I'm working on a site that was recently migrated to a new server. The previous dev mentioned that the Magento API worked for SOAP v2, but I can't verify that is the case so I'm not sure if this issue is specific to my environment. I'm on Magento 1.9.2.4. The error I'm getting when I attempt to parse the wsdl in the client is the following:
WSDLException (at /definitions/binding/operation[7]/operation):
faultCode=INVALID_WSDL: Encountered illegal extension element
'{http://schemas.xmlsoap.org/wsdl/}operation' in the context of a
'javax.wsdl.BindingOperation'. Extension elements must be in a namespace
other than WSDL's

The error is pointing to this location in the wsdl:
<definitions xmlns:typens="urn:Magento" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" name="Magento" targetNamespace="urn:Magento">
 ...
<binding name="Binding" type="typens:PortType">
...
<operation name="storeList">
    <operation soapAction="urn:Action"/>
        <input>
             <body namespace="urn:Magento" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
        </input>
        <output>
             <body namespace="urn:Magento" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
        </output>
    </operation>

The operation element that is a child of operation should have the soap namespace. All operation elements after this one in this wsdl are also missing the correct namespace. If I look at the wsdl.xml defining this operation, it looks correct as far as I can tell. The following is defined in /app/code/core/Mage/Core/etc/wsdl.xml.
<operation name="storeList">
        <soap:operation soapAction="urn:{{var wsdl.handler}}Action" />
        <input>
            <soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
        </input>
        <output>
            <soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
        </output>
    </operation>

I've reviewed the other wsdl.xml files that exist in my install to see if it's being overridden anywhere, but I don't believe it is. I've cleared the cache in both my client and magento install. I've also tried renaming some of the wsdl.xml files to see if I could tell if one of them was introducing the error, but no luck so far. Any ideas on what could be causing this?


text:
Q: Trying to add JS and CSS to layout file in MVC 3 Razor website from partial views Im currently using a method that looks like the following code to add script and css files to the head of the Layout file.
public static class HtmlHelperExtensions
{
    public static MyCompanyHtmlHelpers MyCompany(this HtmlHelper htmlHelper)
    {
        return MyCompanyHtmlHelpers.GetInstance(htmlHelper);
    }
}

public class MyCompanyHtmlHelpers
{
    private static MyCompanyHtmlHelpers _instance;

    public static MyCompanyHtmlHelpers GetInstance(HtmlHelper htmlHelper)
    {
        if (_instance == null)
            _instance = new MyCompanyHtmlHelpers();

        _instance.SetHtmlHelper(htmlHelper);

        return _instance;
    }

    private HtmlHelper _htmlHelper;

    public ItemRegistrar Styles { get; private set; }
    public ItemRegistrar Scripts { get; private set; }

    public MyCompanyHtmlHelpers()
    {
        Styles = new ItemRegistrar(ItemRegistrarFromatters.StyleFormat);
        Scripts = new ItemRegistrar(ItemRegistrarFromatters.ScriptFormat);
    }

    private void SetHtmlHelper(HtmlHelper htmlHelper)
    {
        _htmlHelper = htmlHelper;
    }
}

public class ItemRegistrar
{
    private readonly string _format;
    private readonly List<string> _items;

    public ItemRegistrar(string format)
    {
        _format = format;
        _items = new List<string>();
    }

    public ItemRegistrar Add(string url)
    {
        if (!_items.Contains(url))
            _items.Insert(0, url);

        return this;
    }

    public IHtmlString Render()
    {
        var sb = new StringBuilder();

        foreach (var item in _items)
        {
            var fmt = string.Format(_format, item);
            sb.AppendLine(fmt);
        }

        return new HtmlString(sb.ToString());
    }
}

public class ItemRegistrarFromatters
{
    public const string StyleFormat = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
    public const string ScriptFormat = "<script src=\"{0}\" type=\"text/javascript\"></script>";
}

Using Html.MyCompany().Styles.Add("/Dashboard/Content/Dashboard.css"); to add files...
And @Html.MyCompany().Styles.Render() to render them in Layout_.cshtml.
My problem is that this is a static method meaning it persists the list of stylesheets and script files.
I need to do the same thing that this does but without keeping it persistant.
I need the lists to be remade on every request since they change from page to page what the look are on that specific page.
Is it possible to clear the lists on every request prior to adding the scripts that are needed or maybe after they have been rendered out?
Update:
The reason for not using a section, RenderPartial or RenderaActions is to prevent the same stylesheet or script file to be added more than once to the Layout file.
The site im building has a Layout_.cshtml with the basic layout. This in turn is used by a View that loops through a list of items and for each item a RenderAction is called that outputs the specific partial view for that item. These partial views sometimes need to add stylesheets and scripts.
As there can be needed to add many different scripts and stylesheets from different partial views a global list for styles and scripts were the only way i thought this could be done so there is a global place to check if a script is allready added to the collection or not and then render them all at once in the order they were added.
Update 2:
The real question is how to do the same kind of function (a global list) but without using a static Extension method.

A: I'd do this with sections, i.e.
@section head {
    ...add whatever you want here...
}

And render the "head" section from the layout:
<head>
...other stuff here...
@RenderSection("head", required: false)
</head>

If you don't want sections, and don't want to pass it around, I would use the HttpContext here; store some data against HttpContext.Current.Items[someKey]. If it is null, create a new one and store it in the context.
For example:
public static MyCompanyHtmlHelpers GetInstance(HtmlHelper htmlHelper)
{
    const string key = "MyCompanyHtmlHelpersInstance";
    IDictionary items = (htmlHelper == null || htmlHelper.ViewContext == null
        || htmlHelper.ViewContext.HttpContext == null)
        ? HttpContext.Current.Items : htmlHelper.ViewContext.HttpContext.Items;

    MyCompanyHtmlHelpers obj = (MyCompanyHtmlHelpers)items[key];
    if (obj == null)
    {
        items.Add(key, obj = new MyCompanyHtmlHelpers());
    }
    return obj;
}

A: What you need to do is extend the Html helper a little differently.
public static MvcHtmlString AddStyle(this HtmlHelper<TModel> html, string styleUrl)
{
    string styleTag = string.Format("<link rel='stylesheet' type='text/css' href='{0}' />", styleUrl);
    return MvcHtmlString.Create(styleTag);
}

Then in your view just do:
<head>
    @Html.AddStyle("/Dashboard/Content/Dashboard.css")
</head>

If you need root relative URLs just throw in the Url content helper.
<head>
    @Html.AddStyle(Url.Content("~/Dashboard/Content/Dashboard.css"))
</head>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dropdown values MVC Razor(Country , State) hi i have two dropdowns.

*

*MasterModule(country)

*Submodule(state)

My expectation is to First select Master category(country) than select(state)..
Currently it is showing all states when i selec any of country.
I have following razor code

                @Html.LabelFor(model => model.MasterID, "Department")

                @Html.DropDownList("MasterID", String.Empty)
                @Html.ValidationMessageFor(model => model.MasterID)

                @Html.LabelFor(model => model.SubId, "Employee")

                @Html.DropDownList("SubId", String.Empty)
                @Html.ValidationMessageFor(model => model.SubId)

any help how to acheive this?
Above code is simply binding the dropdown values to both , i want submodules dropdown shows only states of selected country. and always shows values only when i select the country

A: This question describe the same situation that you would like to have, see the accepted solution:
Fill drop down list on selection of another drop down list
Solution found by Jot: http://articlemirror.blogspot.in/2014/01/populate-cascading-dropdown-list-in.html


text:
Q: System.TypeLoadException: 'Method 'get_SerializationSettings' when using KeyVault from Load Test Plugin I have a load test that uses Key Vault to pre-authenticate web requests.
As soon as the code tries to call the method that uses KeyVaultClient class inside, the following exception throws:

System.TypeLoadException: 'Method 'get_SerializationSettings' in type
  'Microsoft.Azure.KeyVault.KeyVaultClient' from assembly
  'Microsoft.Azure.KeyVault, Version=3.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35' does not have an implementation.

I have tried to downgrade the KeyVault nuget to the version 2.0.6, but I receive the same error, with version 2.0.0.0.
I am using .NET framework 4.7.2 and Visual Studio 2017 v.15.9.7
UPDATE: The issue appears when the nuget Microsoft.Rest.ClientRuntime nuget (referenced by Microsoft.Azure.KeyVault) is updated to version 2.3.20. If I roll it back to v. 2.3.18, the load test works fine.

A: Here is something i used it in my code while accesing keyvault client using 3.0.3 library and it worked for me.
try this below and see if it works.
Uri ADL_TOKEN_AUDIENCE = new Uri(urlAudience);
var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));

public static async Task<string> GetAccessToken(string azureTenantId, string azureAppId, string azureSecretKey)
{
    var context = new AuthenticationContext(ConfigurationManager.AppSettings.Get("Authority") + tenantId);
    ClientCredential clientCredential = new ClientCredential(appId, secretKey);
    var tokenResponse = await context.AcquireTokenAsync(ConfigurationManager.AppSettings.Get("VaultUrl"), clientCredential);
    var accessToken = tokenResponse.AccessToken;
    return accessToken;
}

Try to get the token in this way, it should work.

A: The problem is that the load test uses the app.config from the host process "QTAgent_40.exe":
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\QTAgent_40.exe.config
<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
    <bindingRedirect oldVersion="4.5.0.0-9.0.0.0" newVersion="9.0.0.0"/>
</dependentAssembly>

The Newtonsoft.Json - dll is loaded from the folder "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\PrivateAssemblies" (Version 9.0).
But Microsoft.Rest.ClientRuntime 2.3.19 (and higher) requires Newtonsoft.Json 10.0.
Solution:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\QTAgent_40.exe.config
<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
    <bindingRedirect oldVersion="4.5.0.0-12.0.0.0" newVersion="12.0.0.0"/>
</dependentAssembly>


text:
Q: mpi.h not found I tried to compile the Hello World program in C, inside Eclipse PTP, but it gives me an error related to mpi.h.
I have included /usr/local/include and /usr/local/lib in my paths, and also tried running a search with find / -name mpi.h. I still get a No such file or directory error.
I tried to install mpich2, but still couldn't find mpi.h.
Also:

*

*There is no folder inside the include directory, why is that?

*I can find mpicc at /usr/bin/mpicc
The same problem occurs when trying to compile the project as C++ code. What should I do?

A: This Stack Overflow question answers yours.
According to yum, the mpi.h header file is provided by the following packages:
$ yum whatprovides '*/mpi.h'
openmpi-devel-1.8.1-1.el6.x86_64
mpich2-devel-1.2.1-2.3.el6.x86_64
mvapich2-devel-2.0rc1-1.el6.x86_64
mvapich-devel-1.2.0-0.3563.rc1.5.el6.x86_64
mvapich2-psm-devel-2.0rc1-1.el6.x86_64
mpich-devel-3.1-4.el6.x86_64
mvapich-psm-devel-1.2.0-0.3563.rc1.5.el6.x86_64

I've removed most of the output, as well as the i686 versions. Pick the package according to what (variant) you're trying to work with. :)
Note that most of these packages create  a subdirectory in /usr/include when installed. For instance, the mpi.h file provided by openmpi-devel is available at /usr/include/openmpi-x86_64/mpi.h, meaning you'd have to either include openmpi-x86_64/mpi.h in your source code, or add the /usr/include/openmpi-x86_64 directory to your include paths.
Also: some of these packages (such as mvapich-devel) don't even use /usr/include at all, and put their headers under /usr/lib64/{package}/include/.


text:
Q: case statement efficiency in c I have a large switch statement, with about 250 cases, in Visual C:
#define BOP -42
#define COP -823
#define MOP -5759

int getScarFieldValue(int id, int ivIndex, int rayIndex, int scarIndex, int reamIndex)
{
    int returnValue = INT_MAX;
    switch (id)
    {
        case BOP      : returnValue  = Scar[ivIndex][rayIndex].bop[scarIndex][reamIndex];    break;
        case COP        : returnValue  = Scar[ivIndex][rayIndex].cop[scarIndex][reamIndex];       break;
        case MOP         : returnValue  = Scar[ivIndex][rayIndex].mop[scarIndex][reamIndex];     break;
        .....
        default:  return(INT_MAX);
     }
}

The #defines, you will notice, have a huge range, from -1 to -10,000.  The thing is dog slow, and I'm wondering if spending several hours redefining these 250 defines to a narrower (or even consecutive) range could speed things up.  I always thought the compiler would treat the case values in a way that made their numeric value irrelevant, but I have not been able to find any discussion to validate/invalidate that assumption.

A: Disassemble the compiled code and see what the compiler does. I've looked at the output from several different compilers and large switch statements were always compiled into binary decision trees or jump tables. Jump tables are the most optimal thing you can get and they are more likely to be generated by the compiler if the values you're switching on are in a narrow range. It also helps have a default statement on some compilers (but not necessary on others).
This is one situation where disassembling is your only good option, the details of code generation on this level are rarely well documented.

A: Maybe you should use hash table, so you can search hash table instead of "switch case".

A: If you look at the assembly output for the code, you will probably notice that your switch statement is being compiled into code that resembles cascading if statements:
if (id == BOP) ...
else if (id == COP) ...
else if (id == MOP) ...
...
else ...

Because of this, a simple tip to speed up the switch statement is to move the most commonly hit cases near the top.
If the case values are sorted, then the compiler may be able to generate a binary decision tree, reducing the complexity from linear to logarithmic.
At a high enough optimization level on a compiler that supports it, the compiler may be able to generate a computed goto style code. For non-consecutive values, the offset to jump to would be stored in a hash table, and a perfect hash function is generated for the case values. For consecutive values, there is no need for a hash function, as a simple indexed array can be used to store the jump offsets. You would have to check the assembler output for the optimized code to see if your compiler supports this functionality.
Otherwise, it may be better to create your own hash on the case value, and instead of using switch, you would do your own hash table lookup to find the right matrix to use, and then acquire your value.

A: Simple solution:
Break switch case into multiple parts.
if(id<=50)
{
    switch(id)
    {
      //All cases between 0 to 50
    }
}
else if (id>50 && id<=100)
{
    switch(id)
    {
      //All cases between 51 to 100
}
//and so on

the choice of range is yours. And dont create many ranges. This will ensure a code faster than your current code.
Alternatively you can use function pointers and write functions containing the statements that are to be executed in the case.
I would have preferred this method.
typedef struct
{
    void(*Cur_FunctnPtr)();
}CMDS_Functn;

void (*Cur_Func)();
CMDS_Functn FunctionArray[66] = {
                    /*00-07*/    (*Func1),(*Func2),(*Func3),...
                    /*08-0F*/

                    /*40-47*/       };

void my_func()
{
...  //what ever code
    Cur_Func = FunctionArray[id].Cur_FunctnPtr; //Load current Function Pointer
        (*Cur_Func)();
... // what ever code
}

A: Read the code to figure out what the switch compiles to.
If you have a hash table implementation handy, you could try using that, but it will of course require you to extract all the "action" code into something you can jump to from a hashtable lookup result.
If using GCC, I would do a quick test combining GCC's computed goto with a simple sorted array so you can use good old binary search. The latter will cut the number of worst-case comparisons done by your code from 250/2 to log2(250), i.e. around 8.
This will require a look-up table declared at compile-time (and perhaps sorted, once, at run-time), which probably is better in terms of memory overhead than most hashtables will manage.

A: If you know the characteristics of the distribution of likely id values, test for them in  most-likely to least-likely order in your case statement.
If this gets called frequently, you might want to consider storing the choices in a Dictionary:  they get resolved without serial comparisons, and thus might save a lot of time if there are really 10,002 choices.

A: Your problem is that the range of the IDs is not consecutive. No compiler can do better on that than with a cascade of conditions of logarithmic depth, here about 8.
A method to heal this would be to use an enum that gets you the IDs consecutive and the compiler then can use a jump table to speed things up. To really know if that'd work you'd have to check the rest of your application to see if it supports changing the values.

A: The compiler will only optimise using techniques it's aware of, and if none of those techniques work then you'll get something terrible.
You could either implement something yourself, or you could try to give the compiler some clues.  In the latter case you have a fair chance of the compiler "getting it" and then optimising the solution further than your own implementation can -- and the compiler can avoid C syntax limitations which would constrain your own solution.
As for solutions; obviously the best is to renumber them to be consecutive.
Another approach is to take your 250 values and search for a perfect hash function to reduce them to an 8-bit quantity.
#define PERFECT_HASH(x) ((x) & 0xff) /* some clever function of x */

switch (PERFECT_HASH(id))
{
case PERFECT_HASH(BOP): returnValue  = Scar[ivIndex][rayIndex].bop[scarIndex][reamIndex];    break;
case PERFECT_HASH(COP): returnValue  = Scar[ivIndex][rayIndex].cop[scarIndex][reamIndex];       break;
case PERFECT_HASH(MOP): returnValue  = Scar[ivIndex][rayIndex].mop[scarIndex][reamIndex];     break;
.....
default:  return(INT_MAX);
}

But, having cut and paste that code, it looks like you're using a switch statement to convert id into what is effectively a pointer value to different pieces of the data structure.  If all the cases contain a single read of the same kind of pointer then you definitely don't want to use a switch for that.  You need to look at the shape of your data and find a way to compute that pointer more directly.  Or switch simply on the type and compute the address separately.


text:
Q: Convert data to array, and find count based on filters I have data stored in a text file (This is a requirement), which I've turned into an array…
Now I'm trying filter my results based on 2 variables $Start_Date & $End_Date
…then display only unique values with the count next to it.
Stats.txt
08/02/14 | Red | Wood
08/03/14 | Red | Steel
08/04/14 | Blue | Wood
08/05/14 | Red | Steel
08/05/14 | Red | Wood
08/05/14 | Red | Steel
08/05/14 | Blue | Steel
08/06/14 | Blue | Wood

What I have so far:
  $logfile = "stats.txt";
  $Start_Date = 08/04/14;
  $End_Date = 08/05/14;

  if (file_exists($logfile)) {

        $handle = fopen($logfile, "r");
        $log = fread($handle, filesize($logfile));
        fclose($handle);

  } else {
        die ("The log file doesn't exist!");
  }

  // Seperate each logline

  $log = explode("\n", trim($log));

  // Seperate each part in each logline
  for ($i = 0; $i < count($log); $i++) {
        $log[$i] = trim($log[$i]);
        $log[$i] = explode('|', $log[$i]);
  }

Desired Result: (based on $Start_Date = 08/04/14 and $End_Date = 08/05/14)

Date Count:

08/04/14 - 1
08/05/14 - 4

Color Count:

Red - 3
Blue - 2

Material Count:

Wood - 2
Steel - 3

A: write the code like this
$log = "08/02/14 | Red | Wood
08/03/14 | Red | Steel
08/04/14 | Blue | Wood
08/05/14 | Red | Steel
08/05/14 | Red | Wood
08/05/14 | Red | Steel
08/05/14 | Blue | Steel
08/06/14 | Blue | Wood";

$log = explode("\n", trim($log));
// Seperate each part in each logline
$dateFreq = array();
$colorFreq = array();
$MaterialFreq = array();
foreach ($log as $line) {
    $lineArr = explode("|", $line);
    $date = trim($lineArr[0]);
    $color = trim($lineArr[1]);
    $material = trim($lineArr[2]);
    if ($date >= '08/04/14' && $date <= '08/05/14') {
        if (isset($dateFreq[$date])) {
            $dateFreq[$date] = $dateFreq[$date] + 1;
        } else {
            $dateFreq[$date] = 1;
        }
        if (isset($colorFreq[$color])) {
            $colorFreq[$color] = $colorFreq[$color] + 1;
        } else {
            $colorFreq[$color] = 1;
        }
        if (isset($MaterialFreq[$material])) {
            $MaterialFreq[$material] = $MaterialFreq[$material] + 1;
        } else {
            $MaterialFreq[$material] = 1;
        }
    }
}
echo "
Date Count:
\n";
foreach ($dateFreq as $date => $freq) {
    echo $date, " - ", $freq, "\n";
}

echo "
Color Count:
\n";
foreach ($colorFreq as $color => $freq) {
    echo $color, " - ", $freq, "\n";
}

echo "
Material Count:
\n";
foreach ($MaterialFreq as $material => $freq) {
    echo $material, " - ", $freq, "\n";
}


text:
Q: Puting components using GridBagLayout on full screen My problem is that I want to make more complicated (for me) graphical interface for my project. First of all I'm using full screen mode with the code below:
public class MainFrame extends JFrame
{
...
private Container container;
private GridBagLayout gbl;

public MainFrame()
{
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice dev = env.getDefaultScreenDevice();
dev.setFullScreenWindow(this);
setLayoutManager();
}
...
}

and everything is ok.
The next step I do is adding two JPanels. Layout manager that I want to use is GridBagLayout.
private void setLayoutManager()
{
container = getContentPane();
gbl = new GridBagLayout();
container.setLayout(gbl);
}

private void addMenu()
{
MenuBar menu = new MenuBar();
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.ipady = 0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 0.05;
gbl.setConstraints(menu, gbc);
container.add(menu);
}

private void addWorkArea()
{
WorkArea area = new WorkArea();
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbl.setConstraints(area, gbc);
container.add(area);
}

And the result looks like that:

Here is my project:
Why is there is a strip on the top?
What is more when I click there and drag, all application is moving. Please help me. It is important for me to fill all the space get rid of JFrame moving.

A: You're going to laugh when I tell you what the problem is...
Java, for what ever reason, is allowing for the frames insets when it's laying out the content.  That is, it still believes that there is a title bar and frame border.
The fix is horrendously complicated though...
In your MainFrame constructor, you need to call setUndecorated(true) before you do anything else...
public MainFrame() {
    setUndecorated(true); // <-- Add me
    setFullScreen();
    setResizable(false);
    setTitle("Program");
    setLayoutManager();
    addMenu();
    addWorkArea();
}

I know, horrendously complicated (insert sarcasm :P - seriously, I surprised myself when it worked)


text:
Q: Get original sentences from CoreNLP I'm going through my data and want to split it into sentences. I'm using pycorenlp.
from pycorenlp import StanfordCoreNLP
nlp = StanfordCoreNLP('http://localhost:9000')
output = nlp.annotate(text, properties={
    'annotators': 'tokenize,ssplit',
    'outputFormat': 'json'
})
for tempsentence in output['sentences']:
     # store important sentences ...

Now I store some sentences which are important for my application.
Some of those contain " or ' and it seems that CoreNLP changes those sentences. " are converted into -LRB- and -RRB- if I remember that correctly.
Is it possible that I can get the orignial sentence from CoreNLP (since I need to do another CoreNLP run later on and if " is now gone, my data doesn't look orgininal and the 2nd CoreNLP run doesn't seem to recognise some quotiations anymore.

A: *

*Download and install the stanza library: https://github.com/stanfordnlp/stanza

*The returned result will have the original tokens.
example:
from stanza.nlp.corenlp import CoreNLPClient
client = CoreNLPClient(server='http://localhost:9000', default_annotators=['ssplit', 'tokenize'])
result = client.annotate("...")
for sentence in result.sentences:
  for token in sentence.tokens:
    print token.word + "\t" + token.originalText


text:
Q: Fluid mechanics - pressure We know that pressure inside a container depends on depth.
My question is that if this true then if I fill water in a one end closed pipe which has diameter of 2cm and height is 4m and if I fill the same water in a cylinder which has diameter 15cm and height 4m then pressure inside the bottom of the both container is the same?
See image

A: Yes, the pressure at the bottom of the two containers is the same. There is more water in the $15$cm diameter cylinder, but its weight is spread over a greater area.

A: Since Pressure $p$ equals force $F$ per area $A$, your pressure at any given height will be the same in both of your containers. The greater force due to the larger volume is spread over an equally larger area.
$p=\frac{F}{A}$

A: Yes, the pressure depends on height only, regardless of the shape of the container...
...as long as the pressure above the vessels is the same in both cases. I suppose you have atmospheric pressure in both cases, so it's the same.


text:
Q: HDMI not working in Ubuntu 18.04 (Razer Blade 14" 2017) I recently installed Ubuntu 18.04 on my Razer Blade and I have had a lot of issues with it, most of which I have managed to solve. One thing I cannot figure out though is how to get HDMI working. I am using the nvidia card and xrandr outputs this:
$ xrandr
Screen 0: minimum 8 x 8, current 3840 x 2160, maximum 32767 x 32767
eDP-1-1 connected primary 3840x2160+0+0 (normal left inverted right x
axis y axis) 309mm x 174mm
(tons of resolutions and refresh rates)
DP-1-1 disconnected (normal left inverted right x axis y axis)
HDMI-1-1 disconnected (normal left inverted right x axis y axis)

A: I just had a razer blade laptop with GTX 1070 MQ thermal or something. It was using nvidia-435 drivers. None of the hdmi or the thunderbolt was detecting external monitors.
xrandr also gives the same output as yours. My solution was to upgrade the nvidia graphics drivers through nvidia's website.
I choose the following options:
GeForce
GeForce 10 Series (Notebooks)
GeForce GTX 1070
Linux 64 Bit

It redirected me to a download which gave me a .run file, I right clicked it and gave it a permission to be executed as an executable (from properties)
executed it as a super user, it asked me to close everything that uses nvidia gpu, so i did a prime-select intel and rebooted the computer (this switches to intel gpu), and I re ran the installation, it failed again for some reason. I switched to nvidia graphics card with prime-select nvidia and restarted the computer. Afterwards I launched the nvidia-settings app to see the driver version. It said 440, however the ubuntu additional drivers pane says I have 435 installed. When I plugged in the hdmi and the thunderbolt my displays worked.I think it is an Nvidia driver issue.


text:
Q: Angular 8, trouble calling function from another component Trying to call a create-tag modal from a different Component.
The component I am working in is called pets and is located in:
app/main/ClientPatientManagement/Pets
Trying to access the show() method in:
app/main/tags/tags/create-or-edit-tag-modal.component'
Here is the code in my Pets.Component:
    import { CreateOrEditTagModalComponent } from '@app/main/tags/tags/create-or-edit-tag-modal.component';
@Component({
    templateUrl: './pets.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class PetsComponent extends AppComponentBase {

    @ViewChild('createOrEditTagModal', { static: true }) createOrEditTagModal: CreateOrEditTagModalComponent;

Here are some other code including ngOnInit etc. but I want to call the below function when a button is pressed:
createTag(): void {
        this.createOrEditTagModal.show();
    }

My problem is that I keep getting an error saying my this.createOrEditTagModal is undefined.
I have also imported this component in my main.module.ts and added it to my declarations there.
Can anyone help me as to why this keeps being undefined?
EDIT:
For completeness, I added some code from create-or-edit-tag-modal-component
@Component({
    selector: 'createOrEditTagModal',
    templateUrl: './create-or-edit-tag-modal.component.html'
})
export class CreateOrEditTagModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal', { static: true }) modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    constructor(
        injector: Injector,
        private _tagsServiceProxy: TagsServiceProxy
    ) {
        super(injector);
    }

    show():void{
        console.info("Called tag component successfully!"); //for testing
    }

A: Good news, found the problem!
the problem was in my pets.component.html.
I forgot to declare my modal there, so I added this in pets.component.html:
<createOrEditTagModal #createOrEditTagModal (modalSave)="getPets()"></createOrEditTagModal>

This manage to fix the issue, running now smoothly and error free.
Note that the getPets() function gets called after the modal's own save function, so it just basically refreshes the page.

A: I think this first parameter is wrong in your code.
@ViewChild('createOrEditTagModal', { static: true }) createOrEditTagModal: CreateOrEditTagModalComponent;
Should be changed as
@ViewChild(CreateOrEditTagModalComponent, { static: true }) createOrEditTagModal: CreateOrEditTagModalComponent;
Also, make sure pets.component.html has CreateOrEditTagModalComponent in it.

A: Can you please try to give a Directive decorator like this :
@Directive({selector: 'createOrEditTagModal'})
export class CreateOrEditTagModalComponent extends AppComponentBase {


text:
Q: Mui TabList overflowing when wrapped inside a grid In the code below the tabs are overflowing past the visible width after wrapping in the TabsWrapper. I have a use case where the tabs will always be rendered in a similar wrapper. Is it possible to override some styles in ScrollableTabs to achieve the default behaviour?

*

*I'm getting the feeling that there should be a fix as this seems like a common use case w.r.t to CSS Grid and Flex.

*Just in case you aren't familiar with the default behaviour, try rendering ScrollableTabs without it being wrapped in the TabsWrapper.
import React from "react";
import { TabContext, TabPanel, TabList } from "@mui/lab";
import { Box, Tab, Stack } from "@mui/material";

/** Cannot be changed */
function TabsWrapper(props) {
  return (

{props.children}

  );
}

/** Cannot be changed */
function MyTabList(props) {
  return (
    <Stack direction="row">
      <TabList
        orientation="horizontal"
        variant="scrollable"
        onChange={props.onChange}
      >
        {props.children}
      </TabList>
    </Stack>
  );
}

/** Can be changed */
export default function ScrollableTabs() {
  const tabValues = [...Array(30)].map((_, index) => String(index + 1));
  const [tab, setTab] = React.useState("1");

  const handleChange = (_, newValue) => {
    setTab(newValue);
  };
  return (
    <TabsWrapper>
      <TabContext value={tab}>
        <MyTabList onChange={handleChange}>
          {tabValues.map((value) => (
            <Tab label={`Tab ${value}`} value={value} key={value} />
          ))}
        </MyTabList>
        <Box>
          {tabValues.map((value) => (
            <TabPanel value={value} key={value}>
              Tab content {value}
            </TabPanel>
          ))}
        </Box>
      </TabContext>
    </TabsWrapper>
  );
}

*

*Working codesandbox - https://codesandbox.io/s/mui-custom-scrollable-tabs-2mfcjr
Thanks!

A: Wrapping TabContext in
 fixes the issue.
The ScrollableTabs jsx should look like -
export default function ScrollableTabs() {
  const tabValues = [...Array(30)].map((_, index) => String(index + 1));
  const [tab, setTab] = React.useState("1");

  const handleChange = (_, newValue) => {
    setTab(newValue);
  };
  return (
    <TabsWrapper>

        <TabContext value={tab}>
          <MyTabList onChange={handleChange}>
            {tabValues.map((value) => (
              <Tab label={`Tab ${value}`} value={value} key={value} />
            ))}
          </MyTabList>
          <Box>
            {tabValues.map((value) => (
              <TabPanel value={value} key={value}>
                Tab content {value}
              </TabPanel>
            ))}
          </Box>
        </TabContext>

    </TabsWrapper>
  );
}

*

*Working codesandbox - https://codesandbox.io/s/mui-custom-scrollable-tabs-forked-6ycqfv


text:
Q: TypeError: unsupported operand type(s) for +: 'set' and 'set' returning multiple param vals I'm kinda beginner using python from javascript, and wanting to return param vals together into an api... I've been trying to use + though it give's me error
"TypeError: unsupported operand type(s) for +: 'set' and 'set'"
How do correcting this?

def generate_ad(product_type: str, product_name: str, platform: str, audience: str) -> str:
    # Load your API key from an environment variable or secret management service
    product_type = f'Write a creative ad for {product_type} '
    product_name = f'named {product_name}'
    platform = f'to run on {platform} '
    audience = f'aimed at {audience}:'

    enriched_prompt = product_type + product_name + platform + audience

test API call:

from fastapi import FastAPI
from riplir import generate_ad

app = FastAPI()

@app.get("/generate_snippet")
async def creative_ad_api(product_type: str, product_name: str , platform: str, audience: str):
    snippet = generate_ad({product_type} + {product_name} + {platform} + {audience})

    return {
        "message": snippet,
        }

# uvicorn riplir_api:app --reload

A: Either the generate_ad function input is a string, which you can build using f-string:
@app.get("/generate_snippet")
async def creative_ad_api(product_type: str,
                          product_name: str,
                          platform: str,
                          audience: str):
    snippet = generate_ad(f'{product_type} + {product_name} + {platform} + {audience}')

    return {
    "message": snippet,
    }

Or the input is a set, which can be built from the 4 string parameters:
@app.get("/generate_snippet")
async def creative_ad_api(product_type: str,
                          product_name: str,
                          platform: str,
                          audience: str):
    snippet = generate_ad(set(product_type, product_name, platform, audience))

    return {
    "message": snippet,
    }

Or simply, you have 4 inputs:
@app.get("/generate_snippet")
async def creative_ad_api(product_type: str,
                          product_name: str,
                          platform: str,
                          audience: str):
    snippet = generate_ad(product_type, product_name, platform, audience)

    return {
    "message": snippet,
    }


text:
Q: Stored procedure output parameter using sp_executesql returning null I'm trying to determine why a db call in .Net is failing with an output parameter.  I'm using Dapper ORM to make the call and this is a bare bones sample of the trace.  It uses sp_executesql to parametrize the call and I think there lies the problem with the output parameter.
Consider this code:
CREATE PROC test
    @addressId INT = NULL OUTPUT
AS
    -- using select and set to see if if makes a difference using either
    select @addressId = 1
    SET @addressId = 1
GO

declare @p3 int
set @p3=NULL
exec sp_executesql N'test',N'@addressId int output',@addressId=@p3 output
select @p3

I would expect select @p3 to return 1, why does it return null?

A: You need to explicitly declare @addressId as an output parameter in the stored procedure call in exactly the same way you would if you weren't using dynamic SQL:
declare @p3 int
set @p3=NULL
exec sp_executesql N'EXEC test @addressId=@addressId OUTPUT',N'@addressId int output',@addressId=@p3 output
select @p3

Without dynamic SQL, the code would have to be:
declare @p3 int
set @p3=NULL
EXEC test @addressId=@p3 OUTPUT
select @p3

A: As mentioned, the problem is that the dynamic SQL isn't actually passing the parameter through.
However, in this instance, you don't actually need dynamic SQL at all.
declare @p3 int;
exec test @addressId=@p3 output;
select @p3;

Furthermore, it's highly likely that you were simply using SqlCommand incorrectly.
SqlCommand.CommandType defaults to CommandType.Text which explains why the above code was generated, as it expects that the text is an SQL batch rather than the name of a stored procedure. No error was generated because it's valid to call a procedure without using the keyword EXEC.
If you use CommandType.StoredProcedure then everything should just work.


text:
Q: how to avoid shortcut closed xml tags if value is empty in simplexml addChild? I created a xml generator using PHP SimpleXML, the problem now is, whenever there are empty values, the element that was added is inserting a shortcut closed tag, instead of a complete tag. like e.g
instead of this
<mytag></mytag>

the output is giving me this
<mytag/>

how to fix this issue with the addChild() of simpleXMLElement of PHP ?

A: Self-closing tags are a normal part of XML, so normally, you should just not worry about them.  However, if you really want to avoid them and use the full <mytag></mytag> even when empty, SimpleXML doesn't have that option but DOM does, and you can convert to DOM when you output.
For example, if you're using
$xml->asXML()

Change it to
dom_import_simplexml($xml)->ownerDocument->saveXML(null, LIBXML_NOEMPTYTAG);


text:
Q: Connect to Azure SQL on Private Link using Azure DevOps I would like to know, is there any way to connect to the Azure SQL server configured using Private endpoint via Azure DevOps. I have a Azure SQL database deployment task which is not able to connect to the SQL server since the server is configured using private endpoint.
I would like to know the way if any, to connect to the Azure SQL Server configured using private endpoint via Azure DevOps.
Any lead would be really helpful.

A: As it is said here.

Clients can connect to the Private endpoint from the same VNet, peered VNet in same region, or via VNet-to-VNet connection across regions.
Additionally, clients can connect from on-premises using ExpressRoute, private peering, or VPN tunneling. Below is a simplified diagram showing the common use cases.

You can create a self-hosted agent on the azure SQL server VM, or on an Azure VM which is connected to the same VNet. Check here for detailed steps to create self-hosted agent.
You can also create a self-hosted agent on your local machines. And using ExpressRoute, private peering, or VPN tunneling to connect to the Private Endpoint. For more information, check the document Connecting from an on-premises environment over VPN
Then you can run your pipeline on the self-hosted agent by setting the pool to your private agent pool which hosts the self-hosted agent. Your pipeline should be able to connect to the SQL server, since the agent machine is configured to connect to the Private Endpoint.

A: There could be other easier ways but one way possibility could be is using a self hosted agent at on-premise which has got access to the Private endpoint.


text:
Q: URL did not return json (from remote machines only) I am using MVC ASP.NET 4
when I load a page I get "The requested URL did not return json" error message.
the problem occurs when I open the webpage from a remote machine.
If I open the webpage from a browser on the server machine, it works fine without any problem.
When the problem occurs and I click on the left-bottom icon
of the errors I get the message:
"'d' is null or no an object" in the asset.axd file.
I tried remote debugging without any luck.
thanks,
Aviad.


text:
Q: How to make a hyperlink through GridView column value?
I want here that user can see the answer under the question by selecting its heading. The question should be a hyperlink to redirect me on the page Answer.aspx. I mean to say that when user take cursor over the How to do this? it should redirect the user to the desired page. How can I do that?
here is the code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
       DataSourceID="SqlDataSource1" Width="100%" BorderStyle="None">
       <Columns>
     <asp:BoundField DataField="QuestionHEAD" HeaderText="Question"
                                        SortExpression="QuestionHEAD" HeaderStyle-ForeColor="white" HeaderStyle-BackColor="Brown"/>
                                    <asp:BoundField DataField="Problem" HeaderText="Problem"
                                        SortExpression="Problem" HeaderStyle-ForeColor="white" HeaderStyle-BackColor="Brown" />
                                    <asp:BoundField DataField="Forum" HeaderText="Forum" SortExpression="Forum" HeaderStyle-ForeColor="white" HeaderStyle-BackColor="Brown"/>
                                    <asp:BoundField DataField="Username" HeaderText="Asked By"
                                        SortExpression="Username" HeaderStyle-ForeColor="white" HeaderStyle-BackColor="Brown" />
                                </Columns>
                            </asp:GridView>
                            <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                                ConnectionString="<%$ ConnectionStrings:connectionstring %>"
                                SelectCommand="SELECT [QuestionHEAD], [Problem], [Forum], [Username] FROM [Question]">
                            </asp:SqlDataSource>

A: You can use a HyperLinkField for this:
<asp:HyperLinkField DataNavigateUrlFormatString="/somepage.aspx?a={0}&b={1}" DataNavigateUrlFields="Column1, Column2" />

A: Try something like this
Eval("id") should be the question id and Eval("Question") should be the question field in your database

 <asp:TemplateField HeaderText="Question" HeaderStyle-HorizontalAlign="Center"  ItemStyle-HorizontalAlign="Center">
        <ItemTemplate>
            <a href="Answers.aspx?ID=<%#Eval("id")%>"> <%#Eval("Question")%>
        </ItemTemplate>
    </asp:TemplateField>


text:
Q: Is there a Java annotation for bugs? I'm looking for a standard Java annotation that allows me mark some code as "related to bug PROJECT-312". The goal is to be able to create a report where I can see which parts of the code were changed or impacted by a bug. This would, for example, allow to see "hot spots" where a lot of bugs accumulate. Or it would make it easy to go from the IDE to JIRA/BugZilla to see what the bug is all about.
Is there a standard annotation that I can/should use or do I have to write my own?
PS: I'm aware of Mylyn/Tasktop which would do the tracking for me. For my purposes, these tools are too disruptive right now since they substantially change how people have to work every day.

A: Oracle approach

The Java API Specification should contain assertions sufficient to
  enable Software Quality Assurance to write complete Java Compatibility
  Kit (JCK) tests.
This means that the doc comments must satisfy the needs of the
  conformance testing by SQA. The comments should not document bugs or
  how an implementation that is currently out of spec happens to work.

From the official JavaDoc guidelines:

Code bugs are bugs in the implementation rather than in the API
  specification. Code bugs and their workarounds are often likewise
  distributed separately in a bug report. However, if the Javadoc tool
  is being used to generate documentation for a particular
  implementation, it would be quite useful to include this information
  in the doc comments, suitably separated as a note or by a custom tag
  (say @bug).

So basically it's telling you don't mix documentation with bug reporting. Use and parse a special custom tag in comments, you don't really need more than that for a successful bug report.
Also, with Eclipse Jira Connect or similar tools you can have your @bug and TODO comments transformed to bug/task tickets automatically.
Update
If you must, you could do with a couple of custom annotations. Tailor to your needs, document and enforce across the team. More on it here.
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.CLASS)
// Unavailable through reflection.
public @interface classbug {}
// gives you the @classbug annotation.

@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.CLASS)// Unavailable through reflection.
public @interface methodbug {}
// gives you the @methodbug annotation.

A: I'm not personally convinced annotations are the right way to track hot spots.  For one, they'll get ugly in areas with lots of bugs (more @Bug lines than real code!) and for another, they'll unhelpfully populate places that aren't likely to regress, like an Off-By-One error when some code is first implemented.
More to the point, an @Bug annotation is only useful if it's used, and used consistently.  Enforcing this will be a hassle for all involved, and will slow people down without actually providing much insight, since you have no way of knowing what code was impacted by a bug and didn't get annotated.
Better, I would say, would be to implement some external analysis that looks at the files impacted by bug fix revisions (Commit message contains [bB][uU][gG]:? *\d+ or something similar) and runs analysis that way.  You can rapidly inspect all bug fixes, without adding any extra process for your developers.
Google has an interesting paper to this end: Bug Prediction at Google

To your comment about annotations being more "sticky" than comments, that they have a better chance of survival, I would similarly wonder how often that difference would be valuable in practice.  I find it more often that bug comments in code are no longer informative, and stick around longer than they should as is.  If svn|hg|git|whatever blameing the relevant lines doesn't reveal the commits associated with the bug in question, it's likely been iterated on several times since then, yet the comment sticks around.
I'm certainly not saying what you describe never happens, but I wonder how often this is really the case.  If in your experience comments disappear when the could have still been helpful, by all means, see if annotations might do better.


text:
Q: Rezise root partition using other hard disk I have a hd of 150GB and other of 300GB, both partitioned, the former with a root partition and the latter with some unused space.
How can I use the unused space of the second to extend the root partition of the first?

A: If you're not using LVM (or btrfs or ZFS), then "move and symlink" is the best you can do.
Format the partition if it isn't already formatted, and mount it somewhere "generic", like /exra.  Put the mount in /etc/fstab so it'll be mounted on every reboot.  Then move and symlink large directories from the root filesystem to the /extra filesystem.
For example, to move /usr/share/doc to /extra/usr/share/doc:
# uncomment if not already mounted
# mkdir -p /extra
# mount /extra

mkdir /extra/usr/share/
mv /usr/share/doc/ /extra/usr/share/
ln -s /extra/usr/share/doc/ /usr/share/

All of this has to be done as root, of course, so sudo -i first to get a root shell.
Note: you can't safely move directories which have files currently in use by other processes...so if you want to move, say, /var/lib/mysql to /extra/var/lib/mysql you'll have to do it while mysql is temporarily shut down, or while rebooted into recovery mode.
You also can't move files/dirs that are needed early in the boot process.  That means don't move /etc, /bin, /sbin, /lib (or any subdirectories thereof).


text:
Q: 2D Array Method Text Formatting I'm new to Java and recently learned how to use loops and array.
It took me quite a while but now I got the numbers in the right index and print orders. My only issue is that it's printing without aligning to each other. (like in a table - row/column)
I found out about
System.out.format("%-4d", table[t][i]);

of "Roby Cornelissen" on stackoverflow, but since I need a return and on top of that don't use the array but a variable, I'm out of ideas. String.format didn't seem to work for me either, or I used it wrong.
Here is my method:
    public String generateBoard(){
        int total = board.length * board[0].length;
        int zaehler = 0;
        String line = "";
            for( int row = 0; row < board.length; row++){
                zaehler = ( total + 1 ) - ( (row + 1 ) * board[row].length );
                for  ( int col = 0; col < board[row].length; col++){
                    board[row][col] = zaehler++;
                    line = line + board[row][col] + " ";
                }
                line = line + "
";
            }
        line = line + "";
        return (line);

}

I appreciate every help / tips.


text:
Q: CURL PHP HEADER DATA I am trying to use jobcrank feeds api and it requires data to be sent in headers
I want to make request in the following format
POST /v2/QueryService.asmx/QueryJob HTTP/1.1
Host: api.jobcrank.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length

and the query parameters will be sent in following method
apiKey=string&apiSerial=string&serviceTypeID=string&jobType=string&keyWordsType=string&keyWords=string&stateAbbreviation=string&county=string&city=string&isWorkFromHome=string

I have written code also for this but dont know how to send header containing
"POST /v2/QueryService.asmx/QueryJob HTTP/1.1" line
Here is my code:`
<?php
        $fields = array(
    'apiKey'=>'XXX',
    'apiSerial'=>'XXXX',);
$fields_string="";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'/v2/QueryService.asmx/QueryJob');
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
$result = curl_exec($ch);
print $result;
?>

A: CURLOPT_URL requires an absolute URL with scheme and host:
curl_setopt($ch, CURLOPT_URL,'http://example.org/v2/QueryService.asmx/QueryJob');

A: You don't need to set this header - it is being done automatically. What you however need to do is to urlencode your $fields_string, because it may contain forbidden characters like white space. To do this, use http_build_query to build this string directly from your array:
$fields_string = http_build_query($fields);

It will urlencode the values and make the valid post string.

A: You don't have to explicitly add POST header. Curl will do that for you, just set CURLOPT_POST flag to true and that is it.
curl_setopt ($ch, CURLOPT_POST, TRUE);

Have a look at this site when in doubt: http://php.net/curl_setopt


text:
Q: How to test change unit in mongock with its multiple attributes/lifecycle methods? We recently migrated from MongoBee to Mongock, and with Mongock 5 version the @ChangeLog and @ChangeSet are depricated. Writing the @ChangeUnit is easy enough and rollback methods are very helpful.
However, I'm unable to figure out how to write a test simulating the migration in test DB and validating the changes in DB, as there are @BeforeExecution, @RollbackBeforeExecution, @Execution and @RollbackExecution attributes or lifecycle methods in a @ChangeUnit.
Earlier, I used to just call the method with @ChangeSet annotation like
assertOriginalStructure();
someMigrationChangeLog.updateIndexOnSomething();
assertIndexUpdated();

Now, I'm unsure if there is a clean way to write the above test as there is some logic in @BeforeExecution and also in @Execution. I know individually calling the annotated methods will work, but I wanted to know if there is a way to just run one @ChangeUnit as a whole.

A: In the new version 5, the basic change is that a ChangeUnit holds the unit of execution. That's normally done in the method annotated with @Execution, so the first approach is just doing the same you are doing but calling the @Execution method:
assertOriginalStructure();
someMigrationChangeUnit.updateIndexOnSomething();//annotated with @Execution
assertIndexUpdated();

However, your ChangeUnit can also provide@BeforeExecution, which would be used to perform any action that cannot be within the execution, for example, in a transactional MongoDB migration, DDL are not allowed inside a transaction, so that would be done in the @BeforeExecution. So if your changeUnit has both, @Execution and @BeforeExecution, you should do this:
assertOriginalStructure();
someMigrationChangeUnit.beforeExecution();//annotated with @BeforeExecution
someMigrationChangeUnit.updateIndexOnSomething();//annotated with @Execution
assertIndexUpdated();


text:
Q: Has the syntax using SCP changed? Getting unexpected filename error on newer servers I have two servers, lets call them SERVER1b and SERVER2.
SERVER1b reaches out to SERVER2 every night to grab my database dumps, they are titled as folows:
- dump1.sql.bz2
- dump2.sql.bz2
- dump3.sql.bz2

I have a bash script that simply runs the following command:
BLOG_ZIP_FILE="dump1.sql.bz2"
BLOG2_ZIP_FILE="dump2.sql.bz2"
BLOG3_ZIP_FILE="dump3.sql.bz2"
scp server2:"$BLOG_ZIP_FILE $BLOG2_ZIP_FILE $BLOG3_ZIP_FILE" /Volume1/Backups/

server2 is an alias used to connect via SSH to the server.
Whats interesting is that I had this script on a previous server, lets call it SERVER1a that has the exact same paths and it worked fine with the only difference being it was a few years older (maybe older version of SCP?)
Whenever I execute the SCP command on SERVER1b I get the following error:

error: unexpected filename: dump1.sql.bz2

Of course I've double checked the files actually exist, although I don't think that would even be the issue as a different error would be shown.
Edit: Added verbose dump (the most relevant bit)
Authenticated to host.com ([xx.xx.xx.xx]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: Sending command: scp -v -f dump1.sql.bz2 dump2.sql.bz2 dump3.sql.bz2
Sending file modes: C0664 54580203 dump1.sql.bz2
Sink: C0664 54580203 dump1.sql.bz2
error: unexpected filename: dump1.sql.bz2

A: To copy 3 files in a single command, this syntax should work:
scp server2:"{$BLOG_ZIP_FILE,$BLOG2_ZIP_FILE,$BLOG3_ZIP_FILE}" /Volume1/Backups/

(The server will expand this correctly.)

A: I think the problem is that the server-side thinks that dump1.sql.bz2 dump2.sql.bz2 dump3.sql.bz2 is three files, while the client-side thinks it's just one file with spaces in its name.
Until some security improvements that were made to OpenSSH in 2018, the client-side wouldn't have validated what the server-side was doing, so as long as you liked the server-side behavior, it would have worked fine. But now the client-side is doing validation, and complaining about the mismatch between what it told the server to do and what the server is actually doing. (See https://sintonen.fi/advisories/scp-client-multiple-vulnerabilities.txt for more information about this.)
To fix this, you can pass the three filenames as separate arguments to scp, so that both sides will agree about what's supposed to be sent:
scp "server2:$BLOG_ZIP_FILE" "server2:$BLOG2_ZIP_FILE" "server2:$BLOG3_ZIP_FILE" /Volume1/Backups/


text:
Q: What is the minimum output frequency according to this datasheet? Can this DDS output down to 0.05Hz sine?
I think the resolution is 0.0291 Hz. Does that mean that is also the miimum freq. it can synthesize?

A: The resolution of the DDS is equal to the clock frequency divided by 2^32 since the tuning word is 32 bits long.  For a 125 MHz clock (the maximum allowed) this results in a minimum frequency of 0.029 Hz. If you need lower frequencies, just use a lower speed clock.  The minimum clock frequency specified is 1 MHz.  This would result in a minimum frequency of 0.0002328 Hz which could be increased in steps of the same amount. You could, of course, use any clock frequency between 1 and 125 MHz to suit your requirements.

A: Yes, at a clock frequency of 125 MHz.
You can always run it at a lower reference clock frequency — the minimum is 1 MHz, and a setting of 215 would give you an output frequency of 0.05006 Hz.


text:
Q: How to add animation to textures Recently, I saw the best map ever, and it had a menu identical to the main minecraft menu, and I'm trying to replicate it. I believe I have found a way, but it requires more knowledge than the internet is willing to offer. I need the 'pumpkinblur' texture to:
1. Have multiple possible textures, and
2. Change between these textures based on where I am looking (similar to the rx, rxm, ry, and rym arguments)
also, why is there no minecraft-resourcepacks/ minecraft-textures tag?

A:
I need the 'pumpkinblur' texture to: 1. Have multiple possible texture

There is no way, in vanilla Minecraft, to have the pumpkinblur texture have multiple frames. You can animate the texture of blocks and items, but not the more irregular textures like paintings, GUI elements, etc..

How to add animation to textures

The basis of animating a block/item is that each frame should be below the previous one vertically. The width of the image is taken as the height of each frame (16px here):

Then, a file with the same name as the texture you're animating (including the .png), but with .mcmeta on the end, must exist in the same directory as this texture.
To have the animation play (at 20FPS) all that you'll need to do is open up the .mcmeta file with a text editor, and add the following:
{ "animation": { } }

There's a fair bit that you can do with animated textures, such as interpolation ("fading") and changing frame order, so you may want to look at the wiki page on it or a tutorial.

Change between these textures based on where I am looking (similar to the rx, rxm, ry, and rym arguments)

You cannot change between frames of the same texture based on rotation, but you could change an item's data value or switch to a different item (this doesn't work with pumpkinblur) that has a different texture. For example, replacing the player's first hotbar slot with a hoe with a certain damage value if they look upwards:
/replaceitem entity @a[rxm=-90] slot.hotbar.0 diamond_hoe 1 25

This is likely how the menu you saw worked, giving different items or data values different menu textures, changing the item's model rotation so that they face the player when held, and then changing what item the player is holding based off of their rotation.
Could also be teleporting a mob with the item on its head to where the player is facing, or just constantly teleporting a player so that they look at a textured changing block, I can't really tell without knowing what the map is.


text:
Q: Mouse scrolling issue in a specific section in pagepiling.js While scrolling a specific area that will scroll the entire section. overflow scroll section not working properly.
.scroll_sec {
  width: 500px;
  height: 300px;
  margin: 0 auto ;
  overflow-y: scroll;
}

Please check the code: https://codepen.io/anon/pen/PBzyrz

A: Finally, I got the answer to this question.
There is an option for normalScrollElements in pagepiling.js. We can mention the class or id of the overflow scroll section.
Please check the code from here: https://codepen.io/anon/pen/VBRpKa


text:
Q: How to split a Msg from ValueError? I have following code:
try:
#do something
except ValueError as e
print(e) #prints 'ABC is not avalaible'

Now i want the split e using e.split() method but it gives me error. How to split this ValueError msg e?

A: Cast e as a string first by doing str(e)and then you can use split on that.
str(e).split()

A: After debugging I found out e is not a simple string. So below code worked for me:
e.args[0].split()


text:
Q: How can I get a variable's address inside kernel? Currently, I want to get the address of runqueues, which is a variable in the kernel and not planned to be visible to modules or code outside.
I can get the address of runqueues by checking /proc/kallsyms. But this address is not the real address because of the ASLR.
I really do not want to change kernel so I decide to insert a module.
Does anyone know how to get the address of the variable inside the kernel?
Thanks in advance!

A: Your Queries :-

I want to get the address of runqueues, which is a variable in the
  kernel?

runqueue is represented by struct runqueue, that is a core data structure in the scheduler instead of variable.

I can get the address of runqueues by checking /proc/kallsyms.

There are some macros are used to obtain the runqueue associated with a given processor or process. from this macro we are getting the base address of array of runqueue structure and CPU id. I believe you can not retrieve the runqueue info from /proc/kallsysm.

*

*The macro cpu_rq(processor) returns a pointer to the runqueue associated with the given processor.

*The macro this_rq() returns the runqueue of the current processor;

*The macro task_rq(task) returns a pointer to the runqueue on
which the given task is queued.

So, I think to get the info of all runqueue, you have make multi-threading application and dedicate each thread to specific CPU (set cpu affinity).


text:
Q: I'm trying to make a discord bot that DM's a random user and It either DM's me only or I get an error This is my code and It seems the random user selection is broken although it works completely fine in another command I have that pings a random user
client.on('message', message => {
    if (message.content.toLowerCase() === `${prefix}command`) {

    const userList = message.guild.members.cache.array();
    var randomNumber = Math.floor(Math.random() * userList.length)
    var dm = userList[randomNumber]

    console.log(dm.user.id)

    dm.send("123");
}

A: ok, so the code you have written works just fine. The problem is that your bot cannot send a message to its self. There is a very easy solution to this. Just check if the selected member is a bot and return if that's the case. Note: I put your random number inside the array field of the userList.
const userList = message.guild.members.cache.array();
var dm = userList[Math.floor(Math.random() * userList.length)];
if (dm.user.bot) return;

console.log(dm.user.username);

dm.send("123");

Note: If you only have yourself and the bot on your test server then this will only ever send a DM to you. In that case I would recommend getting a secondary account and inviting some friends to the test server.

A: Have you enabled the members intent? The members list only shows you and the bot if you don't have that intent enabled. Read the docs for intents for more information.


text:
Q: When command `Brew install python@2` then error - `Theme error`. How to resolve? When
brew install python@2
Then occurs error:
==> make html
Last 15 lines from /Users/oleksandr-yefymov/Library/Logs/Homebrew/python@2/05.make:
writing output... [ 98%] whatsnew/2.1
writing output... [ 98%] whatsnew/2.2
writing output... [ 98%] whatsnew/2.3
writing output... [ 99%] whatsnew/2.4
writing output... [ 99%] whatsnew/2.5
writing output... [ 99%] whatsnew/2.6
writing output... [ 99%] whatsnew/2.7
writing output... [100%] whatsnew/index

generating indices... genindex py-modindex
writing additional pages... download index
Theme error:
An error happened in rendering the page index.
Reason: TemplateNotFound()
make: *** [build] Error 2

READ THIS: https://docs.brew.sh/Troubleshooting

When: brew doctor
Then: Your system is ready to brew.
OS - Mac Mojave
Any ideas what is that and how to resolve?

A: I had this same problem.
What I did was
$ brew install --debug --verbose python@2

At the HTML failure point, I reached this:
debrew.rb:11:in `raise'
BuildError: Failed executing: make html
1. raise
2. ignore
3. backtrace
4. irb
5. shell
Choose an action: 2
==> Cleaning

I chose (2), Ignore - And the setup continued as expected.

A: I met the same problem, and solved it with ignoring make html step, under CentOS7 with linuxbrew.


text:
Q: Retrieving the COM class factory for component with CLSID {00020906-0000-0000-C000-000000000046} failed due to the following error: 80070005 I am getting the above mentioned error when my web service tries to open MS word document programatically through my .net webb service.
When I run web service through visual studio, it works fine but when I deploy web service on IIS 7, I get the error

Retrieving the COM class factory for
   component with CLSID
   {00020906-0000-0000-C000-000000000046}
   failed due to the following error:
   80070005

I have seen similar questions and tried their solutions on Stackoverflow, MSDN and other resources also but none of them worked for me. Most of the questions were old dating back to 2008/ 2007.
I have tried to change DCOM setting using dcomcnfg command and I have added 'Network Service', 'Network' users, also have added my own user id in 'Microsoft Word Document' component properties and given them full permission. I have also added impersonate=true property in web.config. After doing all this also I am getting error. Can anyone please help me out?
I am trying all this on MS vista 32 bit OS and Office version is Office 2003.

A: I'm not using a web service, but a windows service and I had the same error generated when the service called an executable that attempted to create an Excel object.  I've also read many of the other resources and none of them quite worked for me.  Several were very close which led me to solve the issue in the following way:

*

*I went to the server...Start..Run and ran "dcomcnfg".

*Navigate to Component Services...Computers...My Computer...DCOM Config...Microsoft Excel Application.

*Open properties and select the Identity tab.

*Select "The launching user" (instead of "The interactive user") radio button and click OK to close the properties dialog.

The error went away and the app produces the Excel file when the service runs.
I'm investigating if it is possible to get this working from a Windows service some other way because I'm not sure if this solution will have side effects.  I will update further if I figure anything else out.


text:
Q: "I ordered us..." vs. "I ordered for us..." vs "I ordered ... for us" I usually use a phrase such as:

(1) I ordered us a box.

Would it be more correct to say:

(2) I ordered for us a box.

Or, better still:

(3) I ordered a box for us.

Example 3 sounds the most correct, but are 1 and 2 improper English or are they perfectly valid in written form?

A: (1) and (3) are equally grammatical, but (2) is ungrammatical. Order is a ditransitive verb, which means it can be followed by an indirect and a direct object as in (1), but it is possible to replace the direct object with a prepositional phrase, as in (3).


text:
Q: Android GPS Location Speed Unreliable Writing a GPS logging application~
I'm finding the values returned by the getSpeed() method on Locations reported by LocationManager are massively unreliable. I'm using LocationManager.GPS_PROVIDER, filtering the Locations provided through onLocationChanged for best accuracy. Even at single digit accuracy levels the speed returned is generally ridiculously high. We're talking up to 200 mp/h (yes I know it's logged in metres/sec) when the phone is stationary.
I'm testing the same code base on two different model Android phones, running two different OS versions, and seeing the same issues so I expect this is a code issue.
What am I missing? I've tried averaging locations over a window of time, to no avail. Am I going to have to work out my own speed values based on distance travelled / time? This would be disappointing.
As you will see, I'm not doing anything special - a little filtering for accuracy, even after this both AverageSpeed and _bestLocation.getSpeed() are regularly unfeasibly high, even when accuracy of the location is good.
public void onLocationChanged(Location location) {
    if (location.getAccuracy() < 25f) {
        _recentLocations.add(location);

        if (_bestLocation == null || location.getAccuracy() <= _bestLocation.getAccuracy())
            _bestLocation = location;
    }

    if ((_bestLocation != null && _bestLocation.getAccuracy() < 10f && _recentLocations.size() >= 10)
            || _recentLocations.size() >= 25)
    {
        int Count = 0;
            float TotalSpeed = 0f;
            float AverageSpeed = 0f;
            for (int i = 0; i<_recentLocations.size(); i++) {
                if (_recentLocations.get(i).hasSpeed()) {
                    Count++;
                    TotalSpeed += _recentLocations.get(i).getSpeed();
                }
            }

        if (Count > 0)
                AverageSpeed = TotalSpeed / Count;
        }
}

A: I have worked on GPS hardware for more than 7 years now. The accuracy reading is also not 100% accurate.
Manufacturers state accuracy along with the system used for measuring it.
CEP, RMS, 2DRMS, and R95 are some of the systems.
Read this article for more information: http://en.wikipedia.org/wiki/Circular_error_probable
The accuracy figure does not include outliers. For example, if stated accuracy 5 meters then readings taken in good signal conditions will have maximum error of 5 meters, 95%  of the time. Nothing can be said about the remaining 5% readings or about readings taken in bad signal contions. Protection against these outliers is the special sauce that makes a good location based app stand out from the rest.
Some things you can do are:

*

*Filter out insanely high speeds. Make use of altitude as hint for being in a airplane.

*Correlate information from motion sensors and see if they agree with
GPS. Motion sensor signatures will be very different in steady state
and in motion.

*The typical size of a GSM/3G cell is under a kilometer in urban
areas and 5-10 kilometers in sparsely populated areas. If the
vehicle is moving at high speed for some time and the cell tower
information is still the same, you know something is wrong.

*Does the GPS fix read north one moment and south the next that too
at a high speed? If yes, it is most likely a GPS error.

*Check the number of Satellites used in GPS calculation. 12 is outstanding, 9 is healthy, 5 or less is poor, 4 is bare minimum for lat,lon + altitude
calculation, 3 is bare minimum for lat,lon calculation. Anything less than 3 is not a valid reading. You can be much more confident about the validity of data if number of satellites is high.

A:
GPS devices are positional speedometers, based on how far the receiver
  has moved since the last measurement. Its speed calculations are not
  subject to the same sources of error as the vehicle's speedometer
  (wheel size, transmission/drive ratios). Instead, the GPS's positional
  accuracy, and therefore the accuracy of its calculated speed, is
  dependent on the satellite signal quality at the time. Speed
  calculations will be more accurate at higher speeds, when the ratio of
  positional error to positional change is lower.

From Wikipedia.
Probably you should try this in place where you have good signal strength.

A: I am experiencing the same problem. I think GPS signal depends on a location, some location may give an exact output of location otherwise a 'not-so-reliable' result. In my case, I was located about 200 meters away from my actual location. How about you?
To add, GPS_PROVIDER does not work here in my area. NETWORK_PROVIDER does, and it's the one that give the 200 meters away result.

A: It seemes that most people are assuming that speed information from GPS is based on comparing positions related to time diference. This method is not very good for determining speed, and is worse at lower speeds of travel.
GPS receivers can output speed measurement based on doppler shift from the sattelite measurements. Accuracy of the speed measurement based on doppler is MUCH better compare to speed measurements based on position/time calculations.
Google on gps speed doppler and You will find a lot to read.
One link is here:
http://nujournal.net/HighAccuracySpeed.pdf
/Urban Holmdahl


text:
Q: Add click event to datatable cell I'm trying to add a click event to a dynamically created a datatabe. So this is my js :
   $('#report-table').dataTable({
        "proccessing": true,
        "serverSide": true,
        "ajax": {
            url: '@Url.Action("Get","Controller")',
            type: 'GET'

        },
       "columns": [
           { "data": "Name" },
                { "data": "Date" }, //lest say I want to add a click event here ???
                { "data": "sName", render: myRender }// I tried render but this is rendered without waiting on click function
        ]

    });

and this is my table for example :

A Test
2/13/2020 3:34:40 PM	 //lets say I want to fire a click event when I click the .aaaa class

Let's say I want to fire a click event when I click the .aaaa class.
Can anyone please give me an idea? Can I do this?
I'm stucked right here. Any idea would be apprecciated very very much :)

A: Try this, for more check this forum :
$('#report-table').on('click', 'td.className', function (e) {
    // your code to do something
});

A: Instead of render use className to add a class to the cell
   "columns": [
        { "data": "Name" },
        {
            "data": "Date",
            "className": "your-class"
        },
        { "data": "sName" }
   ]

then put an on click event handler on your class
$('#report-table').on('click', '.your-class', function() {
    //function code here
}

A: $("tr[role='row']").on('click',()=> {
    alert($(this).find('td.aaaa').text());
});


text:
Q: Script to extract only the MaxMind GeoLite2 Country database from gzip containing multiple files Recently MaxMind changed their download policy, and the old simple format is no longer available. The new file format looks like this: GeoLite2-Country_20191231.tar.gz, and inside we have a folder with the same name containing two additional files.
Although there is an option to delete the date parameter from the link, it seems that the downloaded file will still contain the date.
Now, the problem is to extract that GeoLite2-Country.mmdb from the gzip file having that variable name programmatically.
The unzip part existing in my old script was this:
gunzip -c "$1"GeoLite2-Country.mmdb.gz > "$1"GeoLite2-Country.mmdb

The question is how to modify the above part for the new situation. Or, maybe someone knows another way to solve the same problem. Thanks in advance.
The folder structure:
-+ Geolite2-Country_YYYYMMDD.tar.gz:
 |-+ Geolite2-Country_YYYYMMDD
   |- licence.txt
   |- copyright.txt
   |- Geolite2-Country.mmdb

What I need is Geolite2-Country.mmdb in the current folder of gzip file.

A: tar -tf /GeoLite2-City.tar.gz | grep mmdb | xargs tar -xf  /GeoLite2-City.tar.gz --strip-components 1 -C /

Just fix source and destination paths


text:
Q: Eclipse - Jasper report not compiling (java.lang.NoClassDefFoundError: org/apache/commons/digester/Digester) I am trying to generate a jasper report via the Eclipse ide, however when I execute the following line of code:
jasperReport = JasperCompileManager.compileReport("reports/samplereport.jrxml");

I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/digester/Digester
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:146)

I have added the apache common digester jar as a project library but it does not seem to make a difference.
NOTE: I am from a java novice (i.e. Ive a .NET background,) so I am very likely doing something really obvious!

A: you may be missing some jars. try to add these ones with any version.
jasperreports-.jar;
jasperreports-javaflow.jar;
commons-beanutils.jar;
commons-collections.jar;
commons-logging.jar;
commons-digester.jar

A: If your project is based on maven, you can add Jasper reports as a maven dependency, see sample code snippet below. Jasper report would automatically import all the libraries it needs to work properly.
...
<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>6.4.1</version>
</dependency>
...


text:
Q: Draw over other apps using AccessibilityService What would be an approach to spawn an activity through a service which overlays on top of all other active applications?
Something akin to how Google Assistant behaves on an "Okay Google" prompt.
I plan on spawning this activity through a gesture so will be catching AccessibilityEvents by creating an AccessibilityService. Is that the appropriate method or should I be using a foreground service or the newer WorkManager?
Appreciate any pointers.


text:
Q: Type-Error when transposing a vector of vectors While trying to write a template function to transpose a std vector of vectors of a unique type I am catching the following error:
/home/reiner/Desktop/utd-dune/duneuro-tests/src/test_meg_forward.cc: In function 'int run(const Dune::ParameterTree&)':
/home/reiner/Desktop/utd-dune/duneuro-tests/src/test_meg_forward.cc:127:70: error: no matching function for call to 'absolute_error(__gnu_cxx::__alloc_traits<std::allocator<std::vector<Dune::FieldVector<double, 3> > > >::value_type&, std::vector<double>&)'
     absoluteErrors.push_back(absolute_error(ana_direct[i], num_direct));
                                                                      ^
/home/reiner/Desktop/utd-dune/duneuro-tests/src/test_meg_forward.cc:46:3: note: candidate: template<class T> T absolute_error(const std::vector<TIN, std::allocator<_Tp> >&, const std::vector<TIN, std::allocator<_Tp> >&)
 T absolute_error(const std::vector<T> &num, const std::vector<T> &ana) {
   ^~~~~~~~~~~~~~
/home/reiner/Desktop/utd-dune/duneuro-tests/src/test_meg_forward.cc:46:3: note:   template argument deduction/substitution failed:
/home/reiner/Desktop/utd-dune/duneuro-tests/src/test_meg_forward.cc:127:70: note:   deduced conflicting types for parameter 'TIN' ('Dune::FieldVector<double, 3>' and 'double')
     absoluteErrors.push_back(absolute_error(ana_direct[i], num_direct));

The code I am using looks like
template <class T>
T absolute_error(const std::vector<T> &num, const std::vector<T> &ana) {
  std::vector<T> diff;
  std::transform(num.begin(), num.end(), ana.begin(), std::back_inserter(diff),
                 [](const T &a, const T &b) { return a - b; });
  return norm(diff);
}

Sadly my C++-skills are lacking so while trying to correct the function I do not find a suitable solution. Maybe someone of you guys can help me?
Here is the run-function
int run(const Dune::ParameterTree &config) {
  // set up driver
  auto driver = duneuro::MEEGDriverFactory<3>::make_meeg_driver(config);
  auto coils = duneuro::FieldVectorReader<double, 3>::read(config.sub("coils"));
  auto projections =
      duneuro::ProjectionsReader<double, 3>::read(config.sub("projections"));
  driver->setCoilsAndProjections(coils, projections);

  Dune::FieldVector<double, 3> center = config.get<Dune::FieldVector<double, 3>>("analytic_solution.center");
  // read dipoles
  auto dipoles = duneuro::DipoleReader<double, 3>::read(config.sub("dipoles"));

  // store output in an output tree
  Dune::OutputTree output(config.get<std::string>("output.filename") + "." +
                          config.get<std::string>("output.extension"));

  auto solution = driver->makeDomainFunction();

  std::vector<std::vector<Dune::FieldVector<double, 3>>> ana_data;
  std::vector<std::vector<Dune::FieldVector<double, 3>>> ana_direct;

  ana_data = MEGAnalytical(coils, dipoles, projections, center);
  ana_direct = transpose(ana_data);

  std::vector<double> absoluteErrors;
  std::vector<double> relativeErrors;
  std::vector<double> magnitudeErrors;
  std::vector<double> rdmErrors;

  for (unsigned int i = 0; i < dipoles.size(); ++i) {

    // compute numerical solution direct
    driver->solveEEGForward(dipoles[i], *solution, config.sub("solution"));
    auto num_direct =
        driver->solveMEGForward(*solution, config.sub("solution"));

//    subtract_mean(num_direct);
//    subtract_mean(ana_direct);

    auto prefix = std::string("dipole_") + std::to_string(i) + ".";
    absoluteErrors.push_back(absolute_error(ana_direct[i], num_direct));
    output.set(prefix + "ae", absoluteErrors.back());
    relativeErrors.push_back(relative_error(ana_direct[i], num_direct));
    output.set(prefix + "re", relativeErrors.back());
    magnitudeErrors.push_back(magnitude_error(ana_direct[i], num_direct));
    output.set(prefix + "mag", magnitudeErrors.back());
    rdmErrors.push_back(rdm_error(ana_direct[i], num_direct));
    output.set(prefix + "rdm", rdmErrors.back());

    std::cout << "Numerical solution for dipole: " << i << std::endl;
    for (int j = 0; j < num_direct.size() ; j++) {
     std::cout << num_direct[j] << std::endl;
    }

    std::cout << "Analytical solution for dipole: " << i << std::endl;
    for (int k = 0; k < coils.size() ; k++) {
     std::cout << ana_direct[i][k] << std::endl;
    }

  }
  return 0;
}

Additional output of the vectors:
Numerical solution for dipole: 9
9.93612e-05
-2.18637e-05
6.85649e-06
-3.50191e-05
1.43691e-05
-6.86168e-06
-4.64204e-05
7.99942e-06
-1.08231e-06
-2.6123e-05
-2.74267e-05
2.41666e-05
-4.83157e-05
3.60448e-05
-1.84048e-05
Analytical solution for dipole: 9
9.82984e-05 -2.24329e-05 1.00409e-05
-3.21174e-05 1.75503e-05 -6.64402e-06
-4.35313e-05 1.11112e-05 -5.96633e-22
-2.33793e-05 -2.4205e-05 2.26704e-05
-5.0926e-05 3.72573e-05 -2.09367e-05


text:
Q: How do I save user's input in KivyMD I made a simple App that collects users' input and arrane it as list, but how do I save it.
I want to be save users' input, so whenever the app is launched, the previous input is available. I think with has something to do with kivy.json, or something like that(I don't really know), but I don't know how to implement it.
I would really appreciate any help, thanks in advance!
here is my main.py file.
from kivymd.app import MDApp
from kivymd.uix.list import OneLineIconListItem, IconLeftWidget
from kivy.core.window import Window

Window.size = (300, 530)

class MainApp(MDApp):
    def build(self):
        self.theme_cls.primary_palette = 'Gray'
        self.theme_cls.primary_hue = '200'
        self.theme_cls.theme_style = 'Dark'

    def add_item(self, text):
        new_list_item = OneLineIconListItem(text=text)
        new_list_item.add_widget(
            IconLeftWidget(icon="pin")
        )
        self.root.ids.listcontainer.add_widget(new_list_item)
        self.root.ids.listinput.text = ''

if __name__ == "__main__":
    app = MainApp()
    app.run()

And here's my .kv file
MDBoxLayout:
    orientation: 'vertical'
    id: box
    MDToolbar:
        title: 'MyApp'
        pos_hint: {'top': 1}

    MDTextField:
        id: listinput
        hint_text: 'Add Item'
        mode: 'rectangle'
        size_hint_x: .9
        pos_hint: {'center_x': .5}
        text_validate_unfocus: False
        on_text_validate: app.add_item(listinput.text)

    ScrollView:
        MDGridLayout:
            cols: 1
            adaptive_height: True

            MDList:
                id: listcontainer

I would really appreciate any help, Thanks a lot in advance, for your help.


text:
Q: Parsing html with lxml in python I have the following html code:
...

[[footer]] - feed if you want.

...

I am trying to extract "[[footer]] - feed if you want." from this code including the spaces (general task in to find all strings on page containing text "[[footer]]").
import lxml.etree as ET
html = """

[[footer]] - feed if you want.

"""

elem = ET.fromstring(html)

infos = elem.xpath('/p')
for info in infos:
    print 1, info.text
print 2, ET.tostring(elem) #

Results:
1, [[footer]] -
2,
[[footer]] - feed if you want.

Desired result
[[footer]] - feed if you want.

Question
It is humbling that I have to ask this question, since it doesn't seem like it should be hard.
How can I extract all strings on page containing text "[[footer]] using lxml?

A: You can't get the exact string, since lxml converts the HTML to it's own internal data structure, and then you'll want to use the tostring() method to convert it back to a string (meaning that attributes, nesting, etc, could come out in a slightly different order/format, and whitespace will not be preserved).  An example of this would be something like:
for info in infos:
    #Check for some string in the displayed text
    if "search string" in info.text:
        print ET.tostring(info)

Since it sounds like you mentioned this could be anywhere on the page, you'll likely want to make this check info a function and call it recursively as you walk all the elements . . .
Edit in response to your comment:
You could do something like this:
for info in infos:
    #Check for some string in the displayed text
    if "search string" in info.text:
        output_str = info.text
        for children in info:
            output_str += ET.tostring(children)
        print output_str


text:
Q: Git-flow hotfix merging to develop being ahead produces XX commits ahead How to reproduce:

*

*Develop is 6 commits ahead master.

*Create hotfix branch from master.

*Make 2 commits to on hotfix.

*Finish hotfix branch (merge to master, tag, merge to develop)

*Master is now 3 ahead origin/master (2 commits+merge commit)

*Develop is 57 ahead origin/develop (WHAT?!)

Why isn't local devleop 3 ahead origin/develop? I have a feeling it has to do with the --no-ff flag in the merges...

A: I had the same situation once. Since I had write access to the main repo I was doing the merge operations directly to upstream. That would cause some problems.
So instead of doing the merge manually you must do it through a pull request, that is, push your Hotfix branch to your origin (your fork) then create a pull request from hotfix to master, after accepting the pull request the hotfix branch will be merged to master.
Now just open a pull request from master to develop.


text:
Q: Secure way to access Amazon S3 I have been using Transmit FTP program to access my Amazon S3 storage buckets. Just been reading on here that this isn't that secure.
I'm not a command line person as you can probably tell so what would be the best way for me to access my S3 storage on my Mac?
I'm using to store image files that I am making available for download on my website.
Thanks

A: FTP isn't secure, but it sounds like you are confusing this fact with the fact that you are using a multiprotocol client to access S3, and that client also happens to support FTP.
S3 cannot be directly accessed using the FTP protocol, so the client you are using can't actually be accessing S3 using FTP... hence, your security-related concern appears to be unfounded.


text:
Q: set color for each violin in violin plot I tried violin plot in Seaborn with different colors for each violin as:
sns.violinplot(x='type', y='den', data=mydf, ax=axes[0], color=['red','blue','yellow'])

however I got:

ValueError: to_rgb: Invalid rgb arg "('red', 'blue', 'yellow')"
  could not convert string to float: red

A: I think you should use the palette keyword:

color : matplotlib color, optional
Color for all of the elements, or seed for light_palette() when using hue nesting.
palette : seaborn color palette or dict, optional
Colors to use for the different levels of the hue variable. Should be something that can be interpreted by color_palette(), or a dictionary mapping hue levels to matplotlib colors.

import seaborn as sb
import numpy as np

data = np.random.random([100,4])

sb.violinplot(data=data, palette=['r','g','b','m'])


text:
Q: coldfusion - cfprint issues with large spool files I am using cfprint from ColdFusion to print multiple PDFs from a directory.  The problem I am having is that when the files are spooled to the printer the size of the file dramatically increases and slows down everything.  The file in the folder is 125K and when it is in the printer spool it increases up to 15.7MB.  Here is the ColdFusion code:
<cfprint
    source="[FILELOCATION]/[FILE].pdf"
    color="yes"
    printer="[printer name]">

The files will eventually print but it can take upwards of 15-20 minutes.  Does anyone have any solutions for this issue?  I have tried with both CF generated PDFs and ones that I have created from scratch.  Thanks

A: Queue up two to five at a time.  Pause to allow processing. Mark them as printed, move or delete them, move to the next batch...Time this out yourself to see how much time you need to allow. That way you don't compound a bunch of work for the server and create a bottleneck on your CF server.
If you are just doing this with one server consider using a secondary low priority server and run a developer edition fully paid for EULA compliant registered version of Coldfusion (or Railo) and dedicate that server for just printing so your other server can do useful things.
Edit
So the OP has a Coldfusion print bottleneck.  In your server that does the printing (same as your CF server I assume?) and IF this is a windows server (not sure your server version), there is print queue folder. Provided you have access to this folder, you can do a few things.  You can create a method for FTP-ing your files to this folder (or copy if it is the same server).  The printer will queue up the job and off it goes.  You can do some functions like check the print queue for file count.  If the file count is greater zero, check back in 15 minutes.  If the count is zero, copy over a few more files.
You be creating a scheduled task in your CFAdmin and automate.  There is a getprinterInfo() so you can check if the printer is off line and do other things like check for another printer somewhere else if you need to reroute print jobs.  You can also set up several print servers and attach printers to them and hit several print servers and check print queue folders.
The magic is endless, goal is to offset work to something other than your Coldfusion server.
So to recap:

*

*Seperate concerns by not doing cfprint

*Create escape routes to other priters if you can.

*If you must use coldfusion then queue up a dedicated Coldfusion server for print management stuff.

*Use getPrinterInfo() and dump out things to see what you can use, trap etc.

*Ben forta has a tool that can check for several printers, consider incorperating this.

*Next use cfftp (or cffile if you are on the same server) provided you have access and copy files to print queue folders, doing no cfprint at all.

Here is a link on print spool stuff (another link in the doc shows you how you can change the spool location).
When it is over you are going to be the coldfusion print master with escape routes and checks and everything.


text:
Q: Using MagnificationGesture; how can I zoom in to where a user's fingers actually "pinch"? I am facing the same problem as below with SwiftUI.
Using PinchGesture; how can I zoom in to where a user's fingers actually "pinch"?
I think I can solve this problem by giving anchor parameter of scaleEffect the center coordinate of the two fingers.
But I don't know how to get the center.
My Code:
import SwiftUI

struct MagnificationGestureView: View {
  @State var scale: CGFloat = 1.0
  @State var lastScaleValue: CGFloat = 1.0

  var body: some View {
    Image(
      systemName: "photo"
    )
    .resizable()
    .frame(
      width: 100,
      height: 100
    )
    .scaleEffect(
      self.scale
      //, anchor: <---- give: the two fingers center position
    )
    .gesture(
      magnification
    )
  }

  var magnification: some Gesture {
    // Can I get the center of the pinch?
    MagnificationGesture().onChanged { val in
      let delta = val / self.lastScaleValue
      self.lastScaleValue = val
      self.scale = self.scale * delta
    }.onEnded { _ in
      self.lastScaleValue = 1.0
    }
  }
}

Reference:
https://stackoverflow.com/a/58468234/1979953


text:
Q: How does the Matplotlib trisurf plot work? I am unable to understand from the matplotlib documentation(https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html), the working of a trisurf plot. Can someone please explain how the X,Y and Z arguments result in a 3-D plot?

A: Let me talk you through this example taken from the docs

'''
======================
Triangular 3D surfaces
======================

Plot a 3D surface with a triangular mesh.
'''

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

n_radii = 8
n_angles = 36

# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).
radii = np.linspace(0.125, 1.0, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)

# Repeat all angles for each radius.
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)

# Convert polar (radii, angles) coords to cartesian (x, y) coords.
# (0, 0) is manually added at this stage,  so there will be no duplicate
# points in the (x, y) plane.
x = np.append(0, (radii*np.cos(angles)).flatten())
y = np.append(0, (radii*np.sin(angles)).flatten())

# Compute z to make the pringle surface.
z = np.sin(-x*y)

fig = plt.figure()
ax = fig.gca(projection='3d')

ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)

plt.show()

The x, y values are a range of values over which we calculate the surface. For each (x, y) pair of coordinates, we have a single value of z, which represents the height of the surface at that point.


text:
Q: Border wont remove in html table I've got a HTML table with several cells inside, the border=0 property is set yet the border does not go away, what am I doing wrong?

A: Change the first cell spacing to 0
So here's the code:


text:
Q: Ethernet WAN cable not recognized by router, but recognized by everything else, and WAN port works I have an ISP-provided WAN cable (cat. 5E 2PR) going into my apartment, but my router (D-Link DIR-825ACG1 rev. G1) refuses to recognize it whenever I plug it into the WAN port. Specifically, it does not get any kind of connection on it - it just says cable unplugged.
Things I have checked:

*

*The cable works when plugged into my laptop. No problem with the cable itself.

*The WAN port on the router is functional - I have tried with a spare cable and it detects it correctly.
So, the problem only manifests itself when this particular cable is used with this particular device.
In the past I have used this same router in two different apartments and with two different ISPs, and it worked correctly.
I've also tried rebooting, resetting, and tinkering with the router's options for many times, to no avail.
I'm considering buying a crimping tool and some 8P8C connectors and re-crimping the cable as either pass-through or cross-over (I'm not sure which one it is at the moment).
What are some other things I can try, short of ringing up the ISP and asking they fix their cable themselves?
I am also considering there may be a configuration error on my part as well.

A: Solved this by re-crimping my wire. Looks like it was crimped incorrectly for my configuration.


text:
Q: Error time_zone mysql I have a payment host and I presented the following problem. to define and execute my time zone function now returns a date 7 days in carrier delays , you write to technical support and tell me it's my mistake . but I think it is wrong of them . .Screenshot
Whose mistake is it ? mine or theirs?


text:
Q: Is there some elementary proof of invariance of domain? Invariance of domain at least in statement seems a simple result. I mean, the first time I saw the statement I thought: "the proof can't be that bad", but when I searched for it I saw that it needs even algebraic topology to prove this result.
My doubt is: isn't there any other proof of invariance of domain that don't need to use algebraic topology? Is there some more elementary proof of this result?
Thanks very much in advance!

A: The point here is what means elementary. Many think that a bit of singular homology is not that bad (see Greenberg-Harper's Algebraic Topology textbook, for instance). One can use Mapping Degree Theory as in many books devoted to the topic and use Borsuk-Ulam or else. But I would recommend a carefull reading of
http://terrytao.wordpress.com/2011/06/13/brouwers-fixed-point-and-invariance-of-domain-theorems-and-hilberts-fifth-problem/
There one finds a very nice proof. The heavy part is Brouwer Fixed Point Theorem. Apart from that, some manipulations involving Weierstrass Approximation Theorem and the so-called Little Sard Theorem (in this particular case: a polynomial image of $\mathbb{S}^{n-1}$ in $\mathbb{R}^n$ has empty interior, this disguised in measure zero terms).