text:
Q: Can't refresh source for DataGridView I know this question was asked million times but I used lots of advices from there and it still doesn't work for me. Here is my try :
    private void Apply_Click(object sender, EventArgs e)
    {
        Form addIncForm = DataProcessing.newIncident(Incident.Text);
        addIncForm.FormClosed += (s, ex) =>
        {
            this.inciView.DataSource = null;
            this.inciView.DataSource = this.incidentBindingSource;
            this.inciView.Invalidate();
            this.inciView.Refresh();
            this.inciView.Parent.Refresh();
        };
        addIncForm.Show();
    }

Only when I close and open "this" form I can see the changes of inciView. Why this hard refresh (noone of the methods) doesn't work ? and how to refresh it so ?
I think I must force update DataSet somehow .

A: There are two approaches which will work:

*

*Make the form you use to edit your data modal by using ShowDialog() to open it. After the call to ShowDialog() add code to requery and rebind your DataGridView to its data source.

*Add an event to your data entry form that informs listeners that your database has been updated.  The form that opens your data entry form subscribes to this event and in the code that runs when the event fires requery and rebind your DGV.
When I say requery and rebind your DGV I mean do whatever you're doing now to load data into your DGV (i.e. querying your database and setting a DataSource).
In the first approach displaying the data entry form modally will effectively stop execution of your main form until the user is done with the data entry form.  You can also have your data entry form return a DialogResult indicating whether or not the user made any change as opposed to cancelling out.  If so (say DialogResult.OK was returned by the data entry form) you can run your DGV refresh code.
In the second approach you're having your data entry form tell users that the data has been updated.

A: with the assumption that the Control has been bound to a database
this might help,
From the DataSet Designer :

*

*right-click TableAdapter, and choose "Configure..."

*press next, make sure "Fill a DataTable" is checked

*press next/Finish.

in your code add:
myDataSet.AcceptChanges();
myBindingSource.EndEdit();
myTableAdapter.Fill(myDataSet.Table1);

The bound control is refreshed automagically.
The first 2 statements may be redundant but it works for me.
:)


text:
Q: Should you strip data down to the most basic type, or is it ok to pass control-related objects via MVC? I'm pretty new to the MVC pattern; I understand it on a most basic level and I'm trying to get better with it.
That said, I have a form with a DataGridView with a single Column ("path") on it and a button that will try to start a process based on the contents of my grid.
I was unsure if my View should send my DataGridViewRowCollection to the Controller, or if I should strip out just the text values from my single column and pass that to the controller?
Basically, should it be this:
    private void Launch()
    {
        _controller.Launch(dataGridView.Rows);
    }

    public void Launch(DataGridRowCollection rows)
    {
        //iterate over collection
        //process.start(row.Cells[0].Value.ToString())
    }

Or would this be more appropriate:
    private void Launch()
    {
        List<string> process = new List<string();
        //iterate over collection
        //add cell value to List
        //pass List to Controller
    }

    public void Launch(List<string> processes)
    {
        //iterate over collection
        //process.start(row.Cells[0].Value.ToString())
    }

I'm conflicted because I want to remove as much work as possible from the View (the former), but to my understanding the Controller should absolutely not interact with any UI elements (the latter).
I hope there is an actual 'Best Practice' and this isn't too much a question of preference

A: Passing view specific infrastructure classes to controllers is against the architecture. One of the major points is that you would like to test controllers without views. And in the approach where you require view specific classes, this could be tricky if not impossible.
Pass simple types or compound types consisting of simple types. The latter version is more appropriate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What can be the value of the determinant of $A$? Suppose that the $ 3 × 3 $ matrix $A$ has an inverse and each entry of both $A$ and $A^{-1}$
is an integer. What can be the value of the determinant of $A$ ?
I did not understand that what it means that both $A$ and $A^{−1}$
have each entry an integer?

A: I think that's meant to be $A^{-1}$, not $A-1$.  That is, all entries of both the matrix and its inverse are integers.
Hint: the determinant of a matrix of integers is an integer.


text:
Q: What's the difference between Lazy.Force() and Lazy.Value On the MSDN documentation for Lazy.Force<T> extension method says:

Forces the execution of this value and returns its result. Same as
  Value. Mutual exclusion is used to prevent other threads from also
  computing the value.

Does it mean that it's equivalent to creating a Lazy<T> instance with ExecutionAndPublication LazyThreadSafetyMode so that only one thread can initialize the instance?
Thanks

A: Yes. They are both the same, and both make sure that the value will be computed only once.

A: It's a bit strange that the method exists and is not a function - it's not composable and replicates the behavior of .Value.
I would define something like the following (as seen in the F# compiler):
module Lazy =
    // Lazy.force : Lazy<'T> -> 'T
    let force (x: Lazy<'T>) = x.Force()


text:
Q: How to apply a MongoDB MapReduce? I have the follow SQL sentence and I run It a couple of time by day.
INSERT INTO `gas_prices`
    ( `code` , `date` , `lon` , `lat` , `desc` , `price` ) VALUES
    ('$tCode', '$tDate', $tlon, $tlat, '$tdes', $tprice);

I insert 37 records by day, so now, two years ago, the database became so big.
The select sql sentence is this:
SELECT code, date, lon, lat, desc, price FROM `gas_prices`
 where (date, code) in
  (SELECT Max( date ) date, code FROM `gas_prices` GROUP BY code)
 order by lat, lon, code desc;

This SQL sentence spend a long time to return data, for this reason I decided to created a cache system in order to return the data more fast.
Right now I have the opportunity to change the database server by another, I like mongoDB, but I would like to know, How can I apply a mapreduce for my system in mongoDB?


text:
Q: Javascript add MySQL data when checkbox is ticked I am currently using this javscript and PHP code

<form name="form2">

    Total: <input type="text" name="thetotal" id="thetotal" size="20" value="0" />
    VAT:

    Invoice Number
    Company
    Date
    Total

</form>

<form name="form1">

<?php
$sql="SELECT * from billing_pdf_archive order by invoice_number ASC ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
    $counter++;
    $sql2="SELECT * from customer where sequence = '".$result["customer_sequence"]."' ";
    $rs2=mysql_query($sql2,$conn) or die(mysql_error());
    $result2=mysql_fetch_array($rs2);

    $sql3="SELECT * from reseller where sequence = '".$result["reseller_sequence"]."' ";
    $rs3=mysql_query($sql3,$conn) or die(mysql_error());
    $result3=mysql_fetch_array($rs3);

    if($result["customer_sequence"] != '0')
    {
        $company = $result2["company"];
    }
    elseif($result["reseller_sequence"] != '0')
    {
        $company = 'Reseller: '.$result3["company"];
    }

    $total = $result["total"];

    echo '

    <input type="checkbox" name="check" id="check" onclick=\'add('.$total.');\' />
    '.$result["invoice_number"].'
    '.$company.'
    '.$result["datetime"].'
    £'.$result["total"].'

';
}
?>

</form>

so as you can see it is selecting from the MySQL database and i am trying to make it so when one of the checkboxes is ticked it adds the total into the "thetotal" text field (in form 2) but it is just leaving that box as zero - any ideas on what i could do?

A: Here is how you can do it (assuming total is int and not float):

.
in your php, you have to send the checkbox like this:
onclick=\'add('.$total.', this);\'
.

A: You did not specify the total field for form 1, then it raised javascript error, it wont work.
Check it out

            <form name="form1">

            <input type="text" name="formtotal" id="formtotal" value="10" />
            </form>


text:
Q: AWS-Device farm Uses TestNG Framework Regardless of selecting Appium Java Junit for Testing I'm working with AWS-Device Farm and I followed the steps specified to run my test package, I have selected Test Configuration Appium Java Junit But All of my test cases failed. So After looking at popup messages displayed along with error messages I notice that AWS Runs My test cases by converting my junit test cases to TestNG. How to overcome this issue please suggest some solution.

A: In Device Farm's custom environment, it's possible now to change the command to start the test. A java JUnit command can be used the testspec file in theory to run the java tests using JUnit instead of TestNG.
I found these commands(not tested) which could replace the TestNG command.


text:
Q: Perl Log4perl Printing and logging at the same time in a line I'm reading this and I am confused and stuck.
Should I use ALWAYS or print_portfolio('themessage') to both print and log into a file at the same time?
What I want to do:
if ($logfile) {
   open (FILE, '>>', "logfile");
   print "Hello" #some code from Log4perl#;
   #prints on the display and into the logfile
}

instead of:
if ($logfile) { open (FILE, '>>', "logfile"); }
print "Hello";
if ($logfile) { print FILE "Hello"; }

A: You use neither.

*

*ALWAYS is a log level that will always print regardless of the logging level selected. Logging levels are a way of controlling how much information is logged by the logger based on the level selected

*The print_portfolio subroutine is an example that doesn't really have much to do with logging to screen and file at the same time.
I believe the Advanced configuration within Perl section has a clear example on how to set up the logger to print to screen and file at the same time:

Here's an example on how to configure two appenders with the same
  layout in Perl, without using a configuration file at all:
########################
# Initialization section
########################
use Log::Log4perl;
use Log::Log4perl::Layout;
use Log::Log4perl::Level;

   # Define a category logger
my $log = Log::Log4perl->get_logger("Foo::Bar");

   # Define a layout
my $layout = Log::Log4perl::Layout::PatternLayout->new("[%r] %F %L %m%n");

   # Define a file appender
my $file_appender = Log::Log4perl::Appender->new(
                        "Log::Log4perl::Appender::File",
                        name      => "filelog",
                        filename  => "/tmp/my.log");

   # Define a stdout appender
my $stdout_appender =  Log::Log4perl::Appender->new(
                        "Log::Log4perl::Appender::Screen",
                        name      => "screenlog",
                        stderr    => 0);

   # Have both appenders use the same layout (could be different)
$stdout_appender->layout($layout);
$file_appender->layout($layout);

$log->add_appender($stdout_appender);
$log->add_appender($file_appender);
$log->level($INFO);


text:
Q: Can Quantum Entanglement Be Achieved Between a Particle and Existing Particles That Are Quantum Entangled? As the above title mentions, is it theoretically possible for a particle to achieve quantum entanglement with an existing set of particles that are already entangled? I did try searching for a possible answer to this online already, but did not find any articles that go over this specific scenario so I'd like to know what is currently theorized.

A: Imagine a particle is decayed into 2 particles (let's say A and B). Then these 2 are entangled with each other. So, if you measure one particle's momentum you can tell the momentum of the other as well.
Now imagine C comes and collides with B. If you now measure the momentum of A you cannot tell about B's current momentum because of the collision. But you can still find the combined B and C momentum. So C is not just entangled with B, but also A. That is, C came and entangled with the A and B entangled system.

A: It is good to go to the basics of the definition of entanglement, which is the mathematics of quantum mechanics. If one has a complete quantum mechanical solution ( hard for many particles) for a system of particles, than these particles are entangled, because the solution is known and the spin orientations ( for the use of entanglement in the computing form)are known and depend on each other.
The answer to

is it theoretically possible for a particle to achieve quantum entanglement with an existing set of particles that are already entangled

depends on the word  "achieve". If you mean that if you add a particle to the problem can the particles be entangled with the new particle, the answer is yes, because a new quantum mechanical wave function will describe the addition and there will be spin orientations. If you mean will the particles have the same spin orientation they had before the intrusion the answer is "probably not" as the momenta and energies introduced by the new particle may change the orientation of the spins to each  other particle, depending on the values of the input energy. Quantum  mechanics is a probabilistic theory.


text:
Q: array_push mysqli $row return the same data I have a data base return array as such
$row['id']=1, $row['col1']='col1', $row['col2']=col2

when i push each $row to $result
array_push($result, $row);

the $row is overwritten b/c they share the same key. I can't get my mind around it.  but if it is overwritten, when I var_dump($result) it should output only one set, instead it output multiple row with the same set of data, please help.

A: replace this: array_push($result, $row);
with this:
foreach($row AS $current_row)
{
   array_push($result, $current_row);
}

A: I'm not sure to understand.
If you want to add $row in $result, you can use array_merge() function like this:
$result = array_merge($result, $row);

A: array_push adds elements to 2 or more dimension array. Before using it you must define an array. Use this:
$result = array();
while ($row = $stmt->fetch())
{
   array_push($result, $row);
}


text:
Q: Extending leaflet SVG renderer fails to show vector layers I am working on modifying the Leaflet SVG renderer for some cosmetic changes, but I have not been able to get even the most basic extension to work (even without any custom code aside from changing things like create() to L.DomUtil.create()).
here is my most simple example setup:
<!DOCTYPE html>

   <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>

It does not throw any errors in the console and I really don't know where to go from here.
Inspecting the dom shows that the layers exist in the svg tag and that they have coordinates, but the g element does not seem to have any height.
what am I doing wrong?


text:
Q: Xposed : How to hook a method of a nested class(inner class) in xposed framework. I am trying to hook a method using:
 findAndHookMethod("com.android.keyguard.KeyguardPatternView.UnlockPatternListener", lpparam.classLoader, "onPatternDetected", new XC_MethodHook()

Where UnlockPatternListener is a nested class(inner class) and it has a method called onPatternDetected.
The inner class is private.
I am unable to hook this method. Can you tell me the way to do it?

A: Should work this way
 findAndHookMethod("com.android.keyguard.KeyguardPatternView$UnlockPatternListener", lpparam.classLoader, "onPatternDetected", new XC_MethodHook()
                                                            ^


text:
Q: How to install Boot Camp from content of previously created flash storage? I've installed Windows 7 SP1 via Boot Camp before and kept the content of  the SD card that I created during the process. I want to know how I can copy that content to another SD card and install off of it again.
Probably I have to do some things manually like making the flash storage bootable and/or creating a FAT32 partition from Disk Utility.
(And no, I can't download Boot Camp due to my very limited internet connection)
My rig: OS X Yosemite (10.10.3)

A: Boot Camp Assistant is already in Applications > Utilities. It doesn't need to be downloaded.
If the card was good enough to install Windows from last time, it ought to be good enough to do it again.


text:
Q: jquery: How to enable clicks in a zone of the page (disabling rest) I would like to do a tutorial in a page, so my idea is to create some kind of "mask" that disable all the page and enable just a "invisible" box, where things (links and other stuff of the page) works.
It's like a "ozone hole" where links and stuff works, but if you click anywhere else on the page, the click is "captured" and do nothing.
jQuery(".tutorial_holes").click(function(){
     xxxxx
});
jQuery(document).click( function() { return false; } });

I'm starting working with this ... but I do not know what to put in "xxxx" to tell it "leave this area working".
Also I tried with a 100% overlay with z-index:10000 , and above it (z-index:10001) create the "hole" ... but I do not either how to tell javascript to allow clicks in this area of the belowest original page ...
I hope I explained myself :)
Solutions like dialog or adding "disable" classes to elements will not work:
a) Dialog creates a box over the page in which you can "play" ... what I want is exactly the opposite, create a box IN THE PAGE where you can play, disabling the rest
b) Adding "#disable" or similar solutions to elements to disable them after is crazy. I have tons of other jquery plugins and behaviours. I'd need to modify a lot each page. What I need is a non-intrusive solution "over" all my code
Any ideas ?

A: Use event.preventDefault() , here is an example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

   foo
   <form action="http://www.example.com">
        <input type="submit" value="" name="" />
   </form>

A: You can use jQuery dialog plugin comes in jQueryUI which is the easiest and fastest way to achieve the feature which you need. Check it out.

http://jqueryui.com/demos/dialog/

A: While you've hopefully found your own solution to this in the years since it was asked, I'm throwing in an appropriate answer since I had a similar problem that needed solving.
There are essentially two different ways of solving this which meet your criteria (which happened to be mine as well!). Both of these are flexible to element types (they work on more than just  elements).
(for both of these solutions, assume that the class working-links is being applied to any container elements you wish to have functional linking inside of. Keep in mind that while both of these examples are based off of using document as the target container for preventing links from working, it would usually make more sense to have the target be something more refined, like whatever wraps the main content region of the page)

The first is to disable all default click actions on the document, and then (essentially) re-enable them on an appropriate container.
How this works in practice is that an event handler is applied to the document object itself (or any element containing everything that needs to be prevented—which would be best so that site menus/etc still work with no changes needed). Events bubble upwards: you don't need an event handler on every link, you just need one on the document to intercept any clicks on links.
We can take advantage of this behavior to attach another event handler on any containers we want clicks to work within (say, one with a class of working-links) which prevents the click event from propagating up to the handler attached to the document object.
$(document).on("click", function(event) {
  event.preventDefault();
});

$(".working-links").on("click", function(event) {
  event.stopPropagation();
});

Example with accompanying HTML on codepen.io
Note that I've provided these using on() instead of click() because it allows for easily changing these to being delegated events if you are targeting something other than the entire document and may have more targeted regions inserted dynamically (AJAX/etc). This only matters if you chose to bind the event more selectively: at the document level, any changes inside it don't matter and will still be captured by the event binding, since they'll still bubble up properly.
This may matter more for the working-links event: you will need to change that appropriately to add a selector in on() if you are dynamically adding more to the page after this is bound.
If you tried attaching a handler and then selectively removing it from an appropriately classed item, or if you tried attaching a handler only to elements that did not have a class (using the CSS selector :not or by restricting the jquery selection using .not()) this bubbling behavior is why it did not work. Even if you don't attach the event.preventDefault() to the links or their container, if it attaches to any of their ancestors it will bubble to them and the action will still be prevented.

The other method is to apply a click event handler to the document/main container element, and then apply logic dependent on the event.target.
This one is pretty straightforward, but possibly not as elegant.
We're going to simply capture all click events at the document (or whatever container you choose to target) and figure out if the event.target is wrapped within one of our excluding elements. The easiest way to do this is probably to use jquery's is() function.
One thing to keep in mind is that you will need to check not only if the event.target is within the element set matched by the class selector, but also all children of the class selector: otherwise any  elements nested beyond the immediate children will fail to work.
$(document).on("click", function(event) {

  if (! $(event.target).is($(".working-links, .working-links *").children())) {
    event.preventDefault();
  }

});

Example with accompanying HTML on codepen.io
On the plus side, this method does not require any changes in order to function within a dynamic page, at least for the addition of working-links classed elements. If you're adding more of the non-click containers, it will obviously need to be adapted appropriately to make the on() call use delegation mode (see the appropriate jQuery documentation on event binding).
On the down side, this is going to use a bit more resources for the event handler (in order to calculate the jQuery element set each time it runs) than the other method. We probably don't care in most circumstances, but it's not a bad thing to be aware of.


text:
Q: $x^2+3x+3$ is irreducible in $\mathbb{F}_{25}[x]$
Give an example of an irreducible non-linear polynomial in $\mathbb{F}_{25}[x]$.

I know that $x^2+3x+3$ is irreducible in $\mathbb{F}_{25}[x]$ but I know no shorter proof then the exhaustive search (since $\mathbb{F}_{25}[x]$ is not a factorial ring we cannot use Eisenstein's criterion).
Can you please help me to find a more elegant idea?

A: The polynomial you're trying with is reducible, as others have already pointed out. Degree two polynomials with coefficients in $\mathbb{F}_5$ don't work: they're all reducible in $\mathbb{F}_{25}[x]$.
What about a cubic polynomial? It's easy to test whether it's irreducible over $\mathbb{F}_5[x]$: it just needs to have no root. So let' try the simplest one
$$
f(x)=x^3+x+1
$$
Then $f(0)=1$, $f(1)=3$, $f(2)=1$, $f(3)=1$, $f(4)=4$.
Can you see why this polynomial is also irreducible in $\mathbb{F}_{25}$?

A: Your suggested polynomial $f$ is irreducible in $\Bbb F_5[X]$. Therefore $\Bbb F_5[X]/(f)$ is a quadratic extension of $\Bbb F_5$, hence is already $\Bbb F_{25}$, and by construction $f$ has a root there.

A: The quadratic formula works very well in any non-characteristic-$2$ field. So the roots of your $x^2+3x+3$ are
$$
\frac{-3\pm \sqrt{3^2 - 4\cdot 1\cdot 3}}{2\cdot 1} = 1\pm3\sqrt2
$$
Since $\Bbb F_{25}$ is a quadratic extension of $\Bbb F_5$, it contains all the square roots of any element in $\Bbb F_5$. So $\sqrt 2$ actually exists in $\Bbb F_{25}$, and your polynomial has roots. In fact, we get that any quadratic polynomial over $\Bbb F_5$ has roots in $\Bbb F_{25}$. So in order to find irreducible quadratics, you need to use at least one of the twenty non-$\Bbb F_5$ elements of $\Bbb F_{25}$.
For instance, we could take $x^2 + \sqrt2$. There is no square root to $\sqrt2$ in $\Bbb F_{25}$ (proof below), so this is irreducible.

All elements in $\Bbb F_{25}$ may be written in a unique way as $a + b\sqrt2$, where $a, b\in \Bbb F_5$. If $\sqrt2$ has a square root in $\Bbb F_{25}$, then we have a solution to
  $$
(a + b\sqrt2)^2 = \sqrt2\\
a^2 + 2b^2 + 2ab\sqrt2 = \sqrt2\\
a^2 + 2b^2 = 0\quad\land\quad 2ab = 1
$$
  The only solution in $\Bbb F_5$ to $a^2 + 2b^2 = 0$ is $a = b = 0$, but that doesn't solve $2ab = 1$, so $\sqrt{\sqrt2}$ doesn't exist in $\Bbb F_{25}$.


text:
Q: Dynamically add table row when last row field clicked for the first time I want to have a table which dynamically adds a row when the last row in the table is clicked. Specifically I have a row which have 2 text boxes and I would like to add a new row whenever a user clicks into either box.
The aim is to provide a growing list which would then have the option to delete rows etc. (but not specifically needed for this question!)
In my head the logic would work along the lines of
if (either text box clicked && is last row) then
  addrow()

Table fiddle here:

      key
      value

          <input class="vert-align" type="checkbox" value="">

        <input class="form-control" id="paramKey01" type="text" aria-label="..." placeholder="key">

        <input class="form-control" id="paramVal01" type="text" aria-label="..." placeholder="value">

      <button type="submit">Delete</button>

An example of this functionality is if anyone uses 'postman' and the headers tab when building a request!

A: You should use .last() to catch your desired element, and then trig .appendTo() containing new field.

A: Add below scripts and add class delete to the delete button.
 $(document).on('click','tr:last-child input',function(){
   $(this).parents('tbody').append($(this).parents("tr").clone())
   $(this).parents('tr').find('input').val("");
 });

 $(document).on('click','.delete',function(){
   $(this).parents("tr").remove();
 });


text:
Q: If $F\subset G$ where $F$ is a closed set and $G$ is a open set, show that $m^*(G\backslash F)=m^*(G)-m^*(F)$. The exercise is:

If $F\subset G$ where $F$ is a closed set and $G$ is a open limited set, show that $m^*(G\backslash F)=m^*(G)-m^*(F)$.

I try solve this:
If $G=F\dot{\cup}(G\backslash F)$, where $A\dot{\cup}B$ denotes the disjoint union of $A$ and $B$. Then, $m^*(G)=m^*(F)+G=m^*(G\backslash F)$ because $F$ and $F\backslash G$ are a disjoint union. This solve the exercise.
However the hint given is not that way and I was unsure of solve this way.
The hint:

Apply that for each meansurable open limited set $G\backslash F$ and for each $\varepsilon>0$, there is a closed set $F_1$ that $F_1\subset (F\backslash G)$ such that $m^*(F_1)>m^*(G\backslash F)-\varepsilon$(I proved this result in the exercise before that). Show that
  $$
m^*(F)+m^*(G\backslash F)<m^*(F)+m^*(F_1)+\varepsilon=m^*(F\cup F_1)+\varepsilon
$$

I would like to know how to use this tip and my resolution is wrong.

A: Your solution is correct but assumes measurability of $G$ and $F$. The hint avoids this.
Since $F \cup F_1 \subset G$, the hint leads to $m^*(F) + m^*(G \setminus F) < m^*(G) + \epsilon$. Since $\epsilon > 0$ is arbitrary this implies $m^*(F) + m^*(G \setminus F) \le m^*(G)$.
The reverse inequality is a trivial application of subadditivity.


text:
Q: SSRS 2008 - Empty Textbox if condition is true I've got a report which includes a column called Capacity and want to return "" if the result of the above textbox value is the same as the one in the current textbox.
Example;
Country      Capacity        Date
USA           100            01/01/2013
              100            08/01/2013
              100            15/01/2013
              100            22/01/2013

So in this case I would want to show the first row with the Capacity of 100 and the rest just blank rows as the capacity is the same, is there a way to do this in SSRS 2008 as I don't want to alter the SQL?
Thanks

A: You can use the PREVIOUS function (see doku ):
For the Textbox text use an expression to compare the current capacity value to the previous capacity value; if the values are the same display "".
=IIF(Previous(Fields!FieldName.Value) <> Fields!FieldName.Value,
     Fields!FieldName.Value, "")


text:
Q: Entity Framework Core Using multiple DbContexts I'm having a problem that when I try to access a field in my PartsDbContext I get the following error:

System.Data.SqlClient.SqlException: 'Invalid object name 'fieldName''

It seems that this is because I'm trying to make my PartsDbContext use the same database as my ApplicationDbContext which is used with Identity.  I need to know how to setup a 2nd dbcontext to work with EF core that uses/creates a different database.
I've tried creating a 2nd connection string but that gets me this error:

System.Data.SqlClient.SqlException: 'Cannot open database "PartsDb" requested by the login. The login failed.
  Login failed for user 'DESKTOP-4VPU567\higle'.'

Here's my code:
appsettings.json
"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-PrecisionCustomPC-b14db89e-86ad-4855-a17f-ac64a04339aa;Trusted_Connection=True;MultipleActiveResultSets=true",
    "PartsConnection":  "Server=(localdb)\\mssqllocaldb;Database=PartsDb"
},
"Logging": {
    "IncludeScopes": false,
    "LogLevel": {
        "Default": "Warning"
    }
}

PartsDbContext.cs
public class PartsDbContext : DbContext
{
    public DbSet<PartsViewModels.Tower> Towers { get; set; }
    public DbSet<PartsViewModels.Motherboard> Motherboards { get; set; }

    public PartsDbContext(DbContextOptions<PartsDbContext> options)
        : base(options)
    {
    }
}

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddEntityFramework()
        .AddDbContext<PartsDbContext>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("PartsConnection")));

    services.AddMvc();

    services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
    });

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

AdminController.cs
[Authorize(Policy = "RequireAdminRole")]
public class AdminController : Controller
{
    private readonly PartsDbContext _context;

    public AdminController(PartsDbContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Towers()
    {
        var model = _context.Towers.ToList();
        return View(model);
    }
}

The line var model = _context.Towers.ToList(); is where the error is showing up.
Once again. I want to setup my PartsDbContext to work with Entity Framework Core in a way that EF-Core will automatically create the database.

A: I figured it out.  This mostly came about because I accidentally deleted the database that Identity was using and I needed to figure out how to get it back.
Apparently there's nothing wrong with my connection string the way it is.  I just needed to go into the package manager and type these commands in this order:

*

*Add-Migration init -Context PartsDbContext

*Update-Database -Context PartsDbContext
I found this out because that is what I had to do to get my ApplicationDbContext working again and it turns out that this step is done for you when you create a new MVC Core Web Application in Visual Studio using Individual User Authentication.
So basically the steps for adding more DbContexts is to:

*

*Create a DbContext Class

*Create a Connection string for that DbContext in appsettings.json

*Add the DbContext to your configured services in Startup.cs

*Setup the DbContext in the controllers that will use it.

*Open the package manager and run the 2 lines above. (if "-Context" doesn't work try "--context"

*Run your program and let EntityFrameworkCore take care of the rest.

A: First of all, thanks @Joe Higley answer this questions,I want to add more situation to help more people.
My situation is i'm trying to use EF-Identity and Area to create a admin panel, in my admin area own their own controller/models/views..., also contain a new DBcontext.
There is problems, if you try to context.Database.EnsureCreated(); to initialize DB there will show

System.Data.SqlClient.SqlException: 'Invalid object name 'fieldName''

Ref this link Migrations with Multiple Providers
We can use migrations and use --context to set which DbContext you want to  run
In VScode you can run
dotnet ef migrations add InitialCreate --context BlogContext
dotnet ef database update

In Package Management Console you can run
Add-Migration InitialCreate -Context BlogContext
Update-Database

A: In addition to the prior comments, you can use this way:
dotnet ef migrations add InitialCreate --context MyContext

dotnet ef database update --context MyContext

or
Add-Migration InitialCreate -Context MyContext

Update-Database -Context MyContext

A: I cannot comment yet, but I would like to add to the answer.
Currently I am working my way through this tutorial: https://learn.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/model?view=aspnetcore-5.0&tabs=visual-studio
But I too started out with ApplicationDbContext for Identity. So, I ran into a similar problem. Your answer helped me out, thanks!
The tutorial however suggests a cleaner way to do this.

*

*Add a data model

*Scaffold the data model!

This step is huge. It creates the Context class, a connection string in appsettings.json, adds the Context in Startup.cs and more.
For usage of scaffolding take a look at linked tutorial.

*Run given commands in the PMC and you are set.

*

*Add-Migration init -Context ModelContext

*Update-Database -Context ModelContext
So, I would suggest to use scaffolding as it does the most work for you.


text:
Q: Start an already deployed and terminated container in Azure Container Instance How do I start a container in ACI Container Group which is already deployed and in terminated state. Can it be done either through some automation or from logic app? CLI commands show az container restart but not start. The logic app connectors seem to pull the image every time and start it.Is there no means to just start an existing terminated container?

A: Once a container is terminated there is not a start action you can do. You can deploy a new container which will pull the image you have setup and run whatever app is setup.
If the container is in a failed state you could issue a restart command but the results are basically the same. It re-initializes the container, pulls the image and deploys the app.
This is how containers work. They are not a persistent item such as a Virtual Machine. They are designed to be removed, added, and upgraded as needed.

A: This is a pain point on Azure. While container instances are not meant to be restarted after being terminated, the container groups they sit inside are meant to be flexible enough to be restarted. And they have that capability - Microsoft Azure's docs just don't really talk about it. It's left for you to figure out.
The main problem is that when you deploy an updated container instance to an existing container group in Azure, and the matching container instance in Azure is terminated, the deployment will not automatically trigger the new version of that container instance to run again.
In my case, I'm scheduling a container deployment to occur from inside an Logic App using the "Create or update a container group" connector (because Microsoft removed the cloud scheduler earlier this year, forcing people to use Logic Apps for simple tasks like this). If I delete the existing container group and run the Logic App, then it will automatically start the Docker container instance as expected. When I re-run it subsequent times, it fails to start the container, because the previous instance inside the container group is in a terminated state. The solution is to add an additional "Start containers in a container group" action, which will start the container instances anew and allow them to run to completion (at which point my containers terminate again, because they're one-off ETL jobs).


text:
Q: remove layer from open layers not working I am trying to add layers from GeoServer; it's working fine but removing layers is not working. This is my code:
function loadTOCLayer(layerName) {
  var tl = new ol.layer.Tile({
    extent: [-20037508.34, -20037508.34, 20037508.34, 20037508.34],
    source: new ol.source.TileWMS( /** @type {olx.source.TileWMSOptions} */ ({
      url: 'http://172.16.1.58:8080/geoserver/KBJNL/gwc/service/wms',
      params: {
        'LAYERS': layerName,
        'TILED': true
      },
      serverType: 'geoserver'
    }))
  });

  map.addLayer(tl);
}

function removeTOCLayer(ss) {
  map.removeLayer(ss);
}

A: You are mixing layer name and layer reference. You'll have to keep an index of layers by name. Try this:
var layersByName = {};
function loadTOCLayer(layerName) {
  var tl = new ol.layer.Tile({
    extent: [-20037508.34, -20037508.34, 20037508.34, 20037508.34],
    source: new ol.source.TileWMS( /** @type {olx.source.TileWMSOptions} */ ({
      url: 'http://172.16.1.58:8080/geoserver/KBJNL/gwc/service/wms',
      params: {
        'LAYERS': layerName,
        'TILED': true
      },
      serverType: 'geoserver'
    }))
  });

  layersByName[layerName] = tl;

  map.addLayer(tl);
}

function removeTOCLayer(ss) {
  map.removeLayer(layersByName[ss]);
}


text:
Q: Recursive regex with garbled text surrounding? Getting "ArrayArray" I asked a similar question, but it was closed for being too broad.  Basically, I have a bunch of questions like this.  I'm hoping just asking one will be easier.  I've tried some different ways to solve this, but none of them actually work.
I have a text file with a lot of data.  The only data that I'm interested in falls between two brackets, "(" ")".  I'm wondering how to get each instance of info that lies between brackets into an array.
The code I'm using right now returns ArrayArray:
function get_between($startString, $endString, $myFile){
  preg_match_all('/\$startString([^$endString]+)\}/', $myFile, $matches);
  return $matches;
}
$myFile = file_get_contents('explode.txt');
$list = get_between("&nbsp(", ")", $myFile);
foreach($list as $list){
  echo $list;
}

A: Your regex is completely misleaded.
First: [^...] is a complemented character class. A complemented character class is an atom, and whatever ... is is the set of characters which must not be allowed at this point. Ie, [^ab] will allow anything but a and b.
Second: you seem to want to be able to capture between parens. But a paren (open or closing) is a special character in a regex. So, in your example, if $startString is &nbsp(, the paren will be interpreted as a regex metacharacter.
Third: unfortunately, this cannot be solved with regexes, but nested $startString and $endString cannot be matched (well, they can with perl, but perl is perl).
The closest you can get to what you really want is rewriting your regex to use with preg_match_all as follows:
$start = preg_quote($startString, '/');
$end = preg_quote($endString, '/');
$re = '/\Q' . $start . '\E'       # literal $start
    . '('                         # capture...
    . '(?:(?!\Q' . $end . '\E).)' # any character, as long as $end is not found at this position,
    . '+)'                        # one or more times
    . '\Q' . $end . '\E/';        # literal $end

and then use that as your first argument to preg_match_all.
The \Q and \E regex modifiers tell that anything between the first and second should be treated as literals -- hence the paren in &nbsp( will be treated literally, and not as the group opening metacharacter.

A: <?php
function get_between($startString, $endString, $myFile){
  //Escape start and end strings.
  $startStringSafe = preg_quote($startString, '/');
  $endStringSafe = preg_quote($endString, '/');
  //non-greedy match any character between start and end strings.
  //s modifier should make it also match newlines.
  preg_match_all("/$startStringSafe(.*?)$endStringSafe/s", $myFile, $matches);
  return $matches;
}
$myFile = 'fkdhkvdf(mat(((ch1)vdsf b(match2) dhdughfdgs (match3)';
$list = get_between("(", ")", $myFile);
foreach($list[1] as $list){
  echo $list."\n";
}

I did this and it seems to work.  (Obviously, you'll need to replace my $myFile assignment line with your file_get_contents statement.)  A few things:
A: Variable replacement won't occur with single-quotes.  So your preg_replace_all regular expression won't work as a result.  As it literally adds $startString to your expression instead of (. (I also removed the check for } at the end of the matched string.  Add it back in if you need it with \\} just before the ending delimiter.)
B: $list will be an array of arrays.  I believe by default, index zero will contain all full matches.  index one will contain the first subpattern match.
C: This only works so long as $endString will not ever be found inside of a subpattern you are attempting to match.  Say, if you expect (matc(fF)) to give you matc(fF), it won't.  It'll give you match(fF.  You'll need a more powerful parser if you want to get the former result in this case.
Edit: The get_between function here should work with  ( and )} as well, or whatever else you'd want.


text:
Q: Cannot find module 'on-finished' I'm trying to run a Node Server. I'm using Express and Typescript and VSCode as editor. If i compile and try to run my app.js I get this error:
> Error: Cannot find module 'on-finished'
>     at Function.Module._resolveFilename (module.js:440:15)
>     at Function.Module._load (module.js:388:25)
>     at Module.require (module.js:468:17)
>     at require (internal/module.js:20:19)
>     at Object.<anonymous> (C:\nodeProjects\node_modules\express\node_modules\finalhandler\index.js:16:18)
>     at Module._compile (module.js:541:32)
>     at Object.Module._extensions..js (module.js:550:10)
>     at Module.load (module.js:458:32)
>     at tryModuleLoad (module.js:417:12)
>     at Function.Module._load (module.js:409:3)

My app.ts:
/// <reference path="_all.d.ts" />
import * as express from "express";
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Listening on port 3000!');
});

my tsconfig:
{
    "version": "1.7.5",
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "outDir": "../cmpl"
    }
}

my projects structure:
- .vscode/
- cmpl/
- src/
-- node_modules/
-- public/
-- routes/
-- typings/
-- views/
-- _all.d.ts
-- app.ts
-- package.json
-- tsonfig.json

And i don't know where the problem is. If I'm looking into the node_modules folder. The module exists.
Greetz

A: Your issue is
import * as express from "express";
I tested the exact same line on my app using express, threw nearly same error, therefore you'd be better off using a variable, like I always do, and it has never failed me.
var express = require('express')
Should have no issues whatsoever.


text:
Q: How to display "selected radio button" after refresh? After refresh the page, the user selected radio button is missing.
How can I always display the user's "selected radio button" even I had refresh the page?
<input name="radiobutton" type="radio" value="" id="all" checked />

radio with checked is not suitable, because it will always display the default radio button.
Below is my code:-
<form name="myfrm" id="myfrm" action="" method="post">
    <input name="radiobutton" type="radio" value="" id="all" />
    All Languages
    <input name="radiobutton" type="radio" value="" id="english" />
    English
</form>

A: I don't know if this is something you'd want. But a thing that comes up to mind is the HTML5 Web Storage functionality.With that feature you can store data on the computer of the user.
So whenever a user changes an input field you can create a javascript call that stores the value into the localstorage:
localStorage.setItem("inputName", "value");

Then when you load the page, you see if any of these values are stored and then fill them in.

A: You should conform to standards and give a value to every attribute. That means you need checked="checked"
<input name="radiobutton" type="radio" value="" id="all" checked="checked" />

And in case you were asking how to stick to what was selected previously: AFAIK, it is not possible with plain HTML. You need to bind a Javascript event that submits the selected radio button to your server and a dynamically generated page (by PHP, Python, whatever) that puts the 'checked="checked" to the radio button that was submitted as checked.
EDIT:
As I see it, submitting the currently selected radio button to the server and generating your page dynamically might be overkill.

A: i think this discussion is going to help you...though this discussion is about saving state of checkbox, but you can modify that code according to your need..hope this helps to you!!!
Save state of inputElement


text:
Q: ImportError: when importing from a local script library Does importing from a local script lib work in qpython3?
I have a script I created in the Qpython projects3 directory of qpython.
projects3/MPU6502/
I have my main code here in this directory.
main.py
I have a local subdirectory,
projects3/MPU6502/tiny6502lib/
In this sub directory I have the source code,
RAM_8bit_Memory.py
From my main.py source code I load the library,
#-*-coding:utf8;-*-
#qpy:3
#qpy:console
# import 6502 library module
from tiny6502lib.RAM_8bit_Memory import *

when I execute the library import I get the ERRORL:
"ImportError: No module named tiny6502lib.RAM_8bit_Memory"
Is importing local script libraries broken in qpython3?
org.qpython.py/projects/MPU6502/main.py
org.qpython.py/projects/MPU6502/tiny6502lib/RAM_8bit_Memory.py
This code works perfectly on all other flavors of python3 (windows) and pythonista on ipad.
How do I get this import to work? Or does it not work at all?
thank you,

A: Just try to insert the following code before importing tiny6502lib.RAM_8bit_Memory
import sys
sys.path.append("/sdcard/qpython/projects3/MPU6502")
?


text:
Q: Simpler code to combine multiple lists into one array? I actually wish "lists" are still "lists" in that array I have a question similar to this and that, but the solutions to those is that all lists are "united" with lack of "differentiation".
My Python code is like following:
y = np.empty([1,len(test)])
count = -1
for feature in test :
    N = engine.neighbours(np.asarray(feature))
        if len(N) != 4096:
            print "error"
            continue
        count = count + 1
    y [count] = engine.neighbours(np.asarray(feature))

I am just wondering if there is any simplified code to do the job?

A: The linked questions have to do with flattening a list of lists.  In your code you are processing a list of lists (I'm guessing), filtering out some, and collecting the rest in a 2d array.
Oops!  y is initialized with 1 row, yet you try to place values in y[count], where count could increase to the size of test.
y = np.empty([1,len(test)])
count = -1
# I would prefer to start with 0, but thats a style issue
for feature in test :
    N = engine.neighbours(np.asarray(feature))
    # so engine.neighbors requires an array; and returns an array?
        if len(N) != 4096:
            print "error"
            continue
        count = count + 1
    y [count] = engine.neighbours(np.asarray(feature))
    # why call neighbors again?  why not reuse N?

A common way of creating an array incrementally is:
alist = []
for feature in tests:
     N = engine.neighbors(np.array(feature)
     # test N length
     alist.append(N)
y = np.array(alist)

Since by the length test, all N have the same length, the resulting array will be 2d, shape (n,4096), where n is the number of tests with the correct length.
Initializing y to np.empty((length(tests),4096)], and inserting y[count,:] = N may be faster.  You may end up with unfilled rows if some fail the length test, but you can remove those.
Initializing y to np.empty((1,4096)], and inserting y=np.append(y,N) should also work.  Note that this append is different from the list append.  And slower.  I prefer that people use concatenate directly:
y = np.concatenate([y, N[None,:]], axis=0)

The concatenation is explicit, and the required dimension manipulation clear.
To make a 1d array of arrays, you have to do something like this:
y=np.empty((4,),dtype=object)
for i in range(len(y)):
    y[i]=np.arange(i,2*i)

producing:
array([array([], dtype=int32), array([1]), array([2, 3]), array([3, 4, 5])], dtype=object)

which is arguably little more than the y list produced by
y=[]
for i in range(4):
    y.append(np.arange(i,2*i))

In all this I'm assuming that engine.neighbors() takes a 1d array, and returns a 1d array.  If if took/returned multiple feature we could 'vectorize' things.  But as long as we can only give it one feature at a time we are stuck with some form of iteration.


text:
Q: how to get Video id from iframe of youtube in php or cakephp i have this iframe

how to get video id from it by regular expression or any.....

A: You can use:
$subject = '';
$pattern = '!http://(?:www.)?youtube.com/embed/([^"']+)!i';
$result = preg_match($pattern, $subject, $subpattern);

$subpattern will contain:
Array ( [0] => http://www.youtube.com/embed/YRUG-Pu7RzE [1] => YRUG-Pu7RzE )


text:
Q: Remove zero eigenvalues (or any) by deleting rows and columns and other eigenvalues unchanged Is it possible to remove $k$ zero eigenvalues of a matrix by removing $k$ rows and columns of a square matrix (after modification using decomposition methods or other ways) with other eigenvalues unchanged?. If so, how to identify the rows and column to be removed?
Major problem is the loss of sparsity on modified matrix
PS: A simple understanding is, with one zero eigenvalue, there is one dependent row and column in the matrix. Then the dependent row/column can be written as a linear combination of other rows/columns and can be used to reduce the dimension using a transformation. But not sure the eigenvalues invariability and how to choose the the dependent row/column (there will be multiple possibility).

A: No.
Let $A = \left[\begin{array}{cc}2 & 2\\2 & 2\end{array}\right]$. This matrix has eigenvalues $0$ and $4$.


text:
Q: password change field not shown for one user - Ez publish Hi i am using Ezpublish , I logged into the admin panel , and I can search for a user and change his/her password
but for one user i can not change the password , even the password change fields are not shown , I can not figure out the problem actually .
is there any table in Ezpublish database where user permissions , access levels stored ???
i checked in
ezuser
ezuser_accountkey
 ezuser_discountrule
ezuser_role
ezuser_setting
ezuservisit
but I could not find a major difference between the 2 users (password can be edited and password can not be edited)

A: eZPublish stores permissions in 3 tables : ezpolicy, ezpolicy_limitation and ezpolicy_limitation_value.
Maybe an error has been added in var/log/error.log
You can enable debug to search in which template the issue appears.


text:
Q: Using HTML File Input to open camera on native devices I'm trying to open camera on mobile devices with html input tag:
<input type="file" accept="image/*" capture="environment"/>
on ios it working as expected!!!
but on android it open files browser


text:
Q: C - Buffer Overflow Issue Here is the source code for the program
#include <stdio.h>
% filename: test.c
int main(){
  int local = 0;
  char buff[7];
  printf("Password: ");
  gets(buff);

  if (local)
    printf("Buff: %s, local:%d\n", buff, local);
  return 0;
}

I using "gcc test.c -fno-stack-protector -o test" to compile this file, and when I run the file, in order to make the gets overflow, I need to enter at least 13 characters. The way I think is since I only declare 7 bytes to the buff, which means when user enter at least 8 characters, overflow happened. But seems like not this case, why?

A: The stack layout is implementation dependent.
There is no guarantee that local object will be after or before buff object or that both will be contiguous.
In your case, what is likely is 5-bytes (1 + 4) of padding were inserted  after buff object. Such padding is very common and is usually inserted by the compiler for performance reasons. The size of the padding can vary between compilers, compiler versions, compiler options or even from different source codes.
To have a better idea of the layout just print the addresses of both buff and local objects:
printf("%p %p\n", (void *) buff, (void *) local);

A: gets(buff);

There is no default bound check in C. At the best program will crash, usually it will get unallocated memory, so it just works fine. Even sometime you overrun already used memory, and may not realize it till you get into problem.

A: There's no guarantee that the items on your stack will be allocated packed tightly together, in fact I'm pretty certain they're not even guaranteed to be put in the same order.
If you want to understand why it's not failing as you seem to expect, your best bet is to look at the assembler output, with something like gcc -S.
For what it's worth, gcc 4.8.3 under CygWin fails at eight characters as one might expect. It overflows at seven characters but, because the overflowing character is the NUL terminator, that still leaves local as zero.
Bottom line, undefined behaviour is exactly that. It's most annoying feature (to developers) is that it sometimes works, meaning that we sometimes miss it until the code gets out into production. If UB were somehow tied to electrodes connected to the private parts of developers, I guarantee there'd be far fewer bugs :-)


text:
Q: Determine the type of object (e.g. lines or plane) given the intersection Given B =\begin{pmatrix} 1 & -1 & 1\\ 1 & 1 & 3\end{pmatrix}determine the general solution of the homogeneous system Bx=0. This describes the intersection of two objects (e.g. a line or a plane). Determine and find the Cartesian equation of this object.
I have solved the homogeneous equation being x$=t(-2, -1, 1)$ but how do I determine what two objects this intersection represents along with their Cartesian equation?

A: Note that the first two columns are linearly independent, this means rank (dimension of the range space) is at least $2$. But range is $\subseteq \Bbb{R}^2$. Thus the range is entire $\Bbb{R}^2$. By the rank-nullity theorem, the nullity is $3-2=1$. This means the solution space for $B\mathbf{x}=\mathbf{0}$ is $1$ dimensional. Thus it must be a line passing through the origin.
Note: we didn't have to really solve the system to determine the geometry of the solution space.
From your answer it is clear that any solution is parallel to the vector $\begin{bmatrix}-2\\-1\\1\end{bmatrix}$. Hence it is line whose direction vector is this and passes through the origin.


text:
Q: Sharing files, and how to stay updated? I have a program I use on multiple computers, that I would like to keep in sync to each other.
The files shared are .json and .txt files. Am I just able to serialize back to the file every so often without cause for concern? The software is used to make transactions on an inventory, it is only used on 1 computer, and then I use the software to make purchases or restock the items after purchased. I just want to be able to access it from my computer without having to walk to the other computer, close it, and open it on my computer make my changes and close it, walk back and open it back up.
I haven't dug into this at all, as I'm not sure what exactly it is called that I am looking for.
I would think if I can just serialize back to the file it would be ok, but maybe there is an easy way to check if the file has been saved over since I have had it open on my computer?

A: If you want to check whether or not the file was altered since some defined point in time look at the FileInfo. If you have several computers running put the file on a shared folder and use a FileSystemWatcher. In general I think there is nothing principally not working with serializing/deserializing data to disc.
Nevertheless I would suggest backing up data and considering concurrency.


text:
Q: Multiselect options are overrided after load I modified the below file

magento2\vendor\magento\module-catalog\Block\Product\View\Options\Type\Select\Multiple.php

In order to add custom value to the text of the options in the multi-select.
The problem is that it's working but after it loads the product name + price, it gets overridden again by the default product name that has been saved in the backend.
I fixed this in the past but after we moved to 2.4.3 a lot of stuff has changed and this error appeared again.
It's really hard to find information regarding overridden data because I always get into problems overriding Magento modules.
You can see what is happening here:

https://www.hairworldshop.nl/kappersproducten/zoe-t-way-color-100-ml.html

When the page starts loading it adds the custom value as seen here:

Thanks in advance.


text:
Q: iOS HTTP Post method not working when key is not a string I am using Post method to send user data to server.
NSMutableArray *RegistraionKeys=[NSMutableArray arrayWithObjects:@"user[first_name]",@"user[last_name]",@"user[user_profile_attributes][date_of_birth]",@"user[user_profile_attributes][address]",@"user[user_profile_attributes][country]", @"user[user_profile_attributes][phone]", @"user[user_profile_attributes][gender]", nil];

NSMutableArray *RegistraionValues=[NSMutableArray arrayWithObjects:@"aaa", @"GS", @"1987-07-19", @"bbb",@"IND", @"1234567890", @"male",nil];

NSDictionary *userRegistrationDictionary = [[NSDictionary alloc]initWithObjects:RegistraionValues forKeys:RegistraionKeys];

NSData *postData = [NSJSONSerialization dataWithJSONObject:userRegistrationDictionary options:0 error:&error];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:method];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"en" forHTTPHeaderField:@"LOCALE"];

[request setHTTPBody:body];

NSURLSessionDataTask *uploadTask = [sessionManager dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSDictionary *results;
    if (data) {
        results =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    }
}];

Here I have some keys like "user[first_name] , user[last_name] ..etc". If it is only "first_name" then I can pass this key as string. but "first_name" is under "user" so I have passed like "user[first_name]".
This code is not working and not update data into server. I want to know the correct way to pass the data if key is like this ("user[first_name]").
Note : "first_name" is under "user"
Can anyone please help me to solve this?
Thanks in advance.

A: Your issue is here:
NSMutableArray *RegistraionKeys=[NSMutableArray arrayWithObjects:@"user[first_name]",@"user[last_name]",@"user[user_profile_attributes][date_of_birth]",@"user[user_profile_attributes][address]",@"user[user_profile_attributes][country]", @"user[user_profile_attributes][phone]", @"user[user_profile_attributes][gender]", nil];

NSMutableArray *RegistraionValues=[NSMutableArray arrayWithObjects:@"aaa", @"GS", @"1987-07-19", @"bbb",@"IND", @"1234567890", @"male",nil];

NSDictionary *userRegistrationDictionary = [[NSDictionary alloc]initWithObjects:RegistraionValues forKeys:RegistraionKeys];

I'll skip the fact that two var begins with a uppercase.
Well, if you read a little about JSON, or you're used, in Objective-C, to use short hand syntax (it exists in other languages too), you can assume that in fact, your web service is awaiting for something like that:
NSDictionary *userRegistrationDictionary = @{@"user":@{@"first_name":@"aaa",
                                                       @"last_name":@"GS",
                                                       @"user_profile_attributes":@{@"date_of_birth":@"1987-07-19",
                                                                                @"address":@"bbb",
                                                                                @"country":@"IND",
                                                                                @"phone":@"1234567890",
                                                                                @"gender":@"male"}}};

These are the results of the userRegistrationDictionary if you try then to convert it into JSON:
$>YourFirstVersion: {
  "user[user_profile_attributes][country]" : "IND",
  "user[user_profile_attributes][gender]" : "male",
  "user[first_name]" : "aaa",
  "user[last_name]" : "GS",
  "user[user_profile_attributes][date_of_birth]" : "1987-07-19",
  "user[user_profile_attributes][phone]" : "1234567890",
  "user[user_profile_attributes][address]" : "bbb"
}
$>CorrectVersion: {
  "user" : {
    "user_profile_attributes" : {
      "gender" : "male",
      "phone" : "1234567890",
      "country" : "IND",
      "date_of_birth" : "1987-07-19",
      "address" : "bbb"
    },
    "first_name" : "aaa",
    "last_name" : "GS"
  }
}

Yours seems "weird". It's valid, but unusual. Everything is in the same level, but ZzZ[key] seems to look for a dictionary thing.


text:
Q: Roslyn Vsix stopped working after moving the project I had a working Roslyn VSIX Project for analyzing resources that could be localizable.  Everything was working fine until I moved the project to a new location.
The analyzer's still seem to run and trigger the Code fix, However, the Code Action is never Registered into visual studio, so there is no option for that fix for some reason.
My analyzer:
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ConstDiagnosticAnalyzer : DiagnosticAnalyzer
{
    public const string DiagnosticId = "Viventium.Localization.Tools.ConstantToResource";

    // You can change these strings in the Resources.resx file. If you do not want your analyzer to be localize-able, you can use regular strings for Title and MessageFormat.
    // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/Localizing%20Analyzers.md for more on localization
    private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.ConstAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.ConstAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.ConstAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
    private const string Category = "Naming";

    private static ResourceLocalizationRule localizationRule = new ResourceLocalizationRule();

    private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }

    public override void Initialize(AnalysisContext context)
    {
        context.RegisterSyntaxNodeAction(AnalyzeConstDeclaration, SyntaxKind.FieldDeclaration);
    }

    public static void AnalyzeConstDeclaration(SyntaxNodeAnalysisContext context)
    {
        var fieldDeclaration = (FieldDeclarationSyntax)context.Node;

        if (false == IsValidConstDeclaration(context, fieldDeclaration))
        {
            return;
        }

        var firstVariable = fieldDeclaration.Declaration.Variables.FirstOrDefault();
        var firstSymbol = context.SemanticModel.GetDeclaredSymbol(firstVariable);

        context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation(), firstSymbol.Name));
    }

    private static bool VariableIsInResx(SyntaxNodeAnalysisContext context, FieldDeclarationSyntax fieldDeclaration)
    {
        var solution = context.GetSolution();
        var documentPropertyMap = PropertyMapCache.GetDocumentPropertyMap(solution);

        return localizationRule.IsFieldDeclaredInResx(fieldDeclaration, documentPropertyMap);
    }

    private static bool IsValidConstDeclaration(SyntaxNodeAnalysisContext context, FieldDeclarationSyntax fieldDeclaration)
    {
        if (false == fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword))
        {
            return false;
        }

        if (fieldDeclaration.Declaration.Variables.Count > 1)
        {
            return false;
        }

        var declaredVariable = fieldDeclaration.Declaration.Variables.FirstOrDefault();

        var initializer = declaredVariable.Initializer;
        if (initializer == null)
        {
            return false;
        }

        var constantValue = context.SemanticModel.GetConstantValue(initializer.Value);
        if (!constantValue.HasValue)
        {
            return false;
        }

        var variableTypeName = fieldDeclaration.Declaration.Type;
        var variableType = context.SemanticModel.GetTypeInfo(variableTypeName).ConvertedType;

        if (variableType.SpecialType != SpecialType.System_String)
        {
            return false;
        }

        return true;
    }
}

The Fix Provider:
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ConstantToResourceCodeFixProvider)), Shared]
public class ConstantToResourceCodeFixProvider : CodeFixProvider
{
    #region Consts

    private const string title = "Convert Constant Use Resources";

    #endregion

    #region CodeFixProvider Overrides

    public sealed override ImmutableArray<string> FixableDiagnosticIds
    {
        get { return ImmutableArray.Create(ConstDiagnosticAnalyzer.DiagnosticId); }
    }

    public sealed override FixAllProvider GetFixAllProvider()
    {
        // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers
        return WellKnownFixAllProviders.BatchFixer;
    }

    public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
    {
        var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

        // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest
        var diagnostic = context.Diagnostics.First();
        var diagnosticSpan = diagnostic.Location.SourceSpan;

        // Find the type declaration identified by the diagnostic.
        var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf<FieldDeclarationSyntax>().First();

        // Register a code action that will invoke the fix.
        context.RegisterCodeFix(
            CodeActionWithPreview.CreateStateful(
                title: title,
                createChangedDocument: (c, isPreview) => this.CheckConstForLocalization(context, declaration, isPreview, c),
                equivalenceKey: title),
            diagnostic);
    }

    #endregion

    #region Analyzer Logic

    private async Task<Document> CheckConstForLocalization(CodeFixContext context, FieldDeclarationSyntax field, bool isPreview, CancellationToken cancellationToken)
    {
        var documentPropertyMap = PropertyMapCache.GetDocumentPropertyMap(context.Document.Project.Solution);

        var localizationRule = new ResourceLocalizationRule();
        var updatedDocument = localizationRule.ConvertDocumentToUseResources(context.Document, documentPropertyMap, field, isPreview, cancellationToken);

        return await updatedDocument;
    }

    #endregion
}

Can some one please give me a hint to of what is going on an how I can fix this?

A: After hours of debugging it turns out Diagnostic Analyzer's are not allowed to have periods in them...
public const string DiagnosticId = "Viventium_Localization_Tools_ConstantToResource";

The fix was quite simple I just changed the DiagnosticId to use underscores, and I've opened a bug with Roslyn


text:
Q: tableau to show both last and previous 12 month In one worksheet, to display the measure value (Sales) of Last 12 Months(LTM) and Previous 12 Months(PTM) from the selected month.
Current Month is 2018-June , By default selection
PTM date range for the sales period as (2016-June to 2017-May)
LTM date range for the sales period as (2017-June to 2018-May)
If user selects different month from the drop down, let's select (Apr 2018)
PTM date range as (2016-Apr to 2017-Mar)
LTM date range as (2017-Apr to 2018-Mar)

A: This can be done using a parameter. Here are the steps involved:

*

*Create a date parameter

*Create a calculated field as below(You might need to fine tune it to match your exact requirements)

*Add the calculated field to filter card to show only 'SHOW'


text:
Q: Erasing line features based on intersecting polygons using GeoPandas? I have two interesecting geopandas.GeoDataFrame datasets, one containing line features (lines_gdf) and one containing polygons (polygons_gdf):
import matplotlib.pyplot as plt
import geopandas as gpd
from shapely.geometry import Polygon, LineString

# Create sample polygon and line data
polygons_gdf = gpd.GeoDataFrame(geometry=[Polygon(zip([150, 151, 151, 150],
                                                      [30, 30, 31, 31]))])
lines_gdf = gpd.GeoDataFrame(geometry=[LineString(zip([148, 150, 152],
                                                      [28, 30, 32]))])

# Plot example data
polygons_gdf.plot()
lines_gdf.plot(ax=plt.gca(), edgecolor='red')

Desired output
I want to use my polygons dataset to remove or erase any part of my lines dataset it intersects with (essentially a GIS "erase" operation), and return only the non-overlapping parts of my lines (i.e. black lines below):

Using the geopandas.clip tool I've been able to do the exact opposite of what I need to do: clip the data to keep (not remove) the intersecting portion of my lines:
# Clip lines to keep only area within `polygons_gdf`
clipped_gdf = gpd.clip(lines_gdf, polygons_gdf)

# Plot clipped lines over the top of input layers
polygons_gdf.plot(alpha=0.1)
lines_gdf.plot(ax=plt.gca(), edgecolor='red', alpha=0.1)
clipped_gdf.plot(ax=plt.gca(), edgecolor='black')

My question: How do I use geopandas to remove/erase part of a line dataset that intersects with a polygon dataset?
My geopandas version is v0.6.3.

A: A colleague helped me out with this one:

*

*Upgrade geopandas to version 0.7.0 or above. Prior to version 0.7.0, this function supported polygon operations only. Version 0.7.0 introduced the following change:

The geopandas.overlay function now works for all geometry types,
  including points and linestrings in addition to polygons

*Use the geopandas.overlay function with how='difference':

erased_gdf = gpd.overlay(lines_gdf, polygons_gdf, how='difference')

This now gives me the result I required:
# Plot output over the top of input layers
polygons_gdf.plot(alpha=0.1)
lines_gdf.plot(ax=plt.gca(), edgecolor='red', alpha=0.1)
erased_gdf.plot(ax=plt.gca(), edgecolor='black')

A: I haven't used geopandas much, but when I did, I needed a similar operation. Try looking at the set operations. The one you're after is "symmetric difference".


text:
Q: Open to or open for further discussion? This is a bit similar to another question already asked but I think the context is somewhat different.
I was taking a sample Cambridge CPE test and one of the tasks involved was to change a sentence using a given word, changing neither the sentence's meaning nor the word's.
The sentence was:

The manager refused to discuss his decision further.

The word to use was "open".

The manager stated that his decision [insert answer here] discussion.

My answer was:

The manager stated that his decision [was not open for further] discussion.

The answer key says [was not open to further].
Was my answer also correct or not?

A: Yes, your answer is correct as well. To get a feeling for how often certain phrases are used, you can use the Google Ngram Viewer:

Of course, this doesn't tell you that the phrases have the same meaning; for that, you can click on the links below the graph which show a few samples where the phrase is used, with the same meaning as your exercise.


text:
Q: Why or when should I use bit shifts in enum like this? While studying enums, I have seen some people use them in combination with bit shifting. Being a beginner and unsure of correct usage, I would appreciate advice.
So here are 2 examples.
#define BIT(x) (1<<x)

enum WithBits{`

    first = BIT(0), //first = 1
    second = BIT(1), // second = 2
    third = BIT(2) //third = 4  }

BIT(x) is defined where each of enum members has value of 1 shifted x times to the left. For example x of member third is 2. 1 is shifted 2 times so third is connected with value 4. In the end, values of first , second and third are 1, 2 and 4 respectively.
Now we could also do this.
enum WithoutBits{`

    first = 1, // first = 1
    second = 2, // second = 2
    third = 4 // third = 4  }

In this case, first, second and third are also 1, 2 and 4.
Both examples work fine.
What exactly is the difference? Why and when should I use first enum example (WithBits) instead of second example (WithoutBits)?
Thanks you for your time, any help is welcome!

A: There is no reason to use macros like that.  You can either directly write the bit shifts:
enum MyEnum : uint16_t {
  first = 1 << 0,
  second = 1 << 1,
  ...

Or as hex, which is clearer than decimal when the values get larger:
enum MyEnum : uint16_t {
  first = 0x1,
  second = 0x2,
  ...

You probably should specify the size of the enum explicitly when you're making bitmasks, so I've added that above.

A: The two pieces of code create exactly the same structure, which can be used in exactly the same way. The BIT macro, or spelling out 1 << 2 instead of 4, is just an aid to humans reading the code, to signal the intention of the code. Whether it does a good job of signalling that intention is a matter of opinion.
The actual ability to use it in a "bitmask" (what you probably meant by "bitfield") doesn't come from how you write the values, but quite simply from choosing values that each have one bit set, so that you can use boolean logic to create and test different combinations.

A: Another approach is to use a metafunction to generate these masks.
template<typename T, unsigned int BIT>
struct bit_mask
{
  static_assert(std::is_integral<T>());
  static constexpr T value = T{1} << BIT;
}

You could then use this metafunction:
static_assert(bit_mask<uint8_t, 2>::value == 4);      // 0b00000100
static_assert(bit_mask<uint16_t, 8>::value == 256);   // 0b00000001 00000000
auto floatBitmask = bit_mask<float, 3>::value;        // Won't compile

This approach could also be extended to allow you to set multiple bits in the integer, by providing a parameter pack of unsigned ints and recursively ORing the bit shift produced by each parameter provided in the pack:
template<typename T, unsigned int... BIT>
struct bit_mask
{
  static_assert(std::is_integral<T>());
  static constexpr T value = 0;
};

template<typename T, unsigned int BIT, unsigned int... BITS>
struct bit_mask<T, BIT, BITS...>
{
  static_assert(std::is_integral<T>());
  static constexpr T value = (T{1} << BIT) | bit_mask<T, BITS...>::value;
};

template<typename T, unsigned int BIT_A, unsigned int BIT_B>
struct bit_mask<T, BIT_A, BIT_B>
{
  static_assert(std::is_integral<T>());
  static constexpr T value = (T{1} << BIT_A) | (T{1} << BIT_B);
};

This can then be used:
static_assert(bit_mask<uint16_t, 2>::value == 4);      // 0b00000000 00000100
static_assert(bit_mask<uint16_t, 8>::value == 256);    // 0b00000001 00000000
static_assert(bit_mask<uint16_t, 2, 8>::value == 260); // 0b00000001 00000100
static_assert(bit_mask<uint8_t, 0, 1, 2, 3, 4, 5, 6, 7>::value == 255);   // 0b11111111


text:
Q: Image not showing after collapsed I am running into a strange situation where the image won't show up if its visibility is first set to collapsed and latter set to visible through binding.
<ListView Grid.Row="0" ItemsSource="{Binding SystemCheckEntries}">
            <GridViewColumn DisplayMemberBinding="{Binding State}" />
            <GridViewColumn>
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Image Source="info.png"
                               Height="14"
                               ToolTip="{Binding Message}"
                               Visibility="{Binding Message, Converter={StaticResource StringNullOrEmptyToVisibilityConverter}}"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

Converter:
public class StringNullOrEmptyToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.IsNullOrEmpty((string) value) ? Visibility.Collapsed : Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

if I use Visibility.Collapsed in converter then the result looks like

and if I open up visual tree to check the property of the image

which says its suppose to be "Visible" (but apparently not)
If I use Visibility.Hidden in converter then the result looks like

Which is exactly what I wanted. But then I don't want the icon to take up extra space when its not showing.
So .. why is this happening?

A: Some conjecture: The first items have no width (because they are collapsed), the ListView sets the column width to 0. New items are added that have an image but it's not shown because the column has no width.
Edit: Just confirmed this behaviour.


text:
Q: AppCompat Dialog Theme with Mis-colored titlebar - Bug? I have a LoginActivity where I use an AppCompat theme like this:
 <activity
            android:name=".LoginActivity"
            android:theme="@style/Theme.AppCompat.Light.Dialog"
            android:label="Login" />

I am aware that as of this post Google has not yet added Material Themes in AppCompat library for DIALOGS, so I assumed it will fall back on Holo.  Instead, this is what I get:

Keep in mind, I am not using the AppCompat toolBar.  In the Activity, I am not even making a reference to the ActionBar.  What you see above is default behavior, yet I cannot figure out where it is coming from.  Is this a bug perhaps?
(Also, the EditText fields are not being colored with the Primary color for the app.)

A: Note: see my final edit for possibly the best solution
For what it's worth, I do think this is a bug. However, a valid workaround that I discovered is to use @style/Base.Theme.AppCompat.Light.Dialog.FixedSize. Based on your screenshot I think this will work for you as well. However, I have not tested palette coloring yet.
From what I can tell in my testing, this extends the gray border while still allowing you to use AppCompat and v21.
Edit: one side-effect is it now appears that all dialog activities are the same size, which may not work for you. Also, I haven't figured out how to remove the title - requestWindowFeature and supportRequestWindowFeature with Window.FEATURE_NO_TITLE seems to be causing
java.lang.RuntimeException: Unable to start activity ComponentInfo{myclass}:
android.util.AndroidRuntimeException: requestFeature() must be called before adding content

even though I've tried it before and after super.onCreate and definitely before setContentView
Edit#2: Removing the title via XML theming works, and since you have no title there is no bizarre gray box to worry about, which means you can drop the FixedSize setting and the dialog will wrap it's content like it did in earlier versions.
<style name="MyActivityDialogTheme" parent="Base.Theme.AppCompat.Light.Dialog">
    <item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
</style>

Edit #3: You can also just simply remove the gray background - this may be the best solution because it does not require the Base. prefix:
<style name="MyTitledActivityDialogTheme" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:windowNoTitle">false</item>
    <item name="android:windowTitleBackgroundStyle">@android:color/transparent</item>
    <item name="windowActionBar">false</item>
</style>


text:
Q: Formula to show date of the last day of the month specified in another column in Excel For a month number in column A, I want the LAST day of that particular month in column B.  Right now, I'm working with year 2014, so:
A1 number is 1 so B1 date is 01/31/14
A2 number is 2 so B2 date is 02/28/14
A3 number is 11 so B3 date is 11/30/14
A4 number is 10 so B4 date is 10/31/14

etc. for all twelve months of the year 2014.  I will eventually need the same for year 2015, 2016 etc.

A: Formula for B1 (copy down the column):
=DATE(2014,A1+1,0)

This formula returns the date one day before the first day of the next month, which will be the last day of the specified month.
If you will be reusing the same data, stick the year in a cell somewhere and reference that cell instead of hard coding the year in the formula; just change the year in the reference cell.  For example, put 2014 in cell C1.  The formula would then be =DATE($C$1,A1+1,0).  For 2015, change C1 to 2015 and all of the formulas will reflect that year.


text:
Q: best way for python to interface with MySQL I'm still very new to programming and trying to teach myself the correct ways of doing things.
I'm currently writing a script that will take 1-3 values, generated about every second, within python and then save it to a MySQL database. Down the road will build a web interface that will take those values and nicely display them, but for now I just want to save the data.
I will be running the Python code on a Raspberry Pi, and hopefully the web server with the MySQL server. If not on that device on another Raspberry Pi.
What I'm here asking is, what is the best way for Python to work with MySQL? Library or HTTP GET, or another way I don't know about... Since, I was going to build a web interface, I was thinking about having an API.php page that will take GET request and then the PHP code will write the data to the MySQL database.
What I had in mind was to have Python generate a link then use the request library to request the site e.g http://127.0.0.1/API.php?value1=XXX&Value2=YYY&value3=ZZZ  then wait for a JSON return of something like "Data Saved" if the data was saved correctly. Then continue the loop of generating the next value.
What that be the best way of going about this or is there a better way? I know that I will have some security issues, and I hope to resolve them once I learn more about coding. And remember that I want the data written every 1 or 5 seconds. Hopefully, every 1 second.
Thank you guys for your responses,
Throdne

A: First install mysqlclient as this will also provide you support to work with Python 3.6
pip install mysqlclient

Example code
    import mysql.connector
    import _mysql
    db=_mysql.connect("127.0.0.1","root","umer","sys")
    #db=_mysql.connect(host,user,password,db)
    # Example of how to insert new values:
    db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
    db.store_result()
    db.query("SELECT * FROM new1.table1 ;")
    #new1 is scheme table1 is table mysql
    res= db.store_result()
    for i in range(res.num_rows()):
        print(result.fetch_row())

A: pip install mysql failed for me on MacOS Sierra with EnvironmentError: mysql_config not found.
pip install pymysql works. PyMySQL is written in pure Python, so should be more cross-platform than statically compiled modules.
Example code:
import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

A: Python connect xampp mysql windows with pymysql:
Step-1:
Run Command Prompt
    D:\python-3.6.2\Scripts> pip install pymysql
Step-2:
#!D:/python-3.6.2/python.exe
print ("Content-Type: text/html\n")
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='python_mysql')
cur = conn.cursor()
cur.execute("SELECT * FROM authors")
print(cur.description)
print(" Test")
for row in cur:
    print(row)
cur.close()
conn.close()

Save the file as testconn.py in htdocs/PythonProject & open http://localhost/PythonProject\testconn.py
Crud Python & MySQL:
https://github.com/matinict/python-in-xampp-for-windows/

A: There are a lot of ways you could do this, but since you stated that the MySQL server could be on the same Raspberry Pi or a different one, the following is the simplest way to get what you need set up.
First, you need to install a Python package which contains MySQL bindings. There are ton out there, but MySQL-python seems to be mature and good enough.
To install it:
$ pip install mysql

(If you're not already familiar with pip, check out the pip documentation to get started.)
Once you've got a MySQL server running on one of your Raspberry Pis, here's an example what you'll need to do in the code to connect to the server and run various types of queries:
import MySQLdb

host = '192.168.99.100'
user = 'myuser'
password = 'secret'
port = 3306
db = 'test'

conn = MySQLdb.Connection(
    host=host,
    user=user,
    passwd=password,
    port=port,
    db=db
)

# Example of how to insert new values:
conn.query("""INSERT INTO mytable VALUES ('foo3', 'bar2')""")
conn.commit()

# Example of how to fetch table data:
conn.query("""SELECT * FROM mytable""")
result = conn.store_result()
for i in range(result.num_rows()):
    print(result.fetch_row())

Check the MySQL-python user docs for more details on how to use the library.
The above code assumes a couple of things about your MySQL server:

*

*Your server is running at 192.168.99.100. It could be 127.0.0.1 (localhost) or another address.

*Your server already has the user myuser defined, with a password and appropriate permissions.

*You have already created a database called test.

*You have already created a table called mytable on database test which contains the VARCHAR fields of foo and bar.

I won't go into those details, since that's slightly out of scope for this thread, but if you need help have a look at the MySQL documentation for creating users and creating tables.

A: import mysql.connector as connector

class DbHelper:
    def __init__(self):
        self.conn = connector.connect(host = '127.0.0.1', user = 'root', password = '', database = 'python_test')
##        print("Database connected...")

        query = 'create table if not exists user(userID int primary key, firstname varchar(200),lastname varchar(200), Dob varchar(15), contact varchar(10), address varchar(100))'
        curr = self.conn.cursor()
        curr.execute(query)
##        print("Table Created")
        print()

    def insert_Data(self, userID, firstname, lastname, Dob, contact, address):

        query = "insert into user (userID, firstname, lastname, Dob, contact, address) values({},'{}','{}','{}','{}','{}')".format(userID,firstname, lastname, Dob, contact, address)

        curr = self.conn.cursor()
        curr.execute(query)
        self.conn.commit()
        print(query)
        print("User data inserted....")

    def display_Data(self):
        query = 'select * from user'
##        print("query: ", query)
        print()

        curr = self.conn.cursor()
        curr.execute(query)

        for row in curr:
            print('userID :', row[0])
            print('firstname :', row[1])
            print('lastname :', row[2])
            print('Dob :', row[3])
            print('contact :', row[4])
            print('address :', row[5])
            print()
            print()

##        print(" All user data....")

    def delete_user(self, userID):

        query = "DELETE FROM user WHERE userID={}".format(userID)
        curr = self.conn.cursor()
        curr.execute(query)
        self.conn.commit()
##        print(query)
        print("Data delete for UserID " +str(userID))

    def update_Data(self, userID, newfirstname, newlastname, newDob, newcontact, newaddress):

        query = "update user set firstname = '{}', lastname ='{}', Dob = '{}', contact = '{}', address = '{}' where userID = {}".format(newfirstname, newlastname, newDob, newcontact, newaddress,userID)
        curr = self.conn.cursor()
        curr.execute(query)
        self.conn.commit()
##        print(query)
        print()
        print("Data updated for UserID " +str(userID))

##db = DbHelper()
##db.update_Data(1,'saurabh','sharma','25-06-1998','9892809732','malad')


text:
Q: Flash FLA file size becoming huge for no good reason Q1: What is the reason for the enormass bloating of FLA file size, when many edits and saves are made to a FLA file, yet assets are not being added to the library?
Q2: What is the best technique to keep FLA files smaller in size? (with the problem described below. I am not talking about published SWF files or asset management)
Over many edits and many saves of my FLA files, they become 30 times the size on disk from where they start out. Example 750k can get as high as 34mb. In the past "save and compact" used to fill the role of reducing FLA file sizes but now that feature is gone.
The issue is discussed here but does not provide a satisfactory solution or reason:
http://www.xllusion.net/ed/2010/05/04/no-save-and-compact-on-flash-cs5/
Extra Details:
When I save as a CS4 file then back to CS5 the file becomes much smaller after it has become bloated, BUT I take a risk every time I do this that the file will become corrupted (I've had corruptions happen).
I have read that files which were created in CS5 and are never in the format of CS4 don't have this problem, but I find that theory unlikely since I have tried to follow this rule to no success.
I have also read that every FLA file tracks its "history" of assets. So adding and removing assets to the library will sometimes cause bloating because old assets that are removed from the library remain in the FLA file. This seems bogus because there is no purpose to this, but could be an indication of a bug in Adobe Flash Professional CS5, and CS5.5.
Personal details: the files I am editing contain personally created flash components, images, audio, many symbols (20+) but no embedded video.
For me personally, this bloating is a problem because I'm dealing with hundreds of flash FLA files that should be about 1-4mb in size but are instead much larger. The overall effect is that I end up with gigabytes of files instead of hundreds of mbs.
Thanks so much for your help!!!

A: I ran into the same problem. The assets I was importing were a fraction of the size of the FLA.
The solution is to create a new FLA and copy the assets from the library of your bloated FLA into the new one. Save the new one and you should see a significant file size decrease. This bug has been around a long time (at least since CS3) and I would have hoped Adobe would have resolved it by now.

A: Most of the time you can just do "save as", Flash seems to keep a few copies of your library for your undo history and forgets to strip this out when you do a normal save, doing "saves as" will reduce it massively, Ive seen flash files go from 300mb to 500kb using this technique.

A: The FLA File is your library file, the only way to reduce the fla file size is to delete assets inside your project you dont need at all and reduce embedding assets.
Sometimes when your making a SWF you might say import an asset but then decide to delete it or not use it.Generally this item now is added into your FLA library so you will need to remove it from here aswell.
Also you could load dynamicaly, pictures, audio ect..this will reduce the file size but these files will still need to be present in another folder.
other times if im importing pictures i make sure the image is exactly what i want in size for instance, If imported a picture 400x400 but the display size is only 64x64 in the swf. I would edit this image in another program to shrink it to the exact size 64x64 then import it to my FLA.if need be i could reduce the quality down aswell
There are tips and other ways to reduce this size but overall this file has uncompressed assets, the idea is your SWF is the compressed movie.
Always check your library this will justify the file size.
Creating vectors, instead of embedding logo's/images or big backgrounds and animating with librarys will keep your project file low so if you were to draw vector images for backgrounds/ or what not  instead of importing images this will reduce the filesize aswell.
Streaming video instead of embedding has its advantages, firstly your project file is smaller and also streaming can load quicker as it only needs a portion to start playing its content.whilst load dynamically will take longer to start to play as it will need to load the complete movie.Dynamically will still keep your movie smaller in size

A: I reduce my huge files to 20% ie a project (all fla files) summed up to 558 mb but after doing these two step it reduced to only 80 mb.
1.The way to reduce the fla file size is to delete assets inside your project you dont need.
2.Doing "saves as" will reduce file massively.


text:
Q: FOSUserBundle sending bad confirmation links 1 or 2% of users registering seem to get no confirmation email or they get a bad token appended to the confirmation link in the email. I can't determine why or where this wrong token comes from. It doesn't look like a truncated version of the correct one. It's totally different. Clicking it yields a 404 response.
I am not overriding the RegistrationController.
Could it be the mailer settings?
swiftmailer:
    ~
    spool:     { type: memory }

The only other changes I've made were in validation of a few custom fields.
registration:
    form:
        type: acme_user_registration
        validation_groups: [MyRegistration]
    confirmation:
        enabled:    true

Any ideas what's going on?
Thanks.

A: I found a problem while viewing a confirmation email in outlook.com. I turns out that outlook.com is 'previewing' the link to show some expanded metadata in the email message. This has the side effect of enabling the user and deleting the token. Once the user actually clicks the link, they get a token not found error, but their account is enabled.