text:
Q: JTable autoresize issue I'm creating a program in which user can record and analyze the start time and end time of an activity. I think it is having an autoresize problem: at the start of the program, the table shrinks weirdly. But when I click on any cell, it becomes normal.

Below is my code
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.table.*;
import java.awt.event.*;

public class TestTimeLog {
private static int COLUMN_NUM = 4;
private int rowNum = 11;
private JTable table;
private JPanel tablePanel;
public static int FRAME_WIDTH = 700;
public static int FRAME_HEIGHT = 800;

/*
 * Panel that holds the table
 */
public JPanel TimeLogPanel() {

    JPanel timeLogPanel = new JPanel();
    // Create border layout with horizontal gap and vertical gap between components
    timeLogPanel.setLayout(new BorderLayout(20, 20));

    // Set border with parameters of top, left, bottom and right spacing
    timeLogPanel.setBorder(BorderFactory.createEmptyBorder(20, 40, 40, 20));
    timeLogPanel.add(tablePanel, BorderLayout.CENTER);

    // Create table panel and set layout
    tablePanel = new JPanel();
    tablePanel.setLayout(new BorderLayout());

    // Add a component listener to be able to calculate the panel size, thus
    // calculate width and height of column
    tablePanel.addComponentListener(new ComponentListener() {

        // Override component resized method and change cell width and height
        @Override
        public void componentResized(ComponentEvent e) {
            if (tablePanel.getHeight() / rowNum >= 1) {
                table.setRowHeight(tablePanel.getHeight() / rowNum);
            }
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            table.getColumnModel().getColumn(0).setPreferredWidth(tablePanel.getWidth() / 5);
            table.getColumnModel().getColumn(1).setPreferredWidth(tablePanel.getWidth() / 5);
            table.getColumnModel().getColumn(2).setPreferredWidth(tablePanel.getWidth() / 2);
            table.getColumnModel().getColumn(3).setPreferredWidth(tablePanel.getWidth() / 10);
        }

        // Below methods are not used but must be there, as a requirement when adding a
        // listener
        @Override
        public void componentMoved(ComponentEvent e) {
        }

        @Override
        public void componentShown(ComponentEvent e) {
        }

        @Override
        public void componentHidden(ComponentEvent e) {
        }
    });

    // Create a new table with a table model (defined in a different method below)
    table = new JTable(tableModel());

    // Change appearance
    table.setShowGrid(true);
    table.setGridColor(Color.BLACK);
    table.setSelectionBackground(Color.WHITE);
    table.setSelectionForeground(Color.BLACK);

    // Set a raised border
    table.setBorder(new EtchedBorder(EtchedBorder.RAISED));

    // Add table to JScrollPane which is added to table panel
    JScrollPane scrollPane = new JScrollPane(table);
    tablePanel.add(scrollPane);

    return timeLogPanel;
}

/*
 * This method overrides a table model so that it shows desired column names
 */
public DefaultTableModel tableModel() {
    DefaultTableModel model = new DefaultTableModel(rowNum, COLUMN_NUM) {

        private static final long serialVersionUID = 1L;
        String[] columnNames = { "Start Time", "End Time", "Activity", "Priority" };

        @Override
        public String getColumnName(int index) {
            return columnNames[index];
        }
    };
    return model;
}

/*
 * This main method creates a JFrame that holds the JPanel
 */
public void main(String[] args) {

    // Create a new frame
    JFrame guiFrame = new JFrame("Time Log Program");

    // Set size of the frame
    guiFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);

    // Add the panel
    guiFrame.add(TimeLogPanel());

    // Exit normally on closing the window
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Show the frame
    guiFrame.setVisible(true);
    }
}

Somewhere in the code, I did turn off auto resize mode. But the weird display still happens, and I've go not idea how to fix it.
I appreciate any suggestions. Thanks!
EDIT: Also, half of the time I run the program, it will show up perfectly right (a normal table), and half of other time a shrank table appears. It's so weird.


text:
Q: Question about zeros of partial sums of Taylor series of Riemann xi-function Consider the entire function  $ \psi(z) $ whose Taylor series about 1/2   "looking like"  the Riemann xi-function $ \xi(z)=\sum_{n=0}^{\infty}a_{2n}(z-1/2)^{2n} $, but with different  coefficients $a\psi_{2n}$. It is intuitively clear that one can choose these coefficients so that all partial sums of the Taylor series of this function would have zeros only with the real part of  1/2  (for example, one can choose $a\psi_{2n} \sim exp(-n^2)$). Is it also intuitively clear that all the zeros of the function itself $ \psi(z) $ will also lie on the straight line $x=1/2$? Or it is not obvious? I would like to clarify this question.

A: Let $f_N(z) = \sum_{n=0}^N c_n z^n$ with $c_n $ real, if its $N$ zeros $a_{N,1},\ldots,a_{N,N}$ are real and simple there is $r_{N+1} \le 1$ such that for any $c_{N+1}\in [- r_{N+1},r_{N+1}]$,  $f_{N+1}(z) = c_{N+1} z^{N+1}+f_N(z)$ has sign changes and $f_{N+1}'(z)$ stays of constant sign near $a_{N,j}$, so that $a_{N+1,j} \approx a_{N,j}$ is real and simple.
The $N+1$-th zero of $f_{N+1}$ is simple and it can't be complex since complex zeros come by pair.
Letting $c_0 = 1$ and $c_{N+1} = \min(r_{N+1}, e^{-N^2})$ yields an entire function $f(z) = \sum_{n=0}^\infty c_n z^n$ whose zeros are all real and whose every partial sums have only real zeros.
It is not obvious to check if $(e^{-n^2})$ decreases fast enough for $\sum_{n=0}^\infty e^{-n^2} z^n$ to be in that class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Git Extensions 'Do not commit' not working I'm using the Git Extensions version [2.50.02 - latest (current)]. When I open the "Merge branches" I see the checkbox "Do not commit" is checked.

When I perform a Merge, I see all changes are committed (not pushed to the remote). I was expecting these changes are not to be committed so I could review before pushing to the remote branch.
Log shows Git Extension performs the following command

git merge branch --no-commit --no-ff

Has anyone seen this issue? If yes is there a work around?

A: The documentation on the --no-commit option states :

--commit, --no-commit
     Perform the merge and commit the result. This option can be used to override --no-commit.
With --no-commit perform the merge but pretend the merge failed and do not autocommit, to give the user a chance to inspect and further tweak the merge result before committing.

What it does not state explicitly is : the modified files are staged (as if all files had been git added).
You can however see this pretty quickly if you run a git status on your repo.
If you want to review the differences before really committing, you will have to use the --cached opiton on git diff like commands :
git diff --cached
git difftool --cached
git difftool -d --cached
gitk --cached
# etc ...

If changes are already committed on your local machine, it is not what I would have expected from a plugin which states it has run git merge branch --no-commit --no-ff.
I would suggest to look in the log file at the actions after this line to see if by any chance a commit was triggered,
if you see no extra action there, and you do not remember to have done something which may have triggered the commit, it could be a bug in the extension.
Anyway, your changes are not published yet (not pushed), and you can still review the differences by running :
git diff HEAD HEAD~1

If you want to get rid of that commit, but keep the modifications as staged, you can also run :
git reset --soft HEAD~1

As stated above, you can then review the differences using :
git diff --cached


text:
Q: TypeError: 'str' object is not callable I am stuck with these 2 errors in Python 3.3.2:
import os
path="D:\\Data\\MDF Testing\\MDF 4 -Bangalore\\Bangalore Testing"
os.chdir(path)

for file in os.listdir("."):
    if file.endswith(".doc"):
        print('FileName is ', file)

def testcasenames(file):
    nlines = 0
    lookup="Test procedures"
    procnames=[]
    temp=[]
    '''Open a doc file and try to get the names of the various test procedures:'''
    f = open(file, 'r')
    for line in f:
        val=int(nlines)+1
        if (lookup in line):
            val1=int(nlines)
        elif(line(int(val))!=" ") and line(int(val1))==lookup):
            temp=line.split('.')
            procnames.append(temp[1])
        else:
            continue
    return procnames

filename="MDF_Bng_Test.doc"
testcasenames(filename)

Traceback (most recent call last):
  File "D:/Data/Python files/MS_Word_Python.py", line 34, in <module>
    testcasenames(filename)
  File "D:/Data/Python files/MS_Word_Python.py", line 25, in testcasenames
    elif(line(val)!=" " and line(val1)==lookup):
TypeError: 'str' object is not callable

The idea is to only get the test procedure names after I get the Section "Test procedures" while looping in the Test document file (MDF_Bng_Test.doc) and after that I copy all the test procedure names (T_Proc_2.1,S_Proc_2.2...)coming under it.
Ex:
    1.1.1 Test objectives
       1.Obj 1.1
       2.Obj 1.2
       3.Obj 1.3
       4.Obj 1.4
  **2.1.1 Test procedures
       1.T_Proc_2.1
       2.S_Proc_2.2
       3.M_Proc_2.3
       4.N_Proc_2.4**
    3.1.1 Test References
       1.Refer_3.1
       2.Refer_3.2
       3.Refer_3.3

A: when you use () with line, it thinks that line is a function which actually is not. What you actually need to use is [] notation
line[int(val)]!=" " and line[int(val1)]==lookup

A: The problem is in this line:
elif(line(int(val))!=" ") and line(int(val1))==lookup):

If you are trying to index the string, Python uses square brackets notation ([]) to accomplish it, it would be like this:
elif(line[int(val)]!=" ") and line[int(val1)]==lookup):

Another suggestion, parenthesis wrapping if..else statements in Python are optional and normally the code looks better without them:
elif line[int(val)]!=" " and line[int(val1)]==lookup:

Hope this helps!


text:
Q: large modular arithmetic without powers How would you find the answer to this
$$111453 \cdot 1812337  \bmod(10)$$
I know how to do it if given powers but don't know how to solve something like this above.

A: Note : $$111453 \equiv 3 \pmod{10} \ and \ 1812337 \equiv 7 \pmod{10}$$ $$\implies 111453 \times 1812337 \equiv 3 \times 7 \equiv 21 \equiv 1 \pmod{10}$$

A: It is equal to:
$111453$ (mod 10) $×1812337$ (mod 10)


text:
Q: How to modify HTMLbody of email created from default ribbon button and keep default signature? I want, when I create an email using the default ribbon button, to add a greeting to the body while also keeping the default signature.
I have a public function that uses TimeValue to calculate whether to add "Good morning," or "Good afternoon,". I call a sister function that adds it to the email.
Both of these are in a module called "AutoGreeting".
Option Explicit

Public Function Greeting() As String
' Defines greeting by time of day '
' Used in with the AddGreeting() function and clsMailHandler '

    ' If before noon, greeting is Good Morning'
    If Time >= TimeValue("8:00 AM") And Time <= TimeValue("11:59 AM") Then
        Greeting = "Good morning,"
    ' If after noon and before work ends, greeting is Good Afternoon'
    ElseIf Time >= TimeValue("12:00 PM") And Time <= TimeValue("5:10 PM") Then
        Greeting = "Good afternoon,"
    End If
End Function

' call this function to add the above calculated greeting to an email '
' i.e. Call AddGreeting(NewlyCreatedEmail)
Public Function AddGreeting(ByRef DraftEmail As mailItem)

' DraftEmail is used with reference to any MailItem object '
' like in clsMailHander > NewInspector > objCurrentItem / objMailNew '

With DraftEmail
    ' Temporarily editing the subject for testing/debugging to make sure this works
    .Subject = "AddGreeting Function"
    ' This adds the greeting but isn't able to keep the OG body AKA the auto-signature
    ' Because newInspector fires before signature is added
    .HTMLBody = Greeting() & DraftEmail.HTMLBody
End With
End Function

I built a class module for event handling to detect when a new inspector opens and that it is a mailitem. (Unfortunately, it's seems not able to detect yet whether it is a new email or if it is an email that's been retrieved and opened. If you double-click an email from your inbox, it opens in an inspector window. I do this by accident sometimes.)
Explorers and the objMailReply variable are there because I also want to do this for inline replies. I have the event handlers for newExplorer and ActiveInlineResponse that I left out here because I'm focusing on new emails in the inspectors, for now.
Class module is called "clsMailHandler"
' Class for event handling of created emails
' re-start Outlook after compiling and saving changes to re-initialize class
' or run Application_Quit and Application_Startup from ThisOutlookSession cls

Option Explicit

Public WithEvents olApp As Outlook.Application
Public WithEvents objInspectors As Outlook.Inspectors
Public WithEvents objActInspector As Outlook.Inspector
Public WithEvents objExplorers As Outlook.Explorers
Public WithEvents objActExplorer As Outlook.Explorer
Public WithEvents objCurrentItem As Outlook.mailItem
Public WithEvents objMailNew As Outlook.mailItem
Public WithEvents objMailReply As Outlook.mailItem

' Called under Application_Startup in ThisOutlookSession as Handler class is created
Public Sub Class_Initialize()
Set olApp = Outlook.Application
' so far, all that's needed here is to initialize the explorers and inspectors w/ the app itself
Set objInspectors = olApp.Inspectors
Set objExplorers = olApp.Explorers
Set objActExplorer = olApp.ActiveExplorer
End Sub

' Called in Application_Quit as handler class is  cleared
Public Sub Class_Terminate()
'when the application is closed, the class is terminated
'un-set variables
Set olApp = Nothing
Set objInspectors = Nothing
Set objActInspector = Nothing
Set objExplorers = Nothing
Set objActExplorer = Nothing
Set objMailNew = Nothing
Set objMailReply = Nothing
Set objCurrentItem = Nothing
End Sub

' Event handler for a new inspector window opening (i.e. new email is created)
' ISSUE - or when a received email is opened in a new window (double-click)
Public Sub objInspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
Dim insType As String
Set objActInspector = Inspector
' this is just to keep names of object variables short and easy to remember
Set objCurrentItem = objActInspector.CurrentItem
' grab & test type name of current inspector item
insType = TypeName(objCurrentItem)
If insType = "MailItem" Then
    ' if its a mailItem - set variable that's more specific
        Set objMailNew = objCurrentItem
    ' MsgBox is for debugging to make sure this fires
        MsgBox ("New email has been created")
    ' Function from other module that is called to add the greeting
    ' Again, this works to add the greeting, but it doesn't keep the auto-signature
        Call AddGreeting(objMailNew)
End If
End Sub

' This also fires if a received email that was opened in a new window is closed.
Public Sub objActInspector_Close()
' if the inspector window (created email) is closed, clear the variables
    Set objMailNew = Nothing
    Set objCurrentItem = Nothing
    MsgBox ("Inspector has closed")
End Sub

This is how the class is initialized from within ThisOutlookSession
Option Explicit
'Instantiate the class on global application level
Dim EventHandler As clsMailHandler

Sub Application_Startup()
'Set custom variable as new instance of class
'to initialize the class (run Class_Initialize() sub)
Set EventHandler = New clsMailHandler
End Sub

Sub Application_Quit()
'Set handler to nothing to clear instance of class
Set EventHandler = Nothing
End Sub

The event handler for newInspector calls the function that adds the greeting (and edits the subject for testing/debugging purposes), but then my auto-signature doesn't get added. I think because the newInspector event fires off before the email exists, so the automatic signature doesn't fire.
Most of the solutions I see involve programmatically creating the email CreateItem(olMailItem), but I want to apply these to emails created by default.
Some other offered solutions I've seen might work, but I can't find examples I fully understand. Like inspector_activate from Event that fires after signature is added.
How do I get my automatic greeting and keep my automatic signature?

A: First, new items don't have the EntryID property set, it is empty until the item is saved to the store in Outlook. So, checking the property value can help with distinguishing new items and saved ones.
Second, you need to wait for the first Activate event of the Inspector class if you want to get the signature added to the message body. Otherwise, the default signature will be overwritten with your message body modifications.
Third, to preserve the default signature in the message body you must insert your greetings right after the opening <body> tag in the HTMLBody property value.

A: My own answer:
I fixed it using the Inspector_Activate event as a SEPARATE sub. The default "new email" ribbon button creates a new inspector window that the _NewInspector event catches and sets as the active inspector. Inspector_Activate event then gets triggered as the email itself finishes its own creation/initialization process. Then the AddGreeting() function is called to edit the .HTMLbody and add the automated greeting.
Public Sub objInspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
If TypeName(Inspector.CurrentItem) = "MailItem" Then
        Set objActInspector = Inspector
End If
End Sub

Public Sub objActInspector_Activate()
MsgBox ("Inspector Activate")
Set objMailNew = objActInspector.CurrentItem
If Len(objMailNew.EntryID) = 0 Then
    Call AddGreeting(objMailNew)
  End If
  Set objActInspector = Nothing
End Sub

Found it on this random website: https://www.vboffice.net/en/developers/newinspector-and-inspector-activate/


text:
Q: Physically unacceptable solutions for the QM angular equation I'm reading Griffiths's Introduction to Quantum Mechanics 3rd ed textbook [1]. On p.136, the author explains:

But wait! Equation 4.25 (angular equation for the $\theta$-part) is a second-order differential equation: It should have two linearly independent solutions, for any old values of $\ell$ and $m$. Where are all the other solutions? (One is related to the associated Legendre function.)
Answer: They exist of course, as mathematical solutions to the equation, but they are physically unacceptable because they blow up at $\theta=0$ and/or $\theta=\pi$ (see Problem 4.5).

In problem 4.5, I can find that the function $A\ln[\tan (\theta/2)]$ satisfies the $\theta$ equation for $\ell=m=0$. And such function blows up at $\theta=0$ and $\theta=\pi$.
But why such function is physically unacceptable? For the wave function to be physically acceptable, it fundamentally needs to be square-integrable. And  $\ln[\tan (\theta/2)]$ does actually!
$$\int_{0}^\pi [\ln[\tan (\theta/2)]]^2\sin\theta \text d\theta= \frac{\pi^2}6$$
For the well-behaved function case, it makes sense to set the function condition 'finite' and 'square-integrable' equivalently. In this case, although $\ln[\tan (\theta/2)]$ blows up at $\theta=0$ and $\theta=\pi$, it is still square-integrable tamed by $\sin \theta$ term. So it can be normalized to satisfy the Born's statistical interpretation. But the author says such function is physically unacceptable so I wonder why.
Reference
Griffiths, D. J.; Schroeter, D. F. Introduction to Quantum Mechanics 3rd ed; Cambridge University Press, 2018. ISBN 978-1107189638.

A: We are in principle trying to solve the angular TISE problem$^1$
$$ \vec{\bf L}^2Y~=~\hbar^2\ell(\ell+1)Y, \qquad {\bf L}_zY~=~\hbar m Y, $$
on the unit 2-sphere $\mathbb{S}^2$. However, we are using a "tropical" coordinate system $(\theta,\phi)$ that is singular at the north & south poles $\theta=0,\pi$. Hence, we should strictly speaking also solve the TISE in mathematically well-defined "arctic/antarctic" coordinate neighborhoods of the north & south poles, respectively, and see if we can glue the local solutions together into a global solution on $\mathbb{S}^2$. Not surprisingly$^2$, the "arctic/antarctic" coordinate solutions have no singularities at the poles. So the gluing is not possible if the tropical $(\theta,\phi)$ coordinate solution displays singularities at $\theta=0,\pi$, i.e. such singularities are physically unacceptable.
--
$^1$ Here we stick to the differential-geometric formulation using wavefunctions. There is of course also a well-known algebraic formulation using ladder operators, which we will not address here.
We can assume wlog that $\ell\geq 0$. The single-valuedness of the wavefunction $Y$ implies that the constant $m\in\mathbb{Z}$ is an integer. Its range $|m|$ is bounded by $\ell$ for physical reasons. In particular it follows that for fixed $\ell$, the number of independent tropical solutions are finite.
$^2$  After all the $Y$ solutions should maintain $SO(3)$ covariance. Recall that the tropical solutions $Y$ have no singularities or discontinuities at internal points. In fact they are smooth maps in the interior. This can e.g. be derived by a bootstrap argument a la what is done in my Phys.SE answer here. A formulation using weak solutions doesn't change the main conclusion.
An arctic/antarctic solution should then be a linear combination of the finitely many $90^{\circ}$-rotated tropical solutions for the corresponding problem with ${\bf L}_z$ replaced by, say, ${\bf L}_x$. A  finite sum cannot develop internal singularities. $\Box$

A: As mentioned in the answers to How to know if a wave function is physically acceptable solution of a Schrödinger equation? one should also require square-integrability of higher-order derivatives. In your case this already fails for the first derivative.


text:
Q: Using interplot to plot continuous*continuous interactions for multiple individuals I want to produce a plot which demonstrates the effects of a continuous by continuous interaction, with one line for each individual in the dataset. I have managed to successfully plot the interaction at the population level using interplot:

m2<-lmer(RMR~No_Squares*Temperature+(Temperature|ID), data=female1)

interplot(m = m2, var1 = "No_Squares", var2 = "Temperature", ci=FALSE)

But I am at a loss as how to produce such a plot for each individual ID (i.e. to show the differences between individuals)
I have tried adding:
+ geom_smooth(aes(group = ID), method = "lm")

To the code, but this doesn't work.
Any ideas?


text:
Q: Simple Ordinary Differential Equation As simple as this should be, I can not seem to solve it. I can't classify its type and thus figure out how to solve it. It's the only ODE in my problem sheet that I can't solve (embarrassing).
$$t\left(\frac{\mathrm{d}x}{\mathrm{d}t}\right)=x+\sqrt{t^2+x^2}$$

A: Hint, let:
$$x = t v(t) \rightarrow x' = v + t v'$$
Substituting into the original equation, doing some algebra and rearranging, eventually leads to the integration:
$$\int \dfrac{dv}{\sqrt{v^2+1}} = \int \dfrac{1}{t} dt$$
Can you take it from there?

A: This differential equation is an example of a homogeneous differential equation. The reason that change of variables works is because that is the standard technique for solving Euler-homogeneous differential equations. You should always check if a differential equation is exact (poincare's lemma), if non-exact then find an integrating factor (Frobenius theorem) & theoretically the problem can always be solved. However there are shortcuts or more direct methods in special cases such as separable equations, euler-homogeneous equations, linear equations, linear fractional equations, then a bunch of equations with names attached. After that unless you can find a change of variables (Lie theory) you have to use some form of approximation technique, at least in the case of first degree ode's of first order. You shouldn't really think of it as change of variables technique because it only really applies in the homogeneous case, & homogeneity is used for studying higher degree ode's as well hence it has some importance on it's own. Here's a good book.


text:
Q: Trouble obtaining data using genfromtxt I have the following code:
import pandas as pd
data = [['Initial height', param[4]],
        ['Exponential decay constant', param[1]],
        ['Angular frequency', param[2]],
        ['Phi offset', param[3]],
        ['The amplitude', param[0]]]
df = pd.DataFrame(data, columns=['Variable', 'Value'])
print(df)

writePath = '/Users/harryhat/Desktop/Droplet Experiment/Variables/Trial/water-3 variables.txt'
with open(writePath, 'w') as f:
    f.write(
        df.to_string(header = False, index = False)
    )

data = np.genfromtxt(writePath, usecols=2)

from which I want to obtain the second column as save it as data. However when I try to use this the second parameter comes up as nan but I don't know why. Attached is the console showing what type it is and that value that it is. Does anyone know why im getting nan for that value? Any help is appreciated.

A: With your write:
    In [31]: with open('tst1.csv', 'w') as f:
    ...:     f.write(
    ...:         df.to_string(header = False, index = False)
    ...:     )
    ...:

In [33]: cat tst1.csv
             Initial height  0.601793
 Exponential decay constant  0.612753
          Angular frequency  0.109519
                 Phi offset  0.301704
              The amplitude  0.649477

In [34]: np.genfromtxt('tst1.csv', usecols=2)
Out[34]: array([0.601793,      nan, 0.109519, 0.301704, 0.649477])

The default delimiter is white space.  The problem line has 4 fields:
In [35]: np.genfromtxt('tst1.csv')
Traceback (most recent call last):
  File "<ipython-input-35-307e4ac22394>", line 1, in <module>
    np.genfromtxt('tst1.csv')
  File "/usr/local/lib/python3.8/dist-packages/numpy/lib/npyio.py", line 2080, in genfromtxt
    raise ValueError(errmsg)
ValueError: Some errors were detected !
    Line #2 (got 4 columns instead of 3)

If instead I use
In [37]: df.to_csv('tst.csv')

In [38]: cat tst.csv
,Variable,Value
0,Initial height,0.6017927371181283
1,Exponential decay constant,0.6127532376900192
2,Angular frequency,0.109519476902042
3,Phi offset,0.3017037244796229
4,The amplitude,0.6494771015260451

This loads col 2 just fine - the initial nan is the header, which I could skip:
In [39]: np.genfromtxt('tst.csv',delimiter=',', usecols=2)
Out[39]:
array([       nan, 0.60179274, 0.61275324, 0.10951948, 0.30170372,
       0.6494771 ])

genfromtxt has a lot of parameters, though not as many as to_csv.


text:
Q: Are there any server requirements for WordPress transients to work properly? Background Info
I sell WordPress themes where I include a Twitter widget. In the widget I use a WordPress transient that refreshes every 3 hours to cache the Tweets. I've got thousands of people using this and it seems to work for just about everyone. Also, I've done little tests on my end to ensure I know the cache is working properly with how I have everything setup.
However, I've run into maybe 2 or 3 buyers where it's apparent that the cache is not working at all on their servers.
Note: I can tell because they keep getting timeout issues as they're hitting the Twitter API more than the allowed 150 times in an hour.

The Question
So, are there any reasons why someone's specific web server could have problems with WordPress transients? Or maybe something specific to someone's WordPress configuration? Is there anything else I could be overlooking?

A: I had a similar problem once with an aggressive database cache: the first check for an existing transient returned nothing – which was okay – but after I created the transient, I didn't get it, because the empty cached result was always returned. So I built a dozen duplicated transients until I found the issue.
Ask your clients if it happens after they disabled the data base cache. You could filter the 'query' and insert a SQL_NO_CACHE before you check the transient. Make sure to remove the filter afterwards.

A: I had the same issues while checking for updates. It seems that on some hosts transients do not work. And I think it's a problem with the Object Cache.
The normal behaviour is that WordPress saves the transients into the MySQL Database. The value of the transients will be saved as well as the timestamp. If you call a transient with the get_transient() function, WordPress will check if the transient in the database is still valid. If not, it will delete the transient.
I've recognized that this only happens if a customer uses the Object Cache (maybe through an Drop-In-Plugin like the Memcached plugin). I think that is because of a misconfiguration of Memcached. The Object Cache runs out of space and therefore requests for new data with every pageload.
Hopefully I can test this in the near future to provide more information about that.


text:
Q: Linux: Get information/stats about storage network I want to know as much info as possible about the SAN a linux server is connected to.  What commands will give me the most comprehensive view?   Simply knowing the WWN of LUNS doesn't do much for me.  I'd like to know make/model of SAN/disks (if possible), but more importantly speed and performance stats. What do you use for a quick and dirty assessment of your SAN performance (FC or iSCSI)?

A: I'd ask the SAN administrator. It's easier than guessing :) I mean, fdisk and dmesg will give you manufacturer info.
But the answer to this depends on the make/model of the storage array. NetApp != HDS != Lefthand != EMC
Can you give some more info about what you want to know?
If you need SAN specs and don't readily have access to the administrator, that's not a technical issue.
If you are connected and need to benchmark, that IS within your control. At that point, iozone, fio and iostat are your friends. Generate a load on the relevant LUN and measure its performance.

A: I know how it's done AIX, but a quick google on Linux brought me the sg3_utils package. You want to send a SCSI inquiry. Each storage will have their own way of replying- my VSP, for example, embeds the LDEV address, array serial number, and a bunch of other useful information into its reply.
SCSI inquiries are a part of the SCSI protocol, meaning that it should work whether you use FC, FCoE, or iSCSI. That said, it sounds like you want more information than you'll likely get back. If you want to know something about the raid level, caching, or hostgroup settings, you'll probably need to get the data directly from the array.

A: Your question indicates that you are looking for far more than the command-line is suited for. Server monitoring tools like Nagios and its derivatives offer plugins for state-of-the-art SAN monitoring.
SolarWinds also offers a Free SAN Monitor that may be of interest.
In terms of getting this information from the SAN at a lower-level, for instanec using NSMP as @Florin mentions, we would need more information your SAN systems' architecture in order to make suggestions.


text:
Q: Displaying different data types in one canvas based on ItemsControl only shows first Item of each object I need your help again.
The solution worked out very well but after vacation and doing other stuff I need to modify it.
Actually there are Objects (CanvasObject) which are drawn on startup/after reading xml data and others (Module) which are dropped into the canvas from a treeview. These Modules are showing up in the canvas visual children but I cant see them at the canvas.
This is my code so far - I tried different approaches but always got similar results:
C#:
public class CanvasLine
{
    public Point P1 { get; set; }
    public Point P2 { get; set; }
    public Brush Stroke { get; set; }
    public double StrokeThickness { get; set; }
    public DoubleCollection StrokeDashArray { get; set; }
}

public class CanvasObject
{
    public String Name { get; set; }
    public ObservableCollection<CanvasLine> CanvasLines { get; set; }
}

public class Module
{
    public Dictionary<String, String> Attributes { get; set; }
    public Point AnchorPoint { get; set; }
    public Double Height { get; set; }
    public Double Width { get; set; }
}

public class ViewModel
{
    ...
    public ObservableCollection<Object> CanvasObjects;
    ...
}

The Viewmodels ObservableCollection<Object> gets filled with CanvasObjects from a xml - these ones are shown correctly. After that I'm adding Modules to that Collection by dropping them to the canvas. These ones seems to be into the canvas children collection but are not visible.
Here is the corresponding / cleaned up XAML:
        <ItemsControl Grid.Column="1" Grid.Row="2" Margin="0" ItemsSource="{Binding CanvasObjects, UpdateSourceTrigger=PropertyChanged}">
        <ItemsControl.Resources>
            <ScaleTransform x:Key="LineTransform"
                            ScaleX="{Binding ActualWidth,
                 RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                            ScaleY="{Binding ActualWidth,
                 RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
        </ItemsControl.Resources>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas Background="Transparent" AllowDrop="True" Drop="Canvas_OnDrop"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplateSelector>
            <xmlTemp:TemplateSelector>
                <xmlTemp:TemplateSelector.ModuleTemplate>
                    <DataTemplate DataType="{x:Type xmlElements:Module}">
                        <ItemsControl ItemsSource="{Binding RelativeSource={RelativeSource Self}}">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <Canvas/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemContainerStyle>
                                <Style TargetType="ContentPresenter">
                                    <Setter Property="Canvas.Left" Value="{Binding AnchorPoint.X}"/>
                                    <Setter Property="Canvas.Top" Value="{Binding AnchorPoint.Y}"/>
                                </Style>
                            </ItemsControl.ItemContainerStyle>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Rectangle Width="{Binding Width}" Height="{Binding Height}" StrokeThickness="2" Fill="Black" Stroke="Black">
                                        <Rectangle.RenderTransform>
                                            <StaticResource ResourceKey="LineTransform"/>
                                        </Rectangle.RenderTransform>
                                    </Rectangle>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </DataTemplate>
                </xmlTemp:TemplateSelector.ModuleTemplate>
                <xmlTemp:TemplateSelector.LineObjectTemplate>
                    <DataTemplate DataType="{x:Type dt:CanvasObject}">
                        <ItemsControl ItemsSource="{Binding CanvasLines}">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <Canvas/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Path Stroke="{Binding Stroke}"
                                  StrokeDashArray="{Binding StrokeDashArray}">
                                        <Path.Data>
                                            <LineGeometry
                                                Transform="{StaticResource LineTransform}"
                                                StartPoint="{Binding P1}"
                                                EndPoint="{Binding P2}"/>
                                        </Path.Data>
                                        <Path.Style>
                                            <Style TargetType="Path">
                                                <Style.Triggers>
                                                    <Trigger Property="IsMouseOver" Value="True">
                                                        <Setter Property="StrokeThickness">
                                                            <Setter.Value>
                                                                <MultiBinding Converter="{StaticResource MultiplicationConverter}">
                                                                    <Binding Path="StrokeThickness" Mode="OneWay"/>
                                                                    <Binding Source="3"/>
                                                                </MultiBinding>
                                                            </Setter.Value>
                                                        </Setter>
                                                    </Trigger>
                                                    <Trigger Property="IsMouseOver" Value="False">
                                                        <Setter Property="StrokeThickness" Value="{Binding StrokeThickness, Mode=OneWay}"/>
                                                    </Trigger>
                                                </Style.Triggers>
                                            </Style>
                                        </Path.Style>
                                    </Path>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </DataTemplate>
                </xmlTemp:TemplateSelector.LineObjectTemplate>
            </xmlTemp:TemplateSelector>
        </ItemsControl.ItemTemplateSelector>
    </ItemsControl>

Here are the missing event and template selector:
private void Canvas_OnDrop(Object sender, DragEventArgs e)
    {
        Module Module = e.Data.GetData("Module") as Module;
        Canvas Canvas = sender as Canvas;
        if (Module != null && Canvas != null)
        {
            Module.Width = 0.1;
            Module.Height = 0.2;

            Module.AnchorPoint = e.GetPosition(Canvas);
            ViewModel.CanvasObjects.Add(Module);
        }
    }

public class TemplateSelector : DataTemplateSelector
{
    public DataTemplate LineObjectTemplate { get; set; }
    public DataTemplate ModuleTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item is CanvasObject)
            return LineObjectTemplate;
        if (item is Module)
            return ModuleTemplate;
        return base.SelectTemplate(item, container);
    }
}

If I'm changing the ModuleTemplates ItemsControl to a ListBox I can see at least that there is some selected element in the top left corner after dropping a Module somewhere in the canvas. I'm thinking that the Rectangles Container might have no size but I'm not sure how to handle that correctly. Also the dropping position has no effect.
Possibly it's just a stupid error, just like the transparent, not dropable/hitable background which costs me over an hour today and I'm "seeing" it tomorrow after a few hours of sleep but every help and hint is highly appreciated!
Greetings
Edit:
THX to elgonzo I found the error. The Modules ItemsControl was unnecessary! THX again, perfect time to finish work now ;)
Following Code works fine:
        <ItemsControl Grid.Column="1" Grid.Row="2" Margin="0" ItemsSource="{Binding CanvasObjects, UpdateSourceTrigger=PropertyChanged}">
    <ItemsControl.Resources>
        <ScaleTransform x:Key="LineTransform"
                        ScaleX="{Binding ActualWidth,
             RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                        ScaleY="{Binding ActualWidth,
             RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
    </ItemsControl.Resources>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Background="Transparent" AllowDrop="True" Drop="Canvas_OnDrop"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplateSelector>
        <xmlTemp:TemplateSelector>
            <xmlTemp:TemplateSelector.ModuleTemplate>
                    <DataTemplate DataType="{x:Type xmlElements:Module}">
                        <DataTemplate.Resources>
                            <Style TargetType="ContentPresenter">
                                <Setter Property="Canvas.Left" Value="{Binding AnchorPoint.X}"/>
                                <Setter Property="Canvas.Top" Value="{Binding AnchorPoint.Y}"/>
                            </Style>
                        </DataTemplate.Resources>
                        <Rectangle Width="{Binding Width}" Height="{Binding Height}" StrokeThickness="2" Fill="Black" Stroke="Black">
                            <Rectangle.RenderTransform>
                                <StaticResource ResourceKey="LineTransform"/>
                            </Rectangle.RenderTransform>
                        </Rectangle>
                    </DataTemplate>
            </xmlTemp:TemplateSelector.ModuleTemplate>
            <xmlTemp:TemplateSelector.LineObjectTemplate>
                <DataTemplate DataType="{x:Type dt:CanvasObject}">
                    <ItemsControl ItemsSource="{Binding CanvasLines}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <Canvas/>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <Path Stroke="{Binding Stroke}"
                              StrokeDashArray="{Binding StrokeDashArray}">
                                    <Path.Data>
                                        <LineGeometry
                                            Transform="{StaticResource LineTransform}"
                                            StartPoint="{Binding P1}"
                                            EndPoint="{Binding P2}"/>
                                    </Path.Data>
                                    <Path.Style>
                                        <Style TargetType="Path">
                                            <Style.Triggers>
                                                <Trigger Property="IsMouseOver" Value="True">
                                                    <Setter Property="StrokeThickness">
                                                        <Setter.Value>
                                                            <MultiBinding Converter="{StaticResource MultiplicationConverter}">
                                                                <Binding Path="StrokeThickness" Mode="OneWay"/>
                                                                <Binding Source="3"/>
                                                            </MultiBinding>
                                                        </Setter.Value>
                                                    </Setter>
                                                </Trigger>
                                                <Trigger Property="IsMouseOver" Value="False">
                                                    <Setter Property="StrokeThickness" Value="{Binding StrokeThickness, Mode=OneWay}"/>
                                                </Trigger>
                                            </Style.Triggers>
                                        </Style>
                                    </Path.Style>
                                </Path>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </DataTemplate>
            </xmlTemp:TemplateSelector.LineObjectTemplate>
        </xmlTemp:TemplateSelector>
    </ItemsControl.ItemTemplateSelector>
</ItemsControl>


text:
Q: How to work with std::make_unique function and interface classes? Suppose we want to implement strategy pattern. We have an interface Base and two derived classes -- A and B. Instances of Doer class can choose between A's and B's methods do(). And the question is how to complete the code to make how it should be.
class Base {
  virtual void do() const = 0;
};

class A: public Base {
  void do() const override {};
};

class B: public Base {
  void do() const override {};
}

class Doer {
  public:
    Doer(std::unique_ptr<Base> b_ptr) : ptr(b_ptr) {}
    void do() const { ptr->do(); }
  private:
    std::unique_ptr<Base> ptr;
}

int main() {
  Doer doer(std::unique_ptr<Base>());
  doer.do();
  return 0;
}

A: Doer doer(std::make_unique<A>()); // or std::make_unique<B>()

The above is pretty much it. std::unique_ptr works very hard to implement the same coercion as the raw pointer it holds.

A: There are three major problems with your code.
1) do is a keyword of the language. You cannot use it as an identifier (like function name)
2) you take b_ptr by value, so you need to move from it:
Doer(std::unique_ptr<Base> b_ptr) : ptr(std::move(b_ptr)) {}

3) you pass an empty unique_ptr to Doer's constructor, which is equivalent to passing a nullptr. You also try to instantiate the base class. It is impossible because Base is a pure virtual class. Use make_unique with a derived type:
Doer doer(std::make_unique<A>());


text:
Q: Plotly not displaying the labs caption from ggplot I have this code for making a ggplot, which works fine (MRE with a built-in dataset):
mydata <- airquality
avg <- mean(mydata$Wind)
stde <- sd(mydata$Wind)
qup <- qnorm(p = 0.95,mean = avg, sd = stde)
qdown <- qnorm(p = 0.05,mean = avg, sd = stde)
N95 <- length(mydata$Wind[mydata$Wind < qup & mydata$Wind > qdown])
mydata$date <- as.Date(paste(mydata$Month,"-",mydata$Day,sep = ""),format = "%m-%d")

library(ggplot2)
g <- ggplot(mydata, aes(x = date, y = Wind)) + geom_point(aes(colour = "measurements"),pch = 16) +
  geom_hline(aes(yintercept = avg,colour = "mean"),lty = "solid",lwd = 1.2) +
  geom_hline(aes(yintercept = qup,colour = "95%-quantile"),lty = "dotted",lwd = 1.2) +
  geom_hline(aes(yintercept = qdown,colour = "5%-quantile"),lty = "dotted",lwd = 1.2) +
  scale_colour_manual(name = "", values = c(measurements = "deepskyblue4",mean = "goldenrod","95%-quantile" = "goldenrod","5%-quantile" = "goldenrod"),
                      guide = guide_legend(override.aes = list(linetype = c("blank","solid","dotted","dotted"), shape = c(16,NA,NA,NA)))) +
  ylab("Wind [mph]") + xlab("date") + ggtitle("wind speed") +
  scale_y_continuous(limits = c(0,25)) +
  labs(caption = paste("N = ", length(mydata$Wind), "; Mean = ", round(avg,digits = 3), "; Sd = ", round(stde,digits = 3), "; N within limits = ", N95, sep = "")) +
  theme(axis.line.x.bottom = element_line(size=1.5),axis.line.y.left = element_line(size=1.5),plot.title = element_text(hjust = 0.5), axis.title = element_text(size = rel(1.4)),legend.text = element_text(size = rel(1.4)),legend.title = element_text(size = rel(1.3)),axis.text = element_text(size = rel(1.2)))

print(g)

However when I want to make this plot interactive by calling print(plotly::ggplotly(g)), the caption defined in labs is not displayed. Any ideas what causes this or how to fix it?
Many thanks!


text:
Q: Difference between next( ) and next( ).CharAt(0); I have created an abstract class Employee which displays and calculates the Details of Weekly and Hourly Employee.In the main method i have used switch case for a menu and do while to continue using the program as long as the user want.But I'm getting an Error when compiling the code.:
*javac "AbstractDemo.java" (in directory: /home/user/Desktop)
AbstractDemo.java:52: error: incompatible types
    ch=s.next();
             ^
  required: char
  found:    String
1 error
Compilation failed.*

This is the Source Code:
import java.util.*;
abstract class Employee{
    Employee(float amt,int n){
        float sal;
        System.out.println("The amount paid to Employee is:"+amt);
        sal=amt*n;
        System.out.println("Total Salary is:"+sal);
    }

}
class WeeklyEmployee extends Employee{
        WeeklyEmployee(float a,int n){
        super(a,n);
    }
}
class HourlyEmployee extends Employee{
        HourlyEmployee(float amt,int hrs){
        super(amt,hrs);
    }
}

public class AbstractDemo {

    public static void main (String args[]) {
        int a;
        char ch;
        float amount;
        int hours;
        int weeks;
        Scanner s=new Scanner(System.in);
        do{

        System.out.println("Enter the choice");
        a=s.nextInt();
        switch (a) {
            case 1 :
        System.out.println("Enter the salary of weekly employee(Per Week):");
        amount=s.nextFloat();
        System.out.println("Enter the total no of week");
        weeks=s.nextInt();
             Employee W=new WeeklyEmployee(amount,weeks);break;
             case 2:

        System.out.println("Enter the salary of hourly employee(Per hour):");
        amount=s.nextFloat();
        System.out.println("Enter the total no of hours");
        hours=s.nextInt();
        Employee H=new HourlyEmployee(amount,hours);break;
            default:System.out.println("Error invalid Choice");
    }
    System.out.println("Do you wish to continue?(Y/N)");
    ch=s.next();
}while (ch== 'y'||ch== 'Y');

}
}

But When i use s.next().ChatAt(0); the code compiles successfully.Could somebody explain why this is happening?Is Char taking input as String?Or if it is a string why its showing an Error when i edit the while condition to while(ch=="y"||ch=="Y"); ?

A: ch is a char. s.next() returns a String. You can't assign a String to a char. You can assign the first character of the String to a char, which is what you do in ch = s.next().charAt(0);.
It's a good thing you are not trying while(ch=="y"||ch=="Y"), since that would fail even if you changed ch to be a String (which would allow it to pass compilation, but wouldn't give the expected result), since you can't compare Strings in Java with == (you should use equals instead).

A: s.next() returns the next String object. But s.next().charAt(0) returns the first character of the next String object. Hence its expecting character and throwing error

A: the method next() of the Scanner object returns a String. So in order for your assignment to work, you need to extract the first character from this string using the charAt() method.
And since ch is a character not String, while(ch == "y" || ch == "Y") won't work.
Use while(ch == 'y' || ch == 'Y') instead.
(single quotes = character, double quotes = string)

A: This because ch is char and your idea is input single letter Y or N to stop or continue your program. But, you use method next() of Scanner that return a String. That's main reason why you get this
*javac "AbstractDemo.java" (in directory: /home/user/Desktop)
AbstractDemo.java:52: error: incompatible types
    ch=s.next();
             ^
  required: char
  found:    String
1 error
Compilation failed.*
When you try to use s.next().ChatAt(0). It mean that you try to get first character from input.
-> this is just imcompatible types error when you try to assign String to Char without converting it.

A: When you use s.next(), it is read as a string. That's why you get an error with ch=s.next()
However, s.next().charAt(0) will return a char value which can be used by your variable.
Likewise, when you compare char ch to 'y', it compares two chars, but "y" reads as a string and would cause a type mismatch.


text:
Q: LinkedList writing to binary Im trying to write to binary this linked list but it gives me an acess violation. The InsertVertice and InsertAresta create a new instance of that struct and are working fine so i dont know why this is giving me an error. If you need i can add the InsertVertice and InsertAresta functions here.
typedef struct Arestas
{
    int vertice;
    char Action[100];
    struct Arestas* next;
}*arestas;

typedef struct Vertices
{
    int vertice;
    struct Vertices* next;
    struct Arestas* adjacente;
}*vertice;

void WriteBin(vertice v)
{
    FILE * f;
    vertice apt = v;
    struct Arestas* aresta;
    int i;
    f = fopen("Grafo.bin","wb");
    while(apt!=NULL)
    {
        aresta = apt->adjacente;
        fwrite(apt->vertice,sizeof(int),1,f);
        while(aresta!=NULL)
        {
            fwrite(aresta->vertice,sizeof(int),1,f);
            fwrite(aresta->Acao,sizeof(char),100,f);
            aresta = aresta->next;
        }
        apt = apt->next;
    }
}

void main()
{
    vertice v= NULL;
    v = InsertVertice(v,1);
    v = InsertAresta(v,1,2,"ola");
    v = InsertAresta(v,1,3,"hey");
    v = InsertAresta(v,1,4,"oi");
    v = InsertAresta(v,1,5,"hello");
    WriteBin(v);
    system("pause");
}

A: fwrite takes a pointer to the data you're writing as the first parameter. You're not passing it a pointer to an int. You're actually passing the int.
You probably need to do something like &(apt->vertice) for the first parameter.


text:
Q: The verb "sequence" I have found out that the verb "sequence" can mean to combine things in a particular order, or discover the order in which they are combined.
Can I use "sequence" the following way?
"The librarian has sequenced the books in some order. As a curious person, I want to sequence those books."


text:
Q: Xcode send variable with url to php page, retrieve variable in php code for the select statement I am trying to call a php page that connects to mysql database. I have been successful in loading all data from the table to an UITableView in xcode.
What I need to do now is change the select statement to load the data from the table with specific ID.
Here is my xcode:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://server/phppage.php"]];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
// here is where the variable i want to send
    [postDict setValue:@"1" forKey:@"CategoryType"];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
    NSString *urlString =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *stringData = [[NSString alloc] initWithFormat:@"jsonRequest=%@", urlString];
    NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBodyData;
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (!theConnection) {
        NSMutableData *responseData = nil;
        NSLog(@"connection failes");
    }

and here is the php page:-
<?php

// Create connection
$con=mysqli_connect("","","database","") or die ( mysqli_error($MySQL_Handle) );
$sSQL= 'SET CHARACTER SET utf8';
mysqli_query($con,$sSQL) or die ('Can\'t charset in DataBase');

// this is where the variable sent from the xcode is received

$cid = $GET_["CategotyType"];
$sql = "SELECT * FROM itesttable where phone = $cid";

if ($result = mysqli_query($con, $sql))
{
  $resultArray = array();
  $tempArray = array();
  while($row = $result->fetch_object())
  {
  $tempArray = $row;
     array_push($resultArray, $tempArray);
  }
  echo json_encode($resultArray);
}
mysqli_close($con);
?>

I don't know if the error is in the xcode and I'm sending the variable CategoryType the wrong way, or it is in the php and I'm retrieving the variable in a wrong way ....

A: The column phone is an INTEGER column? Because you can access to it without '' only if it is. If it is a VARCHAR, you have to change it to:
$sql = "SELECT * FROM testable WHERE phone = '".$cid."'";

However is a GET method, why don't you access it by URL?
http://wwww.yourdomain.ext/phpPage.php?CategoryType=YOUR_VALUE

A: In your PHP code you have a typo: you query the value for CategotyType instead of CategoryType.
Also, you really, really want to read about what a SQL injection vulnerability is and how to prevent them in PHP.


text:
Q: How to deploy a single user control which has changes to the cs file (ascx.cs) I have a user control (UserControl1.ascx) and I made changes to Its cs file.
That UserControl1.ascx is being used by two or more aspx files using LoadControl.
I don't want to deploy the whole web project dll as this is a fix for a critical issue in a part of the web app and doesn't affect the whole web app.
Updating changes to the single web form code behind is easily done. However not sure about the single user control deployment. Any help is appreciated.

A: it's a bit of a hack but you could move the code from the .ascx.cs file to the .ascx file and remove the inherits attribute. Asp.net first checks the referenced class in the inherit attribute. So I think this should allow you to update the web application without updating the .dll files. I didn't test this however, but I think it could be a viable option.

A: If you just deploy the updated user control (ascx) form and the relevant DLL, the only discernible delay will be the load time of the first hit after deployment, which you can do yourself with a browser refresh.


text:
Q: Batch * wildcard replacement I have a string base of the form *+*. I want to get everything before the +.
For example, if base=foo+bar, I want to get foo.
I've tried doing it with string replacement
set left=%base:+*=%

But this results in left storing foo+bar.
Interestingly, string replacement works for getting everything right of the +:
set right=%base:*+=%

Is +* being replaced by + (i.e. the wildcard is substituting for 0 characters)? Is there a better way to accomplish my task?
EDIT: I'm actually doing this in a for loop. Therefore, delayed expansion is on and (I think) I need to use !. Full code here:
for /d %%d in (*+*) do (
    set base=%%d
    set right=!base:*+=!
    set left=!base:+*=! ::this part doesn't work
    if !left:~-2!==!right:~-2! ( ::do only if last 2 chars match
        copy %%d mirrors
        copy %%d\%%d_montage.bmp mirrors
    )
)

EDIT 2: Comments in code above are only for readability here on SO. ::-style comments may not work correctly in for loops.

A: You may use this trick:
@echo off

set "base=foo+bar"

set "left=%base:+=" & set "right=%"

echo Left=%left%
echo Right=%right%

EDIT: If you want to use the method inside a for loop, use it this way:
@echo off
setlocal EnableDelayedExpansion

for %%a in ("one+two" "first+last") do (
   call :separate %%a
   echo Left=!left!
   echo Right=!right!
   echo/
)
goto :EOF

:separate
set "base=%~1"
set "left=%base:+=" & set "right=%"
exit /B

A: I've never had much luck with environment variable string replacement with wildcards, probably because of the right issue wOxxOm notes.
I'd tend to favor this method here:
for /f "tokens=1,2 delims=+" %a in ('echo %base%') do (
    set left=%a
    set right=%b
)

A: See http://ss64.com/nt/syntax-replace.html

To remove characters from the right hand side of a string is a two step process and requires the use of a CALL statement:

SET base=foo+bar
SET right=%base:*+=%
CALL SET left=%%base:+%right%=%%
echo %left%

A: you could substract the right side from the string:
@echo off
setlocal enabledelayedexpansion
set "base=foo+bar"
set left=%base:*+=%
set "right=!base:+%left%=!"
echo %left% / %right%

but I suggest another approach:
@echo off
set "base=foo+bar"
for /f "tokens=1,* delims=+" %%i in ("%base%") do (
  set "left=%%i"
  set "right=%%j"
)
echo %left% / %right%


text:
Q: Installing GCC on macOS Catalina I am on macOS Catalina and trying to install GCC by following the instructions here:
https://solarianprogrammer.com/2019/10/12/compiling-gcc-macos/
Everything seems to work fine until I try to configure. Then I get the following:
configure: error: cannot run C compiled programs.
If you meant to cross compile, use `--host'.
See `config.log' for more details

While trying to fix this I found the following:
MacOS "configure: error: cannot run C compiled programs"
However this answer requires going to the following directory:
/Library/Developer/CommandLineTools

The problem is I do not have CommandLineTools in /Library/Developer/ not even as a hidden file. Trying to fix this I found this
How to compile GCC on macOS Catalina?
but there is now answer here and I do not have nix and don't want to mess with it as it appears to not be very compatible with macOS Catalina. So the question is how can I run the configure?

A: Install GCC on MacOS
learn from above vedio,i use macOX 11.1, install gcc and g++ step:

*

*"brew install gcc", after that, check install success by: "brew info gcc".

*"cd /usr/local/bin"

*"ls | grep 'gcc'" should see the gcc version you install before, like: gcc-10 or g++-10.

*"ln -s gcc-10 gcc" make a symlink from your gcc version to gcc.

*close terminal, and open again, input "gcc -v", should see it use gcc now.

If still use clang:

*

*make sure you logout and login again.

*use "where gcc" or "which gcc" to check your gcc symlink create success.

*"echo $PATH", make sure "/usr/local/bin" show before "/usr/bin" on your PATH, if not, change it on your ~/.zshrc or ~/.bashrc

A: First you need to install the Command-Line tools.
$ xcode-select --install

Then you probably want to install the headers from a specific .pkg in Terminal:
$ open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

(yours is 10.15, so):
$ open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.15.pkg

After finishing the installation you should have the headers you need to compile with your GCC.

A: Probably not the elegant answer, but it worked. I was able to find the header files needed using $(xcrun --show-sdk-path) I then copied them all to /usr/local where the gcc location was expecting them to be. Now all works.


text:
Q: .htaccess rules blocking legitimate traffic Problem: legitimate traffic to my site is receiving "403 Forbidden" errors.
Example: A request from 199.16.156.125 to GET /robots.txt HTTP/1.1 from user-agent Twitterbot/1.0 should be allowed, but is denied.
Suspected culprit: my root .htaccess file implements the 5G Firewall from PerishablePress; additional deny rules from various WordPress security plugins; a couple of deny rules that I have hacked together myself; and a long list of banned CIDRs.
Sample code (truncated):
# ban all requests via HTTP/1.0
# UNLESS they are requests to either wp-cron or admin-ajax.
<ifModule mod_rewrite.c>
RewriteCond %{THE_REQUEST} !(HTTP/1\.1)$ [NC]
RewriteCond %{REQUEST_URI} !^(/wp-admin/admin-ajax\.php.*|/wp-cron\.php.*)
RewriteRule ^(.*)$ - [F,L]
</ifModule>

# 5G:[USER AGENTS]
<IfModule mod_setenvif.c>
 SetEnvIfNoCase User-Agent ^$ keep_out
 SetEnvIfNoCase User-Agent (casper|cmsworldmap|diavol|dotbot)   keep_out
 SetEnvIfNoCase User-Agent (flicky|ia_archiver|kmccrew) keep_out
 SetEnvIfNoCase User-Agent (libwww|planetwork|pycurl|skygrid)   keep_out
 SetEnvIfNoCase User-Agent  (SISTRIX|AhrefsBot|YandexBot|Baidu|SiteExplorer|MJ12bot|Browserlet|msnbot\-media) keep_out
 SetEnvIfNoCase User-Agent (Java|Wget|CPython|ruby|panscient\.com) keep_out
 <Limit GET POST PUT>
  Order Allow,Deny
  Allow from all
  Deny from env=keep_out
 </Limit>
</IfModule>

#allowed IP (example)
allow from 255.255.255.255

#banned networks
deny from 199.119.224.0/22
deny from 199.30.48.0/21
deny from 99.198.96.0/19

There's more to it than that, but I suspect the problem may be in the above sample code.
What have I tried: 1. edit .htaccess rules to attempt to resolve issue. 2. create 403 logger script to provide additional details about requests that receive a 403 response.  (The hypothesis was that the forbidden requests might include additional X-Forwarded-For headers that contain IP addresses from banned networks; however, it turned out that this hypothesis was not correct.) 3. bang head against desk.
EDIT
If the general consensus is that the posted snippet could not be causing the problem I'm describing, I will accept an answer that helps me to track down the actual cause of the problem through more effective troubleshooting.
UPDATE
I appreciate the community's input and thought I would provide an update.
Eventually,  I contacted my web host for help. After a little back-and-forth, I learned that my host had indeed banned Twitterbot from their network for being a resource hog, apparently by visiting sites running poorly optimized WordPress plugins.  So that specific result was not, in fact, an .htaccess issue after all.
However, I still have a client who can't access my site, gets 403 forbidden message instead: legitimate traffic is getting denied, as described above.  My host confirmed they are not blocking my client's IP address.  I still haven't found a resolution for this.  I have even listed his dedicated IP in an "allow" directive before my list of "deny" directives, and still he's denied.  I edited the code example above to demonstrate.

A: I realise this was posted a while ago and most likely resolved
RewriteCond %{REQUEST_URI} !^(/wp-admin/admin-ajax\.php.*|/wp-cron\.php.*)

is going to forbidden if not /wp-admin/admin-ajax.php or /wp-cron.php
therefore /robots.txt will fail as it falls within the catchment of NOT represented by the !


text:
Q: How do I create a named has_many and belongs_to association in Rails 4.2? I have a model named Comics. My overall goal is to allow every comic to have optional variants(has_many comics) and a single variant_of(belongs_to comic). When I add a variant_of, I expect the inverse variants field to also resemble the same relationship.
I started by creating a variant_of migration:
class AddVariantOfToComics < ActiveRecord::Migration
  def self.up
    add_column :comics, :variant_of, :integer
  end

  def self.down
    remove_column :comics, :variant_of, :integer
  end
end

It worked splendidly. Then I attempted to make a variants index, which is the aspect I am having trouble with:
class AddVariantsToComics < ActiveRecord::Migration
  def change
    add_index :comics, ['variant_of'], :name => 'variants'
  end
end

The comics model:
class Comic < ActiveRecord::Base
  has_many :variants, :class_name => "Comic", :foreign_key => 'variants',
  belongs_to :variant_of, :class_name => "Comic", :foreign_key => 'variant_of'

  ...
end

Can anyone tell me how to relate these fields? Is index the right way to do that or is my naming getting in the way?

A: The foreign key of the has_many association is supposed to be variant_of. Like:
has_many :variants, :class_name => "Comic", :foreign_key => 'variant_of'
And it is not supposed to have a comma after it. In your example it is: :foreign_key => 'variants', which is not a valid syntax.


text:
Q: How do I get my program to print the winners of a plurality election if there is a tie? (CS50 Pset3) I have to make a program which contains the function print_winner, which is supposed to find the candidate(s) with the most votes in an array of candidates and print their name(s). The candidate is a composite data type consisting of a string of the candidate's name as well as an int of their votes. Every time a vote goes toward a candidate, that candidate's number of votes increases by 1.
// Update vote totals given a new vote
bool vote(string name)
{
    for(int i=0; i<candidate_count; i++)
    {
        if(strcmp(name,candidates[i].name)==0)
        {
            candidates[i].votes ++;
            return true;
        }
    }
    return false;
}

I have no problem making a program with print_winner() where there can only be one candidate. The problem comes when I have to code for the possibility that two or more winning candidates have the same amount of votes, in which case I have to print all of their names
I start by creating an array of variable x which is made up of a string and an int, same as a candidate
 typedef struct
    {
        int votes;
        string name;
    }
    winner;

    winner x[candidate_count];

Then, I set all x variables in the array to have 0 votes (Writing this I think this step is unnecessary since the x variables don't have to have a value, let me know if I'm wrong).
 for(int i=0; i<candidate_count; i++)
    {
        x[i].votes=candidates[0].votes=0;
        x[i].name=candidates[0].name="None";
    }

After that, I iterate along the candidates, comparing each candidate to the first x in the array. If that candidate has more votes than x, then I plug the name and number of votes of that candidate into the first x in the array. If there is a candidate that has the same number of votes as the first x in the array, I use iteration along x to plug the values of that candidate into the next x. If there is a third candidate with the same number of votes, the same happens, but the valuesare plugged into the third x in the array. The way I've coded this I hope the first x in the array never has fewer votes than any other x in the array.
for(int i=0; i<candidate_count; i++)
    {
        {
            if(x[0].votes<candidates[i].votes)
            {
                x[0].votes=candidates[i].votes;
                x[0].name=candidates[i].name;
            }

            else if(x[0].votes==candidates[i].votes)
            {
                for(int j=0; j<candidate_count-1; j++)
                {
                    if(x[j].votes>x[j+1].votes)
                    {
                        x[j+1].votes=candidates[i].votes;
                        x[j+1].name=candidates[i].name;
                    }
                }
            }
        }
    }

Finally comes the printing part. I used another iteration along the x array, where I compare each x value(x[i]) the next x value(x[i+1]) in the array, and if they have the same number of votes and a different name, that means that I have different candidates who are both winners. Therefore, I print the name of x[i] and continue with the iteration. As soon as I run across an x[i] whose x[i+1] either has fewer votes or the same name(no two candidates can have the same name in this election), I print x[i] and break the loop.

    for(int i=0; i<candidate_count; i++)
    {
        if (x[i].votes==x[i+1].votes && !(strcmp(x[i].name,x[i+1].name)==0))
        {
            printf("%s\n",x[i].name);
        }
        printf("%s\n",x[i].name);
        break;
    }
    return;

But when I run the program with a tied election, it doesn't give the correct results:
$ ./plurality a b c
Number of voters: 6
Vote: a
Vote: a
Vote: a
Vote: b
Vote: b
Vote: b
Winner: b
What do I do?

A: Supposing everything else is good with your code at check50...
As specs of plurality, you shouldn't modify the code save the vote and print_winner functions

you should not modify anything else in plurality.c other than the
implementations of the vote and print_winner functions (and the
inclusion of additional header files, if you'd like).

so my suggestion is to erase the following and its consequences:
typedef struct
    {
        int votes;
        string name;
    }
    winner;

    winner x[candidate_count];

One working approach to the print_winner function is to make sure to (all inside of this function):

*

*Look among candidates for the one with the most votes, saving the definite winner inside a variable. It really doesn't matter if there's a tie.

*Print candidate with the most votes by calling the winner variable.

*Look for among the OTHER candidates for those who have equal votes, if so print them.

*Make sure not to reprint winners.
Note that my print winner function is like 20 lines long, so my suggestion is that you avoid complex or very long functions.


text:
Q: Separate up arrow lookback for local and global ZSH history Is it possible to...

*

*Step up local ZSH shell history (actions only happened in that prompt)

*Step up global ZSH history (shared history is on) - default what happens when you press UP arrow when shared history is on
... separately.
For example one might bind CTRL+up for global history, normal up for local history. At the same time it makes sense to use the global history for a backwards history search (i.e. CTRL+R).
This might speed up some shell operations, as some operations are specific to that shell window and you want to go back in them.

A: You can setup a special zle widget to show only local history items:
function only-local-history () {
        zle set-local-history 1
        zle up-history
        zle set-local-history 0
}
zle -N only-local-history

Assuming, that ↑ is bound to up-line-or-history (I think that is default), you can bind this widget to another key stroke, like CTRL+↑:
 bindkey "^[Oa" only-local-history

If this works is probably dependent of your terminal. Above line works in URxvt/Screen. With xterm you'll need
 bindkey "^[[1;5A" only-local-history

for CTRL+↑.
Another variant could be
function peek-history () {
        zle set-local-history
        zle up-history
        zle set-local-history
}
zle -N peek-history

so, if you have local history enabled, you can peek into the global one or vice versa.

A: @lumbic's answer worked for me only with a few changes:
setopt share_history

up-line-or-local-history() {
    zle set-local-history 1
    zle up-line-or-history
    zle set-local-history 0
}
zle -N up-line-or-local-history
down-line-or-local-history() {
    zle set-local-history 1
    zle down-line-or-history
    zle set-local-history 0
}
zle -N down-line-or-local-history

bindkey '^[OA' up-line-or-history     # Cursor up
bindkey '^[OB' down-line-or-history   # Cursor down
bindkey '^[[1;5A' up-line-or-local-history    # [CTRL] + Cursor up
bindkey '^[[1;5B' down-line-or-local-history  # [CTRL] + Cursor down

This code makes the global history the default, and uses CTRL-arrow for local history.
Note: I use zsh 5.0.2 together with oh-my-zsh.

A: Copy & Paste this to your .zshrc:
Cursors are using local history:
bindkey "${key[Up]}" up-line-or-local-history
bindkey "${key[Down]}" down-line-or-local-history

up-line-or-local-history() {
    zle set-local-history 1
    zle up-line-or-history
    zle set-local-history 0
}
zle -N up-line-or-local-history
down-line-or-local-history() {
    zle set-local-history 1
    zle down-line-or-history
    zle set-local-history 0
}
zle -N down-line-or-local-history

If you need also key bindings (CTRL + cursors) to step through the global history add also this to your .zshrc:
bindkey "^[[1;5A" up-line-or-history    # [CTRL] + Cursor up
bindkey "^[[1;5B" down-line-or-history  # [CTRL] + Cursor down

To make this work the option SHARE_HISTORY (see 16.2.4 History) needs to be enabled. Run setopt and check if "sharehistory" is listed. If not add setopt sharehistory to your .zshrc. Then one can use set-local-history as we did above. The documenation says:

By default, history movement commands visit the imported lines as well
  as the local lines, but you can toggle this on and off with the
  set-local-history zle binding. It is also possible to create a zle
  widget that will make some commands ignore imported commands, and some
  include them.

Note that by default global history is used (and all functions end with "zle set-local-history 0", i.e. local history is disabled). So pressing CTRL + R will search the global history by default (which makes sense in most cases).
This is quite similar to the solution by @mpy, but ready for copy & paste. It overwrites the cursor keys up and down. I used this mail list entry.
See also:

*

*http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html

*https://stackoverflow.com/questions/9502274/last-command-in-same-terminal/9518734?noredirect=1#comment15415094_9518734

A: Expanding on @lumbric's answer to preserve beginning-search functionality, which many zsh user may have by default. I tried wrapping up-line-or-beginning-search and down-line-or-beginning-search but this caused issues (see @Melebius's answer on this), so instead I'm redefining them and toggling the local history for only the underlying search functions.
Here is the behavior we see with this enabled:
↑ Step backwards through local history or beginning search
↓ Step forwards through local history or beginning search
Ctrl + ↑ Step backwards through global history or beginning search
Ctrl + ↓ Step forwards through global history or beginning search
Ctrl + r  Search global history
Put the following in $ZSH_CUSTOM/local_history_global_beginning_search.zsh or directly in your .zshrc
up-line-or-beginning-local-search() {
  if [[ $LBUFFER == *$'\n'* ]]; then
    zle up-line-or-history
    __searching=''
  elif [[ -n $PREBUFFER ]] &&
      zstyle -t ':zle:up-line-or-beginning-search' edit-buffer
  then
    zle push-line-or-edit
  else
    [[ $LASTWIDGET = $__searching ]] && CURSOR=$__savecursor
    __savecursor=$CURSOR
    __searching=$WIDGET
    zle set-local-history 1
    zle history-beginning-search-backward
    zle set-local-history 0
    zstyle -T ':zle:up-line-or-beginning-search' leave-cursor &&
        zle end-of-line
  fi
}
zle -N up-line-or-beginning-local-search

down-line-or-beginning-local-search() {
  if [[ ${+NUMERIC} -eq 0 &&
      ( $LASTWIDGET = $__searching || $RBUFFER != *$'\n'* ) ]]
  then
    [[ $LASTWIDGET = $__searching ]] && CURSOR=$__savecursor
    __searching=$WIDGET
    __savecursor=$CURSOR

    zle set-local-history 1
    if zle history-beginning-search-forward; then
      zle set-local-history 0
      [[ $RBUFFER = *$'\n'* ]] ||
        zstyle -T ':zle:down-line-or-beginning-search' leave-cursor &&
        zle end-of-line
      return
    fi
    zle set-local-history 0

    [[ $RBUFFER = *$'\n'* ]] || return
  fi
  __searching=''
  zle down-line-or-history
}
zle -N down-line-or-beginning-local-search

# Stepping through local history.
bindkey "${key[Up]}" up-line-or-beginning-local-search       # Cursor Up
bindkey "${key[Down]}" down-line-or-beginning-local-search   # Cursor Down

# Stepping through global history.
bindkey "^[[1;5A" up-line-or-beginning-search                # Ctrl + Cursor Up
bindkey "^[[1;5B" down-line-or-beginning-search              # Ctrl + Cursor Down

# This option both imports new commands from the history file, and also causes your
# typed commands to be appended to the history file (the latter is like specifying
# INC_APPEND_HISTORY, which should be turned off if this option is in effect).
setopt sharehistory

A: I've been trying the options listed in other answers here but I was not happy with them. The widgets1 up-history or up-line-or-history do not include beginning search and the widget1 up-line-or-beginning-search seems to not work well when altering local history preference while using it.2
So I came to the following settings. It enables Ctrl+arrows to browse the global history, Alt+arrows to browse the local history only (similar to Bash) and standalone arrows to use the smart beginning search (default in Oh My Zsh).
up-line-or-local-history() {
    zle set-local-history 1
    zle up-line-or-search
    zle set-local-history 0
}
zle -N up-line-or-local-history

down-line-or-local-history() {
    zle set-local-history 1
    zle down-line-or-search
    zle set-local-history 0
}
zle -N down-line-or-local-history

bindkey "${key[Up]}" up-line-or-beginning-search
bindkey "${key[Down]}" down-line-or-beginning-search
bindkey "^[[1;5A" up-line-or-search    # [CTRL] + Cursor up
bindkey "^[[1;5B" down-line-or-search  # [CTRL] + Cursor down
bindkey "^[[1;3A" up-line-or-local-history    # [ALT] + Cursor up
bindkey "^[[1;3B" down-line-or-local-history  # [ALT] + Cursor up

1 Their down counterparts are meant implicitly, too.
2 The beginning used to search is redefined after altering local history preference, so the whole first found command is used as the beginning to be searched for in the second search.

A: Based on the various answers here, I was able to make a condenced version:
function up-line-or-history() {
    zle set-local-history 1
    zle .up-line-or-history
    zle set-local-history 0
}

function down-line-or-history() {
    zle set-local-history 1
    zle .down-line-or-history
    zle set-local-history 0
}

# Overwrite existing {up,down}-line-or-history widgets with the functions above.
zle -N up-line-or-history
zle -N down-line-or-history

This version will overwrite the existing up-line-or-history and down-line-or-history widgets with new user-defined widgets. This widget enables the local history and will then call the original widgets, which are available under the .-prefixed names. See the zle widget documentation for details.
This means that you get to keep any existing keybindings. You can therefore avoid having to figure out what the escape sequence is for typing an up-arrow in your current terminal.

A: autoload -U up-line-or-beginning-search
autoload -U down-line-or-beginning-search
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey "^[[A" up-line-or-beginning-search # Up
bindkey "^[[B" down-line-or-beginning-search # Down

Above answer worked for me.
Reference: https://coderwall.com/p/jpj_6q/zsh-better-history-searching-with-arrow-keys


text:
Q: TinyMCE keeps adding default video width and height I've got a video pasted into tinymce but I need to stop it defining the dimensions automatically as I'd like to control them via css instead.
So I paste in:
<video id="sampleMovie" preload="" controls="controls" poster="/video/video.png"><source src="/video/video.mp4" type="video/mp4" /></video>

But then tinymce automatically pastes in annoying default dimensions for me and it ends up being:
<video width="300" height="150" id="sampleMovie" preload="" controls="controls" poster="/video/video.png">
<source src="/video/video.mp4" type="video/mp4" /></video>

Which I really, really don't want. Is there a way to stop this?
In my init code I've already got:
relative_urls: false,
cleanup: false,
verify_html : false,

A: TinyMCE 4.0.11 - Automatically remove width and height attributes from img elements inserted via the img plugin
setup: function (editor) {
    editor.on('init', function(args) {
        editor = args.target;

        editor.on('NodeChange', function(e) {
            if (e && e.element.nodeName.toLowerCase() == 'img') {
                tinyMCE.DOM.setAttribs(e.element, {'width': null, 'height': null});
            }
        });
    }
}

Ref: https://gist.github.com/simshaun/7592631

A: I'm sure this is not THE answer but I had a similar dilemma with <IFRAME>.  The workaround I settled with is disabling the width/height attribute as a valid attribute by doing so:
extended_valid_elements : "iframe[style|src|class]"

A: Maybe this is not exactly an answer to this question, but I only noticed after migrating to TinyMCE 6 that a height attribute with a default value of 150 was automatically added when it was missing. You can prevent the default by adding height="".


text:
Q: Spring Boot + JavaFx autowiring doesn't work Yesterday I tried to create project connecting Spring Boot and JavaFX. I was basing on http://www.greggbolinger.com/let-spring-be-your-javafx-controller-factory/
So I created a project and when I run application spring context is created and JavaFx application is run. But the problem is when I try to create some beans e.g using @Repository annotation. When I am autowiring then value is null.
CarGarageApplication.java
package com.car.garage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.car.garage.dao.UsersRepository;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

@SpringBootApplication
@ComponentScan
@EnableJpaRepositories("com.car.garage.dao")
public class CarGarageApplication extends Application {

    private ConfigurableApplicationContext mainContext;
    private Parent rootNode;

    @Autowired
    UsersRepository usersRepository;

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void init() throws Exception {
        mainContext = SpringApplication.run(CarGarageApplication.class);
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/WelcomePage.fxml"));
        loader.setControllerFactory(mainContext::getBean);
        rootNode = loader.load();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setScene(new Scene(rootNode));
        primaryStage.setResizable(false);
        primaryStage.show();
        System.out.println(usersRepository);
    }

    @Override
    public void stop() throws Exception {
        mainContext.close();
    }
}

UsersRepository.java
package com.car.garage.dao;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.car.garage.model.User;

@Repository
public interface UsersRepository extends CrudRepository<User, Long> {

}

User.java
package com.car.garage.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue
    private Long id;

    private String username;
    private String password;

    public User(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

EDIT:
mainContext.getBean(UsersRepository.class) return correct bean instance of UsersRepository but why @Autowired doesn't work

A: We should follow below approach to autowire repository class. because It's mandatory to have SPRING STEREOTYPES class(@Component, @Service like that) from where you are autowiring the another class
@Component
 public class Anotherclass{

     @Autowired
     private UsersRepository usersRepository;
}


text:
Q: C++ cast to array of a smaller size Here's an interesting question about the various quirks of the C++ language. I have a pair of functions, which are supposed to fill an array of points with the corners of a rectangle. There are two overloads for it: one takes a Point[5], the other takes a Point[4]. The 5-point version refers to a closed polygon, whereas the 4-point version is when you just want the 4 corners, period.
Obviously there's some duplication of work here, so I'd like to be able to use the 4-point version to populate the first 4 points of the 5-point version, so I'm not duplicating that code. (Not that it's much to duplicate, but I have terrible allergic reactions whenever I copy and paste code, and I'd like to avoid that.)
The thing is, C++ doesn't seem to care for the idea of converting a T[m] to a T[n] where n < m. static_cast seems to think the types are incompatible for some reason. reinterpret_cast handles it fine, of course, but is a dangerous animal that, as a general rule, is better to avoid if at all possible.
So my question is: is there a type-safe way of casting an array of one size to an array of a smaller size where the array type is the same?
[Edit] Code, yes. I should have mentioned that the parameter is actually a reference to an array, not simply a pointer, so the compiler is aware of the type difference.
void RectToPointArray(const degRect& rect, degPoint(&points)[4])
{
    points[0].lat = rect.nw.lat; points[0].lon = rect.nw.lon;
    points[1].lat = rect.nw.lat; points[1].lon = rect.se.lon;
    points[2].lat = rect.se.lat; points[2].lon = rect.se.lon;
    points[3].lat = rect.se.lat; points[3].lon = rect.nw.lon;
}
void RectToPointArray(const degRect& rect, degPoint(&points)[5])
{
    // I would like to use a more type-safe check here if possible:
    RectToPointArray(rect, reinterpret_cast<degPoint(&)[4]> (points));
    points[4].lat = rect.nw.lat; points[4].lon = rect.nw.lon;
}

[Edit2] The point of passing an array-by-reference is so that we can be at least vaguely sure that the caller is passing in a correct "out parameter".

A: I don't think it's a good idea to do this by overloading. The name of the function doesn't tell the caller whether it's going to fill an open array or not. And what if the caller has only a pointer and wants to fill coordinates (let's say he wants to fill multiple rectangles to be part of a bigger array at different offsets)?
I would do this by two functions, and let them take pointers. The size isn't part of the pointer's type
void fillOpenRect(degRect const& rect, degPoint *p) {
  ...
}

void fillClosedRect(degRect const& rect, degPoint *p) {
  fillOpenRect(rect, p); p[4] = p[0];
}

I don't see what's wrong with this. Your reinterpret-cast should work fine in practice (i don't see what could go wrong - both alignment and representation will be correct, so the merely formal undefinedness won't carry out to reality here, i think), but as i said above i think there's no good reason to make these functions take the arrays by reference.

If you want to do it generically, you can write it by output iterators
template<typename OutputIterator>
OutputIterator fillOpenRect(degRect const& rect, OutputIterator out) {
  typedef typename iterator_traits<OutputIterator>::value_type value_type;
  value_type pt[] = {
    { rect.nw.lat, rect.nw.lon },
    { rect.nw.lat, rect.se.lon },
    { rect.se.lat, rect.se.lon },
    { rect.se.lat, rect.nw.lon }
  };
  for(int i = 0; i < 4; i++)
    *out++ = pt[i];
  return out;
}

template<typename OutputIterator>
OutputIterator fillClosedRect(degRect const& rect, OutputIterator out) {
  typedef typename iterator_traits<OutputIterator>::value_type value_type;
  out = fillOpenRect(rect, out);

  value_type p1 = { rect.nw.lat, rect.nw.lon };
  *out++ = p1;
  return out;
}

You can then use it with vectors and also with arrays, whatever you prefer most.
std::vector<degPoint> points;
fillClosedRect(someRect, std::back_inserter(points));

degPoint points[5];
fillClosedRect(someRect, points);

If you want to write safer code, you can use the vector way with back-inserters, and if you work with lower level code, you can use a pointer as output iterator.

A: I would use std::vector or (this is really bad and should not be used) in some extreme cases you can even use plain arrays via pointer like Point* and then you shouldn't have such "casting" troubles.

A: Why don't you just pass a standard pointer, instead of a sized one, like this
void RectToPointArray(const degRect& rect, degPoint * points ) ;

A: I don't think your framing/thinking of the problem is correct.  You don't generally need to concretely type an object that has 4 vertices vs an object that has 5.
But if you MUST type it, then you can use structs to concretely define the types instead.
struct Coord
{
    float lat, long ;
} ;

Then
struct Rectangle
{
    Coord points[ 4 ] ;
} ;

struct Pentagon
{
    Coord points[ 5 ] ;
} ;

Then,
// 4 pt version
void RectToPointArray(const degRect& rect, const Rectangle& rectangle ) ;

// 5 pt version
void RectToPointArray(const degRect& rect, const Pentagon& pent ) ;

I think this solution is a bit extreme however, and a std::vector<Coord> that you check its size (to be either 4 or 5) as expected with asserts, would do just fine.

A: I guess you could use function template specialization, like this (simplified example where first argument was ignored and function name was replaced by f(), etc.):
#include <iostream>
using namespace std;

class X
{
};

template<int sz, int n>
int f(X (&x)[sz])
{
    cout<<"process "<<n<<" entries in a "<<sz<<"-dimensional array"<<endl;
    int partial_result=f<sz,n-1>(x);
    cout<<"process last entry..."<<endl;

    return n;
}
//template specialization for sz=5 and n=4 (number of entries to process)
template<>
int f<5,4>(X (&x)[5])
{
    cout<<"process only the first "<<4<<" entries here..."<<endl;

    return 4;
}

int main(void)
{
    X u[5];

    int res=f<5,5>(u);
    return 0;
}

Of course you would have to take care of other (potentially dangerous) special cases like n={0,1,2,3} and you're probably better off using unsigned int's instead of ints.

A:
So my question is: is there a
  type-safe way of casting an array of
  one size to an array of a smaller size
  where the array type is the same?

No. I don't think the language allows you to do this at all: consider casting int[10] to int[5]. You can always get a pointer to it, however, but we can't 'trick' the compiler into thinking a fixed-sized has a different number of dimensions.
If you're not going to use std::vector or some other container which can properly identify the number of points inside at runtime and do this all conveniently in one function instead of two function overloads which get called based on the number of elements, rather than trying to do crazy casts, consider this at least as an improvement:
void RectToPointArray(const degRect& rect, degPoint* points, unsigned int size);

If you're set on working with arrays, you can still define a generic function like this:
template <class T, size_t N>
std::size_t array_size(const T(&/*array*/)[N])
{
    return N;
}

... and use that when calling RectToPointArray to pass the argument for 'size'. Then you have a size you can determine at runtime and it's easy enough to work with size - 1, or more appropriate for this case, just put a simple if statement to check if there are 5 elements or 4.
Later if you change your mind and use std::vector, Boost.Array, etc. you can still use this same old function without modifying it. It only requires that the data is contiguous and mutable. You can get fancy with this and apply very generic solutions that, say, only require forward iterators. Yet I don't think this problem is complicated enough to warrant such a solution: it'd be like using a cannon to kill a fly; fly swatter is okay.
If you're really set on the solution you have, then it's easy enough to do this:
template <size_t N>
void RectToPointArray(const degRect& rect, degPoint(&points)[N])
{
    assert(N >= 4 && "points requires at least 4 elements!");
    points[0].lat = rect.nw.lat; points[0].lon = rect.nw.lon;
    points[1].lat = rect.nw.lat; points[1].lon = rect.se.lon;
    points[2].lat = rect.se.lat; points[2].lon = rect.se.lon;
    points[3].lat = rect.se.lat; points[3].lon = rect.nw.lon;

    if (N >= 5)
        points[4].lat = rect.nw.lat; points[4].lon = rect.nw.lon;
}

Yeah, there is one unnecessary runtime check but trying to do it at compile time is probably analogous to taking things out of your glove compartment in an attempt to increase your car's fuel efficiency. With N being a compile-time constant expression, the compiler is likely to recognize that the condition is always false when N < 5 and just eliminate that whole section of code.


text:
Q: Async scaling of images in electron I am populating a list (in my electron app), each item showing a hi-res image from disk.
Now, since the list is getting longer, I am running into performance issues: Electron is occupying a whole lot of RAM, so I guess I will need to render thumbnails somehow.
Electron provides an API for downscaling images.
But this is a synchronous process and so downscaling on render of the UI is not an option, since it would freeze the UI.
So it would need to be done when new images are added by the user.
However, I don't like this idea much, since I would need to take care of managing those additional thumbnail image files.
What is a good solution here? My idea was to run a http server (express) which takes care of delivering downscaled version of the images, similar to this API:
http://localhost:30948/imageshrinker?image=imagedir/myimg.jpg&size=medium
This seems like a whole lot to implement (especially because I think I would need to run this in another worker window right?) and I didn't find any library which I could use.
Any ideas how to best approach this issue?

A: How about using nativeImage.createThumbnailFromPath? It returns Promise, so you could display some loading/dummy/shimmer image on init and show thumbnail when particular promise resolves. With proper cache management (like render Chunks known for ex. from facebook wall) loading even 100 000 images should be a breeze.
Other than that, when I was faced with similar issue, I made some research and for me the best and (actually) the fastest library was Sharp, I was loading JPG images from Hasselblad that has more than 100MB in size and creating a set of thumbnails for Sharp was like 0.4s. This is a bit of troublesome, because you'll have to implement thumbnail management by your own, but in long run you'll benefit from that. In your case I would follow an algorithm such as:

*

*On open file

*Create md5 checksum

*Compare md5 with database entry, if entry exist jump to 7

*Open image within Sharp constructor, resize to desired value

*Save to File within temp/thumbnails folder
  sharp(input)
  .resize(200, 300)
  .toFile(`thumbnails/${md5}.png`)
  .then(() => {
    // update list item with proper image source
  });

*Write database entry with thumbnail source path under original md5 checksum

*Insert thumbnail as an image source

*If Image.onError rises which means thumbnail file does not exists, jump to 4
So you wouldn't have to generate thumbnails everytime someone opens an app, just remember to clean thumbnails directory from times to times, or just dump the idea of keeping thumbnails local, just keep them in-memory, display on request and check if performance is good- might be, like:
sharp(input)
  .resize({ width: 100, height: 100 })
  .toBuffer()
  .then(data => {
    tempImages[itemID] = nativeImage.createFromBuffer(data, {width: 100, height: 100})
  });