Q: Change data connection sql query in LiveCycle based on external data I have a PDF form in LiveCycle Designer ES4 which has a data connection to an Access database.
I would like to AUTOMATICALLY populate the form with data from the database, based on information in an XML file.
For example, I have the following file, name.xml:
<Form>
    <Name>Mike</Name>
</Form>

I would like all the form fields to populate as if the following query had run:
SELECT * FROM Info WHERE Name = 'Mike'

I have thought about a few methods of doing this that make sense to me.  Either

*

*Import the data from the file and create a query string, something like
var nameXML = xfa.loadXML("name.xml")
var name = nameXML."parseTheXMLSomehow"
$.DataConnection.#command.query.commandType = "text"
$.DataConnection.#command.query.select.nodes.item(0).value =
    Concat("SELECT * FROM Info WHERE Name = '", name, "'")
$.DataConnection.open()

*Create a data connection to the XML file and bind it to the Name field, and then somehow change all the other fields as in the option above, or

*Retrieve the data as in the first option, then set the value of the Name field (which is bound to the data connection to the database) to the data value, and somehow have that automatically change everything else.
Problems:

*

*loadXML doesn't work with data files, and xfa.host.importData("name.xml") doesn't seem to do anything (maybe because the document isn't certified  - couldn't understand how to do that)

*I can create the data connection to the XML file and bind it to a field, but it doesn't display anything.  Is there something I need to add to the XML file?

*I can't get the data in the first place, and even if I could, changing one field doesn't automatically change the others, even though they're all bound to the same data source.
Right now, the second option seems to be my best bet if I could get the data to actually populate.
Thanks for any help!

A: Before moving forward, make sure you understand the concept of Reader Extensions.
Your PDF must be applied with appropriate Usage Rights (more specifically 'Database and Web service Connectivity') before loading data into it.
You did not create a data connection directly to your XML file. Rather you would have created a data source from a sample XML file. This will just use the schema of the XML - not the actual data.
If you want to change the values of all fields at the same, set Global Data Binding.
Hope these tips may help you.
-Nith


Q: Generate Expressjs API as methods for client side for isomorphic web Is there a generator for http services exposed by expressjs that wraps the calls to http get post and offer method wrappers client side for the browser in isomorphic apps ? Kind of what Typelite http://type.litesolutions.net/ offer for C# devs webapi but for nodejs expressjs ? Thanks

A: I found that loopback which is based on express have these generators, for anyone interested in this


Q: elasticsearch reindex change document structure I plan on using the _reindex api to reindex some data. Is there a way in which you can flatten an array during the operation using a script and reindex this array as individual documents?
Note: I know I can use scan and scroll, but was hoping to use the in-build reindex API, as it gives a nice progress indication via the tasks api.
I have a structure like the following in index_a
{
 "field_a": [
   "value_a",
   "value_b"
  ]
}

What I would like to do during the reindex is to create individual documents for each of the items in the array during the _reindex operation. I would like something that does this:
doc_1:
{
   "field": "value_a"
}

and doc_2:
{
   "field": "value_b"
}

ElasticSearch Version: 2.4
Is this even possible or would I have to use something like a custom plugin to do this?


Q: Sum of areas of opposite faces in a parallelogram-based pyramid with an inscribed sphere There is given a pyramid ABCDS with parallelogram ABCD. It is also possible to inscribe a sphere inside ABCDS. Show that sum of areas ABS and CDS is equal to BCS and ADS.
I tried to consider five pyramids with the apex in the center of the sphere. But with no progress. Help me.

A: The result is clearly true in the case of a regular pyramid (think to egyptian pyramids).
We are going to show that one can bring back the general case to this special one.
The proof is based on two transformations (a) and (b):

*

*(a) due to the fact that there is an inscribed sphere with center $I$ and radius $r$, the issue can be converted into a question about volumes:

$$\tag{1}area(ABS)+area(CDS)=area(BCS)+area(ADS) \ ? \ \ \iff$$
$$\tag{2} vol(IABS)+vol(ICDS)=vol(IBCS)+vol(IADS) \ \ ?$$
Why is (1) equivalent to (2) ?  In (2), the 4 tetrahedra $IABS, ICDS, ...$ have a common height $r$ ; therefore, applying the formula giving  the volume of a tetrahedron: "$\tfrac13 r \times $ base area", one can proceed forward or backwards from (1) to (2) by multiplying or dividing by $\tfrac13 r$.

*

*(b) There exists a linear transform mapping pyramid $ABCDS$ onto a regular pyramid $A'B'C'D'S'$, making (2) equivalent to

$$\tag{3} vol(I'A'B'S')+vol(I'C'D'S')=vol(I'B'C'S')+vol(I'A'D'S')$$
which is known to be true, completing the proof.
Why is (2) equivalent to (3) ? Because a linear mapping $L$ transforms a polyhedron with volume $V$ into a polyhedron with volume $\det(L) \times V$.
Something remains to be established:
PROOF of the existence of the linear transform $L$:
Let us take the center of the parallelogram as origin $(0,0,0)$ of coordinates.
Let us give the following coordinates names:
$$\tag{2}A(a,b,0), \ B(c,d,0), \ C(-a,-b,0), \ D(-c,-d,0), \ S(e,f,g)$$
Let us consider the regular pyramid with vertices
$$\tag{3}A'(1,0,0), \ B'(0,1,0), \ C'(-1,0,0), \ D'(0,-1,0), \ S'(0,0,1)$$
Then the linear transform associated with matrix
$$M=\begin{pmatrix}a&c&e\\b&d&f\\0&0&g\end{pmatrix}$$
maps $A',B',C',D',S'$ onto $A,B,C,D,S$ resp.
Take $ L= M^{-1}$ for the inverse mapping.
Remarks :
1) The image $I'$ of the center $I$ of the sphere is not necessarily the center of the inscribed sphere in the regular pyramid.
2) About the initial condition (existence of an inscribed sphere), the center $I$ has to belong to the bisecting planes of the 8 dihedral angles. In other words, these bissecting planes have all to be concurrent in a point.

A: Let $E, F, G, H, T$ be the contact points of the inscribed sphere to the triangular faces $ABS$, $BCS$, $CDS$, $DAS$ and parallelogram $ABCD$ respectively.
Color triangles $ABS$, $CDS$, $BCT$, $DAT$ in black and
triangles $BCS$, $DAS$, $ABT$, $CDT$,  in white.
For each face, triangulate it into $3$ or $4$ triangles using the contact point in that face. For example, face $ABS$ becomes 3 triangles $ABE$, $BSE$ and $SAE$ and
face $ABCD$ becomes 4 triangles $ABT$, $BCT$, $CDT$ and $DAT$. This give us totally
$16 = 4\times 3 + 1 \times 4$ triangles.
We can group these $16$ triangles into $8$ pairs according to which edge of the original pyramid they attached to.
Convince yourself the two triangle in such
a pair has same area.  As an example, triangle $ABE$ and $ABT$ are attached to the
edge $AB$ and they have same area.
Notice for such a pair, one of the triangle is in black and the other in white.
This means the total area in black equals to the total area in white.
In other words,
$$\begin{align}
 & \verb/Area/(ABS) + \verb/Area/(CDS) + \verb/Area/(BCT) + \verb/Area/(DAT)\\
= & \verb/Area/(BCS) + \verb/Area/(DAS) + \verb/Area/(ABT) + \verb/Area/(CDT)
\end{align}\tag{*1}
$$
Since $ABCD$ is a parallelogram, it is not hard too see for any point $P$ inside $ABCD$, we have
$$\verb/Area/(ABP)+\verb/Area/(CDP) =
\verb/Area/(BCP) + \verb/Area/(DAP) = \frac12\verb/Area/(ABCD)$$
In particular, set $P$ to $T$, we obtain
$$\verb/Area/(ABT)+\verb/Area/(CDT) =
\verb/Area/(BCT) + \verb/Area/(DAT)$$
Substitute this back into $(*1)$, we obtain the desired equality:
$$\verb/Area/(ABS) + \verb/Area/(CDS) = \verb/Area/(BCS) + \verb/Area/(DAS)$$


Q: BackgroundService does not see database updates I've come across a strange problem with my Blazor app.  The app has a background service that polls remote hosts for status information, and updates the database with that information.  The webasm client sees any updates the background service makes, but if I update a record via the client through an API controller (for instance, changing the IP address) the background service doesn't see the new value unless I restart the server.
Here's some relevant code from the background service:
public class Poller : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private MyDbContext db;

    public Poller(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using (var scope = _scopeFactory.CreateScope())
        {
            db = scope.ServiceProvider.GetRequiredService<MyDbContext>();

            // Main loop
            while (!stoppingToken.IsCancellationRequested)
            {
                // Get list of workers

                foreach (var worker in db.Workers
                    .Where(w => w.Status != WorkerStatus.Updating)
                    .ToList())
                {
                    var prevStatus = worker.Status;
                    // Poll for new status
                    string currentStatus = await worker.PollAsync(stoppingToken);
                    if (currentStatus != null)
                    {
                        worker.Status = currentStatus;
                    }
                    if (worker.Status != prevStatus)
                    {
                        await Log(worker, $"Status changed to {worker.Status}", stoppingToken);
                    }

                    await db.SaveChangesAsync(stoppingToken);
                }
            }
        }
    }

    private async Task Log(Worker? worker, string text, CancellationToken token)
    {
            var entry = new LogEntry
            {
                Worker = worker,
                Text = text
            };
            db.LogEntries.Add(entry);
            await db.SaveChangesAsync(token);
    }

Code from the API controller is basic boilerplate:
    [HttpPut("{id}")]
    public async Task<IActionResult> PutWorker(string id, Worker worker)
    {
        if (id != worker.WorkerId)
        {
            return BadRequest();
        }

        _context.Entry(worker).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!WorkerExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

Thanks!

A: As soon as you are using the same DbContext instance, the updated data will not be seen in your entities.
You can check this blog post for details:

It turns out that Entity Framework uses the Identity Map pattern. This means that once an entity with a given key is loaded in the context’s cache, it is never loaded again for as long as that context exists. So when we hit the database a second time to get the customers, it retrieved the updated 851 record from the database, but because customer 851 was already loaded in the context, it ignored the newer record from the database

http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/
I could successfully reproduce this behavior.
For your case you could as an option create a new instance of context on each iteration
// Main loop
while (!stoppingToken.IsCancellationRequested)
{
    using (var scope = _scopeFactory.CreateScope())
    {
        db = scope.ServiceProvider.GetRequiredService<MyDbContext>();

        // Get list of workers
        foreach (var worker in db.Workers
            .Where(w => w.Status != WorkerStatus.Updating)
            .ToList())
        {
            var prevStatus = worker.Status;
            // Poll for new status
            string currentStatus = await worker.PollAsync(stoppingToken);
            if (currentStatus != null)
            {
                worker.Status = currentStatus;
            }
            if (worker.Status != prevStatus)
            {
                await Log(worker, $"Status changed to {worker.Status}", stoppingToken);
            }

            await db.SaveChangesAsync(stoppingToken);
        }
    }
}


Q: How to make Jar exe file which read/write data from text file How to convert text file into jar file.Actually In my java project I read and write data from a text file but when i convert my project into jar executable file then reading and writing from/into text file not working what should I do to make this work please help me.

A: A jar file is immutable, for security reasons. You cannot save data back to a file stored in a jar file.
Data saved from a Java program must be stored outside the classpath. Where that is, is up to you.
If you program must ship with a sample/default file, to get started, you code can try reading the file from the external location. If not found there, read from the sample/default file in the jar file. After updating content in memory, save to external location, where it will be read from on next execution.

A: You can make use of Classloader to read the file present in jar, but ofcourse you will not be able to write to it.
To be able to read and write both file should be present in filesystem, you may want to have a look at Read and Write to Java file via Resource


Q: How do I include my source code in Nix Docker Tools image? I'm building a web server using NodeJS, and I'm using the Docker Tools that Nix provides to build images for my server.
I have the following Dockerfile that I'm tring to convert into a .nix file
FROM node:12.20.0-alpine3.11 as build-deps
WORKDIR /hedwig-app
COPY ["package.json", "package-lock.json*", "./"]
RUN npm install
COPY . .
RUN npm run build
EXPOSE 8080
CMD [ "node", "build/index.js" ]

However, I don't know how to copy my source code into the Docker image to be built. This is what I have so far
{ pkgs ? import <nixpkgs> {} }:

let
    baseImage = pkgs.dockerTools.pullImage {
        imageName = "alpine";
        imageDigest = "sha256:3c7497bf0c7af93428242d6176e8f7905f2201d8fc5861f45be7a346b5f23436";
        sha256 = "119pbb2nrhs6nvbhhpcd52fqy431ag46azgxvgdmyxrwii97f4ah";
        finalImageName = "alpine";
        finalImageTag = "3.12";
    };
    sourceFiles = builtins.toString ./.;
    gitignoreSrc = pkgs.fetchFromGitHub {
        owner = "hercules-ci";
        repo = "gitignore";
        # put the latest commit sha of gitignore Nix library here:
        rev = "c4662e662462e7bf3c2a968483478a665d00e717";
        # use what nix suggests in the mismatch message here:
        sha256 = "sha256:1npnx0h6bd0d7ql93ka7azhj40zgjp815fw2r6smg8ch9p7mzdlx";
    };
    inherit (import gitignoreSrc { inherit (pkgs) lib; }) gitignoreSource;
    src = gitignoreSource ./.;
in
    pkgs.dockerTools.buildImage {
        name = "hedwig-api";
        tag = "latest";

        fromImage = baseImage;
        contents = [ pkgs.nodejs ];
        runAsRoot = ''
        mkdir /hedwig-app
        cp -r ${src} /hedwig-app
        npm install
        npm run build
        '';

        config = {
            ExposedPorts = {
                "8080/tcp" = {};
            };
            WorkingDir = "/hedwig-app";
            Cmd = ["node" "build/index.js"];
        };
    }

How could I copy my source code into the image before running npm run build?

A: Inside Nix, you can't run npm install. Each step can only do one of two things:

*

*either compute a new store path without network access: a regular derivation

*or produce an output that satisfies a hardcoded hash using a sufficiently simple* process that can access the network: a fixed output derivation

These constraints ensure that the build is highly likely to be reproducible.
npm install needs access to the network in order to fetch its dependencies, which puts it in the fixed output derivation category. However, dockerTools.buildImage will execute it in a regular derivation, so it will fail to contact the npmjs repository.
For this reason, we generally can't map a Dockerfile directly to a series of buildImage calls. Instead, we can build the software with the Nix language infrastructures, like yarn2nix, node2nix or the various tools for other languages.
By doing so, your build becomes reproducible, it tends to be more incremental and you don't have to worry about source files or intermediate files ending up in your container images.
I'd also recommend to limit the contents parameter to a pkgs.buildEnv or pkgs.symlinkJoin call, because the contents are copied to the root of the container while also remaining in its store.

*: sufficiently simple excludes anything beyond fetching a single resource, because that tends to be too fragile. If, for any reason, the fixed output derivation builder produces a different result and the only way to fix it is by changing the output hash, your entire build is essentially not reproducible.


Q: Cordova backbutton press from inappBrowser I was developing a cordova app,which contains a login logout functionality.
The bug is when the user logs out of the app. The logout button calls inAppBrouser plugin to load logout page (from an external web source) after the logout success it stays in the same logout screen, when the user press back button it returns to main screen (from where he logged out), I want to close application there (the page he is going back is supposed to be displayed after login)
I tried clearing the history when inappBrowser gets loaded,
history.go(-(history.length - 1));

but no luck!
from the cordova documentation as JesseMonroy650 said I tried overriding the backbutton press which is not working inside inappbrowser
but the 'exit' eventListener I added seems to be working...
window.addEventListener("exit", function () {
 navigator.app.exitApp();
});

the app sometimes exits evens before the back button is pressed.
the problem with the listener
help& Advises needed.

A: window.addEventListener("exit", function () {
  navigator.app.exitApp();
});

seems to be working fine after upgrading to android version 4.1.1
Cordova version : 5.0.0
InappBrowser Version : 1.1.0
No code changes were needed


Q: Wait till Visual tree is done updating I am getting this error when I open dialog box on startup: Cannot perform this operation while dispatcher processing is suspended.
At the start of the application, a Login Dialog window opens at the top of a window with switchable content. By that I mean I have a window, in which content get switched out by setting a ViewModel property on main window.
I Do not get the error if i do not set the main window viewmodel, because it does not need to change anything in the view.
This is the MainView, with the switchable viewmodel:
<Window x:Class="WpfProject.Views.Main.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ViewModels="clr-namespace:WpfProject.ViewModels.Main"
    Title="WpfProject" Height="700" Width="1000"
    Content="{Binding ViewModel}"
    Visibility="{Binding MainWindowVisiblility}"
    xmlns:MvvmDialogs="clr-namespace:MvvmDialogs.Behaviors;assembly=MvvmDialogs"
    MvvmDialogs:DialogBehavior.DialogViewModels="{Binding Dialogs}"
    xmlns:Behaviors="clr-namespace:WpfProject.Behaviors"

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
>
<i:Interaction.Behaviors>
    <Behaviors:CancelCloseWindowBehavior CloseAction="{Binding CloseAction}"></Behaviors:CancelCloseWindowBehavior>
</i:Interaction.Behaviors>
<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction Command="{Binding StartUpProcedureCommand}"></i:InvokeCommandAction>
    </i:EventTrigger>
</i:Interaction.Triggers>

<Window.DataContext>
    <ViewModels:MainViewModel ></ViewModels:MainViewModel>
</Window.DataContext>

The Interaction Trigger is the action that execute the dialog window.
For dialog windows i am using Mark J Feldman's way of handling dialog boxes, which can be found here
Now as suggested in the Title I would like to wait till the MainViewModel has been changed and updated the view, before opening the dialog window.
Startup procedure command:
private ICommand _StartUpProcedureCommand;
public ICommand StartUpProcedureCommand
{
    get
    {
        return _StartUpProcedureCommand ?? (_StartUpProcedureCommand = new Command(StartUpProcedure));
    }
}
private void StartUpProcedure()
{

    UserLoginDialog();

}
private void UserLoginDialog(IUser user = null)
{

    MainWindowVisiblility = Visibility.Hidden;
    LoginViewModel lvm=new LoginViewModel(user);
    this.Dialogs.Add(lvm);
    if (lvm.Result == null)
        Application.Current.MainWindow.Close();

}

A: Mark's pattern for dialogs looks like a pretty ugly and poorly thought out solution to me, despite the lengthy article he has written.
You are getting a sort of deadlock on the UI thread and need to wrap the showing of the new window in Dispatcher.BeginInvoke so that it is executed asynchronously and allows the dispatcher thread to continue processing.
Something like this:
Dispatcher.BeginInvoke(new Action(() => new CustomDialogWindow {DataContext = parent.DataContext}.ShowDialog());


Q: View is not in the Window hierarchy using Sprite Kit I've already searched stackOverFlow for solutions and found a bunch of threads but none of them helped in my case.
From a plain Sprite Kit template:
I managed to create a table with prototype cells in the storyboard and populated them with a plist. Good so far!
I also managed to show the UITableViewController from my SKScene with the following code:
UIViewController *vc = self.view.window.rootViewController;
[vc performSegueWithIdentifier:@"segueToTable" sender:nil];

I can go back to my SKScene with a segue from a Navigation Bar Back Button.
BUT when I try to show the UITableViewController again I get the following error:
Warning: Attempt to present <TableViewController: 0x135d78580> on <ViewController: 0x135e0c2e0> whose view is not in the window hierarchy!

What can I do to segue between my SpriteKit scene and the UITableViewController?
EDIT:
I'm using NSNotificationCenter now.
Simply add a notification in my main ViewController which calls
  [self performSegueWithIdentifier:@"segueIdentifier" sender:nil];

A: Are you calling the method on viewDidLoad: method? Somethimes calling a modal view controller within viewDidLoad: gives this kind of problem.
You can solve this problem calling it from the viewDidAppear: method.


Q: Pandas: Merge data frames on datetime index I have the following two dataframes that I have set date to DatetimeIndex df.set_index(pd.to_datetime(df['date']), inplace=True) and would like to merge or join on date:
df.head(5)
        catcode_amt type    feccandid_amt   amount
date
1915-12-31  A5000   24K     H6TX08100   1000
1916-12-31  T6100   24K     H8CA52052   500
1954-12-31  H3100   24K     S8AK00090   1000
1985-12-31  J7120   24E     H8OH18088   36
1997-12-31  z9600   24K     S6ND00058   2000

d.head(5)
         catcode_disp disposition   feccandid_disp  bills
date
2007-12-31  A0000   support     S4HI00011               1
2007-12-31  A1000   oppose      S4IA00020', 'P20000741  1
2007-12-31  A1000   support     S8MT00010               1
2007-12-31  A1500   support     S6WI00061               2
2007-12-31  A1600   support     S4IA00020', 'P20000741  3

I have tried the following two methods but both return a MemoryError:
df.join(d, how='right')

I use the code below on dataframes that don't have date set to index.
merge=pd.merge(df,d, how='inner', on='date')

A: It looks like your dates are your indices, in which case you would want to merge on the index, not column. If you have two dataframes, df_1 and df_2:
df_1.merge(df_2, left_index=True, right_index=True, how='inner')

A: You can add parameters left_index=True and right_index=True if you need merge by indexes in function merge:
merge=pd.merge(df,d, how='inner', left_index=True, right_index=True)

Sample (first value of index in d was changed for matching):
print df
           catcode_amt type feccandid_amt  amount
date
1915-12-31       A5000  24K     H6TX08100    1000
1916-12-31       T6100  24K     H8CA52052     500
1954-12-31       H3100  24K     S8AK00090    1000
1985-12-31       J7120  24E     H8OH18088      36
1997-12-31       z9600  24K     S6ND00058    2000

print d
           catcode_disp disposition            feccandid_disp  bills
date
1997-12-31        A0000     support                 S4HI00011    1.0
2007-12-31        A1000      oppose  S4IA00020', 'P20000741 1    NaN
2007-12-31        A1000     support                 S8MT00010    1.0
2007-12-31        A1500     support                 S6WI00061    2.0
2007-12-31        A1600     support  S4IA00020', 'P20000741 3    NaN

merge=pd.merge(df,d, how='inner', left_index=True, right_index=True)
print merge
           catcode_amt type feccandid_amt  amount catcode_disp disposition  \
date
1997-12-31       z9600  24K     S6ND00058    2000        A0000     support

           feccandid_disp  bills
date
1997-12-31      S4HI00011    1.0

Or you can use concat:
print pd.concat([df,d], join='inner', axis=1)

date
1997-12-31       z9600  24K     S6ND00058    2000        A0000     support

           feccandid_disp  bills
date
1997-12-31      S4HI00011    1.0

EDIT: EdChum is right:
I add duplicates to DataFrame df (last 2 values in index):
print df
           catcode_amt type feccandid_amt  amount
date
1915-12-31       A5000  24K     H6TX08100    1000
1916-12-31       T6100  24K     H8CA52052     500
1954-12-31       H3100  24K     S8AK00090    1000
2007-12-31       J7120  24E     H8OH18088      36
2007-12-31       z9600  24K     S6ND00058    2000

print d
           catcode_disp disposition            feccandid_disp  bills
date
1997-12-31        A0000     support                 S4HI00011    1.0
2007-12-31        A1000      oppose  S4IA00020', 'P20000741 1    NaN
2007-12-31        A1000     support                 S8MT00010    1.0
2007-12-31        A1500     support                 S6WI00061    2.0
2007-12-31        A1600     support  S4IA00020', 'P20000741 3    NaN

merge=pd.merge(df,d, how='inner', left_index=True, right_index=True)

print merge
           catcode_amt type feccandid_amt  amount catcode_disp disposition  \
date
2007-12-31       J7120  24E     H8OH18088      36        A1000      oppose
2007-12-31       J7120  24E     H8OH18088      36        A1000     support
2007-12-31       J7120  24E     H8OH18088      36        A1500     support
2007-12-31       J7120  24E     H8OH18088      36        A1600     support
2007-12-31       z9600  24K     S6ND00058    2000        A1000      oppose
2007-12-31       z9600  24K     S6ND00058    2000        A1000     support
2007-12-31       z9600  24K     S6ND00058    2000        A1500     support
2007-12-31       z9600  24K     S6ND00058    2000        A1600     support

                      feccandid_disp  bills
date
2007-12-31  S4IA00020', 'P20000741 1    NaN
2007-12-31                 S8MT00010    1.0
2007-12-31                 S6WI00061    2.0
2007-12-31  S4IA00020', 'P20000741 3    NaN
2007-12-31  S4IA00020', 'P20000741 1    NaN
2007-12-31                 S8MT00010    1.0
2007-12-31                 S6WI00061    2.0
2007-12-31  S4IA00020', 'P20000741 3    NaN

A: I ran into similar problems. You most likely have a lot of NaTs.
I removed all my NaTs and then performed the join and was able to join it.
df = df[df['date'].notnull() == True].set_index('date')
d = d[d['date'].notnull() == True].set_index('date')
df.join(d, how='right')


Q: XC16 Put a data table in PSV memory (PIC) I want to put a table in Flash and read it directly from my C program. According to Microchip this is done by __attribute__((space(psv))) However, as the most things around microchip, their own examples doesn't work that well (usually obsolete and not updated): https://microchipdeveloper.com/16bit:psv
So this is what I'm trying to do:
uint16_t __attribute__((space(psv))) ConfDiskImage[] = {
    /*AOUT*/ 0x01E0,0x0004,0x3333,0x4053,
    /*   1*/ 0x01E1,0x0012,0x0005,0x0000,0x0000,0x0000,0x4120,0x0000,0x0000,0x0000,0x4120,
    /*   2*/ 0x01E2,0x0012,0x0006,0x0000,0x0000,0x0000,0x4120,0x0000,0x0000,0x0000,0x4120,
    /*   3*/ 0x01E3,0x0012,0x0007,0x0000,0x0000,0x0000,0x4120,0x0000,0x0000,0x0000,0x4120,
    /*EOD */ 0x0000,0x0000
};

When I compile I get: "warning: ignoring space attribute applied to automatic ConfDiskImage"
I'm using MPLAB X IDE 5.45 with XC16-gcc v1.50.
Microcontroller: dsPIC33EP256MC506
Any ideas of how to get it to stay in Flash (not being copied to RAM) and read it directly from flash with a pointer?

A: I suspect what you really need is perhaps more involved but the simple answer to the question you asked is to use the const storage class.
For example:
/*
 * File:   main.c
 * Author: dan1138
 * Target: dsPIC33EP256MC506
 * Compiler: XC16 v1.61
 * IDE: MPLABX v5.45
 *
 * Created on February 19, 2021, 11:56 PM
 */

#pragma config ICS = PGD2, JTAGEN = OFF, ALTI2C1 = OFF, ALTI2C2 = OFF, WDTWIN = WIN25
#pragma config WDTPOST = PS32768, WDTPRE = PR128, PLLKEN = ON, WINDIS = OFF
#pragma config FWDTEN = OFF, POSCMD = NONE, OSCIOFNC = ON, IOL1WAY = OFF, FCKSM = CSECMD
#pragma config FNOSC = FRCDIVN, PWMLOCK = OFF, IESO = ON, GWRP = OFF, GCP = OFF

#include "xc.h"

const uint16_t ConfDiskImage[] = {
    /*AOUT*/ 0x01E0,0x0004,0x3333,0x4053,
    /*   1*/ 0x01E1,0x0012,0x0005,0x0000,0x0000,0x0000,0x4120,0x0000,0x0000,0x0000,0x4120,
    /*   2*/ 0x01E2,0x0012,0x0006,0x0000,0x0000,0x0000,0x4120,0x0000,0x0000,0x0000,0x4120,
    /*   3*/ 0x01E3,0x0012,0x0007,0x0000,0x0000,0x0000,0x4120,0x0000,0x0000,0x0000,0x4120,
    /*EOD */ 0x0000,0x0000
};

int main(void)
{
    const uint16_t *pData;

    pData = ConfDiskImage; /* point to the start of the image */
    /*
     * Walk the image
     */
    for(;;)
    {
        if((!*pData) && (!*pData+1))
        {
            /* At end of image point to the start */
            pData = ConfDiskImage;
        }
        pData++; /* skip record type */
        pData += 1+*pData/2;
    }
    return 0;
}


Q: Mimic HTML5 form validation default styling I have a simple HTML5 form with required fileds. When the page loads the fields have no styling. When I click on the required field, type something and then erase the text I just typed and exit the field, it shows me pink box-shadow outside the invalid field in Firefox.
Now I need yellow box-shadow, while retaining the same behavior. That's how I did:
In HTML
<input name="email_address" id="email_address_uuid_479823574" type="email"
       placeholder="ex. example@domain.com" title="Email address" required />

       -------
       -------

<input name="model_number" id="model_number_uuid_479823574" type="text"
       placeholder="ex. oxpd-983s" title="Equipment model number" required />

In CSS
input:required:invalid {box-shadow: 1px 2px 9px yellow};

Result: The page loads with all the fields with yellow box-shadow! Rather wait for user to make the mistake onblur and onsubmit like the default behavior.
How to override the default box-shadow of invalid field without changing the behavior?

A: Try:
input:required:-moz-ui-invalid {box-shadow: 1px 2px 9px yellow};

See https://developer.mozilla.org/en/CSS/:invalid


Q: Laravel Model Restore Event So I have 2 Models Users & Staff. They have one to one relationship with one another.
User.php 'hasOne' Staff
AND
Staff.php 'belongsTo' User
When I Soft Delete a User I want to soft delete Staff entry as well, I have achieved this using(Works Perfectly):
static::deleting(function ($user) {
    $user->staff()->delete();
});

Now I want to restore the staff when I restore the User for that I have tried using this(Not working):
static::restoring(function ($user) {
    $user->staff()->restore();
});

But this is not working. The User Entry is deleted but the Staff entry still remains soft deleted.

*

*Can someone help me understand what I am doing wrong here?

*Also, Is this the best way to get this done? Or is there some other way this should be done?
PS: I'm using Laravel 5.5

A: It isn't working because $user->staff() doesn't fetch deleted staff. That's how relationships work by default.
Just replace it with this:
static::restoring(function ($user) {
    $user->staff()->withTrashed()->restore();
});

A: "static::restoring" event is never triggered when restoring a batch of models.
If you're doing something like:
Yourmodel::whereIn('id', [1,2,3])->restore();

It will restore your models but "static::restoring or restored" will never be triggered, instead you could do something like this:
$models = Yourmodel::whereIn('id', [1,2,3])->get();
foreach($models as $model) {
   $model->restore();
}


Q: Django translation without request object I'm translating my Django app, in which I have a push notification module. From that module, I send a text field to user's mobile devices. Since the trigger of those notifications is not a proper HTTP request (with its "request" object), the default Django way of translating strings doesn't work.
I have a field on every user profile with its preferred language, so I think I should write some kind of middleware which would match that field with its correct translation.
Is there any way of doing that?

A: You are looking for translation.override context manager:
language = user.get_language()
with translation.override(language):
    # Translate your message here.


Q: Passing value from aspx.cs page to stored procedure I have a line in my aspx.cs page that-
cmd.CommandText="INSERT INTO [dbo].[Table] (No_Entered) Values ("+i+")";

My question is : what should be its corresponding stored procedure look like?
Thank you in advance :-)

A: cmd.CommandText = "YourStoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@No_Entered",i); //@No_Entered is parameter name in SP

Stored Procedure
CREATE PROCEDURE dbo.YourStoredProcedureName
@No_Entered int
AS
INSERT INTO TABLENAME (No_Entered) VALUES (@No_Entered)
GO

A: You have to create the stored procedure yourself.  It doesn't magically exist on its own.
https://msdn.microsoft.com/en-us/library/ms187926.aspx


Q: Total changing flux in Faraday Lenz law of induction To clarify my question, I made the illustration below, assuming I understood the Faraday-Lenz law:

Above a copper loop theoretically stays in parallel between the plates A and B.
The magnetic field B hence the flux between the plates A and B is continuously increased.
The copper loop circulates a current such that to oppose the increasing flux.
Above I showed the directions of increasing flux and self generated opposing flux.
My question is, will the total changing flux always be zero no matter the conductor is perfect or not?
If the applied flux was constant(not varying by time) the total flux would be non zero.
But in case the flux is increasing, will the total changing flux be zero?

A: No - there is an easy counterexample. The EMF generated by the flux is independent of the material used in the wire. At a constant EMF, the current in the wire will be proportional to the resistance of the wire (i.e. the conductivity $\sigma$). Therefore, if at some conductivity $\sigma_o$ the "reaction" flux perfect cancels the changing flux, at some lower conductivity it will not.

A: Lenz tells you that the induced current will try and oppose the change producing it.
If Lenz wins and stops the change in magnetic flux there will be no induced emf and hence no induced current.
If there is no induced current there is no opposition to the change of magnetic flux.
Hence Lenz cannot stop the change; Lenz can only reduce the change.

A: The EMF ${\cal E}$ depends on the rate of change of the flux
${\cal E}=-\frac{d}{dt}\Phi(t)$
but the current induced in the loop will depend on the load of the loop.  In your example, you could insert a $10\Omega$ resistor to get some current $I={\cal E}/10$ or a $1\Omega$ resistor to get $10I$.  Hence the $\vec B$ field produced by loop can be changed without affecting $\frac{d}{dt}\Phi(t)$ and "the total changing flux" need NOT "always be zero no matter the conductor is perfect or not". x


Q: How to find match accros multiple lines? I have a file that looks like this:
#% text_encoding = utf8

:xy_name1   Text

:xy_name2   Text text text to a text.

Text and text to text text, text and

text provides text text text text.

:xy_name3   Text

And I want to get each entry (:ENTRY_NAME (tab \t) ENTRY_DESCRIPTION).
Im using r'^([a-zA-Z0-9:_\|!\.\?%\-\(\)]+)[\s\t]+(.*)$' regex but it doesn't work with entries that have multiline descriptions.
How can I do that?

A: The following code will do the trick:
import re

data = '''
#% text_encoding = utf8

:xy_name1   Text

:xy_name2   Text text text to a text.

Text and text to text text, text and

text provides text text text text.

:xy_name3   Text
'''

print(re.findall(r'^:(\S+)\s+([\S\s]*?)(?=\n:|\Z)',data,re.M))

The last parameter in the re.findall is a flag that makes the search a multi-line search.
^:(\S+) will match the beginning of any line followed by a colon and at least one non-space character
\s+ then consumes the tab and spaces before the description
([\S\s]*?) matches the description beginning with the first non-space character and including everything in its way - newlines inclusive. You can not use . here because in a multi-line search the . is not matching the newline character. That is why I used [\S\s] which matches all non-space characters and all space characters. The ? at the end makes the * non-greedy. Otherwise that group would consume everything all the way to the end of the data.
(?=\n:|\Z) marks the end of the description. This group is a positive look-ahead which matches either a newline followed by a colon (\n:) or the end of the data (\Z). A look-ahead does not consume the newline and the colon therefore they will be available for the next match of the findall.
The output of above code is
[('xy_name1', 'Text\n'), ('xy_name2', 'Text text text to a text. \n\nText and text to text text, text and \n\ntext provides text text text text.\n'), ('xy_name3', 'Text\n')]

Try it out here!

A: You can use capture the ENTRY_NAME in group 1.
For the ENTRY_DESCRIPTION in group 2 you can match the rest of the line, followed by all lines that do not start with the entry name pattern.
^:([\w:|!.?%()-]+)\t(.*(?:\n(?!:[\w:|!.?%()-]+\t).*)*)

Regex demo | Python demo
Example
import re

pattern = r"^:([\w:|!.?%()-]+)\t(.*(?:\n(?!:[\w:|!.?%()-]+\t).*)*)"

s = ("#% text_encoding = utf8\n\n"
            ":xy_name1  Text\n\n"
            ":xy_name2  Text text text to a text. \n\n"
            "Text and text to text text, text and \n\n"
            "text provides text text text text.\n\n"
            ":xy_name3  Text")

print(re.findall(pattern, s, re.MULTILINE))

Output
[
  ('xy_name1', 'Text\n'),
  ('xy_name2', 'Text text text to a text. \n\nText and text to text text, text and \n\ntext provides text text text text.\n'),
  ('xy_name3', 'Text')
]


Q: plane calculation in point cloud with lm() in R I have some 3D points and I want to have the better plane which minimize the distance between the plane and the point cloud. I used lm() to extract the 3 values I need.
x<-sample(1:100, 100)
y<-sample(1:100, 100)
z<-sample(1:100, 100)
plot3d(x, y, z, type = "s", col = "red", size = 1)
my.lm <- #I tried different combination of lm: lm(x ~ y + z)/lm(y ~ x + z)/lm(z ~ y + x)
#lm fct     Intercept   1st after ~   2nd after ~
#lm(x~y+z) 43.45653      0.17151     -0.03203
#lm(y~x+z) 40.66175      0.17159      0.02322
#lm(z~x+y) 50.95859     -0.03298      0.02390
planes3d(-1, 0.17151, -0.03203, 43.45653, alpha=0.5) #function use a b c and d of the ax+by+cz+d=0 equation
planes3d(0.17159, -1, 0.02322, 40.66175, alpha=0.5)
planes3d(-0.03298, 0.02390, -1, 50.95859, alpha=0.5)

I thought that the 3 planes extracted from the 3 lm() would be the same but they are very different. So I think that the reference axis chosen in the lm() function define the priority of research.
So how can I have the better plane which fit with my point cloud and that independantly (I don't want to affect the output when I choose which axis I put before the ~)
Where am I wrong? How can it be independant?
When I apply my algorithm with lm(x~y+z) I see that the plane is sometimes orthogonal compared to what I expected.

A: I think that your code is correct, but maybe the question that you are trying to solve is not clear in the sense of the output that you expect.
In the example of a cloud of homogeneously distributed unlabelled 3D points, there is no unique way to perform a dichotomy, separating the points with a unique, "ideal" surface. You can do this for the individual Cartesian components of the set of points though, and this is what your code achieves.
The first plane, shown in red color in the panel on the left in the figure below, separates the points in a linearly optimal way by a plane that only considers the x-coordinate of the points as a function of their position, leading to a function of the type x=f(y,z).
The second plane (green, on the right) is the result of a linear fit of the y-component of the points, y=g(x,z); and the third (shown in blue, in the middle) is a linear fit of the z-component of the points in the set z=h(x,y).
The three planes are certainly different, because they represent fits to different values. Hence, I don't think that there is anything wrong with your code and with your result.

Unlike the case described here, it is often possible to define meaningful (hyper-)planes separating different types of points, (like points with a certain value, e.g., temperature; or points with different attributes like "yellow" and "purple" points). It then depends on the distribution of these points in space whether they are linearly separable or not. In the latter case there are often solutions, too, but they are more complicated. For more information on such cases you may want to read about Support Vector Machines (SVM). Several R packages provide algorithms for SVMs such as, e.g., e1071 or the popular caret library.


Q: Initializing new Fragment in Tabhost/Viewpager construct not working I have an activity holding a sidebar navigation and a place holder for my fragments. (-> on clicking the sidemenu I switch fragments ...)
One of those fragments (called TabFragment) uses tabs, which are populated with (List)fragments (similar to http://developer.android.com/reference/android/support/v4/view/ViewPager.html example, but I dont use Actionbar Tabs, but the old ones).
The first time I show the TabFragment, everything works. The TabFragment is called, there I "populate the tabs" (--> like in the example above I actually just populate the viewpager) with my ListFragments (there onCreateView etc. is called). It works.
Then I try to put another instance of the TabFragment on the screen (I need to show different lists and want to be able to use the back button -> backstack), the TabFragment is called, I add the Fragments to the TabsAdapter, but no lifecycle methode of the ListFragments is called ... why?
[I know that this isn't the best way to go and there are plenty of options to rewrite this to get the same effect, but since it works the first time I'd really like to know where this is going wrong]
Activity Code
     Fragment search1 = new MainListFr();
     Bundle test1 = new Bundle();
     test1.putInt(Constants.FRAGMENT_SEARCH_ID, 1);
     g1.setArguments(test1);

     m_fragmentTransaction = m_fragmentManager.beginTransaction();
     m_fragmentTransaction.add(R.id.main_fragment_container, search1, "search1");
     m_fragmentTransaction.addToBackStack("search1");
     m_fragmentTransaction.commit();

     m_layout.toggleSidebar();

MainListFr (=TabFragment)
public class MainListFr extends Fragment {
   TabHost m_tabHost;
   ViewPager m_viewPager;
   TabsAdapter m_tabsAdapter;

   @Override
   public View onCreateView(final LayoutInflater inflater,
         final ViewGroup container, final Bundle savedInstanceState) {
      final View view = inflater.inflate(R.layout.stub_main, null);

      m_tabHost = (TabHost) view.findViewById(android.R.id.tabhost);
      m_tabHost.setup();

      m_viewPager = (ViewPager) view.findViewById(R.id.main_pager);

      m_tabsAdapter = new TabsAdapter(getActivity(), m_tabHost, m_viewPager);

      View v1 = inflater.inflate(R.layout.tab_left, null);
      View v2 = inflater.inflate(R.layout.tab_right, null);

      Bundle args = getArguments();

      m_tabsAdapter.addTab(m_tabHost.newTabSpec("topsearch").setIndicator(v1),
            SearchListFr.class, args);
      m_tabsAdapter.addTab(m_tabHost.newTabSpec("topsuggestion").setIndicator(v2),
            SuggestionListFr.class, args);

      if (savedInstanceState != null) {
         m_tabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
      }

      return view;
   }
}

SearchListFr (=ListFragment)
   private ListView m_list = null;
   private View m_progress = null;
   private View m_noRes = null;

   SearchAdapter m_searchAdapter = null;
   private Vector<SearchItem> m_searchList = null;

   private int m_searchId = 0;

   @Override
   public View onCreateView(final LayoutInflater inflater,
         final ViewGroup container, final Bundle savedInstanceState) {

      final View view = inflater.inflate(R.layout.fr_videolist, null);

      m_list = (ListView) view.findViewById(R.id.fr_videolist_list);
      m_progress = view.findViewById(R.id.progress_root);
      m_noRes = view.findViewById(R.id.noresult_root);

      m_list.setVisibility(View.GONE);
      m_noRes.setVisibility(View.GONE);
      m_progress.setVisibility(View.VISIBLE);

      Bundle args = getArguments();
      if (args != null) {
         m_searchId = args.getInt(Constants.FRAGMENT_SEARCH_ID);
      }

      // load the content here (asynctask)
      new LoadSearchList().execute();

      return view;
   }

   @Override
   public void onActivityCreated(Bundle _savedInstanceState) {
      super.onActivityCreated(_savedInstanceState);

      m_searchAdapter = new SearchAdapter(getActivity());
      m_list.setAdapter(m_searchAdapter);
      m_list.setItemsCanFocus(true);
      m_list.setOnItemClickListener(this);
   }

TabsAdapter
/**
 * This is a helper class that implements the management of tabs and all
 * details of connecting a ViewPager with associated TabHost.  It relies on a
 * trick.  Normally a tab host has a simple API for supplying a View or
 * Intent that each tab will show.  This is not sufficient for switching
 * between pages.  So instead we make the content part of the tab host
 * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
 * view to show as the tab content.  It listens to changes in tabs, and takes
 * care of switch to the correct paged in the ViewPager whenever the selected
 * tab changes.
 */
public class TabsAdapter extends FragmentPagerAdapter
        implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
    private final Context mContext;
    private final TabHost mTabHost;
    private final ViewPager mViewPager;
    private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

    static final class TabInfo {
        private final Class<?> clss;
        private final Bundle args;

        TabInfo(String _tag, Class<?> _class, Bundle _args) {
            clss = _class;
            args = _args;
        }
    }

    static class DummyTabFactory implements TabHost.TabContentFactory {
        private final Context mContext;

        public DummyTabFactory(Context context) {
            mContext = context;
        }

        @Override
        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }

    public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
        super(activity.getSupportFragmentManager());
        mContext = activity;
        mTabHost = tabHost;
        mViewPager = pager;
        mTabHost.setOnTabChangedListener(this);
        mViewPager.setAdapter(this);
        mViewPager.setOnPageChangeListener(this);
    }

    public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
        tabSpec.setContent(new DummyTabFactory(mContext));
        String tag = tabSpec.getTag();

        TabInfo info = new TabInfo(tag, clss, args);
        mTabs.add(info);
        mTabHost.addTab(tabSpec);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mTabs.size();
    }

    @Override
    public Fragment getItem(int position) {
        TabInfo info = mTabs.get(position);
        return Fragment.instantiate(mContext, info.clss.getName(), info.args);
    }

    @Override
    public void onTabChanged(String tabId) {
        int position = mTabHost.getCurrentTab();
        mViewPager.setCurrentItem(position);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        // Unfortunately when TabHost changes the current tab, it kindly
        // also takes care of putting focus on it when not in touch mode.
        // The jerk.
        // This hack tries to prevent this from pulling focus out of our
        // ViewPager.
        TabWidget widget = mTabHost.getTabWidget();
        int oldFocusability = widget.getDescendantFocusability();
        widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        mTabHost.setCurrentTab(position);
        widget.setDescendantFocusability(oldFocusability);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
}


Q: How to properly loop without eval, parse, text=paste("... in R So I had a friend help me with some R code and I feel bad asking because the code works but I have a hard time understanding and changing it and I have this feeling that it's not correct or proper code.
I am loading files into separate R dataframes, labeled x1, x2... xN etc.
I want to combine the dataframes and this is the code we got to work:
assign("x",eval(parse(text=paste("rbind(",paste("x",rep(1:length(toAppend)),sep="",collapse=", "),")",sep=""))))

"toAppend" is a list of the files that were loaded into the x1, x2 etc. dataframes.
Without all the text to code tricks it should be something like:
x <- rbind(##x1 through xN or some loop for 1:length(toAppend)#)

Why can't R take the code without the evaluate text trick? Is this good code? Will I get fired if I use this IRL? Do you know a proper way to write this out as a loop instead? Is there a way to do it without a loop? Once I combine these files/dataframes I have a data set over 30 million lines long which is very slow to work with using loops. It takes more than 24 hours to run my example line of code to get the 30M line data set from ~400 files.

A: If these dataframes all have the same structure, you will save considerable time by using the 'colClasses' argument to the read.table or read.csv steps. The lapply function can pass this to read.* functions and if you used Dason's guess at what you were really doing, it would be:
 x <- do.call(rbind, lapply(file_names, read.csv,
                                colClasses=c("numeric", "Date", "character")
               ))   # whatever the ordered sequence of classes might be

The reason that rbind cannot take your character vector is that the names of objects are 'language' objects and a character vector is ... just not a language type. Pushing character vectors through the semi-permeable membrane separating 'language' from 'data' in R requires using assign, or do.call eval(parse()) or environments or Reference Classes or perhaps other methods I have forgotten.


Q: How to print the sum of the number of times a certain integer returns? Heres the code:
I want to be able to print something like "Buy! = ???" or "Sell! = ???" or "Hold! = ???".
list_A = []
list_B = []

num_sells = 0
num_buys = 0
num_holds = 0

for x in range(10000):
    list_A.append(np.random.randint(0,10))
    list_B.append(np.random.randint(0,10))

    if list_A[x] > list_B[x]:
        num_buys += 1
        cprint("Buy!", 'green', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)

    elif list_A[x] < list_B[x]:
        num_sells += 1
        cprint("Sell!", 'red', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)

    else:
        num_holds += 1
        cprint("Hold!", attrs=['bold', 'reverse', 'blink', 'dark'], file=sys.stderr)

Recommendations are greatly appreciated.

A: Well then just print the answer outside the loop. If I'm getting your doubt correctly.
list_A = []
list_B = []

num_sells = 0
num_buys = 0
num_holds = 0

for x in range(10000):
    list_A.append(np.random.randint(0,10))
    list_B.append(np.random.randint(0,10))

    if list_A[x] > list_B[x]:
        num_buys += 1

    elif list_A[x] < list_B[x]:
        num_sells += 1

    else:
        num_holds += 1

cprint("Buy!", 'green', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Sell!", 'red', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Hold!", attrs=['bold', 'reverse', 'blink', 'dark'], file=sys.stderr)

Like the above.


Q: Hello world hibernate Trying to run simple java project with SQLight Hybernate. Got exception:
Deleting Doc
Hibernate: delete from Doc
Updating document, DocID = 2, Name = doc 2
Hibernate: update Doc set DocName=?, Job=? where Id=?
exception Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
Jun 15, 2016 3:30:03 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
    at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
    at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:47)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2574)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2478)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2805)
    at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:114)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:267)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:259)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:179)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at hyberntst.Db2.close(Db2.java:46)
    at hyberntst.Db2.saveDoc(Db2.java:75)
    at hyberntst.HybernTst.main(HybernTst.java:19)

I have empty table Doc in data.db
CREATE TABLE `Doc` (
    `Id`    INTEGER PRIMARY KEY AUTOINCREMENT,
    `DocName`   TEXT,
    `Job`   TEXT
)

Hybernate config - hybernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">hyberntst.SQLiteDialect</property>
    <property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
    <property name="hibernate.connection.url">jdbc:sqlite:data.db</property>
    <property name="hibernate.connection.pool_size">1</property>
    <property name="hibernate.show_sql">true</property>
    <!--property name="hibernate.current_session_context_class">thread</property-->
    <!--property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property-->
    <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <mapping resource="hyberntst/Doc.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Class responsible for dealing with DB:
package hyberntst;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Db2 {

    private SessionFactory sessionFactory;
    private Session session;

    Db2() {

        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    //------------------------------------------------------------------------------------------------------------------
    private void open() {
        session = sessionFactory.openSession();
        session.beginTransaction();
    }

    private List query(String hql) {
        Query query = session.createQuery(hql);
        return query.list();
    }

    private void executeUpdate(String hql) {
        Query query = session.createQuery(hql);
        query.executeUpdate();
    }

    private void close() {
        session.getTransaction().commit();
        session.close();
    }

    public void deleteDoc() {
        try {
            open();

            log.finer("Deleting Doc");
            executeUpdate("delete Doc");

            close();
        } catch (Exception ex) {
            log.logExept(ex);
        } catch (Error err) {
            log.warning(err.toString());
        }
    }

    public void saveDoc(Doc doc) {
        try {
            open();
            log.finer("Updating document, DocID = " + doc.getId() + ", Name = " + doc.getDocName());
            session.saveOrUpdate(doc);

            close();
        } catch (Exception ex) {

            log.logExept(ex);
        }

    }

}

Doc class for writing to DB:
public class Doc {
     private Integer id;

    public Integer getId()
    {
        return this.id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    private String docName;

    public String getDocName()
    {
        return this.docName;
    }

    public void setDocName(String docName)
    {
        this.docName = docName;
    }

    private String job;

    public String getJob()
    {
        return this.docName;
    }

    public void setJob(String job)
    {
        this.job = job;
    }

}

"main" code:
Doc d = new Doc();
d.setId(new Integer(2));
d.setDocName("doc 2");
d.setJob("job 2");

Db2 db2 = new Db2();
db2.deleteDoc();
db2.saveDoc(d);

There you can see libs I use:

Looks like delete from database works fine, but what is wrong with insertion?
And what is question marks parmas in log file?
Hibernate: update Doc set DocName=?, Job=? where Id=?

A: In general, if entity id is not null, hibernate will perform update.
More information here:

saveOrUpdate() does the following:

*

*if the object is already persistent in this session, do nothing if
another object associated with the session has the same identifier,
throw an exception

*if the object has no identifier property, save() it

*if the object's identifier has the value assigned to a newly instantiated object, save() it

*if the object is versioned by a  or , and the version property value is the same value assigned to a newly
instantiated object, save() it

*otherwise update() the object

You have to call save() explicitly or leave id null


Q: What is a clean way to write a localized FtpReply to an FtpSession in a Ftplet? I would like to avoid hardcoding reply messages in a Ftplet, how can I call LocalizedFtpReply org.apache.ftpserver.impl.LocalizedFtpReply.translate(FtpIoSession session, FtpRequest request, FtpServerContext context, int code, String subId, String basicMsg) or equivalent, in a clean way?
public class NotifyFtplet extends DefaultFtplet {

    @Override
    public FtpletResult onUploadStart(FtpSession session, FtpRequest request) throws FtpException, IOException {
        session.write(new DefaultFtpReply(FtpReply.REPLY_150_FILE_STATUS_OKAY, "File status okay; about to open data connection."));
        return FtpletResult.SKIP;
    }

}


Q: Tests running locally but no test generation on jenkins ‘Publish JUnit test result report’ failed: No test report files were found I have been writing unit tests for my angular app and they run pretty well on jasmine . However when putting them on jenkins the build doesn't get completed and I have no report generated, I get the following error .
[32m28 07 2019 12:52:27.841:INFO [karma]: [39mKarma v1.7.1 server started at http://0.0.0.0:9876/
[32m28 07 2019 12:52:27.844:INFO [launcher]: [39mLaunching browser ChromeHeadless with unlimited concurrency
[32m28 07 2019 12:52:27.875:INFO [launcher]: [39mStarting browser ChromeHeadless
[31m28 07 2019 12:52:46.448:ERROR [karma]: [39m{ inspect: [Function: inspect] }
Build step 'Execute shell' marked build as failure
Recording test results
ERROR: Step ‘Publish JUnit test result report’ failed: No test report files were found. Configuration error?
Finished: FAILURE

What I tried to do is making two separate jenkins projects . In each one I put a different test file ( in total they're two tests files) .
One of the projects run pretty well but the second one sends back the mentionned Error , I get the same error when putting both test files in the same jenkins project .
This is the project (website folder)
https://github.com/testing-angular-applications/testing-angular-applications.git
The tests are the two .spec files inside chapter03 (inside the same git)
At least I should get the report file but the build didn't go to that point ( no report has been generated)

A: Resolved !
I had to downgrade to Jasmine core 2.4.1 .


Q: Which version of Microsoft Office introduced the ability to edit and save to PDF files? As of the latest several versions of the Microsoft Office suite, it now appears to be possible to interact with PDF files - Word documents can now be saved as a PDF, and PDF files can now be opened and edited directly from within Microsoft Word. Which versions of Office initially introduced this functionality?

A: Which versions of Office initially introduced this functionality?
Exporting PDFs was introduced in Office 2007 Service Pack 2:

Initially, Microsoft promised to support exporting to Portable Document Format (PDF) in Office 2007. However, due to legal objections from Adobe Systems, Office 2007 originally did not offer PDF support out of the box, but rather as a separate free download. However, starting with Service Pack 2, Office allows users to natively export PDF files.

Source Microsoft Office 2007 - Wikipedia
Full read, write and edit support was added in Office 2013:

Microsoft Office 2013 includes updated support for ISO/IEC 29500, the International Standard version of Office Open XML (OOXML) file
  format: in particular it supports saving in the "Strict" profile of
  ISO/IEC 29500 (Office Open XML Strict). It also supports OASIS
  version 1.2 of ISO/IEC 26300:2006, Open Document Format, which
  Office 2013 can read and write. Additionally, Office 2013 provides
  full read, write, and edit support for ISO 32000 (PDF).
...
Other features of Office 2013 include:

*

*PDF Import feature in Microsoft Word

Source Microsoft Office 2013 - Wikipedia

A: Wikipedia says for Microsoft Office, section
Desktop applications:

Support for Portable Document Format (PDF) and OpenDocument (ODF) was first introduced in Word for Windows with Service Pack 2 for Word 2007.

A:
Which versions of Office initially introduced this functionality?

Based on the documentation to edit PDFs within Office.  This feature requires Office 2010 or newer.
However, Office 2007 did indeed have this feature, but required you to install the 2007 Microsoft Office Add-in: Microsoft Save as PDF or XPS add-on in order to save a document as a PDF.  While I have linked to this add-on, the file is not longer accessible, it's simply there for posterity.  Office 2007 Service Pack 2 added the ability to save a document as a PDF natively.

Office 365, Office 2019, Office 2016, Office 2013, Office 2010

Sources:

*

*Edit or make changes to a PDF file

*Save or convert to PDF or XPS in Project desktop

*2007 Microsoft Office Add-in: Microsoft Save as PDF or XPS

*Microsoft Expands List of Formats Supported in Microsoft Office


Q: converting 2D mouse coordinates to 3D space in OpenGL ES I want to convert mouse's current X and Y coordinates into the 3D space I have drawn in the viewport. I need to do this on the OpenGL ES platform. I found following possible solutions implemented in OpenGL, but none fits what I am looking for.

*

*I found NeHe's tutorial on doing exactly this, but in traditional OpenGL way. It uses gluUnProject.
http://nehe.gamedev.net/data/articles/article.asp?article=13
Although gluUnProject is not available in OpenGL ES, its implementation seems simple enough to port back. But before calling it, we need to call glReadPixels with GL_DEPTH_COMPONENT and that is not possible in OpenGL ES. (The reason I found in this thread: http://www.khronos.org/message_boards/viewtopic.php?f=4&t=771)

*What I want to do is similar to picking, except that I don't want to select the object but I want exact coordinates so that I can recognize particular portion of the object that is currently under mouse cursor. I went through the Picking tutorials in this answer.
https://stackoverflow.com/posts/2211312/revisions
But they need glRenderMode, which I believe is absent in OpenGL ES.
If you know how to solve this problem in OpenGL ES, please let me know.
Thanks.

A: I think the general solution is to figure out where in world space the clicked coordinate falls, assuming the screen is a plane in the world (at the camera's location). Then you shoot a ray perpendicular to the plane, into your scene.
This requires "world-space" code to figure out which object(s) the ray intersects with; the solutions you mention as being unsuitable for OpenGL ES seem to be image-based, i.e. depend on the pixels generated when rendering the scene.

A: With OpenGL ES 2.0 you could use a FBO and render the depth values to a texture. Obviously, this wouldn't be exactly cheap (just a way around the restriction of glReadPixels)...
Further, since - as I understand it - you want to pick certain parts of your object you might want to do some sort of color-picking where each selectable portion of the object has an unique color (note that the Lighthouse 3D tutorial only shows the general idea behind color-picking, your implementation would probably be different). You could optimize a little by performing a ray/bounding-box intersection beforehand and only rendering the relevant candidates to the texture used for picking.


Q: Setting up Rocket-chip for Questasim and getting error while compiling jtag_vpi.c I have downloaded Rocket-chip from GIT, installed RISC-V tools and Generated the verilog files for Rocket core. Now I want to run the assembly tests that are given but I dont have VCS instead I have Questasim. I modified the Makefile to use Questasim but the two C++ files that needs to be compiled SimDTM.cc and jtag_vpi.c are giving error.
In Questa we cant compile C files along with verilog files instead we need to compile this separately and generate *.so file and link with -pli while simulating.
Here when I'm compiling jtag_vpi.c I'm getting and error saying invalid conversion from 'void*' to 'PLI_INT32. I'm compiling it with the below command and the error I'm getting is also pasted below.

g++ jtag_vpi.c -I $RISCV/include -I $MTI_HOME/questasim/include -std=c++11 -W -shared -Bsymblic -fPIC

.
.

riscv/rocket-chip/csrc/jtag_vpi.c:398:2: error: invalid conversion from ‘void*’ to ‘PLI_INT32 (*)(t_cb_data*) {aka int (*)(t_cb_data*)}’ [-fpermissive]

Line 398:2 is just an end of a function and the error is shown at the end of each such function.
Any help will be useful.
Thanks in advance.


Q: swift 3 using layers to reveal an image by drawing "clear" lines * Update  Shortly after posting I found this which looks to have all my answers. Not yet worked it out for myself but this might help anyone else with similar issue. Scratch Card effect in Swift 3  End Update *
This is my first question to Stack so apologies if it's a bit 'noob'. My question kind of has two parts. I've used a couple of tutorials which have shown me how to draw lines over an image in an imageView, but I'm struggling to achieve my goal of revealing an image beneath an overlayer by drawing a "clear" line on the layer. Imagine a scratch card... that is the effect I'm after.
I have used the following Stack question/answer to help guide me initially Draw a line realtime with Swift 3.0; but my end goal is being thwarted further by the confusion of image/view bounds.
The tutorial above works great for initial drawing, except when I touch the screen, the position of my finger is converted to the imageView coordinates, so the line never appears where I place my finger. I would really like someone to help my convert the coords so the line draws exactly where I place my finger. I've tried changing the bounds in the 'Draw line' func, but I get strange behaviour from the image and the drawing stops working completely.
If anyone is able to help on either issue I'd be really grateful. And if I need to split the questions then I will do so. I've attached my code if it helps. Thanks for looking...
class ViewController: UIViewController {

    @IBOutlet weak var myImageView: UIImageView!

    var layer: CALayer {
        return myImageView.layer
    }

    var lastPoint = CGPoint.zero
    var red: CGFloat = 0.0
    var green: CGFloat = 0.0
    var blue: CGFloat = 0.0
    var brushWidth: CGFloat = 10.0
    var opacity: CGFloat = 1.0
    var swiped = false

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        swiped = false
        if let touch = touches.first {
            lastPoint = touch.location(in: self.view)
        }
    }

    func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)

        myImageView.image?.draw(in: view.bounds)

        let context = UIGraphicsGetCurrentContext()

        context?.move(to: fromPoint)
        context?.addLine(to: toPoint)

        context?.setLineCap(CGLineCap.round)
        context?.setLineWidth(brushWidth)
        context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
        context?.setBlendMode(CGBlendMode.normal)
        context?.strokePath()

        myImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        myImageView.alpha = opacity
        UIGraphicsEndImageContext()
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        swiped = true
        if let touch = touches.first {
            let currentPoint = touch.location(in: view)
            drawLine(from: lastPoint, to: currentPoint)

            lastPoint = currentPoint
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !swiped {
            // draw a single point
            self.drawLine(from: lastPoint, to: lastPoint)
        }
    }

    func setUpLayer() {
        layer.backgroundColor = UIColor.clear.cgColor
        layer.borderWidth = 10.0
        layer.borderColor = UIColor.red.cgColor
        layer.shadowOpacity = 0.7
        layer.shadowRadius = 10.0
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        myImageView.image = UIImage(named: "8BitGirls.png")

        setUpLayer()
    }
}

A: The UIResponder Touches methods are returning coordinates in your UIViewController.view's coordinates, but you need to draw in your imageViews coordinates.  UIView has multiple methods to help you with this.  try this one:
myImageView.convert(fromPoint, from: view)


Q: Where is statement counter incremented for reporting coverage within Go source code? I am looking into the Golang source code and want to understand how does it calculate coverage. I understand that each block of code has it's own statement counter; however, where is that statement counter being incremented?
Here is a link for the cover.go: https://github.com/golang/go/blob/master/src/cmd/cover/cover.go

A: Realized that you are unable to see where the counters are incremented;; the counters are boolean statements at the end of each block of code and are set to true/false during buildtime.


Q: debug node js chaincode ...? This link gives tutorial on debugging javascript chaincode in hyperledger fabric. I was able to debug my chaincode following it but recently I updated to fabric 1.2 and the peer channel list command
CORE_PEER_LOCALMSPID=Org1MSP CORE_PEER_MSPCONFIGPATH=/home/bct/fabric-samples/basic-network/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp peer channel list

fails with:

Fatal error when initializing core config : error when reading core
  config file: Unsupported Config Type ""

I tried to go back to v1.1 but the problem persists. Can someone give me the complete list of configuration steps that may have been missed in tutorial video (which I was following) that make the debugging chaincode work.
Thanks in advance.

A: Finally, figured out that fabric sdk (https://github.com/hyperledger/fabric-sdk-node) has to be downloaded and configured before following the video tutorial in the question.


Q: Properly writing a hexadecimal value to an address in x86 machine language I'm trying to learn how to write x86 machine code as hexadecimal (as part of putting text to the monitor on a qemu cold start.) My guess from reading a few sites was that the proper instruction to write 0x78073807 to 0xB8000  should be something along the lines of C7 00 80 0B 00 07 38 07 78 00 00 00 00 00 00 00. However, when putting this into a disassembler, the information it returns appears to indicate that this syntax is wrong. What am I missing here?
Thank You!

A: The code is missing the modr/m byte between the opcode C7 and the displacement and immediate.
mov dword [0x000B8000], 0x78073807

C7, 05, 00, 80, 0B, 00, 07, 38, 07, 78


Q: Obtain a link to a specific email in GMail How can I obtain a link (a URL) to a specific email in GMail? I want to click that link and open the specific email.

A: To clarify on the answer provided by Kevin Patel you can get the link directly from your browser, however you must have the reading pane set to "No split", otherwise you get a generic URL.

A: I don't know about a specific "email", but you can view a specific thread (which is usually one email) by clicking in the URL bar and copying that. Then, change the label to "all".
So if the url is "https://mail.google.com/mail/u/0/#inbox/abc123def456", you would change "#inbox" to say "#all" like this: "https://mail.google.com/mail/u/0/#all/abc123def456"
Now the link will work, even after you archive it and it's not in your inbox.

A: Since Google introduced the integration of Google Tasks and Gmail a few weeks ago, one way you can get the URL of a specific Gmail email us:

*

*Turn a given Gmail email into a Google Task;

*Open the task editing window (you can't perform the next task from the task display, it only seems to work when the task editing function is invoked);

*Hover over the link to the originating Gmail email in the next task you just created (the link is at the bottom of the task display);

*Use that URL to access the specific Gmail email by clicking on the link in the corresponding Google task or just pop the URL into the URL bar of any browser or other workflow (of course, the session must be logged in to the relevant Google account).

Enjoy!

A: If you are happy with a bookmarklet that copies a link to the current email to your clipboard, you can try adding this to your bookmarks:
javascript:(function()%7Basync%20function%20copyPermalink()%20%7Btry%20%7BsearchURL%20%3D%20'https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F%23search%2Fmsgid%253A'%3BmessageId%20%3D%20document.querySelector('div%5Bdata-message-id%5D').getAttribute('data-message-id').substring(7)%3Bawait%20navigator.clipboard.writeText(searchURL%20%2B%20messageId)%3Bconsole.log('Mail%20message%20permalink%20copied%20to%20clipboard')%3B%7D%20catch%20(err)%20%7Bconsole.error('Failed%20to%20copy%3A%20'%2C%20err)%3B%7D%7DcopyPermalink()%7D)()

It essentially searches the currently focussed email for its data-message-id attribute, and then converts that into a search url using the msgid predicate (this doesn't seem to be documented, but was quite guessable.). The full link is then copied to your clipboard.
Caveat: Seems to work with or without a preview pane, but this hasn't been extensively tested.

A: I don't think Gmail can show one email, it always shows a thread. You can look for one message, but still will see the whole thread.
If this is OK for you, the URL is
https://mail.google.com/mail/u/0/#search/rfc822msgid:

followed by the message ID (can be found by looking at "show original").
See this question for some more details.

A: Gmail Sharable Link Creator
Site Link: GmailLink.GitHub.io
Steps to Follow to generate the Link

*

*Get the Message ID Of Mail Thread (Mail > 3 dot menu in Right side (⋮) > Click on Show Original > See the MessageID).

*Copy the Message-Id

*Use the MessageId & click On Submit to generate the Mail Sharable Link.
https://stackoverflow.com/a/61849710/7950511

A: You can specify the inbox email address in the link to open the email in the correct inbox.
if INBOX@EMAIL.COM is your inbox email
Create the link as follows
https://mail.google.com/mail/u/INBOX@EMAIL.COM/#all/YOUR_EMAIL_ID

A: You can open up an email that you want in Gmail and after that, you can simply copy the link location from the search bar of your browser. It will create a unique weblink for every single email. It is as simple as that.

A: You just have to click on "show original" and copy the URL.

A: Actyally, get a single email link, without the full thread, seems not to be directly supported;
apart from manual url rewriting or coding tricks, that require time or specific skills, the faster workarounds I know are:
Copy the URL from the tab that opens clicking on one of these 2 entry on the email menu:

*

*print - CONS: It also open the print popup, that you have to dismiss

*show original - CONS: The email is not formatted, you see original sources, so images and formatting are missed, and messy code are added

A: How about this Chrome Extension
https://chrome.google.com/webstore/detail/gmail-message-url/bkdmmijcdflpcjchjglegcipjiabagei/related


Q: C# Generics containing generics? T I got lost implementing a interface where I need TKey, TValue and TMessageListener
public interface IHelper<TKey, TValue, TMessageListener>

but my TMessageListener is TMessageListener<TValue> how can I declare this at the interface layer?

A: It could be achieved with type constraints as follows.
public interface IHelper<TKey,TValue,TMsgLst> where TMsgLst : TMessageListener<TValue>


Q: Restart service from bash script I'm trying to restart a service myservice from a service that is run as a daemon.
I've created a file called myapprestart in /etc/sudoers.d/
that looks like this
%myuser ALL=NOPASSWD: /bin/systemctl restart myservice
%myuser ALL=NOPASSWD: /bin/systemctl start myservice
%myuser ALL=NOPASSWD: /bin/systemctl stop myservice

The myapprestart.service daemon is running successfully as a timed unit that calls /home/myuser/restart.sh but always fails with the following line in journalctl
failed to stop myservice.service: Interactive authentication required.

the script file/home/myuser/restart.sh contains lines like below
systemctl stop myservice
systemctl start myservice

I need some pointers on what i'm not doing right. I've looked at at least four similar questions, but for some reason this case seems not to work. I'm using ubuntu 19.02.

A: Your script restart.sh use the systemctl command, which is part of systemd; because this command needs root rights due to his role, you need to use the sudo command to be able to use it (and your user must be refered in sudoers as an authorized sudo user). Your command would be like below :
sudo /home/myuser/restart.sh

*

*/home/myuser/restart.sh is just the absolute path to start the script, which is the same thing as doing sudo ./restart.sh inside /home/myuser/ folder

Also, as OP mentionned it in comment, you can also call sudo with absolute path with /usr/bin/sudo (/usr/bin/sudo apt update is the same as sudo apt update)


Q: Modificar enlace tomando texto de la propia URL generada por tipeo libre Tengo una inquietud, sobre algo que necesito disponer para difusión.
Si alguien me puede ayudar le agradezco. Estuve revisando las preguntas y lo que mayoritariamente encontré es a la inversa, que es generar enlaces con variables.
En este caso el  enlace que estaría en el cuerpo se completa con el texto libre escrito en la URL.
La URL es así
http://miweb.com/?h=

y el enlace a completar es
y todo lo que se escriba despues del = en la URL se completa igual después del = en el enlace, al actualizar.
Como ejemplo si me dirijo a esta URL
 http://miweb.com/?h=Juan

El enlace se completa así

Muchas gracias
Asi anduvo bien. Gracias
    Link

A: Por que no lo haces asi?
Una funcion que tenga la url base y un input para completarla.

function redirectTo() {
    const url = "http://miweb.com/?h=";
    let param = document.getElementById('completar_url').value;
    window.location.href = url + param;
}
<input id="completar_url" type="text" />
<button>
    pulsa aqui
</button>


Q: Contact cursor returning duplicate rows My application requires contacts to integrate. I am writing a query to get the contacts from the native. I get all the rows but with the duplicate rows. Duplicate are coming if Whatsapp, skype and other accounts are linked.
Below is the query
String isPhoneType = "(" + Data.MIMETYPE + "='" + CommonDataKinds.Phone.CONTENT_ITEM_TYPE
            + "' AND " + CommonDataKinds.Phone.NUMBER + " IS NOT NULL ) ";

    String query = Contacts.DISPLAY_NAME + " IS NOT NULL "
            + " AND (" + isPhoneType + ")" ;

    String[] projection;
    if (Compatibility.isCompatible(11)) {
        projection = new String[] {
                Data._ID,
                Data.CONTACT_ID,
                Data.DATA1,
                Data.DISPLAY_NAME,
                Data.PHOTO_ID,
                Data.LOOKUP_KEY,
                Data.PHOTO_URI
        };
    } else {
        projection = new String[] {
                Data._ID,
                Data.CONTACT_ID,
                Data.DATA1,
                Data.DISPLAY_NAME,
                Data.PHOTO_ID,
                Data.LOOKUP_KEY
        };
    }

    Cursor resCursor = ctxt.getContentResolver().query(uri,
            projection, query,
            null, Data.DISPLAY_NAME + " ASC");

Please help in getting the unique rows based on the phone numbers.
Thanks

A: Add unique to phone number column in sqlite database and you will not get same contact twice.
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT UNIQUE," + KEY_IMAGE + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}


Q: Using overriden function in base class constructor for derived class I'm very new to C++ programming so I wanted to write some simple code to get used to the syntax. I have deliberately ignored pointers and references for the moment.
During coding, I was practising inheritance and I wanted to create a class Hand which represents a hand of cards. The base class has a function called update(), which is used to initialize the "total" and "notation" properties upon construction. Moreover it is possible to add cards to the hand using the add() function which adds a card to the hand and triggers update() to update the properties appropriately.
#include<vector>

class Hand
{
public:
    std::vector<int> cards;
    int total;
    std::string notation; // Abbreviated notation of the object
    // Constructor
    Hand(std::vector<int> cards);
    void update();
    void add(int card);
}

Hand::Hand(std::vector<int> cards)
{
    this->cards = cards;
    update();
}

void Hand::update()
{
    total = 0;
    notation += "{ ";
    for (int card: cards)
    {
        total += card;
        notation += std::to_string(card) + " ";
    }
    notation += "}";
}

void Hand::add(int card)
{
    cards.push_back(card);
    update();
}

Next, I wanted to create a more specific class of Hand called StandHand, which does all the same things as Hand but it also has a variable that changes when the total reaches a particular value.
Initially I thought I could just write the subclass as shown below, but alas.
class StandHand : public Hand
{
public:
    int stand;
    StandHand(std::vector<int> cards, int stand);
    void update();
}

StandHand::StandHand(std::vector<int> cards, int stand) : Hand(cards)
{
    this->stand = stand;
    updateHand();
}

void StandHand::update()
{
    Hand::update();
    notation += stand <= total ? " (stand)" : "";
}

But when I invoke the add() method on a StandHand object, it does not use the StandHand::update() method, rather it uses the base update() method. How can I make sure that the add() method, when used in a subclass of Hand, uses the update() function of that subclass?

A: For starters in the code there is no overloaded functions. The declaration of update in the derived class hides the declaration of the function with the same name in the base class.
As the member function add is declared in the base class then the name of the function update also is searched in the base class.
Declare the function update as a virtual function.
class Hand
{
public:
    // ...
    virtual void update();
};

class StandHand : public Hand
{
public:
    // ///
    void update() override;
};

A: There are two issues in your code, first void update(); in the base class needs to be declared virtual, so that compiler will know that derived classes might override it and use it.
virtual void update();
// add "=0;" if there is no base version of update()

And in the derived class write
void update() override;
//override is unnecessary but recommended
//it verifies that you do indeed overload a method from a base class

Second problem, you cannot call methods from derived class in constructor of its base class. What happens is that calling virtual base method results in calling the base version instead of the derived version. Think of it: the derived object isn't constructed yet but you already call one of its methods? It doesn't make any sense.


Q: Google Foobar challenge "Find the access codes" SOLVED
I was sorting the list when in reality the prompt was asking for the order in which the numbers were given. Not going to delete the post in case someone else makes the same mistake.
I would like to preface this by saying that I have already read over other answers to this conundrum, but to no avail. I even tried copying the provided solutions, just to see if they actually worked, and they failed more test cases than the code I used.
Original Prompt

"Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (li, lj, lk) where the list indices meet the requirement i < j < k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits within a signed 32-bit integer. Some of the lists are purposely generated without any access codes to throw off spies, so if no triples are found, return 0.
A "lucky triple" is a tuple (x, y, z) where x divides y and y divides z, such as (1, 2, 4).
For example, [1, 2, 3, 4, 5, 6] has the triples: [1, 2, 4], [1, 2, 6], [1, 3, 6], making the answer 3 total."

At this point, I'm not even asking for a solution so I can pass to the next level, because I would feel that I am cheating at that point, however, I have no idea why I am failing test cases 3-5 (and obviously the test cases aren't publicly available, but I'm just asking if anyone can find flaws in my programming).
Like I'm sure most people did, I began by creating a triple for-loop that iterated over every possible "triple," but seeing as it was O(n^3), it took too long. I am, however, using that as a "base solution" for my code to compare answers to more complicated cases.
My code (in python)
I apologize if the code is a bit messy, but I am new to python, and mainly did this challenge for the learning opportunity, and just to work my brain.
The function takes a list, l, and then I sort it into descending order. I then create a list which I initialize all values to 0. For the first while-loop set, I am counting the amount of "doubles" where l[y] divides l[x] evenly, then count the amount of factors that l[x] has. I.e if there were a list [1,2,3,4] then this loop checks [3%2] , [3%1], [2%1].
The next while-loop set checks the first 2 numbers ([4%3] , [4%2] , [3%2]). Both of these loops are verified in my (local) code with print statements, and those are the operations occurring. If the mod in the second while set is true, then it increments the counter by the amount of factors that the 'Y' value had (in this case, only [4%2] is true and then it would go to the l_count list and increment the count variable by the value in the array that corresponds to 2. In this case, it is 1, because the only true case for the number "2" in the first while loop is [2%1]). I would have included comments in my code, but I did not think I would be having this issue in the first place.
Anyway, any help would be greatly appreciated! Thanks
l.sort()
l = l[::-1]

length = len(l)

count = 0

l_count = []
for x in range(len(l)):
    l_count.append(0)

x = 1
while x < (length - 1):
    y = x + 1
    while y < length:
        if l[x] % l[y] == 0:
            l_count[x] = l_count[x] + 1
        y = y + 1
    x = x + 1

x = 0
while x < (length - 2):
    y = x + 1
    while y < (length - 1):
        if l[x] % l[y] == 0:
            count = count + l_count[y]
        y = y + 1
    x = x + 1

return count

A: The first thing you do is already a mistake: Sorting. That'll make you report that [6, 5, 4, 3, 2, 1] has three such triples (same as the example) when in reality it doesn't have any.
(Given that you pass two of five tests, I can imagine this is your only mistake. Maybe those tests are already sorted so you're not messing those up.)


Q: Difference between a data warehouse and a MOLAP server What is the difference between a data warehouse and a MOLAP server?
Is the data stored at both the data warehouse and on the MOLAP server?
When you pose a query, do you send it to the data warehouse or the MOLAP server?
With ROLAP, it kind of makes sense that the ROLAP server pose SQL queries to the data warehouse (which store fact and dimension tables), and then do the analysis. However, I have read somewhere that ROLAP gathers its data directly from the operational database (OLTP), but then, where/when is the data warehouse used?

A: The 'MOLAP' flavour of OLAP (as distinguished from 'ROLAP') is a data store in its own right, separate from the Data Warehouse.
Usually, the MOLAP server gets its data from the Data Warehouse on a regular basis. So the data does indeed reside in both.
The difference is that a MOLAP server is a specific kind of database (cube) that precalculates totals at levels in hierarchies, and furthermore structures the data to be even easier for users to query and navigate than a data warehouse (with the right tools at their disposal).
Although a data warehouse may be dimensionally modelled, it is still often stored in a relational data model in an RDBMS.
Hence MOLAP cubes (or other modern alternatives) provide both performance gains and a 'semantic layer' that makes it easier to understand data stored in a data warehouse.
The user can then query the MOLAP server rather than the Data Warehouse. That doesn't stop users querying the Data Warehouse directly, if that's what your solution needs.
You're right that when the user queries a ROLAP server, it passes on the queries to the underlying database, which may be an OLTP system, but is more often going to be a data warehouse, because those are designed for reporting and query performance and understandability in mind. ROLAP therefore provides the user-friendly 'semantic layer' but relies on the performance of the data warehouse for speed of queries.


Q: ConcatRelated function and the fifth argument I'm trying to achieve the following:
If you have:
ItemNo   DocumentNo    Quantity
AB1         WS1           10
AB1         WS2           10

I want:
 ItemNo   DocumentNo    Quantity
AB1         WS1 | WS2          10

I'm not quite understanding how to use the fifth argument. I continue to get errors, stating that "|" is not valid.
Here's the code.
SELECT DISTINCT Query3.ItemNo,  ConcatRelated("Query3.DocumentNo", "Query3", "Query3.ItemNo = " & [Query3.ItemNo] & " | " )
FROM Query3;

Here's the website:
http://allenbrowne.com/func-concat.html

A: I can't tell, but my DJoin function found here and this query:
SELECT
    ItemNo,
    DJoin("[DocumentNo]","[Query3]","[ItemNo] = '" & [ItemNo] & "'"," | ") AS DocumentNos,
    Quantity
FROM
    Query3
GROUP BY
    ItemNo,
    Quantity
HAVING
    Count(*) >=2;

will provide this output:


Q: Assigning to slices of 2D NumPy array I want to assign 0 to different length slices of a 2d array.
Example:
import numpy as np

arr = np.array([[1,2,3,4],
                [1,2,3,4],
                [1,2,3,4],
                [1,2,3,4]])

idxs = np.array([0,1,2,0])

Given the above array arr and indices idxs how can you assign to different length slices. Such that the result is:
arr = np.array([[0,2,3,4],
                [0,0,3,4],
                [0,0,0,4],
                [0,2,3,4]])

These don't work
slices = np.array([np.arange(i) for i in idxs])
arr[slices] = 0

arr[:, :idxs] = 0

A: You can use broadcasted comparison to generate a mask, and index into arr accordingly:
arr[np.arange(arr.shape[1]) <= idxs[:, None]] = 0

print(arr)
array([[0, 2, 3, 4],
       [0, 0, 3, 4],
       [0, 0, 0, 4],
       [0, 2, 3, 4]])

A: This does the trick:
import numpy as np

arr = np.array([[1,2,3,4],
               [1,2,3,4],
               [1,2,3,4],
               [1,2,3,4]])
idxs = [0,1,2,0]
for i,j in zip(range(arr.shape[0]),idxs):
  arr[i,:j+1]=0

A: Here is a sparse solution that may be useful in cases where only a small fraction of places should be zeroed out:
>>> idx = idxs+1
>>> I = idx.cumsum()
>>> cidx = np.ones((I[-1],), int)
>>> cidx[0] = 0
>>> cidx[I[:-1]]-=idx[:-1]
>>> cidx=np.cumsum(cidx)
>>> ridx = np.repeat(np.arange(idx.size), idx)
>>> arr[ridx, cidx]=0
>>> arr
array([[0, 2, 3, 4],
       [0, 0, 3, 4],
       [0, 0, 0, 4],
       [0, 2, 3, 4]])

Explanation: We need to construct the coordinates of the positions we want to put zeros in.
The row indices are easy: we just need to go from 0 to 3 repeating each number to fill the corresponding slice.
The column indices start at zero and most of the time are incremented by 1. So to construct them we use cumsum on mostly ones. Only at the start of each new row we have to reset. We do that by subtracting the length of the corresponding slice such as to cancel the ones we have summed in that row.

A: import numpy as np

arr = np.array([[1, 2, 3, 4],
                [1, 2, 3, 4],
                [1, 2, 3, 4],
                [1, 2, 3, 4]])

idxs = np.array([0, 1, 2, 0])

for i, idx in enumerate(idxs):
    arr[i,:idx+1] = 0


Q: alternatives for website accesibility testing Any suggestions for free tools to test website accessibility (508+). We used to use http://wsspg.dequecloud.com/worldspace/wsservice/eval/checkCompliance.jsp for this purpose and this site is no longer available.

A: Try Google Accessibility Developer Tools Extension for Chrome. It runs an accessibility audit on individual pages, making assertions based on WCAG 2.0.
If you have a Rails project, you can run the assertions from the Google Extension as part of an Rspec integration test suite using capybara-accessible, a rubygem that defines a Selenium based webdriver for Capybara and makes accessibility assertions on page loads. That way you can automate testing across your site and also get failures in CI.

A: Try Wave, which is free to use. But not sure if it has full functionality. Check it out yourself and let me know if its the right one for you.

A: As Felipe said, no automated testing should be relied upon. Specifically if you need to test for Section 508, it states that you have to test with AT. WAVE and Deque WorldSpace does not satisfy this requirement. WAVE is a fine tool to catch low hanging fruit. Maybe the Google Plug-in does as well, but would not rely upon it due to how Chrome handles and reports things to MSAA and other APIs.
I have heard numbers thrown around how well automated testers are. Personally, I set them around the 50% mark, particially due to the "full functionality" aspect that Felipe mentions in Mohammad's answer. In terms of Section 508, this phrase is called "equivalent facilitation", which is covered in 1194.31, which no automated tester can cover. Subpart 1194.31 is the functional standards, which apply to all activities if Section 508 is applicable. The same goes with 1194.41.
FelipeAls said:

[Section 508] outdated and W3C/WAI WCAG 2.0 is a way better resource for improving accessibility nowadays (but of course if you must be compliant with 508, then also test for 508)

While I will say Section 508 is rough around the edges, I wouldn't say it is useless as some market it as. In my experience people pushing this, have limited experience actually dealing with Section 508, or they work behind a product that does testing. Their biggest arguement is usually "heh look, if Section 508 is so good, why doesn't it require headings (<h1>)?" Well, Section 508 was derived from WCAG 1.0, which didn't have it either, so that argument is weak in my opinion. Also, remember how I said people don't realise that 1194.31 is applicable? Let's look at 1194.31(a):

(a) At least one mode of operation and information retrieval that does not require user vision shall be provided, or support for assistive technology used by people who are blind or visually impaired shall be provided.

You can read that as: code a page so that AT can find specific parts of/on a page. What's a good way to allow people to jump around? Headings, and now WAI-ARIA Landmarks.
Section 508 is also being worked on to adopt WCAG 2.0.