text:
Q: Xamarin forms: The equivalent of .Finish() I have a Xamarin Forms application which very well on all three platforms. The app has a login screen and other pages that are available one a user has successfully logged in. My question is: In Xamarin Forms; is there a way to have the equivalent of the Finish method that Xamrin for Android provides to remove the login page from the navigation stack? If a user keeps pressing the back button they eventually get back to the login screen which is undesirable. I have tried using Navigation.PopAsync () but seem not to work

A:
Navigation.PopAsync and Navigation.RemovePage should definitely work.
BUT if your page is also a MainPage you can't remove it. You could change it to another page using this code:
App.Current.MainPage = new NavigationPage(new MyContentPage());


text:
Q: Find $x$ as the given $n$th term in the Fibonacci sequence? With a given $n$ and I am trying to find the value of $x$, as in:
$$Fib(x)=n$$
Using the formula for Fibonacci sequence, where $\varphi$ is the Golden Ration ($\approx1.61803399\ldots$)
$$Fib(z) = \frac{\varphi^z - \cos(z \pi)\varphi^{-z}}{\sqrt{5}}$$
How can I find $x$ if, lets say, $n=11261957$? I so far have this:
$$\varphi^x-\cos(x\pi)\varphi^{-x}=\sqrt{5}(11261957)$$
But I don't know where to go from there. Any help is appreciated!

A: You can calculate it recursively given the formula $$F_n=F_{n-2}+F_{n-1}$$(you can use a code which does it). Formulas which are iterative like $$(\omega=\frac{1+\sqrt 5}{2})\quad F_n=\frac{\omega^{n+1}-\bar\omega^{n+1}}{\sqrt 5}$$ are not that useful in your case, since that's equivalent to solve an equation which for big values of $F_n$ is not that easy to solve. Nevertheless, you can solve them using numerical methods taking $f(n)$ as the nth Fibonacci number.

A: From
$$\phi^x - \cos(x\pi)\phi^{-x} = 11261957\sqrt{5}$$
we can assume that $\phi^{-x}$ is small and get
$$\phi^x \approx 11261957\sqrt{5}$$
The solution to this is
$$x \approx \frac{ln(11261957\sqrt{5})}{ln(\phi)} \approx 35.414$$
and indeed the $35^\text{th}$ and $36^\text{th}$ Fibonacci numbers are
$$9227465 \qquad \text{and} \qquad 14930352$$
which are as close as you can get to $11261957$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pick rows in a 2d Numpy array and store into another so that one array keeps the rows with the highest values in a given column? I have a series of Numpy 2d arrays with a few columns and thousands of rows each.
The first column has a "quality" value for the row.
I also have an empty 2d Numpy array with 50 rows and same number of columns of the arrays above.
I'd like to iterate over these 2d arrays and select into this second array the values with the highest quality value, so that at the end the second array has the rows with the highest quality from all the initial 2d arrays.
For example:
arrays = [
    np.array([[10, 1, 1, 1], [1, 1, 1, 1], [3, 1, 1, 1], [2, 1, 1, 1]]),
    np.array([[1, 2, 2, 2], [1, 1, 1, 1], [1, 1, 1, 1], [200, 1, 1, 1]]),
    np.array([[1, 2, 2, 2], [40, 1, 1, 1], [30, 1, 1, 1], [2, 1, 1, 1]]),
    np.array([[300, 2, 2, 2], [1, 1, 1, 1], [3, 1, 1, 1], [2, 1, 1, 1]]),
]

best_arrays = np.zeros((2, 4), dtype=np.int)

for i in range(len(arrays)):
   arr = arrays[i]

   # do something so that the rows with highest quality are selected into the `best_arrays` array

   print(best_arrays)

So in that the loop would print:
>> [[10, 2, 2, 2], [3, 1, 1, 1]]  # best rows of first array
>> [[10, 2, 2, 2], [200, 1, 1, 1]]  # best rows between first and second arrays
>> [[40, 2, 2, 2], [200, 1, 1, 1]]
>> [[300, 2, 2, 2], [200, 1, 1, 1]]  # best_arrays has the rows with highest "quality" of all.

How can I do this in Numpy? These arrays have a very large number of rows so I can't just iterate over in pure python - I'm looking for a Numpy function so that it runs in C.
Thanks!

A: Since you say that the number of rows are in thousands (which is not that bad), I think this approach will be fairly efficient and flexible to pick the needed number of best rows from each 2D array.
best = 2
quality_col = 0
for array in arrays:
# sort the rows based on the "quality" column
     print(array[np.flip((array[:, quality_col].argsort()))][:best, :])

Output
[[10  1  1  1]
 [ 3  1  1  1]]
[[200   1   1   1]
 [  1   1   1   1]]
[[40  1  1  1]
 [30  1  1  1]]
[[300   2   2   2]
 [  3   1   1   1]]

A: This is a working example derived from @sai's answer with that last step to concatenate arrays and pick the best ones:
import numpy as np

arrays = [
    np.array([[10, 1, 1, 1], [1, 1, 1, 1], [3, 1, 1, 1], [2, 1, 1, 1]]),
    np.array([[1, 2, 2, 2], [1, 1, 1, 1], [1, 1, 1, 1], [200, 1, 1, 1]]),
    np.array([[1, 2, 2, 2], [40, 1, 1, 1], [30, 1, 1, 1], [2, 1, 1, 1]]),
    np.array([[300, 2, 2, 2], [1, 1, 1, 1], [3, 1, 1, 1], [2, 1, 1, 1]]),
]

best_arrays = np.zeros((0, 4), dtype=np.int64)

best = 2
quality_col = 0
for i in range(len(arrays)):
   best_arrays = np.vstack((best_arrays, arrays[i]))

   # select the best rows
   best_arrays = best_arrays[np.flip((best_arrays[:, quality_col].argsort()))][:best, :]

print(best_arrays)

And the best ones are selected:
[[300   2   2   2]
 [200   1   1   1]]


text:
Q: Exhaustive `match` against a bounded random number open System

let random_number_generator = System.Random(int System.DateTime.Now.Ticks) in
let random_number_below n = random_number_generator.Next(n) in
match random_number_below 3 with
| 0 -> "Zero!"
| 1 -> "One!"
| 2 -> "Two!"
;;

The above match statement is not exhaustive, according to the compiler. This is totally legitimate, as F# has no syntactical information that would guarantee the bounds of the random number.
Incomplete pattern matches on this expression. For example, the value '3' may indicate a case not covered by the pattern(s).

What were the idiomatic F# way of matching (or is it simply if-else'ing) against a random number?

A: As in the comments, solving this in general requires solving the halting problem.  As a result the best thing to do is probably
|_ -> failwith "broken RNG"


text:
Q: Propel is dropping database column instead of just renaming it I'm looking for some help with propel's migrations feature.
Its dropping field and creating another one with the new name if the field has been renamed in schema.xml.
Buy this leads to data loss for the specified column... how can i prevent propel from doing that ?
My test case was the following :

*

*Creating a field in schema.xml called "title"

*Inserting data in database

*Renaming field "title" to "name"

*Issuing a select from database.

The data previously inserted in "title" field is now empty.
When looking to migration class it contains :
ALTER TABLE `city`

  ADD
(
    `title` VARCHAR(255) NOT NULL
),

  DROP `name`;

A: When you change the column name in the XML, Propel (nor any other tool) has no way of knowing that you have renamed that column, or if you wanted to remove the old column and add the new one.
It diffs the XML with the database, and sees a column in the database which doesn't exist in your XML (title), so it deletes that column. Then it sees a column in the XML which doesn't exist in the database (name) so it creates the column title for you.
If you want to rename the column, you should do that manually.

A: I know this is a really old question but the simple way to fix this is to rename the column in the xml and then generate the diff.  After that go in to the generated-migration and modify it to rename the column instead of dropping and adding it.  Then when you run the migration it will work properly.
If your database engine is MySQL the code is as follows
ALTER TABLE "table_name"
Change "column 1" "column 2" ["Data Type"];
http://www.w3schools.com/sql/sql_alter.asp


text:
Q: Add logic inside button click inside a custom control I am making a custom control that looks like this (there is a label on the right of the button):
I want the user to be able to define what the button does in his code, but still execute some code on the click event on top of the user's code.
What I want to execute :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Button1.Enabled = False
    Label1.ForeColor = Color.Gray
    Label1.Text = "In Progress"

End Sub

then after this is executed the user's on click event would trigger.
How can I achieve this?

A: With "the user" you mean a developer which uses that user control, right? Well, the most common thing is to raise an event which the next developer can use to implement his own logic. This is exactly the same as you do - you use the Click-Event of the button.
So basically, take your code and add the RaiseEvent below:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Button1.Enabled = False
    Label1.ForeColor = Color.Gray
    Label1.Text = "In Progress"

    ' this does not affect your code but provides a "hook" for
    ' other developers
    RaiseEvent OnButtonClick(Button1)

End Sub

Now you need to define the event itself like this ...
Public Event OnButtonClick(ByVal sender As Control)

... btw, you can pass other stuff (or nothing at all) as arguments. Sending the button as sender is just a habit.
A developer using your user control can attach a so called "Handler" to implement code as soon as the button was clicked, for example:
 AddHandler UserControl1.OnButtonClick, AddressOf OnUserControlButtonClick

This code line should only be executed once, so typically it is placed in the Form_Load event.
Now, in this case the button click is routed to a method called OnUserControlButtonClick() which meets the signature of the event: that means it has one argument which is the sender.
Private Sub OnUserControlButtonClick(ByVal sender as Control)
    ' custom logic here ...
End Sub

There are so many examples on the web, you could start here.


text:
Q: ¿ Una tabla hija debe llevar la llave primaria de la tabla padre? Tengo una base datos donde la tabla usuarios hereda de la tabla persona y otra tabla empleados que también hereda de usuarios , a la vez los usuarios pueden crear empleados.
Soy principiante en Base Datos, recuerdo en mis clases nos decian que las tablas de herencia no deberían llevar llave primaria, que tan cierto es esto? Yo personalmente considero que las tablas hijo si deberian llevar llave primaria. Alguien me puede explicar mejor porfavor.---1 ¿Las tablas hijas deberian llevar llave primaria o simplemente heredar la llave primaria del padre (que es PERSONA)?
---2) ¿En que afectaría que no tenga llave primaria las tablas hijo?
---3) ¿Por ultimo es correcto afirmar que todas las tablas deben tener su llave primaria?


text:
Q: How to dynamically add to a nested element in a JSON object in Java? I want a json object which is equivalent to
var data = {"nodes":"var postLoadData = {\n nodes:{408868239:{'tipo':'clase','shape':'dot','label':'clase2'},843594076:{'tipo':'clase','shape':'dot','label':'ESTADIA'}},edges:{\n 2:{408868239:{},843594076:{}}}};\n \n sys.graft(postLoadData);"}

i have done like this
JSONObject jsonObject = new JSONObject();
jsonObject.put("nodes", "var postLoadData = {\n nodes:{408868239:{'tipo':'clase','shape':'dot','label':'clase2'},843594076:{'tipo':'clase','shape':'dot','label':'ESTADIA'}}," +
                "edges:{\n 2:{408868239:{},843594076:{}}}};\n \n sys.graft(postLoadData);");

i need to add edges and nodes dynamically to this json object. how to do that.

A: Have you read the API for JSONObject it defines the operations you will need. From what I can see you will need to manipulate the value for the key nodes.
I'm curious to see what your JS is going to look like given you have JS in your JSON. Are you planning on calling exec? I'd be very careful how you implement. JSON is used to exchange data what you are trying to do is exchange JS which is not what it's intended for, nor is it safe to do so.

A: You do not have JSON, what you have in that string is this javascript code:
var postLoadData = {
    nodes: {
        408868239: {
            'tipo': 'clase',
            'shape': 'dot',
            'label': 'clase2'
        },
        843594076: {
            'tipo': 'clase',
            'shape': 'dot',
            'label': 'ESTADIA'
        }
    },
    edges: {
        2: {
            408868239: {},
            843594076: {}
        }
    }
};
sys.graft(postLoadData);

The closest valid JSON of that could be:
{
    "nodes": {
        "408868239": {
            "tipo": "clase",
            "shape": "dot",
            "label": "clase2"
        },
        "843594076": {
            "tipo": "clase",
            "shape": "dot",
            "label": "ESTADIA"
        }
    },
    "edges": {
        "2": {
            "408868239": {},
            "843594076": {}
        }
    }
}

You could use the above JSON (not the javascript code) and then do this:
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( theJsonString );


text:
Q: Android 5.0.2 onwards don't allow HID access through Bluetooth LE My app is working fine, until Android 5.0.2 doesn't allow third party app to connect to HID device over Bluetooth low energy.
myGatt.setCharacteristicNotification(gattChar, true);

06-01 17:39:35.356: W/BluetoothGatt(21599):
java.lang.SecurityException: Need BLUETOOTH_PRIVILEGED permission:Neither
user 10157 nor current process has android.permission.BLUETOOTH_PRIVILEGED.

<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />

BLUETOOTH_PRIVILEGED permission doesn't work on a third party app. It's only for system or manufacturer apps.
The latest changes from Android note:
Enforce BLUETOOTH_PRIVILEGED permission for HID-over-GATT
https://android.googlesource.com/platform/packages/apps/Bluetooth/+/02bebee
Code snippet:

private static final UUID[] HID_UUIDS = {
    UUID.fromString("00002A4A-0000-1000-8000-00805F9B34FB"),
    UUID.fromString("00002A4B-0000-1000-8000-00805F9B34FB"),
    UUID.fromString("00002A4C-0000-1000-8000-00805F9B34FB"),
    UUID.fromString("00002A4D-0000-1000-8000-00805F9B34FB") };

if (isHidUuid(charUuid)) enforcePrivilegedPermission();

My question: is there a way to overwrite HID_UUIDS  or enforcePrivilegedPermission? Can I use reflection to by pass it?
Every times Android released a new version, it breaks the previous code.
Thanks!

A: The question is old, but still worth answering.
The HID (and FIDO https://fidoalliance.org/) service is protected and indeed requires system permission source. Only apps signed with the system key may use this service, that is only Bluetooth settings. This is to ensure that 3rd party apps are not able to listen to keys typed on a wireless keyboards, as all notifications and indications are transferred to all BluetoothGatt objects. Without this protection you would be able to connect to a HID device (you still can), enable notifications using gatt.setCharacteristicNotification(.., true) and receive updates whenever a key is typed. With a bit of knowledge about Report characteristics you can then get all the keys and mouse positions, including passwords, etc. So it's not a break, but a bug fix. On KitKat you still may do this.
The only solution is to compile your own AOSP Android version and sign your app with the same key. Otherwise it would be useless protection.
Btw, starting form Android 8 or perhaps earlier you don't get SecurityException. The call just returns true as if any other and you never get any callback.
This might have been changed here: https://android.googlesource.com/platform/packages/apps/Bluetooth/+/32dc7a6b919375aede777f3c821fa316d85449ae%5E%21/#F2


text:
Q: How is Errai able to serialize/deserialize model entities I'm trying to use Errai rest capabilities in my GWT app,
I took a look at the following guide:
http://errai-blog.blogspot.it/2011/10/jax-rs-in-gwt-with-errai.html
In particular, it says:

We simply put this interface somewhere in our client packages (e.g.
  client.shared) where the GWT compiler can find it. To create a request
  all that needs to be done is to invoke RestClient.create()

I think there's a plot hole here, how is Errai able to know how serialize/deserialize model classes ?
Can you help understanfing this ?
thanks

A: According to RestClient Class's create() method
 public static <T, R> T create(final Class<T> remoteService, final RemoteCallback<R> callback, Integer... successCodes) {
   return create(remoteService, null, callback, null, successCodes);
}

In example which you've provided; when using create() method Errai gets the CustomerService Class as remoteService, After many operations;
Errai parses and implements this CustomerService Interface with using their errai-codegen library which uses Java Reflection API.
When parsing simply;

*

*First it looks for JAX-RS annotated methods and defines them as
JaxrsResourceMethod

*Then it looks into parameters of that method if there is any parameter that annontated with JAX-RS annotations.

*If it finds annontated parameters in JaxrsResourceMethod, it keeps that parameter with it's annotation type

*If it finds not annontated parameter in JaxrsResourceMethod it defines as a entityParameter

*Errai holds these annotated parameter and entityParameters  in JaxrsResourceMethodParameters by their method. When building request it uses parameters by their rule.
Let me explain these rules with using an example you've provided.
Customer customer = new Customer("new name", "new last name", "new postal code");
RestClient.create(CustomerService.class, callback).updateCustomer(240193, customer);

Errai will create url like

example.com/cusomers/240193

Because @PathParam("id") annotation rule is adding parameter to the url and according to Errai's entityParameter rule customer will be marshalled when sending data with PUT.
@PUT
@Path("/{id}")
@Consumes("application/json")
@Produces("application/json")
public Customer updateCustomer(@PathParam("id") long id, Customer customer); //- See more at: http://errai-blog.blogspot.com.tr/2011/10/jax-rs-in-gwt-with-errai.html#sthash.2GTQtIg8.dpuf

One more additional note if you check here there is an exception in setEntityParameter method;

Only one non-annotated entity parameter allowed per method:

This means you cant define methods with more than 1 non-annotated parameter in Class which you sent in Errai.


text:
Q: Read txt file without lock in python I am copying the new content of a .txt source file to another with the use of an offset.
with open(source, "rb") as infile:
            infile.seek(offset)
            data = infile.read()
with open(destination, "ab") as outfile:
            outfile.write(data)

Meanwhile, the source file can be updated (new rows added). Can a problem appear with this implementation ? This code could lock the source file ?
This script runs every n seconds and the source file updates can be made at any time.

A: If changes are made while its running you could have problems such as missing data. By locking the file you ensure that no changes are made during execution, and that the copy matches.
Is there a reason you don't want to lock the file?


text:
Q: How to convert DateTime to VarChar(50)? I need to convert DateTime value to Varchar value in 'dd-mm-yyyy hh:mm:ss tt' format.
Please resolve.
Datetime format: 2013-12-13 23:10:56.000
Varchar format: 26/10/2013 08:36:44 PM

A: If you just want that output, googling "sql server datetime format" will reveal this link. If you want to alter the column itself, you have two options:

*

*Alter it directly, then update it and fix the format afterwards.
OR

*Add a new column of the type varchar(20). Move data from old DATETIME column, remove the old column. If needed rename the new column.

A: Try:

CONVERT(VARCHAR(50),GETDATE(),130)


text:
Q: Matlab Image Baseline (Offset Removal) Correction I have this plot:

and want to flatten its baseline/reduce offset using Matlab.
Basically like a baseline correction for a spectrum but here I've got a mesh and can't get my head around it how to flatten its baseline when dealing with a matrix? Basically the dot should stay but the surrounding is actually zero. The noise can stay, though.
Here is the image:

I am wondering if something like this works:
        for x=1:1201
        for y=1:1201
             Ibasetest = polyfit(x,y,1);
        end
        end

Simply put do a baseline for each X along Y for Z data. But I can't get it to work. :(

A: Note: Another method to attempt may include moving/windowing averages to calculate the local amount to offset by.
Method 1: Discrete Cosine Transform (DC Offset Removal)
Converts the image into the frequency domain uses the Discrete Fourier Transform (DCT). Removes the DC coefficient in the top-left corner (set to zero) of the matrix and convert it back to the spatial domain using the Inverse Discrete Fourier Transform (IDCT).

Image = imread("Test_Image.jpg");

%Converting image to greyscale if RGB image%
[Image_Height,Image_Width,Depth] = size(Image);
if(Depth == 3)
Image = rgb2gray(Image);
end

%Removing image offset%
Discrete_Cosine_Transformed_Image = dct2(Image);
Discrete_Cosine_Transformed_Image(1,1) = 0;
Inverse_Discrete_Cosine_Transformed_Image = idct2(Discrete_Cosine_Transformed_Image);

Calibrated_Image = medfilt2(Inverse_Discrete_Cosine_Transformed_Image,[20 20]);

% Plotting the original and thresholded image%
X_Axes = (1:1:Image_Height);
Y_Axes = (1:1:Image_Width);

subplot(1,2,1); surf(X_Axes,Y_Axes,Image,'EdgeColor','none');
title("Original Image Plot");
xlabel('X-Axis'); ylabel('Y-Label');
zlim([0 255]);

subplot(1,2,2); surf(X_Axes,Y_Axes,uint8(Calibrated_Image),'EdgeColor','none');
title("Calibrated Image Plot");
xlabel('X-Axis'); ylabel('Y-Label');
zlim([0 255]);

Key Discrete Cosine Transform (DCT) Filtering Code Lines
%Removing image offset%
Discrete_Cosine_Transformed_Image = dct2(Image);
Discrete_Cosine_Transformed_Image(1,1) = 0;
Inverse_Discrete_Cosine_Transformed_Image = idct2(Discrete_Cosine_Transformed_Image)

Method 2: Standard Uniform Offset (no-tilt accommodation)
Uses a constant value and subtracts that across the whole image matrix.
Test Image 1: Using Lowest Intensity to Calculate Offset

Test Image 2: Using Average/Mean to Calculate Offset

Image = imread("Circular_Image.png");

%Converting image to greyscale if RGB image%
[Image_Height,Image_Width,Depth] = size(Image);
if(Depth == 3)
Image = rgb2gray(Image);
end

   %Removing image offset%
Lowest_Intensity_Value = min(Image,[],'all');
Average = mean(Image,'all');
Calibrated_Image = Image - Average;

% Plotting the original and thresholded image%
X_Axes = (1:1:Image_Height);
Y_Axes = (1:1:Image_Width);

subplot(1,2,1); surf(X_Axes,Y_Axes,Image,'EdgeColor','none');
title("Original Image Plot");
xlabel('X-Axis'); ylabel('Y-Label');
zlim([0 255]);

subplot(1,2,2); surf(X_Axes,Y_Axes,Calibrated_Image,'EdgeColor','none');
title("Calibrated Image Plot");
xlabel('X-Axis'); ylabel('Y-Label');
zlim([0 255]);

Using MATLAB version: R2019b


text:
Q: Syntax for named given/using objects in Scala 3 (Dotty) Is there a one-line way to provide a named reference to a value which is to be implicitly available (i.e. available with using syntax) without the soon-to-be-deprecated implicit keyword? According to the docs, I'd expect the following to work (under SBT, scalaVersion := "3.0.0-M2":
trait Greeter {
  def sayHello(username: String): Unit
  def shutdown(): Unit
}

def greet(username: String)(using g: Greeter): Unit = {
  g.sayHello(username)
}

object Foo extends App {
  given greeter: Greeter = new Greeter {
    override def sayHello(username: String): Unit = println(s"Hello, ${username}!")

    override def shutdown(): Unit = println("Shutting down")
  }

  try {
    greet("world")
  } finally {
    greeter.shutdown()
  }
}

but this fails with
[error] -- Error: /path/to/project/src/main/scala/Foo.scala:12:15
[error] 12 |  given greeter: Greeter = new Greeter {
[error]    |               ^
[error]    |               end of statement expected but ':' found
[error] -- [E040] Syntax Error: /path/to/project/src/main/scala/Foo.scala:12:17
[error] 12 |  given greeter: Greeter = new Greeter {
[error]    |                 ^^^^^^^
[error]    |                 ';' expected, but identifier found

Now: I can work around this in many ways, but either the docs are confusing (or wrong) or I'm misunderstanding something rather fundamental.
Workaround 1 (as suggested here):
lazy val greeter: Greeter = new Greeter {
  override def sayHello(username: String): Unit = println(s"Hello, ${username}!")
  override def shutdown(): Unit = println("Shutting down")
}
given Greeter = greeter
...

but I'd like to be able to do this in a single expression rather than two. The same comment applies to defining the given first and then binding it to a name:
given Greeter with {
  override def sayHello(username: String): Unit = println(s"Hello, ${username}!")

  override def shutdown(): Unit = println("Shutting down")
}
val greeter: Greeter = implicitly

especially since I think implicitly will be deprecated in 3.1 and gone in 3.2.
We could also wrap our invocations of the given object in functions to get around this:
def greet(username: String)(using g: Greeter): Unit = {
  g.sayHello(username)
}

def shutdown(using greeter: Greeter): Unit = {
  greeter.shutdown()
}

given Greeter with {
  override def sayHello(username: String): Unit = println(s"Hello, ${username}!")

  override def shutdown(): Unit = println("Shutting down")
}

try {
  greet("world")
} finally {
  shutdown
}

but that seems boilerplateful to me.

A: Turns out that the
given x: T = ...

syntax was added between revision M2 and revision RC1. The following works with scalaVersion := "3.0.0-RC1":
trait Greeter {
  def sayHello(username: String): Unit
  def shutdown(): Unit
}

def greet(username: String)(using g: Greeter): Unit = {
  g.sayHello(username)
}

object Foo extends App {
  given greeter: Greeter with {
    override def sayHello(username: String): Unit = println(s"Hello, ${username}!")

    override def shutdown(): Unit = println("Shutting down")
  }

  try {
    greet("world")
  } finally {
    greeter.shutdown()
  }
}


text:
Q: google visualization dataTableToCsv I'm using google.visualization.dataTableToCsv to create an Array I can iterate through to populate a Google Timeline chart. The data is coming from a Google Sheet. This is working well, except that strings with commas are getting separated when I use the split function. Is there a better method of doing this?

A: I was able to use the following function to fix this issue
function CSVtoArray(text) {
    var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
    var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;

    // Return NULL if input string is not well formed CSV string.
    if (!re_valid.test(text)) return null;

    var a = []; // Initialize array to receive values.
    text.replace(re_value, // "Walk" the string using replace with callback.
        function(m0, m1, m2, m3) {

            // Remove backslash from \' in single quoted values.
            if (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));

            // Remove backslash from \" in double quoted values.
            else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
            else if (m3 !== undefined) a.push(m3);
            return ''; // Return empty string.
        });

    // Handle special case of empty last value.
    if (/,\s*$/.test(text)) a.push('');
    return a;
};


text:
Q: I can't automatically log in to a site where I have not created an account I'm having this problem after migrating away from MyOpenID and setting my SE Open ID as primary.
I just tried clicking on theoretical cs and I got the Q&A notification bar. I'm using the 'SE open ID' now as main ID. I think my browser is OK for global auth, I just checked. I'm on Ubuntu Firefox.

First I clicked on 'Log in'

As you can see, no luck.

Currently my meta.stackoverflow profile shows this.

A: I just checked, and you do not have a cstheory account. Under no circumstances do we ever automatically create accounts.
So long as you have created an account on the target site, there are a few ways global auto-login can fail, largly based on oddball browser or network configurations. What does this say:
https://cstheory.stackexchange.com/network-login-help


text:
Q: erro mysql Error updating record: You have an error in your SQL syntax; pessoal estou com um problema em um update.
da este erro

string(42) " UPDATE files SET desc='ssss' WHERE id=131" Error updating record: You have an error in your SQL syntax; check the
  manual that corresponds to your MariaDB server version for the right
  syntax to use near 'desc='ssss' WHERE id=131' at line 1

segue meu código
 <?php
// Include the database configuration file
require 'conn/conn1.php';

$id_img = $_POST['id'];
$desc = $_POST['desc'];

$sql = " UPDATE files SET desc='$desc' WHERE id=$id_img";
var_dump($sql);

   if (mysqli_query($conn1, $sql)) {
      echo "Record updated successfully";
   } else {
      echo "Error updating record: " . mysqli_error($conn1);
   }
   mysqli_close($conn1);
?>

poderiam me ajudar por favor!

A: Bom dia, aparentemente não há concatenação entre sua string sql e sua variavel '.$variavel.', também se caso essa variavel for receber alguma string utilize '".$variavel."' espero ter ajudado.


text:
Q: A treatment of basic Kaluza-Klein theory I'm looking for a treatment of the original basic Kaluza-Klein theory.
Can someone recommend a review article or something?

A: How's this: http://www.weylmann.com/kaluza.pdf ?
Be careful though, because there are a couple very big errors that the author makes. For example in equation (6) there should not be a factor of 1/2 in front of the second term on the right-hand side. It should just be a factor of one. If you do the Christoffel symbol calculations and expand out the 5D geodesic equation, you'll get the following:
$$\frac{d^2 x^\lambda}{ds^2}+\begin{Bmatrix} \lambda \\ \mu \nu \end{Bmatrix} \frac{dx^\mu}{ds} \frac{dx^\nu}{ds}=-k\left ( \frac{dx^5}{ds} +A_\nu \frac{dx^\nu}{ds} \right )F^\lambda_{~\mu}\frac{dx^\mu}{ds}$$
In fact, the factor 1/2 that the author has in his paper keeps the equation from being gauge-invariant. Similarly, after equation (6) he says:

This expression is now fully covariant, although the $A_\nu F^\lambda_{~\mu}$ term does not have any classical correspondence.

This is incorrect. It makes no sense to split up the terms, which is why I factored them like you see above. It actually turns out that Noether conserved momentum about the curled-up 5th dimension is:
$$-mk\left ( \frac{dx^5}{ds} +A_\nu \frac{dx^\nu}{ds} \right )$$
So it's a conserved quantity which is gauge-invariant. By comparison with the usual Lorentz Force Law, this conserved momentum is therefore associated with charge.
You should also note that in more modern treatments of KK theory $g_{55}$ isn't restricted to being a constant, and is promoted to a scalar field. Physically this means that the 5th dimension is allowed to have variable size.


text:
Q: Production prefix not working on makeStyles classNames I am using createGenerateClassName for added prefix to className in Material-UI component used in federated library/module of lerna mono-repo.
import { createGenerateClassName, StylesProvider } from '@material-ui/core'

const generateClassName = createGenerateClassName({
      seed: 'xyz',
      productionPrefix: 'abc-',
    })

function Header() {
  return (
    <StylesProvider generateClassName={generateClassName}>
         ...
    </StylesProvider>
  )
}

But prefix is not getting added to classes made using makeStyles in production build mode. Although prefix is getting added to Mui classes.


text:
Q: Is there a way to get the worksheet names from 20MB+ Excel files with PHPExcel? I am using PHPExcel to read data out of Excel files.
With the following code, I am able to read one particular worksheet out of a 3MB Excel file in just a couple seconds. Works nicely.
However, I now have 27MB and 88MB Excel files which I need to get data out of. They are so large that even OpenOffice cannot open them.
I have found that I can use an index number instead of a name when I load a sheet, but this seems inconsistent, e.g. in one particular Excel file setLoadSheetsOnly(0) gave me the third sheet while setLoadSheetsOnly(1) gave me an error even though there were four worksheets in the file. So that seems unreliable for some reason.
Is there a way I can read out the names of the worksheets from a large file so that I can access only one of its worksheets at a time?
        $objReader = PHPExcel_IOFactory::createReaderForFile("data/" . $file_name);
        $objReader->setLoadSheetsOnly(array($sheet_name));
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load("data/" . $file_name);

        echo '
';
        for ($row = 1; $row < $number_of_rows; $row++) {
            echo '
';
            for ($column = 0; $column < $number_of_columns; $column++) {
                $value = $objPHPExcel->setActiveSheetIndex(0)->getCellByColumnAndRow($column, $row)->getValue();
                echo '';
                echo $value . ' ';
                echo '	';
            }
            echo '
';
        }
        echo '
';
        die;

ADDENDUM:
I found some code that gets close, but it doesn't seem to always be accurate, e.g. here it missed the second worksheet in a 27MB file:

and here it only got the third worksheet and missed 3 others:

$objReader = PHPExcel_IOFactory::createReaderForFile("data/" . $file_name);
$objReader->setLoadSheetsOnly(0);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("data/" . $file_name);

echo $objPHPExcel->getSheetCount(), ' worksheets
';
$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    echo $sheetIndex, ' -> ', $loadedSheetName, '
';
}
die;

A: Unfortunately, it isn't possible to read the names of the worksheets without loading the whole file.
Using an index number rather than a name when calling setLoadSheetsOnly() won't give a predictable result: the code logic that performs that check uses in_array() to test if the sheetname that it is about to read is in the array of sheetnames to read. e.g.
// check if sheet should be skipped
if (isset($this->_loadSheetsOnly) && !in_array($sheet['name'], $this->_loadSheetsOnly)) {
    continue;
}

I would suspect that the comparison of a string against a numeric value will be giving a true result for 0 == "mySheetName" when executing this test (based on PHP's loose typing and comparison casting rules).
I could probably provide a Reader method that would return a list of worksheet names without actually loading the entire file, although there would be a performance hit involved.
EDIT
If you add the following method to Classes/PHPExcel/Reader/Excel2007.php
/**
 * Reads names of the worksheets from a file, without loading the whole file to a PHPExcel object
 *
 * @param   string      $pFilename
 * @throws  Exception
 */
public function listWorksheetNames($pFilename)
{
    // Check if file exists
    if (!file_exists($pFilename)) {
        throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
    }

    $worksheetNames = array();

    $zip = new ZipArchive;
    $zip->open($pFilename);

    $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships");
    foreach ($rels->Relationship as $rel) {
        switch ($rel["Type"]) {
            case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument":
                $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"));  //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main");

                if ($xmlWorkbook->sheets) {
                    foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
                        // Check if sheet should be skipped
                        $worksheetNames[] = (string) $eleSheet["name"];
                    }
                }
        }
    }

    $zip->close();

    return $worksheetNames;
}

You can call it by using:
$inputFileType = 'Excel2007';
$inputFileName = 'biostat-behfisk-2005.xlsx';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$worksheetNames = $objReader->listWorksheetNames($inputFileName);

foreach ($worksheetNames as $sheetName) {
    echo $sheetName, '
';
}

the returned $worksheetNames should contain an array of all worksheet names as UTF-8 strings. Because it's only reading the absolute minimum from the .xlsx to retrieve these names, it should be fairly fast. I'll do some more tests before checking it into the PHPExcel SVN, but (for now) it seems to do what you need.
EDIT2
Equivalent method for the Excel5 Reader
/**
 * Reads names of the worksheets from a file, without loading the whole file to a PHPExcel object
 *
 * @param   string      $pFilename
 * @throws  Exception
 */
public function listWorksheetNames($pFilename)
{
    // Check if file exists
    if (!file_exists($pFilename)) {
        throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
    }

    $worksheetNames = array();

    // Read the OLE file
    $this->_loadOLE($pFilename);

    // total byte size of Excel data (workbook global substream + sheet substreams)
    $this->_dataSize = strlen($this->_data);

    $this->_pos     = 0;
    $this->_sheets  = array();

    // Parse Workbook Global Substream
    while ($this->_pos < $this->_dataSize) {
        $code = self::_GetInt2d($this->_data, $this->_pos);

        switch ($code) {
            case self::XLS_Type_BOF:    $this->_readBof();      break;
            case self::XLS_Type_SHEET:  $this->_readSheet();    break;
            case self::XLS_Type_EOF:    $this->_readDefault();  break 2;
            default:                    $this->_readDefault();  break;
        }
    }

    foreach ($this->_sheets as $sheet) {
        if ($sheet['sheetType'] != 0x00) {
            // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module
            continue;
        }

        $worksheetNames[] = $sheet['name'];
    }

    return $worksheetNames;
}

Not as efficient as the Excel2007 Reader version, but should still be faster than parsing the whole .xls file just for the sheet names because I'm only parsing the global stream.

A: I didn't want to amend phpexcel so I went with this:
public function getWorksheetNames($pFilename) {

    $worksheetNames = array ();

    $zip = zip_open ( $pFilename );
    while ( $entry = zip_read ( $zip ) ) {

        $entry_name = zip_entry_name ( $entry );
        if ($entry_name == 'xl/workbook.xml') {
            if (zip_entry_open ( $zip, $entry, "r" )) {
                $buf = zip_entry_read ( $entry, zip_entry_filesize ( $entry ) );
                $workbook = simplexml_load_string ( $buf );
                foreach ( $workbook->sheets as $sheets ) {
                    foreach( $sheets as $sheet) {
                        $attributes=$sheet->attributes();
                        $worksheetNames[]=$attributes['name'];
                    }
                }
                zip_entry_close ( $entry );
            }
            break;
        }

    }
    zip_close ( $zip );
    return $worksheetNames;
}

It only works on excel 2007 or later but did what I needed


text:
Q: Azure TableStorage HowTo? I want to store Contacts on to Azure table(name and gender as a property). so I basically two classes . the one which derives from the TableSerivceContext and the other from TableServiceEntity. now I cant connect the pieces. What I will really do at the cotroller(I use MVC3)
tnx for any hint?

A: im assuming that you are receiving the properties (name and gender) via post from a view.
so your controller might be like this
public ActionResult DoSomething(User model)
{

}

so what you need to do is.. that. make a new ofject of the class thats derived from the TableServiceEntity. and assign the Properties.
like this
var tableUser = new TableUser(){Name = model.Name, Gender=model.Gender}

then from the class derived from TableServiceContext make an object. and use AddObject() method to add the user to the table
http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.addobject.aspx

A: This is what I have done recently to create a very simple MVC3 + Windows Azure Table sample application:

*

*Created a Model Class DataEntity inherit from TableServiceEntity which include all the table properties needed to store along with PartitionKey and RowKey

*Created another Model class DataContext inherit from TableServiceConext which includes IQueryable sets up the Table

*Created a Controller class which creates HTTPGet and HTTPPost method type ViewResult returning View. The controller also have code to create the Table first using Model DataContext type and then added code to call AddObject as DataEntity type as below:

DataContext context = new DataContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
context.AddObject("DataEntryTable", dataEntity);
context.SaveChanges();
Finally you can create views from the controllers.

A: You would need to inherit 'Contact' from TableServiceEntity and a context class from TableServiceContext to provide all the methods to manage your 'Contact' entities. You can then invoke methods on the 'Context' class from anywhere (including the controller).
I have written an alternate Azure table storage client, Lucifure Stash, which does away with having to inherit from any base calls and supports additional abstractions over azure table storage. Lucifure Stash supports large data columns > 64K, arrays & lists, enumerations, composite keys, out of the box serialization, user defined morphing, public and private properties and fields and more.
It is available free for personal use at http://www.lucifure.com  or via NuGet.com.

A: Download the Windows Azure Platform Training Kit and do the lab on Windows Azure Storage.  In 15 minutes you will have a working prototype.


text:
Q: Glassfish 3.1.2.2 behind an SSL terminating load balancer The organisation I'm working for is currently running an application on Glassfish 3.1.2.2 behind a hardware (same issue with software/cloud) load balancer that is also in charge of SSL termination.  We are currently having issues with Glassfish not knowing that it is behind an SSL connection and therefor generating certain things incorrectly.  Specifically the following:

*

*session cookies are not flagged as secure

*redirects generated from Glassfish are done as http:// instead of https://

*request.isSecure() is not returning the correct value

*request.getScheme() is not returning the correct value

In theory we could rewrite all of these things in the load balancer, but on previous projects using Tomcat and have been able to solve all of them at the container level.
In Tomcat I can just set the secure flag and the scheme value on the HTTP connector definition and everything is good to go.  But I can't seem to find equivalents on Glassfish.
Anyone have any ides?

A: If your load balancer provides X-Forwarded-Proto header you can try to use scheme-mapping attribute in the http definition of your domain.xml:
<http default-virtual-server="server"
      max-connections="100"
      scheme-mapping="X-Forwarded-Proto">...

For example nginx can be configured to provide this header very easily:
location / {
    proxy_set_header X-Forwarded-Proto https;
    proxy_pass http://glassfish;
}

Looks like glassfish has some known issues related to scheme-mapping support though.


text:
Q: How can I find the smallest difference between values within a group EXAMPLE DF
df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Falcon',
                              'Parrot', 'Parrot', 'Parrot'],
                   'Max Speed': [380., 370., 25., 24., 26., 29.]})

DESIRED OUTPUT
2 (because the smallest difference is between 24 and 26 of Parrot)

EVEN BETTER (so I can check)
'Parrot, 2'

WHAT I WAS THINKING
'I need to sort by animal and max speed, and then a window function, but there must be a better solution...'

A: We can check groupby with diff
df['new'] = df.sort_values('Max Speed').groupby('Animal')['Max Speed'].diff().abs()
out = df[df.new==df.new.min()]
Out[249]:
   Animal  Max Speed  new
4  Parrot       26.0  2.0


text:
Q: If you roll two fair six-sided dice, what is the probability that the sum is 4 or higher?
If you roll two fair six-sided dice, what is the probability that the sum is $4$ or higher?

The answer is $\frac{33}{36}$ or $\frac{11}{12}$. I understand how to arrive at this answer. What I don't understand is why the answer isn't $\frac{9}{11}$? When summing the results after rolling two fair six sided dice, there are $11$ equally possible outcomes: $2$ through $12$. Two of these outcomes are below four, meaning $9$ are greater than or equal to four which is how I arrived at $\frac{9}{11}$. Can someone help explain why that is wrong?

A: $\frac9{11}$ is wrong precisely because it assumes the probabilities of getting each sum are equal. Here they are not: there's only one way to roll a sum of two (the snake eyes of gambling jargon) but six ways to roll a seven.

A: if the correct answer is $ \frac {33}{36}$ it means there are 36 possible results.. You should try to write them down..It will be more clear. You just used equiprobability in a case where there isn't equiprobability..$P(1)=0 \quad P(2) =1/36,\quad P(3)=2/36 ,\quad P(4)=3/36,$
$ P(5)=4/36 \quad P(6)=5/36 \quad P(7)=6/36 \quad P(8)=5/36 \quad  $
$ P(9)=4/36 \quad P(10)=3/36 \quad P(11)=2/36 \quad P(12)=1/36$
And the answer is just:
$$P=1-P(1)-P(2)-P(3)=\frac {33}{36}$$

A: Your probabilities are wrong. For each value of die 1, there are 6 possible values of die 2, the available scores for a roll of two dice are: (7 is the most likely score)
2,3,4,5,6,7

  3,4,5,6,7,8

    4,5,6,7,8,9

      5,6,7,8,9,10

        6,7,8,9,10,11

          7,8,9,10,11,12

So, out of the 36 total possible outcomes, 33 of them have a value of 4 or higher, or 33:36, or 11:12

A: It is wrong because it is not $11$ equally possible outcome.
There is exactly $1$ way to get the sum to be $2$. ($1+1=2$)
but there is more than one way to get $3$. ($1+2=3, 2+1=3$)

A: As pointed out by others, the possible sums of the dice don't all have an equal probability of showing up. To see this, you can write it all out:
Die 1 | Die 2 | result
  1       1       2
  1       2       3
  1       3       4
  ...
  6       5      11
  6       6      12

When you  look at the resulting table, there are 36 combinations. 1 of those is a 2 (ie you have a 1 in 36 chance of getting a 2 from D1 + D2), 2 of those are '3' etc.
Now it's easy to see how to get the chance of getting a 4 or higher.


text:
Q: Trying (and failing) to write if/else expression in JSX I am trying to write an if/else or conditional that returns a select box with different options in different conditions.
Precisely, when a taskCard is rendered, if the task's userId = 0, I want the select box to be prepopulated with "Assign To:" as the option AND I want all of the company's employees to appear as options beneath. If the task's userId matches the employee's Id, I want the employee's name to prepopulate the box and the remainder of the company's employees to show as options as well.
For some reason, I can't wrap my head around how to do this. I understand that React doesn't allow if/else statements, but even writing this as a ternary statement has caused me problems. I currently have working:
{this.props.employees.map(employee => {
  if (employee.id === this.props.task.userId) {
  return <option key={employee.id} id={employee.id} defaultValue={employee.id} selected>
  {employee.name} {employee.surname}
  </option>

  }  else {

  return <option key={employee.id} id={employee.id} value={employee.id} >
  {employee.name} {employee.surname}
  </option>
      }
    })}
   </select>

but this does not offer me the "Assign To:" option that I am looking for.

A: The first part could be simplified to reduce code duplication. The only difference of your condition is the selected prop, so if employee.id === this.props.task.userId equals true it's selected, otherwise not.
<select defaultValue={...}>
{this.props.employees.map(employee => (
  <option
    key={employee.id}
    id={employee.id}
    selected={employee.id === this.props.task.userId}
  >
    {employee.name} {employee.surname}
  </option>
));
</select>

The "assign to" option can simply be added before or after the map iteration.
<select defaultValue={this.props.task.userId}>
  {this.props.task.userId === 0
    ? <option value="0">Assign To:</option>
    : null
  }

  {this.props.employees.map(employee => (
    <option
      key={employee.id}
      id={employee.id}
      selected={employee.id === this.props.task.userId}
    >
      {employee.name} {employee.surname}
    </option>
  ))};
</select>

See the docs about conditional rendering

A: With the suggestion below, and some additional guidance, I arrived at the following solution:
{this.props.task.userId === 0
 ? <option value="0">Assign To:</option>
 : ""}

 {this.props.employees.map(employee => (
 <option
   key={employee.id}
   id={employee.id}
   defaultValue={employee.id}
   selected={employee.id === this.props.task.userId}
                                    >
   {employee.name} {employee.surname}
   </option>
   ))
   };
   </select>

And this does exactly what I was hoping to get the application to do. Thank you very much for the thoughts and extra eyes!


text:
Q: Windows Phone 8.1 ManipulationDelta Event I'm really confused about this Topic. None of the tutorials I found to e.g. move objects around when there's touch input works. For example they all do something like this:
Control.AddHandler(UIElement.ManipulationStartedEvent, new EventHandler
    <ManipulationStartedEventArgs>(Control_ManipulationStarted), true);

But there's no ManipulationStartedEventArgs, VS2013 can't find it and there's no way to add a using directive. Are those tutorials old and did MS change the way the ManipulationDelta works?
Adding it with the EventHandler section of the Properties section again doesn't work, no Event is fired no matter what I'm trying to do.

A: For manipulation to work the UI Element must have ManipulationMode property set to something other than None or System to be a manipulation event source; i.e Set ManipulationMode to TranslateX if you want an event to fire on a horizontal pointer movement.
For UI manipulation in Windows Universal you have 3 events:

*

*ManipulationStarted

*ManipulationDelta

*ManipulationCompleted

Each with their own EventArgs under System.Windows.Input namespace

*

*ManipulationStartedEventArgs

*ManipulationDeltaEventArgs

*ManipulationCompletedEventArgs

The problem may however be the type of UI Element that you are using, not all accept/generate manipulation events.
Examples of UI Elements that don't:

*

*WebView

*(I expect Canvas but not sure, haven't tested)
Examples of UI Elements that do:

*

*Textblock

*ListView


text:
Q: How to align different input fields in Shiny (vertical offset/padding/alignment)? New to shiny. I'm creating a data exploration app for some experimental data.
I first select a variable to subset by and then use sliders to select a range for the said variables (shown in image). The subsetted data is overlaid on the original plot in red.

I want the sliderInput to be aligned at the same level as the selectInput. What's the best way to do that? I also want to add a checkbox or radio button for these variables which if selected would add a secondary plot (or secondary axis - I know, not recommended but that's what is desired). I haven't implemented that yet but putting that here since that would require the same aligning.
CODE
The arguments of sliderInput and selectInput have been removed for brevity. zdat() is a reactive data.table.
UI
fluidRow(
    column(4,
           uiOutput("subsetZoomPlot_x"), # Select x-axis for SortZoomPlot
           uiOutput("subsetZoomPlot_y"), # Select y-axis for SortZoomPlot
           uiOutput("subsetZoomPlot_var1"), # Subset data by var1
           uiOutput("subsetZoomPlot_var2"), # Subset data by var2
           uiOutput("subsetZoomPlot_var3") # Subset zoomplot data by var3
           ),

    column(4,
           uiOutput("subsetZoomPlot_var1_slider"), # range for subsetZoomPlot_var1 (slider input)
           uiOutput("subsetZoomPlot_var2_slider"), # range for subsetZoomPlot_var1 (slider input)
           uiOutput("subsetZoomPlot_var3_slider") # range for subsetZoomPlot_var1 (slider input)
    )
  ),

  fluidRow(
    plotOutput("subsetZoomPlot")
  )

SERVER
output$subsetZoomPlot_x <- renderUI({
    selectInput(inputId = "subsetZoomPlot_x", ...)
  })

  output$subsetZoomPlot_y <- renderUI({
    selectInput(inputId = "subsetZoomPlot_y", ...)
  })

  output$subsetZoomPlot_var1 <- renderUI({
    selectInput(inputId = "subsetZoomPlot_var1", ...)
  })

  output$subsetZoomPlot_var2 <- renderUI({
    selectInput(inputId = "subsetZoomPlot_var2", ...)
  })

  output$subsetZoomPlot_var3 <- renderUI({
    selectInput(inputId = "subsetZoomPlot_var3", ...)
  })

  output$subsetZoomPlot_var1_slider <- renderUI({
    vmin <- floor(min(zdat()[, get(input$subsetZoomPlot_var1)]))
    vmax <- ceiling(max(zdat()[, get(input$subsetZoomPlot_var1)]))
    sliderInput(...)
  })

  output$subsetZoomPlot_var2_slider <- renderUI({
    vmin <- floor(min(zdat()[, get(input$subsetZoomPlot_var2)]))
    vmax <- ceiling(max(zdat()[, get(input$subsetZoomPlot_var2)]))
    sliderInput(...)
  })

  output$subsetZoomPlot_var3_slider <- renderUI({
    vmin <- floor(min(zdat()[, get(input$subsetZoomPlot_var3)]))
    vmax <- ceiling(max(zdat()[, get(input$subsetZoomPlot_var3)]))
    sliderInput(...)
  })

EDIT:
I added my current code for the UI section. It already has fluidrow(column(), column()) for the layout. My problem is that I want the slider for var1 (rh in the screenshot) to be aligned at the same level as the dropdown where rh is selected (selectInput) and the same for the other two variables. This means the second column needs to be vertically displaced. Is the only way to do this using multiple fluidrow statements for each combination of selectInput and sliderInput?

A: All of the layout issues are things that need to be addressed in the UI section of your shiny app code.
From what I can tell it looks like the code you've included with your question is in the server section since it seems that you have dynamic inputs in your app.
Here is some simple UI code that aligns a select input with a slider input
library(shiny)

ui <- fluidPage(title = 'Example',

            fixedRow(
              column(width = 2,
                     selectInput('input1_choice', 'Select Plot variable 1',
                                 choices = letters[11:20])),
              column(width = 2,
                     sliderInput('input1_val', 'Select Variable 1 Value',
                                 0, 10, 5)
              )
            ),
            fixedRow(
              column(width = 2,
                     selectInput('input2_choice', 'Select Plot variable 2',
                                 choices = letters[1:10])
              ),
              column(width = 2,
                     sliderInput('input2_val', 'Select Varaible 2 Value',
                                 0, 10, 5)
              )
            )
)

shinyApp(ui, server = function(input, output) { })

So each fixedRow call creates a  row in the UI, and each column call within a fixedRow call creates a column in that row to fill with a UI object.
As you change the types of UI objects the height of that row can change but it won't overlap or bleed into another row demonstrated here:
library(shiny)

ui <- fluidPage(title = 'Example',

            fixedRow(
              column(width = 2,
                     selectInput('input1_choice', 'Select Plot Variable 1',
                                 choices = letters[11:20])),
              column(width = 2,
                     radioButtons('input1_val', 'Select Variable 1 Value',
                                 choices = LETTERS[11:20])
              )
            ),
            fixedRow(
              column(width = 2,
                     selectInput('input2_choice', 'Select Plot Variable 2',
                                 choices = letters[1:10])
              )
            ),
            fixedRow(
              column(width = 2,
                     selectInput('input3_choice', 'Select Plot Variable 3',
                                 choices = letters[1:10])
              ),
              column(width = 2,
                     sliderInput('input3_val', 'Select Variable 3 Value',
                                 0, 10, 5)
              )
            )
)

shinyApp(ui, server = function(input, output) { })

The only difference between these examples and what you'll need is to replace the explicit UI object calls I've made (selectInput for example) with uiOutput calls.
Like some comments have said there's documentation out there. I've found https://shiny.rstudio.com/reference/shiny/latest/ to be especially useful.

A: Not sure it is the best solution, but you can use columns in your UI :
fluidRow(
column(4,selectInput("select_x", "Select X Axis", ...)),
column(8),
column(4,selectInput("select_y", "Select Y Axis", ...)),
column(8)
column(4, selectInput("subsetZoomPlot_var1", ...)),
column(4, sliderInput(...)),
column(4),
column(4, selectInput("subsetZoomPlot_var2", ...)),
column(4, sliderInput(...)),
column(4),
...
)


text:
Q: I Want To Load My Products As A Grid Using Php I am building a site, I want to load all products as a grid of col-md-6 on desktop devices but I used this code below but it's loading differently. What Should I do?
<?php
$params = array('posts_per_page' => 4, 'post_type' => 'product');
$wc_query = new WP_Query($params);
?>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
                $wc_query->the_post(); ?>

                <?php the_post_thumbnail(); ?>

<?php the_title(); ?>

                <form><button class="button-default" type="submit"><a href="<?php the_permalink(); ?>"> View Product Details</button></form>

            <?php $row ?>

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else:  ?>

     <?php _e( 'No Products'); ?>

<?php endif; ?>

A: You need to define container class outside the loop. Try this.

<?php
$params = array('posts_per_page' => 4, 'post_type' => 'product');
$wc_query = new WP_Query($params);
?>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
            $wc_query->the_post(); ?>

            <?php the_post_thumbnail(); ?>

<?php the_title(); ?>

            <form><button class="button-default" type="submit"><a href="<?php the_permalink(); ?>"> View Product Details</button></form>

        <?php $row ?>

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else:  ?>

 <?php _e( 'No Products'); ?>

<?php endif; ?>


text:
Q: How to debug why a database trigger is not working? My first two IF statements work just fine (I've tested them), but for some reason the ELSE IF statement won't fire. I've tried different setups for the entire ELSE IF statement, different  arrangements with the @DiscountPercent, and putting the IF statements in a different order, but nothing works. It all results in .3 when it needs to be 30. Can someone please point me in the direction of where I can learn about what I'm doing wrong?
USE MyGuitarshop

GO

CREATE TRIGGER Products_UPDATE
    ON Products
    FOR UPDATE, INSERT

AS

DECLARE
    @DiscountPercent int;

BEGIN

SET @DiscountPercent = (SELECT DiscountPercent FROM INSERTED);

IF @DiscountPercent < 0
    BEGIN
        ROLLBACK TRANSACTION;
        THROW 528732,'Discount Percent cannot be less than 0.',1;
    END;

IF @DiscountPercent > 100
    BEGIN
        ROLLBACK TRANSACTION;
        THROW 528733,'Discount Percent cannot be greatter than 100%.',1;
    END;

ELSE IF @DiscountPercent < 1
        UPDATE Products
            SET @DiscountPercent = ((SELECT DiscountPercent FROM INSERTED) * 100)
            WHERE ProductID IN (Select ProductID FROM Inserted);

END;

GO

UPDATE Products
    SET DiscountPercent = .3
        WHERE ProductID = 1;

GO

USE MyGuitarShop

SELECT * FROM Products

A: There are two special tables that you have access to within the stored procedure. The tables can be examined to reflect the state of the data. Be sure to understand that multiple operations can be batched for certain circumstances.
Trigger - Inserted and Deleted Tables

A: You need to get the value of DiscountPercent from INSERTED table , then check it  :
DECLARE
    @DiscountPercent int;
Begin
SET @DiscountPercent = (SELECT DiscountPercent FROM INSERTED);
.
.
.

That will work when Update/Insert one row , if there is more than 1 row Updated/Inserted then you need to use another way to get all the values.

A: Figured it out!!!! This is what the code needs to be to work:
USE MyGuitarshop

GO

CREATE TRIGGER Products_UPDATE
    ON Products
    FOR UPDATE, INSERT

AS

DECLARE
    @DiscountPercent int;

BEGIN

SET @DiscountPercent = (SELECT DiscountPercent FROM INSERTED);

IF @DiscountPercent < 0
    BEGIN
        ROLLBACK TRANSACTION;
        THROW 528732,'Discount Percent cannot be less than 0.',1;
    END;

IF @DiscountPercent > 100
    BEGIN
        ROLLBACK TRANSACTION;
        THROW 528733,'Discount Percent cannot be greatter than 100%.',1;
    END;

ELSE
    UPDATE Products
        SET DiscountPercent = (SELECT DiscountPercent FROM INSERTED) * 100
            FROM Products
                Join Inserted
                    On Products.ProductID = Inserted.ProductID
            WHERE (SELECT DiscountPercent FROM INSERTED) < 1

END;

GO

UPDATE Products
    SET DiscountPercent = .3
        WHERE ProductID = 4;

GO

USE MyGuitarShop

SELECT * FROM Products


text:
Q: Will `std::vector` do anything I haven't asked it to In C++, if I initialize a std::vector v(100); and never try to resize() nor reserve() it, is the capacity() guaranteed to stay the same all the time? I want to make sure that no memory alloc/freeing/realloc/etc is going on for perforance reasons. (Yes, it would affect performance; my functions are called all the time, and they must returrn quickly).
Resuming it all:
std::vector<float> v;
// somehow, `v' is initialized to have 100 elements
void f() { // this function must return _very_ quickly
    /* do some processing, without ever calling v.resize() or v.reserve(), but
       accesing v.size() and v[i] all the time */
    /* it is guaranteed that no system calls (such as memory management)
       will take place here? */
} // no objects on the stack whose destroyers might try to `delete' anything.

A: From the remarks on vector::reserve() in C++11 23.3.6.3 "vector capacity":

It is guaranteed that no reallocation takes place during insertions
  that happen after a call to reserve() until the time when an insertion
  would make the size of the vector greater than the value of
  capacity().

A: There is vector::data() exposing the array allocated. Hence it is fair to assume that any operation on the vector equivalent to any modification on vector::data() will not effect memory allocation.

A: Any non-const operation on the vector might modify it. Any O(n) operation (like push_back) on the vector may cause the underlying data to be relocated. You can click into the various pages on cppreference to see what the big-Oh notation is for the operations you intend to use.
Calls to size and the subscript operator must complete in O(1) time, and so the vector would not reallocate its buffer.


text:
Q: Is the SSL Certificate in a web-browser for a web app the same as the SAML 2.0 security cert? This might not be a very intelligent question, but I have done my homework of looking around for the answer and I cannot seem to find it.  I am still to new to use SAML terms in this post, so I will define below how I am using them.
Authentication = My company has implemented SAML so that our AD/LDAP authenticates all our users to other applications that we use
Service Provider = is the company providing the application that is relying in our LDAP authentication using SAML 2.0
As I understand the problem we are having is.  There is a certificate used inside the implementation of our SAML 2.0, this certificate will expire soon, and the moment it does all Service Providers will be unable to authenticate.
I am trying to find out were/how to change this certificate, but I am getting confuse with the SSL certificate that the web browser uses for HTTP.
Any suggestions will be great.
I just added a related question in the following link: Expiring Certificate will stop working?

Adding some information.  The X509 Certificate was self-signed by our company. My contact told me that they will re-issue the same certificate.  Will I have to send a public key to the SPs?  Or I just change mine, and is transparent for them?

A: The term "SSL certificate" is flawed. X.509 certificates existed before SSL appeared, and they are not related to SSL. They are used in SSL, but this is just one of the uses.
You need to find out what the original certificate is and what certificate authority issued it (or it is a self-signed certificate). Then you can move further in getting or creating a new certificate (or reissuing the current one).
Update: if the certificate is self-signed, then the other parties probably added it to trusted certs list explicitly in order to accept it. So the re-issued certificate should also be added explicitly (IOW you'd need to send the public part to other parties).

A: @Geo - is your cert for your SAML implementation self-signed (aka self-issued) or signed by a 3rd Party Cert Authority? Also, what product are you using as your SAML Identity Provider? Do you know how the original was generated?


text:
Q: How to query data from ADO.NET Entity Model in Model of asp.net mvc c# I am a new to asp.net mvc c#, Now I created an ADO.NET Entity Model , and retrieved all the table in my database to put in it. Now I have create a View in my project, and I want to take the data from the ADO.net entity to show in my view as the table or something else.
Could anyone show me, how can I query data from ADO.net entity in my model of asp.net mvc?
Thanks in advanced.

A: if you are new to mvc then i think that the great starting point would be to download projects   http://nerddinner.codeplex.com/ and http://mvcmusicstore.codeplex.com/ and go from there. you will definitely get your answer from there.also see this to get the idea
http://www.asp.net/mvc/tutorials/older-versions/movie-database/create-a-movie-database-application-in-15-minutes-with-asp-net-mvc-cs


text:
Q: IDE For Objective-C On Linux I'm learning Objective-C and i would like to know where i can found a IDE for Objective-C on Linux?

A: There are two different IDEs provided with GNUstep, I prefer ProjectManager but there's also ProjectCenter. While neither has been released in a while, the state in VCS is much better than the date of the last release would lead you to believe :-).

A: Honestly when it comes to doing Objective-C and you have access to a Mac, Xcode is your best bet but here's what I know would be close enough on a Linux box:

*

*Project Center

*KDevelop

*And not sure if there's a plugin for it, but Eclipse is a fairly good IDE.

A: What do you want out of an IDE?  Emacs has a very good Objective-C mode, and good integration to parse build errors from GCC and also debug with GDB.  It would be a good IDE for most tasks, unless you really want a GUI builder.

A: Have a look at the latest FreeBSD release, which incorporates Clang, a rival of gcc with a BSD licence instead of a GPL licence.


text:
Q: How to Print Text in a Log This Way R.string.text I have an application and I want to print the stock text in the string file.
But having him put it directly in the Log shows a line
If you convert it by adding an empty text with it the text is printed as a number
Thanks in advance
Main Class
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.i("TAG", R.string.text);

}}

A: Try like this:
Log.i("TAG",getString(R.string.app_language));

A: Try This
 Log.i("TAG",getResources().getString(R.string.text));


text:
Q: JMeter Kafka test by Pepper-box. Jmeter Error: PlaintTextLoadGenerator: Please make sure... parameters are correctly passed I want to do a kafka performmance test by JMeter.
I follow by the next tutorial:

*

*tutorial1

*tutorial2
and I got this error:
2021-09-01 18:13:04,582 INFO o.a.j.e.StandardJMeterEngine: Running the test!
2021-09-01 18:13:04,583 INFO o.a.j.s.SampleEvent: List of sample_variables: []
2021-09-01 18:13:04,584 INFO o.a.j.p.j.s.JavaSampler: Created class: com.gslab.pepper.sampler.PepperBoxKafkaSampler. Uses tearDownTest:
2021-09-01 18:13:04,584 INFO o.a.j.g.u.JMeterMenuBar: setRunning(true, *local*)
2021-09-01 18:13:04,733 INFO o.a.j.e.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group
2021-09-01 18:13:04,733 INFO o.a.j.e.StandardJMeterEngine: Starting 1 threads for group Thread Group.
2021-09-01 18:13:04,733 INFO o.a.j.e.StandardJMeterEngine: Thread will continue on error
2021-09-01 18:13:04,733 INFO o.a.j.t.ThreadGroup: Starting thread group... number=1 threads=1 ramp-up=1 delayedStart=false
2021-09-01 18:13:04,734 INFO o.a.j.t.ThreadGroup: Started thread group number 1
2021-09-01 18:13:04,734 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started
2021-09-01 18:13:04,752 INFO o.a.j.t.JMeterThread: Thread started: Thread Group 1-1
2021-09-01 18:13:04,757 ERROR c.g.p.l.i.PlaintTextLoadGenerator: Please make sure that expressions functions are already defined and parameters are correctly passed.
com.gslab.pepper.exception.PepperBoxException: java.lang.NullPointerException
    at com.gslab.pepper.input.SchemaTranslator.getPlainTextMsgIterator(SchemaTranslator.java:54) ~[pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.input.SchemaProcessor.getPlainTextMessageIterator(SchemaProcessor.java:36) ~[pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.loadgen.impl.PlaintTextLoadGenerator.<init>(PlaintTextLoadGenerator.java:34) [pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.config.plaintext.PlainTextConfigElement.iterationStart(PlainTextConfigElement.java:53) [pepper-box-1.0%20(1).jar:?]
    at org.apache.jmeter.control.GenericController.fireIterationStart(GenericController.java:399) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.control.GenericController.fireIterEvents(GenericController.java:391) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.control.GenericController.next(GenericController.java:160) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.control.LoopController.next(LoopController.java:134) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.threads.AbstractThreadGroup.next(AbstractThreadGroup.java:91) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:254) [ApacheJMeter_core.jar:5.4.1]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_191]
Caused by: java.lang.NullPointerException
    at com.gslab.pepper.input.compile.InMemoryJavaCompiler.compileSchemaClass(InMemoryJavaCompiler.java:39) ~[pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.input.SchemaTranslator.getPlainTextMsgIterator(SchemaTranslator.java:47) ~[pepper-box-1.0%20(1).jar:?]
... 10 more
2021-09-01 18:13:04,757 ERROR c.g.p.c.p.PlainTextConfigElement: Failed to create PlaintTextLoadGenerator instance
com.gslab.pepper.exception.PepperBoxException: com.gslab.pepper.exception.PepperBoxException: java.lang.NullPointerException
    at com.gslab.pepper.loadgen.impl.PlaintTextLoadGenerator.<init>(PlaintTextLoadGenerator.java:37) ~[pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.config.plaintext.PlainTextConfigElement.iterationStart(PlainTextConfigElement.java:53) [pepper-box-1.0%20(1).jar:?]
    at org.apache.jmeter.control.GenericController.fireIterationStart(GenericController.java:399) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.control.GenericController.fireIterEvents(GenericController.java:391) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.control.GenericController.next(GenericController.java:160) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.control.LoopController.next(LoopController.java:134) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.threads.AbstractThreadGroup.next(AbstractThreadGroup.java:91) [ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:254) [ApacheJMeter_core.jar:5.4.1]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_191]
Caused by: com.gslab.pepper.exception.PepperBoxException: java.lang.NullPointerException
    at com.gslab.pepper.input.SchemaTranslator.getPlainTextMsgIterator(SchemaTranslator.java:54) ~[pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.input.SchemaProcessor.getPlainTextMessageIterator(SchemaProcessor.java:36) ~[pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.loadgen.impl.PlaintTextLoadGenerator.<init>(PlaintTextLoadGenerator.java:34) ~[pepper-box-1.0%20(1).jar:?]
... 8 more
Caused by: java.lang.NullPointerException
    at com.gslab.pepper.input.compile.InMemoryJavaCompiler.compileSchemaClass(InMemoryJavaCompiler.java:39) ~[pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.input.SchemaTranslator.getPlainTextMsgIterator(SchemaTranslator.java:47) ~[pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.input.SchemaProcessor.getPlainTextMessageIterator(SchemaProcessor.java:36) ~[pepper-box-1.0%20(1).jar:?]
    at com.gslab.pepper.loadgen.impl.PlaintTextLoadGenerator.<init>(PlaintTextLoadGenerator.java:34) ~[pepper-box-1.0%20(1).jar:?]
... 8 more
2021-09-01 18:13:04,757 ERROR o.a.j.t.JMeterThread: Test failed!
java.lang.NullPointerException: null
    at com.gslab.pepper.config.plaintext.PlainTextConfigElement.iterationStart(PlainTextConfigElement.java:63) ~[pepper-box-1.0%20(1).jar:?]
    at org.apache.jmeter.control.GenericController.fireIterationStart(GenericController.java:399) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.control.GenericController.fireIterEvents(GenericController.java:391) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.control.GenericController.next(GenericController.java:160) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.control.LoopController.next(LoopController.java:134) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.threads.AbstractThreadGroup.next(AbstractThreadGroup.java:91) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:254) [ApacheJMeter_core.jar:5.4.1]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_191]
2021-09-01 18:13:04,758 INFO o.a.j.t.JMeterThread: Thread finished: Thread Group 1-1
2021-09-01 18:13:04,758 INFO o.a.j.e.StandardJMeterEngine: Notifying test listeners of end of test
2021-09-01 18:13:04,758 INFO o.a.j.g.u.JMeterMenuBar: setRunning(false, *local*)

after I saw this post:
Jmeter Error: PlaintTextLoadGenerator...
I installed JDK (win10), but still got the same error, so probably this is the point.
what did I miss?
Thanks!

A: *

*You forgot to include the screenshot of your Java Request sampler, it might be the case you're using it in the way which is not supported. Like if you're trying to use JMeter Functions or Variables - it will fail, you will have to go for template functions instead (it's possible to create your own if pre-defined ones are not suitable for your case

*Your  pepper-box-1.0%20(1).jar file looks very suspicious, it sounds like you downloaded the plugin to the "lib/ext" folder of your JMeter installation twice, please remove any extra copies as it might cause issues

*If you have Kafka java client libraries in JMeter Classpath you don't need any plugins in order to send a message to Kafka, you can do it using JSR223 Sampler and this example Groovy code:
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerRecord

def props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

def producer = new KafkaProducer<>(props);
producer.send(new ProducerRecord<>("your-topic", "your_payload_here");

producer.close();


text:
Q: Azure global network firewall I've got several Subscriptions in a Tenant. I'm trying to find a way to avoid new Web Apps to be accessible for the open internet.
I could create a Network Security Group for that application and control the access from there. But I was thinking for something more... "global". Tenancy level or subscription lever if the global is not possible.
Can something like that be set up?

A: *

*Network Security Groups can only be applied to subnet level (not even vnet), you can apply to NIC but that even lower

*NSG do not work for WebApps

*For WebApps you need to use web.config to control access

*Pretty sure there is no way of doing what you want to achieve in a centralized fashion at least out of the box in Azure

A: Just to highlight, VNet Integration gives your web app access to resources in your virtual network but does not grant private access to your web app from the virtual network. Private site access refers to making your app only accessible from a private network such as from within an Azure virtual network. Private site access is only available with an ASE configured with an Internal Load Balancer (ILB). For details on using an ILB ASE, start with the article here: https://learn.microsoft.com/en-us/azure/app-service/environment/create-ilb-ase
A common scenario where you would use VNet Integration is enabling access from your web app to a database or a web service running on a virtual machine in your Azure virtual network. With VNet Integration, you don't need to expose a public endpoint for applications on your VM but can use the private non-internet routable addresses instead.
Ref : https://learn.microsoft.com/en-us/azure/app-service/web-sites-integrate-with-vnet