text:
Q: Why is bronze league so broad? Recently I saw some statistics about how many people are in each league (bronze / silver / gold / platinum / diamond / master). That is 6 leagues, and Bronze was something like 40% of the entire ladder.
To me that seems pretty rough. Top bronze players are not stellar, but they are good enough to win methodically, balance economy, micro units, and make calculated decisions in the heat of battle. They are using hotkeys and know the whole tech tree.
Why place these players in the same league as a complete casual newcomer who makes 10 workers, 1 of each unit producing structure, and attacks with a single marine?
I can understand that inactive / abandoned accounts will probably be more common in bronze, so bronze should be inflated for that, but I am mostly referring to the diversity of skill you see in bronze league.
The diversity of skill in all the other leagues is extremely small in comparison.

A: While it's true that the top bronze leaguers can play a well balanced game, many of the games can be won with a reasonably well executed all-in unless the opponent just happened to perform the proper counter-strategy.  If someone can win the same amount playing in the same pool, but one is doing early rushes with marines and SCVs and the other playing "normally", who is "better"?
I view silver as a league where those cheese builds can be handily shut down better than 50% of the time--or where the skill in the game grows to include what the other player is doing.

A: The distribution of players is : 20% in bronze league, 20% in silver league, 20% in gold league, 20% in platinium league, 18% in diamond and the top 2% in the recently created master league.
The main difference between low league (<= gold) players and higher league players is the macro part of the game. The better your macro, the higher your league (on a long term perspective). The differences between platinium / diamond and master league player are more detail-oriented (micro, global strategy, information handling, reaction to opponent strategy, ...).

A: So, Opera's answer is almost right, but the difference between it and the correct answer is too long for comments.

Master league is believed to be the top 2% of all active players in a region, and is believed to cut away the top 10% of Diamond league. This would put the approximate league populations at 2%/18%/20%/20%/20%/20% for active players. An active player is defined as a player who has played a certain minimum number of games per week. Going inactive does not demote you, you just no longer take up a spot in your league's percentage of the active population. The percentages are also not hard values and there is some slush involved to allow them to even out over time.

Quote from Starcraft 2 Forum's MVP ExcaliburZ
So what does Active really mean?

It's technically not a hard 2%. It's kind of complicated and our understanding of it isn't 100% thorough yet because we just learned a lot of this on Friday and there are still many questions that remain. I'll try to explain.
First, it's 2% of active players. That means that if you are within the top 2% of other players who are considered active, you are eligible to be promoted.
This raises the obvious question of "what does the system consider to be active?" Active status hinges upon your bonus pool, since the less active you are, the less bonus pool you are spending. You get 1 point of bonus pool every 112 minutes, or 90 per week, meaning 90 bonus pool is equivalent to one "bonus week." From what we understand there are several tiers of activity.

*

*Active players -- Players who spend 90 or more bonus pool per week and have less than X unspent bonus pool.

*Semi-active players -- Players who have less than X unspent bonus pool.

*Inactive players -- Players who have X or more unspent bonus pool.

  X is something that we're still trying to figure out. It could be a flat value, say 6 bonus weeks' worth, or it could be a percentage of total bonus pool accrued throughout the season. We're also unsure of whether tiers 1 and 2 are the same.
Now, back to the league populations. If you are a semi-active or inactive player and you are matched against another semi-active or inactive player, the system does not gain very much information from that because there is a lot of uncertainty surrounding each player's MMR. It gets the most information by matching you against active players. Note that the system doesn't prefer active players in searches, it just so happens that you're more likely to be matched against an active player because they play more often. If you beat the active Master-level players (which compose roughly 2% of the active population) enough that your moving average moves comfortably into the Master region, you can be promoted.
Second, it's important to know that promotion and demotion also hinges upon a certain confidence level. If you start in Bronze, for example, in order to get promoted into Silver you would have to raise that moving average a fair amount of the way into Silver to prove that you belong there. Demotion is no different.
Therefore, it doesn't inherently mean that by getting promoted that you automatically boot someone else back down to Diamond. For example, if one of the people already in Master league goes inactive, then nobody will get demoted. If, on the other hand, all the active players are still playing games but someone's moving average has fallen into around the mid-Diamond region (thereby proving to the system that that person didn't actually belong in Master league), that person would get demoted.
Hope that answers your question, I understand if that's somewhat confusing. Let me know if you have questions on it and I'll try to clarify further. =]

ibid
So what does this mean for your original question?
While technically all leagues should have equal distribution (except for Diamond and Master), in reality, we'll see a much larger number of users in lower leagues as they have been dubbed inactive.  If we look at the distribution of bonus points across leagues, its not hard to see that players in lower leagues have many more bonus points, and thus are more likely to be dubbed inactive, and not taken into account for the distribution.
I guess the ultimate TL;DR here is: Its even for active players, and lower leagues have more inactive players, thus more players.


text:
Q: Confusion about Go back N ARQ Go-Back-N window size
In the second image on the above Page's answer, what will happen after all the three ACKs have been lost? Won't the system get stuck? Sender will keep sending frames 0,1,2 but since the receiver expects frame 3, it will not send an ACK. It will be silent forever, and the sender will keep sending frames 0,1,2 forever, after timeouts. Please explain.

A: My answer is straight No.
Here when that timeout timer timeouts, as happened in this case since acks got lost. Thus the sender will retransmit the data. But you see, the receiver will again send ack because this is what happens in Go-Back-N if ack gets lost. Also, do note that the receiver will discard the packets since it got it before only. Now when the sender will get the ack, it will send again as per win size.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sampling states of an "unnatural" Hamiltonian System I would like to sample from a Gibbs distribution given by
$$f(p, q) = \frac{1}{\mathcal{Z}}e^{-H(p, q; \omega, J)}$$
where $H$ is the Hamiltonian on generalized coordinates $(p,q)\in \mathbb{R}^{2n}$ defined by
\begin{align}
H(p,q; \omega, J)& = \sum_{\ell=1}^n \frac{\omega_{\ell}}{2}(q_{\ell}^2 + p_{\ell}^2) \\
&+ \frac{1}{4}\sum_{\ell, m = 1}^n J_{\ell, m}(q_{\ell}p_{m} - q_m p_{\ell})  \cdot (q_m^2 + p_m^2 - q_{\ell}^2 - p_{\ell}^2)
\end{align}
$$$$
explored in this paper. We take $J$ to be symmetric. Notice that $H$ is not a ``natural" Hamiltonian expessible as $H(p,q) = K(q) + U(p)$ so that, for instance, it is not easy to calculate a marginal on $p$ or $q$ and then use Hamilton's equations to propose new samples for the remaining coordinates in the manner of Hamiltonian MCMC. I'm not sure I can use Gibbs sampling either, since I don't see any tractable conditionals.
Any help with this or references to "unnatural" Hamiltonian systems would be greatly appreciated.
Edit: "Eq. 4" in the comments is the action-angle reparameterization,
$$H(I, \theta; \omega, J) = \sum_{\ell}^n \omega_{\ell} I_{\ell} - \sum_{\ell, m = 1}^n J_{\ell, m}\sqrt{I_{\ell}I_m} \cdot (I_m - I_{\ell})\sin(\theta_m - \theta_{\ell}).$$


text:
Q: Ubuntu Server 15.10, autologin? I'm trying to set up a home server for share printers and files, and I would like to enable auto login at startup, but anything of what I found on the internet worked. Is there any possibility to do this?

A: I edited the symbolic link in /etc/systemd/system/getty.target.wants/getty@tty1.service adding the --autologin param to agetty.  This way:
ExecStart=/sbin/agetty --noclear --autologin <username> %I $TERM

I hope it helps o/


text:
Q: Problem with Integrating Xero API with Laravel using public App - manual action required I am integrating the Xero api using public app with my laravel project which is a API project. I have gone through the xero documentation, and official youtube video (https://youtu.be/BzZpgSHdKfU) for xero-api integration.
I am using library calcinai/xero-php and referring to: https://github.com/calcinai/xero-php/blob/master/examples/public.php
Here i am facing an problem while integrating the api because after hitting /oauth/RequestToken endpoint, it required a manual action which is opens oauth/Authorize?oauth_token={oauth_token}
(here oauth_token received in earlier request)  to get a OTP or oauth_verifier code to complete authentication process.
In my project i want to do whole authentication process at back-end which i believe not works because of the manual action required.
May be i perceived and doing it wrong way, Please suggest me right way or any alternate.
manual action -> hitting the url from browser.
Thanks in advance.

A: You need to read about the different application types at https://developer.xero.com/documentation/getting-started/api-application-types. What you've linked is a public application which requires the user to click to authenticate and provides your application with 30 minutes of access.
For permanent access to a Xero account, you need to use a private application and setup access for each Xero account through https://developer.xero.com/myapps.


text:
Q: Why I am getting an error for QQLine plot in R While trying to draw QQ-Line plot ,I am getting the below error:

Error in int_abline(a = a, b = b, h = h, v = v, untf = untf, ...): plot.new has not been called yet
Traceback:

*

*qqline(resid(linm))

*abline(int, slope, ...)

*int_abline(a = a, b = b, h = h, v = v, untf = untf, ...)*

qqline(resid(linm))

Any clue to solve this would be much appreciated.
thanks

A: You can use something like
library(mlbench)

data(BostonHousing)

#Fit the model
fit.lm <- lm(medv~.,data = BostonHousing)

#Calculate the residuals for the model
x <- residuals(fit.lm, type="deviance")

#First draw the theoretical quantile vs. residuals plot
qqnorm(x, ylab = "Deviance Residuals")

#Then add the line to that plot
qqline(x)

A: Both of you Jared_mamrot and Bappa Das are correct in your way. But I found the below code to get me out of the problem. In fact,
qqnorm(residuals(linm))
qqline(residuals(linm))

Actually, it worked when I ran both qqnorm and qqline together (i.e. in a single cell).
thanks


text:
Q: Mod error due to input vector in vhdl m<=(s-1) mod 2

Here 'm' is a signal while s is an input vector
While trying to implement the code I am getting an error "mod cannot have such operands in this context"
Error might be due to trying to get mod of vector value.
Is there any way to either equate the vector to an integer value or correct the error via some other method?

A: Since mod 2 is basically just extracting the last bit of the vector and the -1 is just negating this, why not just do:
m <= not s(0);

A: I assume 's' is defined as a 'std_logic_vector'.  You better/should use 'unsigned' or 'signed' from the 'ieee.numeric_std' library for those operators.  You can convert your 'std_logic_vector' to 'signed' or 'unsigned' with a typecast.  E.g. unsigned(s).
Anyhow: Sonicwave's solution is cleaner.

A: Either use an integer for the vector instead (ie change the type of the signal) or convert it to an integer before moding
use ieee.numeric_std.all;

i := to_integer(unsigned(s));
m := (i-1) mod 2;


text:
Q: Highlighting code with mouse goes wild in Visual Studio Code When I try to highlight some code in Visual Studio code it goes crazy and moves very fast. E.g. I want to select around one page and end up selecting 10 "pages" worth of code.
How can I make it act normaly when I want to highlight some code?

A: I used to have the same issue. A weird behavior with mouse selection. This was my solution path.
Check for hardware failures.

*

*Unplug the keyboard dongle. If suddenly the mouse selection goes well. Do this steps.

*Check for keys stucked ✅

*Uninstall the keyboard driver from Device Manager ✅

*Change the dongle USB port ✅

And after all this steps, my cursor comes back to normality... for a while .

*

*Made the keyboard check with keyboard tester

*Detect the key with the failure (Fortunately Insert in my case).

*Download the app keytweak and disable that key.

This is a workaround if you don´t want to buy a new keyboard. I hope your failing key isn't any vocal . If so... buy a new one.


text:
Q: Does a product see any difference from being powered by a single phase 240 V European outlet versus 240 V from a split phase 240V (120/120) US outlet? I have seen similar questions and the answers always move on to the physics of the transformer and a center tap. I get all that, I think. My question is whether sophisticated electronics (specifically EV chargers) can tell any difference.
More succinctly, will a European car charger accustomed to receiving 240V over a single Line and Neutral react poorly (or even know) when connected to the US grid 240V over two 120V split phase Lines?

A: Yes, there is a difference, but another thing is if it matters and it depends on how the charger is built.
240 VAC single phase means one wire is neutral at 0V potential (bonded to earth/ground somewhere in the system) and the other wire is the 240 VAC live. The typical US household system means you also have 240 VAC but with center-tapped 0V neutral so you have two 120 VAC live wires.
So basically a simple device would not care how it receives 240 VAC but a more complex device could.
If the charger has a non-polarized mains plug then it must have been made so that which way the mains input live and neutral are must be irrelevant. If it is a fixed installation or has a polarized plug then it may matter which way live and neutral are connected.
So there can be no generic yes/no answer for any car charger you might mean.

A: The difference between a single-phase product made for Europe and that for the US (240V) would be as follows:

*

*The input voltage: Europe - 230 V and US - 240 V.

*The frequency: Europe - 50 Hz and US - 60 Hz.

*The mains fuse: Europe - single fuse in line L and US - two fuses, one in line L1 and the other in line L2.

More succinctly, will a European car charger accustomed to receiving 240V over a single Line and Neutral react poorly (or even know) when connected to the US grid 240V over two 120V split phase Lines?

No charger would be capable of recognizing the difference.
The European charger would work normally in the US, provided the 240 V supply is within 230 V +/- 5%.
However, the additional fuse would need to be incorporated.

A: If you wanted the circuit to be able to tell the difference, you could have it measure the power frequency. European grids operate at 50 Hz, and North American ones at 60 Hz. Easy enough to tell the difference if you're trying.
If you're wondering if it'll actually affect anything, almost certainly not. Especially not with modern electronics; old equipment with mains-frequency transformers could have problems if operated at a lower line frequency than it's designed for, but modern equipment based on switching converters doesn't generally care what the mains frequency is.


text:
Q: "Connection reset by peer exception" in android Here is my code to extract data from sql server using ksoap2 library.
But sometimes it returns connection reset by peer exception.
While searching on this exception gives a solution:

System.setProperty("http.keepAlive", "true");

But still I get this exception,please help me to solve this issue.
System.setProperty("http.keepAlive", "true");
SoapObject request = new SoapObject("http://tempuri.org/", method);
PropertyInfo pio = new PropertyInfo();
pio.setName(name);
pio.setValue(0);
pio.setType(String.class);
request.addProperty(pio);
SoapSerializationEnvelope envelope = new  SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new  HttpTransportSE(address,30000);
androidHttpTransport.call(soapaction, envelope);
Object jObj = (Object)envelope.getResponse();


text:
Q: error C2228: left of '.DXGI_MODE' must have class/struct/union Direct X I am trying to setup my swap chain Buffer but I get the following error
error C2228: left of '.DXGI_MODE' must have class/struct/union
1>        type is 'DXGI_MODE_SCANLINE_ORDER'

Note sure what I am doing wrong. here is the code
DXGI_SWAP_CHAIN_DESC swapChainDesc;

    // Set the width and height of the buffers in the swap chain
    swapChainDesc.BufferDesc.Width = 640;
    swapChainDesc.BufferDesc.Height = 480;

    // Set the refresh rate. This is how often the buffers get swapped out
    swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
    swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;

    // Set the surface format of the buffers
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDesc.BufferDesc.ScanlineOrdering.DXGI_MODE;
    //_SCANLINE_ORDER_UNSPECIFIED;
    swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;

    // Set how the buffers are used. Since you are drawing to the buffers, they are
    //considered a render target
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

    // Set the number of back buffers, 1 is the minimum and normally sufficient
    swapChainDesc.BufferCount = 1;

    // A handle to the main application window
    swapChainDesc.OutputWindow = hWnd;

    // Set whether you are running in a window or fullscreen mode
    swapChainDesc.Windowed = TRUE;

    // How the buffers are swapped. Discard allows the buffers to be overwritten
    //completely when swapped.
    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_NONPREROTATED;

A: Shouldn't this bit
swapChainDesc.BufferDesc.ScanlineOrdering.DXGI_MODE;
//_SCANLINE_ORDER_UNSPECIFIED;

in fact be
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;

?

A: Did'n you mean
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE;
instead of
swapChainDesc.BufferDesc.ScanlineOrdering.DXGI_MODE;

A: swapChainDesc.BufferDesc.ScanlineOrdering is an enum DXGI_MODE_SCANLINE_ORDER, not a class type.
Use something like the following instead:
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;


text:
Q: USB memory stick presents as two storage devices I have a USB memory stick that, when inserted into a computer, appears as two devices. The first is a CD-ROM drive and the second is a normal USB mass storage device.
dmesg gives the following:
[35325.116114] usb 1-2: new full speed USB device using ohci_hcd and address 7

[35325.868988] usbcore: registered new interface driver uas
[35325.875607] Initializing USB Mass Storage driver...
[35325.875675] scsi3 : usb-storage 1-2:1.0
[35325.876380] usbcore: registered new interface driver usb-storage
[35325.876382] USB Mass Storage support registered.
[35327.089961] scsi 3:0:0:0: CD-ROM            USB      Flash Disk       3000 PQ: 0 ANSI: 2
[35327.099399] scsi 3:0:0:1: Direct-Access     USB      Flash Disk       3000 PQ: 0 ANSI: 0 CCS
[35327.130825] sr1: scsi3-mmc drive: 0x/0x caddy
[35327.130956] sr 3:0:0:0: Attached scsi CD-ROM sr1
[35327.131047] sr 3:0:0:0: Attached scsi generic sg2 type 5
[35327.131205] sd 3:0:0:1: Attached scsi generic sg3 type 0
[35327.168612] sd 3:0:0:1: [sdb] 3905536 512-byte logical blocks: (1.99 GB/1.86 GiB)
[35327.182318] sd 3:0:0:1: [sdb] Write Protect is off
[35327.182322] sd 3:0:0:1: [sdb] Mode Sense: 43 00 00 00
[35327.223709] sd 3:0:0:1: [sdb] No Caching mode page present
[35327.223723] sd 3:0:0:1: [sdb] Assuming drive cache: write through
[35327.308129] sd 3:0:0:1: [sdb] No Caching mode page present
[35327.308133] sd 3:0:0:1: [sdb] Assuming drive cache: write through
[35327.336280]  sdb: sdb1
[35327.443196] sd 3:0:0:1: [sdb] No Caching mode page present
[35327.443201] sd 3:0:0:1: [sdb] Assuming drive cache: write through
[35327.443204] sd 3:0:0:1: [sdb] Attached SCSI disk
[35331.073317] UDF-fs: Partition marked readonly; forcing readonly mount
[35331.083014] UDF-fs INFO UDF: Mounting volume 'Tervetuloa', timestamp 2010/06/16 17:10 (10b4)

The memory stick seems to work like a U3 smart drive, but U3_tool won't recognize it.
What is this memory stick, and how do I remove and/or modify files on the CD drive?

A: I have already seen several devices of this kind, and I have been unable to modify the partitions in order to end up having just an ordinary storage device.
I'm afraid that the manufacturer makes these configurations at hardware / firmware level and these can not be undone, at least in a ordinary way.

A: Some USB sticks can be configured to present themselves as two or three storage devices. This works at firmware level – instead of a single disk with partitions, the OS sees two or three separate devices, so you cannot just repartition it.
(U3 is just one example. Another manufacturer, the name of which I forget, sells USB sticks with a ~200 MB read-only partition holding ~20 MB of promo JPEGs and Kaspersky trialware.)
You need special software to reconfigure the drive. Unfortunately, most such programs are Windows-only, not officially available to the public, and you have to know the flash controller being used inside your USB stick and find the specific program.

*

*Tools for U3 drives are widely available.

*UT165 – I have used this myself to remove the aforementioned Kaspersky junkware, seems like a common controller type.

*iCreate
if anyone has programs for other types, feel free to add.

A: Can you repartition the memory stick? That's how U3 works. It keeps the U3 data on one partition, and your data on another. You might also try using Sandisks U3 Removal Tool. I think that's what I did.


text:
Q: Properly test interfaces in c# private methods I am new to c#.  I do have some experience testing javascript.  I was looking at assessing this test similar to checking for a method to be called in with a spy via sinon.
However,  I am not truely sure what to test.  As I noted I am pretty new to c# and am doing testing to get a feel for how the code works.
Here is the private method that I need to test for
 private TicketResponse.PaymentType GetPaymentType(TicketResponse.FormOfPaymentCreditCard paymentType, VCR_DisplayRSTicketingInfosTicketingInfoTicketingTicketDataTourInfo tourInfo)
    {

I read that I test the interfaces. So I am testing something along these lines?
 public enum PaymentType
{
    CASH, CREDIT_CARD, NITP, TRAVEL_CREDIT, GIFT_CARD, JETBLUE_REWARDS, NONE, CHECK, EXCHANGE
}

Any insight would be super helpful thanks.

A: The usual testing methodology is to only test the public interfaces to your class. Testing the private methods usually creates brittle tests, and doesn't necessarily test the public endpoints that other client classes will be using.
If you only test the public interface, you make it easier to change the details/implementation (in the private methods) without breaking the tests.

A: You can't test a private method because it's not visible outside the class in which it's defined.
If you want your method to be testable it has to be public or have a public wrapper.
Private methods are usually tested indirectly via tests on the public methods that call them.


text:
Q: Queries realted to Dropdown list in MVC I am a new to ASP.NET MVC, I am developing an application. I want to bind the data in the drop down list in create view.
How to bind the data in the drop down? I have go through many question and answers here...

*

*I have seen usually everyone suggested to use  List<SelectListItem> what is its purpose?

*Do I need to use ViewModel while binding the data to drop down list?
Can I get simple example where data get bind in the dropdown using viewbag?
I have created a list in controller
 List<string> items = new List<string>();

and I want to pass this list to view using viewbag and simply want to bind to drop down list.
How to do this ?

A: I'd suggest using a ViewModel as it makes interaction with user input so much easier. Here's an example of how you might bind data from your ViewModel to a drop down in your View. First, the ViewModel:
public class CrowdViewModel
{
    public string SelectedPerson { get; set;}
    public IEnumerable<SelectListItem> People { get; set; }
}

So yes, you're right - use a collection of SelectListItems. I'm guessing in your case, the SelectListItem's Value and Text property will be the same. You could turn your List into IEnumerable like this:
[HttpGet]
public ActionResult Home()
{
    // get your list of strings somehow
    // ...

    var viewModel = new CrowdViewModel
    {
        People = items.Select(x => new SelectListItem { Text = x, Value = x })
    }

    return View(viewModel);
}

Now you need to bind that ViewModel's property to the DropDown on your view. If you're using the Razor ViewEngine, the code will look something like this:
@model MyApp.ViewModels.CrowdViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(model => model.SelectedPerson, Model.People)
}

Now when you post that form, MVC will bind the selected value to the ViewModel's SelectedPerson property!
[HttpPost]
public ActionResult Home(CrowdViewModel viewModel)
{
    // viewModel.SelectedPerson == whatever the user selected
    // ...
}

Easy as that!

Update:
If you really want to use the ViewBag (don't do it), you can pass your list through from your Controller action like so:
[HttpGet]
public ActionResult Home()
{
    ViewBag.People = new List<string> { "Bob", "Harry", "John" };
    return View();
}

And then create a SelectList on your View:
@Html.DropDownList("SelectedPerson", new SelectList(ViewBag.People, Model))


text:
Q: Translating a C++ (dealing with corona) function into C# i had a C++ .exe i was using as a standalone image cleaner.
But i now want to use its fonction into my own c# app, so i started to translate it. But i REALLY TOTALLY know nothing about C++ and its logic.
So i come here for some help.
First, does anyone know any equivalent for this function?
Corona "getPixels()" (yes with an "s" because i know c# have a built-in getPixel) :
here is the function explaination from corona doc : getPixels() Corona dll
it is used in the lines i am looking to translate.
here is all the thing:
original C++ code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "corona.h"

#define IMAGE_FORMAT corona::PF_R8G8B8 /* RGB mode - 8 bits each */
#define GetXY(x,y, w)  ((x) + ((w) * (y)))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))

#define SQ(a) ((a) * (a))
#define DISTANCE(a, b, c, d) (SQ(a - c) + SQ(b - d))

int main(int argc, char **argv)
{
corona::Image *img;
unsigned char *pixels;
int threshold = 0;
int distance = 0;
int pixel;
char str[255];
int rows, cols;
int row, col;
unsigned char *bitmap, *p;
unsigned char *outmap;
pixels = (unsigned char*)img->getPixels();
rows = img->getHeight();
cols = img->getWidth();
bitmap = new unsigned char[rows * cols];
p = bitmap;
outmap = new unsigned char[rows * cols];

//convert to single byte grayscale
for (row = 0; row < rows; row++)
for (col = 0; col < cols; col++)
{
    pixel = *pixels++;
    pixel += *pixels++;
    pixel += *pixels++;

    *p++ = pixel / 3;
}

//free corona loading
delete img;

int distance = 8;
int threshold = 7;
//check our threshold
for (row = 0; row < rows; row++)
for (col = 0; col < cols; col++)
{
    if (bitmap[GetXY(col, row, cols)])
    {
        int count = 0;
        int x, y;
        int dhalf = distance / 2 + 1;

        //optimization possible here by checking inside a circle rather than square+dist
        for (x = MAX(col - dhalf, 0); x < MIN(col + dhalf, cols); x++)
        for (y = MAX(row - dhalf, 0); y < MIN(row + dhalf, rows); y++)
        {
            if (SQ(distance) > DISTANCE(col, row, x, y) && bitmap[GetXY(x, y, cols)])
                count++;
        }

        if (count >= threshold)
            outmap[GetXY(col, row, cols)] = 255;
        else
            outmap[GetXY(col, row, cols)] = 0;
    }
    else
        outmap[GetXY(col, row, cols)] = 0;
}
}

What i have now with what i could translate... i hope correctly at least...:
private Bitmap optIm2(Bitmap _img)
        {
            int rows = _img.Height;
            int cols = _img.Width;
            pixels = (unsigned char)img->getPixels();  //here i dont know at all
            bitmap = new unsigned char[rows * cols];  //here i dont know at all
            p = bitmap;
            outmap = new unsigned char[rows * cols];  //here i dont know at all

            //convert to single byte grayscale
            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                    pixel = *pixels++;  //here i dont know at all
                    pixel += *pixels++;  //here i dont know at all
                    pixel += *pixels++;  //here i dont know at all

                    *p++ = pixel / 3;  //here i dont know at all
                }
            }
            //free corona loading
            delete img;

            int distance = 9;
            int threshold = 7;

            //check our threshold
            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                    if (bitmap[GetXY(col, row, cols)])
                    {
                        int count = 0;
                        int x, y;
                        int dhalf = distance / 2 + 1;

                        //optimization possible here by checking inside a circle rather than square+dist
                        for (x = Math.Max(col - dhalf, 0); x < Math.Min(col + dhalf, cols); x++)
                        {
                            for (y = Math.Max(row - dhalf, 0); y < Math.Min(row + dhalf, rows); y++)
                            {
                                if (SQ(distance) > DISTANCE(col, row, x, y) && bitmap[GetXY(x, y, cols)])
                                    count++;
                            }
                        }
                        if (count >= threshold)
                        {
                            outmap[GetXY(col, row, cols)] = 255;
                        }
                        else
                        {
                            outmap[GetXY(col, row, cols)] = 0;
                        }
                    }
                    else
                    {
                        outmap[GetXY(col, row, cols)] = 0;
                    }
                }
            }
return iDontKnowWhatYet;
        }

        private int GetXY(int x,int y, int w) { return ((x) + ((w) * (y))); }
        private int SQ(int a) { return ((a) * (a)); }
        private int DISTANCE(int a, int b, int c, int d) { return (SQ(a - c) + SQ(b - d)); }

Could anyone help me understand and convert this please?

A: The C# code will look something like this
private unsafe Bitmap optIm2(Bitmap img)
{
    int rows = img.Height;
    int cols = img.Width;

    var dstImg = new Bitmap(cols, rows, img.PixelFormat);
    var srcImageData = img.LockBits(new Rectangle(0, 0, cols, rows), System.Drawing.Imaging.ImageLockMode.ReadOnly, img.PixelFormat);
    var dstImageData = dstImg.LockBits(new Rectangle(0, 0, cols, rows), System.Drawing.Imaging.ImageLockMode.ReadOnly, dstImg.PixelFormat);
    try
    {
        var bitmap = new byte[rows * cols];
        var outmap = new byte[rows * cols];

        fixed (byte* ptr = &bitmap[0])
        {
            byte* pixels = (byte*)srcImageData.Scan0;
            byte* p = ptr;

            //convert to single byte grayscale
            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                    var pixel = *pixels++;
                    pixel += *pixels++;
                    pixel += *pixels++;

                    *p++ = (byte)(pixel / 3);  //here i dont know at all
                }
            }
        }

        int distance = 9;
        int threshold = 7;

        //check our threshold
        for (int row = 0; row < rows; row++)
        {
            for (int col = 0; col < cols; col++)
            {
                if (bitmap[GetXY(col, row, cols)] != 0)
                {
                    int count = 0;
                    int x, y;
                    int dhalf = distance / 2 + 1;

                    //optimization possible here by checking inside a circle rather than square+dist
                    for (x = Math.Max(col - dhalf, 0); x < Math.Min(col + dhalf, cols); x++)
                    {
                        for (y = Math.Max(row - dhalf, 0); y < Math.Min(row + dhalf, rows); y++)
                            if ((SQ(distance) > DISTANCE(col, row, x, y)) && (bitmap[GetXY(x, y, cols)] != 0))
                                count++;
                    }
                    if (count >= threshold)
                        outmap[GetXY(col, row, cols)] = 255;
                    else
                        outmap[GetXY(col, row, cols)] = 0;
                }
                else
                    outmap[GetXY(col, row, cols)] = 0;
            }
        }

        // Copy data from outmap to pixels of bitmap. Since outmap is grayscale data, we replicate it for all channels
        byte* dstPtr = (byte*)dstImageData.Scan0;
        for (int row = 0; row < rows; row++)
        {
            byte* rowPtr = dstPtr;
            for (int col = 0; col < cols; col++)
            {
                *rowPtr++ = outmap[GetXY(col, row, cols)];
                *rowPtr++ = outmap[GetXY(col, row, cols)];
                *rowPtr++ = outmap[GetXY(col, row, cols)];
            }
            dstPtr += dstImageData.Stride;
        }
    }
    finally
    {
        img.UnlockBits(srcImageData);
        img.Dispose();

        dstImg.UnlockBits(dstImageData);
    }

    return dstImg;
}

private int GetXY(int x, int y, int w) { return ((x) + ((w) * (y))); }
private int SQ(int a) { return ((a) * (a)); }
private int DISTANCE(int a, int b, int c, int d) { return (SQ(a - c) + SQ(b - d)); }

While I haven't checked your actual logic for the correct algorithm, the code above contains all the bits you need to do that yourself. The main points to note are:

*

*How to get a pointer from an IntPtr (fixed)

*How to get pixel data from a bitmap

*How to write pixel data back to a bitmap

Hope this helps!


text:
Q: Dynamically add content to an existing widget area I have an existing widget area / sidebar.  Rather than adding content to it via Appearance ? Widgets in the Dashboard, I want to inject content into the widget area from functions.php.
Is there hook that allows this?
Thanks :)

A: Yes by using widget_text inject content into the widget area
Add the following code into your function.php file
function widget_content( $content )
{
    // add $content as you want
    return $content;
}

add_filter( 'widget_text', 'widget_content', 99 );

A: Also, you can write a function in the functions.php file and call that function via the widget.
Functions.php:
function myFunction() {
    //do something here
}
add_shortcode('wp_my_function', 'myFunction');

//Allow write shortcode in widgets
add_filter('widget_text', 'do_shortcode');

In the Widget:
Use the text widget, write in the shortcode: [wp_my_function]


text:
Q: Why is ODE15s ignoring my boundary conditions for the Fishers equation? I'm attempting to solve the Fishers PDE on $(x,t) \in (0,1)\times (0,T)$ by spatially discretising (method of lines) and then feeding the time derivative to ODE15s (therefore creating a system of ODEs). Here's the equation in full;
$$\frac{\partial u}{\partial t} = \frac{\partial ^2 u}{\partial x^2} +u(1-u), \quad \quad \frac{\partial u}{\partial x}(0,t) = 0, \quad \quad u(1,t) = 0.$$ I've set the initial conditions as  $n(x,0) = 0.6(1-x^2)$  and then I have set the second element of this to $0.6$ so it respects the boundary conditions at $x=0$. Here's my code:
space_steps=500;
T=100;
x = linspace(0,1,space_steps).';
T_span=[0;T]; %T_vector
n_0 = 0.6*(1-x.^2);
n_0(2)=0.6;
[T_out,Y_out] = ode15s(@(t,y) Fisher(t,y,space_steps),T_span,n_0);

Here's the function 'Fisher' that does all the work:
function output = Fisher(~,input,space_steps)
n = [input(2);input(2:end-1);0];    %dndx = 0 at x=0 so input(1)=input(2), n=0 at the x=1.
dx=1/(space_steps-1);               %Delta x
np = [n(2:end);NaN]; %n_{i+1}
nm=[NaN;n(1:end-1)]; %n_{i-1}
%Second order derivative with a forward and backward finite difference quotient at each boundary respectively
d2ndx2 = [(2*n(1)-5*n(2)+4*n(3)-n(4))/dx; np(2:end-1)-2*n(2:end-1)+nm(2:end-1);(2*n(end)-5*n(end-1)+4*n(end-2)-n(end-3))/dx]/dx^2;
dndt =  d2ndx2 + n.*(1-n); %sets up the equation
output = dndt; %gives it to ODE15s
end

Now for some reason the function or ODE15s is completely ignoring the two boundary conditions I am prescribing it at each run at the begining. Could anyone explain why this is and provide a suitable remedy? Thanks. I'd also appreciate any feedback on my code that you could offer.

A: You want to use $u_0(t)=u_1(t)$, $u_N(t)=0$ to implement the boundary conditions.
That leaves the inner nodes as unknown state variables $u_1(t),...,u_{N-1}(t)$, so it will not be the solver that ignores the boundary values, you construct the code to ignore them from the outset in the computation and only reconstruct and insert them as intermediate values where they are needed. That is, in the computation of the time derivative for the inner nodes via the central second order difference quotient. There is then also no need for one-sided second-order difference quotients, as the differential equation is not evaluated for the outer nodes. You can do this with the code
x = linspace(0,1,space_steps+1).';
dx = x(2)-x(1);
g = @(x) 0.6*(1-x.^2);
n0 = g(x(2:end-1));

function dndt = Fisher(~, u, dx)
    f = n*(1-n);
    dndt = conv([ n(1); n; 0], [1,-2,1], shape="valid")/dx^2 + f;
end;


text:
Q: An error has occurred. Please contact your system administrator. (6632) error in Jasper server 6.2 I am using Jasper report :- TIBCO Jaspersoft Studio-6.2.0.final
           Jasper server :- JasperReports Server Community Edition (v6.2.0)
I published Report book template Jasper report into Jasper Server. But when I am running report from Jasper Server, I am getting below error

Error Message
  An error has occurred. Please contact your system administrator.
  (6632) Error Trace
  com.jaspersoft.jasperserver.api.JSSecurityException: An error has
  occurred. Please contact your system administrator. (6632) Arguments:
  at
  com.jaspersoft.jasperserver.api.security.validators.Validator.validateSQL(Validator.java:500)
  at
  com.jaspersoft.jasperserver.api.engine.jasperreports.util.JRTimezoneJdbcQueryExecuter.createDatasource(JRTimezoneJdbcQueryExecuter.java:167)
  at
  net.sf.jasperreports.engine.fill.JRFillDataset.createQueryDatasource(JRFillDataset.java:1129)
  at
  net.sf.jasperreports.engine.fill.JRFillDataset.initDatasource(JRFillDataset.java:696)
  at
  net.sf.jasperreports.engine.fill.JRFillDatasetRun.evaluate(JRFillDatasetRun.java:226)
  at
  net.sf.jasperreports.engine.fill.JRFillElementDataset.evaluateDatasetRun(JRFillElementDataset.java:238)
  at
  net.sf.jasperreports.engine.fill.JRFillCrosstab.evaluate(JRFillCrosstab.java:610)
  at
  net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:281)
  at
  net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:504)
  at
  net.sf.jasperreports.engine.fill.JRVerticalFiller.fillColumnBand(JRVerticalFiller.java:2026)
  at
  net.sf.jasperreports.engine.fill.JRVerticalFiller.fillDetail(JRVerticalFiller.java:752)
  at
  net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:259)
  at
  net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:119)
  at
  net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:558)
  at
  net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:396)
  at
  net.sf.jasperreports.engine.fill.JRFillSubreport.fillSubreport(JRFillSubreport.java:742)
  at
  net.sf.jasperreports.engine.fill.JRSubreportRunnable.run(JRSubreportRunnable.java:58)
  at
  net.sf.jasperreports.engine.fill.AbstractThreadSubreportRunner.run(AbstractThreadSubreportRunner.java:216)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
  at java.lang.Thread.run(Unknown Source)

I already updated security.validation.sql.on=false in security-config.properties file.
But still I am getting this error.
How to resolve this issue?

A: You might be using some special keywords in your SQL query (such as "with" clause).
You may need to edit the jasperserver-pro/WEB-INF/classes/esapi/validation.properties file.
And edit the line,
Validator.ValidSQL=(?is)^\s*(select|ADD_NEW_CLAUSE_HERE)\s+^;+$.
And restart the server.
Proving the queries you use will be helpful for a more comprehensive answer.

A: for security reasons(!) I personally would recommend (using it is quite insecure as described below!) to

*

*set this to
Validator.ValidSQL=.*

or even better
#/jasperserver/WEB-INF/classes/esapi/security-config.properties
security.validation.sql.on=false

so there is no validity check actually done.
Why? Because the previous (standard regexp) is a quite weak (and immature - as e.g. preventing with ... select ... clauses) check and may suggest that SQL injection would be prevented in a higher degree.
A) if I am NOT concerned about security/SQL injection in my environment or the cost-value-factor is inefficient (take non-IT budget-responsible people into the boat to decide here!), I would leave it like this for now
B) if I am concerned about security/SQL injection in my environment, I would recommend to

*

*read articles about SQL injection and how to prevent it robustly and continually on many necessary levels (e.g. also db user rights) updated for my target databases/ORM frameworks, e.g.

*

*Oracle: Defending Against SQL Injection Attacks

*Oracle: 12c DBMS_ASSERT Package

*PostgreSQL: quote_*(...) functions

*...

*search for better regexp clauses (if existent)? => seems an improper/week method to me only suitable for "little PHP shop style apps"


text:
Q: Topology of $L^2$ space Cardinality of space of all funcions $f: \mathbb R \rightarrow \mathbb R$ is $\beth_2$. However, cardinality of space of all such square-integrable functions, space $L^2$, is $\beth_1=\mathfrak c$, equal to cardinality of $\mathbb R^n$.
So, from set-theoretical point of view, $L^2$ is as big as usual manifolds, which motivates the question:
What are the topological properties of $L^2$ space (with usual topology) and, more precisely, is there any manifold which is homeomorphic to $L^2$?


text:
Q: Where are the start menu customization pictures located on Windows 8? I would like to take some of the images in the red area shown below for personal use. Are they contained in a specific folder, and if so, which one?

A: The pictures are hidden in a DLL file. The file is located at C:\Windows\System32\imageres.dll. You'll need a tool called Resource Hacker to extract the files. To do this:

*

*Copy the DLL file to your desktop.

*Open Resource Hacker and go to File and then Open.

*Choose the DLL file on your desktop.

*The patterns are in the PNG folder.

Unfortunately, these pictures are all just bits and pieces of the wallpaper because some people have longer start screens that require the pattern to repeat over and over.


text:
Q: JS - Do I need to explicitly import JSDoc typedefs in VS Code to have intellisense support? I have a module
camera.d.js
that only contains the following definition:
/**
 * @typedef {object} CropperConfiguration
 * @property {Dimension} dimensions - Dimensions.
 */

and imports the module
global.d.js
that contains the following definition:
/**
 * @typedef {object} Dimension
 * @property {number} width - Width.
 * @property {number} height - Height.
 */

So... if camera.d.js imports global.d.js... in my module CameraUtils.js, that imports camera.d.js, do I need to import global.d.js to access the Dimension definition?
I thought that yes, but... for some reason I don't understand, I can perfectly access this definition only importing camera.d.js and ignoring global.d.js.
Why?
--
Update
Full content of camera.d.js
/**
 * @file Camera type definitions.
 * @license MIT
 * @version 1.0.0
 * @since 1.0.0
 * @category utils
 * @subcategory camera
 * @module CameraTypes
 */

import "../global/global.d";

/**
 * @typedef {object} CropperConfiguration
 * @property {Dimension} dimensions - Dimensions.
 * @property {string} name - Cropper's vector icon name.
 * @property {string} type - Cropper's vector icon type.
 */

And... for importing the types in CameraUtils.js I just do:
import "./camera.d"; // global scope

...

A: I've been using JSDocs with VSCode IntelliSence for a few years now. By default, it's disabled, so you have to enable it first:
https://code.visualstudio.com/docs/languages/jsconfig
I have a public project you can reference from here:
https://github.com/clshortfuse/webhoster/blob/master/jsconfig.json
But basically, you need:
{
  "compilerOptions": {
    "checkJs": true,
  }
}

You don't need a.d.js file. You can inline them. You can also use a .d.ts file for complex types and then import the .js equivalent inline.
See: https://github.com/clshortfuse/webhoster/tree/master/types


text:
Q: Is there any procedure that guaranteed to find the Minimal CNF form of an expression $?$
For example: Find the Minimal CNF form of $abcd+a'b'c'd'$:

My attempts:
Consider $$abcd+a'b'c'd'$$
By Distributeive law we have:
$$\boxed{\begin{array}{ccccc}d'
&\color{orange}{a+d'}&b+d'&\color{red}{c+d'}&\top\\
c'&a+c'&\color{red}{b+c'}&\top&\color{orange}{d+c'}\\
b'&\color{red}{a+b'}&\top&\color{orange}{c+b'}&d+b'\\
a'&\top&\color{orange}{b+a'}&c+a'&\color{red}{d+a'}\\
\cdot&a&b&c&d
\end{array}}$$
That implies $abcd+a'b'c'd'\equiv \color{orange}{(a+d')}(b+d')\dots (c+a')\color{red}{(d+a')}$, however if we pick either $\color{red}{\text{red}}$ or $\color{orange}{\text{orange}}$ expressions and connect them with '$\cdot$'(and), they implies everything else.
For example, let's take $\color{red}{(a+b')(b+c')(c+d')(d+a')}$, then we have:
\begin{align}
&\color{red}{(a+b')(b+c')}\to\boxed{a+c'}\\
&\color{red}{(b+c')(c+d')}\to\boxed{b+d'}\\
&\color{red}{(a+b')(d+a')}\to\boxed{d+b'}\\
&\color{red}{(a+b')}(b+d')\to\boxed{\color{orange}{a+d'}}\\
&\color{red}{(d+a')}(b+d')\to\boxed{\color{orange}{b+a'}}\\
&\color{red}{(c+d')}(d+b')\to\boxed{\color{orange}{c+b'}}\\
&\color{red}{(b+c')}(d+b')\to\boxed{\color{orange}{d+c'}}\\
&\color{orange}{(b+a')(c+b')}\to\boxed{c+a'}\\
\end{align}
Hence we can take them out from the expression, similarly if we pick the $\color{orange}{\text{orange}}$ expression:
\begin{align}
&\hspace{3ex}abcd+a'b'c'd'\\
&\equiv\color{red}{(a+b')(b+c')(c+d')(d+a')}\\
&\equiv\color{orange}{(a+d')(b+a')(c+b')(d+c')}
\end{align}

Another approach is use a k-map, however 'Karnaugh maps do not always give the simplest expression.'
For example, again we consider  $abcd+a'b'c'd'$ that:
$$\boxed{\begin{array}{ccccc}
&a'b'&a'b&ab&ab'\\
c'd'&1&\color{blue}{0}&0&\color{lightgreen}{0}\\
c'd&0&\color{blue}{0}&0&\color{lightgreen}{0}\\
cd&0&\color{blue}{0}&1&\color{lightgreen}{0}\\
cd'&0&\color{blue}{0}&0&\color{lightgreen}{0}
\end{array}}
\boxed{\begin{array}{ccccc}
&a'b'&a'b&ab&ab'\\
c'd'&1&0&0&0\\
c'd&\color{red}{0}&\color{red}{0}&\color{red}{0}&\color{red}{0}\\
cd&0&0&1&0\\
cd'&\color{orange}{0}&\color{orange}{0}&\color{orange}{0}&\color{orange}{0}
\end{array}}\\
\boxed{\begin{array}{ccccc}
&a'b'&a'b&ab&ab'\\
c'd'&1&0&0&0\\
c'd&\color{lightblue}{0}&\color{lightblue}{0}&0&0\\
cd&\color{lightblue}{0}&\color{lightblue}{0}&1&0\\
cd'&0&0&0&0
\end{array}}
\boxed{\begin{array}{ccccc}
&a'b'&a'b&ab&ab'\\
c'd'&1&\color{lightgrey}{0}&\color{lightgrey}{0}&0\\
c'd&0&\color{lightgrey}{0}&\color{lightgrey}{0}&0\\
cd&0&0&1&0\\
cd'&0&0&0&0
\end{array}}$$
\begin{align}
&\hspace{3ex}(\color{blue}{a'b})'(\color{lightgreen}{ab'})'(\color{red}{c'd})'(\color{orange}{cd'})'(\color{lightblue}{da'})'(\color{lightgrey}{bc'})'\\
&\equiv(a+b')(a'+b)(c'+d)(d'+a)(b'+c)
\end{align}
Some works are still required here to simplify the expression $\dots$
Is there any procedure that guaranteed to find the  Minimal CNF form of an expression $?$
Update:
Would Quine–McCluskey algorithm apply on this $?$(I just found this algorithm, I think it might work $\dots$)

A: Yes, as you suspected in your update, the Quine-McCluskey algorithm is an algorithm with exactly this purpose.
Indeed, without a systematic algorithm, you are left with a kind of ad hoc 'trial-and-error' method of trying to simplify, like you do in the first part of your post.
And, as you realized, a K-map does not guarantee the most simple form either: you can, of course 'hit upon' a covering that turns out to be minimal, but without an algorithm you would have no guarantee it is in fact minimal. And, you could end up with a non-minimal covering .. as you yourself ended up with.
I should also point out that the Quine-McCluskey algorithm is typically presented for generating minimal DNF expressions ... but of course we can follow a completely analagous routine to find a minimal CNF.
Now, if do this for your particular example, you'd get a prime implicant chart with 14 implicants, and 12 prime implicants.  Unfortunately, none of the prime implicants are essential, and so you'll have to use something like Petrick's method to find a minimal covering.


text:
Q: How do you link MS Access 2016 to Visual Fox Pro dbf tables as linked tables? I have a Visual FoxPro set of tables (.dbf extension) which I want to create linked tables to in MS Access. The forums I have checked seem to indicate that the vfpodbc.dll is no longer supported. I have installed the new OLE driver, but it does not appear as an option in the Linked table manager for selection. I can access this driver from Excel 2016.
Question:
Am I limited to using the programatic link method via VBA or is there a way to get this to work using the Linked table manager?
My OS is Windows 10.
Visual FoxPro Software is "INFUSION version 8.414"

A: Using the FoxPro OLEDB driver, you will have to connect programmatically. There's no way to link tables the way you can from an ODBC data source.

A: Microsoft Dropped it's support since MS Jet 2.6, but you can try to use Advantage Database Server OBDC driver


text:
Q: Google Maps API geocoder (V3), how to set language on google.maps.GeocoderResult Is there any property that I can use in Google Maps geocoder (V3) to dynamically set  language in result (google.maps.GeocoderResult)?. Not using html header scrip tag <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=vi-VN"></script>
for example
var G = new google.maps.Geocoder(); // google geocoder
G.geocode({'location': ll/*, 'language':'vi-VN'*/}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
    if (results[0]) {
        me.set({'locate':results[0].address_components});
        me.set({'address':results[0].formatted_address});
    } else {
        alert("No results found");
    }
} else {
    alert("Geocoder failed due to: " + status);
}

Reason I want to build a region tree to connect point  have same region
        us
      /     \
   new york  ...
    /  \
   p1   p2

as shown, p1 and p2 are in the same region 'new-york'
thank you

A: I believe it used to be possible to do this in v2, but in v3, the choices are browser prefs, language localization via paramater in the API script URL, and region localization which is also via parameter in the API script URL.
If you want to share more information about your use case, it may be possible to come up with a solution/workaround.


text:
Q: php form submission-checking not being recognized I basically took in 3 pieces of data from a form, and before processing them, I just wanted to make sure that all fields were filled in.  So the focus of this is the second to last IF statement, checking if the different variables are empty.  It seems to only be working for the first variable and I can't figure out how to make it apply to all of them.
<?php

include ("account.php") ;
include ("connect.php") ;

$isdone = FALSE;
$un  =  $_REQUEST [ "un"] ;
$pw   =  $_REQUEST [ "pw"] ;

$data = mysql_query("SELECT * FROM `auth` WHERE username = '$un'") or die(mysql_error());

$info = mysql_fetch_array($data);

$info['username'];
$password = $info['pw'];

session_start();

if(trim($un) != '' && trim($pw) != '' && $password == $pw)
{

    $_SESSION['uze']=$un;

    include "problem.html";

}

elseif( !isset($_POST['submit1']) && $isdone == FALSE)
{
    echo "wrong password";
}

$selected =  $_REQUEST [ "type"] ;

if($selected == 'afs')
{
    $typeinc = 'afs';
}
else if($selected == 'db')
{
    $typeinc = 'database';
}
else if($selected == 'cs')
{
    $typeinc = 'computer systems';
}
else if($selected == 'pw')
{
    $typeinc = 'password';
}
else if($selected == 'hw')
{
    $typeinc = 'hardware';
}
else if($selected == 'other')
{
    $typeinc = 'other';
}

$text = $_REQUEST ["inc"];

$selected2 = $_REQUEST ["yesno"];

if($selected2 == 'yes')
{
    $email = 'yes';
}
else
{
    $email = 'no';
}

if(isset($_POST['submit1']))
{
    if(empty($typeinc) || empty($text) || empty($email))
    {
        print( 'You have not filled in all fields, click to sign in and re-enter' );
    }

}

else{
    mysql_query("INSERT INTO `swp5_proj`. `inci` (`type`, `date`, `time`, `reporter`, `desc`) VALUES ('$typeinc', CURDATE(), CURTIME(), '".$_SESSION['uze']."', '$text');") or die(mysql_error());

    mysql_query("DELETE FROM inci WHERE type = ' '");
$isdone = TRUE;

}

if(isset($_POST['submit1']) && $isdone == TRUE)
{
    echo "session over";
}

?>

A: if((trim($un) !== '') && (trim($pw) !== '') && ($password == $pw))

A: Make sure you clean your REQUEST variables before you put them in a MySQL query.

A: You're setting $email to yes or no in the line just above.

A: In your if statement you are using the shortcut OR operator.... As soon as a single statement evaluates to true, the entire statement evaluates to true and there is no need to continue processing further.


text:
Q: how to remove my app's folder from galleries? My app creates a folder, but strangely it appears in galleries.
Is there a way for the app to keep its folders "hidden" from galleries?
Thanks!

A: you can name your folder .Myfolder adding "." will make it invisible to the galleries


text:
Q: IOS UITableview in Storyboard cell's elements frame size and height shows zero I am creating an TableView and creating its cells as follows
static NSString *CellIdentifier = @"raffel";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UIView *Imv=(UIView*)[cell viewWithTag:100];
UILabel *Title=(UILabel*)[cell viewWithTag:101];
UITextView *TicketDetails=(UITextView*)[cell viewWithTag:102];
UILabel *BDprice=(UILabel*)[cell viewWithTag:103];
UILabel *USDprice=(UILabel*)[cell viewWithTag:104];
UILabel *TickRema=(UILabel*)[cell viewWithTag:105];

NSLog(@"fram %@",Imv);

and the log shows
fram <UIView: 0x1ed91bd0; frame = (0 171; 0 0); autoresize = TM+BM; tag = 100; layer = <CALayer: 0x1ed91c30>>

it shows zero height and width but actuall height*width is 100*100

A: implement this method in your code..
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
   return 100;
}


text:
Q: Get Value from Parcelable Array in Android I need to parse and get the Value from  :
Parcelable[] uuidExtra = intent.getParcelableArrayExtra("android.bluetooth.device.extra.UUID");

My goal is to get UUID from above Parcelable[]. How to achieve it?

A: Try something like this.  It worked for me:
   if(BluetoothDevice.ACTION_UUID.equals(action)) {
     BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
     Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
     for (int i=0; i<uuidExtra.length; i++) {
       out.append("\n  Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString());
     }

Hope this helps!

A: You need to iterate over the Parcelable[], cast each Parcelable to ParcelUuid and use ParcelUuid.getUuid() to get the UUIDs. While you can use toString() on the Parcelables as in another answer, this will give you only a String representing the UUID, not an UUID Object.
Parcelable[] uuids = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if (uuids != null) {
    for (Parcelable parcelable : uuids) {
        ParcelUuid parcelUuid = (ParcelUuid) parcelable;
        UUID uuid = parcelUuid.getUuid();
        Log.d("ParcelUuidTest", "uuid: " + uuid);
    }
}

A: The accepted answer is correct in quoting the docs and saying that the returned object is of type ParcelUuid. However, he does not offer the link to that; here it is:
BluetoothDevice.EXTRA_UUID.
Furthermore, the code provided is wrong in two ways; one, it does not refer to the same method as that of the question, and secondly, it's incompilable (taking some philological liberties here). To rectify both problems, the code should be:
Parcelable[] uuidExtra = intent.getParcelableArrayExtra("android.bluetooth.device.extra.UUID");
if (uuidExtra != null) {
   for (int j=0; j<uuidExtra.length; j++) {
      ParcelUuid extraUuidParcel = (ParcelUuid)uuidExtra[j];
      // put code here
   }
}

Thirdly, if one wants some extra protection (although, normally, the objects should always be ParcelUuid), the following can be used in the for:
   ParcelUuid extraUuidParcel = uuidExtra[j] instanceof ParcelUuid ? ((ParcelUuid) uuidExtra[j]) : null;
   if (extraUuidParcel != null) {
      // put code here
   }

This solution was offered by Arne. I just cannot add comments yet, and plus I offer the documentation page :)

A: From the docs it states that the extra is a ParcelUuid
So you should use
ParcelUuid uuidExtra intent.getParcelableExtra("android.bluetooth.device.extra.UUID");
UUID uuid = uuidExtra.getUuid();

Hope that helps.


text:
Q: Cannot compile method reference in JDK 11 I am currently migrating a project to JDK 11 and compiling it with Maven. However, Maven throws a wobbly over a single method reference (it doesn't have issues elsewhere). The method in question looks like this:
public class MyThing {

    boolean something = true;

    // ...

    public boolean isSomething() {
        return something;
    }

    // ...
}

And the call to the above method looks more or less like this:
return methodThatGetsOptionalDefinition(aString)                 // Optional<Definition>
        .map(definition -> defenition.getMyThing(anotherString)) // Optional<MyThing>
        .map(MyThing::isSomething)                               // Optional<Boolean>
        .orElse(true);

Compiling this, Maven throws the following message:
> mvn clean install -Pdist-snapshot -DskipTests
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project XXXXX: Compilation failure
[ERROR] /D:/XXXXX.java:[63,38] incompatible types: invalid method reference
[ERROR]     method isSomething in class XXXXX.MyThing cannot be applied to given types
[ERROR]       required: no arguments
[ERROR]       found: java.lang.Object
[ERROR]       reason: actual and formal argument lists differ in length
[ERROR]
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.

If I expand the method reference like so, it compiles without a problem:
return methodThatGetsOptionalDefinition(aString)
        .map(definition -> defenition.getMyThing(anotherString))
        .map(myThing -> myThing.isSomething())
        .orElse(true);

Typing the Optional also works:
return methodThatGetsOptionalDefinition(aString)
        .<MyThing>map(definition -> defenition.getMyThing(anotherString))
        .map(myThing -> myThing.isSomething())
        .orElse(true);

The same error occurs when compiling the project using IntelliJ with both Open JDK versions 11.0.1 and 11.0.2. Ironically, IntelliJ complains that the "Lambda can be replaced with method reference". The problem also occurs when using a different "language mode".
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>11</source>
        <target>11</target>
    </configuration>
</plugin>

Does anyone have any idea why this might be happening?
Some of the specific implementation details have been obfuscated.

A: It has to do with the Type definition of the map method.
In order to provide a method reference, the method must have a matching Type definition. Stream map has a function method, but yours is a producer function.
Function = (T) -> R
Producer = () -> R

So, Method::isSomething() is not compatible with Stream.map, but your inline closure myThing -> myThing.isSomething() is..


text:
Q: python postdata list only gives last value of multiplecheckbox I made a form that has multiple checkboxes (grouped), when this data is posted it looks something like:
<QueryDict: {u'action': [u'delete'], u'mails': [u'1', u'2']}>

but now when i try to acces the data in "mails" i only get the last result:
(where postdata is my Querydict)
def mail_action(postdata, character):
    if postdata['action'] == "delete":
        for mail in postdata['mails']:
            print mail

wo with this it only prints "2"
what do i need to do to get the whole list of "mails" ?

A: According to the documentation for Django's QueryDict.__getitem__(key), it says that "If the key has more than one value, __getitem__() returns the last value." So the behaviour you are seeing is intended.
To get all the values, try using QueryDict.getlist(key, default) which "Returns the data with the requested key, as a Python list. Returns an empty list if the key doesn't exist and no default value was provided. It's guaranteed to return a list of some sort unless the default value was no list."
So, your code can be:
def mail_action(postdata, character):
    if postdata['action'] == "delete":
        for mail in postdata.getlist('mails'):
            print mail


text:
Q: Solr - Passing custom parameter for fetch query in Data Import I have configured Solr to import data from MySql database. I need to pass a parameter ( say user_id ) and what I need to gain out of this is to import only the record that matches the passed user id.
http://googlieye:8983/solr/db/dataimport?command=full-import&
entity=user_data_import&user_id=431269
Is it possible to get this done? I'm still trying to work this out. Any kind of suggestion or idea would be helpful.

A: You can pass the query params and then read them in data-config.xml like this:
select * from users where user_id=${dataimporter.request.entity}


text:
Q: JavaFX deselect text upon opening new TextInputDialog I thought I found the answer with deselect() but strangely it doesn't do anything, the text is still all selected on opening.
TextInputDialog textInput = new TextInputDialog("whatever text");
textInput.initOwner(sentence.stage);
Optional<String> result = textInput.showAndWait();
if (result.isPresent()) {
   // process
}
textInput.getEditor().deselect();

A: The Dialog#showAndWait() method does not return until the dialog is closed. That means your call to deselect() is too late. However, simply reordering your code does not appear to solve your problem. This looks like a timing issue; the text is probably selected when the field gains focus so you need to deselect the text after that happens. For example:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextInputDialog;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

  @Override
  public void start(Stage primaryStage) {
    var button = new Button("Show dialog...");
    button.setOnAction(
        ae -> {
          var textInput = new TextInputDialog("Some text");
          textInput.initOwner(primaryStage);
          Platform.runLater(textInput.getEditor()::deselect);
          textInput.showAndWait();
        });

    var root = new StackPane(button);
    primaryStage.setScene(new Scene(root, 500, 300));
    primaryStage.show();
  }
}

The Runnable passed to runLater is executed after the dialog is shown and after the text has been selected.


text:
Q: Routing DHCP through a wireless router I have a SBS 2003 server that is running DNS/AD/DHCP. Address space is 192.168.1.1. We added a new wireless router to the network to replace a old damaged Watchguard Firewall/gateway.
Everything works well except I can not get DHCP to service from the LAN to the Wireless clients. The wireless clients can ping to the server but it's like they are not getting the DHCP server broadcast.
I have move the DHCP to the router for now and it works i.e. The workstation on both the LAN and wireless are getting address but it is causing some issues with SBS.
This wireless router is also currently acting as the gateway and firewall for the network. So the network looks like this:
Internet > Cable Modem > Wireless Router/Gateway/Firewall > Switch > Local Clients icluding SBS
How can I get the DHCP server to broadcast to both the LAN and wireless clients ?

A: By default, these wireless routers are setup to put the wireless devices on a separate address space and do NAT. You need to change that and get the wireless router to be a plain access point, not do DHCP and not do NAT.
The specifics about how to do this depend on the router model, and I almost certainly can't tell you how to do it, but I doubt it is particularly tough once you know what you are looking for.


text:
Q: Jasper Report PDFs Are Not PDF/UA Compliant I want to make PDFs exported by Jasper PDF/UA compliant, but limitations of Jasper are preventing me from doing so. Client is pressuring us to get this done properly.
PDF/UA has a lot of requirements, including but not limited to displaying title and language, embedding fonts, and adding alternate text to images. So far, I have set all the 508 PDF tags, set properties to display title and language, embedded fonts, and added alt text to images all in Jaspersoft Studio. I have also appended the PDF/UA identifier to the output PDF (i.e. after the PDF was generated) via Apache PDFBox. We are using Jaspersoft Studio v6.6.0 coupled with Jasper Reports Library v6.4.0 and Oracle for the DB. From what I've read, Jasper has limited capabilities in this regard due to itext being downgraded back to v2.1.7.js6 because of licensing issues.
<jasperReport xlmns=...>
        ... // other properties
        <property name="net.sf.jasperreports.awt.ignore.missing.font" value="false"/>
        <property name="net.sf.jasperreports.export.xls.detect.cell.type" value="false"/>
        <property name="net.sf.jasperreports.export.xls.sheet.names.all" value="REPORT SHEET NAME"/>
        <property name="net.sjasperreports.default.pdf.font.name" value="Times-Roman"/>
        <property name="net.sf.jasperreports.export.xls.ignore.graphics" value="false"/>
        <property name="net.sf.jasperreports.default.pdf.embedded" value="true"/>
        <property name="net.sf.jasperreports.export.pdf.metadata.title" value="MY REPORT TITLE"/>
        <property name="net.sf.jasperreports.export.pdf.display.metadata.title" value="true"/>
        <property name="net.sf.jasperreports.export.pdf.tagged" value="true"/>
        <property name="net.sf.jasperreports.export.pdf.tag.language" value="EN-US"/>
        ... // parameters, stored proc call, headings, etc.
        <!-- Possible PDF 508 tags to be set on text fields -->
        <property name="net.sf.jasperreports.export.pdf.tag.table" value="start"/>
        <property name="net.sf.jasperreports.export.pdf.tag.th" value="full"/>
        <property name="net.sf.jasperreports.export.pdf.tag.tr" value="start">
        <property name="net.sf.jasperreports.export.pdf.tag.td" value="full">
        <property name="net.sf.jasperreports.export.pdf.tag.tr" value="end">
        <property name="net.sf.jasperreports.export.pdf.tag.table" value="start"/>
        ...
</jasperReport>

... // other imports
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.XMPSchema;
import org.apache.xmpbox.xml.XmpSerializer;
... // more imports

public class ReportResult {
   ... // other methods

    /*
     * @param pdf - The pdf instance created from BAOS
     * @param title - Document
     * @return BAOS containing metadata (UA-identifier, title)
     */
    private ByteArrayOutputStream appendXMPMetaData(PDDocument pdf, String title) throws TransformerException, IOException {
        XMPMetadata xmp = XMPMetadata.createXMPMetadata();
        xmp.createAndAddDublinCoreSchema();
        xmp.getDublinCoreSchema().setTitle(title);
        xmp.getDublinCoreSchema().setDescription(title);
        xmp.createAndAddPDFAExtensionSchemaWithDefaultNS();
        xmp.getPDFExtensionSchema().addNamespace("http://www.aiim.org/pdfa/ns/schema#", "pdfaSchema");
        xmp.getPDFExtensionSchema().addNamespace("http://www.aiim.org/pdfa/ns/property#", "pdfaProperty");
        xmp.getPDFExtensionSchema().addNamespace("http://www.aiim.org/pdfua/ns/id/", "pdfuaid");

        XMPSchema uaSchema = new XMPSchema(XMPMetadata.createXMPMetadata(),
                "pdfaSchema", "pdfaSchema", "pdfaSchema");
        uaSchema.setTextPropertyValue("schema", "PDF/UA Universal Accessibility Schema");
        uaSchema.setTextPropertyValue("namespaceURI", "http://www.aiim.org/pdfua/ns/id/");
        uaSchema.setTextPropertyValue("prefix", "pdfuaid");

        XMPSchema uaProp = new XMPSchema(XMPMetadata.createXMPMetadata(),"pdfaProperty", "pdfaProperty", "pdfaProperty");
        uaProp.setTextPropertyValue("name", "part");
        uaProp.setTextPropertyValue("valueType", "Integer");
        uaProp.setTextPropertyValue("category", "internal");
        uaProp.setTextPropertyValue("description", "Indicates, which part of ISO 14289 standard is followed");
        uaSchema.addUnqualifiedSequenceValue("property", uaProp);

        xmp.getPDFExtensionSchema().addBagValue("schemas", uaSchema);
        xmp.getPDFExtensionSchema().setPrefix("pdfuaid");
        xmp.getPDFExtensionSchema().setTextPropertyValue("part", "1");

        XmpSerializer serializer = new XmpSerializer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        serializer.serialize(xmp, baos, true);

        PDMetadata metadata = new PDMetadata(pdf);
        metadata.importXMPMetadata(baos.toByteArray());
        pdf.getDocumentCatalog().setMetadata(metadata);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        pdf.save(byteArrayOutputStream);
        pdf.close();

        return byteArrayOutputStream;
    }

    protected void getJasperPDFDoc(ReportConfig reportConfig) throws IOException, TransformerException {

        List<ReportParameter> reportParams = reportConfig.getReportParams();

        ... // cookies and printer config

        Map imagesMap = new HashMap();
        request.getSession(true).setAttribute("IMAGES_MAP", imagesMap);

        ByteArrayOutputStream bs = ReportAccess.Instance.getInstance().generateJasperReport(
                getCurrentUserId(), getCurrentUserName(), reportConfig, "PDF",
                 reportParams, getTmpImageUri(),
                 imagesMap, rptTemplateLoc);

        if (bs != null) {
            if (reportConfig.doPrint) {
                response.setContentType("text/html");
            } else {
                log.debug("Got PDF report data");
                String fileName = getReportFileName(reportConfig) + ".pdf";
                response.setContentType("application/pdf");
                String dispositionProperty = "attachment; filename=" + fileName;
                response.setHeader("Content-disposition", dispositionProperty);
            }

            PDDocument pdf = PDDocument.load(new ByteArrayInputStream(bs.toByteArray()));
            ByteArrayOutputStream baosWithMetaData = appendXMPMetaData(pdf, reportConfig.getDisplayName());

            response.setHeader("Content-length", Integer.toString(baosWithMetaData.size()));
            ServletOutputStream os = response.getOutputStream();
            baosWithMetaData.writeTo(os);

            os.flush();
            os.close();
        } else {
            displayError("PDF");
        }
     }

     ... // other methods
}

/* REPORT MANAGER CLASS */
private static void generatePDFDoc(JasperPrint jasperPrint, ByteArrayOutputStream f) {

        try {

            JasperPrint jr = moveTableOfContents(jasperPrint);
            JRPdfExporter exporter  = new JRPdfExporter();
            exporter.setExporterInput(new SimpleExporterInput(jr));
            exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(f));

            //configuration
            SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
            configuration.setCompressed(true);
            configuration.setTagged(true);
            configuration.setTagLanguage("EN-US");

            //set configuration
            exporter.setConfiguration(configuration);

            //export to PDF
            exporter.exportReport();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

I noticed a handful of errors reported by Adobe's Preflight checker as well as our client, listed below:

*

*Non-standard  tag present

*Circular Role Map

*Unknown Anchor cell appended to top-left of every page

*Table is not properly recognized in table-editor view

Images showing my problem(s). Any help in this regard is kindly appreciated.

A: If you want to make things simpler, but different way, PD4ML v4 can be an option. There is a minimalistic sample on the page: https://pd4ml.tech/pdf-ua/
It uses available structure and meta info from input HTML/CSS to produce a valid tagged PDF/UA.
If the goal is to pass PDF/UA file format validation only (e.g. by Adobe's Preflight checker) it is sufficient just to choose Constants.PDFUA as an output format.
pd4ml.writePDF(fos, Constants.PDFUA);

If the goal is to produce Matterhorn Protocol-compliant PDFs (and pass a validation by PAC3 https://www.access-for-all.ch/en/pdf-lab/pdf-accessibility-checker-pac.html), most probably you would also need to align your input HTML: to add TITLE, ALT and LANG attributes, to make sure table structures and heading hierarchy are consistent etc.


text:
Q: FileSaver.js Save as type is incorrect I'm working on a project that uses Electron to wrap a web app to desktop app.
In this project, I use FileSaver.js to export canvas content to png/jpg/pdf.

*

*canvas is turned into base64 image

*base64 image is turned into blob

*blob file is saved using FileSaver.js

Here is how it looks like when Save dialog appears:

This is what it should look like as normal save as (png file):

This matters because if the user forgets to insert .png at the end of file name, the file can not be opened normally.
How can I solve this problem?
Thank you very much.

A: I would suggest using the electron-canvas-to-buffer package  and depending on the users export choice, create two methods and use electron dialog's filter to save accordingly.
For the pdf I used jspdf package. This will save the file as whatever filename you specify. Also I added a snippet to paint the canvas background white to avoid black backgrounds.
Here is a simple example
var canvasBuffer = require('electron-canvas-to-buffer');
var fs = require('fs');
var jsPDF = require('jspdf');

// your canvas drawing
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
// painting the canvas white to prevent black background
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
// drawing
context.fillStyle = 'blue';
context.fillRect(0, 0, 50, 50);
context.fillStyle = 'red';
context.fillRect(50, 10, 30, 20);

// PNG
function savePNG() {
    var buffer = canvasBuffer(canvas, 'image/png');
    dialog.showSaveDialog({
        filters: [{
            name: 'png',
            extensions: ['png']
        }]
    }, function (fileName) {
        if (fileName === undefined) return;
        fs.writeFile(fileName, buffer, function (err) {});
    });
}
// JPG
function saveJPG() {
  var buffer = canvasBuffer(canvas, 'image/jpg');
  dialog.showSaveDialog(
    {
      filters: [
        {
          name: 'jpg',
          extensions: ['jpg'],
        },
      ],
    },
    (fileName) => {
      if (fileName === undefined) return;
      fs.writeFile(fileName, buffer, (err) => {});
    },
  );
}
// PDF
function savePDF() {
  // only jpeg is supported by jsPDF
  let imgData = canvas.toDataURL('image/jpeg', 1.0);
  let pdf = new jsPDF();
  pdf.addImage(imgData, 'JPEG', 0, 0);
  pdf.save('test.pdf');
}


text:
Q: Ошибка сборки проекта - ругается на ненайденные ресурсы     apply plugin: 'com.android.application'

    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.2"
        useLibrary  'org.apache.http.legacy'

        allprojects {
            repositories {
                jcenter()
                maven {
                    url "https://maven.google.com"
                }
            }
        }

        defaultConfig {
            applicationId "redixbit.restaurant"
            minSdkVersion 14
            targetSdkVersion 23
        }

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }
    }

    dependencies {
        compile 'com.android.support:support-v4:25.3.1'
        compile 'com.android.support:appcompat-v7:25.3.1'
        compile files('libs/easyandroidanimationslibrary-v0.5.jar')
        compile 'com.google.android.gms:play-services:11.0.4'

    }

    ----------------
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored" parent="android:TextAppearance.Material.Widget.Button.Borderless.Colored"/>
    <style name="Base.TextAppearance.AppCompat.Widget.Button.Colored" parent="android:TextAppearance.Material.Widget.Button.Colored"/>
    <style name="TextAppearance.AppCompat.Notification.Info.Media"/>
    <style name="TextAppearance.AppCompat.Notification.Media"/>
    <style name="TextAppearance.AppCompat.Notification.Time.Media"/>
    <style name="TextAppearance.AppCompat.Notification.Title.Media"/>
</resources>

-----

A: Ошибка вызвана тем, что у вас версия библиотеки поддержки отличается от compileSdkVersion, buildToolsVersion, targetSdkVersion
Чтобы сборка прошла - замените compileSdkVersion, buildToolsVersion, targetSdkVersion
 на 25 версию


text:
Q: How do I create particles in a mob with an effect? I'm trying to make when I shoot an enemy with a tipped_arrow with the effect Fire Resistance, this active a particle in them.
I make this command that actually work but not how I would like...
/testfor @e[type=Spider] {ActiveEffects:[{Id:12b}]}

and next with a comparator, I use this command for active the particles...
/execute @e[type=Spider] ~ ~ ~  /particle flame ~ ~1 ~ 1.5 1 1.5 0 3 normal @e

The problem is that this active the particle in all spiders and not in the specific spider.

A: The best way to do this would be to use a scoreboard tag. The scoreboard command, like testfor, can search for entities with partial nbt matches, but can also mark them for other commands.
/scoreboard players tag @e[type=spider] add SpiderMark {ActiveEffects:[{Id:12b}]}

If you use this all spider's with fire resistance will receive the "SpiderMark" tag. Then you can add the tag=SpiderMark to the entity selector in the particle command to only play the particle command off spider's with fire resistance.
/execute @e[type=spider,tag=SpiderMark] ~ ~ ~ particle flame ~ ~1 ~ 1.5 1 1.5 0 3 normal @a


text:
Q: C# Setting Entity Framework connectionstring in controller I'm build my webapi project based on this article: A simple POC using ASP.NET Web API, Entity Framework, Autofac, Cross Domain Support
However, I need to pass a connection string to the DbContext because a user that connects to the webapi can select a different database to work with.
Where and what is that best way to implement this? In the controller, having a separate 'service' or a singleton?

A: One way would be to have multiple ConnectionStrings in your web config. You could then select which ConnectionString to use depending on a parameter passed to your webapi:
In your web config:
  <connectionStrings>
<add name="dataBase1" connectionString="/*db info here*/" providerName="System.Data.SqlClient" />

<add name="dataBase2" connectionString="/*db info here*/" providerName="System.Data.SqlClient" />
</connectionStrings>

Then in your code:
public someobject GetData(/*arguments*/, string dbType)
{
    var connectionString = dbType == 'dataBase1'
    ? ConfigurationManager.ConnectionString['dataBase1'].toString()
    : ConfigurationManager.ConnectionString['dataBase2'].toString()

    /*then pass connectionString to dbContext*/
    var dbContext = new DbContext(connectionString);
}

A: I'm currently building a website that requires multiple databases also.  This is the basics (for now).  It may not be the best/efficient way, but it does the job so that I can continue working on the site.
Let's say you have this connection and everything there is correct, except the database name can change.
<add name="MyDbContext" connectionString="Server=SomeConnection;Database=SomeDatabase;"providerName="System.Data.SqlClient" />

You can create a connection string on the fly with this
public MyDbContext CreateDbContext(string databaseName)
{
    SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(System.Configuration.ConfigurationManager.ConnectionStrings["MyDbContext"].ConnectionString);  // Gets the default connection
    sqlBuilder.InitialCatalog = databaseName;  // Update the database name

    return new MyDbContext(sqlBuilder.ToString());
}

Also, unless you want to automatically create a database if it doesn't exist, possibly from incorrect database name, you need to set the initializer.  Simply pass the initializer null to prevent ef from automatically creating one.  I set this in the constructor of MyDbContext
public class MyDbContext : DbContext
{
    /* some other constructors */

    public MyDbContext(string nameOrConnectionString, bool createDb)
        : base(nameOrConnectionString)
    {
        if(!createdDb)
        {
            System.Data.Entity.Database.SetInitializer<MyDbContext>(null);
        }
    }
}


text:
Q: Setup and Deployment does not want to uninstall older version and install new version I have a wpf application written in framework 4. The application is downloaded via a file share and installed on the user pc - an icon will appear on the desktop and the user can click on icon to use the application.
However I used the standard setup and deployment project found in VS 2010 to create an installer program, I have also set the "RemovePreviousVersions = True" on the setup and deployment project properties.
However when I do any change on the application, deploy application and then add NEW deployment files to setup and deployment project, and build the S&D project and run the new setup.exe it DOES pick up that a previous version is installed but does not remove it, just gives me an error that install cannot continue becuase of older version.
WHat could I be doing wrong?
Kind Regards
_geoNeo

A: In case someone else is wondering, the solution is to increase the ProductVersion and answer Yes when prompted about changing the ProductCode.


text:
Q: Does the expression "from off" actually exist? Linkin Park sings "wash the poison from off my skin" in Castle of Glass.
Shawn Mendes sings "ripping all the skin from off my bones" in Mercy.
As far as I can remember these are the only two occasions where I have heard that expression. To me it sounds like it should be "off from" (if at all).
Is this normal, or did the artists just do it to get another syllable for their rhyme?

A: The off in from off seems redundant, but such redundancy has a long history in the language. Here's the state of Massachusetts in 1780 making law about abandoned timber:

[I]f the owner or owners of such logs, masts, spars, or timber shall not appear and take the same from off said land....

And right up to modern times (from a 2000 memoir byHarry Altman):

... would pull the shoes from off their feet and would steal anything else that was accessible.

Off from is much less common, with the off many times part of a preceding phrasal verb, as in laid off, take off, etc.


text:
Q: Mac OS CodeBlocks debugger I just installed CodeBlocks on Mac OS and I ran into a problem when debugging.

ERROR: You need to specify a debugger program in the debuggers's
  settings. (For GCC compilers, it's 'gdb' (without the quotes))

The debug is selected in the CodeBlocks settings.
Debug > Active Debuggers
In Settings > Compiler > Global compiler settings > Toolchain executables
What seems to be wrong?


text:
Q: NOT ABLE TO ACCESS URL https://testdev01.azurewebsites.net I am not able to access "https://testdev01.azurewebsites.net"
Its showing "The service is unavailable"

_errorData: undefined _sourceErrorLevel: undefined baseTypes: ["t","MsPortalFx.Errors.Error"]  code: undefined data: 1 errorLevel: 2
  extension: fx handled: undefined innerErrors: ["message: Failed to
  retrieve the blade definition for 'ActivityLogBlade' from the
  server.\r\nmessage:Manual require of the following modules failed;
  ["_generated/Blades/ActivityLogBlade" : {Error: Couldn't load
  "_generated/Blades/ActivityLogBlade" at
  "https://afd.hosting.portal.azure.net/websites/Content/5.12.34.475/Scripts/_generated/Blades/ActivityLogBlade.js?retryAttempt=1.0371554125639133";
  error code 404, message: Not Found}];\r\nstack:
RPC_Exception ##\nError: Failed to retrieve the blade definition for 'ActivityLogBlade' from the server.\r\nmessage:Manual require of
the following modules failed; ["_generated/Blades/ActivityLogBlade" :
  {Error: Couldn't load "_generated/Blades/ActivityLogBlade" at
  "https://afd.hosting.portal.azure.net/websites/Content/5.12.34.475/Scripts/_generated/Blades/ActivityLogBlade.js?retryAttempt=1.0371554125639133";
  error code 404, message: Not Found}];\n at new r
  (https://portal.azure.com/Content/Dynamic/qLnxN0oZGQC0.js:18:790)\n at
  u (https://portal.azure.com/Content/Dynamic/qLnxN0oZGQC0.js:11:1296)\n
  at Object.tt [as QReject]
  (https://portal.azure.com/Content/Dynamic/qLnxN0oZGQC0.js:11:1405)\n
  at
  https://portal.azure.com/Content/Dynamic/qDdhDKs5uKzm.js:4:5443\r\nFrom
  RPC: fx -> WebsitesExtension
  (MsPortalFx.Internal.Constants.RpcMethods.entryPointGetBladeDefinition)\r\n(Callstack
  capturing is not enabled. Use ?trace=diagnostics to enable it.)\r\n"]
  message: Unable to locate blade 'ActivityLogBlade'. Search
  path:'[0]WebsitesExtension-[1]ActivityLogBlade'.

A: The error (503)- 'The service is unavailable' may be caused by the application level issues, requests taking a long time; application using high memory/CPU or application crashing due to an exception. Firstly, review the application from this front to isolate the problem.
To fetch more details on the error, you could access Kudu console to check the log. You could access http://yourwebappname.scm.azurewebsites.net and review the debug logs.
To access the Application Event Log, use the Diagnose and solve problems blade in the Azure portal.
1.  In the Azure portal, open the app in App Services.
2.  Select Diagnose and solve problems.
Also, to fetch more details on the error, you can always enable logging. Please check out the documentation 'Enable diagnostics logging for web apps in Azure App Service' for a detailed steps on enabling & fetching the logs.
You may also scale-up your App Service Plan and then check to see if that makes any difference.
If feasible, you may restart the WebApp and then check to see if that helps.


text:
Q: How to assert *ast.StructType to specified interface Can I assert a struct represented by *ast.TypeSpec and *ast.StructType to implement a known interface type?
For example
func assertFoo(spec *ast.TypeSpec) bool {
    // spec.Name == "MyStruct"
    st, _ := spec.Type.(*ast.StructType)
    // I want to know whether "MyStruct" implements "FooInterface" or not
    _, ok := st.Interface().(FooInterface)
    return ok
}

but there is no *ast.StructType.Interface() :(

A: The first question would be what are you trying to do?
Compile time check is easy (compiler error if the interface is not implemented):
func assertFoo(t *ast.StructType) {
    var _ FooInterface = t
}

But you don't even need the actual value and can write this as:
func assertFoo() {
    var _ FooInterface = (*ast.StructType)(nil)
}


text:
Q: Hide an element inside a dropdown element of a form I want to hide one of the dropdown options from a form I'm using. I want to keep the element in the form, as the form is doing some calculations based on user inputs and if I take out the option from the form it breaks the calculation, so I'd just like to hide it from users so it's still in the form but not visible to users.
I have inspected the area on the form and this is the code. I want to hide the word Liverpool.
<select class="iphorm-element-select  iphorm_16_25 select2-hidden-accessible" name="iphorm_16_25" id="iphorm_16_25_5e32cecc9b3f6" tabindex="-1" aria-hidden="true">
                                <option value="Liverpool">Liverpool</option>
                                <option value="Shrewsbury">Shrewsbury</option>
                        </select>

A: If you are working in an environment that supports HTML5, you can use the hidden attribute on the option to hide it.
Note that in order for that to work, it can't be the first option (otherwise it will default to that one).
See this working snippet:

<select class="iphorm-element-select  iphorm_16_25 select2-hidden-accessible" name="iphorm_16_25" id="iphorm_16_25_5e32cecc9b3f6" tabindex="-1" aria-hidden="true">
  <option value="-">Choose an option</option>
  <option value="Liverpool" hidden>Liverpool</option>
  <option value="Shrewsbury">Shrewsbury</option>
</select>

Following OP Comment About Editing Existing HTML
OP has stated:

The issue I will probably face is that the html is generated by a
  plugin that creates the form, so I can't add that attribute. I was
  hoping to add a css rule to stop it displaying

Given this circumstance, the CSS property visibility could be used to control whether the option is visible, as per the following snippet:

select > option:nth-of-type(2) {
  visibility: hidden;
}
<select class="iphorm-element-select  iphorm_16_25 select2-hidden-accessible" name="iphorm_16_25" id="iphorm_16_25_5e32cecc9b3f6" tabindex="-1" aria-hidden="true">
  <option value="-">Choose an option</option>
  <option value="Liverpool">Liverpool</option>
  <option value="Shrewsbury">Shrewsbury</option>
</select>

However, this has the unfortunate side-effect of leaving a hole in the select list as opposed to hiding it completely.  It does, however, prevent that option from being displayed or chosen.


text:
Q: Error during loading data frames (xlsx Format) in R Good afternoon,
I'm currently working in R and importing data sets that have .xlsx format.
I use standard function read_excel.
For example:
MCC_1 <- read_excel("MCC_1.xlsx", guess_max = 500000, n_max = 500000)
Most of my files were imported correctly, however suddenly I faced with an error.
It is said: Error: expected ' or "
In a Traceback section I see this:
class = c("rapidxml::parse_error", "C++Error", "error", "condition")
Could you give me any ideas or even solutions of how to overcome it?
Thank you in advance!

A: Found a solution by myself!
All you have to do is to create a copy of your excel file to a new file. The problem stated appears when R is trying to read .xlsx files that were made automatically - for example during data unloading procedure from specific databases.


text:
Q: SQLite Select Query Multiple Where Clause Values I have a statement like so...
SELECT * FROM FOO_TABLE WHERE ID = 1;
What I want is to be able to supply multiple ID's without having to AND. So for example....
SELECT * FROM FOO_TABLE WHERE ID = 1,2,3,4 or (1,2,3,4).
Something along those lines. Is this possible?

A: From the link:
sqlite
SELECT id, . FROM additionalchunks WHERE id in (? ? ? ? ? .)
works, and works efficiently (with an index) :)


text:
Q: Babel spanish option and fancyvrb incompatibility The following MWE compiles without problems
\documentclass{article}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{fancyvrb}

\begin{document}
\SaveVerb{x>y}|x > y|

\begin{equation*}
\UseVerb{x>y}
\end{equation*}
\end{document}

but if I replace the option english by spanish in babel, I got the following error:
$ pdflatex test.tex
! Missing \endcsname inserted.
<to be read again>
                   \unhbox
l.10 \UseVerb{x>y}

I can fix the issue removing > from the name used in the \SaveVerb macro, that is, \SaveVerb{xy}|x > y|, but I want to know if there is a better solution.

A: The problem is that spanish for babel makes < > active characters; you can use the es-noquoting option:
\usepackage[spanish,es-noquoting]{babel}

as in
\documentclass{article}
\usepackage[spanish,es-noquoting]{babel}
\usepackage{amsmath}
\usepackage{fancyvrb}

\begin{document}
\SaveVerb{x>y}|x > y|

\begin{equation*}
\UseVerb{x>y}
\end{equation*}
\end{document}

but then you loose the automatic quotation features implemented by the module through those characters (though the quotating environment can still be used); another option would be to locally deactivate these features and then restore them:
\documentclass{article}
\usepackage[spanish]{babel}
\usepackage{amsmath}
\usepackage{fancyvrb}

\begin{document}
\deactivatequoting
\SaveVerb{x>y}|x > y|

\begin{equation*}
\UseVerb{x>y}
\end{equation*}
\activatequoting
\end{document}

A: You can redefine the commands to sanitize their argument:
\documentclass{article}
\usepackage[spanish]{babel}
\usepackage{amsmath}
\usepackage{fancyvrb}
\let\xSaveVerb\SaveVerb
\def\SaveVerb#1{\xSaveVerb{\detokenize{#1}}}
\let\xUseVerb\UseVerb
\def\UseVerb#1{\xUseVerb{\detokenize{#1}}}
\begin{document}
\SaveVerb{x>y}|x > y|

\begin{equation*}
\UseVerb{x>y}
\end{equation*}
\end{document}


text:
Q: How to clear left-floated element when it collides with a right-floated element? If there is a better design approach, or easily searchable phrase I can google, feel free to let me know and I'll quickly take this down. Unfortunately, I don't think I am Googling the right terms.
To skip the explanation, there is a link to the fiddle at the bottom.

I have a right column that must always be against the right side, and never pushed down.
I have left-side elements that should be inline until they collide with the right column, then they should clear to the next row.

I assumed this could be done by floating the left-side elements to the left, and my right column floated to the right. I can't clear any single left-side element because each left-side element is of variable width.
HTML

Variable width

Variable height

Left margin must always be against left-side

    This column needs to move to the next

    line since there is no room left.

    Instead, it pushes the right-floated div down

    to make room.

Variable width

100% height

Right margin must always be against right-side

CSS
.left-el {
    background-color: orange;
    float: left;
    margin-right: 10px;
}

#right-col {
    background-color: green;
    float: right;
    height: 100%;
}

Conditions

*

*Right col must always be aligned to the right

*Right col must be variable width

*Left elements must be variable width

*Left elements should never interfere with right col

This is what I've been working with: http://jsfiddle.net/TmSuD/ (markup from above)
Perhaps a table is appropriate here?

A: I believe that if you put the right column above the left columns in html it will do what you want.


text:
Q: At a non-singular point of a locally factorial variety, prime divisors are locally principal. But what about Weil divisors? EDIT: My original question was very badly posed, and has been edited substantially.
Suppose $ D' $ is a prime divisor on $ X $ containing a non-singular point $ x, $ and $ f \in I(D') \subset \mathcal{O}_{X,x}. $ Then $ f = up_{1}\dots p_{k}, $ where $ u $ is a unit in $ \mathcal{O}_{X,x} $ and $ p_{i} $ is an irreducible polynomial for $ i \in \lbrace 1,\dots, k \rbrace. $ After a bit of work, we find that $ I(D') = (p_{i}) $ for some $ i. $
So every prime divisor on $ X $ containing $ x $ is locally principal. Suppose $ \lbrace D'_{i} \rbrace_{i=1} $ is some family of such prime divisors. I would like to infer that any Weil divisor $ D = \sum_{i}^{n} n_{i}D'_{i} $ is also locally principal based of the fact that we know the $ D'_{i}$s are.
ASIDE: I am aware of the following fact about Weil divisors on $ \text{Spec}(\mathcal{O}_{X,x}): $ if $ X $ is a variety, and $ \mathcal{O}_{X,x} $ is a UFD for every nonsingular point $ x \in X, $ then any Weil divisor $ D \ni x $ on $ X $ induces a Weil divisor $ D_{x} $ on $ \text{Spec}(\mathcal{O}_{X,x}), $ and $ D_{x} $ is principal.