text:
Q: Wrong output when multiplying. Is it a bug in my compiler? c++ When i write this:
cout << 10000 * 10000;

I get this output:
100000000

But when I try:
cout << 100000 * 100000;

I get:
1410065408

How is this possible? And why?

A: Types of both operands are ints, so type of result is also int. You can run the following program to see what is going on
cout << 100000LL * 100000LL << endl;
cout << 100000 * 100000 << endl;
cout << 100000LL * 100000LL % (numeric_limits<unsigned int>::max()+1LL) << endl; // +1 accounts for zero
cout << typeid(100000 * 100000).name() << endl;

10000000000
  1410065408
  1410065408
  int

Note, that adding of LL fixes the problem.

A: The operands of the multiplication are integral types. As you haven't supplied a suffix on the operands, your compiler will attempt to coerce them into an int, and if that fails, a long int. With C++11 it will additionally attempt a coercion to a long long int. So pre-C++11 your program behaviour could be undefined at this point, but with C++11 both operands can be represented as a long long int as that must be at least 64 bits.
So the problem is either down to that or the fact that your system doesn't have an integral type large enough to represent that product (which is probably evaluated at compile time). So your program behaviour is undefined.
If you promote one of the arguments to floating point, then the output will be in floating point, albeit with the associated loss of precision (usually about 15 significant figures).
Take a look at std::numeric_limits for more details.

A: It is giving a garbage value because integer type limit is crossed.
Easiest way is to define with double and square it you'll definitely going to have correct answer.


text:
Q: FindBy columnName when column name contains "Id" In Grails, Gorm, I have this entity:
class MyEntity implements Serializable {

Long bankTransactionId

int version

BigDecimal someValue

static constraints = {
    bankTransactionId(nullable: false)
    version(nullable: true)
    someValue(nullable: true)
    }
}

Doing MyEntity.findByBankTransactionId(Long.valueOf("3")) throws this exception:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
  column 'this_.id' in 'field list'

I am suspecting the fact that my column has the name id in it. Could it be this?
How to fix it then ?
Thanks.

A: Everything you have provided here looks fine.  In particular, there are no restrictions about having the letters "id" in a column name.
Take a look at your generated MySQL table.  I'm guessing that the id column isn't there for some reason.  Maybe something prevented generating it due to some earlier error that you have now corrected, or you have your datasource set to "none" instead of "update" (or similar) and the whole table is missing!
If this is just a development environment with no real data (and no foreign key constraints), drop the whole MyEntity table and let it be automatically recreated.  If not, move to a different temporary datasource, let a new table be created, and compare the two.  If the new one still doesn't have an id column, you have something going wrong during your startup that is preventing your tables from being created correctly.  You could just add the column in manually, but if you don't figure out what happened to it in the first place, it will probably just happen again.
For reference, in my test environment, my MySQL table for "MyEntity" copied from your example looks like:
desc my_entity;

'id','bigint(20)','NO','PRI',NULL,'auto_increment'
'version','int(11)','YES','',NULL,''
'bank_transaction_id','bigint(20)','NO','',NULL,''
'some_value','decimal(19,2)','YES','',NULL,''

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cmake doesn't find boost windows I'm trying to run this code:
https://github.com/snukky/news-translit-nmt
I've installed boost and got the following messages:
The Boost C++ Libraries were successfully built!

The following directory should be added to compiler include paths:

    C:\Program Files\boost\boost_1_67_0

The following directory should be added to linker library paths:

    C:\Program Files\boost\boost_1_67_0\stage\lib

By the comment of @kenba I've added the following environment variables:

Try 1
When I try to run the following cmd:
 cmake .. -DCMAKE_BUILD_TYPE=Release

I get:
-- Could NOT find Boost (missing: timer iostreams filesystem system chrono) (found version "1.67.0")
CMake Error at CMakeLists.txt:290 (message):
  Cannot find Boost libraries.  Terminating.

-- Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)
-- Configuring incomplete, errors occurred!
See also "D:/ThesisResources/previous_works/news-translit-nmt-master/tools/marian-dev/build/CMakeFiles/CMakeOutput.log".

Try 2
When I try to give a custom boost by this ref
https://marian-nmt.github.io/docs/#custom-boost:
I run the following cmd:
 cmake .. -DBOOST_ROOT="C:\Program Files\boost\boost_1_67_0"

I get the same error.

*

*I've also tried working with Linux WSL (But problems with CUDA installation overthere, their team is working on it), Linux VirtualBox (Not enough resources), and Ubuntu 17.10 I have installed (But Cuda requires Ubuntu 16.04 / 18.04)

What am I missing here? I'm trying any suggestion, stuck on it for a few days. Thanks!
Edit:
I reinstalled Ubuntu 16.04 and the problem was solved. Still don't know how to solve it in windows, but i'll continue use Ubuntu 16.04.

A: I had this problem earlier while trying to build the Windows version of Marian NMT (the same component that you're having trouble with). I can't remember the exact steps to solve the problem, but the root cause is that the Marian NMT build for Windows does not work with newer versions of Boost, since the source code uses some deprecated calling conventions for timer and chrono libraries (maybe some others as well).
The error message kind of confirms this: it can't find Boost, but on the other hand it says it finds your version 1.67.0. The solution is to use an older version of boost, I've confirmed that it works with 1.60.0.
If you just require a Marian NMT decoder that works in Windows, a project I work on has released a plugin for the Trados Studio translation tool, which contains a compiled marian-decoder executable for Windows: https://object.pouta.csc.fi/fiskmo/TradosStudio/FiskmoTranslationProvider.sdlplugin. You can access the executable by unzipping the sdlplugin file, the StartMtPipe.bat shows how to use the decoder.


text:
Q: are particles "knots" or "kinks" of excitation in a field? this is my mental picture for how they travel without a medium, how (like water waves) some can't stay still, why they have wave and particle properties, energy/mass equivalence, conservation, etc.  it might capture uncertainty too -- i've heard that all waves have an uncertainty relation (say in their power spectrum), but i don't get why -- it seems like we can discuss waves with absolute precision.

A: Actually that's not too far off the mark, although I'm not sure "knot" or "kink" is the best word. Quantum field theory, the best theory we currently have to describe particles, says that particles correspond to excitations of a field, which are kind of like waves in water; you could consider the surface of a pond "excited" whenever it's not flat. Just as with water waves, there's an infinite variety of "shapes" you can have for these excitations. For example, you could have a repeating wave, in which the surface of the water cycles up and down over a large area, or you could have just one wave front that just propagates across the water without spreading out very much. The former case is pretty typical for things like light waves, and the latter case is pretty typical for particles of matter, although technically any kind of field (whether it's the electromagnetic field for light, or a quark field in matter, or whatever) can have any of the different types of excitations.
By the way, according to special (and general) relativity, even an object that is standing still is moving through time. So all of these excitations move through spacetime in one way or another. But only certain ones (the excitations in fields corresponding to massless particles) can move through space in such a way that they appear to us to be traveling at the speed of light.

A: The short answer is no. Particles obey a very important property called "cluster decomposition principle", while those type of lumps that you mentioned do not.
What that means is that if you have a particle as an excitation of a theory, you might perfectly well have a two particle state as a solution when their separation goes to infinity. This is a essential ingredient to calculate S matrices and cross sections (that's almost everything that is useful in particle collision experiments). This is not true, in general, for these extended solutions.
Further details can be found in that excellent book Aspects of Symmetry, by Coleman. Check section 6.2.3: Lumps are like particles (almost).

A: particles are ordinary quanta of the corresponding quantum fields - without any knots or other topologically nontrivial features. (You have to get used to the wave-particle duality, probabilities, and the uncertainty principle - they're fundamental features of the world around us.)
However, this is only true for "weakly coupled particles" that are directly described by a Lagrangian composed of "free fields" plus "weak interactions". On the other hand, there can be many other objects that are not just quanta of waves but they have "knots" on them.
We say that they are topological defects. Most typically, one can take the original fields and write down a classical solution of the equations of motion that is topologically nontrivial. The resulting configuration of fields has to exist in the quantum theory, too. It is preserved by the nontrivial topology.
In 1 spatial dimension, a topologically nontrivial configuration is one that drives a scalar field from 1 local minimum of the potential to another, as you move from the left to the right; it is known as the "kink".
In 2 spatial dimensions, there are solutions known as "vortices" (or one "vortex") in which the circular round trip around the center of the solution sees a field to go around a noncontractible curve in the configuration space.
In 3 spatial dimensions, we similarly find magnetic "monopoles" which are also some kinds of "knots" on the fields. More generally, the topological defects that correspond to real objects are known as "solitons". This is contrasted with the "instantons" which are objects localized in the Euclidean spacetime; they don't describe static objects but rather special histories that contribute to various probability amplitudes for processes that appear at one "instant" of time.
Another class of topologically nontrivial configurations are skyrmions, and if you want to see a representative that is really close to your "knots", see a paper about knitted fivebranes in M-theory:
http://arxiv.org/abs/hep-th/9803108
In the quantum theory, objects such as solitons - especially monopoles - may behave indistinguishably from the original quanta. There is sometimes a full symmetry between them - the most famous example is the S-duality of gauge theories in 4 dimensions. Electrically charged particles such as gauginos are exchanged with the magnetic monopoles - solitons - as the coupling $g$ is changed to $1/g$.
All these things, when done properly, still satisfy all the postulates of quantum mechanics such as the nonzero commutators between observables (uncertainty principle). In string theory, topological defects include objects such as D-branes, NS5-branes, and in extra-dimensional theories in general, one also has special "knitted" configurations of the metric such as the Kaluza-Klein monopoles (magnetic monopoles extended in extra dimensions).
Best wishes
Lubos


text:
Q: Google Gusuite Login Issue my gsuite account is suspended i am trying to login to my account I am using the same email and password which I used to register into gsuite but now it is giving me error enter image description here

A: You must use your G Suite admin account.
In the other hand you can restore the password using the alternative email.


text:
Q: What does the !~ method do with String in Ruby From @sawa's answer at: https://stackoverflow.com/a/21892359/226255
What does !~ do?
Example:
re = /[^\d.,]/
"0.0687987167581341,0.120311605902415,89.8399554017928,198.151088713489" !~ re

I couldn't find any documentation in String or Regexp

A: The method !~ is the inverse of =~, that is !(=~). From the Ruby Object#!~ documentation:

[obj !~ other ] returns true if two objects do not match (using the =~ method), otherwise false.

So, since String#=~ performs a string/regex match returning the index of the first match if matched and nil otherwise, String#!~ return false if matched and true otherwise.

A: It means the regex does not match. It's the inverse of =~
Also mentioned here: Does Ruby regular expression have a not match operator like "!~" in Perl?
Apparently it's not documented for some reason.


text:
Q: Flutter: Google Charts Library chart-size/column I am trying to use Googles's chart lib (https://github.com/google/charts) to make same charts.
My problem is the following: I am trying to have the chart on the top, followed by buttons in text.
But everytime, if I try to do the chart in a column like:
 Column(
      children: [
          LineChart(seriesList),
      ],
    );
  }

I need to wrap the LineChart in an expanded (what I not really want), so I do not get an error.
Is there any option, to force the google-charts to a specific size, e.g. half of the screen?

A: There are plenty of different ways.

1. With AspectRatio
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          AspectRatio(
            aspectRatio: 2 * MediaQuery.of(context).size.aspectRatio,
            child: SimpleLineChart.withSampleData(),
          ),
        ],
      ),
    );
  }
}

With SizedBox
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          SizedBox(
              height: MediaQuery.of(context).size.height / 2,
              child: SimpleLineChart.withSampleData()),
        ],
      ),
    );
  }
}

With a ConstrainedBox
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          ConstrainedBox(
              constraints: BoxConstraints.loose(Size(
                double.infinity,
                MediaQuery.of(context).size.height / 2,
              )),
              child: SimpleLineChart.withSampleData()),
        ],
      ),
    );
  }
}

With a ListView, specifying the itemExtent
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        itemExtent: MediaQuery.of(context).size.height / 2,
        children: [
          SimpleLineChart.withSampleData(),
        ],
      ),
    );
  }
}

...
...


text:
Q: performance of custom controls In terms of performance. Is it a good idea to build your own data grid (assuming you have the time) having in mind that you will create one that match perfectly your need? Getting rid of many unnecessary properties and methods. The rendered page might be smaller making the download faster?
thanks

A: As ASP.NET already includes the Repeater control and the DataList control, both of which allow you to specify the HTML output of the control, there is little need to create a new control for performance reasons.

A: The properties and methods of a server control have no direct relationship with the size of the rendered HTML.  Simply removing methods won't make the slightest difference in the size of your download. In my experience, the .NET controls work well enough.  If you encounter a performance problem, you can always drop in a different implementation later.


text:
Q: How to reverse a linked list while keeping the original linked list unchanged How can I reverse a linked list keeping original same?
If I am reversing the linked list it is changing the original one as well.
class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        p = head
        q = self.reverse_list(head)

        while p and q:
            if p.val != q.val:
                return False
            else:
                p = p.next
                q= q.next
        return True

    def reverse_list(self, head):
        curr = head
        prev = None
        while curr is not None:
            tmp = curr.next
            curr.next = prev
            prev = curr
            curr = tmp

        return prev

A: You can make a very aesthetically-pleasing (but not super efficient solution in python) using recursion. Basically, you can switch the order of recursions giving you a forward generator and a reverse generator, then zip and compare
class Solution:
    def isPalindrome(self, head):
        return all(a.val == b.val
                   for a,b
                   in zip(self.forward(head), self.backward(head)))

    def forward(self, head):
        if head is None:
            return
        yield head
        yield from self.forward(head.next)

    def backward(self, head):
        if head is None:
            return
        yield from self.backward(head.next)
        yield head

This is attractive, but unlikely to work with very large lists because of recursion limits.
For larger input you can make a non-recursive version of the forward() generator and render a list from it. Then compare the list to it's reverse:
class Solution:
    def isPalindrome(self, head):
        v = list(self.forward(head))
        return v == v[::-1]

    def forward(self, head):
        while head:
            yield head.val
            head = head.next

This uses O(n) space, but should perform reasonably well.
Another solution would be to iterate through the list adding a parent property as you go. At the end you will have the tail of the list and can follow the parent reference in parallel to running the list from the head again and compare.


text:
Q: HTMLCollection.length returns 0, even though log shows 4 I'm trying to track active section of the website to change the styling of navigation link. However, when I try to loop through the HTMLCollection (property of length is 4) using its length, nothing happens because the length returned is 0. How can I fix that?
var pages = document.getElementsByClassName("page");
var links = document.getElementsByClassName("link-container");

var activePage = 0;

console.log(pages);
console.log(pages.length);

for (var i = 0; i < pages.length; i++) {
  pages[i].addEventListener("mouseover", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
    activePage = i;
    console.log("over");
  });
}

export default activePage;

enter image description here
If I just log an array and its length everything works correctly. I expect pages.length to return 4, not 0


text:
Q: R - return 1st column element and column name given condition I am having data cleaning troubles on what should be a straightforward thing and would really appreciate some help.
I have a df with dates in the first column and different categories (Red, Yellow, Orange) as column names. The remainder of the df are numbers. I would like to search through all elements of the df (other than the first column); if an element is greater than a threshold level (i >0.2, for instance), I would like to return the date and the column name. So ideally, my output would be an nx2 df like this:

*

*November, 2003 | Orange

*October, 1997 | Red
....

Is there a clear best method to use this: I have read about which[] and subset() and %in% and have come away without a clear answer.
Thanks again.

A: May be
library(reshape2)
subset(melt(df, id.var='date'), value > 0.2, select=1:2)

Or using dplyr/tidyr
 library(dplyr)
 library(tidyr)
 gather(df, Var, Val,-date) %>%
                         filter(Val > 0.2) %>%
                         select(-Val)

data
df <- structure(list(date = c("November, 2003", "October, 1997",
"September, 2005"), Red = c(0.1, 0.2, 0.3), Yellow = c(0.3, 0.4, 0.2),
 Orange = c(0.1, 0.2, 0.4)), .Names = c("date", "Red", "Yellow", "Orange"),
 row.names = c(NA, -3L), class = "data.frame")


text:
Q: Is there any way to hide my code? I usually do a project and deploy it on the client machine, but all the Ruby/WATIR scripts are clearly visible to everyone. Is there any way to hide my code? Or is there any way I can secure my code? Or Is there any way to lock a folder through Ruby?

A: You could use jRuby and create a JAR using Warbler but that will only stop non-geek users. Here a link about using watir in jRuby
Converting the script to an executable file like with Ocra is also an option.
Securing the script and let it run in another security context could work.
But what I would do is make it a web-app that can be run anywhere while nobody can see the source code. With a nice framework like Sinatra that shouldn't be that hard.

A: Code obfuscation is one option. You can use tools like RubyScript2Exe or AllInOneRuby to obfuscate your code or make them difficult to understand. However these tools have their own flaws which are nicely discussed here.


text:
Q: React Router Error: Cannot read properties of undefined (reading 'pathname') I was attempting to add a Navbar to a Webb app and as soon as I put <Navbar/> into App.js I get the error below. I've read that the error could be related to the to props of <Link/> but I can't find any issues there and I'm having trouble making sense of this error. I appreciate all ideas and thank you for your time!
> components.tsx:197 Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')
    at Router (components.tsx:197:1)

react-dom.development.js:18687   The above error occurred in the
 component:  at Router
(http://localhost:3003/static/js/bundle.js:62004:15)  at App
Consider adding an error boundary to your tree to customize error
handling behavior. Visit https://reactjs.org/link/error-boundaries to
learn

Navbar:
export default function Navbar() {
  return (

      <Link to="/" className="site-title">

      </Link>

        <CustomLink to="/reflect">Reflect</CustomLink>
        <CustomLink to="/edi">Edi</CustomLink>

  )
}
  function CustomLink({ to, children, ...props }) {
  const resolvedPath = useResolvedPath(to)
  const isActive = useMatch({ path: resolvedPath.pathname, end: true })
  return (

      <Link to={to} {...props}>
        {children}
      </Link>

  )
}

App.js:
function App() {
  return (
    <>
      <Router>
        <NavBar />
        <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/reflect" element={<Reflect />} />
        <Route path="/edi" element={<Edi />} />
        <Route path="/storyboard" element={<StoryBoard />} />
        <Route path="/texteditor" element={<TextEditor />} />
        <Route path="/*" element={<errorPage />} />
        </Routes>
      </Router>
       </>
  );
}
export default App;

A: You should not be using <Router>. That requires you instantiate and pass in your own history <Router history={history}>. Use BrowserRouter instead.


text:
Q: PyPDF2 PdfFileWriter has no attribute stream I am trying to split a pdf into its pages and save each page as a new pdf. I have tried this method from a previous question with no success and the pypdf2 split example from here with no success. EDIT: I can see in my files that it does successfully write the first page, the second page pdf is then created but is empty.
Here is the code I am trying to run:
from PyPDF2 import PdfFileWriter, PdfFileReader

inputpdf = PdfFileReader(open("my_pdf.pdf", "rb"))

for i in range(inputpdf.numPages):
    output = PdfFileWriter()
    output.addPage(inputpdf.getPage(i))
    with open("document-page%s.pdf" % i, "wb") as outputStream:
        output.write(outputStream)

Here is the full error message:
Traceback (most recent call last):
  File "pdf_functions.py", line 9, in <module>
    output.write(outputStream)
  File "/usr/local/lib/python3.4/dist-packages/PyPDF2/pdf.py", line 482, in write
    self._sweepIndirectReferences(externalReferenceMap, self._root)
  File "/usr/local/lib/python3.4/dist-packages/PyPDF2/pdf.py", line 572, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "/usr/local/lib/python3.4/dist-packages/PyPDF2/pdf.py", line 548, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "/usr/local/lib/python3.4/dist-packages/PyPDF2/pdf.py", line 572, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "/usr/local/lib/python3.4/dist-packages/PyPDF2/pdf.py", line 548, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "/usr/local/lib/python3.4/dist-packages/PyPDF2/pdf.py", line 557, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, data[i])
  File "/usr/local/lib/python3.4/dist-packages/PyPDF2/pdf.py", line 572, in _sweepIndirectReferences
    self._sweepIndirectReferences(externMap, realdata)
  File "/usr/local/lib/python3.4/dist-packages/PyPDF2/pdf.py", line 548, in _sweepIndirectReferences
    value = self._sweepIndirectReferences(externMap, value)
  File "/usr/local/lib/python3.4/dist-packages/PyPDF2/pdf.py", line 575, in _sweepIndirectReferences
    if data.pdf.stream.closed:
AttributeError: 'PdfFileWriter' object has no attribute 'stream'

I also tried this and confirmed that I can indeed extract a single page.
from PyPDF2 import PdfFileWriter, PdfFileReader
inputpdf = PdfFileReader(open("/home/ubuntu/inputs/cityshape/form5.pdf", "rb"))

#for i in range(inputpdf.numPages):
output = PdfFileWriter()
output.addPage(inputpdf.getPage(2))
with open("document-page2.pdf", "wb") as outputStream:
    output.write(outputStream)

A: The same thing happened to me.
I was able to solve it by moving the following line inside the loop:
inputpdf = PdfFileReader(open("/home/ubuntu/inputs/cityshape/form5.pdf", "rb"))
I believe that some versions of PyPDF2 have some sort of bug, that when you invoke thePdfFileWriter.write method, it messes with the PdfFileReader instance. By recreating the PdfFileReader instance after each write, it bypasses this bug.
The following code should work (untested):
from PyPDF2 import PdfFileWriter, PdfFileReader

pdf_in_file = open("my_pdf.pdf",'rb')

inputpdf = PdfFileReader(pdf_in_file)
pages_no = inputpdf.numPages

for i in range(pages_no):
    inputpdf = PdfFileReader(pdf_in_file)
    output = PdfFileWriter()
    output.addPage(inputpdf.getPage(i))
    with open("document-page%s.pdf" % i, "wb") as outputStream:
        output.write(outputStream)

pdf_in_file.close()

A: I solved the error "AttributeError: 'PdfFileWriter' object has no attribute 'stream'" by repeating opening the PDF.
My old code:
pdf = PdfFileReader('arq.pfd')
pagi = 14
pagf = 20
dic = PdfFileMerger()

for i in range(pagi -1, pagf):

  pag = PdfFileWriter()
  pag.addPage(pdf.getPage(i))

  with open('pag.pdf', 'wb') as split:

    pag.write(split)

  pag = PdfFileReader('pag.pdf')
  dic.append(pag)

with open(f'PDF ({pagi} - {pagf}).pdf', 'wb') as split:

  dic.write(split)

!rm pag.pdf

My new code:
pdf = PdfFileReader('arq.pdf')
pagi = 14
pagf = 20
dic = PdfFileMerger()

for i in range(pagi - 1, pagf):

  pag = PdfFileWriter()
  pag.addPage(pdf.getPage(i))

  with open('pag.pdf', 'wb') as split:

    pdf = PdfFileReader('arq.pdf') # Adding pdf again
    pag.write(split)

  pag = PdfFileReader('pag.pdf')
  dic.append(pag)

with open(f'PDF ({pagi} - {pagf}).pdf', 'wb') as split:

  dic.write(split)

!rm pag.pdf

Hugs!

A: I have this problem today. But I found so many code just like me without errors, so I think maybe just version error. I have used pypdf2 version==1.27.3, just change it version to 1.25.0, this error will fix.
pip install pypdf2==1.25.0

A: This bug was fixed in version 1.27.8


text:
Q: How would I construct a regex expression that validates a percentage? I am quite new when it comes to regex and I am having a bit of trouble when it comes to what I want to do.
Essentially I want to create a pattern that only accepts inputs of the following kind

*

*A number from 0 - 100 (not including decimals)

*Or a number from 0 - 100 (not including decimals) followed by a percentage sign

So some sample inputs would be
65 - Valid
65% - Valid
-1 - Not Valid
101% - Not valid
65.5 - Not valid
65.5% - Not valid
65 % - Not valid
%65 - Not valid

Anything else shouldn't be valid
Currently I've come up with /[0-9](?:\%)?/ but this won't cover all the valid cases.
What do I need to change in my pattern to get what I'm looking for?


text:
Q: How to obtain Background color of a button with drawable state? Here is my drawable state:
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#ffdcd400" />
        </shape>
    </item>
    <item>
        <shape>
            <solid
                android:color="#ffe8e000" />
        </shape>
    </item>
</selector>

I get the button with this function:
public void ir(View v)
{
        Button boton_clickeado=(Button)v;
        StateListDrawable drawable= (StateListDrawable) v.getBackground();
}

I want to get the background color (state not pressed) "#ffe8e000" programmatically.
But I don't know which function use to obtain it.

A: Try this ..
int color = Color.TRANSPARENT;
StateListDrawable drawable= (StateListDrawable) v.getBackground();
if (drawable instanceof ColorDrawable)
color = ((ColorDrawable) drawable).getColor();


text:
Q: Eclipse debugger suspends on every republish I'm working on a web project in Eclipse Juno.  It's deployed on a Websphere 7.0 server using the IBM plugin.  Recently I have started having a problem where every time I republish to the server, triggered either automatically on saving or manually, the debugger suspends and opens the J9VMInternals class.  It's quite annoying and I'd love to make it stop.  There is not visibly a breakpoint set in that class.
I had this problem a while back while using MyEclipse but it had stopped when I made the switch to Juno, only returning recently.  I have not made any big changes to the environment, although do tweak settings here and there so it's possible I triggered something unknowingly.

A: You could try to resolve that by disabling
Suspend execution on uncaught exception

Under
Window > Preferences > Java > Debug

I had a similar issue with tomcat and some jdk threading class (I cant remember witch one) and could resolve like that.
EDIT
The class mentioned above is java.util.concurrent.ThreadPoolExecutor


text:
Q: Dynamically splitting Disks with Mouseover I've recently stumbled across this site: Koalas to the Max, and the first thought that came to my mind was "I want to recreate this with Mathematica".
As a first step I tried to create a Disk that splits itself up into four disks, when the mouse cursor touches it. Those four disks should in turn split themselves up. Here's what I have so far:
makeDisks[pos_] := makeDisks[1, pos]
makeDisks[level_, pos_] :=
 Module[{
   disk = Disk[pos, 1/level]},
  Mouseover[Dynamic@disk, Dynamic[disk = makeDisks[level + 1, #] & /@
   (pos + # & /@ (1/(2 level)) Tuples[{-1, 1}, 2])]]
  ]

(* test with the following *)

 Graphics[{makeDisks[1]},
   PlotRange -> {{-1, 1}, {-1, 1}}]

For the first disk this seems to work just as I want it. For later steps, however, I got the positioning wrong and some of the disks go back to larger ones, when another one is touched. How can these issues be fixed?
As a next step I want to add colors to the disks. Maybe this can be done by using MapIndexed with makeDisks on the ImageData of some image. The colors in each step should probably be the mean values of appropriate subsets of the image data.
Any help to move this little program forward is highly appreciated!

A: Here's a simple way using buttons, for some reason AutoAction is not working so you have to click, anyone know why?
nextPos[p_, r_] := {p + # r/2, r/2} & /@ Tuples[{1, -1}, 2]

DynamicModule[{diskList = {{ {0, 0}, 1}}},
 Graphics[Dynamic[
   Button[{ColorData["Rainbow"][Last@#], Disk @@ #},
      diskList = DeleteCases[Join[diskList, nextPos @@ #], #]
      ,AutoAction -> True
      ] & /@ diskList]]
 ]

The coloring is only based on depth (radius)
Basing color on underlying image:
background = ImageCrop[ExampleData[{"TestImage", "Peppers"}], AspectRatio -> 1];

DynamicModule[{diskList = {{{0, 0}, 1}}}, Graphics[Dynamic[
   Button[{RGBColor@ImageValue[background,First@#, DataRange -> {{-1, 1}, {-1, 1}}],
       Disk @@ #}
     ,diskList = DeleteCases[Join[diskList, nextPos @@ #], #]
     ,AutoAction -> True] & /@ diskList]]]

Using code from @Szabolcs comment it's possible to split the disks without clicking:
(* Create at most 2^6=64 disks in a row *)
rmin = 2^-6;
DynamicModule[{diskList = {{{0., 0.}, 1.}}}, Graphics[Dynamic[
  EventHandler[{RGBColor@ImageValue[background, First@#, DataRange -> {{-1, 1}, {-1, 1}}],
                Disk @@ #}
    ,{"MouseMoved" :>
      If[Last@# > rmin, diskList =DeleteCases[Join[diskList, nextPos @@ #], #]]}
   ] & /@ diskList]]
]

A: Alternative
DynamicModule[{visited = False},
    Dynamic@EventHandler[
      If[visited,
       Thread@Translate[#0@#, {1, -1}~Tuples~2]~Scale~
        0.5, {ColorData["Rainbow"]@Random[], #}],
      "MouseEntered" :> (visited = True)]] &[Disk[]] // Graphics

Other version. Works "more or less" fine. Read comments
SetAttributes[translateOnHover, HoldFirst];
s : translateOnHover[onVar_, animationLength_, animationRate_: 200][
   prim_] :=
 With[{creationTime = Clock[Infinity]~Refresh~None},
  DynamicModule[{visited = False},
   Dynamic@If[visited,
     With[{visitedTime = Clock[Infinity]~Refresh~None},
      With[{currentTime :=
         1/animationLength (Clock[{0, visitedTime + animationLength,
              1`/animationRate}, visitedTime + animationLength, 1] -
            visitedTime)},
       Thread@Translate[s, ({1, -1}~Tuples~2) /.
           pt : {_, _} :> Dynamic[pt currentTime]]~Scale~
        Dynamic[currentTime /. t_ :> 1 - t + 0.5 t^2]]],
     EventHandler[{ColorData["Rainbow"]@Random[], prim},
      "MouseEntered" :>
       If[onVar &&
         Refresh[Clock[Infinity], None] - creationTime >
          animationLength, visited = True]]]]]

With[{animationLength = 0.8, animationRate = 80},
  DynamicModule[{on = False},
   Column[{Row[{Button["Start", on = True, Enabled -> Dynamic[! on]],
       Spacer[20],
       Button["Stop", on = False, Enabled -> Dynamic[on]]}],
     Graphics[
      translateOnHover[on, animationLength, animationRate][Disk[]],
      ImageSize -> Medium, PlotRange -> 1.2 {{-1, 1}, {-1, 1}}]},
    Alignment -> Center]]] // Panel


text:
Q: MySQL Connector/Net EF Database First Spatial Datatypes Using:

*

*Entity Framework 5

*MySQL Connector Net 6.8.4

*MySQL 5.6.21

*Visual Studio 2013

*MySQL Workbench 6.2

Created the following table in MySQL using the workbench

Opened my application in Visual Studio 2013, navigated to my data access layer project, opened the .edmx, right-clicked on the canvas and chose
"Update model from database...".
I proceeded to add the new table, clicked finish, and this is what got spit out:

As you can see all the spatial data types were just ignored.
The Data Access project include (among other things) the following references:

*

*EntityFramework

*MySql.Data

*MySql.Data.Entity.EF5

*MySql.Web

*System.Data.Entity

I realize that in EF they'll be of type DbGeometry, but I feel like the update process should be able to figure this out for itself. And while I could manually add the mappings, I would prefer not to since they would get blown away next time someone runs the "Update model from database..."
Any insights or suggestions? Thanks!
Edit:
Tested with Entity Framework 6 and continued to have the issue

A: Looking at the Error List Warnings after attempting an "Update Model from Database" I now see:

Error 6005: The data type 'geometry' is currently not supported for the target Entity Framework version; the column 'test_geometry' in the table 'def.spatialdb.routegeometry' was excluded.

This is using latest Entity Framework 6, so I guess it's not possible using code-first only.
Possible solution would be to edit the auto-generated classes to add the DBGeometry properties, but those would get blown away every time the model is updated.


text:
Q: how to search camel case data in oracle database search query? this is my search query
Below search query returns products Because 'iPhone' is case sensitive
SELECT productname,id FROM products where productname LIKE '%iPhone%'

Below search query returns ZERO products Because 'iPhone' is case sensitive
SELECT productname,id FROM products where productname LIKE 'IPHONE%' or  productname LIKE '%iphone%'

If i used UPPER or LOWER function it returns zero, so how can I solve this issue ?
How Can I solve camel case sensitive data in oracle database query. I can not change the product name in database. Anyone have solution for this ?
If you have doubt in my question please ask me I will instant reply

A: SELECT productname, id
FROM products
WHERE LOWER(productname) LIKE LOWER('%iPhone%')

should return something. Note LOWER function on both sides of LIKE.


text:
Q: Use of term rewriting in decision procedures for bit-vector arithmetic I am working on a project whose focus is the use of term rewriting to solve/simplify fixed-size bit-vector arithmetic problems, which is something useful to do as a prior step to some decision procedure such as those based on bit-blasting. The term rewriting may solve the problem at all, or otherwise produce a much simpler equivalent problem, so the combination of both can result in a considerable speed-up.
I am aware that many SMT solvers implement this strategy (e.g. Boolector, Beaver, Alt-Ergo or Z3), but it is being hard to find papers/tech-reports/etc in which these rewriting steps are described in detail. In general, I only found papers in which the authors describe such simplification steps in a few paragraphs. I would like to find some document explaining in detail the use of term rewriting: providing examples of rules, discussing the convenience of AC rewriting and/or other equational axioms, use of rewriting strategies, etc.
For now, I just have found the technical report A Decision Procedure for Fixed-Width Bit-Vectors which describes normalization/simplification steps performed by CVC Lite, and I would like to find more technical reports like this one! I have also found a poster about Term rewriting in STP but it is just a brief summary.
I have already visited the websites of those SMT solvers and I have searched in their Publications pages...
I would appreciate any reference, or any explanation of how term rewriting is being used in current versions of well-known SMT solvers. I am specially interested in Z3 because it looks to have one of the smartest simplification phases. For instance, Z3 3.* introduced a new bit-vector decision procedure but, unfortunately, I was not able to find any paper describing it.

A: Z3 uses rewriting for many the simplification performed during pre-processing. Many of the rewrite rules used for the UFBV strategy (with quantifiers) are described to some detail in the following paper:
Wintersteiger, Hamadi, de Moura: Efficiently Solving Quantified Bit-Vector Formulas, FMCAD, 2010

A: I agree with you. It is hard to find papers describing the preprocessing steps used in modern SMT solvers.
Most SMT solver developers agree that these preprocessing steps are very important for the Bit-Vector theory.
I believe these techniques are not published for several reasons: most of them a little tricks that by themselves are not a significant scientific contribution; most of the techniques only work in the context of a particular system; a technique that may seem to work very well on solver A, does not work on solver B.
I believe that having open source SMT solvers is the only way to address this issue. Even if we publish the techniques used in a particular solver A, it would be very hard to reproduce the actual behavior of solver A without seeing its source code.
Anyway, here is a summary of the preprocessing performed by Z3, and important details.

*

*Several simplification rules, may reduce this size locally, but increase it globally. A simplifier must avoid the memory blowup caused by this kind of simplification.  You can find examples at: http://research.microsoft.com/en-us/um/people/leonardo/mit2011.pdf

*The first simplification step only performs local simplifications that preserve equivalence.
Examples:

2*x - x ->  x
x and x -> x

*

*Next, Z3 performs constant propagation. Given an equality t = v where v is a value. It replaces t everywhere with v.

t = 0 and F[t]  -> t = 0 and F[0]

*

*Next, it performs Gaussian elimination for Bit-Vectors. However, only variables that occur at most twice in arithmetical expressions are eliminated.
This restriction is used to prevent an increase of the number of adders and multipliers in your formula.
For example, suppose we have x = y+z+w and x occurs at p(x+z), p(x+2*z), p(x+3*z) and p(x+4*z). Then, after eliminating x, we would have p(y+2*z+w), p(y+3*z+w), p(y+4*z+w) and p(y+5*z+w). Although we eliminated x, we have more adders than the original formula.

*Next, it eliminates unconstrained variables. This approach is described by in the PhD thesis of Robert Brummayer and Roberto Brutomesso.

*Then, another round of simplification is performed. This time, local contextual simplifications are performed.
These simplifications are potentially very expensive. So, a threshold on the maximal number of nodes to be visited is used (the default value is 10million).
Local context simplification contain rules such as

(x != 0 or  y = x+1) ->  (x != 0 or y = 1)

*

*Next, it tries to minimize the number of multipliers using distributivity. Example:

ab + ac -> (b+c)*a

*

*Then, it tries to minimize the number of adders and multipliers by applying associativity and commutativity.
Suppose the formula contains the terms a + (b + c) and  a + (b + d). Then, Z3 will rewrite them to: (a+b)+c and (a+b)+d.
Before the transformation, Z3 would have to encode 4 adders. After, only three adders need to be encode since Z3 uses fully shared expressions.

*If the formula contains only equality, concatenation, extraction and similar operators. Then, Z3 uses a specialized solver based on the union-find and congruence closure.

*Otherwise, it bit-blasts everything, uses AIGs to minimize the Boolean formula, and invokes its SAT solver.


text:
Q: Garbage values on extracting values from an array while using MPI I am trying to do a matrix matrix multiplication using a MPI. I am right now using a very hard coded approach. I have initialized an array in the processor ranked 0. I send this array to all the other processors i.e the processor with rank 1 and rank 2.
Now, when I try to extract some information in a temporary array, I am getting some garbage values. I cant figure out why.
Here is the code:
MPI_Init(&argc,&argv);
  MPI_Comm_size(MPI_COMM_WORLD,&world_size);;
  MPI_Comm_rank(MPI_COMM_WORLD,&rank);

  if(rank == 0){
        int mat_a[9] = {1,1,1,2,2,2,3,3,3};
        int mat_b[9] = {1,1,1,2,2,2,3,3,3};
        for(i = 1;i<world_size;i++){
                MPI_Send(&mat_a[0],9,MPI_INT,i,tag,MPI_COMM_WORLD);
                //MPI_Send(&mat_b[0],9,MPI_INT,i,tag,MPI_COMM_WORLD);
        }
  }

  if(rank!=0){
        MPI_Recv(&mat_a[0],9,MPI_INT,0,tag,MPI_COMM_WORLD,&status);
        //MPI_Recv(&mat_b[0],9,MPI_INT,0,tag,MPI_COMM_WORLD,&status);
  }

  for(i = rank;i<9;i=i+3){
        temp_1[num] = mat_a[i];
        num++;
  }
  num = 0;
/*  for(i = rank;i<9;i=i*3){
        temp_2[num] = mat_b[i];
        num++;
  }
  num = 0;
 */
  for(i = 0;i<3;i++){
        printf("in rank %d with val at temp_1 = %d\n",rank,temp_1[i]);
  }

Here is my output:
in rank 0 with val at temp_1 = 550149432
in rank 0 with val at temp_1 = 0
in rank 0 with val at temp_1 = 4965952
in rank 1 with val at temp_1 = 1
in rank 1 with val at temp_1 = 2
in rank 2 with val at temp_1 = 1
in rank 2 with val at temp_1 = 2
in rank 2 with val at temp_1 = 3
in rank 1 with val at temp_1 = 3
Job complete

Please help

A: On rank 0 the scope where mat_a is initialized is limited to the conditional
  if(rank == 0){
        int mat_a[9] = {1,1,1,2,2,2,3,3,3};
        int mat_b[9] = {1,1,1,2,2,2,3,3,3};
        for(i = 1;i<world_size;i++){
                MPI_Send(&mat_a[0],9,MPI_INT,i,tag,MPI_COMM_WORLD);
                //MPI_Send(&mat_b[0],9,MPI_INT,i,tag,MPI_COMM_WORLD);
        }
  }

Out of this scope the variable mat_a is declared not initialized.
That is why the output is correct for processes with positive rank and incorrect on the process with rank=0.
Unfortunately with GCC this mistake would not be recognized. Even though it is clear that the variable is used without initialization.
You can find a complete example at the following link that reproduces this error.
To fix this with minimal changes you might do it as follows:
  if(rank == 0){
        int tmp_a[9] = {1,1,1,2,2,2,3,3,3};
        int tmp_b[9] = {1,1,1,2,2,2,3,3,3};
        for(i=0;i<9;i++) {
                mat_a[i] = tmp_a[i];
                mat_b[i] = tmp_b[i];
        }
        for(i = 1;i<world_size;i++){
                MPI_Send(&mat_a[0],9,MPI_INT,i,tag,MPI_COMM_WORLD);
                //MPI_Send(&mat_b[0],9,MPI_INT,i,tag,MPI_COMM_WORLD);
        }
  }


text:
Q: How to discover through javascript that wcf rest service is stop or not hosted? Created 1 wcf Rest service which return JSON data. Through Javascrip/Jquery (without Asp.net)
want to get status that service is stop or not deploy on localhost.
Tried this :
var xmlhttp =  new XMLHttpRequest();
    xmlhttp.open('GET', "http://host/MP4Convertor%20v1.0.0.0/service.svc/CheckServiceStatus", true);

 xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4||xmlhttp.readyState == 0) {
    //alert("Ready state: " + xmlhttp.readyState.toString());
    if (xmlhttp.status == 200) {
        //alert("good");
        alert("Response: " +xmlhttp.responseText);
    }
    if (xmlhttp.status !=200){
        //alert("bad");
        alert("Error: " +xmlhttp.status.toString() +"  response text:  " +xmlhttp.responseText);
    }
} else {
    alert("readystate bad");
}
 }

xmlhttp.send(null);

and another approach:

    $.ajax({
            cache: false,
            url: "http://host/MP4Convertor%20v1.0.0.0/service.svc/CheckServiceStatus?method=callback",
            type: "GET",
            contentType: "application/javascript",
            dataType: "jsonp",
            error: function (data) {
                alert("list failed!");
            },
            success: function (list) {
                alert(list); // must call function as var
            }
       });

But in both case if service is start or stop in always falls in error case
Can any one Please suggest preferable solutions?
Thanks.


text:
Q: Problem displaying user location on screen I am trying to display user location coordinates on screen but nothing shows up when i run the app even though i can see coordinates in console. And the second problem i have is when i press the stop button the location updates do not stop.
LocationManager:
import Foundation
import CoreLocation

class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate{
    let locationManager = CLLocationManager()
    @Published var location: CLLocationCoordinate2D?

    override init(){
        super.init()
        locationManager.delegate = self
    }

    func startTracking() {
        locationManager.requestAlwaysAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.startUpdatingLocation()
    }

    func stopTracking() {
        print("stop test")
        locationManager.stopUpdatingLocation()
        locationManager.allowsBackgroundLocationUpdates = false
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let tempLocation = locations.last?.coordinate
        print(tempLocation)
        DispatchQueue.main.async {
            self.location = tempLocation
        }
    }
}

View:
import SwiftUI
struct ContentView: View {
    @StateObject var locationManager = LocationManager()

    var body: some View {
        VStack{
            startLocationTrackingButton()
            stopLocationTrackingButton()

            if let location = locationManager.location {
                Text("Your location: \(location.latitude), \(location.longitude)")
            }

        }
    }
}
struct startLocationTrackingButton: View{
    @StateObject var locationManager = LocationManager()

    var body: some View{
        Button("START"){
            locationManager.startTracking()

        }
    }
}
struct stopLocationTrackingButton: View{
    @StateObject var locationManager = LocationManager()

    var body: some View{
        Button("STOP"){
            locationManager.stopTracking()
        }
    }
}

Thanks for help!

A: Each of your views has:
@StateObject var locationManager = LocationManager()

You are creating a different Location manager for each one. Try doing it as:
truct ContentView: View {
    @StateObject var locationManager = LocationManager()

    var body: some View {
        VStack{
            StartLocationTrackingButton(manager: locationManager)
            StopLocationTrackingButton(manager: locationManager)

            if let location = locationManager.location {
                Text("Your location: \(location.latitude), \(location.longitude)")
            }

        }
    }
}
struct StartLocationTrackingButton: View{
    @ObservedObject var manager: LocationManager

    var body: some View{
        Button("START"){
            manager.startTracking()

        }
    }
}
struct stopLocationTrackingButton: View{
    @ObservedObject var manager: LocationManager

    var body: some View{
        Button("STOP"){
            manager.stopTracking()
        }
    }
}

Only use @StateObject when you are creating and owning the object. If you are passing on ObservableObject to another view, then that View should declare it as  @ObservedObject and don't give it an initial value.


text:
Q: P-channel or N-channel MOSFET configuration for safety circuit cutoff I'm working on a hobby project and bought some cheap linear actuators with motors in them. Due to the terrible motor speed/torque, I switched them out.  Now I have to implement a safety feature to kill the power to the motor whenever a limit switch is actuated in the device. (It tears up the device if it goes too far.)
Below is the project setup, but this is what I think i need to do.  I need to a N-channel power MOSFET to control a P-channel MOSFET.  The first one can be this one and will control a 12v current from the power supply to trigger a second MOSFET.  This second one is what will kill the power to the motor whenever a voltage is applied. I think i need to use two because the voltage difference between the arduino and the 12vdc power supply is too much to trigger the P-channel MOSFET by itself quickly enough.
How off am I?  I'm a hobbyist, but i'm trying to design it right before building it.
Project Setup

*

*Arduino board

*12vdc brushed motor that normally pulls 15-20 amps

*H-Bridge Relay from Arduino to motor, for control, but not safety shutoff.
   http://www.vexrobotics.com/217-0220.html

*12vdc power supply

*Linear actuator with gearing and two limit switches at either end of gear.
(If either one is hit, then it breaks the circuit. setup in series.)
Example actuator that looks similar but isn't.

simulate this circuit – Schematic created using CircuitLab
To make it clear: This is a safety shutoff and will only be used to protect the motor from destroying the actuator if there is a bug in the program actuating the device.  I can flip the power manually if the power gets cut because of this new circuit.  I just can't rebuild the gearing.

A: You're doing it the hard way (even ignoring a bunch of craziness and nonsense in your schematic, like shorting the power rails through two switches), because it's really annoying to control a FET in series with a load (the motor) where the voltage is all over the place because of the H-bridge.
The right answer is to leave the motor directly connected to the H-bridge and to control the H-bridge inputs using the limit switches.
What H-bridge are you using?  Its control scheme (ENABLE+DIR?  FWD/REV?) will change how you wire it up.  You don't want to completely disable the motor when an end-stop is hit, you just want to prevent it from continuing in the same direction.
You say "H Bridge Relay", so I'll draw it as a pair of relays:

simulate this circuit – Schematic created using CircuitLab
With this schematic, the motor will be idle by default, will run one way when FWD is pulled up, and will run the other way when REV is pulled up (connect these wires to microcontroller outputs).  If you pull them both up, it will stop.
SW3 and SW4 are your limit switches.  Each one, when open, prevents the motor from running in one direction.  The motor can still run in the other direction though, to allow it to come away from the stops.
If your bridge is something else (some FETs controlled by some fancy silicon?) the control scheme will differ, but the desire is the same: each limit switch prevents the motor from running in a particular direction.
Edit: I see you've posted the H-bridge model number now.  It's mechanical therefore too slow for PWM, but it's also wired pretty much like I've drawn it above, with opto-isolators in place of the transistors I've shown.
If your limit switches are wired together and have only two terminals present, then you can't tell which switch has been hit, so you can't easily make a safe-in-hardware system.  You would need to keep track in software of which direction the motor is running and monitor the limit switch in software.  The software would be responsible for deducing from the motor-direction which limit switch was hit, and if it goes wrong (or the software crashes), your motor will crash into its hard stops.
If your limit switches have a common connection (3 pins), then it's doable like this:

simulate this circuit
The conjugate with NPN transistors would also work but it's less obvious which limit switch affects which end.  Either way, you will need to do some testing+experimenting to make sure that things go in the direction you expect and stop in the correct directions.

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. Test circuit with 2-pole 2-way switch.
You mention in a comment that the limit switches are normally closed and in-series. This is most unusual because once a switch opens you won't know which one and you won't be able to run the motor to move off the switch.
The circuit in Figure 1 shows a more normal setup.

*

*With the switch in the position shown the top of the motor is connected to battery + and the motor will run left until LIMIT-L is pressed.

*When the switch is thrown the battery + is connected to the bottom of the motor and current will return to the battery from the motor top despite LIMIT-L being open at this time. The motor can now run right.

I recommend that you check the limit switches again and see if you can set up and understand a simple circuit like this before moving on to electronic control.
A photo and link to the actuator datasheet would be most useful. Also, note that the switches should be set back a little from the physical end of travel to give space for the motor to decelerate to a stop.

A:
simulate this circuit – Schematic created using CircuitLab
A box is a H-Bridge, RLY1 is a power on relay, Sw1,2 are limit switches and a button Safety override is used to switch on manualy to move motor back in case it hit the limit switch.
EDIT: Added start stop button to eliminate the glitch, when limit switches are overdriven on the edge.


text:
Q: JavaScript error (Uncaught SyntaxError: Unexpected end of input) I have some JavaScript code that works in FireFox but not in Chrome or IE.
In the Chrome JS Console I get the follow error:

"Uncaught SyntaxError: Unexpected end of input".

The JavaScript code I am using is:
<script>
 $(function() {
 $("#mewlyDiagnosed").hover(function() {
    $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
 }, function() {
    $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
 });
</script>

It says the error is on the last line which is });

A: In my case, I was trying to parse an empty JSON:
JSON.parse(stringifiedJSON);

In other words, what happened was the following:
JSON.parse("");

A: In my case, it ended up being a simple double quote issue in my bookmarklet, remember only use single quotes on bookmarklets. Just in case this helps someone.

A: This error is mainly caused by empty returned ajax calls, when trying to parse an empty JSON.
To solve this test if the returned data is empty
$.ajax({
    url: url,
    type: "get",
    dataType: "json",
    success: function (response) {

        if(response.data.length == 0){
            // EMPTY
        }else{
            var obj =jQuery.parseJSON(response.data);
            console.log(obj);
        }
    }
});

A: Add a second });.
When properly indented, your code reads
$(function() {
    $("#mewlyDiagnosed").hover(function() {
        $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
    }, function() {
        $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
    });
MISSING!

You never closed the outer $(function() {.

A: http://jsbeautifier.org/ is helpful to indent your minified JS code.
Also, with Google Chrome you can use "pretty print". See the example screenshot below showing jquery.min.js from Stack Overflow nicely indented right from my browser :)

A: I got this error when I was trying to write a javascript bookmarklet. I couldn't figure out what was causing it. But eventually I tried URL encoding the bookmarklet, via the following website: http://mrcoles.com/bookmarklet/ and then the error went away, so it must have been a problem with certain characters in the javascript code being interpreted as special URL control characters.

A: Formatting your code a bit, you have only closed the inner hover function.  You have not closed the outer parts, marked below:
$(// missing closing)
 function() { // missing closing }
     $("#mewlyDiagnosed").hover(
        function() {
            $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
        },
        function() {
            $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
        });

A: In my case, it was caused by a missing (0) in javascript:void(0) in an anchor.

A: I got this since I had a comment in a file I was adding to my JS, really awkward reason to what was going on - though when clicking on the VM file that's pre-rendered and catches the error, you'll find out what exactly the error was, in my case it was simply uncommenting some code I was using.

A: I also got this error pointing to the end of the last script block on a page, only to realize the error was actually from clicking on an element with a onclick="pagename" instead of onclick="window.location='pagename'". It's not always a missing bracket!

A: I think it could be almost any javascript error/typing error in your application.
I tried to delete one file content after another and finally found the typing error.


text:
Q: Efficient boost distribution usage (Rephrased the question)
I'm creating a wrapper class for boost normal distribution, and want to make it as efficient as possible.
If I use:
double x = 0.0;
boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor(rng, nd);
for (int i=0; i<20; i++) {
     double x = var_nor();
}

The loop works fine. My concern is that I don't want to be declaring anything unnecessarily as the method gets called many times. I tried splitting up the code and put this line in the constructor:
boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor(rng, nd);

and have a sample method that does this:
     double x = var_nor();
     return x;

But in this case, I get an error saying var_nor() (ie. with no arguments) is not found.
Can anyone tell me what's going on with these boost declarations ie. what does the

boost:variate_generate etc.

line actually do in with var_nor?
With my limited C++ knowledge, it looks as if var_nor is being defined with two different signatures.
Thanks guys
Pete

A: In your code, var_nor is a variable, not a function, so it doesn't have a signature. It represents a variate_generator object that can behave like a function because it supports operator().
In your code, you declare and initialize var_nor at the same time. The rng and nd arguments are passed to the constructor of the variate_generator object.
When you moved the declaration into your class's constructor, you were declaring var_nor as a local variable in the constructor, so it's no wonder it wasn't available elsewhere. For something to be available throughout an entire class, it needs to be a member variable. Declare it private in the class:
class NormalDistribution
{
  boost::random::mt19937 _rng;
  boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor;
public:
  NormalDistribution();
};

Then initialize it in the constructor:
NormalDistribution::NormalDistribution():
  _rng(), var_nor(_rng, boost::normal_distribution<>(0.0, 1.0))
{ }

The _rng member needs to be declared first so that it will be initialized first. The nd parameter can be omitted and replaced with a temporary normal_distribution object passed directly to the var_nor constructor as shown above.
With those changes, you should be able to use the same normal_distribution object over multiple calls to your sample function, or whatever other uses you have for your NormalDistribution class.
In the code you've since deleted from your question, you were confusing variable declarations with function declarations. You declared nd as a function receiving two parameters and returning a normal_distribution. Likewise with var_nor. It was a function when you really wanted an object. You were confused because it happens to be an object that acts like a function, but it's still just an object.

A: OK, working final version using Rob Kennedy's answer, for others that might be interested:
// normaldistribution.h
#ifndef NORMALDISTRIBUTION_H
#define NORMALDISTRIBUTION_H

#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
class NormalDistribution
{
 public:
    NormalDistribution();
    double sample(void);
 private:
    // Use the boost random number generator
    boost::mt19937 rng;
    // Make a variate_generator OBJECT.
    boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor;
};

#endif // NORMALDISTRIBUTION_H

// normaldistribution.cpp
NormalDistribution::NormalDistribution():
  rng(), var_nor(rng, boost::normal_distribution<>(0.0, 1.0))
{
    std::cout << "Called normal distribution constructor, passing up var_nor" << std::endl;
}

double NormalDistribution::sample(void) {
    double x = var_nor();
    return x;
}

// main.cpp
#include "normaldistribution.h"

int main(int argc, char *argv[])
{
    NormalDistribution *nd = new NormalDistribution();
    for (int i=0; i < 10; ++i)
    {
      double d = nd->sample();
      std::cout << d << std::endl;
    }
    return 0;
}


text:
Q: Why is an integer literal followed by a dot a valid numeric literal in JavaScript? In JavaScript it is valid to end an integer numeric literal with a dot, like so...
x = 5.;

What's the point of having this notation? Is there any reason to put the dot at the end, and if not, why is that notation allowed in the first place?
Update: Ok guys, since you mention floats and integers... We are talking about JavaScript here. There is only one number type in JavaScript which is IEEE-754.
5 and 5. have the same value, there is no difference between those two values.

A: I guess it is just compatibility with other C-like languages where the dot does matter.

A: You DO need the decimal point if you call a method on an integer:
5.toFixed(n) // throws an error

5..toFixed(n) // returns the string '5.' followed by n zeroes

If that doesn't look right, (5).toFixed(n), or 5.0.toFixed(n), will work, too.

A: That's a floating point number. Unlike any other language I've ever encountered, all numbers in Javascript are actually 64-bit floating numbers. Technically, there are no native integers in Javascript. See The Complete Javascript Number Reference for the full ugly story.

A: The correct answer in this case is, that it makes absolutely no difference.
Every number in JavaScript is already a 64bit floating point number.
The ". syntax" is only useful in cases where you can ommit the fixed part because it's 0:
.2 // Will end up as 0.2
-.5 // Will end up as -0.5

So overall it's just saving a byte, but it makes the code less readable at the same time.

A: What if it wouldn't be an integer, but a floating point literal?


text:
Q: GPS location not displayed on button click I am trying to get the gps location through a button click.
The code is given below :
MainActivity.java
public class MainActivity extends AppCompatActivity {

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

protected LocationManager locationManager;

protected Button retrieveLocationButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;

    }

    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MINIMUM_TIME_BETWEEN_UPDATES,
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );

    retrieveLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
    });

}

protected void showCurrentLocation() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;
    }
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();
    }

}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}

}
The problem here is that the Toast is not getting displayed where the location i.e. latitude and longitude is displayed. I have added the runtime permission for API level 23. I have also added the following permissions in the manifest file :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Thank you for your help :)

A: I solved it by adding onRequestPermissionsResult.. above the MyLocationListener class. The code below is the corrected code :
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

protected LocationManager locationManager;

protected Button retrieveLocationButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;

    }

    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MINIMUM_TIME_BETWEEN_UPDATES,
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );

    retrieveLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
    });

}

protected void showCurrentLocation() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1252);
        }
        return;
    }
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode==1252){
        if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
            Log.i("Permission Granted : ", String.valueOf(grantResults));

        }
    }
}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}

}
Thank you @Pavneet_Singh


text:
Q: .htaccess wont work in Ubuntu 14.04 Even with mod_rewrite Iv'e tried everything, I enabled rewrite module, messed around with the apache config and still my server will not add the .php extension automatically. It just keeps showing a 404 error.
BTW, I have this setup on a virtual host.
Here's my Apache config:
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port th$
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/ce

        ServerName computingessentials.tk
        ServerAlias www.computingessentials.tk

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
         <Directory /var/www/ce/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Require all granted
         </Directory>
        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

And here is my htaccess
RewriteEngine on

RewriteRule ^([0-9a-zA-Z-]+)$ $1.php [NC,L]
RewriteRule ^([0-9a-zA-Z-]+)/$ $1.php [NC,L]

RewriteRule ^videos/([0-9a-zA-Z-]+)$ videos.php?var=$1 [NC,L]
RewriteRule ^article/([0-9a-zA-Z-]+)$ article.php?var=$1 [NC,L]
RewriteRule ^video/([0-9a-zA-Z-]+)$ video.php?var=$1 [NC,L]

For example, there is a page called series.php, which should get replaced to /series but when I go to /series, it says file not found.
And you will not be able to access the server since at the moment I have setup my host files to redirect me to the IP.
Tagged In: Getting Started, Apache, DigitalOcean Articles, DNS, PHP, System Tools, Ubuntu

A: Firstly, in Ubuntu 14.04 (and Apache 2.4) the default DocumentRoot was changed from /var/www to /var/www/html
Your Config file says <Directory /var/www/ce/>
Try changing it to default

A: Try your code this way and check for the existence of your file.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([0-9a-zA-Z-]+)/?$ $1.php [NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^videos/([0-9a-zA-Z-]+)$ videos.php?var=$1 [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^article/([0-9a-zA-Z-]+)$ article.php?var=$1 [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^video/([0-9a-zA-Z-]+)$ video.php?var=$1 [NC,L]


text:
Q: Replace and += is abismally slow I've made following code that deciphers some byte-arrays into "Readable" text for a translation project.
with open(Path(cur_file), mode="rb") as file:
    contents = file.read()
    file.close()

text = ""
for i in range(0, len(contents), 2): # Since it's encoded in UTF16 or similar, there should always be pairs of 2 bytes
    byte = contents[i]
    byte_2 = contents[i+1]
    if byte == 0x00 and byte_2 == 0x00:
        text+="[0x00 0x00]"
    elif byte != 0x00 and byte_2 == 0x00:
        #print("Normal byte")
        if chr(byte) in printable:
            text+=chr(byte)
        elif byte == 0x00:
            pass
        else:
            text+="[" + "0x{:02x}".format(byte) + "]"
    else:
        #print("Special byte")
        text+="[" + "0x{:02x}".format(byte) + " " + "0x{:02x}".format(byte_2) + "]"
# Some dirty replaces - Probably slow but what do I know - It works
text = text.replace("[0x0e]n[0x01]","[USERNAME_1]") # Your name
text = text.replace("[0x0e]n[0x03]","[USERNAME_3]") # Your name
text = text.replace("[0x0e]n[0x08]","[TOWNNAME_8]") # Town name
text = text.replace("[0x0e]n[0x09]","[TOWNNAME_9]") # Town name
text = text.replace("[0x0e]n[0x0a]","[CHARNAME_A]") # Character name

text = text.replace("[0x0a]","[ENTER]") # Generic enter

lang_dict[emsbt_key_name] = text

While this code does work and produce output like:
Cancel[0x00 0x00]

And more complex ones, I've stumbled upon a performance problem when I loop it through 60000 files.
I've read a couple of questions regarding += with large strings and people say that join is preferred with large strings. However, even with strings of just under 1000 characters, a single file takes about 5 seconds to store, which is a lot.
I almost feel like it's starts fast and gets progressively slower and slower.
What would be a way to optimize this code? I feel it's also abysmal.
Any help or clue is greatly appreciated.
EDIT: Added cProfile output:
         261207623 function calls (261180607 primitive calls) in 95.364 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    284/1    0.002    0.000   95.365   95.365 {built-in method builtins.exec}
        1    0.000    0.000   95.365   95.365 start.py:1(<module>)
        1    0.610    0.610   94.917   94.917 emsbt_to_json.py:21(to_json)
    11179   11.807    0.001   85.829    0.008 {method 'index' of 'list' objects}
 62501129   49.127    0.000   74.146    0.000 pathlib.py:578(__eq__)
125048857   18.401    0.000   18.863    0.000 pathlib.py:569(_cparts)
 63734640    6.822    0.000    6.828    0.000 {built-in method builtins.isinstance}
   160958    0.183    0.000    4.170    0.000 pathlib.py:504(_from_parts)
   160958    0.713    0.000    3.942    0.000 pathlib.py:484(_parse_args)
    68959    0.110    0.000    3.769    0.000 pathlib.py:971(absolute)
   160959    1.600    0.000    2.924    0.000 pathlib.py:56(parse_parts)
    91999    0.081    0.000    1.624    0.000 pathlib.py:868(__new__)
    68960    0.028    0.000    1.547    0.000 pathlib.py:956(rglob)
    68960    0.090    0.000    1.518    0.000 pathlib.py:402(_select_from)
    68959    0.067    0.000    1.015    0.000 pathlib.py:902(cwd)
       37    0.001    0.000    0.831    0.022 __init__.py:1(<module>)
   937462    0.766    0.000    0.798    0.000 pathlib.py:147(splitroot)
    11810    0.745    0.000    0.745    0.000 {method '__exit__' of '_io._IOBase' objects}
   137918    0.143    0.000    0.658    0.000 pathlib.py:583(__hash__)

EDIT: Upon further inspection with line_profiler, turns out that the culprit isn't even in above code. It's well outside that code where I read search over the indexes to see if there is +1 file (looking ahead of the index). This apparently consumes a whole lot of CPU time.

A: Just in case it provides you pathways to search, if I was in your case I'd do two separate checks over 100 files for example timing:

*

*How much time it takes to execute only the for loop.

*How much it takes to do only the six replaces.

If any takes most of the total time, I'd try to find a solution just for that bit.
For raw replacements there are specific software designed for massive replacements.
I hope it helps in some way.

A: You might use .format to replace += and + following way, let say you have code like this
text = ""
for i in range(10):
    text += "[" + "{}".format(i) + "]"
print(text)  # [0][1][2][3][4][5][6][7][8][9]

which is equvialent to
text = ""
for i in range(10):
    text = "{}[{}]".format(text, i)
print(text)  # [0][1][2][3][4][5][6][7][8][9]

Observe that other string formatting ways might be used as above, I elected to use .format as you are already using it.

A: Turns out, prior to this I was looking up a entry in my list (on each iteration) with the index method +1 (to see if there was a path change), which really did bog down the performance.
In the cProfile we can clearly see it:
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
11179   11.807    0.001   85.829    0.008 {method 'index' of 'list' objects}

It wasn't .replace! It wasn't even included in my question.
What really made me understand what this call was (other than it called index somehow), was another profiler:

I believe that's what Robert Kern's line_profiler is intended for.

Source: https://stackoverflow.com/a/3927671/3525780
It showed me neatly, line-by-line, which code consumed how many CPU-cycles/time, much neater than cProfile.
Once I found out, I replaced it with:
for ind, cur_file in enumerate(to_write):
        next_file = None
        if ind < len(to_write) - 1:
            next_file = to_write[ind+1]

This answer probably doesn't make much sense without the actual code, but I will leave it here nonetheless.


text:
Q: Why won't opacity change on .mouseleave() event? In the following code, the .mouseover() portion works fine, but some funny things are happening when .mouseleave() portion is trigged.  For one, the opacity of '.step_details'is not resetting.  I have tried using both .animate() and .css() to reset the opacity to 0 with no success.  Any thoughts on why this might be?
$('.step').mouseover(function() {
    $(this).css({'border': 'solid #CCC 1px', 'background-color': '#FFF'})
        .animate({'margin-top': '0', height: '300px'}, 500);
    $(this).children('.step_details').css('display', 'block')
        .animate({opacity: 1},700);
})

$('.step').mouseleave(function() {
    $(this).css({'border': 'none', 'background-color': 'inherit'})
        .animate({'margin-top': '150px', height: '150px'}, 200);
    $(this).children('.step_details').css({'display': 'none', 'opacity': 0});
})

Also, there is an inconsistent delay between the resetting of the border/background and the start of the animation that resets the top margin and the height of '.step'.  This seems to imply that the opacity problem may just be a symptom of me misusing the .mouseleave() event trigger.  What am I doing wrong? Is there a better way I should be doing this?
Thanks for reading!

A: http://jsfiddle.net/DXgr8/1/
You're missing .stop()
$('.step').mouseenter(function() {
    $(this).css({border: 'solid #CCC 1px', backgroundColor: '#FFF'})
        .stop().animate({marginTop: '0', height: '300px'}, 500);
    $(this).children('.step_details').stop().animate({opacity: 1},700);
}).mouseleave(function() {
    $(this).css({border: 'none', backgroundColor: 'inherit'})
        .stop().animate({marginTop: '150px', height: '150px'}, 200);
    $(this).children('.step_details').stop().animate({opacity: 0},200);
});

NB anyone testing this, the div hides but is still there to hover, just further down than it was

A: The opacity won't change because the animation sets display:none which is a binary switch to not show that element, any opacity changes won't be seen. However, fadeIn and fadeOut are a good solution for what you're doing.
demo jsfiddle
$('.step').hover(function() { // mouse enter

  $(this).animate({
      'margin-top': '0',
      height: '300px'
  }, 500).children('.step_details').fadeIn(700);

}, function() { // mouse leave

  $(this).animate({
    'margin-top': '150px',
    height: '150px'
  }, 200).children('.step_details').fadeOut(200);

});

the border/background changes can be handled in the CSS using the :hover pseudo-class
.step {
  margin-top:150px;
  border:none;
  background-color:#eee;
}
.step:hover {
  border:solid #CCC 1px;
  background-color:#fff;
}


text:
Q: Image not displaying from local html on iPhone webview I am calling an infoPage.html as below with an image from Resources and referenced as img src="eye.png" in the html, the text displays correctly but I cannot load the image (only a ? appears), any suggestions...
- (void)viewDidLoad {

 [super viewDidLoad];

 CGRect webRect = CGRectMake(15,40,300,450);
 UIWebView *myWebView = [[UIWebView alloc] initWithFrame:webRect];

 myWebView.delegate = self;

 myWebView.scalesPageToFit = NO;
 NSString *htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"infoPage.html"];
 NSString *htmlContent = [NSString stringWithContentsOfFile:htmlPath];
 [myWebView loadHTMLString:htmlContent baseURL:nil];

 //stop webview from scrolling
 [[[myWebView subviews] lastObject] setScrollingEnabled:NO];

 [myWebView loadHTMLString:htmlContent baseURL:nil];

 [self.view addSubview:myWebView];

 [myWebView release];
}

A: You need to use [myWebView loadRequest: [NSURLRequest requestWithURL: [NSURL fileURLWithPath: htmlPath]]], rather than -loadHTML so that it knows where to extract images from. Alternatively, you could pass the path in as the baseURL: argument.

A: Instead of baseURL:nil, try baseURL:[NSURL URLWithString:[[NSBundle mainBundle] bundlePath]]]


text:
Q: Get autoscaling name from ecs ec2 instances I have an ECS cluster, I want to stop those instance and it may be either autoscaling or not... so I started to create a script like this.
import boto3

CLUSTER='BBB'
ec2 = boto3.client('ec2')
ecs = boto3.client('ecs')

ci_list_response = ecs.list_container_instances(
    cluster=CLUSTER )

ci_descriptions_response = ecs.describe_container_instances(
    cluster=CLUSTER,
    containerInstances=ci_list_response['containerInstanceArns'] )

for ci in ci_descriptions_response['containerInstances']:
    print(ci['ec2InstanceId'])

I am able to get a list of ec2-instance ids, but struggling to get those instance's autoscale information. Please share your thoughts if any to resolve this.

A: ec2_client.describe_instances(instanceId)
In the response look for requesterId, that should give you the required information
https://boto3.readthedocs.io/en/latest/reference/services/ec2.html


text:
Q: Marker move According to Route MapBox I have two annotations. There is an image on annotation. I want the image head toward route in MapBox.
Here is what I have tried:
func drawAnnoation (orgin :CLLocationCoordinate2D ,destination :CLLocationCoordinate2D){
        if annotation == nil {
         annotation = CameraAnnotation(coordinate: orgin, title: "SOURCE", subtitle: "D", image:"selfImage" )
            let source = orgin
        annotation.coordinate = source
        annotation.title = "ddd"

            map.setCenter(orgin, zoomLevel: 18, animated: false)
        map.addAnnotation(annotation)
        } else {
            UIView.animate(withDuration: 1.5, animations: {
                // Here Core Animation calls MapBox using an implicit animation.
                self.annotation.coordinate = orgin

            })
        }
        if annotations == nil {
        let annotations = NoteAnnotation(coordinate: destination, title: "DESTINATION", subtitle: "E", image: "car")
        let sources = destination
        annotations.coordinate = sources
        annotations.title = "d"
        map.addAnnotation(annotations)
        }
    }

func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
        guard annotation is CameraAnnotation || annotation is NoteAnnotation else {
            return nil
        }
        if annotation is CameraAnnotation {

            return dview
        } else {

            return sdview
        }
   }

Please help how to achieve this.

A: you mean that it looks like Uber ...when route is moving then simultaneously your annotation should be processed.
i suppose that you need to use Socket for iOS in which you can get lat and long continoulsy from socket and then set the lat and long with annotation .
let source = CLLocation(latitude: Socket_latitiude_value, longitude: Socket_longitude_value)
if annotations == nil {
        let annotations = NoteAnnotation(coordinate: sources , title: "DESTINATION", subtitle: "E", image: "car")
        annotations.coordinate = sources
        annotations.title = "d"
        map.addAnnotation(annotations)
        }


text:
Q: How to do a proper Linux server backup to store apps installed and configurations? I am familiar with using rsync for backups on Linux. However, in the event of a hard disk crash, I have been repeatedly told that with a new disk, install a latest version of the OS, then the data created (word processing files, accounting, etc.) then you are back to normal. However, what about all the configuration files stored in /etc and elsewhere? What about the applications I installed which were not part of a yum repo? I don't believe they can simply be copied back over a new installation or on different hardware without overwriting needs files by the OS?
I would greatly appreciate and kind and thoughtful reply to this, because this problem truly bothers me. I don't want to spend a day or two rebuilding a system by trying to remember which configurations need to be changed, cron jobs, applications installed, scripts, etc.
In addition, how do a document what has been installed on a Linux server? Sometimes you install a script, works great, and easily forget it was there. What should the method be? Create a "logbook" of all changes done to the server including each application? Sounds like there needs to be a better method.
Or should I not be using rsync for full backups like this, and look at something else which might do a bare metal store? Thanks in advance for your helpful reply!

A: I use a run book, based on this old Microsoft TechNet article for SQL Server 2000.

Contents of a Run Book
A run book should contain all of the information you and your staff
need to perform day-to-day operations and to respond to emergency
situations. This information should include the following:

*

*Resource information about the data center and its hardware and
software

*Process information, including step-by-step procedures for operational
and emergency processes
The run book should contain all necessary information to enable a
staff member to perform any process, from performing a backup to
failing over to a remote site.

A: I use two strategies, depending on time, space and resources:
1) Physically mirror the disk (drop to single user mode and "cp /dev/sda /dev/sdb") and keep the drive somewhere else.
2) I use Mondo Rescue which creates bootable restore images which rebuilds the system back to the same state is was when I ran the backup.
Method (2) is faster for large drives that are not full of data. (1) is more reliable if the drives are identical.


text:
Q: Web server for testing POST requests I am developing part of an application which will POST requests to another server, and examine the request as the web server would see it.
Is there any web server that I can set up (quickly and easily) that will allow me to view the requests to it, and return a sensible code. It doesn't need to process the data in any way. It basically just for development / testing purposes.

A: You can use REST-client tool to observe the performance.


text:
Q: Universal web-safe fonts Old issue. I can't get over the fact that Chrome and Firefox under Android 7.0 fail to correctly display text having this styling:
.st8{font-family:'Times New Roman', Times, serif; font-size:19px;}

for an SVG element having text tag <text transform="matrix(1 0 0 1 61.6089 161.1328)" class="st8">Водород</text>.
The page I'm working with. The text "Водород" on Android gets converted to Arial, I guess. Not Times New Roman.
Despite the font being web-safe.
I need the font to be exactly the same on various platforms. Otherwise, if it reverts to some Arial, the layout looks assymetrical.
Another font Georgia, for some reason renders just about fine on Android.
Any suggestions?
After edit.
As I see it, if w3 and w3schools.com present a list of the most common web-safe fonts, then it has to be working no matter the browser. Well, I wish it. Why would then w3schools teach or show standards which are not adopted by everybody?
To me, it would make more sense if Google expanded its collection of fonts with 5 most common Windows/Apple fonts and added those to its Android system. Would be fair. A pareto-optimal exchange.
Google easily takes advantage of proprietory Arial font (read Windows-based font) in its Google docs apps, but fails to integrate Windows based fonts in its Android system. Wiki article on Arial font - https://en.wikipedia.org/wiki/Arial

A: Try using: fonts.google.com
The most popular fonts (Open Sans, Roboto, Montserrat, etc.) usually have multiple language support.


text:
Q: Improve my "From NAND to Tetris" ALU in VHDL I'm following the course From NAND to Tetris, but instead of using the author's software, I'm trying to directly program a Spartan 6 FPGA. I'm now solving the ALU exercise, and ended up writing the following code (disclaimer: I started learning VHDL yesterday):
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity alu is
    Port (x  : in  STD_LOGIC_VECTOR(15 downto 0);
          y  : in  STD_LOGIC_VECTOR(15 downto 0);

          zx : in  STD_LOGIC;
          nx : in  STD_LOGIC;
          zy : in  STD_LOGIC;
          ny : in  STD_LOGIC;
           f : in  STD_LOGIC;
          no : in  STD_LOGIC;

          output : out STD_LOGIC_VECTOR(15 downto 0);
          zr     : out STD_LOGIC;
          ng     : out STD_LOGIC);

             constant zeros: STD_LOGIC_VECTOR(15 downto 0) := "0000000000000000";
end alu;

architecture Behavioral of alu is
begin
    op: process(x, y, zx, nx, zy, ny, f, no)
      variable px: STD_LOGIC_VECTOR(15 downto 0);
      variable py: STD_LOGIC_VECTOR(15 downto 0);
      variable po: STD_LOGIC_VECTOR(15 downto 0);
    begin
      px := x;
      py := y;

      px := zeros   when (zx = '1');
      px := not(px) when (nx = '1');
      py := zeros   when (zy = '1');
      py := not(py) when (ny = '1');

      if (f = '1') then
        po := (px + py);
      else
        po := (px AND py);
     end if;

      po := not(po) when (no = '1');
      output <= po;

     if (po = zeros) then
        zr <= '1';
      else
        zr <= '0';
      end if;

      ng <= po(0);
    end process;
end Behavioral;

I'm now wondering if there is a simpler way to achieve the same thing, considering:

*

*(VHDL) Good practices;

*(VHDL) Code size;

*Using as little sequential logic as possible;

*Synthesis size.

A:
(VHDL) Good practices;

It's a lot easier meeting timing if you make each entity synchronous - give it a clock (and reset if necessary) and write a clocked process.  You then also don't have to worry about keeping sensitivity lists up to date.
Note this:
use IEEE.STD_LOGIC_UNSIGNED.ALL;

Don't use that - although it's better behaved than std_logic_arith.  Use ieee.numeric_std.all; instead and then use the appropriate types for your vectors.
Use of variables - that's a good sign in my book.  Keeps local things very local.
You could size your variables automatically:
variable px : std_logic_vector(x'range);

and your constant (which you could move to the architecture, which would be more conventional):
constant zeros: STD_LOGIC_VECTOR(x'range) := (others => '0');

(VHDL) Code size

I'm not sure you could save that much code without losing readability

Using as little sequential logic as possible;

Why?  Flipflops are almost free in FPGAs.  I almost always run out of LUTs first.

Synthesis size

It's not often that the code has the biggest influence on synthesis size.  It's higher level things like parallel (lots of logic) vs. sequential (a little logic in turn - but don't forget the state machine controlling it can be an overhead).