text:
Q: Batch rename multiple files with hyphenated names I have a series of files that I download/process regularly and need to use a batch file to rename. Each filename is something like word-word-word-datetime.csv. There is always a '-' between words and always -datetime before the '.csv' file extension. I need to remove the -datetime so that the files are named word-word-word.csv. In some cases there might be just one word before the -datetime but there can be a string of many words as well. I download these files and move them to a specific folder for processing, and there is already a batch file in the folder that I need to modify to also rename the files.
For example, I need the filenames below:
this-is-a-file-20200804134809.csv
another-file-20200804134750.csv
some-other-file-20200804134699.csv
file-20200804134389.csv

To be renamed to:
this-is-a-file.csv
another-file.csv
some-other-file.csv
file.csv

This answer is almost exactly what I need, but I'm not familiar enough with the syntax to modify it for renaming files with multiple hyphenated words (code from linked answer copied below).
@echo off

for /F "tokens=1,* delims=-" %%a in ('dir /A-D /B "*.mp4"') do (
    echo move "%%a-%%b" "%%a%%~xb"
)

A: I was able to rename all of the .csv files in my folder, truncating the name to remove the last 15 characters as suggested by @Compo.
@echo off
setlocal enabledelayedexpansion
for %%f in (*.csv) do if %%f neq %~nx0 (
    set "filename=%%~nf"
    ren "%%f" "!filename:~0,-15!%%~xf"
)

A: Here's a more robust example, using the advice I provided in the comments:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /F "EOL=| Delims=" %%G In ('Dir /B /A-D *-??????????????.csv ^
 ^|"%__AppDir__%findstr.exe" /IR ^
 "\-19[0123456789]*\.csv$ \-20[0123456789]*\.csv$"') Do (
    Set "BaseName=%%~nG"
    SetLocal EnableDelayedExpansion
    Ren "%%G" "!BaseName:~,-15!%%~xG"
    EndLocal
)


text:
Q: Linq code is not compiling in aspx page (IIS 10/.ASP .NET 4.7.2) First, my apologies - I am not a C# or asp developer, but I know enough to be dangerous. I inherited a couple of aspx pages on our website that were developed by people no longer with the company. These pages have worked for years running in IIS 7.5 on Windows 2012 and ASP .NET 4.5. We recently upgraded to IIS 10, Windows 2016, and ASP .NET 4.7.2. These two pages work just as before except when they hit LINQ calls. If I comment that code out, the pages work (as much as they can without the LINQ functions).
What I'm trying to understand is what is missing that would cause these to fail. I do not have access to Visual Studio due to corporate restrictions, so remote debugging is not an option. I have been trying to figure this out the old fashion way by commenting stuff out to narrow down the problem. As soon as I uncomment the LINQ calls, it fails. Based on the stack trace below, it looks something is missing that causes it to not compile. As best I can tell, I have all the DLLs that I had before. I have searched other threads, but they all seem to talk about updating the VS project. I don't have VS, just an aspx page, again that worked in earlier incarnations of IIS and ASP .NET.
Exception information:
    Exception type: HttpCompileException
    Exception message: c:\inetpub\wwwroot\STPUserComapre.aspx(187): error CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
   at System.Web.Compilation.AssemblyBuilder.Compile()
   at System.Web.Compilation.BuildProvidersCompiler.PerformBuild()
   at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
   at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
   at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
   at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound)
   at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp)
   at System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)
   at System.Web.HttpApplication.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Server connection error message for inactive server reappears regularly This is the message that reappears very often:

The server in question ("Knorke") is my old MBP, which I reset (clean install) and sold about two years ago. On my current MBP, I connected to the old machine sporadically via AFP because I used it for testing purposes, being a spare machine and all.
Ever since then, I have not found a way to prevent this message from appearing occasionally. I tried cleaning the "recent servers" menu (from Finder's ⌘+K) and have been googling the problem on and off, but have found no solution.
Oddly enough, the message consistently reappears when I start Slack.app, and I believe it also occurs with other Electron-based apps, but that's just a guess on my part.
I am hesitant to try out all kinds of "cache cleaners" and the likes that float around on the internet, as the general opinion seems to be that they're doing more harm than good, so I would prefer a specific solution for this.

A: You issue is most likely a problem with login items.

*

*Take note of your current login items

*Try removing all login items and test.
3 . Add them back one by one until you find the one causing the problem.


text:
Q: Disable drag specific item I found a nice script, http://mjsarfatti.com/sandbox/nestedSortable/, which is almost perfect for me. I just can't find out one little thing.
I want to disable some items to drag. I looked in the readme, tried some options, but didn't get what I wanted.
Could someone tell me how I can disable an item to be dragged?

A: All the instructions are here http://jqueryui.com/sortable/#items
In your code that I extracted and put here http://jsfiddle.net/axgTF/1/
change
items: "li",

to
items: "li:not(.dontsortme)",

and add that class to the items you want to disable from sorting, e.g.

Item 5

Which you can see working here http://jsfiddle.net/axgTF/2/ (Item 5 is disabled)

A: Add a class like static to the
 elements which should not be moved then in the nestedSortable configuration specify items: 'li:not(.static)'.
Demo: Fiddle.
Here the Item 5 Cannot be moved.


text:
Q: loading docker container from existing project, mongo will not connect to database Ubuntu 18.04 At first I had a problem where the mongod service stopped working altogether. Thereupon I completely uninstalled mongodb and reinstalled it and followed instructions per this thread: https://askubuntu.com/questions/921753/failed-to-start-mongod-service-unit-mongod-service-not-found
This caused the mongod service to finally start.
In order for it to work, I also had to follow instructions from this thread:
mongo - couldn't connect to server 127.0.0.1:27017
So far this configuration has worked only 1 time and that was after I followed the instructions to remove the .lock file in the mongod directory and then repair mongod.
I also tried to remove the sock file like stated here: MongoDB Failing to Start - ***aborting after fassert() failure
Full project reset
Then I tried just disconnecting the project entirely; close nodemon for backend, exit ng serve on frontend, stop and remove mongo docker container... And tried again. Here is my step-by-step process after everything should have been fixed:
Restart mongod service
sudo service mongod restart

Restart frontend (executed from frontend directory)
ng serve frontend

Restart backend (executed from backend directory)
npx nodemon backend

Restart mongo container (executed from deploy directory, mongo is the docker container name, I'm building it from existing provided deploy script)
sudo docker-compose up -d mongo
sudo docker ps -a # check container was created and is running

Debugging information:

sudo service mongod status

    Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset:
    Active: active (running) since Thu 2020-01-09 11:21:43 CET; 3min 40s ago
      Docs: https://docs.mongodb.org/manual
  Main PID: 17242 (mongod)
    CGroup: /system.slice/mongod.service
            └─17242 /usr/bin/mongod --config /etc/mongod.conf

 janv. 09 11:21:43 junior-LIFEBOOK-E752 systemd[1]: Started MongoDB Database Server

 sudo mongod2020-01-09T11:25:45.983+0100 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] MongoDB starting : pid=17727 port=27017 dbpath=/data/db 64-bit host=junior-LIFEBOOK-E752
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] db version v4.2.2
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] git version: a0bbbff6ada159e19298d37946ac8dc4b497eadf
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.1.1d  10 Sep 2019
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] allocator: tcmalloc
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] modules: none
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] build environment:
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten]     distmod: ubuntu1804
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten]     distarch: x86_64
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten]     target_arch: x86_64
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] options: {}
 2020-01-09T11:25:45.987+0100 E  STORAGE  [initandlisten] Failed to set up listener: SocketException: Address already in use
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] now exiting
 2020-01-09T11:25:45.987+0100 I  CONTROL  [initandlisten] shutting down with code:48

sudo mongo

  connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
  Implicit session: session { "id" : UUID("8e813fc2-049c-440d-83ce-0b1d8516c4d0") }
  MongoDB server version: 4.2.2
  Server has startup warnings:
  2020-01-09T11:21:43.352+0100 I  STORAGE  [initandlisten]
  2020-01-09T11:21:43.352+0100 I  STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
  2020-01-09T11:21:43.352+0100 I  STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
  2020-01-09T11:21:44.848+0100 I  CONTROL  [initandlisten]
  2020-01-09T11:21:44.848+0100 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
  2020-01-09T11:21:44.848+0100 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
  2020-01-09T11:21:44.848+0100 I  CONTROL  [initandlisten]

  Enable MongoDB's free cloud-based monitoring service, which will then receive and display
  metrics about your deployment (disk utilization, CPU, operation statistics, etc).

  The monitoring data will be available on a MongoDB website with a unique URL accessible to you
  and anyone you share the URL with. MongoDB may use this information to make product
  improvements and to suggest MongoDB products and deployment options to you.

  To enable free monitoring, run the following command: db.enableFreeMonitoring()
  To permanently disable this reminder, run the following command: db.disableFreeMonitoring()

So something weird is happening here, it doesn't find the database from the project and I have no clue why. As far as I can see, it creates a new database including my system details.
How can I fix this please and connect to the project database? I can't move further until I do.

A: it's been resolved. First I found out I didn't need to have the mongod service running locally because mongo was already included in the docker container. But actually this wasn't a database issue at all. There were a few things going wrong like there was a proxy but the command had been changed to execute the connection, endpoints were on localhost but weren't supposed to be, and the content I was expecting to see had been hidden by a careless push from another developer. Fun times! But we can move on now. Thanks to the people who tried to help!


text:
Q: Is there a way to generate a BigQuery table based on JSON data? Let's say we have a simple JSON array as follows:
[
  {
    "id": "0001",
    "customer": {
      "name": "John",
      "age": 30,
      "cars": [
        "Ford",
        "BMW",
        "Fiat"
      ]
    }
  },
  {
    "id": "0002",
    "customer": {
      "name": "Mary",
      "age": 22,
      "cars": [
        "Ford",
        "Fiat"
      ]
    }
  }
]

Is there a way to take that JSON array to automatically create a BigQuery table, infer its schema and populate it with the JSON values? A native solution would be nice but it can be something else too. The resulting schema should look like this:

And, ideally, we should also be able to see in the table the data extracted from the JSON array:

I don't see any technical impediment to that kind of requirement but I haven't found any off-the-shelf solution whereas I know there's a need for it around me.

A: While creating/loading table using JSON data file, JSON data must be newline delimated ie. each object must be in a separate line in the file. (As mentioned by @guillaume)
BQ doesn't support loading direct JSON array to create records and hence it will result in error while parsing the JSON(array) data file during the load job.
Hence, the working JSONL file in your case would be:
{ "id": "0001", "customer": { "name": "John", "age": 30, "cars": [ "Ford","BMW","Fiat"]}}
{ "id": "0002", "customer": { "name": "Mary", "age": 22, "cars": [ "Ford", "Fiat"]}}

Detailed information on Loading JSON data can be found in this Google documentation.


text:
Q: How to prove the inequality $\iint_{x^2+y^2 \leq 1} e^{x^2+y^2}dxdy \leq (\int_{\sqrt{\pi}/2}^{\sqrt{\pi}/2} e^{x^2}dx)^2$ I am having trouble proving the following inequality.
$$
\iint_{x^2+y^2 \leq 1} e^{x^2+y^2}\mathrm{d}x\mathrm{d}y \leqslant {\left(\int_{\sqrt{\pi}/2}^{\sqrt{\pi}/2} e^{x^2} \mathrm{d}x\right)}^2
$$
I have tried the following approaches but all failed.

*

*$$0\leq x\leq 1\implies e^{x^2}\geq xe^{x^2}=\left(\frac{1}{2} e^{x^2}\right)'$$
this failed because $xe^{x^2}$ is too small
sage: numerical_integral(x*exp(x^2),0,sqrt(pi)/2)
(0.5966400253690076, 6.6240349357760975e-15)
sage: numerical_integral(exp(x^2),0,sqrt(pi)/2)
(1.1849166170926333, 1.3155217105571918e-14)

*

*$${\left(\int_{-L}^L e^{x^2}\mathrm{d}x\right)}^2=\iint_{\begin{subarray}{l}{-L\leq x\leq L\\ -L\leq y\leq L}\end{subarray}} e^{x^2+y^2}\mathrm{d}x\mathrm{d}y\leq \iint_{x^2+y^2\leq L^2} e^{x^2+y^2}\mathrm{d}x\mathrm{d} y$$
The area $x^2+y^2\leq L^2$ is too small.

*

*partial(prefix) sum taylor series of $e^{x^2}$, theoretically this can lead to a big enough estimation, however it involves too much calculation.

A: so:
$$I_1=\iint\limits_{x^2+y^2\le 1}e^{x^2+y^2}\,dxdy=\int\limits_0^{2\pi}\int\limits_0^1re^{r^2}\,drd\theta$$

$$I_2=\left(\int\limits_{-\sqrt{\pi}/2}^{\sqrt{\pi}/2}e^{x^2}\,dx\right)^2=\int\limits_{-\sqrt{\pi}/2}^{\sqrt{\pi}/2}\int\limits_{-\sqrt{\pi}/2}^{\sqrt{\pi}/2}e^{x^2+y^2}\,dxdy=\int\limits_0^{2\pi}\int\limits_0^{\sqrt{\pi/2}}re^{r^2}\,drd\theta$$
now since the domains for $\theta$ are the same we can ignore those, and since the functions of $r$ are the same we only really care about comparing the domains, since we know that $\exp(r^2)>0$ and so it comes down to $\sqrt{\pi/2}>1$ so we are integrating a strictly positive function over a larger domain and so the integral will be greater.


text:
Q: Where do TIE Fighters generate thrust? TIE Fighters are an extremely recognizable part of the Star Wars universe, but there's something about them that bothers me.
Where do TIE Fighters generate their thrust?
Based on the way TIE Fighters move in the battlefield, you would think they operate similarly to most other Star Wars universe propulsion ships.
They have thrusters in the back to push the craft forward, yet they can move along an X and Y axis.
 An example being whenever the Millennium Falcon or an X-Wing takes off after being docked or "parked". They rise up vertically into the air, rotate around, and then blast off using the thrusters on the back of their ship.
These ships have obvious ion engines that display a bright glow where the thrust is coming from.
Imperial Cruisers use these glowing propultion systems, as seen here:

However, in the same picture, you see some TIE Fighters heading towards the Cruiser.
They don't have any glowing propulsion spots.
Here is a better look at the back end of a TIE Fighter:

This part of the ship does not glow when it is flying around in space.
So, back to the original question: Where do TIE Fighters generate their thrust?
TIE stands for "Twin Ion Engine".
Ion Engines contain "no moving parts".
"All TIE series starfighters had two or more ion engine outlets..."

A: The little red spots on the TIEs in the first picture are the main engine outlets. They are clearer here:

The second picture doesn't show the engines well because the engines do not appear to be powered. The two pieces on the central cockpit ball that are the darkest appear to be in the correct position for the engines.
Although there were only two engine outlets, Wookieepedia's article on the SIE-TIE engine cites The Essential Guide to Warfare to say that the engine

utilized microparticle accelerators to agitate ionized gases to relativistic velocities, and featured independently articulated ion stream deflector manifolds for pinpoint maneuvering accuracy.

So that's how they maneuvered.
As for why the TIE engines look different than the engines on other starfighters like the X-Wing, the most likely reason is that the TIE fighter is considerably less massive than the X-Wing (the TIE design famously omitted shields and life support systems to reduce mass) and can therefore use smaller and fewer engines to achieve the same thrust and maneuverability.
It could also be that the X-Wing uses a "fusial thrust engine" rather than an ion engine like the TIE (on the other hand, the Y-Wing uses an "ion jet engine", but its engines look more like the X-Wing than the TIE fighter).


text:
Q: No installed build tools found. Install the Android build tools version 19.1.0 or higher I want to install Cordova and I got a error that cordova cannot find build tools.
I install android sdk 24 and set Android-Home, but error is remained.
How can i solve it?


text:
Q: Pure CSS fold corner animation cross-browser compatible I've found a very interesting way to do a pure css animated folding page-tip. It works perfectly in Chrome but it does not in IE or Firefox.
I've tried to figure out where the compatibility problem come from but unfortunately I am not very experienced in CSS and I cannot find it...
Any clue about how to solve it or an alternative way to get a similar effect is highly appreciated!
here is the CodePen
UPDATE:
I've uploaded the CodePen with the code that Bilal suggested. Now it's looking better but still make some weird things. If I remove the div #fpc_corner-contents it's possible to see the folded corner so I think the problem come from some overlying components...
Updated CodePen

A: i did not try but it should work

h1 { color: #900; font-size: 16pt;/* trivial */  }
a.trivial {color: #C55;/* trivial */}
#fpc_effect-back {
background-color: #eeeef4; /* some background color to match corner inside's */
width: 100%;/* trivial */
font: 12pt arial,sans-serif,helvetica,verdana;/* trivial */
color: #666;//trivial
}
#fpc_effect-back * {
box-sizing: border-box;
}
#fpc_box {
width: 500px;/*any relative or absolute*/
position: relative;
background-color: #FFF;
}
#fpc_content {
 padding: 20px;
}
#fpc_content:before {
content:"";
width: 80px;
height: 80px;
float: right;
}
#fpc_page-tip:before, #fpc_page-tip:after {
background-color: #FFF;
position: absolute;
display: block;
z-index: 2;
border-top-right-radius: 60%;
width: 50%;
height: 50%;
content: "";
}
#fpc_page-tip:before {
right: 100%;
top: 0%;
background: -webkit-radial-gradient(-180% 200%, circle, rgba(255,255,255,0) 85%, rgba(0,0,0,.1) 93%);
background: -moz-radial-gradient(-180% 200%, circle, rgba(255,255,255,0) 85%, rgba(0,0,0,.1) 93%);
background: -o-radial-gradient(-180% 200%, circle, rgba(255,255,255,0) 85%, rgba(0,0,0,.1) 93%);
}
#fpc_box:hover #fpc_page-tip:before {
border-right: solid 1px #fff;
}
#fpc_box div#fpc_corner-box:hover #fpc_page-tip:before {
border-right: solid 2px #fff;
}
#fpc_page-tip:after {
top: 100%;
right: 0%;
background: -webkit-radial-gradient(-250% 320%, circle, rgba(255,255,255,0) 85%, rgba(0,0,0,.10) 93%);
background: -moz-radial-gradient(-250% 320%, circle, rgba(255,255,255,0) 85%, rgba(0,0,0,.10) 93%);
background: -o-radial-gradient(-250% 320%, circle, rgba(255,255,255,0) 85%, rgba(0,0,0,.10) 93%);
}
#fpc_box:hover #fpc_page-tip:after {
border-top: solid 1px #fff;
}
#fpc_box div#fpc_corner-box:hover #fpc_page-tip:after {
border-top: solid 2px #fff;
}
#fpc_corner-box {  /* edit these sizes for the default revealing corner size */
height: 20px;
width: 20px;
right: 0;
top: 0;
position: absolute;
overflow: visible;
}
#fpc_box:hover #fpc_corner-box { /* edit corner size (First animation, when the whole page is rollovered) */
height: 50px;
width: 50px;
}
#fpc_box div#fpc_corner-box:hover { /* edit corner size (Second animation, when the corner itself is rollovered) */
height: 100px;
width: 100px;
}
#fpc_corner-box:before {
position: absolute;
top: 0;
right: 0;
content: "";
display: block;
width: 133%;
height: 133%;
}
#fpc_corner-contents:after {
position: absolute;
top: 0;
right: 0;
content: "";
background:  -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0) 37%, #DDD 62%, rgba(230, 230, 230, 0.1) 64%, rgba(255, 255, 255, 0) 67%), -webkit-radial-gradient(-50% 150%, circle, transparent 74%, rgba(0, 0, 0, 0.2) 74%, transparent 81%);
background:  -moz-linear-gradient(45deg, rgba(255, 255, 255, 0) 37%, #DDD 62%, rgba(230, 230, 230, 0.1) 64%, rgba(255, 255, 255, 0) 67%), -webkit-radial-gradient(-50% 150%, circle, transparent 74%, rgba(0, 0, 0, 0.2) 74%, transparent 81%);
background:  -o-linear-gradient(45deg, rgba(255, 255, 255, 0) 37%, #DDD 62%, rgba(230, 230, 230, 0.1) 64%, rgba(255, 255, 255, 0) 67%), -webkit-radial-gradient(-50% 150%, circle, transparent 74%, rgba(0, 0, 0, 0.2) 74%, transparent 81%);
display: block;
width: 133%;
height: 133%;
}
#fpc_page-tip {
position: absolute;
top: 0;
right: 0;
content: "";
background: -webkit-linear-gradient(45deg, #ddd 17%, #dfdfdf 18%, #f5f5f5 30%, #f8f8f8 34%, #eee 39%, rgba(200,200,200,0) 41%);
background: -moz-linear-gradient(45deg, #ddd 17%, #dfdfdf 18%, #f5f5f5 30%, #f8f8f8 34%, #eee 39%, rgba(200,200,200,0) 41%);
background: -o-linear-gradient(45deg, #ddd 17%, #dfdfdf 18%, #f5f5f5 30%, #f8f8f8 34%, #eee 39%, rgba(200,200,200,0) 41%);
display: block;
width: 100%;
height: 100%;
}
#fpc_corner-button {
position: absolute;
width: 7em;
top: 0;
right: 0;
background-color: #900;
color: #fff;
font-family: Verdana, Geneva, sans-serif;
text-align: center;
padding: 8px 5px;
border-radius: 5px;
display: inline-block;
font-size: 11px;
}
#fpc_corner-contents {
width: 125%;
position: absolute;
display: block;
overflow: hidden;
-webkit-mask: -webkit-linear-gradient(45deg, transparent 49%, #000 53%);
-moz-mask: -moz-linear-gradient(45deg, transparent 49%, #000 53%);
-o-mask: -o-linear-gradient(45deg, transparent 49%, #000 53%);
top: 0;
right: 0;
height: 125%;
}
#fpc_corner-contents:before {
content: "";
position: absolute;
top: 0;
right: 0;
content: "";
display: block;
width: 100%;
height: 100%;
background-color: #eeeef4; /* Match this background color to #fpc_effect-back */
}
#fpc_corner-box, #fpc_corner-contents, #fpc_page-tip {
-webkit-transition-property: all;
-webkit-transition-duration: .3s;
-webkit-transition-timing-function: cubic-bezier(0, 0.35, .5, 1.7);
 -moz-transition-property: all;
-moz-transition-duration: .3s;
-moz-transition-timing-function: cubic-bezier(0, 0.35, .5, 1.7);
 -o-transition-property: all;
-o-transition-duration: .3s;
-o-transition-timing-function: cubic-bezier(0, 0.35, .5, 1.7);
}
#fpc_corner-button strong {
font-size: 13px;
font-weight: bold;
display: block;
}


text:
Q: enabling lazy load for angular component

            <dashboard-header></dashboard-header>

             **<dashboard-body></dashboard-body>**

        <dashboard-aside class="dashboard-aside-flex-container"></dashboard-aside>

How can I make dashboard-body lazy load, can some some share the sample code or any link available where I can refer.

A: I think you can refer to the following post.
https://medium.com/angular-in-depth/lazy-load-components-in-angular-596357ab05d8
But it's a little bit complicated. So you can rather use ngIf and implement a conditional rendering with some boolean variable.


text:
Q: Extracting every 3rd data in an array I have thousand of data for x and y, for this case i will just use 12 data.
The array are used to plot a graph
x = np.array([1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000])
y = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
py.plot(x,y)

How can i extract every [3] multiplication for me to plot? For Example
x = np.array([3000,6000,9000,12000])
y = np.array([3,6,9,12])
py.plot(x,y)

How can i extract every [5] multiplication for me to plot ? For Example
x = np.array([5000,10000])
y = np.array([5,10])
py.plot(x,y)

A: Extract every third item starting with the third item (one dimensional array)
x[2::3], y[2::3]

Extract every fifth item starting with the fifth item (one dimensional array)
x[4::5], y[4::5]

A: If you're just asking how to extract every x-th item, slicing accepts a step argument as well as a start and a stop.
For example:
In [1]: import numpy as np

In [2]: np.arange(10)
Out[2]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [3]: x = np.arange(10)

In [4]: x[::2]
Out[4]: array([0, 2, 4, 6, 8])

In [5]: x[::3]
Out[5]: array([0, 3, 6, 9])

In [6]: x[3::3]
Out[6]: array([3, 6, 9])

If you're asking how to find even multiples, you can use boolean indexing.
For example:
In [7]: x[x % 3 == 0]
Out[7]: array([0, 3, 6, 9])

A: Using numpy.where:
>>> x = np.array([1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000])
>>> y = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
>>> idxs = np.where(x % 3 == 0)
>>> x[idxs]
array([ 3000,  6000,  9000, 12000])
>>> y[idxs]
array([ 3,  6,  9, 12])

>>> x[x % 3 == 0]
array([ 3000,  6000,  9000, 12000])

A: Use a function that returns the qualified values. For example:
def filter_indices(lst, value):
    return [v for _, v in enumerate(lst) if v % value == 0]

Result:
>>> filter_indices(l, 3)
[3, 6, 9, 12]

Alternatively, use the np.where function:
indices = np.where(x % 3 == 0)
py.plot(x[indices], y[indices])


text:
Q: How can I vary a parameter over time for a dynamical system in Python? I'm trying to have a parameter that changes based on the current time in terms of the model.
I set up a function:
def func(state,t):
  x = state[0]
  y = state[1]
  z = state[2]

  Iapp = 0.7

  xd = ... + Iapp
  yd = ...
  zd = ...

I want to have Iapp vary over time. Namely, I need it to be -0.7 from time 50 to time 500.
My current efforts that have produced literally no change in my plots:
for t in range(50,500):
    Iapp = -0.7
else:
    Iapp = 0.7

Any ideas?

A: Your code will set Iapp to -0.7 450 times, then set it to 0.7. This is why you don't see any change. What you need is an if statement:
if 50 <= t <= 500:
    Iapp = -0.7
else:
    Iapp = 0.7

Or, if you want a one-liner:
Iapp = -0.7 if 50 <= t <= 500 else 0.7

A: Another approach is to define the time varying parameter outside the ODE. This allows you to change the parameters without modifying the ODE function. One way to do this is to pass the forcing parameter as an array the same length as the time array. Assuming t0=0, Change your call to:
import numpy as np

def func(state, t, Iapp_all, sampling_rate):
    Iapp = Iapp_all[np.floor(t * sampling_rate)]
    ...

Example usage with scipy's odeint.
from scipy.integrate import odeint

y0 = [0, 0]
sampling_rate = 1.
t = np.arange(500) / sampling_rate
Iapp_all = -.7 * np.ones_like(t)
Iapp_all[:51] = .7
y = odeint(func, y0, t, args=(Iapp_all, sampling_rate))


text:
Q: How do I stop error on vba that has previously worked I have been using a simple invoicing system via excel that has been working perfectly for the last 18 months.  I had to have a new processor installed into my laptop yesterday and now I am getting a debug error. I have also installed (pdf hub as this was recommended when I googled the issue).
this is the line I am now getting a debug error on
Ws.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FilePath & "\" & FileName & ".pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False

My error message is:

Run-time error 1004 file not found?

Every other command is working perfectly on this vba.
Please can anyone help?


text:
Q: purrr - how to apply recursively a function n_times over one value I want to apply a function f() to one value n times.
For example, if I wanted to apply this function 5 times, I'd do something like:
f(f(f(f(f(1)))))

Is there any purrr solution for that?
For example, some function y such that:
y( 1, f, 5)

A: Here's one way using purrr::reduce. It's a bit of cheating (maybe not?) but seems to work. In the below demo I am recursively adding 3 to my initial value 5 times -
library(purrr)

x <- 1
n <- 5

rep(x, n+1) %>% reduce(function(x, y) x + 3)
# [1] 16

Here's the documentation for reduce -

.x     A list or atomic vector.
.f     For reduce(), a 2-argument function. The function will be passed
  the accumulated value as the first argument and the "next" value as
  the second argument.

By design reduce requires an x and y argument. While you must pass both to your function, you can choose not to use y like I have done. This means your function uses only the accumulated value recursively.
The intermediate steps can be seen using purrr::accumulate -
rep(x, n+1) %>% accumulate(function(x, y) x + 3)
# [1]  1  4  7 10 13 16

Notice that the function wasn't applied to the first instance and that's why you need n+1 in rep to get correct result.
EDIT 1:
Here's a simplified version of above logic -
reduce(1:n, function(x, y) x + 3, .init = x)
# [1] 16

accumulate(1:n, function(x, y) x + 3, .init = x)
# [1]  1  4  7 10 13 16

EDIT 2:
Here's a similar but simpler base R solution -
Reduce(function(x, y) x + 3, 1:n, init = x)
# [1] 16

A: Could use purrr::map and put that in a loop in y?
f <- function(n) n^2 # or any other function of n

y <- function(n, fun, k = 1) {

  x <- n
  for (i in 1:k) {
    x <- unlist(purrr::map(x, fun))
  }

  return(x)

}

# then to do f five times would be:
y(1, f, 5)

To make more robust you'd probably put some error handling in for the arguments.

A: This is the solution I have found. It looks a little verbose, but it works.
  reduce(
       rerun(5, f),
  compose)(1)


text:
Q: Best fit formula to estimate the task execution duration I am trying to figure out a best estimation calculation for my newly creating tasks running parallel on the same time..
As a first step of my calculation my formula will be Duration(D) = Count(c)/networkthroughput(T). So for the given starting time I can find the duration for 1 task easily and for the next task with the same time, Am doing some calculation myself and I am expecting some idea or relevant formula for the same for the attached image.

And here i need to calculate the duration for each task separately..Idea's / Solutions are welcomed.
Thank you.

A: Why don't you create a function that you pass in your function to time as an argument, then wrap the function call in a couple of date variables?
//Assuming functionToTime is marked async Task
public async Task<TimeSpan>(Action functionToTime){
    DateTime startTime = DateTime.Now;
    await functionToTime;
    return (DateTime.Now - startTime);
}

If functionToTime in not async, you would want to call the function by:
await Task.Run(() => functionToTime);

You can change it to meet your needs, but I think this should be a good starting point.


text:
Q: Set font style for entire word document - VBA I'm trying to figure out how to set the font style for an entire word document, exactly the way it's done by choosing a style preset in the menu:

Since I've already made a macro that converts the entire document word for word, what I'm trying to accomplish with this is changing all the preset tiles (Normal, No Spacing, Title, Heading 1, etc.) to match this existing preset, and not the old presets (with the old fonts).
Is this possible, and what object do I modify to accomplish this?

A: Try this ...
Sub ChgFontInAllStyles()
Dim sty As Word.Style
For Each sty In ActiveDocument.Styles
    If sty.InUse And sty.Type = wdStyleTypeParagraph Then
        sty.Font.Name = "Arial"
    End If
Next
End Sub

A: What you show in the screen shot is an Office Theme. This is not the same as a Word style, although some of the settings do "filter through" to the built-in styles and custom styles that base on these.
Themes is a complex topic if it's a question of defining a custom theme programmatically. If all you want to do is apply an existing theme, then:
Dim sThemePath as String
sThemePath = "C:\Program Files\Microsoft Office\Document Themes 14\Equity.thmx"
ActiveDocument.ApplyDocumentTheme sThemePath

It's necessary to specify the entire path. In the sample code this is the default path for the built-in Office themes for Office 2010.


text:
Q: NHibernate: Using value tables for optimization AND dynamic join My situation is next: there are to entities with many-to-many relation, f.e. Products and Categories. Also, categories has hierachial structure, like a tree. There is need to select all products that depends to some concrete category with all its childs (branch). So, I use following sql statement to do that:

SELECT * FROM Products p
WHERE p.ID IN (
    SELECT DISTINCT pc.ProductID FROM ProductsCategories pc
    INNER JOIN Categories c ON c.ID = pc.CategoryID
    WHERE c.TLeft >= 1 AND c.TRight <= 33378
)

But with big set of data this query executes very long and I found some solution to optimize it, look at here:

DECLARE @CatProducts TABLE (
    ProductID int NOT NULL
)

INSERT INTO @CatProducts
    SELECT DISTINCT pc.ProductID FROM ProductsCategories pc
    INNER JOIN Categories c ON c.ID = pc.CategoryID
    WHERE c.TLeft >= 1 AND c.TRight <= 33378

SELECT * FROM Products p
INNER JOIN @CatProducts cp ON cp.ProductID = p.ID

This query executes very fast but I don't know how to do that with NHIbernate. Note, that I need use only ICriteria because of dynamic filtering\ordering.
If some one knows a solution for that, it will be fantastic. But I'll pleasure to any suggestions of course.
Thank you ahead,
Kostya

A: Answer is simple - adding index to ProductsCategories table for ProductId column fixed the problem.


text:
Q: How to hook Jackson ObjectMapper with Guice / Jersey I can't seem to get my Jackson ObjectMapper Module registered correctly.
I'm using a Guice + Jersey + Jackson (FasterXML) stack.
I've followed how to customise the ObjectMapper based on various question here. In particular, I have a ContextResolver declared, marked as an @javax.ws.rs.ext.Provider and a @javax.inject.Singleton.
I have a GuiceServletContextListener along the lines of:
@Override
protected Injector getInjector() {

     Injector injector = Guice.createInjector(new DBModule(dataSource),
            new ServletModule()
            {
                @Override
                protected void configureServlets() {

                    // Mapper
                    bind(JacksonOMP.class).asEagerSingleton();

                    // ...

                    Map<String, String> initParams = new HashMap<String, String>();
                    initParams.put("com.sun.jersey.config.feature.Trace",
                            "true");
                    initParams.put("com.sun.jersey.api.json.POJOMappingFeature", "true");

                    serve("/services/*").with(
                            GuiceContainer.class,
                            initParams);
                }
            });

    return injector;
}

Mapper defined
import javax.inject.Singleton;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

@Provider
@Singleton
@Produces
public class JacksonOMP implements ContextResolver<ObjectMapper> {

  @Override
  public ObjectMapper getContext(Class<?> aClass) {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Hibernate4Module());
    return mapper;
  }
}

However - with this configuration alone, getContext() is never called, so the mapper is never registered. I'm stuck in a typical guice--annotations-mystery, where it's practically untraceable to what I'm actually supposed to be doing. Spring users just report registering the component, and the container just picks it up.
This answer talks about overriding my own javax.ws.rs.core.Application implementation. However, this looks hard-wired in the jersey-guice impementation of GuiceContainer to be DefaultResourceConfig():
@Override
protected ResourceConfig getDefaultResourceConfig(Map<String, Object> props,
        WebConfig webConfig) throws ServletException {
    return new DefaultResourceConfig();
}

Am I supposed subclass GuiceContainer here? Or is there some other magic annotation that I'm missing?
This seems a fairly common thing to want to do - I'm surprised at how hard it's proving to do with this guice combination.

A:
I'm stuck in a typical guice--annotations-mystery, where it's
  practically untraceable to what I'm actually supposed to be doing.
  Spring users just report registering the component, and the container
  just picks it up.

You really should read excellent Guice documentation. Guice is very easy to use, it has very small number of basic concepts. Your problem is in that you mixed Jersey JAX-RS dependency injection and Guice dependency injection. If you are using GuiceContainer then you declare that you will be using Guice for all of your DI, so you have to add bindings with Guice and not with JAX-RS.
For instance, you do not need ContextResolver, you should use plain Guice Provider instead:
import com.google.inject.Provider;

public class ObjectMapperProvider implements Provider<ObjectMapper> {
    @Override
    public ObjectMapper get() {
        final ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new Hibernate4Module());
        return mapper;
    }
}

Then you should add corresponding binding to your module:
bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class).in(Singleton.class);

This will bind ObjectMapper, but it is not enough to use Jersey with Jackson. You will need some kind of MessageBodyReader/MessageBodyWriter, e.g. JacksonJsonProvider. You will need another provider for it:
public class JacksonJsonProviderProvider implements Provider<JacksonJsonProvider> {
    private final ObjectMapper mapper;

    @Inject
    JacksonJsonProviderProvider(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public JacksonJsonProvider get() {
        return new JacksonJsonProvider(mapper);
    }
}

Then bind it:
bind(JacksonJsonProvider.class).toProvider(JacksonJsonProviderProvider.class).in(Singleton.class);

This is all you need to do - no subclassing is needed.
There is a room for code size optimization though. If I were you I would use @Provides-methods:
@Provides @Singleton
ObjectMapper objectMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Hibernate4Module());
    return mapper;
}

@Provides @Singleton
JacksonJsonProvider jacksonJsonProvider(ObjectMapper mapper) {
    return new JacksonJsonProvider(mapper);
}

These methods should be added to one of your modules, e.g. to anonymous ServletModule. Then you won't need separate provider classes.
BTW, you should use JerseyServletModule instead of plain ServletModule, it provides a lot of useful bindings for you.


text:
Q: Lagrange multipliers from hell - extreme edition When I was a young and innocent boy, a few years ago, I posted this question on Lagrange Multipliers - Lagrange multipliers from hell
4 years later, not much has changed.
Let $\Gamma$ be the intersection of the ellipsoid $\frac{x^2}{a_1^2}+\frac{y^2}{a_2^2}+\frac{z^2}{a_3^2} = 1$ and the plane $b_1x+b_2y+b_3z=0$.
We wish to find the points on $\Gamma$ that are closest to the origin, and that are farthest from the origin.
What I tried:
We wish to find conditional extremum of $f(x,y,z)= \frac{1}{2}(x^2+y^2+z^2)$ given constraints $g_1(x,y,z) = \frac{x^2}{a_1^2}+\frac{y^2}{a_2^2}+\frac{z^2}{a_3^2} -1 = 0$ and $g_2(x,y,z) = b_1x+b_2y+b_3z = 0$
Hence our system is:
$\begin{cases}(x,y,z) = \lambda_1(\frac{2}{a_1^2}x, \frac{2}{a_2^2}y, \frac{2}{a_3^2}z) + \lambda_2(b_1,b_2,b_3) \\ \frac{x^2}{a_1^2}+\frac{y^2}{a_2^2}+\frac{z^2}{a_3^2} -1 = 0 \\ b_1x+b_2y+b_3z = 0\end{cases}$
there are several approaches we can take now. None are very good.
The most tempting one is to say $x = \frac{-b_2y-b_3z}{b_1}$ to get rid of at least one variable, but alas, we don't know if $b_1 \neq 0$. We know that at least one of $b_1,b_2,b_3 \neq 0$ but we don't know which.
Another approach would be to say $x^2 = a_1^2 - \frac{a_1^2}{a_2^2}y^2 - \frac{a_1^2}{a_3^2}z^2$
Combine that with the fact that $b_1^2x^2 = (-b_2y-b_3z)^2$ and you get $a_1^2b_1^2 - \frac{a_1^2b_1^2}{a_2^2}y^2 - \frac{a_1^2b_1^2}{a_3^2}z^2 =(-b_2y-b_3z)^2 $
But now we have an equation that has both $y,z$ and $y^2,z^2$, that doesn't look too promising.
A third approach would be to completely abandon $x,y,z$ and move over to the world of lambdas: $x_1 = \frac{a_1^2b_1\lambda_2}{a_1^2-2\lambda_1}$ etc.
Again we run into the problem of having to split into cases where $a_1^2 = 2\lambda_1$, OR $a_2^2 = 2\lambda_1$, OR $a_3^2 = 2\lambda_1$.
This is a straggering amount of combinations to check and cases to split.
I'm doing something really wrong.
A final approach I thought of was maybe trying to parametrize the $\Gamma$ as we know it's an elipse. But we can't do that really if we don't know which $b$ isnt zero.
4 years have passed, all I've done is increase the pain.

A: To parametrize the ellipse we can choose a basis for the plane that is

*

*$v_1=(b_2,-b_1,0)$

*$v_2=(0,b_3,-b_2)$

then the generic point in the plane is

*

*$P(s,t)=sv_1+tv_2=(sb_2,-sb_1+tb_3,-tb_2)$

Then the problem to solve becomes in two variables
$$\begin{cases}f(s,t)=(sb_2)^2+(-sb_1+tb_3)^2+(-tb_2)^2\\\frac{(sb_2)^2}{a_1^2}+\frac{(-sb_1+tb_3)^2}{a_2^2}+\frac{(-tb_2)^2}{a_3^2} =1\end{cases}$$
Another possible strategy could be to perform a rotation of the system in such way that the given plane coincide with the x-y plane with equation z=0. In this way we obtain an equivalent problem in two variables.
For the rotation we can assume as basis the normal vector to the plane $v_3=(b_1,b_2,b_3)$ the vector $v_1$ orthogonal to $v_3$ and lying in the x-y plane and $v_2=v_3\times v_1$.
The rotation can obtained by

*

*$v_1 \to x$

*$v_2 \to y$

*$v_3 \to z$

that is by the inverse of the matrix $M=[v_1\quad v_2 \quad v_3]$.
But I think that the first method leads to something simpler.


text:
Q: MSMQ or Service Broker or bulk insert for FIFO message processing? We have a scenario where we need to use update/insert queries to the database against incoming real time events. We can go for either of the options presented below
1- MSMQ
2- SQL Service Broker
3- Custom built caching mechanism (using file cache, Bulk Inserts, triggers to convert inserts into updates if rows already exist etc)
We are not using an transactions, what should be the best option?
If we decide to use MSMQ, there is no guarantee about the ordering of the messages, we want it FIFO. So far best approach seems to be our own implementation but if MSMQ or Service broker can provide FIFO message processing it would be real nice.


text:
Q: Html nav element getting style on its own I have an element:
<nav id="datatableWithSearch" aria-label="Activity pagination"></nav>

on my cshtml view. When I inspect the element of this tag in the browser I noticed a style added to this nav. How is it possible.
Style added:
<nav id="datatableWithSearch" aria-label="Activity pagination" style="display:none">

As a temporary solution I have:
 <script>
    $(document).on('ready', function () {
        var element = document.getElementById("datatableWithSearch");
        element.style.display = null;
    });
 </script>

How do I improve on this because this only happens when document is loaded the first time.


text:
Q: a nonresponsive program, doesn't end gracefully when asked to terminate, for testing I want to write a simple program that does nothing but does not easily terminate when asked to.  I want to see the Windows dialog box which says, "this program is not responsive, do you want to wait to let it finish what it's doing, or terminate it now?".  After the user chooses "terminate it now", it should, of course, exit.
The reason I want this is for a testing environment.  I want to test a scenario in which the user is trying to log out, but the system doesn't log them out right away, because of an unresponsive program.
I tried responding to WM_DESTROY by calling Sleep(), but that doesn't seem to do it.  The program still terminates immediately when killed from the Task Manager.  Again, I'm not trying to write something truly "unkillable", just a simple program which makes that dialog box come up asking if the user wants to wait for the program to finish.
Thanks very much for any help.

A: You can try modifying your main-message loop . Use PeekMessage(...) with NO_REMOVE and ignore WM_QUIT messages
EDIT: Remove every message (except WM_QUIT) before processing it (GetMessage( &msg ,msg.hWnd ,msg.message ,msg.message ))


text:
Q: How are tpidr_el1 and tpidr_el2 used in arm64 linux? I was following the kernel_entry code and saw arch/arm64/include/asm/assembler.h (linux 5.10.0-rc5, see https://elixir.bootlin.com/linux/v5.10-rc5/source/arch/arm64/include/asm/assembler.h#L255)
From the way ldr_this_cpu, adr_this_cpu and this_cpu_offset above are used/defined, I understood the compile-generated per-cpu variable's address is the address of the variable for the first cpu and the tpidr_el1 or tpidr_el2 contains the offset of this cpu's variable from that of the first cpu's variable. And we have to appy this offset when accessing the per-cpu variables. Is my understanding correct?
And is tpidr_el1 used for offset between cpus and tpidr_el2 for offset between virtual machines? But definition of set_my_cpu_offset or this_cpu_offset seems to be saying tpidr_el2 is used whenever VHE is implemented. Could anyone briefly explain this to me?


text:
Q: How to set a EF code first connection string at runtime I'm missing something. I have a small project where I am trying to insert some data into a database. When I created the model I used Code First against an existing database. I wanted to make the app capable of point to any server at runtime. This is a down and dirty utility app an and running internally but I need some flexibility when running it.
From reading some msdn articles I saw where I could extend the DBContext on initialization so I did the following:
added a parameter to the initialization:
 public OtherEventModel(string ConnectionString)
            : base("name=OtherEventModel")
        {...

Then within my code I built the connection string based upon the properties passed in from the UI:
private OtherEventModel ConnectToServer(string server, string username, string password)
        {
            try
            {

                SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
                {
                    DataSource =  server,
                    UserID = username,
                    Password = password,
                    InitialCatalog = "My_Database",
                    IntegratedSecurity = true
                };

                var connection = sqlBuilder.ToString();
                ModelContext = new OtherEventModel(connection);

                return ModelContext;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error connecting to server {0}", ex.Message));
            }

I can see the connection string created however when I run the code I receive an exception that the connection string (what should be in app.config could not be found). Which I do not have a connection string or key within app config since I was trying to inject the connection string in at runtime.
Error:
Error inserting data No connection string named 'OtherEventModel' could be found in the application config file

I was under the impression from what I have read that Code first uses a standard SQL connection string and does not require the EntityConnectionStringBuild (used for object first dev)
Can someone point me in the right direction as to what I have missed or what I am doing wrong.
Thanks in advance

A: You're almost there, just pass the connection string to the base:
public OtherEventModel(string ConnectionString)
       : base(ConnectionString)

Make sure you comment the throw line in the method below.  Unfortunately you have to do this again every time you update the model.


text:
Q: Where can I find GIS files that shows the 11 nations of the USA? This book describes the cultural boundaries that define America.  At least one person has created what seems to be a GIS style map from this.
Does anyone know where I can locate these files?


text:
Q: ¿ como obtener datos del lado del cliente con sockets ? Trabajo con sockets actualmente, de la siguiente manera, tengo un gps que esta apuntando hacia mi servidor, de momento tuve que hacer que mi ip sea publica y le asigne un puerto donde llegaran los datos:
Ahora del lado del servidor con nodejs tengo esto:
var express = require("express");
var app = express();
//const net = require('net');
const port = 2345;
const host = '192.168.15.12';
var server = app.listen(port, host);
var io = require('socket.io').listen(server);
app.use((req,res,next) =>{
res.header('Access-Control-Allow-Origin',"http://localhost:4200/");
res.header('Access-Control-Allow-Credentials',"true");
res.header('Access-Control-Allow-Headers',"Origin, X-Requested-With,
Content-Type, Accept");
next();
})
//const server = net.createServer();
server.listen(port, host, () => {
console.log(' Servidor corriendo en port ' + port + '.');
});

let sockets = [];

server.on('connection', function(sock) {
console.log('CONNECTADO: ' + sock.remoteAddress + ':' + sock.remotePort);
sockets.push(sock);

sock.on('data', function(data) {
    data = String(data);
    console.log(typeof(data));
    console.log('DATA ' + sock.remoteAddress + ': ' + data);

    if(typeof(data) != "string" ){
        console.log("Error 1");
    }
    if(data.length < 19){
        console.log("Error 2");
    }
    if(data[0] != '(' && data[data.length-1] != ')'){
        console.log("Error 3");
    }
    else{

        var ID    = data.substr(1,1+11);
        var Comando = data.substr(13,4);
        console.log("ID: "+ID);
        console.log("Comando: "+Comando);
        io.on('connection',(socket) =>{
            socket.emit('data',{
                id:ID,
                comando:Comando
            });
        });

        if(Comando == "BR00"){

            //Fecha
            var offset = 17;
            var offset_end = 6;
            var date = data.substr(offset,offset_end);
            console.log("Fecha: "+date);

            //Disponibilidad
            offset = 23;
            offset_end =  1;
            var disponibilidad = data.substr(offset,offset_end);
            console.log("Dispo: "+disponibilidad);

            //Latitud
            offset = 24;
            offset_end = 9;
            var lat = data.substr(offset,offset_end);
            console.log("Latitud: "+lat);

            //Indicador de latitud
            offset = 33;
            offset_end = 1;
            var lat_in = data.substr(offset,offset_end);
            console.log("Indicador lat: "+lat_in);

            //Longitud
            offset = 34;
            offset_end = 10;
            var lng = data.substr(offset,offset_end);
            console.log("Longitud: "+lng);

            //Indicador de longitud
            offset = 44;
            offset_end = 1;
            var lng_in = data.substr(offset,offset_end);
            console.log("Indicador lng: "+lng_in);

            //Velocidad
            offset = 45;
            offset_end = 5;
            var Velocidad = data.substr(offset,offset_end);
            console.log("Velocidad: "+Velocidad);

            //Hora
            offset = 50;
            offset_end = 6;
            var hora = data.substr(offset,offset_end);
            console.log("Hora: "+hora);

            if(disponibilidad = "A"){
                var lat_dd = parseFloat(lat.substr(0,2)) +
   parseFloat(lat.substr(2,9)) / 60;
                if(lat_in != "N"){
                    lat_dd = - lat_dd;
                }
                var lng_dd = parseFloat(lng.substr(0,3)) +
               parseFloat(lng.substr(3,10)) / 60;
                if(lat_in != "E"){
                    lng_dd = - lng_dd;
                }

                console.log("Lat: "+lat_dd);
                console.log("Lon: "+lng_dd);

            }
        }

    }

    // Write the data back to all the connected, the client will receive it
   as data from the server
    sockets.forEach(function(sock, index, array) {
        sock.write(sock.remoteAddress + ':' + sock.remotePort + " said " +
  data + '\n');
    });
});

// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
    let index = sockets.findIndex(function(o) {
        return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort;
    })
    if (index !== -1) sockets.splice(index, 1);
    console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
});

});
Este servidor cuanto le ejecuto me devuelve datos del gps en consola, Ahora del lado del cliente con Angular version 6 utilizo el siguiente codigo,
import { Component, OnInit } from '@angular/core';
import * as io from 'socket.io-client';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
data: any;
messageText: string;
constructor() {
// this.socket = io.connect('http://localhost:8000');
// this.socket = io.connect('http://localhost:3000');
}

ngOnInit() {
const socket = io('192.168.15.1:2345');
    socket.on('connect', (data) => {
      console.log(data);
    } );
  }
}

y correctamente si me devuelve datos, pero en consola me vienen muchos errores, como lo muestro en la siguiente :
Ahora bien soy nuevo trabajando con sockets, lo que estoy haciendo es correcto ?, es la correcta funcion de implementancion del lado del client ? cualquier observacion me seria de mucha ayuda.


text:
Q: Import java.awt.xxxxx and javax.imageio.imageIO? I have been working on a program in which I use codes from this API (musicg) : http://code.google.com/p/musicg/
However, I still have one part of my code which causes me trouble (GraphicRender.java). In the import part, it happens that some lines remain underlined in red, meaning some data are missing.
Do you have any idea of where I can find these missing parts ?
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

Thanks in advance for any lead you could give me, I'd really appreciate some help to make this work !
See you

A: java.awt.* can not be resolved in android as java.awt.* contains native code. These native code needs to be supported by android separately. So far, it is not done.
However, you can use android.graphics, android's graphics library.
More information available at :
http://developer.android.com/reference/android/graphics/package-summary.html

A: These imports cannot be resolved on Android.
While Android has a lot of classes that the standard Java Development Kit does, it implements its own UI system. Due to this, awt is not included in Android.
However, attempts have been made at porting parts of awt to Android. I haven't tried out the project personally, so I can't say if it meets your requirements.
You could also look into JavaCV and OpenCV for image processing on Android.

A: For the java.awt, I found this android port - https://bitbucket.org/mkmatlock/android-pdfbox/downloads/ (look for the android-awt-*.jar and throw it into your project as a library dependency). I was looking for a pdfbox port (which uses awt internally) when I found that. I haven't tested it thoroughly but it seems to suppress my compile errors.
I'm still looking for the javax.imageio port, will update when I find one.


text:
Q: phpMyAdmin File Limit (already edited php.ini) I'm trying to import a 151 MB database into phpMyAdmin and am getting the error "You probably tried to upload a file that is too large. Please refer to documentation for a workaround for this limit."
I've already edited php.ini with values of upload_max_filesize, memory_limit and post_max_size that more than accommodate this file. Is there anything else I can do to troubleshoot?

A: Try setting max_execution_time and max_input_time with higher values.
max_execution_time = 90
max_input_time = 120

You might want to try memory_limit as well and don't forget to restart the server.


text:
Q: YA novel where the world is divided by color Read this book before 2013.
The protagonist (I think it was a boy) lived in a world where society was divided by colours and each colour had their own city/continent. Each of these colours had their own rules for that part of the world. The main character wants to either change his colour or make it so that all the colours are everywhere. He starts traveling between all of the colours so that he can learn about them while he looks for the being (? Or god? Creature?) that can make him change/make the colours be everywhere.
I remember that in one of the colours there was a limit of how many words someone could speak a day/week, another where everyone could eat whatever they wished for but in the end it was all made of the same thing, and another (blue I think) was submerged and you had to take a train to go to the dome underwater (in this one there was also a mattress that made it so you only had to sleep 4 hours instead of 8 so you had more time to dedicate to other things, I think it was to study).
They did manage to find the being in the end, (with the friends that they made during the journey, if I remember correctly) and it agreed with them to liberate the colours.
It was not a "let's overthrow the government" type of book. It was only a kid going for a adventure with their friends and in fact most of the book is only they learning more about how the others colours live. There wasn't, from what I remember, a caste system: every colour had their own ups and downs on why it was good to live there.

A: The mention of "blue" as one of the colours of this segregated land had me immediately leaping to Divided Kingdom by Rupert Thomson, published in 2006.
Goodreads

One night a boy who comes to be called Thomas Parry is taken from his family, caught up in a comprehensive unraveling of what had been a united kingdom. Reacting to their country's inexorable decline into consumerism, turpitude, racism, and violence, the powers that be establish four independent republics based on the perceived nature of the citizens assigned to each. These new partitions are reinforced with concrete barricades and razor wire.

Wikipedia

The former United Kingdom has been divided into four Quarters: Green (Scotland, the North-East of England and East Anglia); Red (the East Midlands, the North-West of England and Northern Ireland); Blue (Wales and the West Country) and Yellow (the West Midlands), each allocated a different personality type. Each of these personality types is based upon a different Humor: Sanguine is blood, Choleric is yellow bile, Phlegmatic is phlegm and Melancholic is black bile. Each country has a different way of running things: for example, the Blue Quarter uses canals, and the Yellow Quarter is industrious.

As you've recalled it isn't an "overthrow the regime" world or an escape to the outside type scenario. The main character that we follow around is given insight into each of the different regions by virtue of his job in the ministry.

The protagonist is Thomas Parry, a government official for the Sanguines. He attends a conference in the Blue Quarter and visits a club called the Bathysphere where he sees his life as it was before the division. This inspires him to go on a journey across all the quarters to find out about his past.


text:
Q: NullPointerException on ProgressDialog I'm getting a NullPointerException while using a progress dialog.
My code is as follows:
package org.text.me.actionBar.edit.fragments;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.quickblox.core.QBCallback;
import com.quickblox.core.QBCallbackImpl;
import com.quickblox.core.result.Result;
import com.quickblox.module.content.QBContent;
import com.quickblox.module.content.model.QBFile;
import com.quickblox.module.content.result.QBFileUploadTaskResult;
import com.quickblox.module.users.QBUsers;
import com.quickblox.module.users.model.QBUser;
import org.text.me.R;
import org.text.me.actionBar.definitions.Queries;
import org.text.me.actionBar.edit.activity.ChangeNameActivity;
import org.text.me.actionBar.edit.activity.ChangePasswordActivity;
import org.text.me.actionBar.gallery.activity.GalleryActivity;
import org.text.me.actionBar.holder.DataHolder;
import org.text.me.actionBar.utils.bitmap.BitmapUtility;
import org.text.me.actionBar.utils.external_storage.ExternalStorageUtils;

import java.io.File;

import static android.widget.ImageView.ScaleType.FIT_CENTER;
import static org.text.me.actionBar.definitions.Constants.TAG;
import static org.text.me.actionBar.preferences.SharedConstants.*;
import static org.text.me.actionBar.preferences.SharedPrefs.*;

public class EditProfileFragment extends Fragment implements View.OnClickListener, QBCallback {

private View        editProfileView;
private ImageView   ivProfilePicture;
private TextView    tvFullName;
private ImageButton ibPassword;
private ImageButton ibName;

private ProgressDialog progressDialog;

private String fullName = null;

private Bitmap DEFAULT_PROFILE_PICTURE = null;
private Bitmap PROFILE_PICTURE         = null;

private static       int                   DEFAULT_WIDTH            = 300;
private static       int                   DEFAULT_HEIGHT           = 250;
private static final int                   DEFAULT_COMPRESS_QUALITY = 100;
private static final Bitmap.CompressFormat DEFAULT_COMPRESS_FORMAT  = Bitmap.CompressFormat.PNG;
private static final boolean               fileIsPublic             = false;

public static EditProfileFragment getInstance () {
    return new EditProfileFragment ();
}

@Override
public void onCreate (Bundle savedInstanceState) {
    super.onCreate ( savedInstanceState );
    setHasOptionsMenu ( false );
}

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    editProfileView = inflater.inflate ( R.layout.fragment_edit_profile, container, false );

    setupUi ();
    setupProgressDialog ();

    return editProfileView;
}

private void setupUi () {
    tvFullName = (TextView) editProfileView.findViewById ( R.id.tvName );
    ivProfilePicture = (ImageView) editProfileView.findViewById ( R.id.ivEditProfilePicture );
    ibPassword = (ImageButton) editProfileView.findViewById ( R.id.ibPassword );
    ibName = (ImageButton) editProfileView.findViewById ( R.id.ibName );

    tvFullName.setText ( getStringPrefs ( getActivity (), SIGN_IN_USER_FULL_NAME ) );

    if ( getStringPrefs ( getActivity (), PROFILE_PICTURE_PATH ).equals ( null ) )
        setupDefaultProfilePicture ();
    else
        setupProfilePicture ();

    ibName.setOnClickListener ( this );
    ibPassword.setOnClickListener ( this );
    ivProfilePicture.setOnClickListener ( this );
}

private void setupProgressDialog () {
    progressDialog = new ProgressDialog ( editProfileView.getContext () );
    progressDialog.setMessage ( getResources ().getString ( R.string.loading ) );
    progressDialog.setCancelable ( false );
}

private void setupDefaultProfilePicture () {
    DEFAULT_PROFILE_PICTURE = BitmapUtility.decodeSampledBitmapFromResource (
            getResources (),
            R.drawable.action_people,
            DEFAULT_WIDTH,
            DEFAULT_HEIGHT );
    ivProfilePicture.setScaleType ( FIT_CENTER );
    ivProfilePicture.setImageBitmap ( DEFAULT_PROFILE_PICTURE );
}

private void setupProfilePicture () {
    if ( PROFILE_PICTURE != null ) PROFILE_PICTURE.recycle ();

    BitmapFactory.Options options = new BitmapFactory.Options ();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inDither = false;
    options.inSampleSize = 8;
    PROFILE_PICTURE = BitmapFactory.decodeFile ( getStringPrefs ( getActivity (), PROFILE_PICTURE_PATH ),
                                                 options );
    ivProfilePicture.setImageBitmap ( PROFILE_PICTURE );

    if ( !getBooleanPrefs ( getActivity (), IS_PROFILE_UPLOADED ) && !getStringPrefs ( getActivity (),
                                                                                PROFILE_PICTURE_PATH )
            .equals ( null ) ) {

        progressDialog.show ();

        File profilePicture = ExternalStorageUtils.saveBitmapToFile ( PROFILE_PICTURE, DEFAULT_COMPRESS_FORMAT,
                                                                      DEFAULT_COMPRESS_QUALITY,
                                                                      String.valueOf ( getIntPrefs ( getActivity
                                                                                (),
                                                                                SIGN_IN_USER_ID ) ) );
        QBContent.uploadFileTask ( profilePicture, fileIsPublic, new QBCallbackImpl () {
            @Override
            public void onComplete (Result result) {
                if ( result.isSuccess () ) {
                    //Get the uploaded file
                    QBFileUploadTaskResult taskResult = (QBFileUploadTaskResult) result;
                    QBFile file = taskResult.getFile ();
                    int uploadedFileId = file.getId ();

                    //Connect image to user
                    QBUser user = new QBUser ();
                    user.setId ( getIntPrefs ( getActivity (), SIGN_IN_USER_ID ) );
                    user.setFileId ( uploadedFileId );

                    QBUsers.updateUser ( user, new QBCallbackImpl () {
                        @Override
                        public void onComplete (Result result) {
                            if ( result.isSuccess () ) {
                                Toast.makeText ( getActivity (), getResources ().getString ( R.string
                                                                                .action_edit_successful ), Toast.LENGTH_SHORT ).show ();
                                progressDialog.dismiss ();
                                setBooleanPrefs ( getActivity (), IS_PROFILE_UPLOADED, true );
                            } else {
                                progressDialog.hide ();
                                Toast.makeText ( getActivity (), result.getErrors ().get ( 0 ).toString (),
                                                 Toast.LENGTH_SHORT ).show ();
                                Log.e ( TAG, result.getErrors ().toString () );
                            }
                        }
                    } );
                } else {
                    progressDialog.hide ();
                    Toast.makeText ( getActivity (), result.getErrors ().get ( 0 ).toString (),
                                     Toast.LENGTH_SHORT ).show ();
                    Log.e ( TAG, result.getErrors ().toString () );
                }
            }
        } );
    }
}

@Override
public void onClick (View v) {
    switch ( v.getId () ) {
        case R.id.ibPassword:
            startActivity ( new Intent ( this.getActivity (), ChangePasswordActivity.class ) );
            break;

        case R.id.ibName:
            startActivity ( new Intent ( this.getActivity (), ChangeNameActivity.class ) );
            break;

        case R.id.ivEditProfilePicture:
            Intent intent = new Intent ( getActivity (), GalleryActivity.class );
            startActivity ( intent );
            break;
    }
}

@Override
public void onComplete (Result result) {

}

@Override
public void onComplete (Result result, Object query) {
    Queries queryType = (Queries) query;
    if ( result.isSuccess () ) {
        switch ( queryType ) {
            case QUERY_UPDATE_USER_INFO:
                DataHolder.getDataHolder ().getSignInUser ().setFullName ( fullName );
                progressDialog.dismiss ();
                Toast.makeText ( this.getActivity (), getResources ().getString ( R.string
                                                                                .action_edit_successful ),

                                 Toast.LENGTH_SHORT ).show ();
                break;
        }
    } else {
        progressDialog.hide ();
        Toast.makeText ( this.getActivity (), result.getErrors ().get ( 0 ).toString (),
                         Toast.LENGTH_SHORT ).show ();
        Log.e ( TAG, result.getErrors ().toString () );
    }
}
}

And the error that I am getting is as follows:
01-23 07:14:55.524    3126-3126/org.text.me W/dalvikvm﹕ threadid=1: thread exiting     with uncaught exception (group=0x4001d560)
01-23 07:14:55.574    3126-3126/org.text.me E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at org.text.me.actionBar.edit.fragments.EditProfileFragment.setupProfilePicture(EditProfileFragment.java:134)
        at org.text.me.actionBar.edit.fragments.EditProfileFragment.setupUi(EditProfileFragment.java:93)
        at org.text.me.actionBar.edit.fragments.EditProfileFragment.onCreateView(EditProfileFragment.java:76)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
        at android.view.View.measure(View.java:8313)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
        at android.view.View.measure(View.java:8313)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
        at android.view.View.measure(View.java:8313)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
        at android.view.View.measure(View.java:8313)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
        at android.view.View.measure(View.java:8313)
        at android.view.ViewRoot.performTraversals(ViewRoot.java:843)
        at android.view.ViewRoot.handleMessage(ViewRoot.java:1864)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:130)
        at android.app.ActivityThread.main(ActivityThread.java:3698)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:507)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
        at dalvik.system.NativeStart.main(Native Method)

The program works like a charm if I comment out progressDialog.show()
The error occurs at progressDialog.show(); How can a NullPointerException occur there? And what is the solution to it?

A: setupProfilePicture(), which accesses the progressDialog instance and which is still null, is ultimately called before setupProgressDialog(). Step through the setupUi() and setupProgressDialog() calls you're making in onCreateView().

A: Your setupUI method is called before your setupProgressDialog (where the progress dialog is created), and your setupUI method calls setupProfilePicture which tries to use the progress dialog that has not yet been created -- thus the null pointer exception.


text:
Q: Jaggery (WS02) endpoint reference/dynamic endpoint I'm currently developing an application in Jaggery which I deploy on their API manager.
From the Jaggery back end I'm calling a SOAP webservice using the method documented here, which specifies:
<%
var url = 'http://jaggeryjs.org/apidocs/resources/home.jag';
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("user" , "madhuka");
xhr.send();

print("ReadyState : "+xhr.readyState);
print("
ResponseStatus : "+xhr.status);
print("
ResponseText : "+xhr.responseText);
%>

I have everything up and working fine, however I'd like to remove the hard-coded URL and replace it with some sort of URL lookup, based on environment.
What is the correct way of doing this? Can I specify an endpoint in API manager and refer to it? Or perhaps use an EPR file. I've had little luck with the Jaggery documentation in this sense.

A: I have seen many jaggery apps developed for WSO2 products. The practice followed in them is to have a config file in json format. You can have a method to read it and get necessary values by passing the attribute name.
You can either have a config file for each environment and pack the correct one with the app or have a single config file with endpoints for each environment. If you are going to maintain a single config file, you have to dynamically construct the attribute name and read its value. To do that also, you need to maintain which environment it is. Therefore I recommend to use a config file for each environment and bundle the correct file for the environment.


text:
Q: I can't do login using $_SESSION on PHP I'm trying to make a website with XAMP using PHP, MySQL and Bootstrap. I'm beginner in PHP so I take this code on website of developers and when I tried to run on localhost I typed my credentials and the index.php did a refresh only, not show nothing errors, just refresh. I researched on web for 5 days and nothing, here's my code:
index.php
<?php session_start(); ?><!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Signin Template for Bootstrap</title>

    <link href="bootstrap.min.css" rel="stylesheet">

    <link href="signin.css" rel="stylesheet">

      <form class="form-signin" action="validacao.php" method="post">

Please sign in

        Email address
        <input type="text"  name="usuario" id="txUsuario" class="form-control" placeholder="Email" required autofocus>
        Password
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>

            <input type="checkbox" value="remember-me"> Remember me

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
      </form>

validacao.php
<?php

  // Verifica se houve POST e se o usuário ou a senha é(são) vazio(s)
  if (!empty($_POST) AND (empty($_POST['usuario']) OR empty($_POST['senha']))) {
      header("Location: index.php"); exit;
  }

  // Tenta se conectar ao servidor MySQL
  mysql_connect('localhost', 'root', '') or trigger_error(mysql_error());
  // Tenta se conectar a um banco de dados MySQL
  mysql_select_db('wda_crud') or trigger_error(mysql_error());

  $usuario = mysql_real_escape_string($_POST['usuario']);
  $senha = mysql_real_escape_string($_POST['senha']);

  // Validação do usuário/senha digitados
  $sql = "SELECT `id`, `nome`, `nivel` FROM `usuarios` WHERE (`usuario` = '".$usuario ."') AND (`senha` = '".$senha ."') AND (`ativo` = 1) LIMIT 1";
  $query = mysql_query($sql);
  if (mysql_num_rows($query) != 1) {
      // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
      echo "Login inválido!"; exit;
  } else {
      // Salva os dados encontrados na variável $resultado
      $resultado = mysql_fetch_assoc($query);

      // Se a sessão não existir, inicia uma
      if (!isset($_SESSION)) session_start();

      // Salva os dados encontrados na sessão
      $_SESSION['UsuarioID'] = $resultado['id'];
      $_SESSION['UsuarioNome'] = $resultado['nome'];
      $_SESSION['UsuarioNivel'] = $resultado['nivel'];

      // Redireciona o visitante
      header("Location: site.php"); exit;
  }

  ?>

site.php
<?php session_start(); ?>

    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Dashboard Template for Bootstrap</title>

    <link href="bootstrap.min.css" rel="stylesheet">

    <link href="dashboard.css" rel="stylesheet">

      <button class="navbar-toggler navbar-toggler-right hidden-lg-up" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

      </button>
      <?php echo $_SESSION['UsuarioNome']; ?>

            Home (current)

            Settings

            Profile

            Help

        <form class="form-inline mt-2 mt-md-0">
          <input class="form-control mr-sm-2" type="text" placeholder="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>

              Overview (current)

              Reports

              Analytics

              Export

              Nav item

              Nav item again

              One more nav

              Another nav item

              Nav item again

              One more nav

              Another nav item

Dashboard

Label

Something else

Label

              Something else

Label

              Something else

Label

              Something else

Section title

                  #
                  Header
                  Header
                  Header
                  Header

                  1,001
                  Lorem
                  ipsum
                  dolor
                  sit

                  1,002
                  amet
                  consectetur
                  adipiscing
                  elit

                  1,003
                  Integer
                  nec
                  odio
                  Praesent

                  1,003
                  libero
                  Sed
                  cursus
                  ante

                  1,004
                  dapibus
                  diam
                  Sed
                  nisi

                  1,005
                  Nulla
                  quis
                  sem
                  at

                  1,006
                  nibh
                  elementum
                  imperdiet
                  Duis

                  1,007
                  sagittis
                  ipsum
                  Praesent
                  mauris

                  1,008
                  Fusce
                  nec
                  tellus
                  sed

                  1,009
                  augue
                  semper
                  porta
                  Mauris

                  1,010
                  massa
                  Vestibulum
                  lacinia
                  arcu

                  1,011
                  eget
                  nulla
                  Class
                  aptent

                  1,012
                  taciti
                  sociosqu
                  ad
                  litora

                  1,013
                  torquent
                  per
                  conubia
                  nostra

                  1,014
                  per
                  inceptos
                  himenaeos
                  Curabitur

                  1,015
                  sodales
                  ligula
                  in
                  libero

Someone can tell me what is the error? It can be the XAMP?

A: Your error in this line
There is no name field in
   <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>

you have put name field in label
    Password

change this two lines to
    <input type="password" name="senha" id="inputPassword" class="form-control" placeholder="Password" required>

    Password

A: The <input...> tags must have a name= attribute or they will not be sent from the HTML form to the PHP script by the browser.
So add a name= attribute to this <input>
<input type="password" name="senha" id="inputPassword" class="form-control" placeholder="Password" required>
                       ^^^^^^^^^^^^

I am guessing its just a typo because you have a name="senha" attribute in the  and that is not necessary.
Password
        can be removed     ^^^^^^^^^^^^

Note: You should always code your session_start(); at the top of your scripts right after the first <?php


text:
Q: With Phonegap, how can I check how much free disk space remaining? I have a Phonegap app that uses filesystem API to save file on device filesystem.
On startup the app requires some filesystem space with window.requestFileSystem but runtime it's possible to download other files and I can't predict the total amount of needed disk space.
The idea is to check the space available before download begins and if the space is not enough then trigger a message to user.
Is there some method with Phonegap to check remaining free space?

A: Before found this post I create my own function that do this, trying to get a filesystem with a determined bytes until reach the limit and assume the free space, recursively. Due the callbacks, maybe it's necessary set a timeout bigger than 0. In my tests, the diference between the cordova.exec way and my way was very small, and is possible better the accuracy lowering the value of the limit.
function availableBytes(callback, start, end){
    callback = callback == null ? function(){} : callback
    start = start == null ? 0 : start
    end = end == null ? 1 * 1024 * 1024 * 1024 * 1024 : end //starting with 1 TB
    limit = 1024 // precision of 1kb

    start_temp = start
    end_temp = end
    callback_temp = callback
    if (end - start < limit)
        callback(start)
    else{
        window.requestFileSystem(LocalFileSystem.PERSISTENT, parseInt(end_temp - ((end_temp - start_temp) / 2)), function(fileSystem){
            setTimeout(function(){
                availableBytes(callback_temp, parseInt(parseInt(end_temp - ((end_temp - start_temp) / 2))), end_temp)
            }, 0)
        }, function(){
            setTimeout(function(){
                availableBytes(callback_temp, start_temp, parseInt(end_temp - ((end_temp - start_temp) / 2)))
            }, 0)
        })
    }
}

Can be used like:
availableBytes(function(free_bytes){
    alert(free_bytes)
}

A: The code will call the getFreeDiskSpace method of the File plugin (cordova.file.plugin) and depending on the success or error callback, give you a result.  If the success callback is reached, you'll get the total free disk space in kilobytes.  You can easily convert to megabytes or gigabytes with simple math.
cordova.exec(function(result) {
    alert("Free Disk Space: " + result);
}, function(error) {
    alert("Error: " + error);
}, "File", "getFreeDiskSpace", []);

A: Phonegap does not provide this feature. The solution is to create yourself a phonegap plugin to check the space available.

*

*Phonegap plugin development guide

*android implementation

*iOS implementation


text:
Q: Rails 3 Float Rounding Error Running ruby 1.8.7.
(1.005 * 100).round
result:  100
(1.006 * 100).round
result:  101
100.5.round
result: 101
(1.005 * 100)
result: 100.5
What is going on here?  Can someone try this in the latest version of ruby please?
Thanks!

A: Floating Point Math is what's going on.
For the last one, I do not get 100.5, and you aren't either, even if for some reason it's displaying as that:
Loading development environment (Rails 3.2.8)
1.9.3p194 :001 > (1.005 * 100).round
 => 100
1.9.3p194 :002 > (1.006 * 100).round
 => 101
1.9.3p194 :003 > 100.5.round
 => 101
1.9.3p194 :004 > (1.005 * 100)
 => 100.49999999999999


text:
Q: VBA PowerPoint Mouseout Technique Not Called I believe I have a problem with powerpoint macros that is keeping me from getting my desired behavior. I'm attempting to achieve a mouseover/mouseout effect in a powerpoint slide.
The idea is given three square shapes, change the line color of each independently on hover...

shape line changes on hover
...then return it to its original state on mouseout. I know PP doesn't support mouseout, so I'm attempting to use the mouseout hack consisting of another shape with a mouseout macro mentioned here -

shape lines reset when mouse is over background shape
I'm trying to use the following macros to achieve this. shapeHover() is triggered when the mouse is on a square. MouseOutHack() is supposed to be triggered when the mouse is on the background shape, but the lines are not resetting to their original color. Is there a problem with my macros? Both are in the same module.
Option Explicit

Public myShape As Shape ' Global reference to mouse over shape

Sub shapeHover(oShp As Shape)
  Set myShape = oShp
  With oShp
    ' Change the properties you need here
    oShp.Line.ForeColor.RGB = RGB(0, 0, 0)
  End With
End Sub

Sub MouseOutHack()
  With oShp
    ' Reset the properties you need here
    oShp.Line.ForeColor.RGB = RGB(255, 0, 0)
  End With
End Sub

A: As Ahmed AU said ... use myShape in MouseOutHack and leverage the With statements if you're going to use them ... and then it'll work.
Option Explicit

Public myShape As Shape ' Global reference to mouse over shape

Sub shapeHover(oShp As Shape)
  Set myShape = oShp
  With oShp
    .Line.ForeColor.RGB = RGB(0, 0, 0)
  End With
End Sub

Sub MouseOutHack()
  With myShape
    .Line.ForeColor.RGB = RGB(255, 0, 0)
  End With
End Sub


text:
Q: ipywidgets: button.on_click() has output delay Introduction
I am trying to make a small tool for classifying images using the ipywidgets in a Jupyter Notebook, but I  am having some trouble aligning the classes and the images. Do you have any suggestion how to fix this.
What I did
import ipywidgets as widgets
from IPython.display import display
import glob

# My images
image_paths = glob.glob("./images/*.png")

# Display image
def display_image(path):
    file = open(path, "rb")
    image = file.read()
    return widgets.Image(
                value=image,
                format='png',
                width=700,
                height=700,
            )

# Dropdown
def create_dropdown():
    return widgets.Dropdown(
        options=["1","2","3","4","5","6","7","8","9","10"],
        value='5',
        description='Category:',
        disabled=False
    )

# Creating widgets
input_dropdown = create_dropdown()
button = widgets.Button(description="Submit")
output_image = widgets.Image()
output_image.value = display_image(image_paths[-1]).value

# Define function to bind value of the input to the output variable
def bind_input_to_output(sender):
    image_path = image_paths[-1]
    image_score = input_dropdown.value
    next_image_path = image_paths.pop()
    print(image_score, image_path)
    output_image.value = display_image(next_image_path).value

# Tell the text input widget to call bind_input_to_output() on submit
button.on_click(bind_input_to_output)

# Displaying widgets
display(output_image, input_dropdown, button)

Results
With the above code I end up categorising the upcoming picture, but I really don't understand why. It seems the widgets does not update the image the first time I press the button.

A: def bind_input_to_output(sender):
    image_path = image_paths.pop()
    image_score = input_dropdown.value
    next_image_path = image_paths[-1]
    print(image_score, image_path)
    output_image.value = display_image(next_image_path).value

pop first and give next filename at last item


text:
Q: Getting non compacted key/value from day window based statestore Topology Definition:
 KStream<String, JsonNode> transactions = builder.stream(inputTopic, Consumed.with(Serdes.String(), jsonSerde));

     KTable<Windowed<String>, JsonNode> aggregation =
                    transactions
                            .groupByKey()
                            .windowedBy(
                                    TimeWindows.of(Duration.ofSeconds(windowDuration)).grace(Duration.ofSeconds(windowGraceDuration)))
                            .aggregate(() -> new Service().buildInitialStats(),
                                    (key, transaction, previous) -> new Service().build(key, transaction, previous),
                                    Materialized.<String, JsonNode, WindowStore<Bytes, byte[]>>as(statStoreName).withRetention(Duration.ofSeconds((windowDuration + windowGraceDuration + windowRetentionDuration)))
                                            .withKeySerde(Serdes.String())
                                            .withValueSerde(jsonSerde)
.withCacheDisabled())
                            .suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()));
            aggregation.toStream()
                      .to(outputTopic, Produced.with(windowedSerde, jsonSerde));

State Store API: Fetch key by looking up all timewindows.
 Instant timeFrom = Instant.ofEpochMilli(0);
    Instant timeTo = Instant.now();
    WindowStoreIterator<ObjectNode> value = store.fetch(key,timeFrom,timeTo);
    while(value.hasNext()){
                System.out.println(value.next());
            }

As a part of test,performed 2 transactions and it produces key 1, My requirement is to get key1 twice(current & previous) without compaction when i lookup statestore. Result always returns final result with key and final aggregated value.
Txn1 --> Key - Key1 | Value - {Count=1,attribute='test'}
Txn2 --> Key - Key1 | Value - {Count=2,attribute='test1'}
Current Behavior after statestore lookup: Always get compacted key1 with value = {Count=2,attribute='test1'}
Instead I would like to get all key1 for that window duration.
As part of solution I  did below changes but unfortunately it did not worked.

*

*Disabled caching at topology level

*cache.max.bytes.buffering to 0

*Removing compact policy manually from internal changelog topic

Suspecting changelog topic is compacted and thus get compacted keys upon calling statestore api.
What changes are needed to get noncompated keys through statestore API?

A: If you want to get all intermediate result, you should not use the suppress() operator. suppress() is designed to emit a single result record per window, i.e., it does the exact opposite of what you want.


text:
Q: Javascript - Map instead of for loop I have a csv file with 5000 rows, with thirty fields per row (The data represent measurements of the concentration of different chemical elements).
I want to parse and visualize the data with D3js. After reading in the file I have an array with length 5000. Here, each element is an object with the measurements of the various chemical elements. measurements[5].Aluminium for instance returns the concentration of Aluminium at the fifth measurement.
Now I rather want to have arrays for each element with all their very measurments as elements. While this is easy with a for-loop, I want to try the map function.
Aluminium = measurements.map(function(row){
    return row.Aluminium;
});

This works and I could do this for each element but I would prefer to have the element as a parameter itself.
function selectElement(elementname){
      measurements.map(function(row){
          return row.elementname;
      });
};

Aluminium = selectElement('Aluminium');
Iron = selectElement('Iron');

And this is where I am stuck.

A: With Javascript, you can select children properties with a string of the key in square brackets, so obj.key becomes obj['key']
Using this notation, you can rewrite the selectElement function to match below:
function selectElement(elementname){
      measurements.map(function(row){
          return row[elementname];
      });
};

We know that elementname is a string, which is used as a selector for the row object

A: row.elementname looks for a key with the value "elementname". The dot notation does not do evaluation. Do
function selectElement(measurements, elementname){
      return measurements.map(function(row){
          return row[elementname];
      });
};

Aluminium = selectElement(measurements, 'Aluminium');
Iron = selectElement(measurements, 'Iron');


text:
Q: Drag by touch android UI I have problem with UI image on canvas for android in unity, the object does not follow the exact touch coordinates it moves slightly, but not enough to actually be functional
I tried everything, including creating a new project that apparently works as intended but without image from UI only by move sprite to the scene
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragScript : MonoBehaviour{

//offset dotkniecia objektu
float deltaX, deltaY;

//dostep do komponentu rigibody
Rigidbody2D rb;

//bool do dostepu poruszania pilki
bool moveAllowed = false;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

void Update(){

    /// <summary>
    /// inicjowanie zdarzenia dotykowego
    /// jezeli ma miejsce zdarzenie dotykowe czyli jest > 0
    /// </summary>
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);

        // uzyskuje pozycje dotykowe
        Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);

        //przetwarzanie faz dotykowych
        switch (touch.phase)
        {
            //jezeli dotykasz ekranu
            case TouchPhase.Began:
                Debug.Log("DOTKNALES PALCEM WTFF");
                // jezeli dotkniesz elementu
                if (GetComponent<BoxCollider2D>() == Physics2D.OverlapPoint(touchPos)){

                    Debug.Log("DZIALA IF");
                    /// <summary>
                    /// pobierz offset pomiedzy pozycjami ktore dotkniesz
                    /// i srodek objektu gry
                    /// </summary>
                    deltaX = touchPos.x - transform.position.x;
                    deltaY = touchPos.y - transform.position.y;

                    /// <summary>
                    /// jezeli dotyk zaczyna sie w ciagu colidera obiektu
                    /// wtedy może się poruszać
                    /// </summary>
                    moveAllowed = true;

                    /// <summary>
                    /// ogranicza troche rigibody aby sie poruszał
                    /// bardziej płynnie i poprawnie
                    /// </summary>
                    //rb.mass = 1;
                    rb.freezeRotation = true;
                    //rb.velocity = new Vector2(0, 0);
                    rb.gravityScale = 0;
                    GetComponent<PolygonCollider2D>().sharedMaterial = null;
                }
                break;
            // Gdy przesuwasz palcem po ekranie
            case TouchPhase.Moved:
                // jezeli przesuwam obiekt i moveallowed = true
                if (GetComponent<BoxCollider2D>() == Physics2D.OverlapPoint(touchPos) && moveAllowed)
                {
                    rb.MovePosition(new Vector2(touchPos.x - deltaX, touchPos.y - deltaY));
                }
                break;

            // puszczasz palce
            case TouchPhase.Ended:
                Debug.Log("KONIEC");
                moveAllowed = false;
                //rb.mass = 17;
                rb.freezeRotation = false;
                rb.gravityScale = 45;
                break;
        }
    }
}

}
it must move an UI image with fingers
no error messages it just doesn't move correctly

A: The script is attached to the wrong object in the Hierarchy. You need to attach it to the Canvas and not the image. The script uses the transform of the object it is placed on. Thus, if you place it on a child, the parent object will not follow.
To resolve this, try adding the script to the canvas.