text:
Q: Sessions in Codeigniter I am using sessions to store data from my multi step form so that when the user completes all three sections of the form then the information is inserted in to the database. I have built the form so that the user can go back to any stage and modify the information they have submitted, the thing is though, the values that repopulate the form are stored in sessions so if the user leaves the form page and goes elsewhere in the website and then returns to the form the information is still in the form…is there a better way to do this? I want the data destroyed if they leave the form…
Thanks

A: Assuming your form exists only in one controller and isn't spread across multiple ones, you could simply unset all session values in the __construct of every other controller. (You could extend the base controller if you have lots to save the hassle of adding this functionality to many.
That way if the user visits another section, the values will be lost, but providing they remain within the "form" they can remain intact.

A: You could with JavaScript and the unload event, but it'll prove tricky since unload may fire with each "section" of the form.


text:
Q: Vector field on the unit sphere Let $\vec\psi$ be the vector field defined on the unit sphere $S^2$ in the basis $(\vec e_r,\vec e_\theta,\vec e_\varphi)$ of spherical coordinates by:
$$\vec\psi(r=1,\theta,\varphi)=(0,\sin\varphi,0)$$
I want to determine the integral curves of $\vec\psi$.
So I solve the system $$\begin{cases}\dfrac{dr}{dt}=0\\ \dfrac{d\theta}{dt}=\sin \varphi \\
\dfrac{d\varphi}{dt}=0 \end{cases}$$
and the integral curves are given by: $r(t)=c_1$, $\varphi(t)=c_2$ and $\theta(t)=\sin(c_2)t+c_3$ where $c_1,c_2,c_3$ are any constant numbers.
Is this correct and is there any physical phenomena that can be described by such a vector field ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Class member behave differently when define as static or non static I have WPF application with PcapDotNet DLL's that measure my machine Interface Rate.
This is the Model:
public class Interface
{
    public PacketDevice PacketDevice { get { return livePacketDevice; } }
    private DateTime _lastTimestamp;
    private double _bitsPerSecond;
    private double _packetsPerSecond;
    private DateTime _lastTimestamp;
    private static List<Interface> _machineInterfaces; // list of all machine interfaces

    public void Start(Interface inf)
    {
        OpenAdapterForStatistics(inf.PacketDevice);
    }

    public void OpenAdapterForStatistics(PacketDevice selectedOutputDevice)
    {
        if (selectedOutputDevice != null)
        {
            using (PacketCommunicator statCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the output adapter
            {
                try
                {
                    statCommunicator.Mode = PacketCommunicatorMode.Statistics; //put the interface in statstics mode
                    statCommunicator.ReceiveStatistics(0, StatisticsHandler); //start the main loop
                }
                catch (Exception)
                { }
            }
        }
    }

    private void StatisticsHandler(PacketSampleStatistics statistics)
    {
        DateTime currentTimestamp = statistics.Timestamp; //current sample time
        DateTime previousTimestamp = _lastTimestamp; //previous sample time
        _lastTimestamp = currentTimestamp; //set _lastTimestamp for the next iteration

        if (previousTimestamp == DateTime.MinValue) //if there wasn't a previous sample than skip this iteration (it's the first iteration)
            return;

        double delayInSeconds = (currentTimestamp - previousTimestamp).TotalSeconds; //calculate the delay from the last sample
        _bitsPerSecond = statistics.AcceptedBytes * 8 / delayInSeconds; //calculate bits per second
        _packetsPerSecond = statistics.AcceptedPackets / delayInSeconds; //calculate packets per second

        if (NewPointEventHandler != null)
            NewPointEventHandler(_bitsPerSecond);
        double value = _packetsPerSecond;
    }

As you can see Start method start to measure the Interface rate and put the values into 2 fields:
_bitsPerSecond and _packetsPerSecond.
So after the application start i have this field:
List<Interface> _machineInterfaces;

That read all my machine interfaces.
After that i start my Start method:
    private void StartStatistics()
    {
        int index = listview.SelectedIndex; // select the selected interface from my `ListView` list.
        Interface inf = new Interface();
        ThreadStart tStarter = delegate
        {
            inf.Start(Interface.MachineInterfaces[index]); // send the selected interface
        };
        Thread thread = new Thread(tStarter);
        thread.IsBackground = true;
        thread.Start();

        statisticsTimer.Start(); // start my timer
    }

*

*OK so now this is my Question:

This is my Timer Tick Event:
public RadObservableCollection<double> mbitPerSecondValue { get; private set; }

If my BitsPerSecond Class Interface member define as regular and not Static it's  value is always zero:
    private void statisticsTimer_Tick(object sender, EventArgs e)
    {
        int index = listview.SelectedIndex;

        double bps = Interface.MachineInterfaces[index].BitsPerSecond; // always zero !
        mbitPerSecondValue.Add(bps);
    }

In case BitsPerSecond define as static all good:
    private void statisticsTimer_Tick(object sender, EventArgs e)
    {
        int index = listview.SelectedIndex;
        double bps = Interface.BitsPerSecond;
        mbitPerSecondValue.Add(bps);
    }

So my question is why ?
Edit
Currently i changed my function:
private void StartStatistics()
        {
            int index = lvAdapters.SelectedIndex;
            Interface inf = new Interface();
            ThreadStart tStarter = delegate
            {
                foreach (Interface item in Interface.MachineInterfaces)
                    item.Start();
            };

            Thread thread = new Thread(tStarter);
            thread.IsBackground = true;
            thread.Start();

            statisticsTimer.Start();
        }

What i want to achieve is to open statistics on each interface on my machine , but again in the first interface (i have 2) i can see the traffic changing (BitsPerSecond) but in the second interface it's always zero (i make sure to generate some traffic through this interface so it not supposed to be zero)

A: For your second question, try to call each Interface's Start from different threads. The only suspicious thing I see is that maybe statCommunicator.ReceiveStatistics is blocking the thread and preventing the other Interfaces from being Started.
This should avoid that problem:
private void StartStatistics()
{
    foreach (Interface item in Interface.MachineInterfaces)
    {
        ThreadStart tStarter = delegate
        {
            item.Start();
        };

        Thread thread = new Thread(tStarter);
        thread.IsBackground = true;
        thread.Start();
    }

    statisticsTimer.Start();
}

A: Well, it's obvious why it's working when defined as static: all instances of Interface are sharing the same property, so when you increment its value from one place, the new value is automatically available everywhere.
But as a regular non-static property, you have to make sure you're reading from the same instance you've previously modified. And you're not.
First of all, you're creating a new Interface (let's call it Interface A) and then calling its Start, passing another Interface (that we'll call Interface B) that you get from Interface.MachineInterfaces, as parameter:
private void StartStatistics()
{
    ...
    Interface inf = new Interface();
    ThreadStart tStarter = delegate
    {
        inf.Start(Interface.MachineInterfaces[index]); // send the selected interface
    };
    ...
}

Inside the Start method of Interface A, you're subscribing to the statistics of Interface B, but the handler is still in Interface A:
public void Start(Interface inf)
{
    OpenAdapterForStatistics(inf.PacketDevice);
}

public void OpenAdapterForStatistics(PacketDevice selectedOutputDevice)
{
    ...
    statCommunicator.ReceiveStatistics(0, StatisticsHandler); //start the main loop
    ...
}

And when the handler in Interface A is called, it increments its own _bitsPerSecond value. Not Interface B's, but Interface A's.
private void StatisticsHandler(PacketSampleStatistics statistics)
{
    ...
    _bitsPerSecond = statistics.AcceptedBytes * 8 / delayInSeconds; //calculate bits per second
    ...
}

But in the end, you're checking the value of BitsPerSecond in Interface B, taken again from Interface.MachineInterfaces!
private void statisticsTimer_Tick(object sender, EventArgs e)
{
    ...
    double bps = Interface.MachineInterfaces[index].BitsPerSecond; // always zero !
    ...
}

-- SUGGESTED SOLUTION 1 --
Why don't you just make it so Start uses its own instance, so you don't have to create a new Interface just to use it?
public void Start()
{
    OpenAdapterForStatistics(this.PacketDevice);
}

That way you can just do:
private void StartStatistics()
{
    int index = listview.SelectedIndex; // select the selected interface from my `ListView` list.
    ThreadStart tStarter = delegate
    {
        Interface.MachineInterfaces[index].Start(); // send the selected interface
    };
    Thread thread = new Thread(tStarter);
    thread.IsBackground = true;
    thread.Start();

    statisticsTimer.Start(); // start my timer
}

...And you should get the desired output in your Timer Tick callback.
-- SUGGESTED SOLUTION 2 --
If you don't want to call Start from the original Interfaces inside Interface.MachineInterfaces, then you'll have to store the new Interface in some kind of Dictionary, so you can access it later to get BitsPerSecond from it:
private Dictionary<Interface, Interface> InterfaceDictionary = new Dictionary<Interface, Interface>();

private void StartStatistics()
{
    int index = listview.SelectedIndex; // select the selected interface from my `ListView` list.
    Interface inf = new Interface();
    ThreadStart tStarter = delegate
    {
        inf.Start(Interface.MachineInterfaces[index]); // send the selected interface
    };
    Thread thread = new Thread(tStarter);
    thread.IsBackground = true;
    thread.Start();

    statisticsTimer.Start(); // start my timer

    if (InterfaceDictionary.ContainsKey(Interface.MachineInterfaces[index]))
        InterfaceDictionary[Interface.MachineInterfaces[index]] = inf;
    else
        InterfaceDictionary.Add(Interface.MachineInterfaces[index], inf);
}

And in your Timer Tick callback, grab the data from the associated Interface, not from the one in Interface.MachineInterfaces:
private void statisticsTimer_Tick(object sender, EventArgs e)
{
    int index = listview.SelectedIndex;
    var interface = InterfaceDictionary[Interface.MachineInterfaces[index]];
    double bps = interface.BitsPerSecond;
    mbitPerSecondValue.Add(bps);
}


text:
Q: Antlr4 StringTemplate not compatible with Json.net dynamic items I would like to read a dynamic object from a json file and then use this in a stringTemplate.
The following code works.
dynamic data = new { bcName = "Lixam B.V", periodName = "July 2013" };
var engine = new Template("<m.bcName> <m.periodName>");
engine.Add("m", data);
engine.Render().Should().Be("Lixam B.V July 2013");

The following code fails
var json = "{bcName : 'Lixam B.V', periodName : 'July 2013'}";
dynamic data = JsonConvert.DeserializeObject(json);
string name = (data.bcName);
name.Should().Be("Lixam B.V"); // this passes
var engine = new Template("<m.bcName> <m.periodName>");
engine.Add("m", data);
engine.Render().Should().Be("Lixam B.V July 2013"); //fails

Is there another way to configure JsonConverter to be compatible with StringTemplate

A: You need to create an IModelAdaptor for whatever the compiled type representing dynamic is, and register it using TemplateGroup.RegisterModelAdaptor.

A: Inspired on Mr. Harwell's answer, I've implemented an IModelAdaptor that enable the usage of Newtonsoft.Json parsed objects.
Here it goes:
internal class JTokenModelAdaptor : Antlr4.StringTemplate.IModelAdaptor
{
    public object GetProperty(
        Antlr4.StringTemplate.Interpreter interpreter,
        Antlr4.StringTemplate.TemplateFrame frame,
        object obj,
        object property,
        string propertyName)
    {
        var token = (obj as JToken)?.SelectToken(propertyName);
        if (token == null)
            return null;
        if (token is JValue)
        {
            var jval = token as JValue;
            return jval.Value;
        }
        return token;
    }
}

You just need to register the adaptor in your template group, like this:
template.Group.RegisterModelAdaptor(typeof(JToken), new JTokenModelAdaptor());


text:
Q: Minutely cron, ensuring only a single instance Is there a way to run a script every minute (or 2, or 5, etc), but only if it isn't already running?
We have a set of scripts that need to run every minute. Sometimes they might start and finish in a second, other times they might go on for 5 minutes.
Our current way of avoiding simultaneous executions is by setting a is_running flag in each script, and exiting if it's still enabled. But this is a little unreliable (i.e., fatal errors would cause the flag to remain enabled even after the script halted).
We could write our own little manager, but I'm wondering if there is a more fashionable solution that already exists.

A: I would tend to agree with Warner's pid file answer.  However, does the following feature of Anacron accomplish this?
-s
    Serialize execution of jobs. Anacron will not start a new job before the previous one finished.

I haven't tested it myself, I don't find anacron's documentation thorough enough ...
If you want be particularly lazy ;-) You can just have the script exit if greping through ps output returns the process as running. But a lock/pid file is best.

A: a better way is to use flock instead of a pidfile.  check the manpage: flock(1). The advantage is that no matter how a process finishes/dies, the lock is gone with it.

A: That's the proper solution for that approach.  Typically, a pid file would be used and a pid test would be done against the process to insure it's running.  If stale, the lockfile would be removed and the process would run anyway.
Any additional intelligence would typically be written in the software itself, as a daemon, as opposed to running in cron.

A: If your scripts are coded in a language which supports the flock(2) syscall, then you could flock() a lock file with a function call too. Example:

*

*Perl: flock

*Python: fcntl.flock
If you are stuck with Bash or other scripting language which doesn't support this, the already proposed solution with flock(1) is fine too.
P.S. In any case, you should create a separate lock file only once (if it doesn't already exist), and never delete it. The directory "/var/lock" is a good place for such files.

A: This is a solution if your script runs in python (or you could create a python command to run before the next command) - I ran into this exact problem last week, and although I did find some good solutions, I decided to make a very simple and clean python package and uploaded it to PyPI. You could certainly lock __file__ to not have to think about giving it a custom resource name to lock.
Install with: pip install quicklock
Using it is extremely simple:
[nate@Nates-MacBook-Pro-3 ~/live] python
Python 2.7.6 (default, Sep  9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from quicklock import singleton
>>> # Let's create a lock so that only one instance of a script will run
...
>>> singleton('hello world')
>>>
>>> # Let's try to do that again, this should fail
...
>>> singleton('hello world')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/nate/live/gallery/env/lib/python2.7/site-packages/quicklock/quicklock.py", line 47, in singleton
    raise RuntimeError('Resource <{}> is currently locked by <Process {}: "{}">'.format(resource, other_process.pid, other_process.name()))
RuntimeError: Resource <hello world> is currently locked by <Process 24801: "python">
>>>
>>> # But if we quit this process, we release the lock automatically
...
>>> ^D
[nate@Nates-MacBook-Pro-3 ~/live] python
Python 2.7.6 (default, Sep  9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from quicklock import singleton
>>> singleton('hello world')
>>>
>>> # No exception was thrown, we own 'hello world'!

Take a look: https://pypi.python.org/pypi/quicklock


text:
Q: Prove that sum is convergent How to prove that the following sum is convergent? $$\sum_1^\infty\frac{\sin(n + \ln{n})}{n}$$
I tried to use formula $$\sin(n+ \ln{n}) = \sin{n}\cos \ln{n} + \sin \ln{n}\cos{n}$$ and $$\sum_1^N \sin{n} \leq \frac{1}{\sin{1/2}}$$
But I can't make same estimates for $\sin{n}\cos \ln{n} $ and $\sin \ln{n} \cos{n}$.

A: Here give another method for the convergence of
$$\sum_{n=1}^\infty\frac{\sin(n+\ln{n})}{n}.$$
Use the OP's formula:
$$\sin(n+\ln{n})=\sin{n}\cos\ln{n}+\sin\ln{n}\cos{n},$$
We will prove the two series
$$\sum_{n=1}^\infty\frac{\sin{n}\cos\ln{n}}{n},\quad
\sum_{n=1}^\infty\frac{\sin\ln{n}\cos{n}}{n}$$
are convergent.
For the convergence, we use the following $\bf{Dirichlet-Abel\ test}$:Dirichlet-Abel

If the series $\sum\limits_{n=1}^\infty a_n,\sum\limits_{n=1}^\infty b_n$ satisfy the following conditions:
(1) $\left\{\sum_{k=1}^n a_k\right\}$ is bounded;
(2) $\lim\limits_{n\to\infty}b_n=0;$
(3) $\sum\limits_{n=1}^\infty|b_n-b_{n+1}|$ is convergent,
then the series $\sum\limits_{n=1}^\infty a_nb_n$ is convergent.

For the first series $\sum_{n=1}^\infty\frac{\sin{n}\cos\ln{n}}{n}$,
take $a_n=\sin n,b_n=\frac{\cos\ln n}{n}$, it is easy to see conditions $(1),(2)$
are satisfied, as for condition $(3)$, just notice that:
$$\left(\frac{\cos\ln x}{x}\right)'=-\frac{\sin\ln x+\cos\ln x}{x^2},$$
and (Lagrange's mean value theorem)
$$\left|\frac{\cos\ln n}{n}-\frac{\cos\ln(n+1)}{n+1}\right|<\frac{2}{n^2}.$$
By the Dirichlet-Abel test, we know the convergence of
$$\sum_{n=1}^\infty\frac{\sin{n}\cos\ln{n}}{n}.$$
In the same way, we can prove the second is convergent.
So the series $$\sum_{n=1}^\infty\frac{\sin(n+\ln{n})}{n}$$
is convergent.

A: Look separately at the intervals $N^2\le n < (N+1)^2$, with $N\gg 1$. For these $n$, we have that
$$
|\sin (n+\log n) - \sin (n+\log N^2)| \le \log (n/N^2) \lesssim 1/N \lesssim 1/n^{1/2} ,
$$
and since $\sum n^{-3/2}<\infty$, we may replace $\sin (n+\log n)$ by $\sin (n+\alpha_N)$, for the $n$ currently under consideration.
However, as you already indicated, it's easy to control $\sum \sin (n+\alpha)/n$. Using summation by parts and the fact that $\sum_{n=N_1}^{N_2}\sin (n+\alpha)=O(1)$, we obtain that
$$
\sum_{N^2\le n<(N+1)^2} \frac{\sin (n+\alpha)}{n} = O(1/N^2) + \sum_{N^2\le n<(N+1)^2} O(1)/n^2 = O(1/N^2) ,
$$
and this is summable over $N$.


text:
Q: Webelement object python variable not recognized by intellisense I am new to python and web scraping with selenium. I was following a tutorial and I noticed in the tutorial, when Tim referenced the Webelement object intellisense listed all the possible functions. However when I was following the tutorial my webelement object did not return any methods and intellisense did not recognize the options. I am using most recent version of python verison 3.9.6 pip version 21.2.3 Selenium version 3.141.0
Code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

PATH = "localpath"
driver = webdriver.Chrome(PATH)
HTTPS = "https://"

# hard coded data to test
siteDomain = "indeed.com"
jobSearch = "Entry Level Software Developer"
locationSearch = "Richmond, VA"

# Goes to Site
driver.get(HTTPS + siteDomain)

# obtains access to elements from website
searchJob = driver.find_element_by_name("q")
searchLocation = driver.find_element_by_name("l")

# clear text field
searchJob.clear()
searchLocation.clear()

# inputs values into website elements
searchJob.send_keys(jobSearch)
searchLocation.send_keys(locationSearch)

# presses button to search
searchLocation.send_keys(Keys.RETURN)

driver.quit()

when I do driver.xxx I get the intellisense auto fill options. When I try to use the objects searchJob and searchLocation I do not get the intellisense auto fill options. I manually type out searchJob.send_keys(jobSearch) searchLocation.send_keys(locationSearch). Also element.clear() is also not working as I believe the problem is the same. I would like to see the options to better understand more complex problems. Any help is appreciated!

A: For your problem with element.clear() the following subsitution worked for me
searchLocation.send_keys(Keys.CONTROL, "a", Keys.BACK_SPACE)

Which is just saying select everything with control a and then delete it. If you're on a mac you might need to do COMMAND or something like that.
I had the same problem with IntelliSense when I reproduce what you did in VSC. I then tried it in Pycharm CE2021 and had IntelliSense work well. If you are not too attached to VSC then you might want to try Pycharm as a quick fix.

A: The Intellisense was provided by the Pylance Language Server by default. You can switch to another language server, such as JediLSP.
Add this in the settings.json file:
"python.languageServer": "JediLSP",


text:
Q: URL Rewriting friendly URL with htaccess I'm interested in rewriting a url which is already "friendly" in order to clean up what is already in the path.
At the moment, I have a URI which points to http://example.com/page/index/home, but ideally id like to have the remove page/index completely, and just have http://example.com/home.

A: To achieve what you want, you can just do this:
RewriteEngine On
RewriteRule ^/home$ /index.php [QSA,L]

QSA stands for Query String Append. It will append the query string (your GET parameters) to the end of your URL automatically if there is one.

A: Something like the following...
RewriteEngine On
RewriteRule ^page/index/home$   /home [L]

If you know the specific page you are matching

A: You can use this rule in .htaccess file:
RewriteEngine On
RewriteRule   ^home$   page/index/home [NC]


text:
Q: Show dynamically changed text from RealtyKit entity in a QLPreviewController There is a good question and answer here about dynamically changing text of an entity in a Reality Composer scene.  Is there a way to do the same but show it in a QLPreviewController rather than an ARView?
Here is code for loading a previewItem (from a URL) into the QLPreviewController.  So I would like to dynamically change the text in the file before returning the preview item to display.  Assume I am using a .rcproject that has a bubble text, for example.
class ARQLViewController: UIViewController,
                          QLPreviewControllerDataSource,
                          QLPreviewControllerDelegate {

    var allowsContentScaling = true
    var webViewModel: WebViewModel

    init(webViewModelReceived: WebViewModel) {
        webViewModel = webViewModelReceived
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidAppear(_ animated: Bool) {
        setupOnAppear()
    }

    func setupOnAppear() {
        let previewController = QLPreviewController()
        previewController.dataSource = self
        previewController.delegate = self
        present(previewController, animated: true, completion: nil)
    }

    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }

    func previewController(_ controller: QLPreviewController,
                    previewItemAt index: Int) -> QLPreviewItem {
        let url = webViewModel.afUrlForAR
        let previewItem = ARQuickLookPreviewItem(fileAt: url!)
        previewItem.allowsContentScaling = allowsContentScaling
        return previewItem
    }
}

A: About QLPreviewController
AR QuickLook is based on the RealityKit engine and it serves to preview AR QuickLook items in .usdz or .reality format with lighting (including soft contact shadows and PBR materials), light estimation, animation, gestures, anchoring, sound and file sharing. It was conceived as a zero-config view controller for AR scenes.
Since the model is QLPreviewItem or ARQuickLookPreviewItem, you will not be able to change model's parameters or its hierarchy. So the answer is: you can preview .usdz and .reality models with animation and physics in QLPreviewController but you cannot change their parameters, the way you used to do in RealityKit.
The code for creating an ARQuickLook app is short and concise:
import QuickLook

class ViewController: UIViewController, QLPreviewControllerDataSource {

    func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 }

    override func viewDidAppear(_ animated: Bool) {
        let arController = QLPreviewController()
        arController.dataSource = self
        present(arController, animated: true)
    }

    func previewController(_ controller: QLPreviewController,
                    previewItemAt index: Int) -> QLPreviewItem {

        let path = Bundle.main.path(forResource: "ar3", ofType: "usdz")!
        return URL(fileURLWithPath: path) as QLPreviewItem
    }
}


text:
Q: Call function on previously selected radio button with the same name Hello I have some radio buttons with different radio groups name. I want to call the function on the previously selected radio button for that specific group.
If I check the radio button then select the different radio button from the same group. I want call the function or add class on the previously selected radio button of the same group in jQuery.
Here is the example code -
RadioGroup1Button 1: <input type='radio' name='radioGroup1' />

RadioGroup1Button 2: <input type='radio' name='radioGroup1' />

RadioGroup2Button 1: <input type='radio' name='radioGroup2' />

RadioGroup2Button 2: <input type='radio' name='radioGroup2' />

RadioGroup2Button 3: <input type='radio' name='radioGroup2' />

Please help

A: Is it something like this you want?
$("input:radio").on("mousedown", function() {
  var name = $(this).attr("name");
  if ($("input:radio[name='" + name + "']:checked").length == 1 && $(this).is(":not(:checked)")) {
    $("input:radio[name='" + name + "']").removeClass("PrevChecked");
    $("input:radio[name='" + name + "']:checked").addClass("PrevChecked");
  }
});

Demo

$("input:radio").on("mousedown", function() {
  var name = $(this).attr("name");
  if ($("input:radio[name='" + name + "']:checked").length == 1 && $(this).is(":not(:checked)")) {
    $("input:radio[name='" + name + "']").removeClass("PrevChecked");
    $("input:radio[name='" + name + "']:checked").addClass("PrevChecked");
  }
});

RadioGroup1Button 1: <input type='radio' name='radioGroup1' />
 RadioGroup1Button 2: <input type='radio' name='radioGroup1' />
 RadioGroup2Button 1: <input type='radio' name='radioGroup2' />
 RadioGroup2Button 2: <input type='radio' name='radioGroup2'
/>
 RadioGroup2Button 3: <input type='radio' name='radioGroup2' />


text:
Q: What does "synchronize" exactly do? I have a question which may sound very basic but here it is. As commonly known in Java the synchronize keyword is used to deal with multiples threads accessing one particular instance. Now imagine if an instance A has a synchronized method do(). Does that mean that if a thread T1 executes the method do() and therefore acquires the lock of A, no other thread will access the instance A until T1 releases the lock (even if other methods are not synchronized)? or it means that all not-synchronized methods (or blocks of code) are accessible except that particular do() method which maybe executed by only one thread at a time?

A: Straight from the Java documentation:

It is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Therefore, your latter explanation is correct.

A: A synchronized method ensures that this method is not called for more than one object instances simultaneously and also during execution of a synchronized method all the associated instance variables are refreshed before starting executing the method.

A: If T1 gets a lock on method do() i.e method is under synchronized block.
and other portion of program say method display() is not synchronized then other threads can access this method.
So your or is correct.


text:
Q: Java: JPA classes, refactoring from Date to DateTime With a table created using this SQL
Create Table X (
    ID varchar(4) Not Null,
    XDATE date
);

and an entity class defined like so
@Entity
@Table(name = "X")
public class X implements Serializable {
    @Id
    @Basic(optional = false)
    @Column(name = "ID", nullable = false, length = 4)
    private String id;
    @Column(name = "XDATE")
    @Temporal(TemporalType.DATE)
    private Date xDate; //java.util.Date
    ...
}

With the above, I can use JPA to achieve object relational mapping. However, the xDate attribute can only store dates, e.g. dd/MM/yyyy.
How do I refactor the above to store a full date object using just one field, i.e. dd/MM/yyyy HH24:mm?

A: If you want to also store time information at the database level, use TemporalType.DATETIME:
@Column(name = "XDATE")
@Temporal(TemporalType.DATETIME)
private Date xDate; //java.util.Date

Use a TIMESTAMP column type at the database level (and xDate will be stored as 'yyyy-MM-dd HH:mm:ss.S').

A: Have you tried changing the @Temporal value to TemporalType.DATETIME? java.util.Date and java.sql.Date both store date and time components, the TemporalType controls which part JPA stored/pays attention to; date, time, or both.


text:
Q: include one mouseover into a div created with javascript i have one script  :
        if (el.tags.includes(selectedTag)) {
            const itemsContent = document.createElement('div');
            itemsContent.className = 'items-content';
            const h2 = document.createElement('h2');
            h2.className = 'project-title';
            h2.innerHTML = el.title;
            div.appendChild(h2);
            main.appendChild(div);
        }

And i want to be able to add a mouseover in my 'itemsContent' div
to generate something like :

 My content

Thanks ;)

A: Use
itemsContent.addEventListener("mouseenter", function (event)){
// your event handler code goes here
 })
Refer https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event


text:
Q: d3.js appending text when there is already text on the page I'm trying to append some text to text which is already on the page. The first time I do it, it works. The second time I tried it, I had trouble until I found this: http://knowledgestockpile.blogspot.com/2012/01/understanding-selectall-data-enter.html
Once I added a key function, it worked for all entries but the first. How do I get the first to show up?
var dataset=[{"x":0, "y":2},{"x":1, "y":2},{"x":2, "y":2},{"x":3, "y":2}];
  vis.selectAll("text")
     .data(dataset)
     .enter()
     .append("text")
     .text(function(d,i) {return d.x;})
     .attr("text-anchor", "middle")
     .attr("x", function(d, i) {return scaleX(d.x);})
     .attr("y", function(d) {return scaleY(-5) ;})
     .attr("font-family", "sans-serif")
     .attr("font-size", "11px")
     .attr("fill", "black");

  vis.selectAll("text")
     .data(dataset,function(d){return d;})
     .enter()
     .append("text")
     .text(function(d,i) {return d.x;})
     .attr("text-anchor", "middle")
     .attr("x", function(d, i) {return scaleX(d.x);})
     .attr("y", function(d) {return scaleY(20) ;})
     .attr("font-family", "sans-serif")
     .attr("font-size", "11px")
     .attr("fill", "black");

Here is the fiddle: http://jsfiddle.net/tvinci/hbASc/2/

A: By selecting the text and then calling data(), you're telling d3 to match the new elements with existing elements. When you do this, the intention is usually to update existing elements instead of simply adding all of them as new ones.
If what you want to do is add the text twice, you can assign different classes to the text in both selections such that the .enter() selection will contain all the elements in both cases. The code would be something like
vis.selectAll("text.one")
   .data(dataset)
   .enter()
   .append("text")
   .attr("class", "one")
   ...

vis.selectAll("text.two")
   .data(dataset)
   .enter()
   .append("text")
   .attr("class", "two")
   ...

If you want to update the existing text, remove the .enter() in the second call chain. It also won't be necessary to pass in a key function in this case.


text:
Q: How hide and show view when scroll page I wrote this code, and i hided view
self.tableView.tableHeaderView = nil

But if i try show it again, this code cant do it
tableView.tableHeaderView = tableHeaderView

Help me please
My code
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (self.lastContentOffset < scrollView.contentOffset.y) {
        // moved to top
        self.tableView.tableHeaderView = nil
    }
    else if (self.lastContentOffset > scrollView.contentOffset.y) {
        if tableView.tableHeaderView == nil {
        // moved to bottom
            tableView.tableHeaderView = pre_test_view
        }
    }
    else {
        // didn't move
    }
}

A: So when you initially instantiate the UITableView and set the tableViewHeader to nil you are not really hiding it...so much as initiating the tableView without it. What you can do..is call tableView.reloadData() after tableView.tableHeaderView = tableHeaderView and that should probably do it.


text:
Q: Get Android predefined string I'm tying to get predefined Android strings (from android sdk):
I do can get strings like: android.R.string.ok and android.R.string.cancel.
But I cannot get android.R.string.activity_resolver_use_always and android.R.string.activity_resolver_use_once
Getting error 'Cannot resolve symbol' in Android Studio even though I can see all the strings id's in android.R file.
using: context.getString(android.R.string.activity_resolver_use_always)
Is there other way to get those strings?

A: That's the answer:
int resId = getResources().getIdentifier("activity_resolver_use_once", "string", "android");
final String always = getString(resId);


text:
Q: ERROR-ITMS 90534 "Invalid Toolchain "
ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

I am facing this issue while uploading to the appstore. I am using xcode8.3 can anyone help me to resolve this issue?

A: You are getting this error since you are using beta version of XCode, to avoid this error, use public version of XCode & this error will be resolved.


text:
Q: Seaborn heatmap colors - same colors for the magnitude of values I have values of a matrix going from +1 to -1 and I would like the same color for +1 and -1. Is there a way to do this?
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

# Load the example flights dataset and convert to long-form
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")

# Draw a heatmap with the numeric values in each cell
f, ax = plt.subplots(figsize=(9, 6))
mv1 = np.mean(flights.mean());
sns.heatmap(flights- mv1, annot=True)

Thanks.

A: You can use seaborn's diverging_palette() to generate such a cmap by passing the same hue value for the negative and positive end of the cmap.
data = np.random.uniform(low=-1, high=1, size=(10,10))
cmap = sns.diverging_palette(240,240, as_cmap=True)
sns.heatmap(data, cmap=cmap)


text:
Q: ConstraintLayout - center TextView in the root but don't override Button So my application supports different languages and I can't predict how long will be title TextView. I want to have back Button on the same line but I want to prevent Text to cover the button. There's an example what I mean:

What's wrong with that:

What I want to achieve: when text will "meet" button, it should be spread out to two lines. I've tried barriers but then I can't center TextView in parent View and also auto-sizing text for button(this button could be TextView with enabled clickOn) but as you know it works only for API 26+, I need to support lower Android versions.
Is there way to achieve both: create Barrier to separate Button and TextView and also keep TextView in the middle of screen(not center between button and end of the screen)?

A: I just think of a quick resolve for this.
You can create one more Button with the same size as your Back button. And align it to the right of the screen, with attribute visibility="invisible. Then make your TextView's width match with the 2 buttons.
Then your problem solved ! But make sure to change the additional button's attributes when ever you change your button's attributes

A: For further help.
So to sum up what we've got to do based on @Sơn Phạm answer.
We need to create a mirror of the Button on the opposite side:

TextView should start at the end of left Button and end at start of the right Button:

You need to set TextView width as match_constraint. Nextly you need to set right button android:visibility="invisible"(not gone!) and make it unclickable. Now, we've got what we wanted to achieve:

IMPORTANT: Set the same string source for both buttons because when you support different languages your text button will change(e.g. en "Back", es "Regreso") but you want to keep both buttons same width. When you set button text source for both, for example @string/back both buttons will scale automatically.
    <Button
    android:id="@+id/button"
    android:text="@string/back"
    ... />

    <Button
    android:id="@+id/button2"
    android:text="@string/back"
    ... />

NOTE: It also works well with Barriers.


text:
Q: Firefox use another charset when send form I have problem with Firefox browser. On page I have "form" and when I submit this "form" then my webpage change charset from "utf-8" to "Windows-1250". When I go to another place in page then charset go back to "utf-8". This problem is only in Firefox in another browser works everything fine (Chrome, Opera, IE - I can check this in Safari etc..)
I search on internet a lot of time, but I found nothing. Some way is via Ajax or change something in Firefox or get some plugin, but I need solution which can work for everyone without change something in browser. Because clients must have correct default charset => no some "alert" with information what they must change on their pc. I have Firefox 27.0.1.
I have this codes:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="cs" />
<form accept-charset="utf-8" action="poslat.html" onsubmit="this.action=''; return kontrola_udaju_vlozit_inzerat(this);" method="post" enctype="multipart/form-data">

Attribute "accept-charset" don´t help me. And all of pages (php, js) are in UTF-8. I have this problem on 3 sites (I mean) and this type of problem have some peoples on internet and for that I mean this is Firefox bug but I need solved it.
Can anyone help me?

A: I found a workaround /not a solution/ :
redirect to specified url instead of displaying the same page after form submit
just a few minutes later found solution:
I added a line to htaccess:
AddDefaultCharset utf-8

works :) in my page


text:
Q: How can i add a class for this php file? I am building my website through wordpress, I found a cool plugin that shows the Total of sales and views of a product, my problem is that I need to customize the field with CSS and I don't know how to add a class in the PHP file or if it is even possible.
I want to add the class to customize the fields in the single product page because if I do it without a specific class all the changes affect the whole page. Here is the code.
<?php
/*
Plugin Name: Product Sold Count
Plugin URI:  http:\\bhaskardhote.in
Description: This Plugin will used to show the total product sale count & and total view of product .Nice and easy way to know your sale of each product.
Version: 3.0.1
Author: Bhaskar Dhote
Author URI: http:\\bhaskardhote.in
*/
define( 'WP_WOOSOLD_URL', plugin_dir_url(__FILE__) );
define( 'WP_WOOSOLD_PATH', plugin_dir_path(__FILE__) );
define( 'WP_WOOSOLD_SLUG','woo_soldcount' );

if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');
global $wpdbb_content_dir;

if(!function_exists('wp_get_current_user')){
    include(ABSPATH."wp-includes/pluggable.php") ; // Include pluggable.php for current user
}

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "View: 0";
    }
    return 'Views: '.$count;
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

add_action( 'woocommerce_single_product_summary', 'wc_product_sold_count', 11 );
function wc_product_sold_count() {
    global $product;
    setPostViews(get_the_ID());
    $units_sold = get_post_meta( $product->id, 'total_sales', true );
    echo '
'. sprintf( __( 'Total Sold: %s', 'woocommerce' ), $units_sold ).' '.getPostViews(get_the_ID());'
';
}
add_action('inti','wc_product_sold_count');

?>

A: Try the following
echo '
'. sprintf( __( 'Total Sold: %s', 'woocommerce' ), $units_sold ).' '.getPostViews(get_the_ID());'
';

Hope this helps :)


text:
Q: Java Propertie File not found when running on command line In my program, a Java8 application library, written on NetBeans, when I go to the dist folder and run Project.jar using the command:
java -jar Project.jar

I get the following error:
Sorry, unable to find config.properties
Exception in thread "main" java.lang.NullPointerException

It seems it cannot create the input stream necessary to read the properties file.
Here is the class I use to read the properties:
public class PropertyAccess {

    public static String getPropertyFromFile(String propertyName){
        String ret = "";
        //System.out.println(propertyName);
        InputStream input = null;
        Properties prop  = new Properties();

        try {
            String filename = "config.properties";
            input = PropertyAccess.class.getResourceAsStream(filename);
            if(input == null) {
                    System.out.println("Sorry, unable to find " + filename);
            }

            //input = PropertyAccess.class.getResourceAsStream("/config/config.properties");
            //input = new FileInputStream("config/config.properties");

            input = PropertyAccess.class.getClassLoader().getResourceAsStream("config/config.properties");

            prop.load(input);
            ret =  prop.getProperty(propertyName);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return ret;
    }
}

There is a bad design/implementation where I load the prop file every time I need to read a property from file, this will be corrected before the main release, but this is not what is causing the issue.
Can someone explain how to fix this?
I've tried to add the file to the classpath, but  it also doesnt work.


text:
Q: Mysql procedure updating wrong value due to multi-threading in Java I am using below mentioned MYSQL procedure(exact arguments not mentioned) to insert the data in three tables
"T1" ,"T2" and "T3".
CREATE DEFINER=`root`@`%` PROCEDURE `insert_values`(v1,v2,v3,v4,v5,v6.......)
begin
declare max_id bigint;
start transaction;
insert ignore into T1
fields(.....)
values
(v1,v2,v3,.......);
insert ignore into T2
fields(......)
values
(v1,v4,..........);
If (v3 <> '') Then
    set @max_id:=(select max(id) from T1);
    insert ignore into T3
    fields(.......)
    values
    (@max_id,v3,v5,v6,........);
End If;
commit;
end

In table T1 and T2 the field "id" is the primary key which is auto-increment so not getting inserted through procedure.
In this procedure I am inserting data first in table T1 and T2 and then reading the maximum "id"
(last inserted/auto-incremented "id") from table T1 in variable "max_id" which was auto-generated
by "insert ignore into T1....." query of this procedure.
I am calling this procedure through java code which is using multi-threading.
My problem is that the statement "set @max_id:=(select max(id) from T1);" is sometimes instead of reading the last
auto-increment value generated by "insert ignore into T1....." query of this session/thread, is reading the wrong
value(because may be  another parallel thread is inserting its data in the table T1 before the current thread reads
the "max_id" from T1 and hence "max_id" is getting the value incremented by another thread).
So how to resolve this issue?
Is changing the isolation level can be the solution?
These tables using INNODB storage engine.
"@@GLOBAL.tx_isolation" is 'REPEATABLE-READ'
"@@tx_isolation" is 'REPEATABLE-READ'
"@@autocommit" is '1'
Thanks & Regards

A: Have you tried using LAST_INSERT_ID()?
...
insert ignore into T1
fields(.....)
values
(v1,v2,v3,.......);
/* SET @max_id := LAST_INSERT_ID(); */
SET max_id := LAST_INSERT_ID();
...
insert ignore into T3
fields(.......)
values
(max_id,v3,v5,v6,........);
...

UPDATE
It is important to indicate the difference between 9.4. User-Defined Variables (@max_id) and 13.6.4.1. Local Variable Syntax DECLARE (max_id), are different variables. In this case better to use (max_id) local variable.


text:
Q: Whats bad with an array? Why this code doesn't work? echo get('option_1') returns null.
$settings= array(
    'option_1' => 'text'
);

function get($name)
{
    if ($name)
        return $settings[$name];
}

echo get('option_1');

A: The simple solution is to make $options be a global variable inside get():
function get($name)
{
    global $options;
    if ($name)
        return $options[$name];
}

If you don't like global state, make $options as an argument to get() (but then it's just syntactic sugar...):
function get($name, $options)
{
    if ($name)
        return $options[$name];
}

A: Because $options is out of the scope of the get function. You either have to:

*

*Pass $options along with $name as a function parameter

*Declare $options as global variable (very bad idea)

*use $options as an internal class variable and access it with $this->options (only works inside a class)

A: The $options is not in the scope of your get function.
An object oriented solution:
class Options
{
  private static $options = array(
    'option_1' => 'text',
  );

  public static function get($name)
  {
    return isset(self::$options[$name]) ? self::$options[$name] : null;
  }
}

echo Options::get('option_1');


text:
Q: Ionic View Template Not Being Updated When $scope Variable Is Updated In Controller I have an ionic app I'm testing the ability to check for fingerprint login. All this works, BUT when I check for whether a user has stored login credentials and get back the decrypted value, I want to SHOW a button that allows user to initiate fingerprint login.
The problem is, when I get back the success when gathering credentials from SecureStorage, I set a variable to show the button ($scope.canUseFingerprint) which is modeled to a button in the view using ng-if. BUT the button never shows up, UNLESS I type a single character into the email input again (there is no "change" function on the input).
I have inspected and it shows the variable is getting set to true, yet the button will not showup until a single character is entered into that email input.
Can someone take a look?
Here is my view:
<form name="loginForm" ng-submit="login(email, password)">
    Email
    <input type="text" ng-model="email" placeholder="typehere"></input>
    Password
    <input type="text" ng-model="password" placeholder="typehere"></input>
    <button type="submit">Test Login</button>

    <button type="button" ng-if="canUseFingerprint" ng-click="showFingerPrint()">Show Finger Print</button>

    <button type="button" ng-click="testShowFingerPrint()">Test Show Button</button>
    <button type="button" ng-click="clearKeys()">Clear All Keys</button>
</form>

Here is my controller:
$ionicPlatform.ready(function(){
    $scope.canUseFingerprint = false; //Initialized to false

var ss = new cordova.plugins.SecureStorage(
  function () {
    console.log('Success');
    // $scope.allowFingerprintLogin = true;
    setTimeout(function(){
      checkForLoginCreds(); //Checks for login credentials
    },3000)

  },
  function (error) {
    $scope.canUseFingerprint = false;
    addLockScreen();
    console.log('Error ' + error);

  },
  'my_app');
var checkForLoginCreds = function(){

  ss.get(
    function (value) {
      console.log('Success, got ' + value);
      // This should activate the button, but does nothing. It DOES get set to true. Only after typing single character in input does the button show.
      $scope.canUseFingerprint = true;
    },
    function (error) { console.log('Error ' + error); },
    'loginInfo');
}
})

A: To convert ss.get from a callback-based service to a promise-based service, use the AngularJS $q Service:
function ssGetPromise(ss,key) {
    var deferred = $q.defer();
    ss.get(
        function (value) {
            console.log('Success, got ' + value);
            deferred.resolve(value);
        },
        function (error) {
            console.log('Error ' + error);
            deferred.reject(error);
        },
        key
    );
    return deferred.promise;
}

Usage:
ssGetPromise(ss,'loginInfo').then(function(value) {
    $scope.canUseFingerprint = true;
});

The $q Service creates promises that are integrated with the AngularJS Framework. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.


text:
Q: HAProxy -- pause/queue all traffic without losing requests I basically have the same problem as mentioned in this thread -- I would like to temporarily suspend all requests to all servers of a certain backend, so that I can upgrade the backend and the database it uses. Since this is a live system, I would like to queue up requests, and send them to the backend servers once they've been upgraded. Since I'm doing a database upgrade with the code change, I have to upgrade all backend servers simultaneously, so I can't just bring one down at a time.
I tried using the tcp-request options combined with removing the static healthcheck file as mentioned in that thread, but had no luck. Setting the default "maxconn" value to 0 seems to pause and queue connections as desired, but then there seems to be no way to increase the value back to a positive number without restarting HAProxy, which kills all requests that had been queued up until that point. (The "hot-reconfiguration" options using -sf and -st start a new process, which doesn't seem to do what I want).
Is what I'm trying to do possible?

A: I eventually ended up asking this question of Willy Tarreau, the author of HAProxy. He was intrigued by my suggestion, and committed a small change to HAProxy that allows for setting maxconn down to zero via the admin socket (this wasn't possible at the time I asked), which solved my problem. Quoting from the followup email I sent him:

Hi there. That solves my problem pretty well. I issued "set maxconn
  frontend my_frontend 0", waited a few seconds for connections to
  drain, and then all subsequent connections are paused. I restarted the
  server, issued "set maxconn frontend my_frontend 3000", and
  connections resumed properly, without erroring out on existing
  requests.

In response to JesseP's answer -- absolutely, most of the time I never want to do this. We generally try and stage our DB migrations in exactly the way you mention, because suspending traffic is risky at best. Some of our users set ridiculously low client-side timeouts, so we generally don't want traffic suspended for more than 15 seconds. But for a recent migration where we had a complex set of code and data migrations to perform simultaneously, having this option available was a lifesaver.
So, to sum up -- not recommending this for everyday use, but the option is there should the need arise.

A: Even if you accomplish what you're asking, you're going to end up with longer running data migrations, too many servers to update, etc., in the future, and clients will end up timing out while they wait for stuff to come back online.
You should really try to build your updates such that existing servers can still run.  This may involve deploying some updated code with existing database, then updating the database, then deploying the actual update.
In the end, you should be able to deploy one server at a time, with out breaking things.


text:
Q: Why is nan? not implemented on ruby Fixnum? I have a class where I use a Fixnum default value. I'd like to put a guard to ensure that the class is never instantiated with a NaN parameter. I discovered to my consternation that Fixnum doesn't support nan?.  I have a work-around. I just wondered why.
class Table

  attr_reader :rows, :min, :max, :increment
  def initialize min = 0, max = 100, increment = 20
    min = 0 if min.respond_to?(:nan?) && min.nan?
    max = 100 if max.respond_to?(:nam?) && max.nan?
    @min, @max, @increment, @rows = min.floor, max.ceil, increment, []
  end
end

To be clear, this is the behavior I'm talking about:
[8] pry(main)> 0.0.nan?
=> false
[9] pry(main)> BigDecimal.new(0).nan?
=> false
[10] pry(main)> 0.nan?
NoMethodError: undefined method `nan?' for 0:Fixnum
from (pry):10:in `__pry__'

For example, the behavior after dividing by zero.
[1] pry(main)> 0/0
ZeroDivisionError: divided by 0
from (pry):1:in `/'
[2] pry(main)> 0.0/0.0
=> NaN
[3] pry(main)> BigDecimal.new(0) / BigDecimal.new(0)
=> #<BigDecimal:1029faf80,'NaN',9(36)>
[4] pry(main)>

A: Probably because an integer is a finite or definite number and NaN is not applicable to it.
From Wikipedia:

In computing, NaN, standing for not a number, is a numeric data type
  value representing an undefined or unrepresentable value, especially
  in floating-point calculations. Systematic use of NaNs was introduced
  by the IEEE 754 floating-point standard in 1985, along with the
  representation of other non-finite quantities like infinities.

Further examination:
0.0.class
# => Float
0.class
# => Fixnum
0.class.superclass
# => Integer


text:
Q: 2 Templates to one SharePoint Library, Default templates Ok, I'm not a script writer, otherwise I'd have this automated already. I need a quick assist in the most basic steps possible.
I have a SharePoint form library using InfoPath based forms. I have a "Public" template for my customers which submits to a "Private" library, through very granulated permissions so they cannot view the library. The Private library has it's own template based on the original Public template. This way I can transition one form's information seamlessly to the new template. The new Private template would have all of the internal details that we do not want the customer to see, but also all information fron the customer-filled Public form.
Is there any way to default all items opened from the Private library to use the Private Template, even though they were submitted form the Public template?

A: Once an InfoPath form is submitted to a library it will always open in the template it was created in. In your case that is the Public template. There is a workaround for this scenario and it involves some programming. I would suggest that you create a custom logic in the form that would open a different view based on data entered. IE. once submitted you could change a value in your InfoPath form an make another view in the form default.
This is not ideal solution, but InfoPath does not support what you are looking for. InfoPath forms are pure XML and a super user might open the XML in some editor and see and update the values you are trying to protect.
The most aggressive option would be to change the reference to InfoPath template programatically, which is tricky as you might corrupt the form. However XML would still be there.


text:
Q: Best practice for floating license purchases? Is there a best practice for determining how many floating licenses of a product to buy? I need to purchase Rational Rose for 15 developers, but I'm unsure as to how to determine how many floating licenses that will translate to.  Since this is a new project, I do not have usage statistics to help me determine when peak times are, etc.  Is the consensus to purchase more than needed, and let the excess lapse at renewal time, or do you take a guess and increase as needed?  Thanks!

A: My thoughts ...
I assume a standard "concurrent user" licensing scheme and that all 15 guys work the same hours.  I also assume that 15 is not a reasonable answer.
If you can, survey the manager and developers about what fraction of their time will be spent using the tool.  Multiply that fraction times 15 and round up.  If you can't, then I would use 50% and make sure everyone knows that this is a WAG.  I would negotiate with the company the right to purchase more licenses are the same price for some period of time.
The decision about whether to overbuy or underbuy from there depends on whether there is lockout when all the licenses are consumed and the mechanism for getting more licenses.  Generally, I like to err on the side of getting an extra license or two.
1- Make sure you understand the licensing terms around the floating license.  Be clear about the license terms.  Not every company supports "floating" licenses, even if you are planning on using them that way.
2- Also make sure you know how the licenses are enforced .. license manager server, honor system, some kind of token/dongle, or something else.
3- Make sure all know before the decision is made the cost and mechanisms for the addition of licenses.
4- You may need to enforce discipline around folks leaving the tool running when they aren't using it. If you decide to get three licenses, and two of them are being consumed by guys at lunch, two other folks may be out of luck.
5- Plan for review of the situation 2 or 3 times a year plus during budget season.

A: It would depend on how that company does their licensing. I would get a sales guy on the phone and talk him into letting you expand when you need to and start out small, say, 5?


text:
Q: override searchProvider.php does not work Create : override/modules/ps_facetedsearch/src/Product/SearchProvider.php
Create : override/modules/ps_facetedsearch/ps_facetedsearch.php
Delete the cache manually
Version : 1.7.6.4
override SearchProvider.php doesn't work
override ps_facetedsearch.php work
I need to delete 2 types of sorting ... into SearchProvider.php:getAvailableSortOrders() but I never go through the overloaded function

if (!defined('PS_VERSION'))
exit;

class SearchProviderOverride extends SearchProvider
{

/**
 * @return array
 */
public function getAvailableSortOrders()
{
    $sortPosAsc = new SortOrder('product', 'position', 'asc');
    $sortPriceAsc = new SortOrder('product', 'price', 'asc');
    $sortPriceDesc = new SortOrder('product', 'price', 'desc');
    $translator = $this->module->getTranslator();

    die('hello not world!');

    return [
        $sortPosAsc->setLabel(
            $translator->trans('Relevance', [], 'Modules.Facetedsearch.Shop')
        ),
        $sortPriceAsc->setLabel(
            $translator->trans('Price, low to high', [], 'Shop.Theme.Catalog')
        ),
        $sortPriceDesc->setLabel(
            $translator->trans('Price, high to low', [], 'Shop.Theme.Catalog')
        ),
    ];
}

}```

A: "getAvailableSortOrders" is a private method. You are probably only hidding the private method with your public one.
You should override the "runQuery" method since it's the only one that uses "getAvailableSortOrders". This way your overriden "runQuery" will call the appropriate "getAvailableSortOrders" method.
And finally, you can make your "getAvailableSortOrders" private since its only meant  to be used in this class.
if (!defined('PS_VERSION'))
exit;

class SearchProviderOverride extends SearchProvider
{

/**
 * @return array
 */
private function getAvailableSortOrders()
{
    $sortPosAsc = new SortOrder('product', 'position', 'asc');
    $sortPriceAsc = new SortOrder('product', 'price', 'asc');
    $sortPriceDesc = new SortOrder('product', 'price', 'desc');
    $translator = $this->module->getTranslator();

    die('hello not world!');

    return [
        $sortPosAsc->setLabel(
            $translator->trans('Relevance', [], 'Modules.Facetedsearch.Shop')
        ),
        $sortPriceAsc->setLabel(
            $translator->trans('Price, low to high', [], 'Shop.Theme.Catalog')
        ),
        $sortPriceDesc->setLabel(
            $translator->trans('Price, high to low', [], 'Shop.Theme.Catalog')
        ),
    ];
}

/**
 * @param ProductSearchContext $context
 * @param ProductSearchQuery $query
 *
 * @return ProductSearchResult
 */
public function runQuery(
    ProductSearchContext $context,
    ProductSearchQuery $query
) {
    $result = new ProductSearchResult();
    // extract the filter array from the Search query
    $facetedSearchFilters = $this->filtersConverter->createFacetedSearchFiltersFromQuery($query);

    $context = $this->module->getContext();
    $facetedSearch = new Search($context);
    // init the search with the initial population associated with the current filters
    $facetedSearch->initSearch($facetedSearchFilters);

    $orderBy = $query->getSortOrder()->toLegacyOrderBy(false);
    $orderWay = $query->getSortOrder()->toLegacyOrderWay();

    $filterProductSearch = new Filters\Products($facetedSearch);

    // get the product associated with the current filter
    $productsAndCount = $filterProductSearch->getProductByFilters(
        $query->getResultsPerPage(),
        $query->getPage(),
        $orderBy,
        $orderWay,
        $facetedSearchFilters
    );

    $result
        ->setProducts($productsAndCount['products'])
        ->setTotalProductsCount($productsAndCount['count'])
        ->setAvailableSortOrders($this->getAvailableSortOrders());

    // now get the filter blocks associated with the current search
    $filterBlockSearch = new Filters\Block(
        $facetedSearch->getSearchAdapter(),
        $context,
        $this->module->getDatabase()
    );

    $idShop = (int) $context->shop->id;
    $idLang = (int) $context->language->id;
    $idCurrency = (int) $context->currency->id;
    $idCountry = (int) $context->country->id;
    $idCategory = (int) $query->getIdCategory();

    $filterHash = md5(
        sprintf(
            '%d-%d-%d-%d-%d-%s',
            $idShop,
            $idCurrency,
            $idLang,
            $idCategory,
            $idCountry,
            serialize($facetedSearchFilters)
        )
    );

    $filterBlock = $filterBlockSearch->getFromCache($filterHash);
    if (empty($filterBlock)) {
        $filterBlock = $filterBlockSearch->getFilterBlock($productsAndCount['count'], $facetedSearchFilters);
        $filterBlockSearch->insertIntoCache($filterHash, $filterBlock);
    }

    $facets = $this->filtersConverter->getFacetsFromFilterBlocks(
        $filterBlock['filters']
    );

    $this->labelRangeFilters($facets);
    $this->addEncodedFacetsToFilters($facets);
    $this->hideUselessFacets($facets, (int) $result->getTotalProductsCount());

    $facetCollection = new FacetCollection();
    $nextMenu = $facetCollection->setFacets($facets);
    $result->setFacetCollection($nextMenu);
    $result->setEncodedFacets($this->facetsSerializer->serialize($facets));

    return $result;
}

}


text:
Q: Considering General Relativity, how long would it take for a ball to stop oscillating dropped through the center of the Earth? In Newtonian view, if a relatively small mass was dropped through a frictionless tunnel without drag intersecting the center of a non-rotating, spherically symmetric,uniform density Earth, then the object should oscillate in simple harmonic motion forever. But if we consider General Relativity then under the same restrictions the object's mass accelerating would create tiny gravitational waves which would gradually radiate away it's energy producing damped oscillation. So my question is if a ball was dropped through the tunnel intersecting earth under the above restrictions, would it gradually come to a halt in the center of Earth in finite time? If so, then what time would it take?

A: Gravitational waves, unlike in your system with a dipole, require a quadrupole. For example, the motion of two mutually orbiting bodies will generate gravitational waves (see the binary black hole merger which is how we first detected gravitational waves). So the system you describe, assumed to be a perfectly symmetrical non-rotating system, will not generate gravitational waves.
Note that an oscillating charge that can generate electromagnetic waves, is not analogous to an oscillating mass, in that the latter will not on its own generate gravitational waves.


text:
Q: Sed bash script iterating multiple times I have an assignment of editing a text file, called LOLOLOL.
HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY bob bob bob Gary gary

the the bird in the the bush!

LOL MATE!

I have a bash script file called lolz.script:
#!/bin/bash

sed '1i Hee hee hee\n Ho Ho Ho\n' $1
sed 's/bob/Bob/g' $1

running .\lolz.script LOLOLOL at the command line, I get multiple iterations of the LOLOLOL text- precisely, one iteration per sed command.
For example, the output shows the first and second sed commands (applied for each) here:
*Hee Hee Hee
Ho Ho Ho*
HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY bob bob bob Gary gary

the the bird in the the bush!

LOL MATE!
HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY *Bob Bob Bob* Gary gary

the the bird in the the bush!

LOL MATE!

*

*--- * show the changed part of the text file in the output.

Whereas what I want output:
*Hee Hee Hee
Ho Ho Ho*
HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY Bob Bob Bob Gary gary

the the bird in the the bush!

LOL MATE!

As you can see, each sed command is applied independently in each iteration of printing the text file. I need all sed commands to be applied together.
Note how the desired header from the first sed command is applied in the first iteration, while in the second it is not (but the bob to Bob change is).
Why has this happened, and what can I do to make commands in a script cumulative to one text file? This didn't seem to happen with same-format awk script.

A: Simply: you are invoking sed twice.
If you run those commands in a terminal one after the other, you will end up with two sets of output. Your script is just doing the same thing in its own shell.
You can use {} to group commands and put each one on a new line or use ; so all the commands act on the file cumulatively, calling sed only once:
#!/bin/bash
sed '{
     1i Hee hee hee\n Ho Ho Ho\n
     s/bob/Bob/g
}' "$1"

output of ./script file
Hee hee hee
 Ho Ho Ho

HRFJGEKGJHEJGKJVNEJGKJEG BOB BO B

GARY gARY gARY gary

FOG GARY Bob Bob Bob Gary gary

the the bird in the the bush!

LOL MATE!


text:
Q: Returning JSON from WCF Web Service I am trying to return JSON from a WCF Web service but all I get is bad request when I visit the URL.
Here is the interface:
 [ServiceContract]
    public interface IHighWCFService
    {
        [OperationContract]
        [WebGet(BodyStyle = WebMessageBodyStyle.Bare,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "KnownZombies")]
        [WebInvoke(Method = "GET")]
        List<ZombieInfo> GetZombies();

        [OperationContract]
        void DoWork();
    }

Here is the implementation of the above interface:
public class HighWCFService : IHighWCFService
    {
        public void DoWork()
        {
            throw new NotImplementedException();
        }

        public List<ZombieInfo> GetZombies()
        {
            var zombies = new List<ZombieInfo>()
                              {
                                  new ZombieInfo() {FirstName = "John", LastName = "Doe"},
                                  new ZombieInfo() {FirstName = "Mohammad", LastName = "Azam"}
                              };
            return zombies;
        }
    }

    [DataContract]
    public class ZombieInfo
    {
        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }
    }

I visit the following URL which results in 400 bad request:
http://localhost:22059/HighWCFService.svc/KnownZombies

The Web.Config looks like this:
<system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="HighOnCodingWebApps.HighWCFServiceBehavior">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
   </serviceBehaviors>
  </behaviors>
  <services>
   <service behaviorConfiguration="HighOnCodingWebApps.HighWCFServiceBehavior"
    name="HighOnCodingWebApps.HighWCFService">
    <endpoint address="http://localhost:22059/HighWCFService.svc" binding="webHttpBinding" contract="HighOnCodingWebApps.IHighWCFService">
     <identity>
      <dns value="localhost" />
     </identity>
    </endpoint>
    <endpoint address="http://localhost:22059/HighWCFService.svc" binding="webHttpBinding" contract="IMetadataExchange" />
   </service>
  </services>
 </system.serviceModel>

A: Two things:

*

*I think a 400 bad request error is genearated by some other problem not related
to JSON.

*I also think that you have to serialize that list in a list
of JSON objects in order to receive them since you're not using SOAP
anymore. You can use this class DATACONTRACTJSONSERIALIZER


text:
Q: Write C++ data to Apache Parquet: ParquetFileWriter or Write Arrow Table? I'm looking for the proper way to write data to a Parquet file in Cpp/C++. It seems like there are two choices: either writing direct to Parquet or writing to Arrow then Parquet.
Is writing to Arrow then converting to Parquet with WriteTable preferred? Would either performance considerations or ease of use drive one to write directly to Parquet with the ParquetFileWriter or some other tool?
Looking first at the code it seemed like the ParquetFileWriter was the proper bet. But the usage in the unittest seemed clunky.
Then I found the docs which say to use the WriteTable free fn. WriteTable takes an Apache Arrow Table so it seems I must write to that first. I was taken aback at first because then I must open the lid on Arrow.


text:
Q: Shiny server: Fatal error: unable to open the base package I just installed shiny server and I get an error when I load the shiny web page:
An error has occurred. The application failed to start shows on the right side of the screen.
Then I checked the log and shows:
su: ignore --preserve-environment, it's mutually exclusive to --login.
Fatal error: unable to open the base package
When I type su - shiny and I try to run R I also get the Fatal error: unable to open the base package, so I guess there is a problem with R.
I can load R when I'm root or R user and apparently R works fine.
Any idea? Could it be a PATH problem? If yes, I couldn't find it out.
Thanks in advance.


text:
Q: java.net.ConnectException: General SSLEngine problem I'm getting "java.net.ConnectException: General SSLEngine problem"
   import play.api.libs.ws._

   ws.url("https://bacd.com")
     .withFollowRedirects(true)
     .get

However, it works with all other URLs I've tried. What is the root cause of the exception?

A: Please check the Default SSLContext is set to true.
ssl-config.default = true or you can have a look on SSL-Config here https://lightbend.github.io/ssl-config/WSQuickStart.html
`


text:
Q: Send html video object (canvas) to Flask using Ajax i have been trying get user image from camera using flask but i have been receiving base64 encoded image but which is not decodable. i have been trying various codes from different platforms still unable to get the desired result
var video = document.getElementById('video');
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
        //video.src = window.URL.createObjectURL(stream);
        video.srcObject = stream;
        console.log(stream)
        video.play();
    });
}

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
//ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
setInterval(myTimer, 1000);

function myTimer() {

    data = canvas.toDataURL("");
    $.ajax({
        type: "POST",
        url: "/submit", //I have doubt about this url, not sure if something specific must come before "/take_pic"
        data: data,
        contentType: false,
        processData: false,
        success: function (data) {
            if (data.success) {
                //alert('Your file was successfully uploaded!');
            } else {
               // alert('There was an error uploading your file!');
            }
        },
        error: function (data) {
            console.log('There was an error uploading your file!');
        }
    }).done(function () {
        console.log("Sent");
    });

}

on my flask app i have been trying various things changed js multiple time but i could not get the proper result
@app.route('/submit',methods=['POST'])
def submit():
    image = flask.request.data
    # print()
    # offset = image.index(',')+1
    print(image)
    # print(image)
    # print(offset)
    # input()
    # img_bytes = base64.decode(image[offset:],"utf-8")
    # input()
    # img = Image.open(BytesIO(img_bytes))
    # img  = np.array(img)
    # cv2.imshow(img)
    # cv2.waitKeys(0)
    cv2.destroyAllWindows()
    # print(image)
    return ""

whatever i do i always is receiving
b'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAEvklEQVR4nO3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4Mwu4AAehrHaUAAAAASUVORK5CYII='

A: Basically my mistake was that I was not drawing anything to canvas so that was causing error for receiving the image.
This is the working version below:
    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>

    <body>
        <video id="video" width="640" height="480" autoplay></video>
        <canvas id="canvas" width="640" height="480"></canvas>
    </body>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="        crossorigin="anonymous"></script>
    <script>
        var video = document.getElementById('video');
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: true }).then(function     (stream) {
                 //video.src = window.URL.createObjectURL(stream);
                video.srcObject = stream;
                console.log(stream)
                video.play();
            });
    }

    setInterval(myTimer, 5000);

    function myTimer() {
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        var video = document.getElementById('video');
        ctx.drawImage(video,0,0)
        ctx.translate(video,0)
        document.getElementById("canvas").style = "display:none;"
        //ctx.drawImage(canvas,0,0)
        data = canvas.toDataURL("image/JPEG");

        console.log(data)
        $.ajax({
            type: "POST",
            url: "/submit",
            data: data,
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.success) {
                    //alert('Your file was successfully uploaded!');
                } else {
                   // alert('There was an error uploading your file!');
                }
            },
            error: function (data) {
                console.log('There was an error uploading your file!');
            }
        }).done(function () {
            console.log("Sent");
        });

    }

</script>

</html>


text:
Q: How to use TypeScript on an AngularJS application (1.x) with Webpack I'm following the official tutorial to migrate from AngularJS (1.x) to Angular (2+).
I managed to break my application into Components and use ES6 with a module loader, in my case Webpack, but now I'm not sure how to setup TypeScript.
I guess I need to install the TypeScript compiler and somehow tell Webpack to use it. How can I do it?
The source code is available here: https://github.com/shindarth/othello

A: *

*First of all run:

npm install typescript awesome-typescript-loader source-map-loader --save-dev
this will install typescript, awesome-typescript-loader and source-map-loader to the list of the devDependencies of package.json file.

*

*Then create the typescript compiler config file named tsconfig.json with a basic configuration inside:

{
     "compilerOptions": {
       "module": "commonjs",
       "target": "es5",
       "noImplicitAny": false,
       "sourceMap": true
     }
}

you can further customise the ts compiler options referring to the official tsconfig.json documentation.

*

*At this point we can rename all our *.js files to .ts.

*Note that wherever we were importing angularjs using:
import angular from 'angular';
we need to change it with:
import * as angular from 'angular';

*

*Finally we can tell WebPack to use the ts compiler to compile our *.ts source files.

So edit the file webpack.config.js as follows:
1) Edit the entry file name (since we renamed it and changed its extension to .ts).
In my case it was ./app/index.js before, change to:
entry: {
    app: './app/index.ts'
},

2) then below add the following:
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
    rules: [
        // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
        { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

        // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
        { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
    ]
},


text:
Q: C# Windows Form Application with Database not running on Client's System I have developed a Windows Form Application in C# that uses SQL Server database connectivity. I developed it in .NET Framework 4.0 and SQL Server 2008 R2. My application is using a local database present in the root directory of the application called AG.mdf.
This is my connection string:
Data Source=.;AttachDbFilename=|DataDirectory|\\AG.mdf;Integrated     Security=True;User Instance=True

I created the installer by adding Setup Project inside Visual Studio installer template as a new project in my application. I build the Setup project and it created the installer for me. I deployed the application on my User's system, the application starts initially but then it suddenly pops up an error

Unhandled exception has occurred in your application. If you click continue, the application will ignore this message and attempt to continue. If you click quit, the application will close immediately.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

P.S: I have installed .NET Framework 4.0 and SQL Server Compact Edition on my User's system as well!
Should I quit programming :'(

A: I think you might be getting Express Edition and Compact Edition confused; they're really quite different.
Compact Edition takes an SDF database file, and is an embedded database, not a separate server. I don't think it can work with MDF directly at all - you might be able to export an MDF to an SDF though.
SQLCE doesn't know about User Instances, Integrated Security, or database attachments. I think you'd need the path to the SDF file directly in the Data Source section, but it would need to be an SDF, not an MDF.
So basically, it looks like you're installing Compact Edition, but then using connect strings and data files for the full/express edition, which isn't likely to work.

A: Thanks a lot everyone for your help. I have solved this problem on my own. My only concern was about installing the SQL Server on client's machine but later i realized that i have to install a Database management tool (SQL Server) on client's system in order to make my application run.
Hence, I installed SQL Server Express on client's machine and change my QueryString a bit, as follows

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AG.mdf;Database=AG;Integrated Security=True;User Instance=True;Trusted_Connection=Yes

Moreover, i also gave the Full Control Permission as Allow on that folder which contains my deployed application, so that Dot Net Framework in my application can access the deployed .mdf database
Happy coding! :)

A: "|DataDirectory|\AG.mdf" in means that it need to look DB in the Data Directory, but not in the root folder of the application.
Small example how to set the DataDirectory:
AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory + "DB");


text:
Q: Non-X/Non-GUI terminal emulator for Ubuntu Server I have a computer running Ubuntu Server (non-X/non-GUI), I need a terminal emulator which has VT100/VT320 capabilities like Gnome-Term and xTerm do on my other (GUI) Ubuntu box.
tMux and GNU Screen don't work properly (they don't respond to all VT commands like Gnome-Term and xTerm do).
So besides tMux and GNU Screen, are there any other non-X/non-GUI terminal emulators out there for Ubuntu?
Don't need modem or telnet capabilities, just a shell.

A: Kermit emulates all kinds of terminals. DEC VT52, VT100, VT102, VT220, VT320 terminals,  the Heath/Zenith-19 terminal and Tektronix graphics 4010/4014 terminals are all build in but others can be made on the run.
It runs on many clients. I run mine on a DOS 8086 (thats pre XT), a DOS 80286 and Windows10. It also runs on ANY linux, unix, DOS, atari, commodore, MSX, android, Apple  and windows machine. It might be a bit complicated in the beginning but all commands and ini files etc. are the same on all platforms so like with linux once learned used everywhere.
Kermit is free.


text:
Q: Cookies set in Windows.Web.Http.HttpRequestMessage are ignored on redirects I'm using HttRequestMessage, and adding a cookie in an IHttpFilter as follows:
public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
{
    var c = new HttpCookiePairHeaderValue("SSOAutologonCertificate", "true");
    request.Headers.Cookie.Add(c);
    return InnerFilter.SendRequestAsync(request);
}

Using Fiddler I can see that the cookie is correctly added to the outgoing request. However, the reply is an auto-redirect. When fiddler captures that outgoing request, that cookie is no longer set in the http header - it seems to have been forgotten.
Is this expected behavior? Or a bug? If it is expected behavior, is there anything I can do to alter it?
If, on the other hand, I add the cookie to the Cookie collection on a HttpBaseProtocolFilter object, then everything works as expected, and the cookie is there for every auto-redirect query. Of course, while that will work for now, that totally defeats the purpose of a IHttpFilter. :-) This behavior was observed on a windows store app (running on Windows 10 tech preview).
BTW, I spent some time trying to figure out how to step into the .NET source for the Windows.Web.Http namespace, but nothing seemed to work (I can into other .NET source). Is there a special trick for these windows component files (the module is Windows.Web.winmd).
Thanks in advance!


text:
Q: How to convert this nested string list into the actual list How to convert string into new_list without using eval(), exec() or any other libraries?
string = '[1,2,3,[4,5,6],7,[8,[9,10]],11]'

new_list = [1,2,3,[4,5,6],7,[8,[9,10]],11]

A: The biggest problem you're facing with this question is that you cannot say how deep the list will nest, therefore the best option is to make a recursive function that evaluates the string and calls itself whenever it encounters a new list.
Another issue you will run in to is that a number can be multiple digits long and it would not be a clean solution to only assume it might be max 2 digits. A while loop to find all consecutive digits is probably the best solution for that. Here is my implementation:
def get_number(str, idx):
    """Find all consecutive digits and return them and the updated index"""
    number = ""
    while str[idx].isdigit():
        number += str[idx]
        idx += 1
    return int(number), idx

def recursive_list(str, idx):
    """Transform a string to list, recursively calling this function whenever a nested list is encountered."""
    lst = []
    # Loop over the entire string
    while idx < len(str):
        char = str[idx]
        # When encountering a digit, get the entire number
        if char.isdigit():
            number, idx = get_number(str, idx)
            lst.append(number)
            idx += 1
        # When encountering a closing bracket, return the (sub-)list
        elif char == ']':
            return lst, idx + 1
        # When encountering an opening bracket, append the nested list
        elif char == '[':
            nested, idx = recursive_list(str, idx + 1)
            lst.append(nested)
        else:
            # Go to the next character if we encounter anything else
            idx += 1
    return lst, idx

def main():
    """Transform a string to a list."""
    str = "[1,2,3,[4,5,6],7,[8,[9,10]],11]"
    new_list, _ = recursive_list(str, 1)
    print(new_list)

if __name__ == "__main__":
    main()


text:
Q: Change UI without lose Bluetooth connection I have 2 fragments which extends a Bluetooth fragment (connect, send, receive). The difference between the fragments is, that one have buttons and the other have an editText.
The Problem is, that when I change between them, the BT connection get lost, because I extend again the BT Fragment. How can I access my BT fragment from multiple other fragments? Can I acces from the button fragment over the FragmentActivity to the BT fragment? Or is an Interface the right way?

A: Try to separate BT layer from presentation layer. Use a Service to maintain BT connection, fetch data and forward it to the UI. Use fragments to subscribe to notifications coming from your service, e.g. via LocalBroadcastManager and display the data.


text:
Q: Delete Record Using eventname instead of ID i am currently creating a web page to delete data from a table using php by using name column in the table instead of ID. But it is not getting deleted when i give the input as event name.
<?php
    session_start();
    $servername = "localhost";
    $username = "database_admin";
    $password = "Veritasirum123";enter code here
    $dbname = "workflow";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    ?>

            <?php

            if(isset($_POST['submit'])){
                $ename=$_POST["ename"];
            $sql="DELETE from event where ename=$ename";

    if ($conn->query($sql) === TRUE) {
       echo '<script language="javascript">';
        echo 'alert("Event Deleted Successfully")';
        echo '</script>';
    } else {
        echo '<script language="javascript">';
        echo 'alert("Event Deletion Failed")';
        echo '</script>';
    }
    }
    ?>

A: please check
this variable value  :$ename=$_POST["ename"];
or
try using this variable :
$ename=$_GET["ename"];
or
please past event name static and check it

A: It can be a issue with the value you are parsing.. or can be a issue with datatype.. check your passing value and remove it's any white spaces by using trim() funcion
$ename=trim($_POST["ename"]);
then if ename field is string then you have to put single quotes. like below
$sql="DELETE from event where ename='$ename'";


text:
Q: Javascript highest number in each tr, skip 3 columns I have a table, that will add a class to the highest number in each tr.
I want it to skip the first 3 columns and not search them.  And then if there are multiple of the highest then bold those too.
I will paste code here as well as fiddle.
HTML

        no
        no
        no
        yes
        yes
        yes

        150
        name
        10.5
        1.5
        12
        9.3

        12.0
        name
        150
        150
        13.5
        150

        160
        name
        115
        15
        11
        160

        145
        name
        151
        12
        18
        18

JAVASCRIPT
jQuery(function($) {
    $.fn.max = function(callback) {
        var max = null,
            maxIndex = null;

        this.each(function() {
            var value = callback.call(this);
            if (+value === value) {
                if (!max || value > max) {
                    max = value;
                    maxIndex = $(this).index();
                }
            }

        });
        return max !== null ? this.eq(maxIndex) : $();
    };
}(jQuery));

$('tr').each(function()
    $(this).children('td').max(function() {
        var value = +$(this).text();
        if (!isNaN(value)) {
            return value;
        }
    }).addClass('highest');
});

FIDDLE
http://jsfiddle.net/65S7N/96/

A: Just add a selector as a parameter to the plugin, and filter by that :
jQuery(function($) {
    $.fn.max = function(selector) {
        var elems = $();
        this.each(function() {
            var max = 0,
                ele = $(this).find(selector).each(function(i,el) {
                var n  = parseFloat($(el).text());
                if ( n > max ) max = n;
            }).filter(function() {
                return parseFloat($(this).text()) === max;
            });
            elems = elems.add(ele);
        });
        return elems;
    };
}(jQuery));

$('tr').max('td:gt(2)').addClass('highest');

FIDDLE

A: To skip the first 3 columns, use:
$(this).children('td').filter(function(i) {
    return i > 2;
}).max(...)

The filter function receives the zero-based position of the element within the collection.
If you want to highlight multiple entries that have the max value, maxIndex needs to be an array, not a single value. When value === max, push the current index onto the array. Or make it a jQuery collection of elements, rather than indexes, and add the current element to it.

A: $('tr').each(function(){
    var this = $(this);
    var max = -Infinity;
    var indexes = [];
    this.find('td:gt(2)').each(function(index){
        var this_num = ($(this).text() >> 0);
        if ( max < this_num ) {
            max = this_num;
            indexes = [index];
        } else if (max == this_num ) {
            indexes.push(this_num);
        }
    });
    $(indexes).each(function(index){
        this.find('td:eq('+index+')').addClass('highest');
    });
});

should work.. haven't tested :|


text:
Q: Whats does pg_escape_string exactly do? I'm using the following script which takes the data from a html form and stores in a Postgres DB. There is this pg_escape_string function which stores the value from the form to the php variable. Searching the web throughout, I found that pg_escape_string escapes a string for insertion into the database. I'm not much clear on this. What does it actually escaping? What actually happens when its said that a string is escaped?

 <?php
 if ($_POST['submit']) {
     // attempt a connection
     $dbh = pg_connect("host=localhost dbname=test user=postgres");
     if (!$dbh) {
         die("Error in connection: " . pg_last_error());
     }

     // escape strings in input data
     $code = pg_escape_string($_POST['ccode']);
     $name = pg_escape_string($_POST['cname']);

     // execute query
     $sql = "INSERT INTO Countries (CountryID, CountryName) VALUES('$code', '$name')";
     $result = pg_query($dbh, $sql);
     if (!$result) {
         die("Error in SQL query: " . pg_last_error());
     }

     echo "Data successfully inserted!";

     // free memory
     pg_free_result($result);

     // close connection
     pg_close($dbh);
 }
 ?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
      Country code:
 <input type="text" name="ccode" size="2">

      Country name:
 <input type="text" name="cname">

      <input type="submit" name="submit">
    </form>

A: Consider the following code:
$sql = "INSERT INTO airports (name) VALUES ('$name')";

Now suppose that $name is "Chicago O'Hare". When you do the string interpolation, you get this SQL code:
INSERT INTO airports (name) VALUES ('Chicago O'Hare')

which is ill-formed, because the apostrophe is interpreted as a SQL quote mark, and your query will error.
Worse things can happen, too. In fact, SQL injection was ranked #1 Most Dangerous Software Error of 2011 by MITRE.
But you should never be creating SQL queries using string interpolation anyway. Use queries with parameters instead.
$sql = 'INSERT INTO airports (name) VALUES ($1)';
$result = pg_query_params($db, $sql, array("Chicago O'Hare"));

A: pg_escape_string() prevent sql injection in your code


text:
Q: Is there any method to regenerate cms/blocks in magento2 without sql file? So far, I developed cms/blocks on staging server directly, therefore I have no any local dev environment.
Suddenly server HDD was crashed and i failed to restore data on server.
All my codes have been managing by git but can't find any certain files that are related to cms/blocks

A: The content of CMS blocks are stored in the database table cms_block. There is not backup in the filesystem.