text:
Q: AutoARIMA performance I am  trying to implement a pmdarima AutoARIMA estimation exercise for learning reasons.
Observation is that, selected model fits the train data quite well, however it performs poorly on test data, at a glance.
Dataset is daily temperatures from 1981.01.01 to 1990.12.31 with strong cycle behaviour. Best model found by pmdarima.AutoARIMA is ARIMA(1,0,3)(0,0,0)[0].
I am not sure if the model should perform better on test data or results cannot be improved further for this dataset.
My question is, why the same model performs so differently on train and test data despite that they have similar properties?
Thank you very much.
import matplotlib.pyplot as plt
import pandas as pd
import pmdarima as pm
from sktime.forecasting.model_selection import temporal_train_test_split
from data_preparation import data_preparation

y = data_preparation('D:/Stat/dataset/temperatures.csv', 'Date', 'Temp', 'D')
y_train, y_test = temporal_train_test_split(y, train_size = 0.8)
forecaster = pm.auto_arima(y_train, trace = True)
fitted = forecaster.predict_in_sample()
forecast = forecaster.predict(len(y_test))
fitted = pd.Series(fitted, index = pd.date_range(start = y_train.index[0], periods = len(y_train) + 1, freq='D', closed='right'))
forecast = pd.Series(forecast, index = pd.date_range(start = y_test.index[0], periods = len(y_test) + 1, freq='D', closed='right'))

figure = plt.figure(figsize=(12, 5))
figure.suptitle("AutoARIMA - Temperatures")
new_plot_1 = figure.add_subplot(111)
new_plot_1.plot(y_train.index, y_train.values, 'darkblue')
new_plot_1.plot(y_test.index, y_test.values, 'darkgreen')
new_plot_1.plot(fitted, 'royalblue')
new_plot_1.plot(forecast, 'red')

A: As jbowman notes, you are not telling auto_arima that these are seasonal data with cycle length (about 365). auto_arima does not automatically detect season cycle length, which would be very hard, and possibly impossible if you have multiple-seasonalities. See also here. So tell your code about the seasonality, e.g., by setting m=365 and seasonal=True.
However, even then auto_arima may not pick up on the seasonality. This is a well-known weakness of ARIMA for seasonality with long periods. You can in principle force it to use seasonality, e.g., by setting D=1 to force seasonal differencing. Note that this is not the only way to make ARIMA work with seasonality: you could also try to enforce SARIMA components, like SAR(P). Unfortunately, I do not think that auto_arima allows you to fix the SARIMA orders, or specify minimum SARIMA orders. (At least the default value of start_P=1 will start out with an SAR(1) component.)
Finally, a better approach especially for highly regular seasonality as here would likely be Fourier terms to model seasonality in ARIMA models.


text:
Q: Method to solve a system of nonlinear equations Suppose that I have the following system,
$$
\begin{equation}
    \left\{\begin{array}{lcl}
    a + b + c + d & = & \alpha \\
    a^2 + b^2 + c^2 + d^2  & = & \beta \\
    a^3 + b^3 + c^3 + d^3& = & \gamma \\
    a^4 + b^4 + c^4 + d^4& = & \theta
    \end{array}\right.
\end{equation}
$$
in which I know that $\alpha, \beta, \gamma$ are positive, $\alpha=1$, $\beta<1$, $\gamma<1$, and $\theta<1$. If I know the values of $\beta$, $\gamma$, and $\theta$, how can I find $a, b, c, d$? Can someone tell me if there is a method to solve this? Which system of equations is this one? Does this have a specific name?

redpajama_set_name: RedPajamaStackExchange


text:
Q: First check value before we put it into an if statement (CLOSED) I have a form with the following select inputs:
In the first file:
<select class="form-control" name="city" id="city">
    <option value="">--</option>
    <option value="breda">Breda</option>
</select>

<select class="form-control" name="interior" id="interior">
    <option value="">--</option>
    <option value="gestoffeerd">Gestoffeerd</option>
</select>

In the second file I retrieve that data
$search_city = $_POST['city'];
$search_interior = $_POST['interior'];

I also have a variable: $result this is an array that I retrieved from an api. In this array are some houses. Each house has some specs as a city and an interior spec.
I want all houses based on what I select in the select form.
When i for example selected a city but not an interior then I will retrieve all houses form that city
When i for example selected an interior but not a city then I will retrieve all houses with that interior from all city's
When i for example nothing selected then I will retrieve all houses
if(isset($search_city) == $result['city'] && isset($search_interior) == $result['interior']){
    // echo all results based on selected values
}

A: In your form, you can change the HTML of the dropdown's first option to be empty:
    <select class="form-control" name="city" id="city">
        <option value="">--</option>
        <option value="breda">Breda</option>
    </select>

    <select class="form-control" name="interior" id="interior">
        <option value="">--</option>
        <option value="gestoffeerd">Gestoffeerd</option>
    </select>

Then in your PHP logic, you would check if it's empty:
if ( !empty( ucfirst($_POST['city'] ) ){
    $city = ucfirst($_POST['city'];
}

if ( !empty( ucfirst($_POST['interior'] ) ){
    $city = ucfirst($_POST['interior'];
}


text:
Q: How to write the code in VB from MS access Working on this database in MS Access and tried to put it in VB.net..
in my MS access the "Replace" work as what it is suppose to do. but when i tried it in vb.net "Replace" function does not work.. some Advice they give is that to work it around with LEFT and RIGHT function with also LEN in it.. how could i do it? I tried by I failed..
This in MS ACCESS: How could i Write in VB?
 Replace(Replace(Trim([f_7Synonyms].[SynSpecies]),"var. ",""),"f. ","") AS Speciest


text:
Q: Transactional API Journeys - Split decisions - Marketing Cloud I would ask about the proper design and approach for Transactional Api Journeys with localized content. Imagine status Emails for 6 different countries. Right now it is done using a multistep Journey with an API Entry Event. Inside Journey, there is a decision split for colour or language. So the right person receives a correct status email. The downside of that solution is a slightly low delivery time and no option to set the callback with track data.
A much better solution in my mind is to use API Transactional Journeys, but each separate Journey for each case sounds painful to me.
Is there a way to create decision splits in Transactional Api Journeys in Marketing Cloud or just AMPSCRIPT on the email level?

A: This is a quite standard case for a localization Data Extension.
Imagine you will have a data extension with following fields:

language
color
subject
title
text
cta_text

EN
Red
Thanks for purchasing our red product
Red products are the best
You will love them
See more red products

DA
Red
Tak fordi du købte vores røde produkt
Røde produkter er de bedste
Du vil elske dem
Se flere røde produkter

In the transactional API payload, you should include the language and color parameters for this particular recipient. You will then use these values to lookup the correct version of the content, and use it to populate your email:
var @rows, @row, @rowCount, @lang, @color, @i

set @lang = AttributeValue("language")
set @color = AttributeValue("color")

set @rows = LookupRows("Translations","language", @lang, "color", @color)
set @rowCount = rowcount(@rows)

if @rowCount > 0 then

    var @subject, @title, @text, @cta_text
    set @row = row(@rows, @i)
    set @subject = field(@row,"subject")
    set @title = field(@row,"title")
    set @text = field(@row,"text")
    set @cta_text = field(@row,"cta_text")

ENDIF


text:
Q: Arduino MKRFox1200 Configuration I want to install a Arduino MKRFox1200 .
I've installed the drivers,

but i can't find it in the IDE

and even its installed I see this message in the IDE

and this is the result of Get Board Info, but the board is flashing green

A: You need to install the MKRFox board support package.
Follow the getting started instructions and add the Atmel SAMD Core to your Arduino IDE from the Board Manager.
After you installed it, you should be able to select select the MKRFOX1200 in Tools>Board


text:
Q: Cannot install Scipy in FreeBSD 13 with Python 3.10 I am trying install scipy in FreeBSD 13. I have built python 3.10 on FreebSD 13 and managed to install pandas, matplotlib and numpy on a virtual environment which has python 3.10. However, when I try to install sklearn or scipy I get an error saying scipy could not be installed.
Here it is below for when doing pip install scipy. I get the same error more or less when trying to install sklearn.
ERROR: Failed building wheel for scipy
  Failed to build scipy
  ERROR: Could not build wheels for scipy, which is required to install pyproject.toml-based projects
Command errored out with exit status 1: /home/schroter/.pymain/dataViz/bin/python3 /tmp/pip-standalone-pip-d3nnvp2f/__env_pip__.zip/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-xp_669rf/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'Cython>=0.28.5' 'oldest-supported-numpy; python_version!='"'"'3.7'"'"' or platform_machine=='"'"'aarch64'"'"' or platform_system=='"'"'AIX'"'"' or platform_python_implementation == '"'"'PyPy'"'"'' 'numpy==1.14.6; python_version=='"'"'3.7'"'"' and platform_machine!='"'"'aarch64'"'"' and platform_system!='"'"'AIX'"'"' and platform_python_implementation != '"'"'PyPy'"'"'' 'scipy>=1.1.0' Check the logs for full command output.

My pip list is as below:
(dataViz) schroter@SCHROTER:~ % pip list
Package          Version
---------------- -------
cycler           0.11.0
kiwisolver       1.1.0
matplotlib       3.4.3
numpy            1.21.4
pandas           1.3.4
Pillow           8.4.0
pip              21.3.1
pyparsing        3.0.6
python-dateutil  2.8.2
pytz             2021.3
semantic-version 2.8.5
setuptools       58.5.3
setuptools-rust  0.12.1
six              1.16.0
toml             0.10.2
wheel            0.37.0

Would anyone be able to help me in this regards please?
Thanks & Best Regards
Schroter

A: Reuse system package
# install system-wide version in site-packages
doas pkg install py38-scipy-1.8.0
# create a virtualenv with site-packages included
python -m venv --system-site-packages .venv

Drawback is you'll get all packages from site-packages, however you can tackle that by
doas pkg install py38-scipy-1.8.0
python -m venv .venv

YOUR_PYTHON_VERSION= SET IT HERE
ln -s $(python -c 'import lxml, os.path; print(os.path.dirname(lxml.__file__)') ./.venv/lib/$YOUR_PYTHON_VERSION/site-packages

borrowed from https://stackoverflow.com/a/13719417
Regular Installation (TODO)
Haven't figured out it yet, but maybe someone else will, so putting here 2 links which might be helpful

*

*https://forums.freebsd.org/threads/python-scipy-with-python3-x-on-freebsd-11.59009/

*https://reviews.freebsd.org/D23447

A: Have you tried to install scipy from freebsd ports? The freebsd ports contain patches to make the code compile on FreeBSD.


text:
Q: Why we use Dual supply Emitter Bias in Transistor As i am studying about DC Biasing of transistor, i am just able to fully understand only Base Bias after that i am stuck at Emitter Bias which is also called Dual Supply Emitter bias where we apply voltage Vee to emitter, Now my question is, In Emitter bias we know Ic become independent of Beta when Base voltage become zero, it means as it gets independent of Beta so its operating point will be stable.. and the problem is solved.. than why we move to other bias conditions like Collector feedback bias or voltage divider bias etc etc why we dont end the game at Emitter bias after studying Base Bias. Thankyou.

A: With an BJT transistor in a linear circuit, you need to make the collector current (Ic) not depend on the HFE (used to be called Beta) of the transistor.
The usual method is to make some resistor on the emitter have a lot more voltage drop than the Vbe (Base to Emitter) of the transistor.
This can be done by having a positive and negative supply voltage and keeping the Base near zero volts.  Life, however, often doesn't give you two supply voltages. In that case, setting the base at some voltage part way between the positive and negative supplies is much easier than having to make a new power supply circuit. This is the two resistor voltage divider in many designs.
Sometimes you may find your self designing in a case where adding one more component will be objected to by management.  A resistor from the collector to the base of a BJT takes fewer parts than the voltage divider.
Sometimes the supply voltage you have is much too low for a normal design.  In this cases, you must get very creative about biasing of the transistors.

A: It can be shown - as far as DC bias point stability against tolerances and temperatur changes is concerned - that the best bias method is to use

*

*a resistive voltage divider at the base node for providing a bias voltage Vb as "stiff" as possible. For this purpose the resistor niveau should be as low as possible - depending on some limits set by allowed DC power consumption as well as input resistance of the whole circuit. In this case, the "unknown" value of the base current (due to large beta-tolerances) plays a minor role only.

*an additional resistor Re in the emitter path for providing negative DC feedback. In this case, any unwanted increase of the collector current will increase the voltage Ve at the emitter node (npn case) and, thus, reduce Vbe=Vb-Ve. Hence, this effect will counteract the Ic increase up to a certain degree.


text:
Q: Explanation of an equation Given a system $AX=B$ and a perturbed system $(A+E)Y=B+F$ with $E$ and $F$ being the perturbation matrices, how does the following second equation come? Consider $A$ and $(A+E)$ both to be invertible.
$$X-Y=A^{-1}B-(A+E)^{-1}(B+F)=(A+E)^{-1}(EX-F)$$

A: It's \begin{align}(A+E)(A^{-1}B-(A+E)^{-1}(B+F))&=(A+E)A^{-1}B-B-F\\&=B+EA^{-1}B-B-F\\&=B+EA^{-1}B-B-F\\&=EX-F\end{align}


text:
Q: close the batch file command scripts I have the following batch file script code to run. When I run it, it executes successfully, but does not close the cmd window automatically. What should I add to have it close the window automatically?
::Copy Files Made Or Modified Today
@echo off
setlocal
set source=c:\src
set dest=c:\dest
pushd "%source%"
set t=%date:~4%
for /f %%a in ('dir /b /a-d /o-d') do call :PROCESS "%%a"
goto :eof
popd

:PROCESS
for /f %%j in ('echo %~t1') do set d=%%j
if "%d%"=="%t%" copy %1 "%dest%"
goto :eof

A: Test this if you are clicking on the batch file.
@echo off
::Copy Files Made Or Modified Today
setlocal
set source=c:\src
set dest=c:\dest
pushd "%source%"
set t=%date:~4%
for /f %%a in ('dir /b /a-d /o-d') do call :PROCESS "%%a"
cls
goto :eof
popd

:PROCESS
for /f %%j in ('echo %~t1') do set d=%%j
if "%d%"=="%t%" copy %1 "%dest%"
goto :eof


text:
Q: Excel - How to display information or move on to next column if blank So this may be a little confusing.
I'm trying to figure out how to get excel to display a cell's text or move onto another column if that original cell is blank.
In other words, if A1 has "Dog", I want it to display "Dog". But if A1 is blank, I want it to check C1. If C1 has "Cat" in it, I want it to display "Cat". If C1 is blank, I want it to check E1....so on and so forth.
Is this possible?
Thanks!

A: I think everybody is overthinking this a bit. There's no reason at all to use VBA. Just use a combination of the Excel formulas IF and ISBLANK.
=IF(ISBLANK(A1),IF(ISBLANK(C1),E1,C1),A1)

A: Try something like this:
Option Explicit

Sub A()

Dim rng As Range, cell As Range
Set rng = Range("A1:G2")
Dim jump As Boolean
jump = False

For Each cell In rng
If jump = False Then
    If (cell.Value <> "") Then
        MsgBox ("Contents of cell at row:" & cell.Row & "," & cell.Column & vbCrLf & "is:" & vbCrLf & cell.Value)
    Else
    'if A1 has "Dog", I want it to display "Dog". But if A1 is blank, I want it to check C1
    jump = True
    End If
Else
    jump = False
End If
Next cell

End Sub

A: This is one possible approach. Keep in mind, it doesn't break in case of NO entry, so it will throw an error once it reaches the end of the sheet.
Sub ShowText()
    Dim rngStart As Range
    Dim strResult As String

    Const OFFSET_VALUE As Integer = 2

    Set rngStart = ActiveSheet.Range("A1")
    strResult = ""

    Do
        strResult = rngStart.Value
        Set rngStart = rngStart.Offset(, OFFSET_VALUE)
    Loop While strResult = ""

    MsgBox strResult

End Sub

A: This seems to work:
Range("A1").Select

Do While IsEmpty(Selection.Value)
Selection.Offset(0, 2).Select
Loop

MsgBox Selection.Value


text:
Q: Сравнение массивов c# У меня есть два массива, и их надо сравнить, но один из них необходимо сравнивать, начиная с 16 элемента, а второй с начала. Так вот, существует ли какая нибудь функция, либо быстрый метод для такой операции? Ибо сейчас просто переписываю в новый массив все элементы 1 массива, начиная с 16, а уже потом их сравниваю. Эта операция повторяется у меня в цикле сравнение различных хешей, поэтому быстродействие здесь как никак нужно.
resultArr = new byte[cleartext.Length - 16];

Array.Copy(cleartext, 16, resultArr, 0, cleartext.Length - 16);

if (resultArr.SequenceEqual(key_64bytes))


text:
Q: how can I insert a background image in react for the whole screen? I am developing a react web page.
 var sectionStyle = {
      width: "100%",
      height: "100%",
      backgroundImage: "url(" +  background  + ")"
    };

This way, I tried to insert a background image. The background image is visualized only up to the amount of content available inside the div.
I want to view it on the whole screen.

A: Try height: "100vh" instead of 100%

A: Try This way:
 var sectionStyle = {
      width: 100vh,
      height: 100vh,
      backgroundImage: "url(" +  background  + ")"
    };


text:
Q: Automatically Post to Google + Business Page Is it possible to post to Google + through PHP using some kind of API? I've read many conflicting statements on various places, including here on SO.
I've read that you need an analytics account, that you need to add a website to your page, that it isn't possible, that it's a closed service and you must apply, that you need your GMail username & password .etc.
Just really looking for a bit of clarity really. Found this, but I'm not sure if it allows this functionality. The lack of documentation really makes it quite daunting looking into this as well, there is literally nothing I can find at all.
Another option I've found appears to work, however it was from a website where you must pay to download the API. I'm genuinely not sure how or if it can be done.

A: Google restrict this API to whitelisted partners and companies through https://developers.google.com/+/web/api/rest/pages-signup
You could however use a third party script such as https://gist.github.com/zachbrowne/3301749 which handles the posting as if it was a logged in front end user rather than a direct API update flow.


text:
Q: Adding html links to response of chatbot i am making a chatbot in node js and i am able to fetch the response
But the links are also shown as text. i want to display them as links
 responseText = `You want to learn about ${agent.parameters.course}.
                  Here is a link to the course: ${coupon.link}`;

I need help converting the link text to html
i tried this ```
     responseText = `You want to learn about ${agent.parameters.course}.
                    Here is a link to the course: ` + `${coupon.link}`;

but this is not working .Response i am getting from chatbot is

You want to learn about chatbots. Here is a link to the course: https://www.udemy.com/user/jana-bergant

**Is there any way of parsing the string (use regular expression) and when you find a link in the string, add the html tag (<a href="...) around it.?
**

A: Use Link method to convert you links from strings.
For Ex :

 var str = "This is link";
var link = str.link("https://www.somelink.com");
var msg = "Hi "+link;
document.write(msg);

A: Try:

let course = 'https://www.google.com';
let coupon = 'https://www.stackoverflow.com';

const courseLink = `<a href='${course}'>${course}</a>`;
const couponLink = `<a href='${coupon}'>${coupon}</a>`;

responseText = `You want to learn about ${courseLink}.
                  Here is a link to the course: ${couponLink}`;

document.body.innerHTML += responseText;

A: On what integration (Facebook Messenger, Google Assistant) are you testing this? Messenger should make links clickable, but unfortunately Google Assistant doesn't allow this.

A: it depends on your html lets say your div for messages is called
bot_msg so all you need to do is:
html = '
' + 'click here to do sth' + '
';

here I link to js fnc called do_sth in same html page. Then you append html string.


text:
Q: javalite could not find or load main class After successfully following along the instructions of the javalite example project (here), the command line returns:

Could not find or load main class activejdbc.examples.simple.Main

when trying to execute:
java -classpath target/dependency:target/classes activejdbc.examples.simple.Main
Maven: 3.6.0
Java: jre1.8.0_191, jdk1.8.0_201
Operating System: Windows 10 (64-bit).
All commands were executed in folder simple-example-master.
Output of each command is here

A: that command is good for Linux. On Windows, you need to use backslashes and smi-colon in place of a colon:
java -classpath target\dependency;target\classes activejdbc.examples.simple.Main

I will update the docs


text:
Q: Prevent indent in exam class so that I can repeat question text on next page (next part) How can I make a repeated question not indent using documentclass exam?
I want to repeat the question number and text on the next page, for part B. I've tried just retyping the question, including question number that I know it's going to get and the \noindent (as you can see below), but no help.
\begin{questions}

\question Question 1

\newpage
\question QUESTION 2 TEXT

\begin{parts}
\part Question 2, Part A

\newpage
\noindent 2. Repeat QUESTION 2 TEXT

\part Question 2, part B

\end{parts}
\end{questions}

A: The exam class has two commands for this:
\uplevel{} moves up one level, so it writes its argument at the "question" level from within a "parts" list.  It does include the normal paragraph indentation.
\fullwidth{} writes its argument without any indentation as if it were outside the questions environment.
You probably want the \uplevel{} command.
Documentation: Section 6. http://www-math.mit.edu/~psh/exam/examdoc.pdf


text:
Q: python subprocess - How to check if there is not any new data in the PIPE? I have the following example:
import subprocess

p = subprocess.Popen("cmd",stdin = subprocess.PIPE, stdout=subprocess.PIPE )
p.stdin.write(b'cd\\' + b'\r\n')
p.stdin.write(b'dir' + b'\r\n')
p.stdin.write(b'\r\n')

while True:
    line = p.stdout.readline()
    print(line.decode('ascii'), end='')
    if line.rstrip().decode('ascii') == 'C:\>': #I need to check at this point if there is new data in the PIPE
        print('End of File')
        break

I am listening to the PIPE for any output from the subprocess and if there is not any new data coming through the PIPE I would like to stop reading. I would like to have a control statement that would tell me that PIPE is empty. This would help me to avoid problems in case my process freezes or ends with an unexpected result.

A: Unless the process is over or there is a signal you are expecting to stop reading at, there is no good way to know ahead of time if there is data in the pipe, because the command will only terminate when it reaches the number of bytes you want to read [.read(n)], reaches a newline char [.readline()], or reaches the end of the file (which doesn't exist until the process is over).
However, you don't need to run cmd.exe to run your program, since your program will already be run in the cmd shell.
I suggest you use subprocess to call the program directly, and handle exceptions/return_code in your code.  You could do something like...
import subprocess
import time

p = subprocess.Popen("your_program.exe",
                     "-f", "filename",
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE)

# If you have to use stdin, do it here.
p.stdin.write('lawl here are my inputs\n')

run_for = 0
while p.poll() == None:
    time.sleep(1)
    if run_for > 10:
        p.kill()
        break
    run_for += 1

if p.return_code == 0:
    ...handle success...
else:
    ...handle failure...

You could do this in a loop and spin up a new process that would run the next file.
If it's that costly to spin up the program (and if it's not then stop reading now because it's about to get embarrassing) then perhaps (and this is a total hack, but) after your process has run a while, you could pass a particularly odd but innocuous string to p.stdin, as in p.stdin.write("\n~%$%~\n").
If you could get away with that, then you could do something like...
for line in p.stdout.readlines():
    if '~%$%~' in line:
        break

But holy crap, please don't do that.  It's such a hack.


text:
Q: Where can i find the options for Selenium module? Where can i find all the configurable options for Selenium module in Python?
For example, the code below are some of the configurable options for the webdriver, but there seems to be no documentation on the full list of options.
Does anyone have a good documentation on the options? Much appreciated!
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
chrome_options.add_argument('headless')

Couldnt find the documentation online

A: You can find all the Chrome command line switches here:
https://peter.sh/experiments/chromium-command-line-switches/


text:
Q: Is it possible to change signing of apk? The client needs signed APK, but he does not gave us existing key. Meanwhile client also cannot create signed apk from code we gave him. The only options he ever consider: we gave him apk and he signed it with existing jks. however when he try to sign it with  the Jarsigner tools to re-sign the app with their Google Enterprise key, it is throwing an error:
unable to sign jar: java.io.EOFException: Unexpected end of ZLIB input stream

There is something possibly wrong with GZIPInputStream or GZIPOutputStream, or possibly there is no gz.close(); which would need to be called on the GZIPOutputStream in order for the code to read it.v

A: You can't update the app with different .jks file.
For more details read this doc  also share with your client.


text:
Q: What does CPU utilization mean? When I say my utilization is 40% what does it mean actually?
This is my understanding: Say the CPU is capable of processing 100 instructions per second, whereas the CPU is given only 40 instructions (by all processes running) per second, then I can say it's 40% utilization.
Say out of 40 instructions, 30 instructions are given by process A and 10 instructions by process B. Then I can say process A's CPU utilization is 30% and
process B's CPU utilization is 10%. Is that correct?


text:
Q: NSDateFormatter giving me two different days of the week, for the same date have a bunch of dates, and I am trying to get their days of the week. But whenever, I loop through, even after midnight, the day of the week doesn't change for a few hours, and I don't know why.
Here's my code:
func parseArray(array: [HKQuantitySample])
{
let formatter = NSDateFormatter()
formatter.dateFormat = "EEEE"

for element in array
{
    let startDate: NSDate = element.startDate //example: 2015-11-13 13:30:07 +0000

    let startDateArray = String(startDate).componentsSeparatedByString(" ") // example: ["2015-11-13", "13:46:53", "+0000"]

    let startDateString = startDateArray[0] // example: 2015-11-13
    let startDateTimeString = startDateArray[1] // example: 13:58:39

    let startDateDayOfTheWeek = formatter.stringFromDate(startDate)

    print("startDate: \(startDateString), startTime: \(startDateTimeString), dayOfWeek: \(startDateDayOfTheWeek)")
}

Here is what I am getting:
startDate: 2015-11-12, startTime: 23:32:01, dayOfWeek: Thursday
startDate: 2015-11-12, startTime: 23:41:19, dayOfWeek: Thursday
startDate: 2015-11-12, startTime: 23:50:36, dayOfWeek: Thursday

/* midnight */
startDate: 2015-11-13, startTime: 00:07:35, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 00:19:19, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 00:32:20, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 00:41:37, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 00:55:34, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 01:04:51, dayOfWeek: Thursday
2016-06-21 17:39:10.446213 appleWatchHealth[1173:238873] [MC] Reading from public effective user settings.
startDate: 2015-11-13, startTime: 01:14:57, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 01:24:50, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 01:36:39, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 01:45:56, dayOfWeek: Thursday

So even after it changes from the 12th to the 13th, it keeps giving me Thursday. However it does change to friday at around 1 pm:
startDate: 2015-11-13, startTime: 13:01:31, dayOfWeek: Friday

Also, I have no idea what this last line means:
2016-06-21 17:39:10.446213 appleWatchHealth[1173:238873] [MC] Reading from public effective user settings.

A: String (startDate) uses the description of startDate, which is purely for debugging purposes. You should never, ever use it for something that an enduser sees. Therefore there is no way to make it display anything else than what you see.
NSDateFormatter should be used whenever you want to convert an NSDate to something that the end user sees.


text:
Q: how to fix "Caused by: java.lang.IllegalStateException: No element found in 'only'" in Kotlin I want to select a value from DB in Kotlin but getting "Caused by: java.lang.IllegalStateException: No element found in 'only'" error.
I have written a class and and I have used map as RowMapper

class MarketplaceGetEffectiveRateQuery(private val handle: Handle) {

    fun run(resourceUUID: UUID,subscriptionUuid: UUID): BigDecimal {
       return handle.createQuery(GET_EFFECTIVE_RATE_QUERY)
            .bind("resourceUUID", resourceUUID)
                .bind("ms_subscription_id", subscriptionUuid)
            .map(EffectiveRateMapper())
                .findOnly()
    }
}

   override fun map(rs: ResultSet, ctx: StatementContext): BigDecimal {
       return rs.getBigDecimal("effective_rate")
    }
}

A: I'm assuming that you are using JDBI.
If so then this is absolutely correct behavior
public interface ResultIterable<T> extends Iterable<T> {

     /**
     * Get the only row in the result set.
     * @throws IllegalStateException if zero or multiple rows are returned
     * @return the object mapped from the singular row in the results
     */
    default T findOnly() { ... }
}

Note @throws IllegalStateException if zero or multiple rows are returned
Hence you should only use findOnly() when you are absolutely sure that a query always produces a single result


text:
Q: How to send a JavaScript object along with an html form? I have an HTML form, which has quite a few input fields. As the user types in one of them, JavaScript generates a few objects that contain data I need to get to the server. I know I can send these objects with AJAX, but I need them to end up in the same function as the normal data from the form once they get server-side (I'm using flask for the backend). Is there any way I can send the objects along with the form, so that they somehow end up in the same place?
Here is the beginning of the form:
<form action="/org/new-task" method="post">

        <select name="rep-type" class="form-select">
            <option selected disabled>Type of task</option>
            <option value="0">Ongoing/repeating</option>
            <option value="1">One-off</option>
        </select>

    ...

and here is the output when I console.log() one of the objects (there are multiple, but they are very similar):
(2) ["painting", "cleaning"]

A: To have some objects sent with a "normal" form submit... You could store those in some hidden input elements as string.
You will have to parse that string on the python side. Look here for how

let some_object = {
  name: "John",
  last: "Doh"
}

// Stringify the object and store it in the hidden input
let hidden_input = document.querySelector("[name='js_object']")
hidden_input.value = JSON.stringify(some_object)

// Just for this demo... to console log something.
document.querySelector("form").addEventListener("submit", function(e){
  e.preventDefault()
  console.log(hidden_input.value)
  console.log(typeof(hidden_input.value))
})
<form>
  <input type="hidden" name="js_object">
  <button type="submit">Submit</button>
</form>

A: You have either a hidden input or can serialize the form on submit and submit it using JavaScript. It's probably simpler to avoid the DOM updates though and just use JS:
From MDN:
Using FormData bound to a form element
You can also bind a FormData object to an  element. This creates a FormData object that represents the data contained in the form.
The HTML is typical:
<form id="myForm">
  Send me your name:
  <input id="myName" name="name" value="John">
  <input type="submit" value="Send Me!">
</form>

But JavaScript takes over the form:
window.addEventListener( "load", function () {
  function sendData() {
    const XHR = new XMLHttpRequest();

    // Bind the FormData object and the form element
    const FD = new FormData( form );

    // Define what happens on successful data submission
    XHR.addEventListener( "load", function(event) {
      alert( event.target.responseText );
    } );

    // Define what happens in case of error
    XHR.addEventListener( "error", function( event ) {
      alert( 'Oops! Something went wrong.' );
    } );

    // Set up our request
    XHR.open( "POST", "https://example.com/cors.php" );

    // The data sent is what the user provided in the form
    XHR.send( FD );
  }

  // Access the form element...
  const form = document.getElementById( "myForm" );

  // ...and take over its submit event.
  form.addEventListener( "submit", function ( event ) {
    event.preventDefault();

    sendData();
  } );
} );

I'd suggest replacing the XHR with a fetch request though, or using whatever library you're using in place of it. This is the most flexible in that you can now process how you want to send the FormData. You can change it into JSON and make your processing on the server that much easier.


text:
Q: Linear Combination of some vector Sorry for my newbish ways but i don't know how to write out everything here yet so bare with me.
The question asks to write some vector in $S$ as a linear combination of the others.
the vectors are:
$v1 = [0,0,0]$
$v2 = [-2,3,-4]$
$v3 = [4,-3,2]$
i got the reduced row echelon form which is
\begin{matrix}
0 & 1 & 0\\
0 & 0 & 1\\
0 & 0 & 0
\end{matrix}
So what do i do from here? Is $x_1$ a free variable or just 0 or is $x_2$ a free variable?
I honestly have no idea where to start due to all the $x_1$'s being 0.

A: Let us name these vectors as X, Y and Z respectively where X is the zero vector. Since one of the given vectors is a zero vector, they are certainly dependent and one can be written as a linear combination of the two others. One way to do this is:
      kX=0Y+0Z where k is any real.

A: By applying elementary row operations on your reduced row echelon form you will have the matrix:
\begin{matrix}
0 & 0 & 0\\
0 & 1 & 0\\
0 & 0 & 1
\end{matrix}
Note that the first row have no leading 1, this means that $x_1$ is a free variable. So you are correct.
Knowing $x_1$ a free variable, you can now solve for the solution set of your equations.


text:
Q: Is there a way to 'tag' text within a cell such that that text can be formatted differently and handle click actions? Is there a way to tag areas of text such that the reader knows he/she can click on the text and perform some actions on it such as go to a url.
Ideally the background could be formatted to a 'highlight' color. Once the tag is recognized, 'hover over' and click actions could be implemented.


text:
Q: Need help to parse file We have a file with below information:
Files: *
License: LGPL-2+
Files: po/bg.po
       po/eo.po
       po/sl.po
       po/sv.po
       po/th.po
       po/tr.po
License: LGPL-2+
Files: po/te.po
License: LGPL-2+
Files: po/vi.po
License: LGPL-2+
Files: tls/tests/mock-pkcs11.*
License: LGPL-2.1+
Files: dbus-1/dconf-dbus-1.*
       tests/gsettings.c tests/dbus1.c
License: GPL-3+
Files: debian/*
License: GPL-3
Files: po/fi.po
License: LGPL-2+

I want to combine all files which are under same license, looking for the output in below format :
LGPL-2+(*,po/bg.po,po/eo.po,po/sl.po,po/sv.po,po/th.po,po/tr.po,po/fi.po,po/te.po,po/vi.po),LGPL-2.1+(tls/tests/mock-pkcs11.*),
GPL-3+(dbus-1/dconf-dbus-1.*,tests/gsettings.c tests/dbus1.c),GPL-3(debian/*)

----or----
LGPL-2+(*,po/bg.po,po/eo.po,po/sl.po,po/sv.po,po/th.po,po/tr.po,po/fi.po,po/te.po,po/vi.po)
LGPL-2.1+(tls/tests/mock-pkcs11.*)
GPL-3+(dbus-1/dconf-dbus-1.*,tests/gsettings.c tests/dbus1.c)
GPL-3(debian/*)

Any helps appreciated.Thanks in advance!!

A: awk to rescue:
$1=="License:"{
  a[$2]=a[$2](a[$2]?",":"")f;
  next
}
$1=="Files:"{
  f=$2
  next
}
{
  for(i=1;i<=NF;i++)
    f=f (f?",":"")$i
}
END{
  for(i in a)
    printf "%s(%s)\n",i,a[i]
}

The variable f is filled with filenames. When the keyword License: is found, all files in the variable f are copied to the array a.
The END statement just print the content of the array.
Note the (...?...:...) which is the inline C style if ... then ... else ... statement used for adding the comma , inbetween each filename.


text:
Q: Loading a .js file conditionally. How? First demo is a .js file which is loaded with:
<script src="https://cdnjs.cloudflare.com/ajax/libs/zooming/1.4.2/zooming.js"></script>
https://codepen.io/zuhocuyixu/pen/oqpdWz
 The .js adds a nice zooming feature to the image.
Second demo is trying to load the same .js file with head.js. It does not work.
https://codepen.io/zuhocuyixu/pen/XEVEwG

Any advice on why this is not working?

A: If you look at your dev tools, you will find zooming is actually loading.
Your problem is zooming is loaded after your document html has been loaded, so you will need to tell zooming to re-parse,.
I don't personally use Zooming, but try ->
head.load('https://cdnjs.cloudflare.com/ajax/libs/zooming/1.4.2/zooming.js', function () {
  new Zooming();
});

A: I recommend looking through the zooming.js docs
You can initialize the zooming on images like this yourself:
head.ready(document, function() {
    head.load('https://cdnjs.cloudflare.com/ajax/libs/zooming/1.4.2/zooming.js', function() {
         var zooming = new Zooming();
         zooming.listen('.my-img');
    });
});

and change your html to this:
<img
    class="my-img"
    style='max-width: 100%;'
    draggable="false" ondragstart="return false;"
    src="https://image.ibb.co/bxRTKn/trees_crop.jpg"
    data-original="https://preview.ibb.co/eRYm5S/trees.jpg"
    alt="test"
/>


text:
Q: Zend Framework 2 - Some Begginner Questions this is my first question,
I'm a ZF2 Beginner and I have some questions related with the tutorial I'm following ("Zend Franework 2 by Example").
I follow the instructions but when I'm going to test the result, links missmatch and do not link to their correctly route. My explanation.
I've created a new one Users module following the skeletonModule structure for ZF2. The module.config.php code is
    <?php
return array(
    'controllers' => array(
        'invokables' => array(
            'Users\Controller\Index' =>
            'Users\Controller\IndexController',
        ),
    ),
    'router' => array(
        'routes' => array(
            'users' => array(
                'type'    => 'Literal',
                'options' => array(
                    // Change this to something specific to your module
                    'route'    => '/users',
                    'defaults' => array(
                        '__NAMESPACE__' => 'Users\Controller',
                        'controller'    => 'Index',
                        'action'        => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    // This route is a sane default when developing a module;
                    // as you solidify the routes for your module, however,
                    // you may want to remove it and replace it with more
                    // specific routes.
                    'default' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '/[:controller[/:action]]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            ),
                            'defaults' => array(
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),
    'view_manager' => array(
        'template_path_stack' => array(
            'users' => __DIR__ . '/../view',
        ),
    ),
);

My next step was create 3 .phtml pages called "index.phtml", "login.phtml" and "new-user.phtml". Index is the main page (obviously) and is linked to the other two.
Index code is:

Bienvenido al modulo de usuarios

Login ||
Registro

Login code is:

Login

Esta página contendrá el formulario de inicio de sesión (Login).

Volver a inicio.

New-user code is:

Registro de nuevo usuario

Esta página contendrá el formulario de registro para un nuevo usuario.

Volver a inicio.

Here is my doubt. In the tutorial the href links are different than mine. For index.phtml tutorial code is Login || Registro NOT Login ||
    Registro
If I change my href links like tutorial mentions it doesn't work and redirect to an error page cause ZF2 do not locate the other phtml files. If I put the links with "../" my project works OK.
I cannot post any picture but if you want and can help me, I send the project structure pic to your email. Thanks 4 all!

A: never faced that issue,
anyway, is that project running on localhost? Which url are you visiting to see your homepage?
I also suggest you to use the url view helper to render your urls
<a href="<?php echo $this->url('users/default', array('controller' => 'index', 'action' => 'login')); ?>">Login


text:
Q: I want to show a chapter page number from 15 to 25 - barteksc/AndroidPdfViewer I'm using barteksc/AndroidPdfViewer, and suffering from an issue that is I want to show a chapter page number from 15 to 25, how it will be? I can start a chapter page number using .defaultPage(15) but how can I finish on page 25? Is it possible? Here is sample code:
private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
        .defaultPage(15)
        .onPageChange(this)
        .enableAnnotationRendering(true)
        .onLoad(this)
        .scrollHandle(new DefaultScrollHandle(this))
        .load();
}

Please help me in this regard. Thanks in advance

A: If you want to show some pages, mention them on pages function as followed, it will show pages from 15 to 25.
.pages(15,16,17,18,19,20,21,22,23,24,25)

Below is complete function.
private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
        .defaultPage(15)
        .onPageChange(this)
        .enableAnnotationRendering(true)
        .onLoad(this)
        .scrollHandle(new DefaultScrollHandle(this))
        .pages(15,16,17,18,19,20,21,22,23,24,25)
        .load();
}


text:
Q: How to update XCode installed from XIP file? I have installed XCode 9 from XIP file and then moved it to Applications folder and it even shows up in Launchpad. I have the latest version of Sierra with security update also installed but app store doesn't seem to accept that I have it installed (Xcode) and instead of providing up with with the update it's asking me to install XCode 9.1. Is there any solution or I have to download and install the XCode 9.1 version?
There might be a way around to add some var to the path so the app store could detect it as installation form itself and update it right away!


text:
Q: Where can I find a the code related to custom block in Wordpress plugin? I am now looking into a legacy Wordpress project with some custom plugin that are written by previous developer that no longer work in the company. I am a PHP developer but haven't touched Wordpress for some time. I have done some research on Google and it seems that to add a new block type in a plugin, it is the register_block_type() function. I found in the plugin code that there is a few register_block_type() in one of the files, but not all custom block are found. To be specific, the custom block circled in the screenshot (the one named "Cards") are all not found anywhere in the plugin code.

I am sure it is added in the plugin, as all the custom block types are gone when the plugin is disabled, but where else in the plugin / what other functions can the custom block types be added?


text:
Q: Better way to add spaces between double semicolons My task is simple: I have a CSV file inside a C# string, split with semicolons. I need to add spaces for each empty cell. A;B;;;;C; should become A;B; ; ; ;C;. Right now, I'm using the replace method twice:
csv = csv.Replace(";;", "; ;").Replace(";;", "; ;");

That's necessary, because in the first pass, it will replace any occurance of ;; with a space between, but there's no lookback, so the second semicolon of the replaced sequence won't be checked again. Therefore I would end up with a A;B; ;; ;C;, which is not what I want.
Is there a more elegant, clear, and less redundand way to solve that task?

A: You can try to Split string into the parts, then replace empty entries with spaces using Select (it requires using System.Linq;) and Join the entries back
var str = "A;B;;;;C";
var parts = str.Split(';').Select(p => string.IsNullOrEmpty(p) ? " " : p);

var result = string.Join(";", parts);

The output will be the following A;B; ; ; ;C
Benchmark result in comparison with OP code and Regex solution:

What is the clear and more elegant is up to you decision.
Benchmark code for the reference is below
[SimpleJob]
public class Benchmark
{
    string input= "A;B;;;;C";

    [Benchmark]
    public string SplitJoinTest()
    {
        var parts = input.Split(';').Select(p => string.IsNullOrEmpty(p) ? " " : p);
        return string.Join(";", parts);
    }

    [Benchmark]
    public string DoubleReplaceTest()
    {
        return input.Replace(";;", "; ;").Replace(";;", "; ;");
    }

    [Benchmark]
    public string RegexTest()
    {
        return Regex.Replace(input, ";(?=;)", "; ");
    }
}

A: One way is to use regular expressions.
using System.Text.RegularExpressions;

var result = Regex.Replace("A;B;;;;C;", ";(?=;)", "; ");

We replace every semicolon that is followed by another semicolon with the string "; ".
It's definitely less redundant, and it's clear if you know how to read regex :) Whether it is more elegant is up to you to decide.


text:
Q: IndexedDB - Duplicate database I am using indexedDB in emberjs with an Adapter (Here) for that. It's working the same way as a normal implementation of indexedDB request, but every time I refresh my page twice, there is a new database created with the same name as the one I'm using.
When I clear the cache and cookie, I have to close and reopen chrome to actually refresh the indexedDB information.
After the clear cache, I run my page for the first time, it's working fine, I can see the data inside the chrome debugger. But when I reload twice, a new database with the same name as the one I'm using is created but without any table in it. And my first database is still there with my table, but I can't see the information in it.
When I refresh my page it's only callback onsuccess, not even onupgrade.
Is this a common bug of indexedDB ?


text:
Q: React-Redux changed state is not re-rendering I have built a fairly large react-redux application.  In one component I have added an undo feature.  Tracing the state all the way through it is definitely being updated and not mutated.  It even re-renders the component and all child components.  However on the page the component position is not modified until I click the component to either move it again or highlight it.
I have definitely verified that this is not a case of mutated state and have stepped through all the redux code to ensure that the shallow equality fails and I have added breakpoints on the main component and the child component which should be moved.
I will add code if you want to see it but my question is why a re-rendered component in React would not re-render in the updated position on the screen, even though the top and left coordinates have definitely changed?
Edit adding code
//layout.js

const mapLayoutDispatchToProps = (dispatch) => {
    //add action creators here - by reference?
    return {
        Layout_Set_Current_Site: (siteId) => { dispatch(Layout_Set_Current_Site(siteId)) },
        Layout_Get_Sites: () => { dispatch(Layout_Get_Sites()) },
        Layout_Get_Map_Background: (siteId, callback) => { dispatch(Layout_Get_Map_Background(siteId, callback)) },
        Layout_Get_UserImages: (deskId) => { dispatch(Layout_Get_UserImages(deskId)) },
        Layout_Create_Desk: (type, siteId, height, width) => { dispatch(Layout_Create_Desk(type, siteId, height, width)) },
        Layout_Restore_All: () => { dispatch(Layout_Restore_All()) },
        Layout_Undo_Change: (callback) => { dispatch(Layout_Undo_Change(callback)) },
        Layout_Redo_Change: () => { dispatch(Layout_Redo_Change()) },
        Layout_Fetch_Desks: (siteId) => { dispatch(Layout_Fetch_Desks(siteId)) },
        Layout_Get_Desk_Types: () => { dispatch(Layout_Get_Desk_Types()) },
        Layout_Set_Current_Desk: (desk) => { dispatch(Layout_Set_Current_Desk(desk)) }
    };
}

getDesks = () => {
    console.log("Layout.getDesks");
    // const d = this.props.layout_moveData.desks.present;
    const desks = clone(this.props.layout_moveData.present);
    return desks;
}

   handleKeyPress = (e) => {
        console.log("Layout.handleKeyPress");
        if (this.state.edit) {
            switch (e.code) {
                case 'KeyZ':
                    if (e.ctrlKey) {
                        this.props.Layout_Undo_Change();
                        e.cancelBubble = true;
                        // this.forceUpdate();
                    }
                    break;
                case 'KeyY':
                    if (e.ctrlKey) {
                        //this.props.Layout_Redo_Change();
                        UndoMove.redo();
                        e.cancelBubble = true;
                    }
                    break;
                default:
                    break;
            }
        }
    }

    buildDesks = () => {
        const desks = this.getDesks();
        let ret = desks.map((desk, index) =>
            <Desk
                key={index}
                desks={desks}
                index={index}
                deskTypes={this.props.layout.deskTypes}
                scale={this.getScale()}
                editable={this.state.edit}
            />
        );
        return ret;
    }

    render=()=>{

            return (

                    <Row>
                        <Col sm={1}>
                            {this.showAdmin()}
                        </Col>
                        <Col sm={10}>
                            {this.state.details}
                        </Col>
                    </Row>
                    <Row>
                        <Col sm={1}>
                            <select onChange={(e) => this.changeMap(e.target)}>
                                {this.buildMapOptions()}
                            </select>
                        </Col>
                        <Col sm={10} id="Layout_Map_Container">
                            {this.buildMap()}
                            {this.buildDesks()}
                        </Col>
                    </Row >
                    {this.showStatus()}

            );
        }
    }

//desks.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Draggable from '../../Elements/Draggable';

import {
    Layout_Clear_Desk,
    Layout_Delete_Desk,
    Layout_Update_Desk_Data,
    Layout_Set_Current_Desk
} from '../../../redux/Creators/Layout_Creator';

import '../../../shared/styles/layout.css';
const clone = require('rfdc')();

const mapDesksStateToProps = (state) => {
    return {
        layout: state.layout,
        layout_moveData: state.layout_moveData
    }
}

const mapDesksDispatchToProps = (dispatch) => {
    return {
        Layout_Clear_Desk: (deskId) => { dispatch(Layout_Clear_Desk(deskId)) },
        Layout_Delete_Desk: (deskId) => { dispatch(Layout_Delete_Desk(deskId)) },
        Layout_Update_Desk_Data: (desk, deskId) => { dispatch(Layout_Update_Desk_Data(desk, deskId)) },
        Layout_Set_Current_Desk: (deskId) => { dispatch(Layout_Set_Current_Desk(deskId)) }

    }
}

class Desk extends Component {

    constructor(props) {
        super(props);
        this.state = {
            desk: clone(props.desks[props.index]),
            desks: clone(props.desks)
        }
    }

    rightClick = (e, deskId) => {
        if (this.props.editable) {
            const desk = this.state.desk;
            let rotation = parseInt(desk.rotation);
            rotation += 90;
            if (rotation >= 360) rotation -= 360;
            desk.rotation = rotation;

            this.props.Layout_Set_Current_Desk(desk);
            this.props.Layout_Update_Desk_Data(desk);
        }
    }

    updateProperties = (data) => {
        let string = `Top: ${data.top}, Left:${data.left}`;
        // data = this.state.details + ', ' + data
        this.setState({ details: string });
    }

    mouseUp = (e, deskId, data) => {
        console.log("Layout.mouseUp");
        const desks = clone(this.state.desks);
        // let desk = ;
        if (data.dragged && this.props.editable) {
            // this.clickDesk(e, deskId);
            const scale = this.props.scale;
            const newX = parseInt(data.left / scale);
            const newY = parseInt(data.top / scale);

            desks[deskId].x = newX + ""; //convert to strings
            desks[deskId].y = newY + "";

            console.log(this.state.desks);
            console.log(desks);
            this.props.Layout_Update_Desk_Data(desks, deskId);
        }
        else {
            this.clickDesk(e, deskId);
        }

    }

    clickDesk = (e, deskId) => {
        if (deskId !== null && deskId !== undefined && deskId !== false) {

            this.props.Layout_Set_Current_Desk(this.state.desk);
        }
        else {
            this.props.Layout_Set_Current_Desk(null);
        }
    }

    render() {

        let deskImg = null;
        // const desk = this.props.desks[this.props.index];
        let desk = clone(this.state.desk);
        try {
            let dImg = this.props.deskTypes.find(
                d => parseInt(d.deskType) === parseInt(desk.deskType)
            );
            deskImg = dImg.deskImage;
        }
        catch (ex) {
            console.log(ex);
        }
        const userName = desk.UserLogon !== (null || '') ? desk.UserLogon : "Unassigned";

        const top = Math.trunc(parseInt(parseInt(desk.y) * this.props.scale));
        const left = Math.trunc(parseInt(parseInt(desk.x) * this.props.scale));

        let imgStyle = {
            width: `${parseInt(parseInt(desk.width) * this.props.scale)}px`,
            height: `${parseInt((parseInt(desk.height) * this.props.scale))}px`,

            position: 'absolute'
        }
        if (this.props.layout.currentDesk && desk.id === this.props.layout.currentDesk.id) {
            imgStyle.border = '2px solid cyan';
        }
        const url = `data:image/jpeg;base64,${deskImg}`;
        try {
            //
            return (
                <Draggable key={desk.id}
                    index={this.props.index}
                    enabled={this.props.editable}
                    left={left}
                    top={top}
                    onMove={this.updateProperties}
                    onStop={this.mouseUp}
                    onRightClick={this.rightClick}
                >
                    <div style={{
                        position: 'relative',
                        transform: `rotate(${parseInt(desk.rotation)}deg)`
                    }}
                        className='deskImg'>

                </Draggable>
            );
        }
        catch (ex) {
            console.log(ex);
            return null;
        }

    }//buildDesks
}

export default connect(mapDesksStateToProps, mapDesksDispatchToProps)(Desk);

//layout_creators.js
export const Layout_Undo_Change = () => (dispatch, getState) => {
    const state = getState();
    const desks = clone(state.layout_moveData);
    console.log("1", state.layout_moveData.present)
    //if no past to undo to
    if (desks.past.length === 0) return;
    const previous = clone(desks.past[desks.past.length - 1]);
    desks.past.shift();
    const undoPast = clone(desks.past);
    // const undoPast = clone(desks.past).slice(0, desks.past.length - 1);
    const undoFuture = [clone(desks.present), ...clone(desks.future)]
    const undoDesks = { past: undoPast, present: previous, future: undoFuture };
    dispatch({ type: ActionTypes.LAYOUT_UNDO_MOVES, payload: clone(undoDesks) });
    console.log("2", state.layout_moveData.present)
    let init = fetchInit();
    init.method = "POST";
    const deskData = { mode: 'UPDATEMANY', data: previous };
    init.body = JSON.stringify(deskData);
    let myReq = new Request(`/dataAPI/Layout/`, init);
    fetch(myReq)
        .then((response) => {
            if (response.ok) {
                return response;
            }
            else {
                var error = new Error("Error " + response.statusText);
                error.response = response;
                throw error;
            }
        }, (error) => {
            var err = new Error(error.message);
            throw err;
        })

        .catch(err => {
            return dispatch({
                type: ActionTypes.LAYOUT_FAILED,
                payload: err.message
            });
        });
}

//layout_reducer.js
import * as ActionTypes from '../ActionTypes';

export const layout = (state = {
    isLoading: true,
    isLoadingMap: false,
    isLoadingDesks: false,
    desksLoaded: false,
    mapLoaded: false,
    currentMap: null,
    currentDesk: null,
    maps: [],
    deskTypes: [],
    editMode: false,
    errMess: null
}, action) => {
    switch (action.type) {
        case ActionTypes.LAYOUT_SITES_LOADING:
            return { ...state, isLoading: true };
        case ActionTypes.LAYOUT_DESKS_LOADING:
            return { ...state, isLoadingDesks: true, desksLoaded: false };
        case ActionTypes.LAYOUT_MAP_LOADING:
            return {
                ...state, isLoadingMap: true, desks: [],
                currentDesk: null, editMode: false, desksLoaded: false
            };
        case ActionTypes.LAYOUT_MAP_LOADED:
            return { ...state, isLoadingMap: false, mapLoaded: true, maps: action.payload };
        case ActionTypes.LAYOUT_MAPS_LOADED:
            return { ...state, maps: action.payload, isLoading: false };
        case ActionTypes.LAYOUT_DESKTYPES_LOADED:
            return { ...state, deskTypes: action.payload };

        case ActionTypes.LAYOUT_SET_CURRENT_DESK:
            return { ...state, currentDesk: action.payload };
        case ActionTypes.LAYOUT_SET_EDITMODE:
            return { ...state, editMode: action.payload };
        case ActionTypes.LAYOUT_DESK_DELETED:
            return { ...state, currentDesk: null }
        case ActionTypes.LAYOUT_DESKS_LOADED:
            return { ...state, currentDesk: null, isLoadingDesks: false, desksLoaded: true }

        case ActionTypes.LAYOUT_SET_ACTIVE_MAP:
            return { ...state, currentMap: action.payload, desksLoaded: false };

        case ActionTypes.LAYOUT_FAILED:
            return {
                ...state, isLoadingMap: false, isLoadingDesks: false, desksLoaded: false,
                errMess: action.payload, pageUsageData: []
            };
        case ActionTypes.LAYOUT_RESTORE_ALL:
            return {
                ...state,
                isLoading: true, isLoadingMap: false, mapLoaded: false, currentMap: null,
                maps: [], desks: [], deskTypes: [], editMode: false,
                errMess: null, desksLoaded: false
            }
        default:
            return state;
    }
}

export const layout_moveData = (state = {

    past: [],
    present: null,
    future: []

}, action) => {

    switch (action.type) {
        case ActionTypes.LAYOUT_DESKS_LOADING:
            return { ...state, present: [], past: [], future: [] };
        case ActionTypes.LAYOUT_DESKS_LOADED:
            return { ...state, present: action.payload, past: [], future: [] };
        case ActionTypes.LAYOUT_DESK_DELETED:
            return { ...state, present: action.payload.present, past: action.payload.past, future: action.payload.future };
        case ActionTypes.LAYOUT_RESTORE_ALL:
            return { ...state, present: [], past: [], future: [] };
        case ActionTypes.LAYOUT_SET_MOVES:
            return { ...state, present: action.payload.present, past: action.payload.past, future: action.payload.future };
        case ActionTypes.LAYOUT_UNDO_MOVES:
            return { ...state, present: action.payload.present, past: action.payload.past, future: action.payload.future };
        case ActionTypes.LAYOUT_REDO_MOVES:
            return { ...state, present: action.payload.present, past: action.payload.past, future: action.payload.future };
        default:
            return state
    }
}

A: I have extrapolated all items in the page to separate components as in React redux state change does not cause update even after deep copy of all state data.  This allowed for better stack handling.


text:
Q: Delay setText in Game I tried looking at the other solutions on StackOverFlow, but none seemed to fix my implementation of a game I'm making. I need it to delay each iteration of playGame method(which sets the TextView among other things) for 3 or so seconds without delaying the whole thing in a while loop.
@Override
public void onResume(){
    super.onResume();
    int count = 0;
    while(!stopGuessing){
        Log.i("count", Integer.toString(count));
        if (count > 9) {
            break;
        }
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Do something after 5s = 5000ms
               playGame();

            }
        }, 5000);
        //playGame();
        count++;
    }
}


text:
Q: Is there any way to split the string to rows in R? I have following string "[Time].[Fiscal Year].&[2014]}^[Time].[Fiscal Half Year]^[Time].[Fiscal Quarter]^[Time].[Month]" and need to split the string in below format. Kindly help me to find the way to fulfill my requirement.

A: You can use strsplit to split on ^ and gsub to find the pattern [*].[*] and put the result in a data.frame.
data.frame("Time Value"=
 gsub("(\\[.*?\\]\\.\\[.*?\\]).*", "\\1", strsplit(x,"\\^")[[1]])
 , check.names = FALSE)
#                 Time Value
#1      [Time].[Fiscal Year]
#2 [Time].[Fiscal Half Year]
#3   [Time].[Fiscal Quarter]
#4            [Time].[Month]

Data:
x <- "[Time].[Fiscal Year].&[2014]}^[Time].[Fiscal Half Year]^[Time].[Fiscal Quarter]^[Time].[Month]"

A: Maybe the code can make what your want. Given string s as below
s <- "[Time].[Fiscal Year].&[2014]}^[Time].[Fiscal Half Year]^[Time].[Fiscal Quarter]^[Time].[Month]"

then the data frame can be formed via
r <- unlist(strsplit(s,"\\^"))
df <- data.frame("Time Value" = unlist(regmatches(r,gregexpr("\\[.*?\\]\\.\\[.*?\\]",r))),check.names = F)

such that
> df
                 Time Value
1      [Time].[Fiscal Year]
2 [Time].[Fiscal Half Year]
3   [Time].[Fiscal Quarter]
4            [Time].[Month]

A: Simple Base R solution:
gsub( "\\.\\&.*", "", unlist(strsplit(x, "\\^")))

Data:
x <- "[Time].[Fiscal Year].&[2014]}^[Time].[Fiscal Half Year]^[Time].[Fiscal Quarter]^[Time].[Month]"


text:
Q: Replace part of string with variable using sed or awk Is there a way to replace only a part of a string with a random number using sed or awk?
From a URL list file, i need to replace each GET url param that matches the pattern with a random number.
Example:

*

*https://example.com?param1=somevalue&param2=somevalue

*https://otherexample.com?param1=somevalue&param2=somevalue
Replace "param1=" with random number
So, after replace:

*

*https://example.com?param1=512512412&param2=somevalue

*https://otherexample.com?param1=9568478547&param2=somevalue

A: basically same syntax for sed and awk - the extended regex is
s/(param)([0-9])=([0-9]{3,})/\1\2= { … fill in rand number u want … } /g'

awk side, either mawk or gawk
match($0, /(param)([0-9])=([0-9][0-9]+)/);

$0 = substr($0,1,RSTART + 6)
     {…fill in rand #…}
    substr($0, RSTART+RLENGTH);

Unfortunately, since mawk2 has neither backreferences like \1 \2 nor bracket expansion like {3,} , sadly if u wanna write portable code then match is the way to go.
if u wanna stay on gawk, then gensub works reasonably okay.


text:
Q: How to handle fallback page with internationalization for dynamic page in Next.js? In Next.js documentation, there is a section for internationalized routing with dynamic routes and getStaticProps pages.
In the provided example, they use the fallback property set to true:
// pages/blog/[slug].js
export const getStaticPaths = ({ locales }) => {
  return {
    paths: [
      // if no `locale` is provided only the defaultLocale will be generated
      { params: { slug: 'post-1' }, locale: 'en-US' },
      { params: { slug: 'post-1' }, locale: 'fr' },
    ],
    fallback: true,
  }
}

I have a very similar project with 2 locales: 'en' and 'fr'.
Everything is working fine when my blog article does exist. But if the article does not exists (or when the page has not been generated yet at build time), then I display my custom fallback page as explained here.
I could provide my getStaticProps function or fallback page. But it is very similar to the example defined on the doc as well, so very simple.
The issue is that when displaying my fallback page, I do not have any locale yet. So all my translations display keys instead of english or french value (not only for my fallback custom component but the whole main layout/page).
From what I understand the problem is that:

*

*Fallback page is displayed until getStaticProps has finished

*Fallback page props are empty

*Locale is returned by getStaticProps function

I feel like this should be a common scenario, and maybe I'm missing something. How could I know the locale when displaying the fallback page?
Please note that I use next-i18next on my project. So my URL is either: /articles/[slug] or /fr/articles/[slug].

A: It appears that the problem was not the locale.
But since the not existing pages needs to be statically generated, then the serverSideTranslations function has not yet been called.
So the react-i18next/i18next has not been yet initialized with the translations neither.
This means there are not yet any translations in the client in that moment.
What I chose to do is to use the 'blocking' value of the fallback property. This is not perfect, but this is the better option in my opinion.


text:
Q: Why was the Marauder's Map not used during the battle of Hogwarts? Harry has the Marauder's Map during the battle of Hogwarts, if he were to give this map to a senior, commanding mage it could have helped organise the defence of Hogwarts better.
Since knowing the arrangement of the forces arrayed against you is a big advantage.
Why did Harry choose to hide this fact and not let it be used to help during the battle?

A: The question isn't directly answered in the books or movies, but I see two possibilities.
Possibility 1: The Map Is Most Useful in Harry's Hands
What you have to remember is that the reason this whole battle is happening is because Harry has to look for the final Horcruxes hidden within Hogwarts before he can defeat Voldemort. The sequence of events leading up the Battle is basically:

*

*Harry enters Hogwarts through a secret passage because he has to search for the Rowena Ravenclaw Horcrux.

*Harry is caught by the Carrows who alert Voldemort to Harry's presence.

*Dumbledore's army sends out word to the Order of the Phoenix that something is about to go down and Order members start streaming into the school in preparation.

*Voldemort demands that the resistance give up Harry Potter by midnight or he will attack the school.

*When they don't give him up, the battle is on.
The battle isn't primarily about gaining back control of Hogwarts, although some students might think it is. The battle is about buying Harry enough time to find the Horcrux and destroy it. If the Horcrux wasn't at Hogwarts, then Harry could just leave through the secret passage and hide from Voldemort the way he's done all year.
Harry's mission is more important than anything else that is going on. So if he can use the Map to help him accomplish this mission then that is at least arguably a better use for it than directing troop movements. And it is pretty easy to see that the Map might be useful in helping the most wanted wizard in Britain sneak around Hogwarts in the midst of a battle in order to find a hidden magical object. I don't know if Harry actually uses the Map during the Battle, but in theory I can see how it might help him.
All that being said, I think the second possibility is more likely:
Possibility 2: It Never Occurred to Harry To Use the Map In This Way
Harry Potter just isn't the kind of kid who thinks "Gee, I better take all the information I have and present it to the most qualified adults and also give them my cool, magical objects so they can handle Voldemort and the Death Eaters." Harry Potter is the kind of a kid who tries to do everything on his own -- sometimes with the help of Ron and Hermione, only reluctantly with the help of others. If he trusts an adult a lot -- like Dumbledore or Sirius -- then he might take some of his worries to them, but only after much deliberation. His instinct is to try to do things on his own. When he arrives at Hogwarts on the night of the battle, he's reluctant to even let Dumbledore's Army help him search for the diadem.
Harry isn't focused on how he can lead his army to victory during the battle. He's focused on finding and destroying the Horcruxes ... on the mission that he's been carrying out with the help of Ron and Hermione. In fact, the one time when he really almost gets distracted by things like troop movements, McGonagall quickly gets him back on task:

But he broke off as Kingsley had stepped forward on the raised platform to address those who had remained behind.
"We've only got half an half an hour until midnight, so we need to act fast. A battle plan has been agreed between the teachers of Hogwarts and the Order of the Phoenix. Professors Flitwick, Sprout and McGonagall are going to take groups of fighters up to the three highest towers - Ravenclaw, Astronomy, and Gryffindor - where they'll have good overview, excellent positions from which to work spells. Meanwhile Remus" - he indicated Lupin - "Arthur" - he pointed toward Mr. Weasley, sitting at the Gryffindor table - "and I will take groups into the grounds. We'll need somebody to organize defense of the entrances or the passageways into the school - "
"Sounds like a job for us." called Fred, indicating himself and George, and Kingsley nodded his approval.
"All right, leaders up here and we'll divide up the troops!"
"Potter," said Professor McGonagall, hurrying up to him, as students flooded the platform, jostling for position, receiving instructions, "Aren't you supposed to be looking for something?"
"What? Oh," said Harry, "oh yeah!"
He had almost forgotten about the Horcrux, almost forgotten that the battle was being fought so that he could search for it.

Both because of Harry's personality and because his focus during the battle is on this very important side mission, I just don't think that giving the map to a commanding wizard would have occurred to him. He probably would  have given it up if someone else had suggested it and it had seemed like a good plan -- I just don't think he would have come up with the idea on his own. And not that many other people knew about the Map -- I think just Ron, Hermione, Fred, George, and Remus.

A: The Marauder's Map was useful to students of Hogwarts for sneaking around and such, however, there was no need to sneak around, because there was a full scale battle going on. Also, even if at the beginning things were organized, much of the battle became a free for all, with every wizard just trying to keep themselves alive. They were not Aurors or Hit Wizards, or even Ministry Police, they were just students, some as young as thirteen, traditional military tactics wouldn't have worked, because in the heat of battle, many of them would forget their orders.

A: The Battle of Hogwarts is fast-paced and chaotic. In many instances it simply breaks down into small, individual or group duels. In such an environment, where you constantly need to keep your wits about you to stay alive, there is not enough time to stop and study the Map. Remember, the Map has hundreds of names on it even on a good day (teachers and students). Distinguishing between all the names to discern some kind of tactical advantage, and furthermore, quickly and effectively communicating this tactic amongst your allies, would be near impossible in the heat of the Battle. It's likely your window of opportunity on the advantage would have been missed by the time you had gotten yourself organised.

A: It's been a while, but to use the Marauder's Map don't you have to solemnly swear that you are up to no good? The times the map was being used before rules were being broken, authority was being disobeyed. But defending Hogwarts against an all out attack does not really fall into "up to no good".


text:
Q: Why can you indirectly bind an rvalue to an lvalue reference but not directly? From what I've read and seen you cannot bind an expression that is an rvalue to an lvalue reference. What I have seen however is that you can bind an rvalue to an rvalue reference and since a named rvalue reference is inherently an lvalue, you can bind it to an lvalue reference. What is the reason behind disallowing binding an rvalue to an lvalue reference. Is it for optimization purposes?
Take this example:
#include <iostream>

using std::cout;

void bar ( int& b ) {

    cout << "bar " << b << "\n";
    b = 3;
}

void foo ( int&& a ) {

    cout << a << "\n";
    bar(a);
    cout << a << "\n";
}

int main ( int argc, char ** argv ) {

    foo(1);
}

A:
What is the reason behind disallowing binding an rvalue to an lvalue reference?

No answer to this question can be complete without a reference to the invaluable and distinguished source, The Design and Evolution of C++ by Bjarne Stroustrup.
In section 3.7 Bjarne writes:

I made one serious mistake, though, by allowing a non-const reference
  to be initialized by a non-lvalue.  For example:
void incr(int& rr) { rr++; }

void g()
{
    double ss = 1;
    incr(ss);    // note: double passed, int expected
                 // (fixed: error in Release 2.0)
}

Because of the difference in type the int& cannot refer to the
  double passed so a temporary was generated to hold an int
  initialized by ss's value. Thus incr() modified the temporary, and
  the result wasn't reflected back to the calling function.

I highly recommend The Design and Evolution of C++ for understanding many of the "why questions" one might have, especially regarding the rules that were laid down prior to the C++98 standard.  It is an informative and fascinating history of the language.

A: It's a fundamental rule of C++ and it prevents bugs:
int foo();

int& x = 3;      // whoops
int& y = foo();  // whoops (sometimes)

"Rvalue references" (a set of types; not to be confused with actual rvalues) were created at least in part so that you can still do this if you really want to:
int&& x = 3;     // oh, go on then *sigh*
int&& y = foo(); // you'd better be sure!

In the previous examples, I bind (or attempt to bind) objects "referenced" by an rvalue expression to a reference.
Now, I shall bind the object named by an lvalue expression to a reference:
int i = foo();

int& x = i;      // no problem michael

And to make sure that you really meant to obtain an rvalue reference from an lvalue expression, introducing the incredibly poorly-named std::move:
int&& x = std::move(i);  // doesn't move anything

These later rules came much, much later than the original, fundamental rule that has doubtless prevented many bugs over the past twenty years.
Note that Visual Studio has historically accepted T& x = bar() where T is a user-defined type; go figure.

A: When you call foo(1), a temporary int equal to 1 is created, and int&& a is bound to it. You can freely change it. The same way you can write int&& a = 1;. a itself is an lvalue, so you can bind lvalue reference to it.
You may read a great article Universal References by Scott Meyers which explains rvalue and lvalue references in detail.


text:
Q: How to isolate the x and z components of a quaternion rotation? I can't comment other posts yet. ShawnFeatherly in this post wrote:

Here's a way to get the local rotation of just the y-axis. This function can be modified to get the x or z-axis.

/// <summary> isolate the y-Component of a rotation </summary>
private Quaternion yRotation(Quaternion q)
{
    float theta = Mathf.Atan2(q.y, q.w);

    // quaternion representing rotation about the y axis
    return new Quaternion(0, Mathf.Sin(theta), 0, Mathf.Cos(theta));
}

It works for me! But how can I change this to get xRotation and zRotation? My quaternion representation is (x, y, z, w). Thanks!

A: As far as I know you can do the same with the other components:
float theta_y = Mathf.Atan2(q.y, q.w);

Quaternion yRotation = Quaternion(0, Mathf.Sin(theta_y), 0, Mathf.Cos(theta_y));

float theta_x = Mathf.Atan2(q.x, q.w);

Quaternion xRotation = Quaternion(Mathf.Sin(theta_x), 0, 0, Mathf.Cos(theta_x));

float theta_z = Mathf.Atan2(q.z, q.w);

Quaternion zRotation = Quaternion(0, 0, Mathf.Sin(theta_z), Mathf.Cos(theta_z));


text:
Q: VBA - Search text for partial string, copy entire string I have a series of files outlining different product builds, and each file is named with just the printer job number. What I would like to do is cycle through each such file in my folder, open it grab the product number, and rename the file with that string. The products would all begin with the same prefix, but the following digits are unique to each product. I've got it to the point where my macro prompts the user for that prefix, but I'm stumped as to how to search the .txt file for it, and then how to capture everything up to the next "space". Each product line begins with a different prefix, and may have a different number of following digits. It only needs to grab the first instance of the prefix, which so far has been line 3 -- but I don't want to limit it to only searching that line, as it may be different in the future.
Edit:
The pertinent info here is "2940UB200L". "2940" is the product line, given by the user, and the values following are unique to the assembly. However, there may be other products within the same product line listed below this header (I can't post that list). 100's of these Bills are in a folder, and each file is named with only the print job number. So far, I really only have code for a pop-up box requesting the product line prefix and a way to cycle through the folder. Everything else is bits and pieces that don't quite work together. In a given folder, everything SHOULD be from the same product line.
Sample text... Doesn't seem to be formatting the same in the preview as what I've pasted:
PRODUCTION PLANT                     INDENTED BILL
PARENT ITEM NO.             DESCRIPTION ROUND RING
2940UB200L                  ENGR DRAW 00000LM000/ZN31
                            STANDARD BATCH QUANTITY           1.000 RELATIVE SEQ   RELATIVE    SEQ   COMPONENT                       ENGINEERING       QUANTITY
LEVEL       NO.   ITEM NO.        DESCRIPTION     DRAWING NUMBER         PER
Working code:
Sub ChangeFileName()

Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ProdLine As String 'Product Line to search
Dim CatNum As String 'Full Part number
 'Get the folder object associated with the directory
With Application.FileDialog(msoFileDialogFolderPicker)
  .AllowMultiSelect = False

 'Close macro when no folder is selected
  If .Show <> -1 Then MsgBox "No folder selected! Exiting sub...": Exit Sub
  myDir = .SelectedItems(1)

  On Error Resume Next

  FolderName = .SelectedItems(1)
  Err.Clear

  On Error GoTo 0

End With

 'Gives File list a header
Set objFolder = objFSO.GetFolder(FolderName)
 'Prompts user for Product Line
ProdLine = InputBox("Enter product line prefix (example: 2940)")

 'Find Part Number
 'Change file name

End Sub

Thanks for any input


text:
Q: CSS: using image sprites with css pseudo classes :before and :after I have never tried that before. I created an image sprite that is contains two icons. Each icon is 26px wide and high. So the sprite is 26x52px.
I have an element that is either in a div.something or in a div.anything. Depending on which class it's in I want to add a corner cap to the left or right.
So therefore I'm positioning the .element relative, the apply the :before pseudoclass to the img and position it absolute with a height and width of 26px so only one icon of the sprite fits in. I also apply "overflow:hidden" in order to hide the second icon on the sprite.
.element {
    position:relative;
}

.element:before{
    content: url("../images/sprite.png");
    position: absolute;
    height:26px;
    width:26px;
    overflow:hidden;
}

.something .element:before {
    top: -2px;
    left: -2px;
}

anything .element:before {
    top: -28px;
    right: -2px;
}

This works fine for the left-corner where I use the first top icon in the sprite.
However now I wonder how I can show only the second icon in the sprite for the "anything .element".
So actually the "mask" should be positioned at -2px, -2px but the sprite img inside should start at -26px so the second icon is shown.
Is this possible with css the way I'm doing it right now?

A: Support for :before and :after pseudo elements on img tags is limited, if at all existent on most browsers.
The best solution would be to place your img inside a div, and then have the class applied to the actual div, rather than the img.
You almost have the usage for the pseudo element correct. You can give this a try:
.somediv { position:relative;}

.somediv:before {
  position: absolute;
  content: '';
  height: 26px;
  width: 26px;
  top: 0;
}

.somediv.foo1:before {
  background: url("../images/sprite.png") no-repeat -2px -2px;
  left: 0;
}

.somediv.foo2:before {
  background: url("../images/sprite.png") no-repeat -2px -28px;
  right: 0;
}

Use the background:; property rather than the content:; property so that you can position the sprite within the :before pseudo element.
left:; right:; and top:; should be used for absolute positioning of the pseudo element relative to its parent (.somediv).
Placing a 1px border around your pseudo element will help you understand the different positioning :)

A: Don't use content to insert your image, as you cannot modify its position. Instead, set the content to " " and add the sprite as a background image. You can then use the background-position property to move the sprite to the correct position. Otherwise your example should be working just fine.
A working demo:

http://jsfiddle.net/RvRxY/1/


text:
Q: Newton-Cotes formula problem Please help me to solve this problem...

By the method of undetermined coefficients I found $a=c=1/6$ and $b=2/3$ and $\alpha=\gamma=2/3$ and $\beta=-1/3$. Also that both are exact for polynomials of degree $\leq 3$.
But I cannot figure out which one is better.
Thank you.

A: Considering function $f(x)$ to be integrated between $a$ and $b$, let me set $f_i=f(x_i)$ where $x_i=a+(b-a)\frac in$ where $n$ is the degree. We shall consider $n=3$ which is your problem.
Closed Newton-Cotes formula is $$\int_a^b f(x)\,dx\approx \frac{b-a}{6}\,(f_0+4f_1+f_2)$$ and the error is $-\frac{(b-a)^5}{2880}f^{(4)}(\xi)$.
Open Newton-Cotes formula is $$\int_a^b f(x)\,dx\approx \frac{b-a}{3}\,(2f_1-f_2+2f_3)$$ and the error is $\frac{7(b-a)^5}{23040}f^{(4)}(\xi)$.
As you can see, assuming similar $\xi$'s, the errors are in a ratio of $7:8$ slightly favouring the open form (just as Rory Daulton answered).

A: "Better" is vague here. I tested both approximations using $f(x)=x^4$, and the approximation errors I got were:

*

*about $0.00833$ for the first (out of $0.2$),

*about $0.00729$ for the second (out of $0.2$).

So, for this example, the second was slightly "better" in terms of error. However, other examples may give different results.
Another way the second is better is that it can handle improper integrals, where the values of $f(x)$ are not defined at the endpoints $x=0$ and $x=1$. For example, the second could approximate
$$\int_0^1 \frac 1{\sqrt x}\,dx$$
to an error of about $0.36827$ (out of $2$), whereas the first could not give any approximation at all.
I therefore conclude that the second approximation formula is "better."


text:
Q: How to exclude NoneType class while reading string in Python I have a list that is pulled into python from Google Sheets.
Some of the cells are empty and return a value of None.
I checked the class type for these 'None' values and it says class = 'NoneType'
What is the best way to exclude these cells, without loosing the the "i coordinate" of the cells that do contain the string values i'm interested in?
This is what I tried, but i'm getting a syntax error:
for i, val in enumerate(some_list):
    if ( i != isinstance(NoneType))
        print (i,val)

A: for i, val in enumerate(some_list):
    if val is not None:
        print (i,val)

If you wish to skip None and blank values:
for i, val in enumerate(some_list):
    if val is not None and val != "":
        print (i,val)

A: In case, when gapes in i are not needed:
for i, val in enumerate([x for x in some_list if x]):
    ...


text:
Q: How to edit "kMDItemXxx" file metadata on macOS? Today I tried to edit the metadata of a picture file. I used mdls to display them, then looked for a command to edit one. But I couldn't find any.
For vanilla metadata, like basic timestamps, touch is good enough. And for these things called "extended attributes" (quarantine, etc.), macOS gives you xattr -d.
But is there a CLI way to edit, say, kMDItemBitsPerSample or kMDItemFSName, or the key/value pairs used by Spotlight?

A: The Spotlight system collects a variety of types of metadata about files. Some kinds of metadata are what I'd call "superficial", and can be easily changed by changing the file properties; but some "deeper" ones depend on the contents of the file, and cannot be changed without significant changes to the file itself.
kMDItemFSName is an example of a "superficial" attribute -- it's just the filename, so renaming the file will change it. kMDItemBitsPerSample, on the other hand, is a property of the data in the file (it's the bit depth of an image or audio file). Changing kMDItemBitsPerSample would involve some sort of recoding of the image or audio file.
Mind you, there are some attributes that are in-between in superficiality. For example, mp3 files include metadata like the album name (kMDItemAlbum) and track number (kMDItemAudioTrackNumber) that are part of the file's contents, but can be edited (by some apps, like the old iTunes) without touching the audio content of the file.


text:
Q: How can I prevent a string argument changing from null to empty when bound to a parameter? Consider the following code:
function f {
    param (
        [AllowNull()]
        [string]
        $x
    )
    return $x
}

$r = f -x $null

$null is converted to [string]::Empty by the time return is reached.  $null is different from [string]::Empty and I'd like to preserve this distinction.  I'd also prefer to keep $x as type [string] because $x only has meaning as a string and the interface is used elsewhere.

*

*How can I make $x come out as $null when it is passed $null?

*Is there some other way I can tell that $x was passed $null not [string]::Empty from inside f?

Update 1
What I am trying to do works for other types.  Here is the same concept for [int]:
function f {
    param(
        [System.Nullable[int]]$x
    )
    return $x
}

$r = f -x $null

In that case $r is indeed $null.  $x can be either $null or [int] but nothing else.  It seems strange to me to have to allow any object just so I can pass a $null or [int].
[System.Nullable[string]] produces an error that boils down to [System.Nullable[T]] requires that [T] is a value type.  [string] is a reference type, so that doesn't work.

Update 2
It seems to be possible to pass $null without causing conversion to a parameter of any type except [string].  I've tested the following:
function f { param([System.Nullable[int]]$x) $x }
function f { param([System.Nullable[System.DayOfWeek]]$x) $x }
function f { param([hashtable]$x) $x }
function f { param([array]$x) $x }
function f { param([System.Collections.Generic.Dictionary[string,int]]$x) $x }
function f { param([System.Collections.ArrayList]$x) $x }
function f { param([System.Collections.BitArray]$x) $x }
function f { param([System.Collections.SortedList]$x) $x }
function f { param([System.Collections.Queue]$x) $x }
function f { param([System.Collections.Stack]$x) $x }

Passing $null to any of these functions outputs $null.  The only parameter type I haven't found a way to which to pass $null without conversion is [string].

Update 3
PowerShell's behavior in this regard is also inconsistent with C#.  The corresponding function in C# is as follows:
public string f(string x)
{
    return x;
}

Calling f(null) returns null.

Update 4
Apparently [NullString]::Value was intended to address this problem.  I seems to work to pass null to string parameters in C# APIs.  However, [NullString]::Value gets converted to [string]::empty in PowerShell the same as $null.  Consider the following code:
function f {
    param (
        [AllowNull()]
        [string]
        $x
    )
    return $x
}

$r = f -x ([NullString]::Value)
$r.GetType().Name

Executing that code outputs String. $r is [string]::Empty despite that [NullString]::Value was passed to $x.

Update 5
The PowerShell team has indicated that this was by design:

This is by design and ... changing the behavior would be a massive breaking change.

That thread involved an interesting discussion about the reasoning behind it.  I suspect that some of ramifications of this behavior were not understood when the decision was made as the behavior directly contravenes PowerShell cmdlet "Strongly Encouraged Design Guideline" SD03 which reads in part as follows:

If your parameter needs to differentiate between 3 values: $true, $false and "unspecified", then define a parameter of type Nullable. The need for a 3rd, "unspecified" value typically occurs when the cmdlet can modify a Boolean property of an object. In this case "unspecified" means to not change the current value of the property.

A: To summarize and complement the information from the question, answers, and comments:
tl;dr:
It's best not to fight PowerShell's design of not allowing [string] variables to be $null, and to limit use of [NullString]::Value to calls to .NET methods.

*

*PowerShell converts $null to '' (the empty string) when it is assigned to [string]-typed [parameter] variables, and parameter variables also default to  ''.

*

*The only exception is the use of uninitialized [string] properties in PSv5+ custom classes, as alxr9 (the OP) points out: class c { [string] $x }; $null -eq ([c]::new()).x indeed yields $True implying that property .x contains $null. However, this exception is likely accidental and probably a bug, given that when you initialize the property with $null or assign $null to it later, the conversion to '' again kicks in; similarly, using return $null from a [string]-typed method outputs ''.

*The exception aside, PowerShell's behavior differs from C# string variables / parameters, to which you can assign / pass null directly, and which default to null in certain contexts. string is a .NET reference type, and this behavior applies to all reference types.
(Since reference type instances can inherently contain null, there is no need for a separate nullable wrapper via System.Nullable`1, which is indeed not supported (it works for value types only).)

*As noted in the question (update 5), PowerShell's departure from C#'s behavior is by (design, and it's changing it is not an option for reasons of backward compatibility alone.

*[NullString]::Value was introduced in v3 specifically to allow passing null to string parameters of .NET methods - and while use in pure PowerShell code wasn't explicitly discouraged or prevented, the unexpected behavior in update 4 and the comments by a core PowerShell team member (see below) suggest that such uses weren't anticipated.

*

*Caveat: While it is possible to use [NullString]::Value in pure PowerShell code, there may be pitfalls beyond the one discussed below, given that use of [NullString]::Value was never intended outside the context of calling .NET methods; to quote a core member of the PowerShell team:

Parameters to C# methods was the target scenario for [NullString]::Value, and I will say that might be the only reasonable scenario.

*

*A workaround is to type your (parameter) variable as [object] or to not type-constrain it at all, which amounts to the same. Such variables happily accept $null, but note that you may have to stringify (convert to [string]) non-$null values yourself (although PowerShell does that for you automatically in explicit or implied string contexts) - see the penultimate code example below.

If, despite the advice above, you do need a [string] parameter variable that you can pass $null to via [NullString]::Value, as in update 4 in your question, there is an - obscure - workaround for the optimization bug that prevents your code from working, thanks to sleuthing by PetSerAl:
function f {
    param (
        [string] $x
    )
    # Workaround; without this, even passing [NullString]::Value
    # returns '' rather than $null
    if ($False) { Remove-Variable }
    return $x
}

$r = f -x ([NullString]::Value)
$r.GetType().Name  # now fails, because $r is $null

Note that when assigning / passing [NullString]::Value to a [string]-typed [parameter] variable, it is instantly converted to $null (in the case of a parameter variable, only if the bug gets fixed or with the workaround in place).
However, once $null has been successfully stored in the variable this way, it can apparently be passed around as such (again, only if the bug gets fixed or with the workaround in place).

If you don't want to rely on the workaround / wait for the fix and/or don't want to burden the caller with having to pass [NullString]::Value instead of $null, you can build on the answers by Curios and Jason Schnell, which rely on using an untyped (implicitly [object]-typed) or explicitly [object]-typed parameter, which can accept $null as-is:
function f {
    param (
        [AllowNull()] # Explicitly allow passing $null.
                      # Note: Strictly speaking only necessary with [Parameter(Mandatory=$True)]
        $x # Leave the parameter untyped (or use [object]) so as to retain $null as-is
    )

    # Convert $x to a type-constrained [string] variable *now*:
    if ($null -eq $x) {
        # Make $x contain $null, despite being [string]-typed
        [string] $x = [NullString]::Value
    } else {
        # Simply convert any other type to a string.
        [string] $x = $x
    }

    # $x is now a bona fide [string] variable that can be used
    # as such even in .NET method calls.

    return $x
}

It's somewhat cumbersome, but enables the caller to pass $null directly (or any string, or a type of any other instance that will be converted to a string).
A slight down-side is that this approach doesn't allow you to define positional parameters in the same position via different parameter sets that are selected by the parameters' specific types.

Finally, it's worth mentioning that if it's sufficient to detect when a (non-mandatory) parameter was omitted, you can check $PSBoundParameters:
function f {
    param (
        [string] $x
    )

    if ($PSBoundParameters.ContainsKey('x')) { # Was a value passed to parameter -x?
        "-x argument was passed: $x"
    } else {
        "no -x argument passed."
    }
}

As stated, this only works for the omission case (and therefore doesn't work for mandatory parameters at all). If you pass $null, the usual conversion to '' kicks in, and you won't be able to distinguish between passing $null and ''.
(Though if you added the above workaround / waited for the bug fix, you could again pass [NullString]::Value to effectively pass $null, or even use [NullString]::Value as the parameter default value.)

A: function f {
    param (
        [AllowNull()]$x
    )
    return $x
}

$r = f -x $null

By removing the [string] and using [AllowNull()] the above function will now allow you to pass in a null object or an empty string. You can check for the type using $x.GetType with an if statement and determining if $x is null or an empty string.

A: By default, [string] assigns default value as [string]::Empty, so the parameter definition will convert it whenever enters function f.
a. You can change the parameter as [object]$x
[object]$newparamnull -eq $null
[string]$newparamstring -eq [string]::Empty

b. The previous change will do the job:
function f {
    param (
        [AllowNull()]
        [object]
        $x)
   if($x -eq $null) {
      write-output "null"
   }
   elseif($x -eq [string]::empty){
      write-output "empty"
   }
   else {"other"}
}

Test:
f -x $null
f -x [string]::empty
f -x "aaa"