text:
Q: What are the simplest examples of nonlinear statistical functionals? I am reading Wasserman's book "All of Statistics" in which he defines a statistical functional as any function $T(F)$ of the cumulative distribution function $F(x)$ that outputs a real number. Then he goes on to define a 'linear statistical functional' as a functional $T$ for which the following condition holds:
$$T(aF+bG) = aT(F) + bT(G)$$
where $F$ and $G$ are CDFs, and $a, b$ are constants. Obviously the functionals like the mean and variance are linear. What are some examples of "nonlinear statistical functionals"?

A: *

*Variances. Per the Wikipedia page on mixture distributions, expectations are linear, but variances are not. (When you think about it, this is kind of obvious, because expectations involve integrating over a function, which is linear, but variances involve integrating over the square of a function, which isn't.)
Specifically, for $n$ mixture components with means $\mu_i$, variances $\sigma_i^2$ and mixture weights $w_i$ summing to one, we have a mixture mean and variance of
$$ \begin{align*}
\mu =& \sum_{i=1}^n w_i\mu_i \\
\sigma^2 =& \sum_{i=1}^n w_i(\sigma_i^2+\mu_i^2-\mu^2).
\end{align*}$$
The expression for $\sigma^2$ is quite different from $\sum w_i\sigma_i^2$ because of the squared means. For instance, consider two normals $N(0,1)$ and $N(1,2)$ with weights $(0.3,0.7)$, then
$$ \begin{align*}
\mu =& w_1\mu_1+w_2\mu_2 = 0.7 \\
\sigma^2 =& w_1(\sigma_1^2+\mu_1^2-\mu^2)+w_2(\sigma_2^2+\mu_2^2-\mu^2) = 1.91
\neq 1.7 = w_1\sigma_1^2+w_2\sigma_2^2.
\end{align*}$$
Here is a quick R simulation for people who (like me) don't trust my math-fu:
weights <- c(0.3,0.7)
means <- c(0,1)
vars <- c(1,2)

index <- 2-(runif(1e7)<weights[1])
sims <- rnorm(length(which_one),mean=means[index],sd=sqrt(vars[index]))

mean(sims)
sum(weights*means)

var(sims)
sum(weights*vars)

*Quantiles. For instance, your CDFs could be normal distributions with different means and variances, so $aF+bG$ would be a Gaussian mixture, and $T$ could extract any quantile. Quantiles of mixtures are not simply the weighted averages of the quantiles of the components. (See here for an argument why the median is not a linear functional for mixtures of normal distributions.)

*The maximum or minimum of distributions with bounded support. If your two CDFs are for a $U[0,1]$ and a $U[0,2]$ distribution and $a,b>0$, then the mixture will have minimum $0$ and maximum $2$, regardless of the specific values of $a$ and $b$. Yes, this is not all that different from quantiles.

*The (-1)-median, which is the functional that minimizes the expected mean absolute percentage error, and is not very well known.


text:
Q: How to check if UIImage has transparency I use this function to detect if UIImage has transparency:
extension UIImage {
  public func isTransparent() -> Bool {
    guard let alpha: CGImageAlphaInfo = self.cgImage?.alphaInfo else { return false }
    return alpha == .first || alpha == .last || alpha == .premultipliedFirst || alpha == .premultipliedLast
  }
}

But it doesn't work. I tried it with a png Image with no transparency but it still return true.
Loop for each pixel is not a good idea because it's too expensive i guess.
Any idea how to check if UIImage has transparency, like this image:
image

A: You asked about Swift. Menaim gave a useful answer, but in Objective-C.
Here is a Swift version:
extension UIImage {
    var hasAlpha: Bool {
        guard let alphaInfo = self.cgImage?.alphaInfo else {return false}
        return alphaInfo != CGImageAlphaInfo.none &&
            alphaInfo != CGImageAlphaInfo.noneSkipFirst &&
            alphaInfo != CGImageAlphaInfo.noneSkipLast
    }
}

I just tested the above on a PNG image with no alpha channel and it worked.
Here is a PNG image with no alpha channel (Assuming SO's site preserves it...)

A: Your solution seems to be good and working without issues but you can check out this one as well:
- (BOOL)hasAlpha : (UIImage*) img
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(img.CGImage);
    return (
            alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast
            );

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: MS SQL Store Procedure Optimizing I have attached my query result. How can I optimize this sp? Also do I need to optimize? I can get the result in 0.2 or in some case more.
Client Execution Time   18:18:18        18:18:08        18:17:49        18:17:24        18:13:18
Query Profile Statistics
  Number of INSERT, DELETE and UPDATE statements    281     281     281     50      0       178.6000
  Rows affected by INSERT, DELETE, or UPDATE statements 235     235     235     44      0       149.8000
  Number of SELECT statements   4870        4870        4870        741     13      3072.8000
  Rows returned by SELECT statements    3653        3653        3653        598     37      2318.8000
  Number of transactions    281     281     281     50      0       178.6000
Network Statistics
  Number of server roundtrips   1       1       1       3       3       1.8000
  TDS packets sent from client  1       1       1       3       3       1.8000
  TDS packets received from server  119     110     90      898     78      259.0000
  Bytes sent from client    138     138     138     284     288     197.2000
  Bytes received from server    327491      327491      327491      2861601     197860      808386.8000
Time Statistics
  Client processing time    2755        3793        2364        908     332     2030.4000
  Total execution time  3225        4294        2825        2095        1375        2762.8000
  Wait time on server replies   470     501     461     1187        1043        732.4000

A: There's a number of options you can look at:
1.SQL Merge
SQL Merge can be used to perform Inserts, Updates and Deletes in a single statement.
http://technet.microsoft.com/en-us/library/bb510625.aspx
http://blog.sqlauthority.com/2008/08/28/sql-server-2008-introduction-to-merge-statement-one-statement-for-insert-update-delete/
2.Output Clause
The SQL output clause can be used to return any value from 'inserted' and 'deleted' (New value and Old value) tables when doing an insert or update.
http://msdn.microsoft.com/en-us/library/ms177564(v=sql.90).aspx


text:
Q: Where is Tkinter module containing functions? Where is the Tkinter module (in python 2.7) containing all the functions such as Tk(), tk.Entry(), tk.Button(), etc? I want to make a list of all the functions in a cheatsheet for quick reference and a sense of overview/control that is not gained by the impenetrable jargon-filled descriptions. There appears to be no file in the source files of python27 that gives this, there is a suggestion online that it is a binary file and therefore not accessible. Is this so? Is there not a file containing the functions within the python27 source?
Anyway any idea of where the functions in Tkinter are listed so I can make my own quick reference cheatsheet?

A: Read the official python documentation
Start by reading python's official tkinter documentation at the following address:

*

*https://docs.python.org/3/library/tk.html.

From there you will learn that tkinter doesn't implement any of the widgets itself. Rather, it is just a thin object-oriented wrapper around an embedded tcl interpreter. For better or worse, it expects you to get some of the details of the widgets by learning about tcl/tk.
What does "thin object oriented wrapper" mean?
The underlying tcl/tk interpreter is not object-oriented (ie: not based on classes and instances). Python, however, is highly class-oriented. To make tkinter more pythonic, the developers decided to make the interface to tcl/tk based on classes.
Without this interface, to create a frame might look like this:
tk = _tkinter.create(screenName=None, baseName=None, className='Tk',
                     interactive=True, wantobjects=1, useTk=True,
                     sync=0, use=None)
frame = tk.call("frame", ".myframe", "-background", "red")

With the wrapper this becomes:
root = tkinter.Tk()
frame = tk.Frame(root, background="red")

Read the offical tcl/tk documentation
The canonical documentation for the tk library that's part of tcl can be found at the following link:

*

*http://tcl.tk/man/tcl8.5/TkCmd/contents.htm
Find the package location on your disk
To see the things that are unique to tkinter such as the classes that wrap the underlying tk widgets, you can look through the files in the tkinter module. The easy way to find them is to import the module and then examine the __file__ attribute to see where it's stored on your disk.
If you're on python3 the above will probably show a link to the __init__.py file, and on python2 it will probably show a link to Tkinter.pyc. In both cases you can see the containing folder, where you can look around and examine everything that makes up the package on your system.
bash-3.2$ python3
Python 3.7.2 (default, Jan 13 2019, 12:50:01)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
>>> print(tkinter.__file__)
/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py

(Of course, the actual file and location depends on your version and your OS)
See the official source files on github
The files are available through github at the following link. The bulk of the definition of tkinter is in the file __init__.py.

*

*https://github.com/python/cpython/blob/3.7/Lib/tkinter


text:
Q: Bluetooth disappears after lastest update After applying the latest 18.04 update to my Dell Precision 5520, bluetooth has completely disappeared.
Bluetooth settings screen
This happened once before and rectified itself after the next update. I've tried rebooting hoping it was transient but no luck.
This is the full dmesg log from the last boot. There are errors related to USB but I don't know how that relates.
dmesg log: https://pastebin.com/HC6sBa72
These are the updates that were applied this morning. There is nothing that appears directly related to bluetooth or wireless in there.
Start-Date: 2018-10-28  09:36:52
Commandline: aptdaemon role='role-commit-packages' sender=':1.365'
Install: linux-headers-4.15.0-38-generic:amd64 (4.15.0-38.41, automatic), linux-modules-extra-4.15.0-38-generic:amd64 (4.15.0-38.41, automatic), linux-modules-4.15.0-38-generic:amd64 (4.15.0-38.41, automatic), linux-headers-4.15.0-38:amd64 (4.15.0-38.41, automatic), linux-image-4.15.0-38-generic:amd64 (4.15.0-38.41, automatic)
Upgrade: libpackagekit-glib2-18:amd64 (1.1.9-1ubuntu2.18.04.1, 1.1.9-1ubuntu2.18.04.3), update-manager-core:amd64 (1:18.04.11.5, 1:18.04.11.6), linux-headers-generic:amd64 (4.15.0.36.38, 4.15.0.38.40), friendly-recovery:amd64 (0.2.38, 0.2.38ubuntu1), linux-libc-dev:amd64 (4.15.0-36.39, 4.15.0-38.41), libapt-inst2.0:amd64 (1.6.3ubuntu0.1, 1.6.6), grub-common:amd64 (2.02-2ubuntu8.6, 2.02-2ubuntu8.7), linux-image-generic:amd64 (4.15.0.36.38, 4.15.0.38.40), apt:amd64 (1.6.3ubuntu0.1, 1.6.6), update-manager:amd64 (1:18.04.11.5, 1:18.04.11.6), google-chrome-stable:amd64 (70.0.3538.67-1, 70.0.3538.77-1), grub2-common:amd64 (2.02-2ubuntu8.6, 2.02-2ubuntu8.7), gdm3:amd64 (3.28.3-0ubuntu18.04.1, 3.28.3-0ubuntu18.04.3), libapt-pkg5.0:amd64 (1.6.3ubuntu0.1, 1.6.6), packagekit-tools:amd64 (1.1.9-1ubuntu2.18.04.1, 1.1.9-1ubuntu2.18.04.3), grub-pc:amd64 (2.02-2ubuntu8.6, 2.02-2ubuntu8.7), linux-signed-generic:amd64 (4.15.0.36.38, 4.15.0.38.40), gir1.2-gdm-1.0:amd64 (3.28.3-0ubuntu18.04.1, 3.28.3-0ubuntu18.04.3), grub-pc-bin:amd64 (2.02-2ubuntu8.6, 2.02-2ubuntu8.7), libxnvctrl0:amd64 (410.66-0ubuntu0~gpu18.04.1, 410.73-0ubuntu0~gpu18.04.1), libgdm1:amd64 (3.28.3-0ubuntu18.04.1, 3.28.3-0ubuntu18.04.3), grub-efi-amd64-bin:amd64 (2.02-2ubuntu8.6, 2.02-2ubuntu8.7), man-db:amd64 (2.8.3-2, 2.8.3-2ubuntu0.1), python3-update-manager:amd64 (1:18.04.11.5, 1:18.04.11.6), packagekit:amd64 (1.1.9-1ubuntu2.18.04.1, 1.1.9-1ubuntu2.18.04.3), apt-utils:amd64 (1.6.3ubuntu0.1, 1.6.6), light-themes:amd64 (16.10+18.04.20180421.1-0ubuntu1, 16.10+18.04.20181005-0ubuntu1), ubuntu-artwork:amd64 (1:16.10+18.04.20180421.1-0ubuntu1, 1:16.10+18.04.20181005-0ubuntu1), grub-efi-amd64-signed:amd64 (1.93.7+2.02-2ubuntu8.6, 1.93.8+2.02-2ubuntu8.7), gir1.2-packagekitglib-1.0:amd64 (1.1.9-1ubuntu2.18.04.1, 1.1.9-1ubuntu2.18.04.3), apt-transport-https:amd64 (1.6.3ubuntu0.1, 1.6.6), gstreamer1.0-packagekit:amd64 (1.1.9-1ubuntu2.18.04.1, 1.1.9-1ubuntu2.18.04.3), linux-generic:amd64 (4.15.0.36.38, 4.15.0.38.40), ubuntu-mono:amd64 (16.10+18.04.20180421.1-0ubuntu1, 16.10+18.04.20181005-0ubuntu1), nvidia-settings:amd64 (410.66-0ubuntu0~gpu18.04.1, 410.73-0ubuntu0~gpu18.04.1)
End-Date: 2018-10-28  09:38:34

I'd love to be able to diagnose this myself but don't have the depth of skills yet to know what to do or where to look. Any idea's or direction would be much appreciated


text:
Q: Apple Watch and iPhone app requirements for submitting to App Store? I have created a simple Apple Watch app that displays a list of emoticons in a list and displays a bigger version when clicked. Nothing earth-shattering, but just an exercise.
Now I'm ready to submit it to the App Store, but what are the requirements in regards to the iPhone portion? Currently, when clicking on the app in the iPhone emulator, it brings up a blank screen. Am I supposed to put just some dummy image there so it's not a blank white screen? I've heard it will get rejected if it's just blank on the iPhone, but my watch app needs no interaction with the iPhone. Any help, suggestions, or experience is greatly appreciated.

A: Your Watch app can only currently be submitted as an extension of an iPhone app. If your iPhone app is blank, non functional, or doesn't have a purpose outside of the watch extension, it will likely be rejected: https://developer.apple.com/app-store/watch/


text:
Q: Can't remove controller name MVC4 I'm worknig in MVC4 where i need to redirect a user under a certain scenario to LogOut. I'm using the redirect in the .js file. But when i try to redirect the routing is not proper. It adds to the existing controller and throw me error.
//Code
// .cshtml:
<script type="text/javascript">
    var logoutUrl = '@Url.Action("LogOut", "Account")';
</script>

//Controller:
 [AllowAnonymous]
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Account", null);
        }

//.JS:
  window.location.href = logoutUrl;

When i try to redirect the user will be in page
/Home/Index

But, after redirecting it goes to
/Home/Account/LogOut

instead of /Account/LogOut
My routeConfig,
 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
            );

        }

this throws me the error. But i need to remove the Home from the url and redirect to Account/LogOut.
How can i achieve this?

A: Please make sure you are getting the correct url or for testing purpose just use hard-coded url
and try once
var logoutUrl = '/Account/LogOut';
PS: i would have commented if i could but less reputation


text:
Q: Azure devops pipeline terraform error - 403 when attempting role assignment I'm attempting to deploy an aks cluster and role assignment for the system assigned managed identity that is created via terraform but I'm getting a 403 response
azurerm_role_assignment.acrpull_role: Creating...
╷
│ Error: authorization.RoleAssignmentsClient#Create: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailed" Message="The client '626eac40-c9dd-44cc-a528-3c3d3e069e85' with object id '626eac40-c9dd-44cc-a528-3c3d3e069e85' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write' over scope '/subscriptions/7b73e02c-dbff-4eb7-9d73-e73a2a17e818/resourceGroups/myaks-rg/providers/Microsoft.ContainerRegistry/registries/aksmattcloudgurutest/providers/Microsoft.Authorization/roleAssignments/c144ad6d-946f-1898-635e-0d0d27ca2f1c' or the scope is invalid. If access was recently granted, please refresh your credentials."
│
│   with azurerm_role_assignment.acrpull_role,
│   on main.tf line 53, in resource "azurerm_role_assignment" "acrpull_role":
│   53: resource "azurerm_role_assignment" "acrpull_role" {
│
╵

This is only occurring in an Azure Devops Pipeline. My pipeline looks like the following...
trigger:
- main

pool:
  vmImage: ubuntu-latest

steps:

- task: TerraformInstaller@0
  inputs:
    terraformVersion: '1.0.7'

- task: TerraformCLI@0
  inputs:
    command: 'init'
    workingDirectory: '$(System.DefaultWorkingDirectory)/Shared/Pipeline/Cluster'
    backendType: 'azurerm'
    backendServiceArm: 'Matt Local Service Connection'
    ensureBackend: true
    backendAzureRmResourceGroupName: 'tfstate'
    backendAzureRmResourceGroupLocation: 'UK South'
    backendAzureRmStorageAccountName: 'tfstateq7nqv'
    backendAzureRmContainerName: 'tfstate'
    backendAzureRmKey: 'terraform.tfstate'
    allowTelemetryCollection: true

- task: TerraformCLI@0
  inputs:
    command: 'plan'
    workingDirectory: '$(System.DefaultWorkingDirectory)/Shared/Pipeline/Cluster'
    environmentServiceName: 'Matt Local Service Connection'
    allowTelemetryCollection: true

- task: TerraformCLI@0
  inputs:
    command: 'validate'
    workingDirectory: '$(System.DefaultWorkingDirectory)/Shared/Pipeline/Cluster'
    allowTelemetryCollection: true

- task: TerraformCLI@0
  inputs:
    command: 'apply'
    workingDirectory: '$(System.DefaultWorkingDirectory)/Shared/Pipeline/Cluster'
    environmentServiceName: 'Matt Local Service Connection'
    allowTelemetryCollection: false

I'm using the terraform tasks from here - https://marketplace.visualstudio.com/items?itemName=charleszipp.azure-pipelines-tasks-terraform
This is my terraform file
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=2.46.0"
    }
  }
}

provider "azurerm" {
   features {}
}

resource "azurerm_resource_group" "TerraformCluster" {
  name     = "terraform-cluster"
  location = "UK South"
}

resource "azurerm_kubernetes_cluster" "TerraformClusterAKS" {
  name                = "terraform-cluster-aks1"
  location            = azurerm_resource_group.TerraformCluster.location
  resource_group_name = azurerm_resource_group.TerraformCluster.name
  dns_prefix          = "terraform-cluster-aks1"

  network_profile {
    network_plugin = "azure"
  }

  default_node_pool {
    name       = "default"
    node_count = 1
    vm_size    = "Standard_D2_v2"
  }

  identity {
    type = "SystemAssigned"
  }

  tags = {
    Environment = "Production"
  }
}

data "azurerm_container_registry" "this" {
  depends_on = [
    azurerm_kubernetes_cluster.TerraformClusterAKS
  ]
  provider            = azurerm
  name                = "aksmattcloudgurutest"
  resource_group_name = "myaks-rg"
}

resource "azurerm_role_assignment" "acrpull_role" {
  scope                = data.azurerm_container_registry.this.id
  role_definition_name = "AcrPull"
  principal_id         = azurerm_kubernetes_cluster.TerraformClusterAKS.identity[0].principal_id
}

Where am I going wrong here?

A: The Service Principal in AAD associated with the your ADO Service Connection ('Matt Local Service Connection') will need to be assigned the Owner role at the scope of the resource, or above (depending on where else you will be assigning permissions). You can read details about the various roles here the two most commonly used roles are Owner and Contributor, the key difference being that Owner allows for managing role assignments.
As part of this piece of work, you should also familiarize yourself with the principle of least privilege (if you do not already know about it). How it would apply in this case would be; if the Service Principal only needs Owner at the Resource level, then don't assign it Owner at the Resource Group or Subscription Level just because that is more convenient, you can always update the scope later on but it is much harder to undo any damage (assuming a malicious or inexperienced actor) on overly permissive role assignment after it has been exploited.

A: I tried everything to get this existing storage service to re-connect to the Azure Devops Pipeline to enable Terraform deployments.
Attempted and did not work: Break lease on tf state, remove tf state, update lease on tfstate, inline commands in ADO via powershell and bash to Purge terraform, re-install the Terraform plugin etc. etc. etc.)
What worked:
What ended up working is to create a new storage account with a new storage container and new SAS token.
This worked to overcome the 403 forbidden error on the access of the Blob containing the TFState in ADLS from Azure Devops for Terraform deployments. This does not explain the how or the why, access controls / iam / access policies did not change. A tear down and recreate of the storage containing the TFState with the exact same settings under a difference storage account name worked.


text:
Q: Why is IntelliJ auto-complete so bad? Coming from a Netbeans scene, currently I'm trying to change my current work IDE to IntelliJ-idea, and the change so far has been pretty good but there is an absolutely important factor that still hasn't convinced me about IntelliJ, the auto-complete & intellisense.
Assume that I'm trying to create a new instance of a Scanner object, if I type new Scanner on Netbeans pressing CTRL + SPACE it pops up the following dialog with all the constructor parameteres it can receive:
Arguments in Netbeans
But, on other hand in Intellij, not only I need to add two parentheses in object declaration, when I press CTRL + SPACE it doesn't pop me the constructor arguments
Arguments in Intellij.
Click on images to see both Netbeans and Intellij results since I can't incorporate images due to being a new user.
EDIT!!!!!!!
See this answer for a possible solution for my problem

A: IntelliJ tries to find members that matches what you already typed fuzzily, so yeah, it does mean that you have to type more to get the correct completions. On the other hand, it gives you classes that you have not even imported yet, and imports it automatically for you if you select it.
About the constructor, it does show you all the overloads if you press (:

Alternatively, you can use this menu item (or its corresponding shortcut):

Don't forget that you can configure code completion in lots of ways in the settings:

Note the "Parameter Info" section. Make sure you have set the "Autopopup in:" setting properly.


text:
Q: How to set choices in dynamic with Django choicefield? I want to set choices in dynamic.
I used __set_choices method but, when request method is POST,
is_valid method always return False.
if request.method=='POST':
    _form = MyForm(request.POST)
    if _form.is_valid():
        #something to do

A: The key is to realise that choices can be any iterable:
import uuid
from itertools import count
class MyForm(BaseForm):

    counter = count(1)

    @staticmethod
    def my_choices():
        yield (uuid.uuid1, next(counter))

    afield = forms.ChoiceField(choices=my_choices)

Or whatever logic you like inside my_choices.

A: I often set the choices dynamicly in the constructor:
class MyForm(BaseForm):
    afield = forms.ChoiceField(choices=INITIAL_CHOICES)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['afield'].choices = my_computed_choices

A: In a view you could do the following
--views.py
lstChoices = _getMyChoices()

form.fields['myChoiceField'].choices = lstChoices

where lstChoices is list of dynamically generated tuples for your choices.

A: Use the constructor to set dynamic choices as shown below:
class DateForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Write the code here to set dynamic choices

        self.fields['month'].choices = dynamic_choices

In addition, I recommend to add the empty label '("", "---------")' to dynamic choices so that the dynamic choices works properly as the default behavior of the select box in Django.

A: Similar to maersu's solution, but if you have a ModelForm with a model that has a ForeignKey to another model, you may want to assign to the field's queryset instead of choices.


text:
Q: Print a UIImageView with AirPrint I have a UIImageView that contains a photo. I want to print the UIImageView with AirPrint. What should i do? Can I convert the photo into a PDF and after print the PDF? How can I try AirPrint with the iPhone Simulator?
Thanks

A: You can go to the iOS simulator and go to the file settings. Then you can press "Open printer simulator."


text:
Q: Getting hibernate session on a shared entity manager proxy gives back the same proxy In our Spring Boot 1.5 project, we were using Spring ORM 5.3.3, Hibernate 5.0.12
To get the session, we had this utility class that uses entity manager to get the current session
The entity manager that gets injected here is Shared Entity Manager Proxy
@Component
public class EntityListenerUtil {

    @PersistenceContext
    private EntityManager entityManager;

    public EntityListenerUtil() {
    }

    public EntityManager getCurrentEntityManager() {
        return this.entityManager;
    }

    public Transaction getCurrentTransaction() {
        Session session = this.getCurrentSession();
        return session.getTransaction();
    }

    public Session getCurrentSession() {
        return getCurrentEntityManager().unwrap(Session.class);
    }
}

When we started using spring boot 2.4.2, it pulled in the same Spring ORM 5.3.3 and Hibernate 5.4.27
The same code when ran now gives back the same shared entity manager proxy bean the entityManager field contains instead of giving the session implementation (SessionImpl for example)
The difference is that hibernate 5.0.12 Session does not extend EntityManager but 5.4.27 Session does.
The use of EntityManager shouldn't alter the behavior of fetching Session with the unwrap method with hibernate version change.
Spring ORM SharedEntityManagerCreator checks if the type we want to unwrap is an instance of the same proxy and if so, it returns back the same proxy. That condition was returning false before as Hibernate 5.0.12 Session didn't extend EntityManager but the new one does.
Any suggestions on how to get around this?


text:
Q: How do you adjust the trace rotation on a Hameg HM 307? I have a [rather old] Hameg HM 307 oscilloscope with the trace rotation slightly off. There is no trace rotation adjuster anywhere on the outside of the device. The user manual mentions that it is possible to adjust the trace rotation but it doesn't say how to do it.
Does anybody know how this is

A: I can't see any means of electrically adjusting the rotation from a brief look through the pdf manual.
However, you might be able to adjust the yoke or even physically rotate the CRT in it's mountings - just watch-out for EHT voltages!!

A: I've got one of those with the same problem. (I used it only yesterday...)
It might be possible to fix it but it won't be an electrical adjustment where you just open the case and turn a potentiometer. It probably involves physically rotating the tube inside the case, or there might be some adjustment magnets around the base of the CRT tube.
I say: Leave it alone. Rejoice in it!


text:
Q: Vertical table with dynamic data Seems to be the same requirement like AngularJS "Vertical" ng-repeat but solution doesn't work for *ngFor
I have this object array that I am trying to bind to an HTML table. Its format is something like below:
[
 {
   "Animal":"Dog",
   "Country":"France",
   "Food":"Tofu",
   "Car":"Nano",
   "Language":"TypeScript"
 }
]

Now this can simply be formatted in the default HTML horizontal table way like this:

    Animal
    Country
    Food
    Car
    Language

    {{data.Animal}}
    {{data.Country}}
    {{data.Food}}
    {{data.Car}}
    {{data.Language}}

This would create table like below(Please ignore the data in the table;its just to  give an idea.):

But how would I create a structure like this with dynamic data(kind of a vertical table):

A: In Component:
this.arrayOfKeys = Object.keys(this.datas[0]);

html:

        {{key}}

            {{data[key]}}

A: Use ng-container if You have data structure similar to groups[].items[].name
So, if You want to add row

    <ng-container *ngFor="let group of groups">

            {{group.name}}

            {{item.name}}

    </ng-container>

Source: https://stackoverflow.com/a/44086855/1840185


text:
Q: Scanning directory and creating thumbnails from already exisiting images What I'm trying to accomplish with this code is, first it scans a directory after images, then it takes one image and create a thumbnail out of it if its bigger than 170x170. The problem I'm having is when I try to load the new file it doesn't work quite as expected.
<?php
foreach (glob('img/*.png') as $f) {
    $list[filemtime($f) . '-' . $f] = $f;
}

$keys = array_keys($list);
sort($keys);

$picOne = $list[array_pop($keys)];
$picTwo = $list[array_pop($keys)];
$picThree = $list[array_pop($keys)];
$picFour = $list[array_pop($keys)];

list($width, $height) = getimagesize($picOne);
if ($width > 170 && $height > 170) {
    $thumb = imagecreatetruecolor(170, 170);
    $source = imagecreatefrompng($picOne);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, 170, 170, $width, $height);
    $path = $picOne."_170x170.png";
    imagepng($thumb, $path);
}

echo '  ';
echo '  ';
echo '  ';
echo '';

?>

This code should make a new file, right?
$path = $picOne."_170x170.png";
imagepng($thumb, $path)

That part works fine sure but $picOne gets _170x170.png added to it and I don't understand why. What I think I've done is just to create a new file with the $picOne name + _170x170.png but instead $picOne gets it as well.
Can anyone help me fix this code or explain what I need to do to get it to work?
Here's what I'm trying to do basically:
1. Scan a directory.
2. Take an image and create a thumbnail from it.
3. Output the thumbnail.

A: The reason you are having issue is that you are not creating new file but overwriting existing file. To create new file every time you try using this loop :
    $path =  $picOne."_170x170.png";

    $x = 0 ;
    while (file_exists($path))
    {
        $path = $picOne ."-" . $x . ."_170x170.png";
        $x++;
    }

This would always give you a new file name all the time and you can put it in a simple function.


text:
Q: How to request data used post method from a simple html page to yii2 applicaion i am building online payment system for my project and i am new to yii2.
I have a simple html with the address http://localhost/ops/onlineStore/home.php with the following simple code
`
<form method="post" action="http://localhost/ops/frontend/web/index.php?r=site/payment">
   <input type="hidden" value="35" name="price">
   <input type="hidden" value="Breathney Spears Audio CD" name="product_name">
   <input type="hidden" value="someSore" name="Store">
   <button type="submit" name="redirect">
Breatheny Spears
Audio CD
35 Afs</button>
</form>

`
now i want to get these posted data from my yii2 app please guide me step by step what to do. Thank you

A: in your SiteController in PaymentAction:
you can simply get the values:
$_POST['price'];
...
or to use yii2 functions:
$post_arr = Yii::$app->request->post();
$price = $post_arr['price'];
...

A: If your form i realetd  to a Yii2 model You can use Yii2 function  load ..
    $model = new MyModel();

    $post = $model->load(Yii::$app->request->post();

then you can refer to each attribute as
    $post->my_attribute;

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
http://www.yiiframework.com/doc-2.0/yii-base-model.html
http://www.yiiframework.com/doc-2.0/guide-structure-controllers.html


text:
Q: Prove that if $f(x)$ is differentiable at $x_0$ and $n \in \mathbb{N}$ then $\lim_{n\to\infty} n[f(x_0+1/n)-f(x_0)]$ I've just started to study differentiation and this problem really haunts me in my sleep, because I feel like I know what the solution is going to look like I am just not able to execute it. I think I should use the definition of derivative than somehow use the Hein definition of limits. But these are just my ideas and I don't know how to use them. Could you please help me by giving me some hints or solutions. Thank you very much.

A: If $f$ is differentiable at $x_0$, then there exists finite the following limit $$\lim_{x \rightarrow x_0} \frac{f(x) - f(x_0)}{x - x_0}$$ hence just substitute $x= x_0 + 1/n$


text:
Q: Using equation numbers as part of examples I want to use equations that I have already numbered as part of an example. i.e. above the example I define an equation for potential energy (3.2), then showing students how to use it in an example I want to write out the equation again and use the same number.
Potential energy is given by
E=mgh (3.2)
Example:
find the potential energy gained of a 30 kg child that climbs 10 m of stairs.
E=mgh (3.2)
Can this be done?


text:
Q: Python Twister Reactor callLater time source? I figured out that when I schedule a function with :
reactor.callLater(delay, function)

If during the delay, the system date is changed, the delay set in reactor.callLater will not be respected.
So, for example, if at 15:00:00 I schedule my function in 30 secondes :
reactor.callLater(30, function)

If during these 30 secondes, the system date is set to 14:00:00, my function will be called at 15:00:30 and not at 14:00:30 (so 1 hour and 30 seconds delay instead of 30 seconds).
So is there a way to tell to reactor to not use the system date but to work like a time.sleep() ?
Thanks for your help.

A: Not quite.  This is a long-standing but yet unimplemented feature request.  See https://twistedmatrix.com/trac/ticket/2424.


text:
Q: Hook for redraw event in Blackberry Is there a way to add a redraw callback to a live screen object, i.e. not via inheritance?

Reasoning:
I want to draw an overlay from an extension for widget sdk (substituting jumpy position:fixed), so the screen is created by the bbwp stub.
I can get it by
Ui.getUiEngine().getActiveScreen()

and draw on it quite nicely, but I need a way to redraw when appropriate.

Note:
I've abandoned the approach to push the overlay as a screen, because i couldn't make it transparent / find a way to pass events through.

A: If you want to push the overlay as a screen, you should be able to make it's background transparent by overriding the paintBackground() method as follows:
// Make background transparent
protected void paintBackground(Graphics graphics) {
    XYRect xy = graphics.getClippingRect();
    graphics.pushContext(xy, 0, 0);
    graphics.setGlobalAlpha(0);
    graphics.setColor(0xffffff);
    graphics.fillRect(xy.x, xy.y, xy.width, xy.height);
    graphics.popContext();
}

Then, to pass touch events through, override the following method and return -1 if you don't want your screen to handle the touch event:
public int getFieldAtLocation(int x, int y) {
    return -1;
}


text:
Q: C++ 2D algorithm code is reading the array wrong Like the title said, my code is reading a 2D array entirely wrong.
    const int WINNING_ROWS[8][3] = { (0, 1, 2),
                                     (3, 4, 5),
                                     (6, 7, 8),
                                     (0, 3, 6),
                                     (1, 4, 7),
                                     (2, 5, 8),
                                     (0, 4, 8),
                                     (2, 4, 6) };

Above is my 2D array of numbers.
My program doesn't seem to be able to read it properly.
For example, if I were to ask for row 2, item 1, I would expect 7, it, however, instead gives me 6.
Here is a list of rows and item requests I have done to try and figure out what has gone wrong here.

*

*row 0, item 0, expected outcome 0, actual outcome 2

*row 3, item 2, expected outcome 6, actual outcome 0

*row 1, item 0, expected outcome 3, actual outcome 6

*row 5, item 1, expected outcome 5, actual outcome 0

*row 8, item 2, expected outcome 6, actual outcome 13629648

*row 7, item 2, expected outcome 6, actual outcome 0

for reference, here is the code I have been using to call the items from the array
cout << WINNING_ROWS[7][2] << endl;

Edit 1: ignore the item in bold, that was a mistake on my part when testing my code.
Edit 2: my question has been answered.

A: const int WINNING_ROWS[8][3] = { (0, 1, 2),
                                     (3, 4, 5),
                                     (6, 7, 8),
                                     (0, 3, 6),
                                     (1, 4, 7),
                                     (2, 5, 8),
                                     (0, 4, 8),
                                     (2, 4, 6) };

That doesn't mean what you think it does.  The (0,1,2) is not a row of three elements, but a single integer computed using the comma operator.  0,1,2 evaluates to 2.
You need to use the proper {...} braces instead of parenthesis, or leave them out completely.

Suggest also you change const to constexpr.

A: WINNING_ROWS[8][2] is out of the array bounds, which means it will cause undefined behavior. If you want to get the last element, you should try cout << WINNING_ROWS[7][2] << endl; since they are 0-indexed.


text:
Q: TypeArgumentException in silverlight lambda expression I've defined the following method
public static Expression<Func<T,dynamic>> CreateExpression(string propName)
{
ParameterExpression param = Expression.Parameter(typeof(T));

MemberExpression aggregator = Expression.PropertyOrField(parameter,propName);

return Expression.Lambda<Func<T,dynamic>>(aggregator,param);
}

The code compiles OK but in the runtime the last line
throws argumentexception stating 'Expression of Type 'System.Int32' cannot be used for return type 'System.Object'
Am i missing something?
Thanks in advance

A: Use Expression.Convert. That will add the boxing conversion you require to turn the Int32 basic type (or any basic type you reference) into an object.


text:
Q: Cycle through jComboBox I have a bunch of jComboBox in a panel.  What is the best way to cycle through the panel and set setSelectedIndex(0) for each of the controls?

A: You can iterate over a tree of Components by checking whether each Component is an instance of Container, and if so iterate over the container's child components and so forth.  You could wrap this functionality in a ComponentIterator, which is initialised with the root Component in the hierarchy.  This would allow you to iterate over a component tree and initialise each JComboBox to a specific value.
However, I would not recommend this "generic" approach as it could have unforeseen results as your code evolves over time.  Instead, it would probably make sense to write a simply factory method that creates and initialises your JComboBox; e.g.
private JComboBox createCombo(Object[] items) {
  JComboBox cb = new JComboBox(items);

  if (items.length > 0) {
    cb.setSelectedIndex(0);
  }

  return cb;
}

Here's the ComponentIterator implementation in case it's of any use:
public class ComponentIterator implements Iterator<Component> {
    private final Stack<Component> components = new Stack<Component>();

    /**
     * Creates a <tt>ComponentIterator</tt> with the specified root {@link java.awt.Component}.
     * Note that unless this component is a {@link java.awt.Container} the iterator will only ever return one value;
     * i.e. because the root component does not contain any child components.
     *
     * @param rootComponent Root component
     */
    public ComponentIterator(Component rootComponent) {
        components.push(rootComponent);
    }

    public boolean hasNext() {
        return !components.isEmpty();
    }

    public Component next() {
        if (components.isEmpty()) {
            throw new NoSuchElementException();
        }

        Component ret = components.pop();

        if (ret instanceof Container) {
            for (Component childComponent : ((Container) ret).getComponents()) {
                components.push(childComponent);
            }
        }

        return ret;
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}

A: Create a list to keep track of all the combo boxes being added to the panel, and then loop over them. For example:
List<JComboBox> list = new ArrayList<JComboBox>();

JComboBox box = new JComboBox();
panel.add(box);
list.add(box); //store reference to the combobox in list

// Later, loop over the list
for(JComboBox b: list){
    b.setSelectedIndex(0);
}


text:
Q: How can I delete all  from wp_posts content table in mysql I have a wordpress site with wp_posts (content) over 1GB data. there are some content with  or only
I want to delete the Total  tag with those styles and classes.
I tried to use
 update wp_posts set post_content=replace(post_content, '<div.*?>','')
but it's not working..


text:
Q: gojs diagram is not shown in IE11 I drew a diagram in gojs, the diagram does not show in IE11, but in other browsers it is displayed as usual. There are also other diagrams in the system, and they are shown.
  The style of the div that wraps the diagram (diagram.div):
   position: absolute;
     width: calc (100% - 0.625rem);
     height: 100%;
     z-index: 1000;
     float: right;
     top: 1.25brake;

In f12 I saw that the canvas has property: "height=1"  compared to other browsers where the canvas has a height of several hundred.
If I change the div's height to px and not in percentage, the diagram is displayed as usual.
the structure of the elements:

    <cabinet-map>

    <canvas width="231" height="1" style="..."></canvas>

    </cabinet-map>
<cabinet-map>
...
</cabinet-map>

the scss:
.cabinets-grid
{
display:table;
border-collapse:collapse;
width: calc(100% - 3.438rem);
height:100%;
margin-left: 3.438;
table-layout:fixed;
}
.cabinet-unit
{
display:table-cell;
position:relative;
}
.cabinetMap {
position:absolute;
width:calc(100% - 0.625rem);
height:calc(100% - 1.5rem);
z-index:1000;
float:right;
top:1.25rem;
}

A: You cannot set height: 100% unless you also set outer elements to have an accommodating height.
Often but not always you simply need to add to your CSS:
html, body {
  height:100%;
}

A: According to Make a DIV fill an entire table cell, and Firefox, IE9+ issue with div height 100% inside a td (working example on Chrome),
The problem is that IE cell in table does not get percentage height (it must get a fixed number), so cabinetMap does not get value.
Because the table is dynamic, I added a snippet of code that sets the height:
const cabinets_grid = this.diagram.div.parentElement.parentElement.parentElement;
const height = cabinets_grid.getBoundingClientRect().height
    if (!height) {
        setTimeout(() => {
            this.calcCabinetHeight(onLoad);
        }, 150);
    }
    else {
        this.diagram.div.style.height = height - 24 + 'px';
        this.zoomToFit();
    }


text:
Q: inheritance class how to use the __new__ function of the bass class in python 3.x? In Python 3.x, inheritance classes use the __new__ function, or its own? In the following code, two __new__ function, how to call them?
class A:
    def __new__(cls):
        print("A",cls)
        return super().__new__(cls)

class B(A):
    def __new__(cls):
        print(cls)
        return super().__new__(cls)

a = A()
print("-----------")
b = B()

output :
A <class '__main__.A'>
-----------
<class '__main__.B'>
A <class '__main__.B'>

A: Your code should be a slight different.
First of all, since A doesn't inheriet from any class, there's no point in writing super().__new__(cls). Super() returns the immidiate parent class. Secondely, the "this" argument in Python is usually called self.
Anyway, are you sure that you meant __new__ and not __init__? See the difference here.
class A:
    def __new__(self):
        print("A",self)
        return super().__new__(self)

class B(A):
    def __new__(self):
        print(self)
        return super().__new__(self)

a = A()
print("-----------")
b = B()

Let's look at the output:
A <class '__main__.A'>
-----------
<class '__main__.B'>
A <class '__main__.B'>

When you create A, you call only A's constructor.
When you create B, you first print class B's flag and then call A's constructor (with the super() function).


text:
Q: Not able to use bulbs to program Titan GraphDB/Rexster I have Titan (with embedded cassandra running on my system).
cd titan-cassandra-0.3.1
bin/titan.sh config/titan-server-rexster.xml config/titan-server-cassandra.properties

I have rexster server running
cd rexster-console-2.3.0
bin/rexster-console.sh

I am able to create a graph from the rexter shell using Gremlin queries.
 g = rexster.getGraph("graph")
 v1 = g.addVertex([name:"s1"])
 v2 = g.addVertex([name:"s2"])
 e1 = g.addEdge(v1, v2, "likes")

I have installed bulbs on my system as follows.
sudo apt-get install python2.7-dev
sudo apt-get install libyaml-dev

sudo pip install  https://github.com/espeed/bulbs/tarball/master

If I try the following from ipython on my machine
In [1]: from bulbs.rexster import Graph

In [2]: g = Graph()

I get the following error.
---------------------------------------------------------------------------
LookupError                               Traceback (most recent call last)
/home/karthik/Projects/ryu_extras/<ipython-input-2-eb1ac0314e67> in <module>()
----> 1 g = Graph()

/usr/local/lib/python2.7/dist-packages/bulbs/rexster/graph.pyc in __init__(self, config)
     54
     55     def __init__(self, config=None):
---> 56         super(Graph, self).__init__(config)
     57
     58         # Rexster supports Gremlin

/usr/local/lib/python2.7/dist-packages/bulbs/base/graph.pyc in __init__(self, config)
     56         self.factory = Factory(self.client)
     57
---> 58         self.vertices = self.build_proxy(Vertex)
     59         self.edges = self.build_proxy(Edge)
     60

/usr/local/lib/python2.7/dist-packages/bulbs/base/graph.pyc in build_proxy(self, element_class, index_class)
    122         if not index_class:
    123             index_class = self.default_index
--> 124         return self.factory.build_element_proxy(element_class, index_class)
    125
    126     def load_graphml(self, uri):

/usr/local/lib/python2.7/dist-packages/bulbs/factory.pyc in build_element_proxy(self, element_class, index_class, index_name)
     17         proxy_class = element_class.get_proxy_class()
     18         element_proxy = proxy_class(element_class, self.client)
---> 19         primary_index = self.get_index(element_class,index_class,index_name)
     20         element_proxy.index = primary_index
     21         return element_proxy

/usr/local/lib/python2.7/dist-packages/bulbs/factory.pyc in get_index(self, element_class, index_class, index_name)
     25             index_name = element_class.get_index_name(self.client.config)
     26         index_proxy = self.build_index_proxy(element_class, index_class)
---> 27         index = index_proxy.get_or_create(index_name)
     28         return index
     29

/usr/local/lib/python2.7/dist-packages/bulbs/rexster/index.pyc in get_or_create(self, index_name, index_params)
     78
     79         """
---> 80         resp = self.client.get_or_create_vertex_index(index_name, index_params)
     81         index = self.index_class(self.client,resp.results)
     82         self.client.registry.add_index(index_name, index)

/usr/local/lib/python2.7/dist-packages/bulbs/rexster/client.pyc in get_or_create_vertex_index(self, index_name, index_params)
    666         script = self.scripts.get('get_or_create_vertex_index')
    667         params = dict(index_name=index_name, index_params=index_params)
--> 668         resp = self.gremlin(script, params)
    669         #assert "MANUAL" in resp.content['results'][0]

    670         result = {'name': index_name, 'type': 'manual', 'class': 'vertex'}

/usr/local/lib/python2.7/dist-packages/bulbs/rexster/client.pyc in gremlin(self, script, params, load)
    354         if self.config.server_scripts is True:
    355             params["load"] = load or [self.scripts.default_namespace]
--> 356         return self.request.post(gremlin_path, params)
    357
    358

/usr/local/lib/python2.7/dist-packages/bulbs/rest.pyc in post(self, path, params)
    129
    130         """
--> 131         return self.request(POST, path, params)
    132
    133     def delete(self, path, params=None):

/usr/local/lib/python2.7/dist-packages/bulbs/rest.pyc in request(self, method, path, params)
    184         http_resp = self.http.request(uri, method, body, headers)
    185
--> 186         return self.response_class(http_resp, self.config)
    187
    188

/usr/local/lib/python2.7/dist-packages/bulbs/rexster/client.pyc in __init__(self, response, config)
    196     def __init__(self, response, config):
    197         self.config = config
--> 198         self.handle_response(response)
    199         self.headers = self.get_headers(response)
    200         self.content = self.get_content(response)

/usr/local/lib/python2.7/dist-packages/bulbs/rexster/client.pyc in handle_response(self, http_resp)
    220         headers, content = http_resp
    221         response_handler = RESPONSE_HANDLERS.get(headers.status)
--> 222         response_handler(http_resp)
    223
    224     def get_headers(self,response):

/usr/local/lib/python2.7/dist-packages/bulbs/rest.pyc in not_found(http_resp)
     37
     38 def not_found(http_resp):
---> 39     raise LookupError(http_resp)
     40     #return None

     41

LookupError: ({'status': '404', 'transfer-encoding': 'chunked', 'server': 'grizzly/2.2.16', 'date': 'Sat, 10 May 2014 06:22:49 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'}, '{"message":"Graph [emptygraph] could not be found"}')

What does these mean?

A: Titan has its own module...
>>> from bulbs.titan import Graph
>>> g = Graph()


text:
Q: Converting an Unconventional Riemann Sum to an Indefinite Integral I am trying to convert the following Riemann Sum into an indefinite integral:
$$\lim_{n \to \infty} \Bigl(nx_{n+1}^m +\sum_{k=1}^n -x_k^m \Bigr)$$
where $m$ is an arbitrary constant. I am wondering if this sum could be converted to an integral in the first place, given that pesky $nx_{n+1}^m$ term before the summation.
I have tried to look at other Riemann Sum-Integral conversions - trapezoidal approximation, center of mass integrals - but none of them seem to help in converting this particular limit. If anyone  could help me out here, it would be much appreciated. Thanks!


text:
Q: What is a recursive function in PHP?
Possible Duplicate:
What is a RECURSIVE Function in PHP?

What is a recursive function in PHP? And are there any good tutorials or examples of a PHP recursive function?

A: Recursive functions in php are no different than in other languages.  It's simply a function that calls itself.  There's no real need to show examples of recursion in php because it's just so simple.  Take a look at the Wikipedia article.  And here's the famous fibonacci numbers example in php.


text:
Q: Linq return string array /// <summary>
/// Returns list of popular searches
/// </summary>
public static string[] getPopularSearches(int SectionID, int MaxToFetch)
{
    using (MainContext db = new MainContext())
    {
        return (from c in db.tblSearches where c.SectionID == SectionID && c.Featured select new[] { c.Term });
    }
}

I looked at other questions but they seem to be slightly different, I get the error:
Cannot implicitly convert type 'System.Linq.IQueryable<string[]>' to 'string[]'

I know this is probably simple, could someone point out what's wrong here please?

A: You are attempting to return an unmaterialized query. The query is only evaluated when it is enumerated. Luckily for you, the ToArray method take the pain out of enumerating and storing. Simply adding it to the end of your query should fix everything.
return (
    from c in db.tblSearches
    where c.SectionID == SectionID && c.Featured
    select new[] { c.Term }
).ToArray();

EDIT
Looking in more detail, perhaps:
return (
    from c in db.tblSearches
    where c.SectionID == SectionID && c.Featured
    select new[] { c.Term }
).SelectMany(x => x).ToArray();

to flatten the results of your query, or even (less redundantly):
return (
    from c in db.tblSearches
    where c.SectionID == SectionID && c.Featured
    select c.Term
).ToArray();

A: Sure - you're trying to return from a method declared to return a string[], but you're returning a query - which isn't a string in itself. The simplest way of converting a query to an array is to call the ToArray extension method.
However, as you're already selecting a string array for every element in the query, that would actually return string[][]. I suspect you really want to select a single string per query element, and then convert the whole thing into an array, i.e. code like this:
public static string[] GetPopularSearches(int sectionID, int maxToFetch)
{
    using (MainContext db = new MainContext())
    {
        var query = from c in db.tblSearches
                    where c.SectionID == sectionID && c.Featured
                    select c.Term;
        return query.Take(maxToFetch)
                    .ToArray();
    }
}

Note that:

*

*I've renamed the method and parameters to match .NET naming conventions

*I've added a call to Take in order to use the maxToFetch parameter

A: Add .ToArray() at the end of the return statement.


text:
Q: How to prove that the Kronecker delta is the unique isotropic tensor of order 2? Is there a  way to prove that the Kronecker delta $\delta_{ij}$ is indeed the only isotropic second order tensor (i.e. invariant under rotation), i.e. so we can write $T_{ij} = \lambda \delta_{ij}$ for some constant $\lambda$?
By rotational invariance I mean:
$$
T_{ij} = T^\prime_{ij} = R_{ip} R_{jq} T_{pq}\text{,}
$$
where the matrices $R_{ij}$ are orthogonal.
It is very straightforward to show that $\delta_{ij}$ is invariant, but how can I show that it is unique?

A: There is a simpler proof at http://www.damtp.cam.ac.uk/user/reh10/lectures/nst-mmii-chapter3.pdf, pg 61, that proceeds as follows
Starting with an isotrophic 2nd order tensor written in matrix form Tij, its coordinates are rotated 90 deg. around the 3 axis to get T'ij, then by comparing T'ij (which equals Tij as T is isotrophic) and Tij and concluding by inspection that T11 = T22, T13 = T23 = -T13 = 0, T31 = T32 = -T31 = 0, and then rotating the coordinates 90% about the 2 axis to conclude that T11 = T33 and T21 = T32 = 0 and T21 = T23 = 0.
That is, the proof is simplicity itself and is given in detail in the reference.

A: Step 1: Realize $T$ is diagonal. Let
$$R_{kl}=\begin{cases}
 -1 & \text{if }k=l=j\\
 \delta_{kl} & \text{otherwise}\\
\end{cases}$$
therefore $R$ is the reflection w.r.t to the hyperplane perpendicular to the j-th vector in the standard ordered basis.
$$R=R^T\land R^2=I\Rightarrow R^TR=RR^T=I$$
Therefore:
$$T_{ij}=\sum_{p,q}R_{ip}R_{jq}T_{pq}=R_{ii}R_{jj}T_{ij}\\
i\neq j\Rightarrow T_{ij}=-T_{ij}\Rightarrow T_{ij}=0$$

Step 2: Realize $T_{jj} = T_{11}$. Let
$$P_{kl}=\begin{cases}
 \delta_{jl} & \text{if } k=1\\
 \delta_{1l} & \text{if } k=j\\
 \delta_{kl} & \text{otherwise}
\end{cases}$$
therefore $P$ is the permutation matrix that interchanges the 1st and j-th rows on left multiplication.
$$(P^TP)_{kl}=\sum_{m}P^T_{km}P_{ml}=\sum_{m}P_{mk}P_{ml}=\sum_{m\neq1,j}P_{mk}P_{ml}+\sum_{m=1,j}P_{mk}P_{ml}\\
=\sum_{m\neq1,j}\delta_{mk}\delta_{ml}+\delta_{jk}\delta_{jl}+\delta_{1k}\delta_{1l}=\sum_{m}\delta_{mk}\delta_{ml}=\delta_{kl}$$
Therefore:
$$T_{jj}=\sum_{p,q}P_{jp}P_{jq}T_{pq}=\sum_{q}P_{jq}^2T_{qq}=\sum_{q}\delta_{1q}^2T_{qq}=\sum_{q}\delta_{1q}T_{qq}=T_{11}$$


text:
Q: Call to undefined function Intervention\Image\Gd\imagecreatefromjpeg()
Hi all,
The error is displayed when I post a pic.jpeg.
I tried to install php7.0-gd but it didn't install.
What should I need my dockerfile?
can you please look into and help.
root@2213ad6df220:/var/www/html/laravel-app# sudo apt-get install php7.0
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'php7.0-thrift' for regex 'php7.0'
Note, selecting 'php7.0-remctl' for regex 'php7.0'
Note, selecting 'php7.0-common' for regex 'php7.0'
Note, selecting 'php7.0-curl' for regex 'php7.0'
0 upgraded, 0 newly installed, 0 to remove and 16 not upgraded.
root@2213ad6df220:/var/www/html/laravel-app# sudo apt-get install php7.0-gd
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php7.0-gd
E: Couldn't find any package by glob 'php7.0-gd'
E: Couldn't find any package by regex 'php7.0-gd'

FROM php:7.2-fpm
# install composer
RUN cd /usr/bin && curl -s http://getcomposer.org/installer | php && ln -s /usr/bin/composer.phar /usr/bin/composer
RUN apt-get update \
&& apt-get install -y \
git \
zip \
unzip \
vim
RUN apt-get update \
   && apt-get install -y libpq-dev \
   && docker-php-ext-install pdo_mysql pdo_pgsql
RUN apt-get update && \
  apt-get -y install libzip-dev libicu-dev libonig-dev \
  zlib1g-dev \
  libjpeg-dev \
  libpng-dev \
  libfreetype6-dev \
  libjpeg62-turbo-dev && \
  apt-get clean && \
  rm -rf /var/lib/apt/lists/*
RUN docker-php-ext-install bcmath gd
WORKDIR /var/www/html


text:
Q: how can I get the same result of leptonica's pixReduceRankBinary2 and pixCloseBrick on openCV? I am translating a go program that uses leptonica library to a python script that uses openCV, and I cant find a way to translate the following:
img = pixReduceRankBinary2(img, 2, NULL);
img = pixReduceRankBinary2(img, 2, NULL);
img = pixCloseBrick(NULL, img, 2, 3);

is there an implementation of those functions in openCV?

A: Here is one way to do that using Python/OpenCV/Skimage. Simply read the image and ensure it is binary. The use Skimage downscale_local_mean to downsample by 2 using 2x2 neighborhoods producing a factor of two smaller image whose values are the means of the 2x2 neighborhoods. Then threshold again in 25% increments to correspond to leptonica counts for their pixReduceRankBinary2 function.
Input (rice grains):

import cv2
import numpy as np
import skimage.transform

# read image
img = cv2.imread('rice_bw.png')

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold to binary
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]

# decimate by factor of 2 to mean values in 2x2 regions
decimate = skimage.transform.downscale_local_mean(thresh, (2,2))

# set count to 1,2,3 or 4
count=2

# convert count to percent of 255 in increments of 25%
count_thresh = 255 * (25/100) * count

# threshold again
result = cv2.threshold(decimate, count_thresh, 255, cv2.THRESH_BINARY)[1]

# write result to disk
cv2.imwrite("rice_bw_binary_decimate.png", result)

# show result
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result for count=2:


text:
Q: Error: Could not find or load main class C:.java.javafx-sdk-19.0.2.1.lib--add-modules I am new to javafx and when i try run my application in vs code,it produces the following error which is:
PS C:\Users\user\3D Objects\java_projects>  c:; cd 'c:\Users\user\3D Objects\java_projects'; & 'C:\Program Files\Java\jdk-19\bin\java.exe' '@C:\Users\user\AppData\Local\Temp\cp_dpl2unip6fff4m8qjz0emjat8.argfile' 'SudokuApplication'
Error: Could not find or load main class C:.java.javafx-sdk-19.0.2.1.lib
Caused by: java.lang.ClassNotFoundException: C:.java.javafx-sdk-19.0.2.1.lib

I expect solution to my error so that my application can run normally.


text:
Q: access NSDictionary content I have an NSDictionary like
{
        nodeAttributeArray =         (
                        {
                attributeName = ReportDate;
                nodeContent = "08-31-1986";
            },
                        {
                attributeName = ReportType;
                nodeContent = PQ1;
            }
        );
        nodeName = Period;
    },
    {
        nodeAttributeArray =         (
                        {
                attributeName = ReportDate;
                nodeContent = "08-31-1987";
            },
                        {
                attributeName = ReportType;
                nodeContent = PQ2;
            }
        );
        nodeName = Period;
    }

I have shown 2 values here. But there are almost 50 such members inside my dict
How do I access the contents of this inside a for loop ?
I want the value inside "nodeContent"
Thank you.

A: From looking at the data structure, it seems to me that the root structure is a List and not a dictionary as you pose in the question. Is that correct? If that is the case, then an iteration for printing the attribute values to the console would be:
NSArray *array; // this is your list with 50 values or so in it
//... some code to load the data into array
NSDictionary *d;
for (NSDictionary *period in array){
    NSLog(@"%@",[period objectForKey:@"nodeName"]);
    for (NSDictionary *nodeAttributeArray in [period objectForKey:@"nodeAttributeArray"]){
        NSLog(@"\t%@=%@",[nodeAttributeArray objectForKey:@"attributeName"],[nodeAttributeArray objectForKey:@"nodeContent"]);
    }
}


text:
Q: How to add php plugin code in theme I've installed WP-PostRatings plugin
It is to set up but I am trying to add it to the theme. In plugin template there is such code: I have tried to add these code so  <php echo " These code here" ?> but it doesn't show. If I need to insert in comment php. How can I generate code for PHP loop? Not shortcode

But in Admin panel it shows me ratings:

A: If you, for some reason, don't want to use the shortcode ([ratings]), you can always use the_ratings() directly in your template.
Make sure you are within the loop so it'll be able to identify the correct post ID for you.
If you want to use it outside the loop, you can pass your ID manually. The function's signature is
function the_ratings($start_tag = 'div', $custom_id = 0, $display = true) {

so you could call it as
the_ratings("div", 123)

if you wanted to output the ratings for the post with the ID 123.

A: To print a shortcode in your own code you need to use the do_shortcode() function, eg: echo do_shortcode('[ratings id="1" results="true"]');


text:
Q: Setting up a dynamic bucketed constraint in MarkLogic for dates In my database, I have a path range index on <date> that contains xs:dates.
<date>2019-01-01</date>

I'm trying to set up a faceted constraint with the following buckets:
2019 with quarter (2019 Q1 (Jan-Mar), Q2 (April-June) etc)

2018

2017

2016

2015

etc

My issue is, I want to dynamically update the bucket to compute the current year into the quarterly bucket, with the rest of the years following. I have a current bucketed range constraint:
<constraint name="date">
    <range type="xs:date" facet="true">
        <path-index>/data/date</path-index>
        <bucket ge="2019-01-01" lt="2019-03-01" name="q1">2019 Q1</bucket>
        <bucket ge="2019-04-01" lt="2019-06-01" name="q2">2019 Q2</bucket>
        <bucket ge="2019-07-01" lt="2019-09-01" name="q3">2019 Q3</bucket>
        <bucket ge="2019-10-01" lt="2019-12-01" name="q4">2019 Q4</bucket>
        <bucket ge="2018-01-01" lt="2019-01-01" name="2018">2018</bucket>
        <bucket ge="2017-01-01" lt="2018-01-01" name="2017">2017</bucket>
        <bucket ge="2016-01-01" lt="2017-01-01" name="2016">2016</bucket>
        <bucket ge="2015-01-01" lt="2016-01-01" name="2015">2015</bucket>
    </range>
</constraint>

The issue with the above, is that it manually is setting 2019 to be split up into quarters, but when it turns 2020 and years following, how could I get the bucket to automatically update and only split apart the current year into quarters?

A: Would computed buckets address the requirement?  See:
http://docs.marklogic.com/guide/search-dev/search-api#id_22725
and
http://docs.marklogic.com/guide/search-dev/appendixa#id_91755
Hoping that helps,


text:
Q: Client Certificates and FireFox I need some help to understand what is happening with my web application.
I have a simple web app (c# .Net 2.0) that uses a smartcard authentication. In my testing box (win 2k3 32 bits, iis6) everything works fine but in my production box (win2k3 64 bits, iis6) firefox is unable to send the certificate, hosted in the card, to the server (the collection Request.ClientCertificate is empty). If I try to browse the same production site with IE (6, 7 and 8) or Safari it works.
IIS's configuration is the same on both servers: same ssl certificates, same CTL.
I've been read a lot about firefox problems with certificates but none of them matches mine.
If any of you can give a clue of what is happening I will be very thankful.
Glauco.

A: Do you run Firefox on the same machine (and thus the 64/32 bit difference) or both times on the same client computer (I would assume 32bit here), and it does not work for you when the server is different (64bit)?
Does Firefox see the certificate (Preferences -> Advanced -> Encryption -> "View certificates -> My Certificates" and "Security devices")? Enable "Ask every time" for certificate selection and verify that Firefox indeed tries to use the card.
Which card (manufacturer, type) and software (PKCS#11 provider) do you use?

A: Disclaimer: this is only based my own observations.
As of version 22.0, Firefox will not present the client certificate at all if the CN ("common name") field of the server's certificate appears to be a DNS name but does not match the host it is talking to (i.e. the hostname in the URL bar).
If you think this may be your issue, you could test it by either ensuring that the host you request is the one in the CN field of the server cert, or by providing a self-signed cert with a silly value like "Jim Bob" in the CN field.


text:
Q: Get ref to show full, cumulative reference to nested item I'm using enumitem and trying to label items with only their current level, but reference them with their full "absolute" value. Here's a sample document:
\documentclass[letterpaper]{article}
\usepackage{enumitem}
\newlist{parin}{enumerate}{4}
\setlist[parin,1]{label=\arabic*.,ref=\arabic*,leftmargin=*}
\setlist[parin,2]{label=(\alph*),ref=\theenumi\alph*,leftmargin=*}
\setlist[parin,3]{label=(\arabic*),ref=\theenumii\arabic*,leftmargin=*}
\setlist[parin,4]{label=(\roman*),ref=\theenumiii\roman*,leftmargin=*}
\begin{document}
\begin{parin}
\item Foo
\label{foo}
\begin{parin}
\item Bar
\label{bar}
\begin{parin}
\item Baz
\label{baz}
\begin{parin}
\item Label Me
\label{labelme}
\end{parin}
\end{parin}
\end{parin}
\end{parin}
\ref{foo}
\ref{bar}
\ref{baz}
\ref{labelme}
\end{document}

The expected output is for the references to appear as:
1 1a 1a1 1a1i

But instead, they appear as:
1 0a 1 i

Would love some guidance, thanks!

A: Your new list is parin, so the associated counters are parini, parinii, pariniii, and not enumi, enumii, enumiii:
\documentclass[letterpaper]{article}
\usepackage{enumitem}
\newlist{parin}{enumerate}{4}
\setlist[parin,1]{label=\arabic*.,ref=\arabic*,leftmargin=*}
\setlist[parin,2]{label=(\alph*),ref=\theparini\alph*,leftmargin=*}
\setlist[parin,3]{label=(\arabic*),ref=\theparinii\arabic*,leftmargin=*}
\setlist[parin,4]{label=(\roman*),ref=\thepariniii\roman*,leftmargin=*}
\begin{document}
\begin{parin}
\item Foo
\label{foo}
\begin{parin}
\item Bar
\label{bar}
\begin{parin}
\item Baz
\label{baz}
\begin{parin}
\item Label Me
\label{labelme}
\end{parin}
\end{parin}
\end{parin}
\end{parin}
\ref{foo}
\ref{bar}
\ref{baz}
\ref{labelme}
\end{document}


text:
Q: jQuery AJAX response type I'm trying to make a working example of jQuery 1.9.1 AJAX + icanhaz/mustache. This is my template:

and this is my JavaScript:
$(document).ready( function() {
    $("#user-btn").click(function() {
        $.ajax({
            type: "GET",
            url: "../php/client/json.php",
            data: {
                type: "users"
            }
        }).done(function( response ) {
            var element = $('#dialog-message');
            element.html("
");
            element.append(ich.user(response));
            element.append("
");
        });
});

The AJAX response from this address looks something like:
{"users":[{"username":"jd","fullname":"John Doe"},{"username":"jl","fullname":"John Lennon"}]};

With the following code, icanhaz cannot render anything for me. I spent some time with javascript console and found out that the typeof response is string and I expected object. Icanhaz also expects object - that's why it didn't manage to render the correct response.
Am I doing something wrong or am I just a poor newbie who didn't know that jquery.ajax returns string responses always? If so, how should I handle them?

A: Try the option dataType: "json" for $.ajax.

A: Modify the click function:
$("#user-btn").click(function () {
    $.ajax({
        type: "GET",
        url: "../php/client/json.php",
        data: {
            type: "users"
        },
        dataType: 'json',
        success: function (data) {
            // Your code...
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});

A: If you are getting a string returned from your AJAX call, you need to add dataType: "json". This will make jQuery parse the response as JSON, if possible.
$(document).ready( function() {
    $("#user-btn").click(function() {
        $.ajax({
            type: "GET",
            url: "../php/client/json.php",
            data: {
                type: "users"
            },
            dataType: "json"
        }).done(function( response ) {
            ...
        });
});

Are you sure your ich.user method expects an array of users and not just a single user object?


text:
Q: Why functions.firestore get error despite functions.https doesn't? I wnader why await citiesRef.get(); in the exports.createID get error despite the same await citiesRef.get(); in the exports.newID doesn't.
exports.newID = functions.https.onRequest(async (req, res) => {
  let citiesRef = fireStore.collection('system').doc('uid_counter');
  let snapshot = await citiesRef.get();
  let counter = snapshot.get('counter');
  console.log('current counter = ', counter);
  res.status(200).send({ counter: counter});
  snapshot.ref.update({counter: coounter})
//  res.send('aho');
});

exports.createID = functions.firestore.document('users/{userId}').onCreate((snap, context) => {
  // ... Your code here
  const newValue = snap.data();
  let citiesRef = fireStore.collection('system').doc('uid_counter');
  let snapshot = await citiesRef.get();
  let counter = snapshot.get('counter');
  let id = hashids.encode(counter++)
  snap.ref.update({id: id})
  console.log(id)
  counter
});

Any suggestions are welcome! Thank you!

A: You need to add async keyword:
exports.createID = functions.firestore.document('users/{userId}').onCreate(async (snap, context) => {

The await operator is used to wait for a Promise. It can only be used inside an async function.


text:
Q: Positive lookahead doesn't match Arabic text Regex doesn't match Arabic text when using lookahead assertion
I am  trying to split the text:

شكرا لك على المشاركة في هذه الدراسة. هذا الاستبيان يطلب معلومات عن:

stored in
$sentences = "شكرا لك على المشاركة في هذه الدراسة. هذا الاستبيان يطلب معلومات عن:";

with regex:
$pattern = "/(?<=\.)\s+(?=\p{IsArabic}+)/";

in function
preg_split($pattern, $sentences);

The regex doesn't match. It does match if I remove the lookahead assertion.
Why does that happen? What could be a workaround?

A: You may fix it by using the \p{Arabic} Unicode property class (see supported names here) and adding u modifier to the regex. Note that + quantifier after \p{Arabic} is redundant.
Use
$sentences = "شكرا لك على المشاركة في هذه الدراسة. هذا الاستبيان يطلب معلومات عن:";
$pattern = "/(?<=\.)\s+(?=\p{Arabic})/u";
print_r(preg_split($pattern, $sentences));

Result:
Array
(
    [0] => شكرا لك على المشاركة في هذه الدراسة.
    [1] => هذا الاستبيان يطلب معلومات عن:
)


text:
Q: javascript polling at given time interval Following function is being called at every 10 second.
function getData()
    {
        $.ajax({
              url       : "refresh.php",
              type      : "POST",
              data      : {"id" : id},
              success   : function(data) {
                 $(".show").html(data);
              }
          });
    }
        $(document).ready(function(){
      setInterval("getData()",50000);//Polls in every 50 sec
    });

What I want is: when page is loaded, getData() should be called instantly, after that each call should be at given interval i.e. 50second
how to do this?

A: Just add a manual call to getData() in the dom ready handler
function getData() {
    $.ajax({
        url: "refresh.php",
        type: "POST",
        data: {
            "id": id
        },
        success: function (data) {
            $(".show").html(data);
        }
    });
}
$(document).ready(function () {
    setInterval("getData()", 50000); //Polls in every 50 sec
    getData(); //invoke on page load
});

A: Call the function from the ready event.
Also, use the function reference in the setInterval call rather than a string.
$(document).ready(function(){
  setInterval(getData,50000);
  getData();
});


text:
Q: Algebraic expression solving Mr. Jain is 4 times as old as his son. After 10 years he will be twice as old as his son. Find Mr. Jain and his son's present ages.

A: A direct retranscript of the statement is $$j=4s,\\j+10=2(s+10).$$
By substitution,
$$4s+10=2s+20,$$ giving $5$ and $20$ (and later $15$ and $30$).

A: If we set $j$ as the current age of Mr. Jain and $s$ as the current age of his son, we can then write the statements as two linear equations
\begin{align}
j&=4s\\
(j+10)&=2(s+10)
\end{align}
We can then solve this by substituting $j=4s$ into the second equation
\begin{align}
(j+10) &= 2(s+10) \\
(4s+10)&=2(s+10) \\
4s+10&=2s+20 \\
2s&=10\\
s &= 5
\end{align}
We can then say that \begin{align}j&=4s \\
j &= 4\times 5 \\
j &= 20 \end{align}

A: How to model the statements:

Mr. Jain is 4 times as old as his son.

$$
J = 4 S \quad (1)
$$

After 10 years he will be twice as old as his son.

$$
J + 10 = 2 (S + 10) \quad (2)
$$
These are linear equations. One way to solve this system is inserting equation $(1)$ into equation $(2$):
$$
4S  + 10 = 2 (S + 10) \iff \\
2 S = 10 \iff \\
S = 5
$$
which then is used with equation $(1)$ to give
$$
J = 4\cdot 5 = 20
$$


text:
Q: SQLite statement logic I have a statement like so:
transaction.executeSql('SELECT item1, item2 FROM table WHERE ...)

is it possible to do something like the following:

*

*If item1 is not null and item2 is null, only select item1

*If item1 is null and item2 is not null, only select item2

*If item1 and item2 are null, don't select either of them

*If item1 and item2 are not null, select both of them

is there a way to satisfy all four of these conditions in one SELECT statement?  I have been thinking about it, but I feel like I have to do two separate SELECT statements.  I've tried to figure out how to do it with AND and OR but no luck.  This is mostly for personal interest, as I could do it separately, but nevertheless I'd appreciate anyone's help.

A: SELECT queries must return a fixed number of columns, so the only way to do this is to use a single column and to return a varying number of records:
SELECT item1 FROM MyTable WHERE item1 IS NOT NULL AND ...
AND
SELECT item2 FROM MyTable WHERE item2 IS NOT NULL AND ...


text:
Q: NextJs  doesn't rerun scripts When I use the <Link> tag in NextJs to navigate between pages it doesn't rerun my scripts after changing pages. It only runs the scripts after the first page load or when I press reload. When using plain  tags instead, it works fine because the page reloads after each navigation. As far as I can tell this happens because the <Link> tag makes it a Single-Page Application and doesn't refresh the page when navigating between pages.
I would greatly appreciate anyway to have it rerun the scripts when navigating between pages or to have it refresh the page without using just plain  tags and losing the Single-Page Application functionality.
This code doesn't refresh the page
 <Link href="/page1">
   Page 1
 </Link>
 <Link href="/page2">
   Page 2
 </Link>

This code does refresh the page
 Page 1
 Page 2

I load in all my scripts using a scripts component
export default const MyScripts = () => {

    return (


text:
Q: Why uninitialized pointers cause mem access violations close to 0? It is said that often (but not always) when you get an AV in a memory location close to zero (like $89) you have an uninitialized pointer.
But I have seen this also in Delphi books... Hm... or they have been all written by the same author(s)???

Update:
Quote from "C++ builder 6 developers guide" by Bob Swart et all, page 71:

When the memory address ZZZZZZZZZ is close to zero, the cause is often
  an uninitialized pointer that has been accessed.

Why is it so? Why uninitialized pointers contain low numbers?  Why not big numbers like $FFFFFFF or plain random numbers?  Is this urban myth?

A:
Why uninitialized pointers contain low numbers?

They don't. They can contain any value.

Why not big numbers like $FFFFFFF?

They can perfectly well contain values like $FFFFFFF.

or plain random numbers?

Uninitialised variables tend not to be truly random. They typically contain whatever happened to have been written to that memory location the last time it was used. For instance, it is very common for uninitialised local variables to contain the same value every time a function is called because the history of stack usage happens to be repeatable.
It's also worth pointing out that random is an often misused word. People often say random when they actually mean distributed randomly with uniform distribution. I expect that's what you meant when you used the term random.

A: Your statement about AV close to zero is true for dereferencing a null pointer. It is zero or close to zero because you either dereference the null pointer:
int* p{};
const auto v = *p; // <-- AV at memory location = 0

or access an array item:
char* p{};
const auto v = p[100]; // <--AV at memory location = 100

or a struct field:
struct Data
{
  int field1;
  int field2;
};

Data* p{};
const auto v = p->field2; // AV at memory location = 4

A: This is confusing "uninitialized pointers" with null references or null pointers.  Access to an object's fields, or indexes into a pointer, will be represented as an offset with respect to the base pointer.  If that reference is null then the offsets will generally be addresses either near zero (for positive offsets) or addresses near the maximum value of the native pointer size (for negative offsets).
Access violations at addresses with these characteristic small (or large) values are a good clue that you have a null reference or null pointer, specifically, and not simply an uninitialized pointer.  An uninitialized reference can have a null value, but may also have any other value depending on how it is allocated.


text:
Q: JSF InputText issue in DataTable I have problem with InputText. When I try to get the InputText value after clicking the button, the value is null.
When I create the login page, there isn't a problem but using a DataTable does.
package controller;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;

import model.Groups;
import model.Student;
import util.DataHolder;

@ManagedBean(name = "edit", eager = true)
@SessionScoped
@RequestScoped
public class EditController implements Serializable {

private static final long serialVersionUID = 1L;

private List<Student> studentList;
private Groups group;

@PostConstruct
public void init() {
    this.group = DataHolder.getGroup();
}

public List<Student> getStudentList() {
    studentList = group.getStudents();
    return studentList;
}

public void saveGrade(Student student) {
    System.out.println(student.getName() + " " + student.getSurname() + "grade =" + student.getGrade());
}

public Groups getGroup() {
    return group;
}

public void setGroup(Groups group) {
    this.group = group;
}

public void setStudentList(List<Student> studentList) {
    this.studentList = studentList;
}

}

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Edit Page</title>

<link rel="stylesheet"
    href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css"></link>

<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>

<script
    src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></link>

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"></link>

<script>
    $(document).ready(function() {
        $('#example').DataTable();
    });
</script>

<h:body>
<div class="container">
    <h:dataTable value="#{edit.studentList}" var="student"
        styleClass="table table-striped table-bordered" id="example">
        <h:column headerText="Student">
            <f:facet name="header">
                <h:outputLabel>Student</h:outputLabel>
            </f:facet>
            <h:outputText value="#{edit.studentList.indexOf(student) + 1}" />
        </h:column>
        <h:column>
            <f:facet name="header">
                <h:outputLabel>Number</h:outputLabel>
            </f:facet>
            <h:outputText value="#{student.no}" />
        </h:column>
        <h:column>
            <f:facet name="header">
                <h:outputLabel>Name</h:outputLabel>
            </f:facet>
            <h:outputText value="#{student.name}" />
        </h:column>
        <h:column>
            <f:facet name="header">
                <h:outputLabel>Surname</h:outputLabel>
            </f:facet>
            <h:outputText value="#{student.surname}" />
        </h:column>
        <h:column>
            <f:facet name="header">
                <h:outputLabel>Grade</h:outputLabel>
            </f:facet>
            <h:column>
                <h:form>
                    <h:inputText value="#{student.grade}" class="form-control"></h:inputText>
                </h:form>
            </h:column>
        </h:column>
        <h:column>
            <h:form>
                <h:commandButton class="btn btn-danger btn-sm" value="Save"
                    action="#{edit.saveGrade(student)}" />
            </h:form>
        </h:column>
        <h:column>
            <h:form>
                <h:commandButton class="btn btn-danger btn-sm"     value="Delete"
                    action="#{edit.deleteStudent(student)}" />
            </h:form>
        </h:column>
    </h:dataTable>
</div>
</h:body>
</html>


text:
Q: Getting the output of a msqli prepared statement as a variable in PHP I am beginning using prepared statements:
($stmt = $db->prepare('SELECT email FROM users WHERE token=?'))
|| fail('MySQL prepare', $db->error);
$stmt->bind_param('s', $token)
|| fail('MySQL bind_param', $db->error);
$stmt->execute()
|| fail('MySQL execute', $db->error);
$stmt->close();

The statement returns an email address, and I was wondering if it is possible to convert the desired email address into a string for further use in PHP? Which is the best way to do this?
Thanks.

A: $stmt->bind_result($email);
$stmt->fetch();
echo $email;

A: Very easy... with PDO:
$stmt = $db->prepare('SELECT email FROM users WHERE token=?');
$stmt->execute(array($token));
$desired_string = $stmt->fetchColumn();

note the amount of code required


text:
Q: JPA cant find Entity meta model even if it is present in code 2018-06-04 16:55:38.821  WARN 10092 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'topicController': Unsatisfied dependency expressed through field 'topicService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'topicService': Unsatisfied dependency expressed through field 'topicRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'topicRepository': Cannot create inner bean '(inner bean)#77e80a5e' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#77e80a5e': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2018-06-04 16:55:38.840  INFO 10092 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-06-04 16:55:38.884  INFO 10092 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-04 16:55:39.082 ERROR 10092 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field topicRepository in com.example.demo.topic.TopicService required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

here is my Entity Class
package com.example.demo.topic;
   import javax.persistence.Column;
   import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
   import javax.persistence.Table;
   @Entity
  @Table(name="Topic")
  public class TopicPOJO {
@Id
 @Column(name = "Id", nullable = false)
String id;
 @Column(name = "name", nullable = true)
String name;
 @Column(name = "desc", nullable = true)
String description;
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public TopicPOJO(String id, String name, String description) {
    super();
    this.id = id;
    this.name = name;
    this.description = description;
}

public TopicPOJO() {
    super();

}

}

**here is my application**
package com.example.demo.topic;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoJpaApplication {

public static void main(String[] args) {
    SpringApplication.run(DemoJpaApplication.class, args);
}
}

Here is My POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>demo-JPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo-JPA</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derby</artifactId>
        <scope>runtime</scope>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

here is my interface which extends repository
package com.example.demo.topic;
import org.springframework.data.repository.CrudRepository;

public interface TopicRepository extends CrudRepository<TopicPOJO,String>
{
}

here is my service class
package com.example.demo.topic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;

@Service
public class TopicService {
@Autowired
TopicRepository topicRepository;
public List<TopicPOJO> getAllTopics()
{
    List<TopicPOJO> topics=new ArrayList<>();
    topicRepository.findAll()
    .forEach(topics::add);
    return topics;
}

public TopicPOJO getTopic(String id)
{
    return topicRepository.findById(id).get();
}

public void addTopic(TopicPOJO topic)
{
    topicRepository.save(topic);

}

public void updateTopic(String id,TopicPOJO topic) {

    topicRepository.save(topic);
}

public void deleteTopic(String id) {

    topicRepository.deleteById(id);
}

}

Here is my Controller
package com.example.demo.topic;
import java.util.List;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TopicController {

@Autowired
TopicService topicService;

@RequestMapping("/topic")
public List<TopicPOJO> getAlltopics()
{

    return topicService.getAllTopics();

}

@RequestMapping("/topic/{id}")
public TopicPOJO gettopic(@PathVariable String id)
{

    return topicService.getTopic(id);

}

@RequestMapping(method=RequestMethod.POST,value="/topic")
public void addTopic(@RequestBody TopicPOJO topic)
{

     topicService.addTopic(topic);

}

@RequestMapping(method=RequestMethod.PUT,value="/topic/{id}")
public void updateTopic(@RequestBody TopicPOJO topic,@PathVariable String
id)
{

     topicService.updateTopic(id,topic);

}

@RequestMapping(method=RequestMethod.DELETE,value="/topic/{id}")
public void deleteTopic(@PathVariable String id)
{

     topicService.deleteTopic(id);

}

}


text:
Q: pagebackref option is not working in Beamer When I use \usepackage[pagebackref]{hyperref} in \documentclass{article}, it works perfectly. But when I use it in beamer class i.e. \documentclass[hyperref={pagebackref=true}]{beamer}, it does not work and no error is displayed. My task is to include the page numbers where the reference is cited in the bibliography produced by beamer. Please advise how I can achieve my task.
the following example is working perfectly
\documentclass{article}
\usepackage[colorlinks=true,citecolor=blue,pagebackref=true]{hyperref}
\usepackage[english]{babel}
\usepackage{Sweave}

\begin{document}
Antecedent to 1970, Luce and Tukey's \cite{Luce1964} present first article on conjoint. Explain the relation between consumer's decision and the factors involved in his/ her decision making \cite{Orme2010}. In 1971, Green and Rao's joint effort of card-sort conjoint analysis \cite{Green1971} gained success beyond imagination. In 1975, Green and Wind \cite{Green1975} described the measures consumer judgments for carpet cleaners, and business leaders, this new method was soon taken into consideration.

\bibliographystyle{Ieeetr}
\bibliography{References/conjoint}

\end{document}

but when I used the following
\documentclass[hyperref={pagebackref=true,colorlinks=true,citecolor=blue,pagebackref=true}]{beamer}
\usepackage{graphicx}
\usepackage[english]{babel}
\usepackage[square, numbers]{natbib}
\usepackage{Sweave}
\usepackage{ragged2e}

\usepackage{beamerthemeshadow}

\begin{document}
\justifying

\section{Conjoint Analysis }
\begin{frame} \frametitle{Conjoint Analysis}
Antecedent to 1970, Luce and Tukey's \cite{Luce1964} present first article on conjoint. Explain the relation between consumer's decision and the factors involved in his/ her decision making \cite{Orme2010}. In 1971, Green and Rao's joint effort of card-sort conjoint analysis \cite{Green1971} gained success beyond imagination. In 1975, Green and Wind \cite{Green1975} described the measures consumer judgments for carpet cleaners, and business leaders, this new method was soon taken into consideration.
\end{frame}

\bibliographystyle{Ieeetr}
\bibliography{References/conjoint}

\end{document}

no error found, but I am unable to find the page number in the bibliography to go-back at the page where it was cited as done in article class in first example.

A: As is mentioned in the comments, this is something which is simply not implemented in beamer. Support for bibliographies in the class is limited, and reflects the fact that presentations are not good places for such things.

A: Answers along the lines "you should not want that feature" make me sad. Usually the OP has a reason to require that feature...and the same desire brought me here.
I think I found a solution - although I have not tested it extensively.
The problem seems to be that hyperref is loaded inside of beamer (and here as part of  \documentclass). Thus, configuring some of the options of hyperref later in the document using \hypersetup works for some options of hyperref but not for all. It looks like this is the case here: hyperref patches the reference system as part of its loading, and when later the respective options are set, there is no way to tell hyperref to redo this patching process.
For this sequencing issue there is \PassOptionsToPackage which can be used before \documentclass.
My solution is to place
\PassOptionsToPackage{pagebackref=true}{hyperref}
\PassOptionsToPackage{backref=slide}{hyperref}

before \documentclass and then the whole thing works nicely.
Bug: My solution only works partially. It prints the backlinks in the bibliography, but (a) the links are not yet working properly and (2) for broken frames the number is not always correct. So, still working on it.
** Solved:** Ok. Now it works. The issue was that you have to use.
  \PassOptionsToPackage{backref=page}{hyperref}


text:
Q: Make a code with number prefix and other string prefix in Laravel I have to make a format for transaction number and the format example is a BKK-202009-00001. The number 00001 that will auto increment.I've tried but not getting the expected output.
CODING
public function createBefore($model, $arrayData, $metaData, $id=null)
{
    //$arrayData["no_draft"] = $this->custom_getdraftid(null);
    $prefix = 'BBK';

    if ($arrayData['payment_type']=='CASH') {
        $prefix='BKK';
    } elseif ($arrayData['payment_type']=='GIRO') {
        $prefix='BGK';
    }
    ff($prefix);
    $no_transaction = \DB::table('acc_tra_cash_bank_expenses_header')
    ->selectRaw(" '$prefix' || '-' ||to_char(CURRENT_DATE, 'YYYYMM')||'-'||RIGHT('0000'||(
                            RIGHT( (SELECT no_transaction FROM acc_tra_cash_bank_expenses_header WHERE no_transaction LIKE '$prefix'||to_char(CURRENT_DATE, 'YYYYMM')||'%'
                                        ORDER BY id DESC LIMIT 1),5)::INTEGER+1)::TEXT,5) AS no_transaction")->first();
    ff($no_transaction->no_transaction);
    if (!$no_transaction) {
        $bulantanggal = date('Ym');
        $no_transaction->no_transaction = "$prefix-$bulantanggal-00001";
    }

    $newModel = $model;
    $newArrayData  = array_merge($arrayData, [
       'no_draft'=> $this->custom_getdraftid(null),
        'no_transaction' => $no_transaction->no_transaction
    ]);
    return [
        "model"  => $newModel,
        "data"   => $newArrayData,
    ];
}

A: If I understand you correctly, you need a format like BKK-202009-00001 with incrementing number. A solution would be like
$string = 'BKK-202009-00001'; //the last entry from the database
$number = last(explode("-",$string)); //explode the string to get the number part, last is a laravel helper
$new = str_pad(intval($number) + 1, 5, 0, STR_PAD_LEFT); //increment the number by 1 and pad with 0 in left.

$no_transaction->no_transaction = $prefix.'-'.$bulantanggal.'-'.$new; //concat string and number to generate the desired output