text:
Q: Could not create a share with SAP UI5 Repository I'd like to share my SAPUI5 project to my ABAP Backend.
But I can't connect to the backend.
Ii I right-click on the project -> Team -> Share Project... I can see the Popup. Then I choose SAPUI5 ABAP Repository and click next. Nothing happens!
Sometimes I've got error "Null pointer exception", but sometimes it does nothing.
Please have a look at the logfile.
Does anyone know a workaround ? How can I create a share manually?
Kind regards - Sven

!ENTRY org.eclipse.jface 4 2 2020-06-03 07:22:22.227
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface".
!STACK 0
java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.sap.ide.ui5.team.ui.internal.AfrRepositoryProviderConfigurationWizard$5.invoke(AfrRepositoryProviderConfigurationWizard.java:409)
    at com.sun.proxy.$Proxy22.canSupportCTSProject(Unknown Source)
    at com.sap.adt.transport.ui.internal.widgets.TransportSelectionComposite.isCTSProjectSupported(TransportSelectionComposite.java:1264)
    at com.sap.adt.transport.ui.internal.widgets.TransportSelectionComposite.createControl(TransportSelectionComposite.java:1215)
    at com.sap.adt.transport.ui.internal.widgets.TransportSelectionComposite.<init>(TransportSelectionComposite.java:177)
    at com.sap.adt.transport.ui.internal.widgets.TransportSelectionWizardPage$1.<init>(TransportSelectionWizardPage.java:81)
    at com.sap.adt.transport.ui.internal.widgets.TransportSelectionWizardPage.createControl(TransportSelectionWizardPage.java:81)
    at org.eclipse.jface.wizard.Wizard.createPageControls(Wizard.java:178)
    at com.sap.ide.ui5.team.ui.internal.AfrRepositoryProviderConfigurationWizard.createPageControls(AfrRepositoryProviderConfigurationWizard.java:143)
    at org.eclipse.jface.wizard.WizardDialog.createPageControls(WizardDialog.java:743)
    at org.eclipse.jface.wizard.WizardDialog.setWizard(WizardDialog.java:1181)
    at org.eclipse.jface.wizard.WizardDialog.updateForPage(WizardDialog.java:1234)
    at org.eclipse.jface.wizard.WizardDialog.lambda$3(WizardDialog.java:1222)
    at org.eclipse.jface.wizard.WizardDialog$$Lambda$612/155678765.run(Unknown Source)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:72)
    at org.eclipse.jface.wizard.WizardDialog.showPage(WizardDialog.java:1222)
    at org.eclipse.team.internal.ui.wizards.ConfigureProjectWizardMainPage.lambda$1(ConfigureProjectWizardMainPage.java:167)
    at org.eclipse.team.internal.ui.wizards.ConfigureProjectWizardMainPage$$Lambda$597/1616936875.doubleClick(Unknown Source)
    at org.eclipse.jface.viewers.StructuredViewer$1.run(StructuredViewer.java:782)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45)
    at org.eclipse.ui.internal.JFaceUtil$$Lambda$20/1422262786.run(Unknown Source)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:174)
    at org.eclipse.jface.viewers.StructuredViewer.fireDoubleClick(StructuredViewer.java:779)
    at org.eclipse.jface.viewers.StructuredViewer.handleDoubleSelect(StructuredViewer.java:1100)
    at org.eclipse.jface.viewers.StructuredViewer$4.widgetDefaultSelected(StructuredViewer.java:1213)
    at org.eclipse.jface.util.OpenStrategy.fireDefaultSelectionEvent(OpenStrategy.java:251)
    at org.eclipse.jface.util.OpenStrategy.access$0(OpenStrategy.java:249)
    at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java:308)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4207)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1037)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4024)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3624)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:823)
    at org.eclipse.jface.window.Window.open(Window.java:799)
    at org.eclipse.team.internal.ui.wizards.ConfigureProjectWizard.openWizard(ConfigureProjectWizard.java:229)
    at org.eclipse.team.internal.ui.wizards.ConfigureProjectWizard.shareProjects(ConfigureProjectWizard.java:130)
    at org.eclipse.team.internal.ui.actions.ConfigureProjectAction.lambda$0(ConfigureProjectAction.java:40)
    at org.eclipse.team.internal.ui.actions.ConfigureProjectAction$$Lambda$575/1253482877.run(Unknown Source)
    at org.eclipse.team.internal.ui.actions.TeamAction.lambda$1(TeamAction.java:306)
    at org.eclipse.team.internal.ui.actions.TeamAction$$Lambda$576/137209289.run(Unknown Source)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:72)
    at org.eclipse.team.internal.ui.actions.TeamAction.run(TeamAction.java:304)
    at org.eclipse.team.internal.ui.actions.ConfigureProjectAction.execute(ConfigureProjectAction.java:35)
    at org.eclipse.team.internal.ui.actions.TeamAction.run(TeamAction.java:567)
    at org.eclipse.team.internal.ui.actions.TeamAction.runWithEvent(TeamAction.java:603)
    at org.eclipse.ui.internal.PluginAction.runWithEvent(PluginAction.java:229)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:579)
    at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:413)
    at org.eclipse.jface.action.ActionContributionItem$$Lambda$287/1231956957.handleEvent(Unknown Source)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4207)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1037)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4024)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3624)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1158)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1047)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:155)
    at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:658)
    at org.eclipse.ui.internal.Workbench$$Lambda$32/451801229.run(Unknown Source)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:557)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:154)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:150)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:203)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:137)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:107)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:401)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:255)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:657)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:594)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1447)


text:
Q: How to print the before lines of search keyword with out using grep in a gz file? How to print the lines before a search keyword without using grep in a .gz file?
ID:342N000390AAAAAAAA   07/14/15 10:26      (MV90    )
         * Register Data Imported
         * Warning - No Profile Data
     07/14/15 10:24  05/13/15 08:16       15    1   5956

I want to search the No Profile Keyword and print the ID NUMBER THAT IS 342N000390AAAAAAAA and necessarily "No Profile" won't come in third line; it may come in any line. My Operating system is HP-UX, so many commands are not eligible.

A: You could work with awk instead:
gzcat file.gz | awk '/No Profile Data/{printf "%s\n%s\n%s\n", b, a, $0} {b=a;a=$0}'

*

*gzcat (or zcat on Linux) prints the content of the gzipped file to the standard output

*awk then searches for the string "No Profile Data" and prints the two previous lines

A: Edited
New approach: removing line breaks.
Assuming that you have only one ID per gzipped file, you can try the following:
gunzip -c file.gz | sed -e ':a;N;$!ba;s/\n/ /g' -e '/^[[:space:]]/d' -e 's/^ID:\([[:alnum:]]*\).*Warning - No Profile Data.*/\1/' -e '/^ID:/d'

*

*gunzip -c extracts the file to stdout

*sed collapses all lines into one, then removes all lines not starting with ID:, then extracts the ID from matching files, then removes the ID: line for non-matching files, so that it displays either the ID or nothing.

Credits due to https://stackoverflow.com/a/1252191/5148242 and https://unix.stackexchange.com/a/218094/124507 @DarkHeart
Original
grep is still the appropriate option, but for the sake of the exercise, you can use sed for the finding, and paste for the -B2 part:
zcat nogrep.gz | paste - - - | sed -e '/^[[:space:]]/d' -e 's/^ID:\([[:alnum:]]*\).*Warning - No Profile Data/\1/' -e '/^ID:/d'

*

*paste joins each group of 3 lines

*sed removes all lines not starting with ID:, then extracts the ID from matching files, then removes the ID: line for non-matching files, so that it displays either the ID or nothing.

A: (hopefully) the final product

find . -name \*.gz -type f -exec   gzcat {} +  |
sed -ne'/^ *ID:/h;/No Profile/!d;x' \
    -e's/^ *ID:\([^ ]*\).*/\1/p'

So that will recursively find all of the regular files rooted in the current directory with filenames which match the pattern *.gz and call zcat as few times as is necessary to iteratively uncompress every one in a single stream to sed's stdin.
sed will scan its input for lines which are headed with the string *ID:. It will hold a copy if found, and next look for No Profile while deleting all lines which don't match. When found sed will swap into hold space and try to trim an ^ *ID: line to only the portion falling between the first : and next occurring <space>. If successful, sed prints the results.
As @DarkHeart points out you will most likely have to alter the zcat command name to gzcat on an HPUX system, though.

variations

This would be all you need to search a single file for line pairs occurring immediately previous to a match for the string No Profile:
gzip -d <file.gz |
sed -e'1N;$!N;/\n.*No Profile/P;D'

That will just scan input three lines at a time. Each line is separated by a \newline in pattern space. As each New line is pulled in, the oldest is Deleted. If the regexp \n.*No Profile is ever matched in pattern space (as it will be when it is the newest line in pattern space, and the following cycle when it is the second to newest), the oldest line is printed. And so you get the two lines occurring before No Profile. If you want to also print the line on which it is found...
gzip -d <file.gz |
sed -e'1N;$!N;/No Profile/P;D'

with find:

find . -name \*.gz -type f -exec zcat {} + |
sed -e'1N;$!N;/No Profile/P;D'

You can swap the . there for the name of some directory if you like. You can also add the \n.*No Profile bit to avoid printing the matching line. That command will recurse into all child directories of .. If that is not to your liking:
find . \! -name . -prune -name \*.gz  \
          -type f -exec zcat {} +     |
sed -e'1N;$!N;/No Profile/P;D'

If you are specifically looking for the leading ID field and only if can be found two lines prior to a match for No Profile you can do:
find . -name \*.gz -type f -exec zcat {} + |
sed -ne'/^ID/!D;/\n/!N;N' \
     -e's/ .*\n.*\n.*No Profile.*//p;D'

...which would print only the leading ID field as it might occur in any/all of the *.gz files find calls zcat to print and only if ID definitely occurs two lines before a No Profile match.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to run exe with output via cmd like Linux Running a program in Windows by inputting this in cmd.exe.
./myapp.exe

Then the program looks like running in another thread, the different thread from cmd. How to make the program run via cmd exactly like Linux style. When the cmd terminal destroyed, the running program also terminated. While the program is running, the cmd will capture the std output on time.

A:
Then the program looks like running in another thread, the different thread from cmd.

Well, the program is running in a separate process, which has its own threads.
On Windows, there are two main types of programs: console and windowed.
Console programs are typically text-mode applications that print text.  These already behave the way you want: you run the program, the shell (cmd.exe) waits for it finish before returning you to an interactive prompt.  If the program is long-running, forcibly terminating cmd.exe will terminate the program.
Windowed programs are typically applications that have a graphical user interface (e.g. notepad.exe, explorer.exe, firefox.exe).  They don't behave the way you want: when you run them through cmd.exe, cmd.exe does not wait for them and returns you to an interactive prompt immediately.  The executed program runs independently of cmd.exe, and terminating one has no effect on the other.
Note that console programs can have windows and that windowed programs can have console output.  So what makes a program "console" or "windowed"?
Part of the .exe specifies whether it should be run with the "console" subsystem or with the "windows" subsystem. This is configured (often implicitly) when the program was built.  This can be changed after the program was built; editbin.exe (included with Visual Studio) can modify the .exe file and change which subsystem the program should use.
If you just want to see stdout and stderr output, you don't need to modify the .exe file.  Normally windowed applications don't send that output anywhere, but you can change that with pipes/redirects.  For example, you can run:
SomeWindowedApplication.exe > output.txt

or, if you have cat (or an equivalent) available:
SomeWindowedApplication.exe | cat

Doing so also will cause cmd.exe to wait for the program to terminate before returning you to the interactive prompt.  Note that this does not have the termination behavior you want (i.e., terminating cmd.exe in the last example will terminate cat.exe, not ShowWindowedApplication.exe).
Also see:

*

*https://stackoverflow.com/a/2424210/179715

*https://stackoverflow.com/a/2628025/179715


text:
Q: Finding people to do usability testing Does anyone have recommendations/experience of how to find people willing to do usability testing of web based apps?  I suspect I may need people who might actually be potential users, because mine is a commercial/vertical app which contains some processes and terminology which may not mean much to the average joe/jane.
I have a fairly robust prototype of a web app which is designed for people in Sales Management and before I go too much further with it I want to try a couple of key pieces out on some live users.  I have a few friendly faces I can turn to (and have already), but I really want strangers who will not feel they need to be nice to me about it.
I'm fine designing the usability tests themselves, it is finding the guinea-pigs that is proving difficult.

A: I've used this service a couple times and have been impressed with the quality of the feedback they provide.
usertesting.com

A: Don't Make Me Think has the exact chapter you would be interested in. Basically, you should set up your test in such a way that it's not about being nice or not, but it's about finding out whether the user can use it or not. This way you can use all your relatives or friends you want and know.
In a nutshell: set up a desk with a computer that has access to your app, get two chairs, a notepad and a pencil. The book mentions a video link to your co-workers, but let's skip that. You get your tester and place her in front of the computer, while you sit beside her with notepad and pencil at the ready. Be specific about that for the sake of this test, it's technically impossible that she would do something wrong, because that's what you are interested in.
Ask her then to do some specific tasks; You present her with some kind of state in the application, and ask her to do something. Example: "If you would want to do a new entry, how would you go about doing it". Ask her to describe what she's thinking, her train of thought; "I would seek for some kind of 'add' or '+' labeled button, let's see if I can find it. They're usually underneath the lists", etc. Make notes of the subtleties of her gestures and faces, like if she hunts with the cursor for something, or if she's grimacing in frustration.
If she can't find that add button quickly enough, there's a usability problem.
But really, buy the book. It's a great read, worth every penny.

A: Do you have a list of local companies who could be potential customers for your application?  This would be a good place to look; you can simultaneously get users for user testing and make good contacts.

A: Take yourself to Starbucks and put a sign on the back of your laptop which says "Ask me for a Free Coffee" make sure you use some screen recording software like Silverback to record the session for later.

A: I read this a few days ago and it might help:
http://www.joelonsoftware.com/uibook/fog0000000249.html

A: Does your organization have a Sales team that will allow you to borrow appropriate users? I think that would be a good start for Alpha testing of the UI. After that, perhaps your customer can use the Beta UI for further testing.

A: Believe it or not an ad in Craig's List works for us. Simply offer a reward, we use $50 prepaid debit cards, and you can usually get 10 - 20 people per ad.

A: see useit.com - there are several levels of usability testing, and it is obviously critical to recruit users that are representative of your target market

A: You could also check out uTest.com, a software testing services that relies on "crowdsourcing" the testing process. While more on the side of functional and technical testing, I'm sure you could negotiate a test project more focused on usability testing.


text:
Q: bash: change names of multiple filles within the workdir I have number of files
mol0.pdb
mol1.pdb
mol2.pdb
...
mol888.pdb

I need to rename this files changing the number +1 for each file in order that it could became like:
mol1.pdb
mol2.pdb
mol3.pdb
...
mol889.pdb

Could you suggest me some simple solution using bash terminal without possibility to make a script each time and run a loop:
for file in *.pdb
do
  # some command to change the number e.g. using i conter with mv
done

A: list=( mol*.pdb )
while IFS= read -r n; do
  mv "mol$n.pdb" "mol$((n + 1)).pdb"
done < <( printf '%s\n' "${list[@]}" | sed 's/mol\(.*\)\.pdb/\1/' | sort -nr )

sort -rn is here to sort the list of numbers in reverse order such that renaming a file never overwrites another.

A: here you go:
#!/bin/env bash

for file in *.pdb
do
    mv $file "${file%%[[:digit:]]*}$((${file//[!0-9]/}+1))".pdb;
done

first pattern remove everything with digits and beyond so we have "file123" becomes "file" now get the file name again and remove the words replacing them with nothing, getting the number, and sum 1, and last we add the extension. Just move one filename to another, and we are done.

A: Another approach; if there are a lot of files this might be a little faster.
EDITED
This line was broken:
$: # lst=(file*.xmp); # this is the original assignment that mis-orders the filenames

Changing it to this one should work, but gains a bit less less over Renaud's solution, which is probably easier for some to read. YMMV.
$:  mapfile -t lst < <( printf "%s\n" file*.xmp | sort -n -k1.5,1 )
$: ndx=${#lst[@]};
$: while [[ -n "${lst[--ndx]}" ]] && ((ndx>=0)); do echo mv "${lst[ndx]}" "newDir/file$((ndx+1)).xmp"; done
mv file9.xmp newDir/file10.xmp
mv file8.xmp newDir/file9.xmp
mv file7.xmp newDir/file8.xmp
mv file6.xmp newDir/file7.xmp
mv file5.xmp newDir/file6.xmp
mv file4.xmp newDir/file5.xmp
mv file3.xmp newDir/file4.xmp
mv file2.xmp newDir/file3.xmp
mv file1.xmp newDir/file2.xmp
mv file0.xmp newDir/file1.xmp

Falls apart if there are any gaps in your initial numbering, though.


text:
Q: how is the rank of a skew map is even ? In the book of Linear Algebra by Greub, at page 230, it is claimed that

More general, it will now be shown that the rank of a skew
  transformation is always even. Since every skew mapping is normal (see
  sec. S.5) the image space is the orthogonal complement of the kernel.
  Consequently, the induced transformation $\psi_1 : Im(\psi) \to
 Im(\psi)$ is regular. Since $\psi_1$ is again skew, it follows that
  the dimension of $Im(\psi)$ must be even. It follows from this result
  that the rank of a skew-symmetric matrix is always even.

However, I cannot understand how does the fact that the dimension of $im(\psi)$ should be even follow from his argument.
Note that, I have seen this answer, but if works on a complex space, and I'm particularly interested in understanding the Greub's argument.

A: While Greub is not as determinant-phobic as Axler, my impression is that he also would rather not resort to a determinantal argument if possible. What he had in mind probably goes like this: as $\psi_1^\ast\psi_1$ is self-adjoint, it has an eigenpair $(\lambda,u)$. Let $v=\psi_1(u)$. Since $\psi_1$ is skew and regular, we have $u\perp v\ne0$. Yet $\psi_1(v)=-\lambda u$ and $\psi_1^\ast\psi_1(v)=\lambda v$. Therefore $u$ and $v$ are two mutually orthogonal eigenvectors of $\psi_1^\ast\psi_1$ and they also span a two-dimensional invariant subspace of $\psi_1$. Proceed recursively, we see that $Im(\psi_1)$ is a direct sum of two-dimensional invariant subspaces, each spanned by two eigenvectors of $\psi_1^\ast\psi_1$. Hence it is even-dimensional.

A: A skew-symmetric linear transformation on an odd-dimensional space has determinant zero and is therefore not regular. So since $\psi_1 \colon \operatorname{Im}(\psi) \to \operatorname{Im}(\psi)$ is skew-symmetric and regular, the space $\operatorname{Im}(\psi)$ must be even-dimensional.


text:
Q: MyBatis hits Cannot Assign Requested Address Socket Exception at high volume with Pooled connection I am using MyBatis to pull data from database into a cache as needed.  At high volumes of message traffic, I start to see the following exception:
 ### Error querying database. Cause: org.postgresql.util.PSQLException: Connection to <my-database>:<my-port> refused. Check that the hostname and port are correct and that the postmaster is
 accepting TCP/IP connections.
 ### The error may exist in mappers/<my-mapper>.xml
 ### The error may involve <my-mapper>.getById
 ### The error occurred while executing a query
 ### Cause: org.postgresql.util.PSQLException: Connection to <my-database>:<my-port> refused. Check that
 the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:122)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:113)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:73)

<truncated>

 Caused by: org.postgresql.util.PSQLException: Connection to <my-database>:<my-port> refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:262)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:52)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:216)
    at org.postgresql.Driver.makeConnection(Driver.java:404)
    at org.postgresql.Driver.connect(Driver.java:272)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:201)
    at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:196)
    at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.getConnection(UnpooledDataSource.java:93)
    at org.apache.ibatis.datasource.pooled.PooledDataSource.popConnection(PooledDataSource.java:385)
    at org.apache.ibatis.datasource.pooled.PooledDataSource.getConnection(PooledDataSource.java:89)
    at org.apache.ibatis.transaction.jdbc.JdbcTransaction.openConnection(JdbcTransaction.java:140)
    at org.apache.ibatis.transaction.jdbc.JdbcTransaction.getConnection(JdbcTransaction.java:62)
    at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:315)
    at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:75)
    at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:61)
    at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:303)
    at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:154)
    at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:102)
    at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:82)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:120)
    ... 16 more
 Caused by: java.net.ConnectException: Cannot assign requested address (connect failed)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:61)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
    ... 37 more

I do not see these exceptions with small amounts of traffic, only at scale, so it doesn't seem to be any sort of functional problem or syntax issue with the mapper.  In my config file for mybatis, this is how my source is configured:
<environments default = "ingestion_environment">
    <environment id = "ingestion_environment">
        <transactionManager type = "JDBC"/>

        <dataSource type = "POOLED">
            <property name = "driver" value = "org.postgresql.Driver"/>
            <property name="url" value="jdbc:postgresql://<my-database>:<my-port>/<my-user>" />
            <property name="username" value="<username>" />
            <property name="password" value="<password>" />
            <property name="poolMaximumCheckoutTime" value="50000"/>
            <property name="poolMaximumActiveConnections" value="10"/>
        </dataSource>
    </environment>
</environments>

I'm trying to figure out what about high traffic could lead to these exceptions--with a pooled connection, it seems like the number of connections really shouldn't be changing even when there are more messages to handle.  What could cause this?


text:
Q: Installed date for an iOS app using Xamarin Is there a way to find the date an app was installed on a device using Xamarin.iOS?

A: Why don't you use UserDefaults?
You could check for a key let's say "installDate", if it does't exist it means it's the first time your launching the app and you'll set the installDate as the current date. If it does exist you know that the app was launched already.

A: I solved it by adding:
var urlToDocumentsFolder = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User).First();
var creationDate = NSFileManager.DefaultManager.GetAttributes(urlToDocumentsFolder.Path).CreationDate;


text:
Q: .Net Core transaction decorator without TransactionScope In my .NET Core application, I have a decorator class that I hoped would be able to handle transactions by wrapping the execution of database commands in a TransactionScope. Unfortunately, it appears that support for TransactionScope isn't going to make it into SqlConnection by the release of .NET Core 2: https://github.com/dotnet/corefx/issues/19708:
In the absence of TransactionScope, I'm not sure of the best approach to this problem. With TransactionScope, my transaction decorator looks like this:
public class TransactionCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
    private readonly ICommandHandler<TCommand> decorated;

    //constructor

    public void Handle(TCommand command)
    {
       using (var scope = new TransactionScope())
       {
           this.decorated.Handle(command);

           scope.Complete();
       }
    }
}

Currently, each implementation of ICommandHandler gets an instance of my DapperContext class and handles commands like this:
public void Handle(UpdateEntity command)
    {
        var sql = Resources.UpdateEntityPart1;

        this.context.Execute(sql, new
        {
           id = command.Id;
        });

        var sql = Resources.UpdateEntityPart2;

        //call Execute again
    }

The DapperContext class has a connection factory to provide new connections for each call to its Execute method. Because the command handler may have to to perform multiple database writes for a single TCommand, I need the ability to rollback when something fails. Having to create transactions at the same time that I create connections (in DapperContext) means I have no way to guarantee transactional behavior across connections.
The one alternative I've considered doesn't seem all that satisfying:

*

*Manage connections and transactions at the command handler level, then pass that information to the dapper context. That way all queries for a given command use the same connection and transaction. This might work, but I don't like the idea of burdening my command handlers with this responsibility. In terms of overall design, it seems more natural that the DapperContext be the place to worry about having a connection.

My question, then: Is there any way to write a transaction decorator without the use of TransactionScope, given the current limitations of SqlConnection in .NET Core? If not, what's the next best solution that doesn't violate the principle of single responsibility too egregiously?

A: A solution could be to create a SqlTransaction as part of the decorator, and store it in some sort of ThreadLocal or AsyncLocal field, so it is available for other parts of the business transaction, even though it is not explicitly passed on. This is effectively what TransactionScope does under the cover (but more elegantly).
As example, take a look at this pseudo code:
public class TransactionCommandHandlerDecorator<TCommand>
    : ICommandHandler<TCommand>
{
    private readonly ICommandHandler<TCommand> decorated;
    private readonly AsyncLocal<SqlTransaction> transaction;

    public void Handle(TCommand command)
    {
        transaction.Value = BeginTranscation();

       try
       {
            this.decorated.Handle(command);

            transaction.Value.Commit();
       }
       finally
       {
           transaction.Value.Dispose();
           transaction.Value = null;
       }
   }
}

With an abstraction that handlers can use:
public interface ITransactionContainer
{
    SqlTransaction CurrentTransaction { get; }
}

public void Handle(UpdateEntity command)
{
    // Get current transaction
    var transaction = this.transactionContainer.CurrentTransaction;

    var sql = Resources.UpdateEntityPart1;

    // Pass the transaction on to the Execute
    // (or hide it inside the execute would be even better)
    this.context.Execute(sql, transaction, new
    {
       id = command.Id;
    });

    var sql = Resources.UpdateEntityPart2;

    //call Execute again
}

An implementation for ITransactionContainer could look something like this:
public class AsyncTransactionContainer : ITransactionContainer
{
    private readonly AsyncLocal<SqlTransaction> transaction;

    public AsyncTransactionContainer(AsyncLocal<SqlTransaction> transaction)
    {
        this.transaction = transaction;
    }

    public SqlTransaction CurrentTransaction =>
        this.transaction.Value
            ?? throw new InvalidOperationException("No transaction.");
}

Both the AsyncTransactionContainer and TransactionCommandHandlerDecorator depend on an AsyncLocal<SqlTransaction>. This should be a singleton (the same instance should be injected into both).


text:
Q: Using pagination in a React component, without re-rendering the entire component I've set up pagination(using a 3rd party component) in one of my React components. Each time a page button is clicked, this function is executed:
 handlePageChange= (page)=>{
    history.push(`/duplicates?page=${page}`)
}

I'm using "Router" from "react-router-dom", and "createBrowserHistory" from JS history library:

When the component mounts, i simply extract the "page" query parameter, and dispatch a Redux action, that fetches all relevant data, and puts its in the Redux state:
  componentDidMount(){
    this.props.fetch(this.state.activePage)
}

The "activePage" is taken from the component state:
state={
     activePage: this.queryParams.page || 1
 }

Everything works nicely, with one very fundamental "flaw": Being that i use history.push on every pagination action, the entire component re-mounts. Sure, i can navigate back and forth in my "pages", and even bookmark them, but the fact that the entire component needs to re-render, seems to undermine one of the main purposes of React: Being very efficient, when it comes to DOM manipulations.
Is there any way to setup pagination, without having to choose between history and efficiency?
EDIT: this is the component:
import React from 'react';
import _ from "lodash";
import { connect } from 'react-redux';
import { searchAction, fetchDuplicates } from '../../actions/products';
import DuplicateProduct from './DuplicateProduct';
import Pagination from 'react-js-pagination'
import queryString from 'query-string';
import {history} from '../../routers/AppRouter';

class Duplicates extends React.Component{
     queryParams= queryString.parse(this.props.location.search);

     state={
         activePage: this.queryParams.page || 1
     }

handlePageChange= (page)=>{
    history.push(`/duplicates?page=${page}`)
}

componentDidMount(){
    this.props.fetch(this.state.activePage)
}

render(){
    console.log(this.queryParams.page)
    return(

Duplicate Titles

number of pages: {this.props.numberOfPages}

      <Pagination
        activePage={parseInt(this.state.activePage)}
        itemsCountPerPage={150}
        totalItemsCount={this.props.numberOfProducts}
        pageRangeDisplayed={10}
        onChange={this.handlePageChange}
        className="pagination"

      />

       {this.props.duplicates.length>0 &&(
         this.props.duplicates[0].map((duplicate_group)=>{
             return (

                     <DuplicateProduct duplicate_group={duplicate_group}/>

             )

         })
       )
        }

    );

};
}

const mapStateToProps= (state)=>({
    duplicates: state.products.duplicates,
    numberOfPages: state.products.numberOfPages,
    numberOfProducts: state.products.numberOfProducts
})

const mapDispatchToProps =(dispatch,props)=>({
    fetch: (page)=> dispatch(fetchDuplicates(page))
})

export default connect(mapStateToProps, mapDispatchToProps)(Duplicates);

This is the PrivateRoute:
import React from 'react';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';
import Header from '../components/Header';

export const PrivateRoute = ({
  isAuthenticated,
  component: Component,
  ...rest
}) => (
    <Route {...rest} component={(props) => (
      isAuthenticated ? (

          <Component {...props} />

      ) : (
          <Redirect to="/" />
        )
    )} />
  );

const mapStateToProps = (state) => ({
  isAuthenticated: state.auth.isLoggedIn
});

export default connect(mapStateToProps)(PrivateRoute);


text:
Q: jQuery Mobile Slider with Gradients and Labels? I need to implement a jQuery Mobile slider with a few extras.
This is what we have implemented
http://bseth99.github.io/jquery-ui-extensions/tests/visual/labeledslider/variable_labels.html
We added a nice blue to red gradient underlay but the problem is it won't support a swiping slide functionality on a mobile device. We can touch the slider at various points and that works but not sliding back and forth. I have my range set from 1-100 and interval of 1.  Notice that this example even allows a mouse to click and drag the slider back and forth very smoothly - that's what I want to happen via a mobile device.  I've left a question on his blog hoping he might have a new version coming out based on jQuery Mobile rather than just jQuery UI but I figured I'd ask in the meantime if anyone else has encountered and solved this puzzle.
I've looked at the options for the regular jQuery Mobile slider and see the data-theme and data-track-theme which sound hopeful for a gradient but I'd still be left with needing the labels.


text:
Q: How can I run the Delphi XML schema binding generator from the command line? For build automation, I would like to invoke the XML Data Binding Wizard in Delphi from a build script. I have found the WSDLImp.exe, but this tool seems to generate WSDL based Delphi code only.
Is the XML schema binding wizard (which generates Delphi code for XSD files) available as a command line tool?

A: As it is a Wizard, it is by definition a UI kinda thing, not a command line one.
Maybe you mean as a separate exe that you can launch without Delphi?
AFAIK, it is not possible.
FYI, it is part of the dclnet design time package. The class of the wizard-dialog is TXMLNewBindingDlg.


text:
Q: Gap beneath "Sticky Footer" - Only happens when I add tables? I'm battling with what seems to be a conflict between my table and footer. My end goal is to have a short "Sticky Footer" on a product page. Products are contained within a table.
As I stand right now- I've barely managed to get my footer to stick to the bottom of the view-port. I need it to be a lot shorter though- and when I change it's "height" dimension- rather than decreasing in height from the top down, it shrinks from the bottom up, creating an unsightly gap.
Here is my source code & style-sheet:

@charset "utf-8";
/* CSS Document */
html,
html* {box-sizing: border-box;
 margin: 0;
padding: 0;
height: 100%}
body {
font-size: 1vw;
background: rgba(0,0,0,1.00);
 text-decoration: none;
 padding: 0em;
 margin: 0em;
 float: inherit;
 height: 100%
}
header {
 position: fixed;
 padding:0em;
 z-index: 1000;
 top: 0;
 left: 0;
 width: 100%;
 text-decoration: none;
 color: transparent}
nav {
 z-index: 400;
 top: 0;
 left: 0;
 opacity; .100;
 float: right;
 display: inline-block;
 width: 100%; height: 10%;
 text-decoration: none;
 font-size: 160%;
 font-family: Centaur;
 position: fixed;
 color: transparent}

menu {
 height: 5%;
 display: inline-block;
 float: right;
 text-decoration: none; color: transparent;}

a href{color: black;}
@font-face {
    font-family:Centaur;
    src: url('your_font.ttf');}
p{color: black; text-decoration: none; font-size: 12px}

 <meta charset="utf-8"></meta>
<title>Albion-Swords/Swords</title>
<meta name="viewport" content="width=device-width">

<link href="Albion Front Page Style Sheet.css" rel="stylesheet" type="text/css">

LOADING...

Home

Swords

Museum Line

Next Generation

Squire Line

Maestro Line

Skirmish Line

Special Edition

About

Media

Story

Gallary

Facebook

Twitter

Testimonials

News

Order

The Albion Mark Next Generation Line

Iron Age & Roman Swords

     <p1 style="text-decoration: underline">The Cherusker</p1>
<p1>Germanic War-Knife
$880.00</p1>

   <p1 style="text-decoration: underline">The Aquilifer</p1>
<p1>Fulham Gladius
$770.00</p1>

  <p1 style="text-decoration: underline">The Tiberius</p1>
<p1>Fulham Gladius II
$770.00</p1>

  <p1 style="text-decoration: underline">The Allectus</p1>
<p1>Mainz Gladius
$770.00</p1>

  <p1 style="text-decoration: underline">The Augustus</p1>
<p1>Mainz Gladius II
$770.00</p1>

  <p1 style="text-decoration: underline">The Pedite</p1>
<p1>Pompeii Gladius
$770.00</p1>

  <p1 style="text-decoration: underline">The Trajan</p1>
<p1>Guttmann
 Pompeii Gladius
$825.00 </p1>

  <p1 style="text-decoration: underline">The Decurio</p1>
<p1>(Roman Spatha)
$880.00</p1>

  <p1 style="text-decoration: underline">The Auxilia</p1>
<p1>(Roman Spatha)
$880.00</p1>

  <p1 style="text-decoration: underline">The Alaris</p1>
<p1>Spatha I
 available for

advance reservation
$880.00</p1>

<p1>Information sent to Albion Swords Ltd is kept strictly confidential. It is not shared or sold to other firms. Data may be used to send e-mail announcements which may be opted out of via email. Copyright (c) 2005: Albion Swords Ltd, LLC. This site and all pages and images contained therein unless otherwise indicated are property of Albion Armorers Swords Ltd, LLC and may not be reproduced or used without express consent. Site created and maintained by Howard & Amy Waddell & Cody Carter. Principal photography by: Leif Hansen, Søren Niedziella & Emma Martinson.</p1>

My apologies for the mixed up code. I am using in-markup CSS as well as a style-sheet...
If the snippet does weird things, here is a screenshot:


text:
Q: Im having an issue with the jquery autocomplete select method My current code is
$(".Commodities").autocomplete({
source: function (request, response) {
    $.getJSON('url',  function (data) {
            var comms = $.map(data, function (el) {
                 return {
                     label: el.desc,
                     value: el.desc

                 };

             });
               response($.ui.autocomplete.filter(comms, request.term));

         })
     },
      minLength: 2,
          select: function( event, ui,el ) {
        $('#commcd').val(ui.item.code);

        }

});

I'm not really familiar with the ui.item part of the code but I'm assuming it's pulling from the mapped out json. I'm sure that my formatting is off somewhere and I'm assuming its how I used the ui.item property. I'm at a loss but it would be a huge help if anyone could shed a light on this the last step I need to finish this is just passing that extra value to an input field.

A: Consider the following.
$(".Commodities").autocomplete({
  source: function (request, response) {
    $.getJSON('url?term=' + request.term, function (data) {
      var comms = $.map(data, function (el) {
        return {
          label: el.desc,
          value: el.desc,
          code: el.code
        };
      });
      response(comms);
    })
  },
  minLength: 2,
  select: function(event, ui) {
    $('#commcd').val(ui.item.code);
    return false;
  }
});

If your URL is an API, it should be able to accept a term or query to help reduce the results. It is always better to do this server-side if possible. Otherwise, you can filter the results as you did.
response($.ui.autocomplete.filter(comms, request.term));


text:
Q: pandas Grouper changes date value Based on this thread: Pandas Subset of a Time Series Without Resampling
The goal is to return the latest date in a month (with a value), and return that value.
Sample code:
Date    CumReturn
3/31/2017    1
4/3/2017     .99
5/31/2017    1.022
4/4/2017     100
4/28/2017    1.012
5/1/2017     1.011
6/30/2017    1.033

import pandas as pd
df = pd.read_clipboard(parse_dates = ['Date'])
df.set_index('Date')
df

I thought this would work:
df.groupby(pd.Grouper(freq = 'M')).max()

But it returns the dates corresponding to the highest values (CumReturn), rather than the max dates in the index.
df.groupby(pd.Grouper(freq = 'M')).last()

However, the output shows that the last day in April is chosen, rather than the latest day in the df. pandas assigns the value from April 28 to April 30, and returns this df:
    CumReturn
Date
2017-03-31  1.000
2017-04-30  1.012
2017-05-31  1.022
2017-06-30  1.033

What causes this behavior? I assume pandas is just picking the latest date in each month, but that seems odd since those dates aren't present in the original data.


text:
Q: Is json.loads() vulnerable to arbitrary code execution? Is json.loads from Python's standard json module vulnerable to arbitrary code execution or any other security problems?
My application can receive JSON messages from non-trustworthy sources.

A: Note that the below answer is relating to the default Python3.4 installation for Windows 10 64-bit. Also note that this answer only looks at the py scanner, not the c scanner.
For the source files see https://hg.python.org/cpython/file/tip/Lib/json or find them in your local python installation.

Research

See the reference implementation at the bottom of this post alongside this research
The parsing functions called by json.loads(s) are defined in \Lib\json\scanner.py:
parse_object = context.parse_object
parse_array = context.parse_array
parse_string = context.parse_string
parse_float = context.parse_float
parse_int = context.parse_int
parse_constant = context.parse_constant

with context being an instance of the JSONDecoder class which is defined in \Lib\json\decoder.py and uses the following parsers:
self.parse_float = parse_float or float
self.parse_int = parse_int or int
self.parse_constant = parse_constant or _CONSTANTS.__getitem__
self.parse_string = scanstring
self.parse_object = JSONObject
self.parse_array = JSONArray

From here we can look at each individual parser to determine whether or not it is susceptible to arbitrary code execution:

parse_float
This uses the default float function and so is safe.

parse_int
This uses the default int function and so is safe.

parse_constant
_CONSTANTS is defined within the same file as:
_CONSTANTS = {
    '-Infinity': NegInf,
    'Infinity': PosInf,
    'NaN': NaN,
}

and so a simple lookup is being performed, and so it is safe.

parse_string, JSONObject, JSONArray
As can be seen by looking at the implementations at the end of this post, the only external code that could be executed is:
From JSONObject:

*

*object_pairs_hook

*object_hook
From JSONArray:

*

*scan_once

object_pairs_hook, object_hook
By default object_pairs_hook and object_hook are defined as None from the decoder initializer:
def __init__(self, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, strict=True,
        object_pairs_hook=None)

scan_once
scan_once is defined as:
self.scan_once = scanner.make_scanner(self)

The source for which can be found in \Lib\json\scanner.py, from which we can see that it scan_once simply calls the appropriate parser for each part of the JSON object.

Conclusion

From the above and the reference implementation it can be seen that as long as the scanner used by the JSON decoder is the default, arbitrary code will not be executed, it is probably possible by using a custom decoder through the use of its __init__ parameters to instead make it execute arbitrary code, but save that I don't think so.

Implementation

BACKSLASH
BACKSLASH = {
    '"': '"', '\\': '\\', '/': '/',
    'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t',
}

STRINGCHUNK
STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)

scanstring
def py_scanstring(s, end, strict=True,
        _b=BACKSLASH, _m=STRINGCHUNK.match):
    """Scan the string s for a JSON string. End is the index of the
    character in s after the quote that started the JSON string.
    Unescapes all valid JSON string escape sequences and raises ValueError
    on attempt to decode an invalid string. If strict is False then literal
    control characters are allowed in the string.

    Returns a tuple of the decoded string and the index of the character in s
    after the end quote."""
    chunks = []
    _append = chunks.append
    begin = end - 1
    while 1:
        chunk = _m(s, end)
        if chunk is None:
            raise ValueError(
                errmsg("Unterminated string starting at", s, begin))
        end = chunk.end()
        content, terminator = chunk.groups()
        # Content is contains zero or more unescaped string characters
        if content:
            _append(content)
        # Terminator is the end of string, a literal control character,
        # or a backslash denoting that an escape sequence follows
        if terminator == '"':
            break
        elif terminator != '\\':
            if strict:
                #msg = "Invalid control character %r at" % (terminator,)
                msg = "Invalid control character {0!r} at".format(terminator)
                raise ValueError(errmsg(msg, s, end))
            else:
                _append(terminator)
                continue
        try:
            esc = s[end]
        except IndexError:
            raise ValueError(
                errmsg("Unterminated string starting at", s, begin))
        # If not a unicode escape sequence, must be in the lookup table
        if esc != 'u':
            try:
                char = _b[esc]
            except KeyError:
                msg = "Invalid \\escape: {0!r}".format(esc)
                raise ValueError(errmsg(msg, s, end))
            end += 1
        else:
            uni = _decode_uXXXX(s, end)
            end += 5
            if 0xd800 <= uni <= 0xdbff and s[end:end + 2] == '\\u':
                uni2 = _decode_uXXXX(s, end + 1)
                if 0xdc00 <= uni2 <= 0xdfff:
                    uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
                    end += 6
            char = chr(uni)
        _append(char)
    return ''.join(chunks), end

scanstring = c_scanstring or py_scanstring

WHITESPACE
WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)

WHITESPACE_STR
WHITESPACE_STR = ' \t\n\r'

JSONObject
def JSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook,
               memo=None, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
    s, end = s_and_end
    pairs = []
    pairs_append = pairs.append
    # Backwards compatibility
    if memo is None:
        memo = {}
    memo_get = memo.setdefault
    # Use a slice to prevent IndexError from being raised, the following
    # check will raise a more specific ValueError if the string is empty
    nextchar = s[end:end + 1]
    # Normally we expect nextchar == '"'
    if nextchar != '"':
        if nextchar in _ws:
            end = _w(s, end).end()
            nextchar = s[end:end + 1]
        # Trivial empty object
        if nextchar == '}':
            if object_pairs_hook is not None:
                result = object_pairs_hook(pairs)
                return result, end + 1
            pairs = {}
            if object_hook is not None:
                pairs = object_hook(pairs)
            return pairs, end + 1
        elif nextchar != '"':
            raise ValueError(errmsg(
                "Expecting property name enclosed in double quotes", s, end))
    end += 1
    while True:
        key, end = scanstring(s, end, strict)
        key = memo_get(key, key)
        # To skip some function call overhead we optimize the fast paths where
        # the JSON key separator is ": " or just ":".
        if s[end:end + 1] != ':':
            end = _w(s, end).end()
            if s[end:end + 1] != ':':
                raise ValueError(errmsg("Expecting ':' delimiter", s, end))
        end += 1

        try:
            if s[end] in _ws:
                end += 1
                if s[end] in _ws:
                    end = _w(s, end + 1).end()
        except IndexError:
            pass

        try:
            value, end = scan_once(s, end)
        except StopIteration as err:
            raise ValueError(errmsg("Expecting value", s, err.value)) from None
        pairs_append((key, value))
        try:
            nextchar = s[end]
            if nextchar in _ws:
                end = _w(s, end + 1).end()
                nextchar = s[end]
        except IndexError:
            nextchar = ''
        end += 1

        if nextchar == '}':
            break
        elif nextchar != ',':
            raise ValueError(errmsg("Expecting ',' delimiter", s, end - 1))
        end = _w(s, end).end()
        nextchar = s[end:end + 1]
        end += 1
        if nextchar != '"':
            raise ValueError(errmsg(
                "Expecting property name enclosed in double quotes", s, end - 1))
    if object_pairs_hook is not None:
        result = object_pairs_hook(pairs)
        return result, end
    pairs = dict(pairs)
    if object_hook is not None:
        pairs = object_hook(pairs)
    return pairs, end

JSONArray
def JSONArray(s_and_end, scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
    s, end = s_and_end
    values = []
    nextchar = s[end:end + 1]
    if nextchar in _ws:
        end = _w(s, end + 1).end()
        nextchar = s[end:end + 1]
    # Look-ahead for trivial empty array
    if nextchar == ']':
        return values, end + 1
    _append = values.append
    while True:
        try:
            value, end = scan_once(s, end)
        except StopIteration as err:
            raise ValueError(errmsg("Expecting value", s, err.value)) from None
        _append(value)
        nextchar = s[end:end + 1]
        if nextchar in _ws:
            end = _w(s, end + 1).end()
            nextchar = s[end:end + 1]
        end += 1
        if nextchar == ']':
            break
        elif nextchar != ',':
            raise ValueError(errmsg("Expecting ',' delimiter", s, end - 1))
        try:
            if s[end] in _ws:
                end += 1
                if s[end] in _ws:
                    end = _w(s, end + 1).end()
        except IndexError:
            pass

    return values, end

scanner.make_scanner
def py_make_scanner(context):
    parse_object = context.parse_object
    parse_array = context.parse_array
    parse_string = context.parse_string
    match_number = NUMBER_RE.match
    strict = context.strict
    parse_float = context.parse_float
    parse_int = context.parse_int
    parse_constant = context.parse_constant
    object_hook = context.object_hook
    object_pairs_hook = context.object_pairs_hook
    memo = context.memo

    def _scan_once(string, idx):
        try:
            nextchar = string[idx]
        except IndexError:
            raise StopIteration(idx)

        if nextchar == '"':
            return parse_string(string, idx + 1, strict)
        elif nextchar == '{':
            return parse_object((string, idx + 1), strict,
                _scan_once, object_hook, object_pairs_hook, memo)
        elif nextchar == '[':
            return parse_array((string, idx + 1), _scan_once)
        elif nextchar == 'n' and string[idx:idx + 4] == 'null':
            return None, idx + 4
        elif nextchar == 't' and string[idx:idx + 4] == 'true':
            return True, idx + 4
        elif nextchar == 'f' and string[idx:idx + 5] == 'false':
            return False, idx + 5

        m = match_number(string, idx)
        if m is not None:
            integer, frac, exp = m.groups()
            if frac or exp:
                res = parse_float(integer + (frac or '') + (exp or ''))
            else:
                res = parse_int(integer)
            return res, m.end()
        elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
            return parse_constant('NaN'), idx + 3
        elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
            return parse_constant('Infinity'), idx + 8
        elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
            return parse_constant('-Infinity'), idx + 9
        else:
            raise StopIteration(idx)

    def scan_once(string, idx):
        try:
            return _scan_once(string, idx)
        finally:
            memo.clear()

    return _scan_once

make_scanner = c_make_scanner or py_make_scanner


text:
Q: responsive jquery css rnd web design tool download I'm new to RWD web page design, going to develop dynamic responsive HTML using latest jquery and css.
Previously I used mobirise tool (https://mobirise.com/) for static HTML web page.
I was unable to implement grid, drop-down button, radio button, text box, etc. in mobirise tool.
Please suggest me any other good RWD tool for dynamic HTML web page development for my JAVA project.


text:
Q: Countable product of finite spaces has no isolated point Let each $X_i$ be a finite metric space. Define $X = \prod_{i\geq 1} X_i$ to be the product space equipped with the uniform metric, ie.
$$\rho_{\infty}(\mathbf{x}, \mathbf{y}) = \sup_{i\geq 1} d(x_i,y_i)$$
Show that $X$ contains no isolated points.

This question was given to me in an analysis course, but I have a feeling that it is false. Consider each $X_i = \{0,1\}$ with $d(0,1)=d(1,0)=1$. This is a metric space, of course, with $d(0,0)=d(1,1)=0$, $d(1,0) = d(0,1) = 1$, and $d(0,1) \leq d(0,0) + d(1,0)$ and vice versa.
If that is the case, however, then take $x = (0,0,\dots)$ and consider the ball $B_{\frac{1}{2}}(x) = \{x\}$. Clearly this is a contradiction.
Am I correct? Is the question presented in its current form false?


text:
Q: How to overlay histograms in matlab I have multiple histograms that I would like to overlay on top of each other but I don't know how to do it. I found the code below but I don't know how to modify it to run on a loop instead of just two histograms.
data1 = randn(100,1);       % data of one size
data2 = randn(25, 1);       % data of another size!

myBins = linspace(-3,3,10); % pick my own bin locations

% Hists will be the same size because we set the bin locations:
y1 = hist(data1, myBins);
y2 = hist(data2, myBins);

% plot the results:
figure(3);
bar(myBins, [y1;y2]');
title('Mixed size result');

or what is a better way of comparing histograms if they are more than 10 or 20.

A: Your question is very general. Firstly I do not understand why you insist on a for loop.
Personally I don't like the included bar plot. It quickly gets messy (especially since the bars are not at the "original" location)
If you got a lot of histograms I would consider a stairstep plot as it doesn't fill the plot area so much. Or you could come up with your own - eg using transparent patches.
If it get's lots of curves there are many ways to visualize them google for "multivariate visualization" and be amazed. One of the most amusing ways would be Chernoff faces.

A: it's much easier now:
histogram(data1, myBins);
hold on;
histogram(data2, myBins);

A: You could do the following, although it's not the only way:
data = cell(1, N);
y = cell(1, N);
yBar = zeros(N, 10);
for i=1:N
    data{1, i} = randn(10*round(rand(1,1)), 1);
    y{1, i} = hist(data{1, i}, myBins);
    yBar(i, :) = y{1, i};
end
yBar = yBar';
figure(3);
bar(myBins, yBar);
title('Mixed size result');

Using the y cell is not obligatory of course, I left it there to actually show what's happening.

A: I would suggest this. It's simple and does not require for loops:
bar([y1.' y2.'],'stacked')

A: Here's a way that was useful to me:

I'm plotting a histogram for each column of the matrix ao.
The code was:
    for i = 1:size(ao,2)
        [h, y] = hist(ao(:,i), linspace(-5,10,100));
        h = i + (0.95./max(h(:))) .* h;
        barh(y, h, 'BarWidth', 1, 'BaseValue', i, 'LineStyle', 'none');
        hold on;
    end
    grid;

Note that just changing barh to bar will give the same thing but going up-down instead of left-right (i.e. the figure rotated by 90° anti-clockwise).


text:
Q: How to work with dependent fields in Spring 3.0? I tried to create my first spring mvc application. I'm using architecture: Spring MVC-Service-DAO-Persistence Architecture.
I've get this error:
Field error in object 'rooms' on field 'roomTypeId': rejected value [7]; codes    [typeMismatch.rooms.roomTypeId,typeMismatch.roomTypeId,typeMismatch.mypackage.domain.RoomType,typeMismatch]; arguments
[org.springframework.context.support.DefaultMessageSourceResolvable: codes   [rooms.roomTypeId,roomTypeId]; arguments []; default message [roomTypeId]];
default message [Failed to convert property value of type 'java.lang.String' to required type   'mypackage.domain.RoomType'
for property 'roomTypeId'; nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String] to required  type [mypackage.domain.RoomType] for property
'roomTypeId': no matching editors or  conversion strategy found]

Domain:
@Entity
@Table(name = "rooms")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Rooms.findAll", query = "SELECT r FROM Rooms r")})
public class Rooms implements Serializable {
...
@JoinColumn(name = "RoomTypeId", referencedColumnName = "RoomTypeId")
@ManyToOne
private RoomType roomTypeId;
...
public RoomType getRoomTypeId() {
    return roomTypeId;
}
public void setRoomTypeId(RoomType roomTypeId) {
    this.roomTypeId = roomTypeId;
}
}

Controller:
@RequestMapping(value = "/room/add", method = RequestMethod.POST)
public String addRoom(@ModelAttribute("rooms") Rooms room,
        BindingResult result) {
    roomService.addRoom(room);
    return "redirect:/rooms";
}

I tried:
@RequestMapping(value = "/room/add", method = RequestMethod.POST)
public String addRoom(@ModelAttribute("rooms") Rooms room, @RequestParam Long roomTypeId,
        BindingResult result) {
    room.setRoomTypeId(typeService.getType(roomTypeId.intValue()));
    roomService.addRoom(room);
    return "redirect:/rooms";
}

jsp:
<form:form method="post" action="room/add" commandName="room">

        <form:label path="name">
                <spring:message code="label.roomname" />
            </form:label>
        <form:input path="name" />

        <form:label path="roomTypeId">
                <spring:message code="label.typeroom" />
            </form:label>

            <form:select path="roomTypeId" name="roomTypeId">
                <c:forEach items="${typeList}" var="type">
                    <form:option value="${type.roomTypeId}" label="${type.name}"/>
                </c:forEach>
            </form:select>

        <input type="submit"
                               value="<spring:message code="label.addroom"/>" />

</form:form>

I understand why this shows me. But I do not know how to fix it. Help me fix it or tell me what I'm doing wrong.

A: In the following method declaration
public String addRoom(@ModelAttribute("rooms") Rooms room, @RequestParam Long roomTypeId, BindingResult result...,

put the BindingResult argument next to the Rooms argument.


text:
Q: How do you map an interface that derives from two classes in MonoTouch? I have the following interface definition in an external library
@interface AGSGPS : UIView < CLLocationManagerDelegate >

Normally your would define in the ApiDefinition.cs as:
[BaseType (typeof (UIView))]
interface AGSGPS : CLLocationManagerDelegate

The problem with this is that both UIView and CLLocationManagerDelegate are classes and this breaks down to the following code behind:
class AGSGPS : UIView, CLLocationManagerDelegate

which is illegal in C#
thoughts?

A: You do not need to "map" the object. The type in the angle brackets is a protocol and that means that your AGSGPS object adopts that protocol.
Check the docs here
Now, adopting a protocol means that your object should implement all the protocol's methods. To do this in your ApiDefinition, just treat CLLocationManagerDelegate's methods as if they belong to your AGSGPS type, eg:
[BaseType (typeof (UIView))]
interface AGSGPS
{

    [Export("locationManager:didUpdateHeading:")]
    void UpdatedHeading(CLLocationManager lman, CLHeading heading);

    // etc, include all CLLocationManagerDelegate's methods
}


text:
Q: Нажать программно кнопку мыши средствами C# Подскажите решение. Требуется программно нажать кнопку мыши, затем кнопку клавиатуры в приложении WPF без использования сторонних API. Импорт библиотеки user32.dll не предлагать.
Здесь нашел частичное решение проблемы, но там предупреждение что метод работает по-разному в версиях Windows.
Прошу пример для нажатия кнопки мыши и клавиатуры.
Нашел пример как это можно сделать, запускается но не кликает
 public void imitianionDoubleRight()
 {
      var temp = new System.Windows.Forms.MouseEventArgs(System.Windows.Forms.MouseButtons.Right, 2, 630, 630, 0);

      button1_MouseClick(null, temp);
 }

 private void button1_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
 {
 }

A: Попробуйте использовать System.Windows.Forms.SendKeys:
SendKeys.Send("{ENTER}");

Подробнее можно узнать на msdn
Но под капотом там так же используется user32.dll, если я не ошибаюсь
UDP
Вот есть пример нажатия на мышь без явного использования сторонних библиотек

A: Без user32.dll никуда, потому что все действия связаные с вводом мышки и клавиатуры на Windows сводится к user32.dll. Даже WPF где-то у себя в недрах использует user32.dll, для генераций событий связаные с мышкой и клавиатурой.
А для эмуляции ввода с мыши и клавиатуры используйте InputSimulator, но эта библиотека тоже где-то у себя внутри использует user32.dll.
Example: Single key press
public void PressTheSpacebar()
{
  InputSimulator.SimulateKeyPress(VirtualKeyCode.SPACE);
}

Example: Key-down and Key-up
public void ShoutHello()
{
  // Simulate each key stroke
  InputSimulator.SimulateKeyDown(VirtualKeyCode.SHIFT);
  InputSimulator.SimulateKeyPress(VirtualKeyCode.VK_H);
  InputSimulator.SimulateKeyPress(VirtualKeyCode.VK_E);
  InputSimulator.SimulateKeyPress(VirtualKeyCode.VK_L);
  InputSimulator.SimulateKeyPress(VirtualKeyCode.VK_L);
  InputSimulator.SimulateKeyPress(VirtualKeyCode.VK_O);
  InputSimulator.SimulateKeyPress(VirtualKeyCode.VK_1);
  InputSimulator.SimulateKeyUp(VirtualKeyCode.SHIFT);

  // Alternatively you can simulate text entry to acheive the same end result
  InputSimulator.SimulateTextEntry("HELLO!");
}

Здесь больше примеров.


text:
Q: Что нужно добавить в код? У меня есть программа, которая переводит ВСЕ буквы верхнего регистра в нижний. Что нужно добавить в неё или изменить, что бы только гласные буквы переходили в нижний регистр.
Код программы:
#include <stdlib.h>
#include <locale.h>

void fun(char str1[]){
    int j;
    char ch1;
    printf("Введите предложение:\n");
    gets(str1);
    printf("\n");
    printf("\n");
    printf("Преобразование заглавных букв в прописныее имеет вид:\n");
    while (str1[j]) {
        ch1 = str1[j];
        putchar(tolower(ch1));
        j++;
    }

    }

int main()
{
    setlocale(LC_ALL,"rus");
    int k = 0;
    char ch2[] = "A E I O U Y \n";
    fun(ch2);
    return 0;
}

A: я бы сделал так. но это для английского текста.
#include <stdio.h>

void to_lower ( char *str ) {
        do {
                *str += *str >= 'A' && *str <= 'Z' ? 32 : 0;
        } while ( *str++ );
}

int main ( ) {
        char test_str[] = "ALPHA most";

        to_lower ( test_str );

        printf ( "%s\n", test_str );
}


text:
Q: Colorir linha no datagridview c# Estou tentando utilizar o seguinte método:
  for (int i = 0; i < dgvRequisicao.Rows.Count; i++)
        {
            valor = Convert.ToDouble(dgvRequisicao.Rows[i].Cells["valor"].Value);

            if (valor > 20000.01 && valor < 100000)
                dgvRequisicao.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
            else if (valor > 100000.01)
                dgvRequisicao.Rows[i].DefaultCellStyle.BackColor = Color.Red;
        }

Mas não está colorindo de jeito nenhum.
Obrigado

A: Você vai precisar usar o evento CellFormating.
private void dgvRequisicao_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    valor = Convert.ToDouble((string)e.Value);

    if (valor > 20000.01 && valor < 100000)
        dgvRequisicao.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
    else if (valor > 100000.01)
        dgvRequisicao.Rows[i].DefaultCellStyle.BackColor = Color.Red;
}


text:
Q: Complex SQL Server Pivot Involving Null and blank vs. Filled values I need to separate the "dep" column into 2 different columns one being "recorded" the other being "unrecorded". the "unrecorded" column will contain the sum of time for entries where "dep" is blank or null for that day. The "recorded" column needs to display the sum of time for that day where the "dep" column is not null or blank.
So far this is what I have
 SELECT Cast(Start_Time AS DATE) AS Date, dep,
 sum(time) as "Total Time"
 FROM A6K_Events
 Group By Cast(Start_Time AS DATE), dep

and it yields this
 +------------+--------------+------------+
 | Date       | Dep          | Total Time |
 +------------+--------------+------------+
 | 2018-06-29 | Null         | 3544       |
 +------------+--------------+------------+
 | 2018-06-29 | Other        | 268        |
 +------------+--------------+------------+
 | 2018-06-29 | Training     | 471        |
 +------------+--------------+------------+
 | 2018-06-29 | Change Point | 371        |
 +------------+--------------+------------+
 | 2018-06-28 | Null         | 4519       |
 +------------+--------------+------------+
 | 2018-06-28 | Training     | 1324       |
 +------------+--------------+------------+
 | 2018-06-28 |              | 50         |
 +------------+--------------+------------+

This is what I would like the end result to be
+------------+----------+------------+
| Date       | Recorded | Unrecorded |
+------------+----------+------------+
| 2018-06-29 | 1110     | 3544       |
+------------+----------+------------+
| 2018-06-28 | 1324     | 4569       |
+------------+----------+------------+

Any suggestions or help would be appreciated. I cannot figure out how to pivot and filter out null and blank values into one column while the other filled values into another column.
Thank you.

A: Pivot is not required, we can fetch the data using CASE statement
 SELECT start_time as Date, sum(case when dep is not NULL or dep <> '' then time end) as "Recorded", sum(case when dep is NULL or dep = '' then time end) as "Unrecorded"
 FROM A6K_Events
 Group By start_time order by 1 desc


text:
Q: How to save a PHP string with variable not explicit? I have an array like this:
$list = array (
  "Today is ".$aaaa."/".$mm."/".$gg,
  "Oggi è il ".$gg."/".$mm."/".$aaaa,
  "Aujourd'hui, c'est ".$gg."/".$mm."/".$aaaa
);

I would like to save them in a database (with variables not explicit) and then re-use them in php format.
Is it possible to save as string a string in php format?
Example:
$gg = 1;
$myString = "Today is ".$gg;
echo $myString;

$gg = 17;
echo $myString;

This example, of course, show always "Today is 1".
I would like it show "Today is 1", "Today is 17".
Can I save myString with variables not explicit?

A: use sprintf() and save the format.

A: use printf
$myString = "Today is %s";

$today = '21/12/2012';
printf($myString,$today); // Today is 21/12/2012

$today = 21;
printf($myString,$today); // Today is 21

printf will output directly the string.
sprintf will return it
EDIT: in your specific case you should specific the order
$list = array (
  'Today is %1$s/%2$s/%3$s',
  'Oggi è il %3$s/%2$s/%1$s',
  'Aujourd\'hui, c\'est %3$s/%2$s/%1$s'
);

foreach($list as $string) {
    printf($string,"2012","12","21");
    echo  " <br />";
}

However for localization I would use the setlocale function for simple strings and strftime (with setlocale) for localized dates

A:
Can I save myString with variables not explicit?

Sort of, yes. You can implement that:
class MyStringVariable
{
    private $mask;
    private $variables;

    public function __construct($mask, array $variables) {
        $this->mask = $mask;
        $this->variables = $variables;
    }

    public function __toString() {
        return vsprintf($this->mask, $this->variables);
    }
}

Usage (Demo):
$gg = 1;
$myString = new MyStringVariable("Today is %s\n", [&$gg]);
echo $myString;

$gg = 17;
echo $myString;

Output:
Today is 1
Today is 17

This works basically by wrapping vsprintf (see sprintf) into an object of it's own that also stores the variable references you want to make use of. The magic __toString method takes care of resolving the output when it is needed.

A: $sql = 'My var is %s';

$a = 100;
$foo = sprintf($sql, $a);

EDIT 1;
$list = array(
    "Today is %s/%s/%s",
    "Oggi è il %s/%s/%s",
    "Aujourd'hui, c'est %s/%s/%s"
);

foreach ($list as $str)
{
    $a   = 2012;
    $m   = 12;
    $g   = 17;

    if (strstr($str, 'Today '))
        $foo = sprintf($str, $a, $m, $g);
    else
        $foo = sprintf($str, $g, $m, $a);
}

A: I don´t know if this is the best way but it works,
you save the lines as strings, and with eval() then convert to variables
$list = array (
    'Today is ".$aaaa."/".$mm."/".$gg'
);
$aaaa = 2012;
$mm = 11;
$gg = 00;
eval("\$mylist = \"$list[0];");
echo $mylist;

Happy coding !!


text:
Q: Select updates other selects I have n number of selects generate with ng-repeat and I need to update the all the options in the other selects, when I change one of the select. I need to create a vote mechanism. Example:
Init:
- select 1: 1,2,3,4
- select 2: 1,2,3,4
- select 3: 1,2,3,4
- select 4: 1,2,3,4

After change select 1:
- select 1: 2 (selected)
- select 2: 1,3,4
- select 3: 1,3,4
- select 4: 1,3,4

After change select 2:
- select 1: 2 (selected)
- select 2: 4
- select 3: 1,3
- select 4: 1,3
...etc

The number of the selects is dynamic, options always show the number of the generated selects
My code so far:

        <select ng-model="selectedPollNum" ng-change="changedPoll(selectedPollNum)">
            <option ng-repeat="option in items">{{ $index + 1 }}</option>
        </select>
        {{item.name}}

jsFiddle: https://jsfiddle.net/gvwpgtj6/2/
Also options start with empty, and I want to start with the first one

A: I think this will be your requirement. If you select an option by default in select, it is hard to hide the default selected options in other drop downs. So leaving empty is recommended.
CONTROLLER:

function LoginController($scope) {
  $scope.arr = [];
  $scope.obj={};
  $scope.items = [{
    name: 'Lorem ipsum dolor sit amet'
  }, {
    name: 'Consectetur adipiscing elit'
  }, {
    name: 'Fusce faucibus turpis eget'
  }, {
    name: 'Sed quis nisl sed ligula'
  }, {
    name: 'Nunc ultricies ipsum vitae'
  }];

  $scope.changedPoll = function(num, i) {
  $scope.obj[i] = num;$scope.arr=[]
    angular.forEach($scope.obj, function(value,key){
    $scope.arr.push(parseInt($scope.obj[key]))
    });
  }
}

      <select ng-model="selectedPollNum" ng-change="changedPoll(selectedPollNum, $index)">
        <option ng-repeat="option in items" ng-show='arr.indexOf($index + 1)<0'>{{ $index + 1}}</option>
      </select>
      {{item.name}}


text:
Q: Plugin: The Events Calendar Get Page Not Found I have installed "The Events Calendar" (http://wordpress.org/plugins/the-events-calendar/).
In "The Events Calendar Settings" section I checked "Show The Events Calendar link". When I go to my event page www.example.com/events/ it shows in title - page not found but in any case it shows the calendar.

A: go your wordpress admin panel

Event->setting

see the image setting enter your slug

after adding your slug this display like url.

Your current Events URL : XXXXXXXXXXXXXXXXXXXXXXXXXX

A: Settings > Permalinks [ re-save ] just press save Changes.


text:
Q: Solving simultaneous equations/inequalities I need to solve a mix of equations/inequalities:
a1 + a2 + a3 >= 50
b1 + b2 + b3 <= 40
c1 + c2 + c3 <= 10
a1 + b1 + c1  = 50
a2 + b2 + c2  = 35
a3 + b3 + c3  = 15

There are nine variables and six equations/inequalities, but I will be zeroing three of the variables at a time (I will have to check all combinations).
I tried a couple of packages in R (limSolve, matlib) with no success.
#The matrix representation:
X1 <- c(1,1,1,0,0,0,0,0,0)
X2 <- c(0,0,0,1,1,1,0,0,0)
X3 <- c(0,0,0,0,0,0,1,1,1)
Y1 <- c(1,0,0,1,0,0,1,0,0)
Y2 <- c(0,1,0,0,1,0,0,1,0)
Y3 <- c(0,0,1,0,0,1,0,0,1)
A1 <- matrix(c(X1,X2,X3,Y1,Y2,Y3),c(9,9))
A2 <- t(A1); colnames(A2) <- c("a1","a2","a3","b1","b2","b3","c1","c2","c3")
b <- c(50,40,10,50,35,15)

Any help will be appreciated.

A: This can be solved using linear programming. There is nothing to optimize, you are just searching for a feasible solution.
library(lpSolve)

res=lp(
  "min",
  rep(0,ncol(A2)),
  A2,
  c(">=","<=","<=","==","==","=="),
  b
)

res$solution

[1] 50 35 15  0  0  0  0  0  0


text:
Q: How does the ? make a quantifier lazy in regex I've been looking into regex lately and figured that the ? operator makes the *,+, or ? lazy. My question is how does it do that? Is it that *? for example is a special operator, or does the ? have an effect on the * ? In other words, does regex recognize *? as one operator in itself, or does regex recognize *? as the two separate operators * and ? ? If it is the case that *? is being recognized as two separate operators, how does the ? affect the * to make it lazy. If ? means that the * is optional, shouldn't this mean that the * doesn't have to exists at all. If so, then in a statement .*? wouldn't regex just match separate letters and the whole string instead of the shorter string? Please explain, I'm desperate to understand.Many thanks.

A: I think a little history will make it easier to understand.  When the Larry Wall wanted to grow regex syntax to support new features, his options were severely limited.  He couldn't just decree (for example) that % is now a metacharacter that supports new feature "XYZ".  That would break the millions of existing regexes that happened to use % to match a literal percent sign.
What he could do is take an already-defined metacharacter and use it in such a way that its original function wouldn't make sense.  For example, any regex that contained two quantifiers in a row would be invalid, so it was safe to say a ? after another quantifier now turns it into a reluctant quantifier (a much better name than "lazy" IMO; non-greedy good too).  So the answer to your question is that ? doesn't modify the *,  *? is a single entity: a reluctant quantifier.  The same is true of the + in possessive quantifiers (*+, {0,2}+ etc.).
A similar process occurred with group syntax.  It would never make sense to have a quantifier after an unescaped opening parenthesis, so it was safe to say (? now marks the beginning of a special group construct.  But the question mark alone would only support one new feature, so the ? itself to be followed has to be followed by at least one more character to indicate which kind of group it is ((?:...), (?<!...), etc.).  Again, the (?: is a single entity: the opening delimiter of a non-capturing group.
I don't know offhand why he used the question mark both times.  I do know Perl 6  Rules (a bottom-up rewrite of Perl 5 regexes) has done away with all that crap and uses an infinitely more sensible syntax.

A: Imagine you have the following text:
BAAAAAAAAD

The following regexs will return:
/B(A+)/ => 'BAAAAAAAA'
/B(A+?)/ => 'BA'
/B(A*)/ => 'BAAAAAAAA'
/B(A*?)/ => 'B'

The addition of the "?" to the + and * operators make them "lazy" - i.e. they will match the absolute minimum required for the expression to be true. Whereas by default the * and + operators are "greedy" and try and match AS MUCH AS POSSIBLE for the expression to be true.
Remember + means "one or more" so the minimum will be "one if possible, more if absolutely necessary" whereas the maximum will be "all if possible, one if absolutely necessary".
And * means "zero or more" so the minimum will be "nothing if possible, more if absolutely necessary" whereas the maximum will be "all if possible, zero if absolutely necessary".

A: ? can mean a lot of different things in different contexts.

*

*Following a normal regex token (a character, a shorthand, a character class, a group...), it means "Match the previous item 0-1 times".

*Following a quantifier like ?, *, +, {n,m}, it takes on a different meaning: "Make the previous quantifier lazy instead of greedy (if that's the default; that can be changed, though - for example in PHP, the /U modifier makes all quantifiers lazy by default, so the additional ? makes them greedy).

*Right after an opening parenthesis, it marks the start of a special construct like for example
a) (?s): mode modifiers ("turn on dotall mode")
b) (?:...): make the group non-capturing
c) (?=...) or (?!...): lookahead assertion
d) (?<=...) or (?<!...): lookbehind assertion
e) (?>...): atomic group
f) (?<foo>...): named capturing group
g) (?#comment): inline comments, ignored by the regex engine
h) (?(?=if)then|else): conditionals
and others. Not all constructs are available in all regex flavors.

*

*Within a character class ([?]), it simply matches a verbatim ?.

A: This very much depends on the implementation, I guess. But since every quantifier I am aware of can be modified with ? it might be reasonable to implement it that way.


text:
Q: Sample in R a category with multiple levels and take a specific sample size from each category I have the following dataset
it contains 3 character variables (A,B,C).
Variable A consists of 13 levels and i want to take a random sample of size n=30 in each category.
The final dataset I want to contain all the samples in rows and the suited B.
I tried
data%>%
  group_by(B)%>%
  sample_n(size=30,replace = TRUE)

but it didn't work.Any help ?

A: I checked your data, some groups you created (like DRH) has less than 30 observations. Since you passed the replace=TRUE argument, R duplicates if there is less than 30 observations. You can basicaly remove the argument (while keeping only greater than 30 sample groups) or follow this way;
grouped_data <- data %>%
group_by(GEAR) %>%
mutate(size=n())

grouped_data %>%
filter(size>=30) %>%
sample_n(size=30,replace = TRUE) %>%
ungroup %>%
select(-size) -> part_1

grouped_data %>%
filter(size<30) %>%
ungroup %>%
select(-size) -> part_2

I filtered the groups whose sample size greater than 30 then took random 30 observations from each of them in part_1. part_2 includes the groups whose sample size less than 30.


text:
Q: What built in python function would I use to split up a string into each separate character? If I had a 4 digit code saved in a variable as a string without spaces between the digits, how could I split them up into the separate digits?

A: You can pass any iterable to a list, including a string.
>>> list("1234")
['1', '2', '3', '4']

If you want to iterate over the digits, you don't have to to convert it to a list, you can iterate over the string.
for digit in "1234":
    print(digit)


text:
Q: Calculate double integral using polar coordinates Let $f(x,y) = x^2\sqrt{x^2 +y^2}$ and domain $D = \{(x,y) : x^2 +y^2 \le 4 \ , 0\le y\le x\}$. Find value of
$$\iint_D f(x,y) \ dx dy$$
I tried to use $x = r\cos \theta$ , $y = r\sin \theta$ and then got:
$$\iint_Df(x,y)\,dxdy=\int_0^{\pi/4} \int_0^{2} (r^3\cos^2\theta)\cdot r\,drd\theta =\frac{\pi +2 }{8}\cdot\frac{32}{5}$$
I don't know whether this answer is correct or not.


text:
Q: Apply function on column values after streaming from Kafka I need to apply a function on certain columns just after reading the stream from a Kafka topic and before writing it to any landing or table.
This is done in azure databricks.
CREATE FUNCTION encrypt AS 'com.encrypt.EncryptJava' using JAR 'hdfs:/.../jars/encryption_1.0.0.jar';

select encrypt(123,'key');

var streamingSelectDF = spark.readStream
    .format("kafka")
    .option("kafka.bootstrap.servers", bootStrapServers)
    .option("subscribe", topicName)
    .option("startingOffsets", "earliest")
    .load()
 .selectExpr("CAST(value AS STRING)").withColumn("jsonData",from_json($"value",schema)).select($"jsonData.*")

The above code creates a function and reads the json data from the kafka stream and explodes it into multiple columns.
Next need to apply the above function on few columns and transform it before saving it to a landing or table.
I am getting various different error while trying.
streamingSelectDF.withColumn("encrypted_col",encrypt($"acntnum","b1")).writeStream.outputMode("append")
.option("mergeschema",true)
 .option("checkpointLocation", checkPointPath)
.format("delta")
.trigger(Trigger.ProcessingTime("5 seconds"))
.table("raw_data")

command-3006790186109139:29: error: not found: value encrypt
streamingSelectDF.withColumn("encrypted_col",encrypt($"acntnum","b1")).writeStream.outputMode("append")

Can anyone help me on how to achieve the same.

A: Solved it with
.withColumn("encrypted_acctnum",expr("encrypt(acctnum, 'b1')"))


text:
Q: fetch() POST Request, data becomes object key Has anyone had an issue with sending a POST fetch request where the JSON String becomes the Object Key on the recieving end, specifically using { "Content-Type": "application/x-www-form-urlencoded" } for a header.
I have also tried to use CircularJSON to try and fix any circular references that stringify may have created because NodeJS was spitting type errors when the JSON was received.
Client side code:
/* Triggered on a button click */
triggerTransfer(product) {

    let headers = {
        body: CircularJSON.stringify(product),
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        method: "POST"
    }

    this.setState({
        transferState: {
    /* State changes*/
        }
    })

    fetch( _API + '/products/transfer', headers)
        .then(res => {
            return res.json()
        })
        .then((res) => {
            console.log(res)
            this.setState({
                transferState: {
        /* State changes*/
                }
            })
        })
        .catch(err => this.setState({ error: err }))
}

Server Side Route (Please note that I am using body-parser as well), I know this route doesn't do anything, but this was just to help debug the issue:
router.post('/transfer', async (req,res,next)=>{
  console.log(req.body);
  res.json(req.body);
})

When sent from the client side the JSON String looks like this:
{
  "id": 1127,
  "identifier": "CABLE-RJ45-NETWORK-TESTER",
  "description": "CABLE-RJ45-NETWORK-TESTER",
  "price": 50,
  "cost": 35,
  "vendor": {
    "id": 104,
    "identifier": "",
    "name": "",
    "_info": {
      "company_href": ""
    }
  },
  "_info": {
    "lastUpdated": "2012-08-30T05:37:13Z",
    "updatedBy": ""
  }
}

When received on the service side the object looks like this:
{
  '{"id":1127,"identifier":"CABLE-RJ45-NETWORK-TESTER","description":"CABLE-RJ45-NETWORK-TESTER","price":50,"cost":35,"vendor":{"id":104,"identifier":"","name":"","_info":{"company_href":""}},"_info":{"lastUpdated":"","updatedBy":""}}': ''
}

Notice that the JSON string sent from the client side is now the object key :(
Any help would be awesome

A: All good, fixed this by changing the headers and stepping away from encoding:
    let headers = {
        body: CircularJSON.stringify(product),
        headers: { "Content-Type": "application/json" },
        method: "POST"
    }


text:
Q: Trigonometric idnetity IF $\sin \alpha = 3 \sin (\alpha+2\beta)$, then the value of $\tan (\alpha+\beta)+2 \tan \beta=$?
ATTEMPT:
$\sin \alpha = 3 (\sin (\alpha+\beta) \cos \beta + \cos (\alpha+\beta) \sin \beta)$
Dividing by $\cos\beta \cos(\alpha+\beta)$
$$
\frac{\sin \alpha}{\cos \beta \cos(\alpha+\beta)}=3[\tan(\alpha+\beta)+\tan\beta]
$$
Putting  $\tan(\alpha+\beta)+2\tan \beta= X$
$$
\frac{\sin\alpha}{\cos\beta \cos(\alpha+\beta)}=3[X-\tan\beta]
$$

A: $$SinA=3\left(SinA\,Cos2B+CosA\,Sin2B\right)$$ Divide throughout by $CosA$ we get
$$TanA=3\left(TanA\,Cos2B+Sin2B\right)$$ Use $Cos2B$ and $Sin2B$ in terms of $Tan$ and then Simplify

A: $$\frac{\sin(\alpha+2\beta)}{\sin\alpha}=\frac13$$
Applying Componendo and dividendo,  $$\frac{\sin(\alpha+2\beta)-\sin\alpha}{\sin(\alpha+2\beta)+\sin\alpha}=\frac{1-3}{1+3}$$
Applying Prosthaphaeresis Formulas,
$$\frac{2\sin\beta\cos(\alpha+\beta)}{2\cos\beta\sin(\alpha+\beta)}=-2$$
Can you take it home from here?


text:
Q: Cannot pass variables to django home template from another template in app I've got a simple view, form and 2 templates in my django (1.9.2) project
The template that view is passed works like a charm, iterates through and displays wanted value without problems.
Yet when I want to include this template into another one the iteration does not occur. I've tried using {% include with %} but maybe I'm not doing it right.
The template that is the for the homepage is placed in project template folder, while the template to be included is inside the app
news/models.py:
class News(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    posted = models.DateField(db_index=True, auto_now_add=True)

def __unicode__(self):
    return '%s' % self.title

news/views.py:
from news.models import News
from django.shortcuts import render
from django.template import RequestContext

def news(request):
    posts = News.objects.all()
    return render(request, 'news.html',{'posts':posts })

news/templates/news.html:
{% load i18n %}
{% block content %}

News

    :D
    {% for post in posts %}
        {{ post.title }}
        {{ post.body }}
    {% endfor %}
{% endblock content %}

templates/home.html:
{% extends "base.html" %}
{% load i18n %}
{% block content %}

  {% include "news.html" with posts=posts %}

{% include "footer.html" %}
{% endblock content %}

When checking at http://127.0.0.1:8000/news/ everything is fine,
but at http://127.0.0.1:8000/ only :D is displayed
No idea how to tackle this
Thanks :^)
EDIT:
For the Home I actually use only template and in urls it looks like this:
url(r'^$', TemplateView.as_view(template_name='pages/home.html') ,  name="home")

Also for the base I use cookie-cutter django from cookiecutter-django
Should I define view somewhere for home also?

A: It seems that when you are using
url(r'^$', TemplateView.as_view(template_name='pages/home.html') ,  name="home")

You are not defining posts at all. To make it working you have to pass context with posts to this name="home" view but you are using default as_view which doesn't pass posts.
I would make it like so:
news/urls.py:
url(r'^$', views.home,  name="home")

news/views.py:
from news.models import News
from django.shortcuts import render
from django.template import RequestContext

def home(request):
   posts = News.objects.all()
   return render(request, 'home.html', {'posts':posts })

news/templates/news.html:
{% load i18n %}
{% block inner_content %}

News

    :D
    {% for post in posts %}
    {{ post.title }}
    {{ post.body }}
    {% endfor %}
{% endblock inner_content %}

templates/home.html:
{% extends "base.html" %}
{% load i18n %}
{% block content %}

  {% include "news.html" with posts=posts %}

{% include "footer.html" %}
{% endblock content %}


text:
Q: django under virtualenv causing importerror In ubuntu lucid ,I installed python2.7.5 and set up a virtualenv .In the terminal I typed workon envpy275 and using pip installed these sw from requirements file
python==2.7.5
Django==1.4.3
South==0.7.6
distribute==0.6.28
dj-database-url==0.2.1
django-registration==0.8
numpy==1.4.1
matplotlib==1.2.0
psycopg2==2.4.6
python-memcached==1.48
simplejson==3.0.7
wsgiref==0.1.2

$workon envpy275
(envpy27)me@ubuntu:~/dev/python/django/myapp$ pip install -r requirements.txt

This installed these softwares into ~/.virtualenv/envpy275/lib/python2.7/site-packages.
My system already has Django1.4 at /home/me/Django-1.4.and my .bashrc file has
PYTHONPATH=/home/me/Django-1.4
PYTHONPATH=$PYTHONPATH:/home/me/dev/python/django/myapp

since my project settings file is in /home/me/dev/python/django/myapp/mysite directory
I set the DJANGO_SETTINGS_MODULE as below
 (envpy27)me@ubuntu:~/dev/python/django/myapp$ export DJANGO_SETTINGS_MODULE='mysite.setings'

Then,at the terminal ,I try to run the django server
(envpy27)me@ubuntu:~/dev/python/django/myapp$ python manage.py runserver

This produced the following warning and error
/home/me/.virtualenvs/envpy275/lib/python2.7/site-packages/pytz/__init__.py:35: UserWarning:
Module django was already imported from
    /home/me/Django-1.4/django/__init__.pyc, but /home/me/.virtualenvs/envpy275/lib/python2.7/site-packages
is being added to sys.path
 from pkg_resources import resource_stream
  ...
  ...
 file "/home/me/Django-1.4/django/conf/__init__.py", line 95, in __init__
  raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
 ImportError: Could not import settings 'mysite.setings' (Is it on sys.path?): No module named setings

A: You may have a typo where you set DJANGO_SETTINGS_MODULE to mysite.setings - normally this would be mysite.settings pointing to a file mysite/settings.py


text:
Q: What can we say about the order of a group given the order of two elements? If I know that a group of finite order has two elements $a$ and $b$ s.t. their orders are $6$ and $10$, respectively. What statements can be made regarding the order of the group?
I know by Lagrange's that the elements should divide the order of the group, so I've taken the $\operatorname{lcm}$. I think the order of our group should be a multiple of $30$. But I'm thinking there's more I can say.

A: You can't say anything about the order of the group except that it must be divisible by $6$ and $10$.  In fact, nothing can be said about the order of $ab$, either!  (see the commentary here.)