text:
Q: React Google Maps Stuck on "Loading" when putting the StandaloneSearchBox in the code I have a page on my react js where I am trying allow companies to register for my website and add their locations so that other companies come over for rentals, purchases, etc. I also need Markers if I can add them. I have gotten my Google Maps on my page, however, I can't get the Search bar (StandaloneSearchBox) on the page because it is stuck on "Loading". Here is my code:
import {useState, useEffect } from 'react'
import { GoogleMap, StandaloneSearchBox, LoadScript } from '@react-google-maps/api';

const initialState = {
  company: '',
  email: '',
  password: '',
  isMember: true,
}

  const Register = () => {

    const mapContainerStyle = {
      height: "400px",
      width: "800px"
    }

    const center = {
      lat: -3.745,
      lng: -38.523
    };

  const [values, setValues] = useState(initialState)

  // global state and useNavigate
  const handleChange = (e) => {
    console.log(e.target)
  }

  const onSubmit = (e) => {
    e.preventDefault()
    console.log(e.target)
  }
  const handleLoad = ref => this.searchBox = ref;
  const handlePlacesChanged = () => console.log(this.searchBox.getPlaces());
    return (

Direct Connection

Register

Want to join and connect with companies? Sign up and get your company out there:

    Profile Photo:
      <input id="image" type="file" name="profile_photo" placeholder="Photo" required="" capture></input>
    Company Name

        <input text="headline headline--input" placeholder="Enter Company"></input>

    Email

          <input text="headline headline--input" placeholder="Enter Email"></input>

     Map

  <LoadScript
    googleMapsApiKey='API_HERE'>
        <GoogleMap
          id="map"
          mapContainerStyle={mapContainerStyle}
          center={center}
          zoom={10}
        >

          <StandaloneSearchBox
          onLoad={handleLoad}
          onPlacesChanged={handlePlacesChanged}
        >
          <input
            type="text"
            placeholder="Customized your placeholder"
            style={{
              boxSizing: `border-box`,
              border: `1px solid transparent`,
              width: `240px`,
              height: `32px`,
              padding: `0 12px`,
              borderRadius: `3px`,
              boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
              fontSize: `14px`,
              outline: `none`,
              textOverflow: `ellipses`,
              position: "absolute",
              left: "50%",
              marginLeft: "-120px"
            }}
          />
        </StandaloneSearchBox>
        </GoogleMap>
      </LoadScript>

                          Direct Connection

706-263-0175

    )
}

export default Register

I have tried adding more imports like from the ScriptLoaded file in the ../api/docs folder, however, it causes the whole page to go blank. If I get rid of the StandaloneSearchBox from import {} from '@react-google-maps/api' and from the LoadScript GoogleMap code, it has it on the page no problem, only it doesn't have the Search Bar and Markers to search for an address (StandaloneSearchBox)

A: I think the problem is that there was no library. In order for it to display the Search Box, there has to be a library. const lib = ['places']; is setting the places as a library and the library must be added to the LoadScript code where your API key goes. Updated code should have fixed the issue here:
import {useState, useEffect } from 'react'
import { GoogleMap, LoadScript, StandaloneSearchBox } from '@react-google-maps/api'
const lib = ['places'];
const mapContainerStyle = {
  height: "400px",
  width: "800px"
}

const center = {
  lat: -3.745,
  lng: -38.523
};

const position = {
  lat: 37.772,
  lng: -122.214
}

const initialState = {
  company: '',
  email: '',
  password: '',
  isMember: true,
}

  const Register = () => {

    const [searchBox, setSearchBox] = useState(null);

  const handlePlacesChanged = () => console.log(searchBox.getPlaces());
  const handleLoad = ref => {
    setSearchBox(ref);
  };

  const [values, setValues] = useState(initialState)

  // global state and useNavigate
  const handleChange = (e) => {
    console.log(e.target)
  }

  const onSubmit = (e) => {
    e.preventDefault()
    console.log(e.target)
  }

      return (

Direct Connection

Register

Want to join and connect with companies? Sign up and get your company out there:

    Profile Photo:
      <input id="image" type="file" name="profile_photo" placeholder="Photo" required="" capture></input>
    Company Name

        <input text="headline headline--input" placeholder="Enter Company"></input>

    Email

          <input text="headline headline--input" placeholder="Enter Email"></input>

     Map

    <LoadScript
    googleMapsApiKey='API_HERE'
    libraries={lib}
    >
        <GoogleMap
          mapContainerStyle={mapContainerStyle}
          center={center}
          zoom={10}
        >
          <>
           <StandaloneSearchBox
          onLoad={handleLoad}
          onPlacesChanged={handlePlacesChanged}
        >

          <input
            type="text"
            placeholder="Search"
            style={{
              boxSizing: `border-box`,
              border: `1px solid transparent`,
              width: `240px`,
              height: `32px`,
              padding: `0 12px`,
              borderRadius: `3px`,
              boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
              fontSize: `14px`,
              outline: `none`,
              textOverflow: `ellipses`,
              position: "absolute",
              left: "50%",
              marginLeft: "-120px"
            }}
          />
        </StandaloneSearchBox>
        </>
        </GoogleMap>
</LoadScript>

                          Direct Connection

706-263-0175

    )
}

export default Register


text:
Q: adding column in view not present in database table I have a table in my database. Let's say that it has 3 fields: field1,field2,field3. Now I want to create a view which will contain field1,field2, and filed4, where filed4 is the new filed. Now I want to know Is it possible to make such a view. if yes then how?
I am using MySQL query browser version 1.1.20

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add suffix to variable value conditional on another variable Given the data below, what is the easiest way to add a suffix to the variable 'var' depending on the value of 'type'? So for example, if type = "white", add "_t" to the end of each value of var, and add "_b" if type = "black".
structure(list(var = c("test", "test", "score", "score", "base",
"base"), type = c("white", "black", "white", "black", "white",
"black")), row.names = c(NA, -6L), spec = structure(list(cols = list(
    var = structure(list(), class = c("collector_character",
    "collector")), type = structure(list(), class = c("collector_character",
    "collector"))), default = structure(list(), class = c("collector_guess",
"collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x0000024d0c9a2b10>, class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"))

A: We can use dplyr::case_when():
library(tidyverse)

dat %>%
  mutate(var = case_when(type == "white" ~ paste0(var, "_t"),
                         type == "black" ~ paste0(var, "_b"))
         )
#> # A tibble: 6 × 2
#>   var     type
#>   <chr>   <chr>
#> 1 test_t  white
#> 2 test_b  black
#> 3 score_t white
#> 4 score_b black
#> 5 base_t  white
#> 6 base_b  black

data from OP
dat <- structure(list(var = c("test", "test", "score", "score", "base",
                       "base"),
               type = c("white", "black", "white", "black", "white",
                                         "black")),
          row.names = c(NA, -6L),
          class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"))

Created on 2023-02-20 with reprex v2.0.2

A: Another option with tidyverse
library(dplyr)
library(stringr)
df1 %>%
  mutate(var = str_c(var, substr(str_replace(type, "^w", "t"), 1, 1), sep = '_'))

-output
# A tibble: 6 × 2
  var     type
  <chr>   <chr>
1 test_t  white
2 test_b  black
3 score_t white
4 score_b black
5 base_t  white
6 base_b  black


text:
Q: Close Primeng's ModalBox when clicked I am reviewing the Primeng documentation for the Modals, but I can not find a way to programmatically close a Modal Box (Example, when I click the "accept" button).
source: https://www.primefaces.org/primeng/#/dialog

A: As shown on the documentation,  the <p-dialog> component has a [(visible)] property. It's two-binding, so you can actually close (or hide) the element by setting the aforementioned property's value to false. Example:
<p-dialog header="Foo" [(visible)]="showDialog">
  <p-footer>
    <button type="button" (click)="functionToCloseDialog()" label="Accept"></button>
  </p-footer>
</p-dialog>

And your ts file will have something like:
export class SomeComponent {
  showDialog: boolean;

  functionToCloseDialog() {
    this.showDialog = false; // closes/hides the dialog box
  }
}

A: Now you dont need to use hide and show. You need to include DynamicDialogRef service for example:
 constructor(private ref: DynamicDialogRef) {}

 closeModal(): void {
    this.ref.close();
 }

 closeModalWithData(): void {
   // you can pass data like this
   this.ref.close(data)
   // and catch it after with onClose event
 }


text:
Q: Find the additive inverse of vector space Exercise with proposed solution
So for this question, the functions I am getting for the additive inverse are the following:
-u
and
-6-u
following the process of the answer in the following question:
Finding the additive inverse in a vector space with unusual operations
Which will give me -3 and -3 for the vector.
For some reason it is still wrong.
I think I am misunderstanding something
Update:
(u1,u2) element of V, (v1,v2) element of V: Addition is defined as (u1+v1-3, u2+v2+3) and not as simply (u1+v1, u2+v2). So I can't just say that the additive inverse is -(u2,u2).
If I set u1+v1-3=3 and u2+v2+3=-3, I get v1=-u1 and v2 = -6-u2 which would represent the i functions as mentioned above. However, they don't seem to work.

A: The first several are correct but you seem to have misunderstood the last question.  You are asked for the additive inverse of (x, y) which will depend on x and y, not constants.  (x, y)+ (p, q) is defined as (x+ p- 3, y+ q+ 3).  Since the additive identity is (3, -3) we must have x+ P- 3= 3 and y+ q+ 3= -3 so p= 6- x and q= -y- 6.
The additive inverse of (x, y) is (6- x, -y- 6).


text:
Q: Solution to DE over closed smooth manifold I am trying to prove the following assertion:
Let $V$ be a smooth vector field on a closed manifold. Then the differential equation $x'=V(x)$ has a solution for all time.
My idea is to use local existence around each point, and by compactness pick a subcover of the open cover formed by these neighborhoods and "patch" them together. Is this correct?

A: For each $x \in M$, choose $\varphi_x:U_x \to M$ a chart such that $x \in \varphi_x(U_x)$.  Let $x \in W_x \subset K_x \subset U_x$ where $K_x$ is compact, and $V_x$ is open.  Choose a finite subcover $\varphi_{x_1}(W_{x_1}),\dots,\varphi_{x_n}(W_{x_n})$ of $M$.  Let $\tilde V_k$ be the vector field on $U_{x_k}$ such that its push forward by $\varphi_{x_k}$ is $V$ on $\varphi_{x_k}(U_{x_k})$.  Let $\delta>0$ be such that for all $y \in M$, there exists $k = 1,\dots,n$ with $B(\varphi_{x_k}^{-1}(y),\delta) \subset V_{x_k}$.  Let $\Delta = \max_k \sup\{|V_{x_k}(z)|: z \in K_{x_k}\}$.
Let $T$ be the supremum of those $\tau$ such that there exists a solution $x:[0,\tau] \to M$ satisfying $\dot x = V(x)$.  Suppose $T < \infty$, for a contradiction.
Choose $\tau > \max\{0,T - \frac12\delta/\Delta\}$.  Solve the equation $\dot z = \tilde V_k(z)$, $z(\tau) = \varphi_{x_k}^{-1} (x(\tau))$ on $W_{x_k}$.  Note that it has a solution for $t \in [\tau,T+\frac12\delta/\Delta]$.  Push forward this to a solution $\dot x = V(x)$ on $M$ for $t \in [0,T+\epsilon]$.

A: The theorem about the maximal solution tells us that if one end of its domain interval is finite, then the solution will leave every compact subset of the domain of the ODE when approaching this interval end.
As the manifold as domain of the ODE is itself compact, no solution can leave this compact set, thus by contradiction the domain interval of the maximal solution has no finite end-point, it is the whole real line.


text:
Q: SQL SERVER CONFIGURATION ERROR I got an errors named

The Specified service is not valid. To continue, provide a domain account for SQL SERVER AGENT service.
Parameter AGTSVCSTARTUPTYPE start must ba manual for clustering.
The service account is not valid. To continue, provide a domain account for SQL Server service.

I made the account name "NT AUTHORITY\SYSTEM" but still i got the same errors..


text:
Q: Get data from tcp listener callback in the main thread I've created a transparent proxy for fixing the incoming data, but I want to have all the data from the listening callback in the main thread (where I've opened the socket). What's the best way to do it in the C#?
I am using the library TrotiNet plus some rewriting logic - fixing the response header. The simple code - as follows
using System;
using TrotiNet;

namespace TrotiNet.Example
{
    public class TransparentProxy : ProxyLogic
    {
        public TransparentProxy(HttpSocket clientSocket)
        : base(clientSocket) { }

        static new public TransparentProxy CreateProxy(HttpSocket clientSocket)
        {
            return new TransparentProxy(clientSocket);
        }

        protected override void OnReceiveRequest()
        {
            Console.WriteLine("-> " + RequestLine + " from HTTP referer " +
                RequestHeaders.Referer);
        }

        protected override void OnReceiveResponse()
        {
            Console.WriteLine("<- " + ResponseStatusLine +
            " with HTTP Content-Length: " +
            (ResponseHeaders.ContentLength ?? 0));
        }
    }

    public static class Example
    {
        public static void Main()
        {
            int port = 12345;
            bool bUseIPv6 = false;

            var Server = new TcpServer(port, bUseIPv6);
            Server.Start(TransparentProxy.CreateProxy);

            Server.InitListenFinished.WaitOne();
            if (Server.InitListenException != null)
                throw Server.InitListenException;

            while (true)
            {
                //need to get the response data here
                System.Threading.Thread.Sleep(1000);
            }

            //Server.Stop();
        }
    }
}

So mainly, I need to get all the data that comes to OnReceiveResponse in the main thread (Example.Main executor). I do such a proxy for one call - so data not more than 1kB.

A: Probably you fit in producer/consumer pattern, try to use BlockingCollection it support "Concurrent adding and taking of items from multiple threads"
(https://msdn.microsoft.com/en-us/library/dd997371(v=vs.110).aspx) like this:
BlockingCollection<Data> dataItems = new BlockingCollection<Data>(100);

in your dataReceiver handler do
dataItems.Add(data);

in your main thread consumer:
data = dataItems.Take();

Also better to replace infinity loop with sleep to Console.Readkey()


text:
Q: How to store the remaining bit of a file into a variable in c My Code:
#include <stdio.h>

int main(int argc, char *argv[]){
  char line1[128];
  char line2[128];
  char line3[128];
  char rem_text[128];
  FILE *f;

  f = fopen((argv[1]), "r");
  if (!f) {
     printf("error");
  } else {
      fscanf(f, "%127[^\n]\n%127[^\n]\n%127[^\n]\n%127[^\n] ", line1, line2,line3, rem_text);
      printf("1:%s\n", line1);
      printf("2:%s\n", line2);
      printf("3:%s\n", line3);
      printf("4:%s\n", rem_text);
      fclose(f);
  }

  return 0;
}

The Program works almost as expected, except for one detail.
What it is supposed to do is, take the first three lines of a file and store them in individual variables. (which works) but then I would like to store the entire remaining bit of the file into its own variable.
How do I do that?
Thanks in advance
If for example my test.txt file contains
Kapitel 1
chapter_21.txt
chapter_42.txt
'Would you tell me, please, which way I ought to go from here?'
'That depends a good deal on where you want to get to,' said the Cat.
'I don't much care where -' said Alice.
'Then it doesn't matter which way you go,' said the Cat.
'- so long as I get SOMEWHERE,' Alice added as an explanation.
'Oh, you're sure to do that,' said the Cat, 'if you only walk long enough.'

I would like to store
Kapitel 1 as Title
chapter_21.txt as chapter_a
chapter_42.txt as chapter_b
and
'Would you tell me, please, which way I ought to go from here?'
'That depends a good deal on where you want to get to,' said the Cat.
'I don't much care where -' said Alice.
'Then it doesn't matter which way you go,' said the Cat.
'- so long as I get SOMEWHERE,' Alice added as an explanation.
'Oh, you're sure to do that,' said the Cat, 'if you only walk long enough.' as rem_text


text:
Q: Why CSS grid don't work even though my class tag was correct? I want my h2 to appear on the right of the image, but it does not work when I use grid. Please let me know if you see something not right with my code. Thank you!

body {
        display: grid;
        grid-template-areas: "header nav" "berry menu" "footer footer";
        grid-template-columns: 30% 70%;
        grid-template-rows: 200px 600px 100px;
    }

    .berry{
        grid-area: berry;
    }

    .menu{
        grid-area: menu;
    }

            Shopping Basket

Sally's Cheesecakes

Made with fresh blueberries and farm cheese from New Zealand. No added sugar cake perfect for anyone

A: In your CSS you're styling the body element instead of . Easiest mistakes may be most difficult to spot sometimes :)
Change
body {
 ...
}

To
main {
 ...
}

A: You need to redo the html structure in the same way as in my example. The grid rules will be assigned to the main tag.

main {
    display: grid;
    grid-template-areas: "header nav" "berry menu" "footer footer";
    grid-template-columns: 30% 70%;
    grid-template-rows: 200px 600px 100px;
}

header {
    grid-area: header;
}

nav {
    grid-area: nav;
}

.berry{
    grid-area: berry;
}

.menu{
    grid-area: menu;
}

footer {
    grid-area: footer;
}

Sally's Cheesecakes

        Shopping Basket

Made with fresh blueberries and farm cheese from New Zealand. No added sugar cake perfect for anyone

          footer


text:
Q: how to generate custom 403 HTTP responses in Plone (prevent redirect) Upon unauthorized access, Plone by default provides a redirect to login form. I need to prevent this for certain subpaths (ie. not globally), and instead return 403 Forbidden, with a custom (short) HTML page, after the (otherwise) normal Plone authentication & authorization has taken place.
I looked into ITraversable but using that takes place too early in the request processing chain - ie. before auth etc.
One possible yet unexplored method is having a custom view injected to URL path that performs auth checks on the object that maps to the remaining subpath. So there could be a request with URL something like http://myplone/somepath/customview/withcustom403, where:

*

*The customview view implements IPublishTraverse, and its publishTraverse() returns itself

*The same view then next validates, in its __call__ method, the access to withcustom403 object, ie. by calling getSecurityManager().validate()

*If validation fails, the view sets response to 403 and returns the custom HTML

Would this work? Or is there some event triggered after auth takes place, but before Plone calls response.Unauthorized() (triggering redirect), that would provide a cleaner solution?
This is for current Plone 4.3.4.

A: You could create a new PAS Challenge plugin based on the acl_users/credentials_cookie_auth plugin and make sure to move it to the top of the Challenge plugins in acl_users.
Or maybe use a monkey patch to change the current plugin.  For demonstration purposes only, you can edit Products/PluggableAuthService/plugins/CookieAuthHelper.py.  In the unauthorized method, you will see these lines:
url = '%s%scame_from=%s' % (url, sep, quote(came_from))
resp.redirect(url, lock=1)

Before those lines, add two lines to prevent unauthorized access to any resource that has nogo in its url:
if 'nogo' in came_from:
    return 1

If you create your own plugin, check the setupAuthPlugins function in Products/PlonePAS/Extensions/Install.py for a way to install it if you do not want to do it by hand.

A: You could override Products/CMFPlone/skins/plone_login/require_login.py and add any logic that you want there to give a custom response.
Or bypass require_login completely and use an own browser view to handle this.  In your Plone Site go to acl_users/credentials_cookie_auth/manage_propertiesForm and for the Login Form property replace require_login with your browser view name.


text:
Q: Finding out when/from where an assembly has been loaded I currently work on a HUGE C++/CLI/C# application. At some point during the runtime (not at startup) this application loads a certain .NET assembly.
By using the Modules Window in Visual Studio I can see that the assembly is initially not loaded. After some time the assembly appears in the Modules Window.
Is there an easy way to find out where/why/when the assembly has been loaded? Ideally I would like to set some sort of breakpoint, that fires when this specific assembly is being loaded. So that the application pauses and I get a proper call stack.
Is this possible without instrumenting the code (too much)?

A: You can try my Runtime Flow tool to find it out.
For example, setting Monitoring filter to Module == MyAssembly.dll will show you the first method called in the assembly and adding more modules will show who called it.


text:
Q: Rcpp find unique character vectors I am learning Rcpp from Hadley Wickham's Advance R: http://adv-r.had.co.nz/Rcpp.html.
There is one exercise to implement R function unique() in Rcpp using an unordered_set (challenge: do it in one line!). The solution finds the unique numbers in a numeric vector. I am trying to find the unique characters in a character vector using the second code chunk, which produces an error. Any idea on how to achieve this simple function manually ? Thanks!
// [[Rcpp::export]]
    std::unordered_set<double> uniqueCC(NumericVector x) {
      return std::unordered_set<double>(x.begin(), x.end());
    }

    // [[Rcpp::export]]
    std::unordered_set<String> uniqueCC(CharacterVector x) {
      return std::unordered_set<String>(x.begin(), x.end());
    }

A: For object types not in the STL library you need to define your own hash function. String (capital S) is an Rcpp object.
The easiest way to do this is to use Rcpp's ability to convert to common STL objects.
// [[Rcpp::export]]
std::unordered_set<std::string> uniqueCC(CharacterVector x) {
  auto xv = Rcpp::as<std::vector<std::string>>(x);
  return std::unordered_set<std::string>(xv.begin(), xv.end());
}

> x <- sample(letters, 1000, replace=T)
> uniqueCC(x)
 [1] "r" "o" "c" "n" "f" "s" "y" "l" "i" "j" "m" "v" "t" "p" "u" "x" "w" "k" "g" "a" "d" "q" "z" "b" "h" "e"

Alternatively, you can take in a STL string vector and Rcpp magic will do the rest:
// [[Rcpp::export]]
std::unordered_set<std::string> uniqueCC(const std::vector<std::string> & x) {
  return std::unordered_set<std::string>(x.begin(), x.end());
}


text:
Q: Why can't a class act as an enclosing space for a function in Python The Python documentation on classes says that when a class definition is entered, a new namespace is created, and used as the local scope.
Any assignments to the variables go in this local space.
Function definitions bind the name of the new function in this local scope.
Then I executed this simple piece of code in Python:
class C:
    next_serial = 1337

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.z = next_serial
        next_serial += 1

c1 = C('ABC','XYZ')
print(c1.x)
print(c1.y)
print(c1.z)

It failed with UnboundLocalError: local variable 'next_serial' referenced before assignment
Now as per the documentation Class C created a new namespace which acts as a local scope where variable next_serial is bound to int object 1337
and function init is bound to the definition of the function in the class.
Why did Python not treat this local scope as an enclosing scope for the function init?


text:
Q: Can't call java methods from c++ wrapper in JNI I'm new in JNI and c++. I have some api that required shared pointer with some handler to subscribe on some messages. I can call required method in my handler in "main" c++ method, but when I call it from c++ wrapper I get JVM error and my application crash. My native method is next:
public native int subscribe(Handler handler);

Java Handler class:
public class Handler {
public void call(String m1, String m2) {
    System.out.println("call: " + m1 + " " + m2);
}

}
JNI implementation:
JNIEXPORT jint JNICALL Java_com_lib_NativeClient_subscribe (JNIEnv* env, jobject thisObj, jobject javaHandler) {

jclass handlerClass = env->GetObjectClass(javaHandler);
jmethodID call = env->GetMethodID(handlerClass, "call", "(Ljava/lang/String;Ljava/lang/String;)V");
const std::string &message1 = "message1";
const std::string &message2 = "message2";
jstring javMessage1 = env->NewStringUTF((const char* )message1.c_str());
jstring javMessage2 = env->NewStrbingUTF((const char* )message2.c_str());
env->CallVoidMethod(javaHandler, call, javMessage1, javMessage2);

JavaWrapperHandler javaWrapperHandler = JavaWrapperHandler(env, javaHandler);
std::shared_ptr<JavaWrapperHandler> handlerSharedPointer = std::make_shared<JavaWrapperHandler>(javaWrapperHandler);

return some::lib::subscribe(handlerSharedPointer);
};

All works fine, I call 'call' method with this code. But I need to call this method after I subscribe to messages, I.e. Subject will call it. I write c++ wrapper for my java class to pass it to subscribe method:
class JavaWrapperHandler : public some::lib::Handler {
JNIEnv* env;
jobject javaHandler;
public:
JavaWrapperHandler(JNIEnv* genEnv, jobject handler) {
        env = genEnv;
       javaHandler = env->NewGlobalRef(handler);
    }

~JavaWrapperHandler() {
        env->DeleteGlobalRef(javaHandler);
}

virtual void call(const std::string &message1, const std::string &message2) {
    jclass handlerClass = env->GetObjectClass(javaHandler);
    jmethodID call = env->GetMethodID(handlerClass, "call", "(Ljava/lang/String;Ljava/lang/String;)V");  // Here I get error
    jstring javMessage1 = env->NewStringUTF((const char* )message1.c_str());
    jstring javMessage2 = env->NewStringUTF((const char* )message2.c_str());
    env->CallVoidMethod(javaHandler, call, javMessage1, javMessage2);

};
};

When Subject call 'call' method I receive JVM error:

A fatal error has been detected by the Java Runtime Environment:
SIGSEGV (0xb) at pc=0x7694d8a4, pid=5681, tid=5702
JRE version: OpenJDK Runtime Environment (Zulu11.31+16-CA) (11.0.3+7) (build 11.0.3+7-LTS)
Java VM: OpenJDK Client VM (11.0.3+7-LTS, mixed mode, serial gc, linux-arm)
Problematic frame:
V  [libjvm.so+0x3e58a4]  get_method_id(JNIEnv_, _jclass, char const*, char const*, bool, Thread*) >>[clone .isra.149]+0x288

What is wrong? Thanks in advance.

A: Just going to expand on @PaulMcKenzie 's comment.
You need to replace:
JavaWrapperHandler javaWrapperHandler = JavaWrapperHandler(env, javaHandler);
std::shared_ptr<JavaWrapperHandler> handlerSharedPointer = std::make_shared<JavaWrapperHandler>(javaWrapperHandler);

with
std::shared_ptr<JaveWrapperHandler> handlerSharedPointer = std::make_shared<JavaWrapperHandler>(env, javaHandler);

You are violating the rule of three in your definition of JavaWrapperHandler, but you can skip fixing that (since fixing it isn't straightforward with the global reference) as long as you make sure your object never appears except through a pointer reference.

A: Finally, I wrote working code. In the native method it is required to retrieve and save JVM variable (which can be shared between threads) to retrieve JNIenv (which can't be shared between threads) when it will required in another thread:
JNIEXPORT jint JNICALL Java_com_lib_NativeClient_subscribe (JNIEnv* env, jobject thisObj, jobject javaHandler) {
static JavaVM *jvm;
int status = env->GetJavaVM(&jvm);
    if(status != 0) {
        std::cout << "Failed to receive JavaVm instance" << std::endl;
    }
std::shared_ptr<JavaWrapperHandler> handlerSharedPointer =
std::make_shared<JavaWrapperHandler>(jvm, javaWrapperHandler);
return some::lib::subscribe(handlerSharedPointer);
};

Then, retrieve env where it is required. Also it required to attach current thread to vm:
    class JavaWrapperHandler : public some::lib::Handler {
JavaVM *vm;
jobject javaHandler;
public:
JavaWrapperHandler(JavaVM *gen_vm, jobject handler) {
       vm = gen_jvm;
       JNIEnv *env = nullptr;
       vm->GetEnv((void**)&env, JNI_VERSION_1_6);
       javaHandler = env->NewGlobalRef(handler);
    }

~JavaWrapperHandler() {}

virtual void call(const std::string &message1, const std::string &message2) {
        JNIEnv *env = nullptr;
        auto result = vm->GetEnv((void**)&env, JNI_VERSION_1_6);
        if (result == JNI_EDETACHED) {
                std::cout << "Thread detached." << std::endl;
                if (vm->AttachCurrentThread((void**)&env, NULL) == JNI_OK) {
                    std::cout << "Attach current thread to vm" << std::endl;
                } else {
                    std::cout << "Failed to attach thread." << std::endl;
                }
            } else if (result == JNI_EVERSION) {
            std::cout << "Unsupported JNI version." << std::endl;
            }

    jclass handlerClass = env->GetObjectClass(javaHandler);
    jmethodID call = env->GetMethodID(handlerClass, "call", "(Ljava/lang/String;Ljava/lang/String;)V");  // Here I get error
    jstring javMessage1 = env->NewStringUTF((const char* )message1.c_str());
    jstring javMessage2 = env->NewStringUTF((const char* )message2.c_str());
    env->CallVoidMethod(javaHandler, call, javMessage1, javMessage2);

};
};


text:
Q: NGINX + php7.0-fpm + phpmyadmin Disclaimer: I've tried tips listed in probably every google result on the first 2 pages. None of them worked for me. This is not a duplicate.
I'm running Debian 9 in LXC container that had LAMP installed, today I wanted to replace apache2 with php-fpm and nginx.
The problem is that I can't get this config to work at all.
The "default" virtual host is disabled (file/symlink not present in sites-enabled)
Current config (sites-enabled/phpmyadmin):
server {
    listen 127.0.0.1:80;
    root /home/fakeuser/fakepath;
    index index.php index.html index.htm index.nginx-debian.html;
    server_name _;

    location ~\.php$ {
            include snippets/fastcgi-php.conf;
            #fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /usr/share/phpmyadmin/$fastcgi_script_name;
            fastcgi_pass  unix:/run/php/php7.0-fpm-phpmyadmin.sock;
            include fastcgi_params;
    }

    location /phpmyadmin {
        alias /usr/share/phpmyadmin;

        location ~\.php$ {
            include snippets/fastcgi-php.conf;
            #fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /usr/share/phpmyadmin/$fastcgi_script_name;
            fastcgi_pass  unix:/run/php/php7.0-fpm-phpmyadmin.sock;
            include fastcgi_params;
        }
    }

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
    }
}

When I try to open:
localhost/index.php

I get index.php downloaded to my pc
when I try to open:
localhost/phpmyadmin/index.php

I get "File not found."
and this entry in
/var/log/nginx/error.log

2018/09/17 19:22:37 [error] 27804#27804: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /phpmyadmin/index.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm-phpmyadmin.sock:", host: "localhost"

UPDATE:
I've checked log of php-fpm, and it just prints this into log every time:
- -  20/Sep/2018:21:03:26 +0000 "GET /phpmyadmin/index.php" 404
I have no idea what I'm doing wrong, www-data user have access to everything in that directory, I've checked 5 times by now.

A: Looking at your configuration I'm not sure that your nginx directives fastcgi_pass and fastcgi_param are correct.
try something simpler like this:

location ~* \.php$ {
    include /etc/nginx/fastcgi.conf;
    include /etc/nginx/fastcgi_params;
    fastcgi_index index.php;
    fastcgi_pass 127.0.0.1:9000;
   }

if your php-fpm is listening on port 9000 or point it to a correct socket path (defined in fpm conf file)

Also please check it file /run/php/php7.0-fpm-phpmyadmin.sock exists. I'm under the impression that the default php7 socket path is unix:/run/php/php7.0-fpm.sock. There may be other things you need to check as php.ini. Please try to follow nginx how to section of this tutorial:  https://www.howtoforge.com/tutorial/installing-nginx-with-php7-fpm-and-mysql-on-ubuntu-16.04-lts-lemp/


text:
Q: Resolve masked/shortened URL twint is scraping from twitter I am using twint for scraping twitter profiles.
When I run this script:
    c = twint.Config()
    c.Username = username
    c.Store_object = True
    c.Store_object_users_list = users
    c.Hide_output = True
    twint.run.Lookup(c)
    try:
        userna = users[0]
    except:
        continue
    web = userna.url

I get the masked/shortened URL instead of a real one. How can I get the real url?
What would you advise?

A: Preface: This answer is based on my results and findings from evaluating UVuuMe's answer (in it's initial version).

To translate a shortened URL into the full URL it represents, you can use the package  requests which comes indirectly with twint (it's required by googletransx which is required by twint which you already installed, so there is no need for pip install requests).
Send a HEAD request, then check the response's status_code for 303, only then read the location header; there are other cases where a location will be in the response, but not in case of HTTP 200 OK.
import requests

# Short URL for a Python Requests Tutorial
short_url = 'https://youtu.be/tb8gHvYlCFs'

res = requests.head(short_url)
if res.status_code == 303: # "See Other"
    full_url = res.headers['location']
elif res.status_code == 200: # "OK"
    # let's conclude that short_url is already what we are looking for
    full_url = short_url
else:
    # replace by your error handling:
    assert(False)

A: The following works.
import requests

resp = requests.head(short_link)
resp.status_code
true_url = resp.headers["Location"]


text:
Q: How to limit the zoom of a time scale in d3.js to the minute? I have a d3v4 chart using time scale on the x axis. Everything is working fine, but when I zoom in, it never stops. Is there a way to make it stop zooming when the minute scale is reached?
d3.scaleTime().range([0, width])
...
var zoom = d3.zoom()
      .scaleExtent([1, Infinity])
      .translateExtent([[0, 0], [width, height]])
      .extent([[0, 0], [width, height]])
      .on("zoom", zoomed);

I am able to stop it from zooming if I change Infinity to some number, but the problem is that the size of the scale is different every time so the scale extent needed to reach the minute scale varies.

A: You just need to set your scaleExtent to the proper values. If "the size of the scale is different every time", just set scaleExtent using the initial domain values:
var domainStart = new Date('1/1/2017'),
    domainEnd = new Date('2/1/2017');

var scale = d3.scaleTime()
  .domain([domainStart, domainEnd])
  .range([0, width])

...

// max zoom is the ratio of the initial domain extent to the minimum
// unit that you want to zoom to (1 minute == 1000*60 milliseconds)
var zoomMax = (domainEnd.getTime() - domainStart.getTime()) / (1000*60),
    zoomMin = 1;

var zoom = d3.zoom()
  .scaleExtent([zoomMin, zoomMax])
  .translateExtent([[0, 0], [width, height]])
  .extent([[0, 0], [width, height]])
  .on("zoom", zoomed);


text:
Q: Gstreamer - display and record video using Tee element hangs My target is to stream and record video at the same time.
Gstreamer version: 1.16.1, OS: debian 11
Initially I had more complex pipeline containing compositor on one branch and different custom filters. The simplified version of my constructed pipeline is as follows:
gst-launch-1.0 videotestsrc ! "video/x-raw,width=500,height=300,framerate=50/1"  !  tee name=t \
 t. ! queue !  x264enc ! splitmuxsink name=mux_sink  max-files=10000 next-file=5 max-size-time=600000000 location=video%02d.mp4 \
 t. ! queue !  "video/x-raw,width=500,height=300,framerate=50/1"  !  glimagesink

How this pipeline acts on my system is that it starts without problems but goes from NULL state to READY state and hangs there. The displayed video is also stationary and no video file is saved.
Here is svg file generated from the dot dump null->ready state: https://drive.google.com/file/d/1oGwDufDdljbuKr8b0YURvg5VxPzMtQWb/view?usp=sharing
I have already tried both branches separately without tee element - both working. I have also tried different combinations of caps filters on both queues. I tried raising gstreamer debug level to see if there was something suspicious there - nothing.
The task should be quite straight-forward, I must be missing something here.
Thanks in advance!

A: The latency for the default x264 settings are too high for this use case. Use tune=zerolatency option for the x264enc element or increase the queue size after the tee for the display path. This will prevent deadlocking for preroll.


text:
Q: HERE API Route Calculation suddenly stopped working I am experiencing some weird and really frustrating problems with the routing service of the HERE API. It was working totally fine till yesterday, but when I tested it today it shows nothing at first and then I get the following message in the console:
https://route.ls.hereapi.com/routing/7.2/calculateroute.json?xnlp=CL_JSMv3.1.9.0&apikey=XXXXX&mode=fastest%3Bcar&waypoint0=geo!53.551084599999996%2C9.9936818&waypoint1=geo!42.14731201935119%2C24.73156194202602&representation=display&routeAttributes=summary request failed
and another 2 errors:
https://route.ls.hereapi.com/routing/7.2/calculateroute.json?xnlp=CL_JSMv3.1.9.0&apikey=Y94bXc6tWL5xKdfNAMuKVFYyixiGECdBdQozM_IFxLg&mode=fastest%3Bcar&waypoint0=geo!53.551084599999996%2C9.9936818&waypoint1=geo!42.14731201935119%2C24.73156194202602&representation=display&routeAttributes=summary 504 (GATEWAY_TIMEOUT)
Access to XMLHttpRequest at 'https://route.ls.hereapi.com/routing/7.2/calculateroute.json?xnlp=CL_JSMv3.1.9.0&apikey=Y94bXc6tWL5xKdfNAMuKVFYyixiGECdBdQozM_IFxLg&mode=fastest%3Bcar&waypoint0=geo!53.551084599999996%2C9.9936818&waypoint1=geo!42.14731201935119%2C24.73156194202602&representation=display&routeAttributes=summary' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have no idea what caused these errors. I tried out previous versions of my code, whereby I am 100% sure it was working correctly, but now it is failing there as well.
The code, related to the routing:
showRoute() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(this.displayLocationInfo, () => {
                    this.$swal({ icon: 'warning', text: 'Моля разрешете достъп до данните за локация!' })
                }, { enableHighAccuracy: true });
            }
        },
        displayLocationInfo(position) {
            const lng = position.coords.longitude;
            const lat = position.coords.latitude;

            this.$store.dispatch('setStartWaypoint', `geo!${lat},${lng}`)

            if (!this.$store.getters.getRoutingParameters['waypoint1']) {
                return this.$swal({ icon: 'warning', text: 'Моля изберете офис!' })
            }

            const routingParameters = this.$store.getters.getRoutingParameters
            const router = this.platform.getRoutingService();

            router.calculateRoute(routingParameters, this.onResult,
                function(error) {
                    console.log(error.message);
                });
        },
onResult(result) {
        if (Object.keys(this.map.getObjects()).length > 0) {
            for (let object of this.map.getObjects()){
                if (object.id === 'route'){
                        this.map.removeObject(object);
                }
            }
        }
        var route,
        routeShape,
        startPoint,
        endPoint,
        linestring;
        if(result.response.route) {
            route = result.response.route[0];
            routeShape = route.shape;
            linestring = new H.geo.LineString();

            if (route.summary.distance < 1000) {
                this.distance = route.summary.distance + ' м'
            } else {
                this.distance = (route.summary.distance / 1000).toFixed(2) + ' км'
            }

            routeShape.forEach(function(point) {
                const parts = point.split(',');
                linestring.pushLatLngAlt(parts[0], parts[1]);
            });

            startPoint = route.waypoint[0].mappedPosition;
            endPoint = route.waypoint[1].mappedPosition;

            const routeOutline = new H.map.Polyline(linestring, {
                style: {
                    lineWidth: 6,
                    strokeColor: 'rgba(8, 48, 69, 0.5)',
                    lineTailCap: 'arrow-tail',
                    lineHeadCap: 'arrow-head'
                }
            });

            const routeArrows = new H.map.Polyline(linestring, {
                style: {
                    lineWidth: 6,
                    fillColor: 'white',
                    strokeColor: 'rgba(255,255,255,1)',
                    lineDash: [0, 2],
                    lineTailCap: 'arrow-tail',
                    lineHeadCap: 'arrow-head'
                }
            });

            const routeLine = new H.map.Group();
            routeLine.id = 'route'
            routeLine.addObjects([routeOutline, routeArrows]);

            const startMarkerIcon = new H.map.Icon(require('../assets/marker.svg'), {
                size: {
                    w: 42,
                    h: 60
                }
            })

            const startMarker = new H.map.Marker({
                lat: startPoint.latitude,
                lng: startPoint.longitude
            }, { icon: startMarkerIcon });

            const endMarker = new H.map.Circle({
                lat: endPoint.latitude,
                lng: endPoint.longitude
            }, 6);

            endMarker.setStyle({
                strokeColor: 'white',
                fillColor: 'rgba(8, 48, 69, 0.5)',
                lineWidth: 2
            })

            startMarker.id = 'route'
            endMarker.id = 'route'

            this.map.addObjects([routeLine, startMarker, endMarker]);

            this.map.getViewModel().setLookAtData({bounds: routeLine.getBoundingBox()});
        }
    },

A: I had the same issue.
It just started to work again right now... Maybe someone of here staff could tell us what was wrong?


text:
Q: asp.net page's preinit event I am new to asp.net. I have an aspx page and i have to write some code in its PreInit event.
From where i find PreInit event on the page.
As we double click on button to get button click event(or selecting button and select event from property pane)
Plz reply me ASAP.

A: Man, why do you need the mouse?
If you need to write some code into PreInit just write the code:
protected virtual void OnPreInit(EventArgs e)
{
   base.OnPreInit(e);
   //your code
}

or in class constructor add a event handler for it:
...
PreInit += new EventHandler(SomeMethodName)
...

and define the event handler method
private void SomeMethodName(object sender, EventArgs e)
{
   //your code
}

And by the way, check a .Net Framework book and a Visual Studio manual.

A: You need to do some reading:
http://msdn.microsoft.com/en-us/library/ms178472.aspx#lifecycle_events


text:
Q: How to find and change keyboard shortcuts effectively in TeXStudio This question is based on a misunderstanding due to a bug in TeXStudio: There should be a warning when you use a key-combination that has already been used. However, this warning may be absent when for some reason two different parameterizations of the same key are detected. This happens for example for CTRL+SHIFT+^ vs CTRL+SHIFT+6. Make sure to use the latter form by typing it in by hand (rather than the automatical detection which strangely does not result in the format used by the rest of TeXStudio). (See my answer for more details.)

When I wanted to change some keyboard shortkeys in TeXStudio I ran into some trouble. I started changing some shortcuts to combinations that I liked, hoping/thinking that if I would use a combination that was already in use TeXStudio would warn me what other key already uses that combination. It seems that TeXStudio has no such check leading to problems with combinations that are used multiple times. In addition it seems that TeXStudio has no way to search through the shortcuts by key combinations. Since there are thousands of shortcuts it would take forever to find the doubles. Did I overlook a way to search by key combination? Is there some other solution?

I am interested in finding the actions the key bindings had been bound to by default in order to remove those (not my new ones) so that I can replace them with my own.

A: As you have noticed

TeXStudio would warn me what other key already uses that combination.

So now we have numerous problems and you could simply delete the ini file, thus loosing ALL customisation including all the key changes. That would be the best advise to give when someone has ignored all the previous warnings. However:-
You know you can change each key back to its default, one by one like this.

Knowing they are stored in the TeXstudio.ini file like this

The simplest bulk solution WITHOUT TeXstudio active (otherwise it will save the unwanted customisation again), is to simply delete all those rogue entries keeping as few as is possible.

A: Firstly, there actually is a warning system when you assign a key combination twice. What happened here is that I assigned a new binding by pressing the key combination. But for keys involving shift there are two interpretations for every key combination. In my case it detected CTRL+SHIFT+^. This combination was free and so no warning was given. However the combination CTRL+SHIFT+6 was taken by Toggle Bookmark. Of course this combination actually corresponds to the same keys, but it appears that in the option menu one interpretation is used, while in the editor the other is used. The solution is to set the key combination in the menu more carefully by hand (not by pressing the buttons) to the combination where the default symbol (not the top one, activated by shift) is used.
So there is no need to search the existing bindings by key combination. One can just try a desired combination and if it is already in use you will receive a warning.


text:
Q: Required bits to communicate a partial order? Suppose that you have a ranking (i.e. a strict complete partial order) over $n$ different objects, so that the objects can be ordered as $a>b>\cdots>n$. You want to communicate the exact order you have to a outside server. The question is how many bites do you need to do it? We are interested in the minimal number of bits that the task requires.
My initial guess is that you need $\frac{n(n-1)}{2}$ bites to transfer the information, because the partial order is equivalent to pairwise comparison among all the elements of ${1,...,n}$. One can verify that there are exactly $\frac{n(n-1)}{2}$ such binary relations.
Yet a recent paper claims that the partial order can be transmited in $\log_2(n!)$ bits. I understand that this follows from Shannon's entropy, but I just can't see the precise way to allocate the binary digits to express the ranking. Any ideas or explanations?
Intuitive answers are very welcome. Thanks,

A: Assuming that the ranking is strict and linear, transmitting it amounts to transmitting a permutation $\sigma$ of $[n]=\{1,2,\ldots,n\}$. For $k,\ell\in[n]$ write $k\prec\ell$ if and only if $k$ precedes $\ell$ in $\sigma$. For each $k\in[n]$ let
$$p(k)=|\{\ell\in[n]:\ell<k\text{ and }\ell\prec k\}|\;;$$
$0\le p(k)\le k-1$. The number $p(k)$ specifies where $k$ must be inserted amongst the numbers $\{1,\ldots,k-1\}$, so $\sigma$ can be reconstructed from the sequence $\langle p(2),p(3),\ldots,p(n)\rangle$, which can be expressed in
$$\sum_{k=2}^n\lceil\lg k\rceil\approx\lg(n!)$$
bits.

A: This is at best a partial answer.
For a general finite partially ordered set (i.e. a partial order that is not necessarily a total order), I can think of two things that would reduce the amount of information that would need to be sent.
The first is to collapse "similar" elements into a single element.  By similar elements, I mean that they are covered by the same set of elements and they cover the same set of elements (this means that an element is similar to itself).  For each element $a$, find the set $A$ of similar elements to $a$, then collapse $A$ into a single element.  This produces a new "reduced" poset where each element is similar to itself, and no others.
The next thing to do is to decompose the reduced poset into chains (another name for total order).  Dilworth's Theorem may be of some use here.
Then, instead of sending all pairs in the partial order, send the chains in order (as a list of lists, for example), and for each element $a$ of the reduced poset that was produced by collapsing at least 2 elements from the original poset, send the list of similar elements $a_1,\ldots,a_k$.
I don't know how close this gets you to $\log_2 n!$, though.
Actually, I almost see it for a total order.  There are $n$ elements in total.  $\log_2n$ bits are needed to encode each element. Therefore, a list containing $n$ elements will require $n\log_2n$ bits.  I don't know how to get $\log_2n!$ exactly, but I believe that $\log n!=O(n\log n)$ (see, for example, Why is $\log(n!)$ $O(n\log n)$?)


text:
Q: cURL GET topspin API - PHP I'm trying to interact with the topspin API in PHP.
On their website:
curl --data "auth_token=abc123&email=test@example.com&account_id=1&
acquired_by=curltest" http://api.artistlink.com/home/fans.json

How to do I do this in PHP?
I've tried something like this:
$str= "?auth_token=blah&email=blah@blah.com&account_id=1&
acquired_by=curltest";

$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,'http://api.artistlink.com/home/fans.json'.$str);      curl_exec($ch);
curl_close($ch);

But I get this:

What's going on?

A: You need to use CURLOPT_POSTFIELDS. Try this:
<?php
    $ch = curl_init('http://api.artistlink.com/home/fans.json');
    $data = "auth_token=blah&email=blah@blah.com&account_id=1&acquired_by=curltest";
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_exec($ch);
    curl_close($ch);
?>

Check out some more information here.

A: You are using HTTP_GET instead of HTTP_POST Try:
$str = "auth_token=blah&email=blah@blah.com&account_id=1&acquired_by=curltest";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.artistlink.com/home/fans.json');
curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);

$json = json_decode($data);
if (isset($json->error)) {
    echo $json->error;
} else {
    print_r($json);
}


text:
Q: pgfplots: 3D Axes System. Reverse xlabel
*

*This question is about a 3D coordinate system in pgfplots.

*Problem 1: I want to have the xlabel on the "other side" (tried x dir = reverse, already).

*Problem 2: This is less important (nice to have). I want to have the perspective as in my hand drawing (a perfect cross: y and z, and the 3rd dimension, depth, is indicated by a 45 degree line: x), see "Remark" in the hand drawing. Additional Remark: In the hand drawing I use different labels (this is a typical automotive coordinate system). But I can fake that by just naming the xlabel "y" and so on.

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[
        width = 80mm,
        height = 80mm,
        axis lines = center,
        no marks,
        axis line style = {latex-latex, ultra thick}, %
        unit vector ratio = 1 1 1,
        ticks = none,
        xmin = -1,
        xmax = 1,
        ymin = -1,
        ymax = 1,
        zmin = -1,
        zmax = 1,
        xlabel = $x$,
        ylabel = $y$,
        zlabel = $z$,
    ]
    % No plot
    \end{axis}
\end{tikzpicture}

\end{document}

Related

*

*pgfplots: `x dir = reverse` --> Problem with x-label (`xlabel`) placement

A: For you first request you can use x dir=reverse swap the position of xmin and xmax.  However, this does not move the xlabel.  Here you can use
every axis x label/.style={at=(ticklabel cs:-0.07)}

The ticklabel cs: starts at 0 at one end of the axis and ends at 1 at the other, so 0.07 puts the label just beyond the "beginning" of the axis.  Putting this together, and adding a plot that shows the positive first quadrant for x and y, and using the same idea to adjust the ylabel, we get

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[
        width = 80mm,
        height = 80mm,
        axis lines = center,
        no marks,
        axis line style = {latex-latex, ultra thick}, %
        unit vector ratio = 1 1 1,
        ticks = none,
        xmin = -1,
        xmax = 1,
        ymin = -1,
        ymax = 1,
        zmin = -1,
        zmax = 1,
        x dir=reverse,
        every axis x label/.style={at={(xticklabel cs:-0.07)}},
        every axis y label/.style={at={(yticklabel cs:1.07)}},
        xlabel = $x$,
        ylabel = $y$,
        zlabel = $z$,
    ]
    \addplot3 [surf, z buffer=sort, samples=15, variable=\u,
    variable y=\v, domain=0:1, y domain=0:1, opacity=0.5]
    ({u},{v},0);
    \end{axis}
\end{tikzpicture}

\end{document}

Unfortuantely pgfplots does not support perspective drawing.


text:
Q: Is there a Scala equivalent to Python's list comprehension? I'm translating some of my Python code to Scala, and I was wondering if there's an equivalent to Python's list-comprehension:
[x for x in list if x!=somevalue]

Essentially I'm trying to remove certain elements from the list if it matches.

A: The closest analogue to a Python list comprehension would be
for (x <- list if x != somevalue) yield x

But since you're what you're doing is filtering, you might as well just use the filter method
list.filter(_ != somevalue)

or
list.filterNot(_ == somevalue)


text:
Q: ¿Cómo puedo poner una imagen de fondo tamaño completo en un div usando una URL? A continuación esta mi código html, tengo un
, un
 y un carrusel en bootstrap.

                Previous

                Next

Todo esta bien hasta que deseo implementar una imagen de fondo en mi div con clase "main" en la siguiente imagen se muestran inspeccionados los elementos.

El color naranja claro es el
 el siguiente es el
 que contiene el carrusel en bootstrap, deseo poner una imagen muy colorida de fondo para poder visualizarla detrás pero no logro que aparezca y he intentado de muchas maneras pero no logro hacerlo, lo único que logro poner es un color pero no una imagen, mi codigo css es el siguiente:
.main {

    background-image: url(assets/images/fondo1.jpg);
}

También intenté con una imagen web y logré colocarla pero solo en tipo mosaico y deseo que se muestre completa una sola imagen utilice este código.
    .main {

    background-image: url("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSg3O0NE7UMpDZghidkYpLmmE0Z8bleQbiI4ZkrxMa0rDzpYUHE");
}

Pero se visualiza así.

¿Puedo centrar o ampliar esta imagen para que aparezca en su totalidad en el div sin repetirse o simplemente aparecer la imagen de mis archivos locales igual sin repetirse? Cualquiera de las dos opciones me servirían.

A: Intenta usando el style en el HTML en lugar aplicarlo en CSS [más ejemplos aquí].1
Intenta agregando esto a tu clase
class="carousel-inner" style="background: url(https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSg3O0NE7UMpDZghidkYpLmmE0Z8bleQbiI4ZkrxMa0rDzpYUHE) no-repeat left center; background-size: cover;"

A: Alejandro, en corto, puesto que se trata de un elemento 'full resposive', para darle solución hay que implementar, vía Jquery, (1) una función de ajuste de la altura  en base a el ancho de slider; (2) trabajar con los eventos 'slide.bs.carousel' –que es el inicio del cambio de imagen en el slider- y 'slid.bs.carousel' –que se sucede al final del cambio- ; (3) e implementar una función de escalamiento de imagen, de acuerdo a las dimensiones del div padre y de la imagen en cuestión.
En largo.
1-. Una función que "deduzca", en base al ancho del div padre de la imagen, la altura del mismo. Conseguido lo anterior,  hay 'amarrar' esas dimensiones, para que (cuando llegue la imagen, sin importar el tamaño de la misma) el slider no varíe su altura.
Esta última función hay que incorporarla al evento resize --'$(window).on('resize', functon(){.... --  para que el slider permanezca 'full reponsive'.
    var $parentImgW = ' '
    var $parentImgH = ' ';
    var $myCarousel = $('#myCarousel')
    var $carouseItems =  $('.item');
    function $F_getAdjustImagesParents(){
        $parentImgW = $myCarousel.width(); // A
        $parentImgH =  ($parentImgW*9)/16; // B
        $carouseItems.height($parentImgH+'px').css('max-height',$parentImgH+'px'); //C
        console.log('$parentImgW ====> '+$parentImgW);
        console.log('$parentImgH ====> '+$parentImgH)
    };
   $F_getAdjustImagesParents();

    $(window).on('resize',function(){  // D
        $F_getAdjustImagesParents();
    });

2-. En el evento eventos 'slide.bs.carousel' –que es el inicio del cambio de imagen en el slider, como antes dijimos- vamos a obtener el número de 'slide' que va a entrar, el cual nos va a servir para, una vez que haya terminado la transición de la imagen –evento 'slid.bs.carousel'-, saber de  cuál imagen se van a obtener las dimensiones originales.
    $myCarousel.on('slide.bs.carousel', function(event) {// Start the slide's change process
          var $slideNum = $("#"+event.relatedTarget.id).data('slide_num'); // F
          console.log('$lideNum ====> '+$slideNum)
          $myCarousel.on('slid.bs.carousel', function(event) {//end Start the slide's change process
            var $imgW = $('#myCarouselSlideImage'+$slideNum).width(); //G
            var $imgH = $('#myCarouselSlideImage'+$slideNum).height(); //G
            console.log('$imgW ====> '+$imgW);
            console.log('$imgH ====> '+$imgH); ......

3-. Una vez que se tienen las dimisiones tanto del div padre como de la imagen, entonces ya podemos utilizar la función de escalamiento de imagen.
       ....
        var $result = '';
        $result = ScaleImage($imgW, $imgH, $parentImgW, $parentImgH, true); //H
        console.log('$result.width ====> '+$result.width);
        console.log('$result.height ====> '+$result.height);
        console.log('$result.targetleft ====> '+$result.targetleft);
        console.log('$result.targettop ====> '+$result.targettop);
        $('#myCarouselSlideImage'+$slideNum).animate({ // I
                                                  width:$result.width+'px',
                                                  height:$result.height+'px',
                                                  left:$result.targetleft+'px',
                                                  top:$result.targettop+'px'      },
                                                                300);
      });
   });

function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {

    var result = { width: 0, height: 0, fScaleToTargetWidth: true };

    if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
        return result;
    }

    // scale to the target width
    var scaleX1 = targetwidth;
    var scaleY1 = (srcheight * targetwidth) / srcwidth;

    // scale to the target height
    var scaleX2 = (srcwidth * targetheight) / srcheight;
    var scaleY2 = targetheight;

    // now figure out which one we should use
    var fScaleOnWidth = (scaleX2 > targetwidth);
    if (fScaleOnWidth) {
        fScaleOnWidth = fLetterBox;
    }
    else {
       fScaleOnWidth = !fLetterBox;
    }

    if (fScaleOnWidth) {
        result.width = Math.floor(scaleX1);
        result.height = Math.floor(scaleY1);
        result.fScaleToTargetWidth = true;
    }
    else {
        result.width = Math.floor(scaleX2);
        result.height = Math.floor(scaleY2);
        result.fScaleToTargetWidth = false;
    }
    result.targetleft = Math.floor((targetwidth - result.width) / 2);
    result.targettop = Math.floor((targetheight - result.height) / 2);

    return result;
}

Es necesario mencionar que para que todo esto funcione, hay que ajustar el parámetro de posición de la imagen a  absoluto; y esto se debe hacer en Jquery, debido a que  si se hace desde Css el slider no se desplegará correctamente.
    $('.myCarouselImgs').css('position','absolute'); // E

Puedes ver lo anterior funcionando en: https://jsfiddle.net/omarlin25/nd90r1ht/59/
Nota1: Lo anterior, fue una repuesta elaborada para una pregunta similar en la versión anglo. Puedes verla Aquí.
Nota2. La fuente, y explicación, de la función de escalamiento de imagen proviene de Aquí.

A: Sucede por que Bootstrap te lo impide ya que por la jerarquía del CSS los estilos de Bootstrap se toman primero. Lo que debes hacer es usar !important en tu CSS y este será tomado.
.main {
  background-image: url(assets/images/fondo1.jpg) !important;
  background-repeat: no-repeat !important;
  background-size: cover !important;
}

El background-repeat: no-repeat; evita el mosaico y el background-size: cover; obliga a la imagen a abarcar todo el espacio. Sino quieres esto, y solo quieres una imagen, centrada que no se repita ni abarque todo el espacio utiliza:
.main {
  background-repeat: no-repeat !important;
  background-position: top center !important;
}

O si quieres que solo se repita en Y:
background-repeat: repeat-y !important;

Espero te sirva, saludos.

A: no estás tan mal...
quizás estás indicando mal la ruta.
intenta:
.main {

    background-image: url(../assets/images/fondo1.jpg);
    background-size: 100%;
}

o quizás la ruta es ../images/fondo1.jpg pero dependerá de tu distribución


text:
Q: How to retrieve data hierarchically using JPA with many to many join to same table I have a table(tbl_versions) consisting some versions. And relation between versions are like parent and child. so I put relations in another table(tbl_relations) which has two records (parent_id,child_id) and it has many to many relation with tbl_versions. I want to retrieve data as tree model and at the end have a json file which is in tree model. Any suggestion for how can I select and retrieve with JPQL?

A: Hierarchical queries are not easy to implement. Generally speaking, writing native SQL is the most powerful way to create a query because by end of the day, JPQL, HQL or whatever will be translated to the native SQL and sent to the Database. Then if you could not write your query (I mean with just one go) with SQL then you would not find a way to write it by JPQL.
But getting back to your concrete issue, databases like Oracle providing mechanism like start with connect by which is not supported by JPQL because the other databases like MySQL don't support that.
My suggestion, in this case, is using one more column to hold hierarchy between records. That column works just as a metadata holder which describes not only the parent-child relationship between two records but also has information about current record's ancestors.


text:
Q: How do facebook update content when somebody has posted something I'm really interested on how facebook loads only content when someone else has posted something. The only thing that I can think of is using something like the one below to constantly update the page without reloading the page.
setInterval(ajax_stuff, 1000);

I was watching the console and indeed the request occurs and another new content is added to the page.

I want to be enlightened on how is this done. It would really be awesome if I can use this on a project. I mean doing setInterval every second really consumes much resource. Making a request only when its needed would be the best way to do things. Specifically I want to use it on this project:
https://github.com/anchetaWern/ChatRo
It's basically just a chat box, currently it still uses the setInterval(). I want to update only the  content when someone else on the chat session has actually entered something.

A: I cannot speak directly to how FaceBook does this, but in general, you should be looking at WebSockets.
WebSockets allow the JavaScript on your page to maintain an open connection with a server whereby you can push data out in near-realtime to all of the clients connected to the server.
Take a look at http://pusher.com
Also, google Web Sockets.

A: If you're looking for something on your own (non-Windows) server to the end user then also check out the APE project. It is OpenSource using SSJS using comet.
Note that it still uses Apache and your normal LAMP set-up so no need to get a dedicated machine or VPS to host it on.
I also don't know how Facebook does it but APE does sound like a good option.
I only found this with a minute or so of Googling as your question got me interested, I haven't used or tested it but as a free tool that is on your own server it definitely is worth looking at.
Also as a note, I did find a comment in Portuguese that complains that it doesn't work with Windows servers, this is specified in the documentation.
Good luck and I would be interested in how it goes if you decide to give it a shot!


text:
Q: Listing, counting factors of unique Mongo DB values over all keys I'm preparing a descriptive "schema" (quelle horreur) for a MongoDB I've been working with.
I used the excellent variety.js to create a list of all keys and show coverage of each key.  However, in cases where the values corresponding to the keys have a small set of values, I'd like to be able to list the entire set as "available values."  In R, I'd be thinking of these as the "factors" for the categorical variable, ie, gender : ["M", "F"].
I know I could just use R + RMongo, query each variable, and basically do the same procedure I would to create a histogram, but I'd like to know the proper Mongo.query()/javascript/Map,Reduce way to approach this.  I understand the db.collection.aggregate() functions are designed for exactly this.
Before asking this, I referenced:

*

*http://docs.mongodb.org/manual/reference/aggregation/

*http://docs.mongodb.org/manual/reference/method/db.collection.distinct/

*How to query for distinct results in mongodb with python?

*Get a list of all unique tags in mongodb

*http://cookbook.mongodb.org/patterns/count_tags/
But can't quite get the pipeline order right.  So, for example, if I have documents like these:
{_id : 1, "key1" : "value1", "key2": "value3"}
{_id : 2, "key1" : "value2", "key2": "value3"}

I'd like to return something like:
{"key1" : ["value1", "value2"]}
{"key2" : ["value3"]}

Or better, with counts:
{"key1" : ["value1" : 1, "value2" : 1]}
{"key2" : ["value3" : 2]}

I recognize one problem with doing this will be any values that have a wide range of different values---so, text fields, or continuous variables.  Ideally, if there were more than x different possible values, it would be nice to truncate, say to no more than 20 unique values.  If I find it's actually more, I'd query that variable directly.
Is this something like:
db.collection.aggregate(
   {$limit: 20,
    $group: {
        _id: "$??varname",
        count: {$sum: 1}
   }})

First, how can I reference ??varname? for the name of each key?
I saw this link which had 95% of it:
Binning and tabulate (unique/count) in Mongo
with...
input data:

{ "_id" : 1, "age" : 22.34, "gender" : "f" }
{ "_id" : 2, "age" : 23.9, "gender" : "f" }
{ "_id" : 3, "age" : 27.4, "gender" : "f" }
{ "_id" : 4, "age" : 26.9, "gender" : "m" }
{ "_id" : 5, "age" : 26, "gender" : "m" }

This script:
db.collection.aggregate(
   {$project: {gender:1}},
   {$group: {
        _id: "$gender",
        count: {$sum: 1}
   }})

Produces:
{"result" :
   [
     {"_id" : "m", "count" : 2},
     {"_id" : "f", "count" : 3}
   ],
   "ok" : 1
}

But what I don't understand is how could I do this generically for an unknown number/name of keys with a potentially large number of return values?  This sample knows the key name is gender, and that the response set will be small (2 values).

A: If you already ran a script that outputs the names of all keys in the collection, you can generate your aggregation framework pipeline dynamically.  What that means is either extending the variety.js type script or just writing your own.
Here is what it might look like in JS if passed an array called "keys" which has several non-"_id" named fields (I'm assuming top level fields and that you don't care about arrays, embedded documents, etc).
keys = ["key1", "key2"];
group = { "$group" : { "_id" : null } } ;
keys.forEach( function(f) {
     group["$group"][f+"List"] = { "$addToSet" : "$" + f };  } );
db.collection.aggregate(group);
{
    "result" : [
        {
            "_id" : null,
            "key1List" : [
                "value2",
                "value1"
            ],
            "key2List" : [
                "value3"
            ]
        }
    ],
    "ok" : 1
}


text:
Q: Matplotlib, plotting multiple individual hline on barplot from a pandas dataframe I have a simple pandas dataframe and plot like the following:
import pandas as pd
import matplotlib.pyplot
import numpy as np

test_df_1 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))
test_df_1.plot(kind='bar')

This results in the following plot:

I then have another dataframe:
test_df_2 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))

Which is the same dimensions as my first dataframe. I wish to plot over the top as simple horizontal lines, like the following mock up:

How do I achieve this? I know of axhline but I don't know how I can apply it in this instance to achieve what I want.

A: I can't think a better method, but you can get the information of the bars from ax.patches:
import pandas as pd
import matplotlib.pyplot
import numpy as np

test_df_1 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))
ax = test_df_1.plot(kind='bar')
test_df_2 = pd.DataFrame(np.random.random_integers(100, size=(10,2)), columns = ['COL_A', 'COL_B'], index=list('abcdefghij'))

x = np.array([r.get_x() for r in ax.patches])
w = np.array([r.get_width() for r in ax.patches])

ax.hlines(test_df_2.values.T.ravel(), x, x + w, color="red", lw=2)

Here is the output:


text:
Q: Hibernate/JPA Bidirectional cascade saveOrUpdate I am trying to have a many-to-many bidirectional relationship for 2 entities (News and Tag).
But when I try to saveOrUpdate the News (which has Set), somehow it always saves a new set of Tag even id is already populated in the Tag
Is it something wrong with my annotation?
News.java
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "NEWS_ID")
    public Long getId() {
        return id;
    }

    @ManyToMany(fetch = FetchType.LAZY,  cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @Cascade( org.hibernate.annotations.CascadeType.SAVE_UPDATE )
    @JoinTable(name = "NEWS_TAGS", joinColumns = @JoinColumn(name = "NEWS_ID"), inverseJoinColumns = @JoinColumn(name = "TAG_ID"))
    public Set<Tag> getTags() {
        return tags;
    }

Tag.java
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "TAG_ID")
    public Long getId() {
        return id;
    }

    private Collection<News> news;

    @JsonIgnore
    @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "tags")
    public Collection<News> getNews() {
        return news;
    }

NewsDAO
public void save(News news){
         this.hibernateSessionFactory.getCurrentSession().saveOrUpdate(news);
    }

What I want to do is when, I save "News", the related Set will be ignored if Tag exist, and will insert new if Tag isn't, is this possible?
Please advise

A: The problem is that your object (Tag) is not "connected". By that I mean hibernate is not aware of your object and, when you try to save News, hibernate will see your Tags as new Objects always. Try get the Tag object from db before save or update and use this object.


text:
Q: Problem with centering my popup Updated with whole popup code
//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var cid;
var hname;
var cname;
var cfname;
var ctstamp;

var popupCompareStatus = 0;

//loading popup with jQuery magic!
function loadComparePopup(){
//loads popup only if it is disabled
if(popupCompareStatus==0){
    $("#compareBackgroundPopup").css({
        "opacity": "0.7"
    });
    $("#compareBackgroundPopup").fadeIn("slow");
    $("#popupCompare").fadeIn("slow");
    popupCompareStatus = 1;
}
}

//disabling popup with jQuery magic!
function disableComparePopup(){
//disables popup only if it is enabled
if(popupCompareStatus==1){
    $("#compareBackgroundPopup").fadeOut("slow");
    $("#popupCompare").fadeOut("slow");
    popupCompareStatus = 0;
}
}

//centering popup
function centerComparePopup(){
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popupCompare").height();
var popupWidth = $("#popupCompare").width();
console.info("windowWidth="+windowWidth+", windowHeight="+windowHeight+"popupWidth="+popupWidth+", popupHeight="+popupHeight);

$("#popupCompare").css({
    position: "absolute",
    width: "800px",
    top: $(window).height()/2 - $("#popupCompare").outerHeight()/2,
    left: $(window).width()/2 - $("#popupCompare").outerWidth()/2
});

$("#compareBackgroundPopup").css("height", $(window).height());
}
var dummy1='<list>  <TagResult elementname="osname" subCategory="system" value1="Linux" value2="HP-US1000" isEqual="false"/>  <TagResult elementname="hostname" subCategory="system" value1="estilo" value2="benz" isEqual="false"/>  <TagResult elementname="release" subCategory="system" value1="2.6.18-128.el5" value2="B.11.23" isEqual="false"/><TagResult elementname="version" subCategory="system" value1="Red Hat Enterprise Linux Server release 5.3 (Tikanga)" value2="U" isEqual="false"/>  <TagResult elementname="machine" subCategory="system" value1="x86_64" value2="ia64 hp server rx2600" isEqual="false"/>  <TagResult elementname="bitmode" subCategory="system" value1="64" value2="64" isEqual="true"/>  <TagResult elementname="numberofcpu" subCategory="system" value1="4" value2="2" isEqual="false"/>  <TagResult elementname="cpuspeed" subCategory="system" value1=" 1862.890" value2="1400" isEqual="false"/>  <TagResult elementname="maxfilesperproc" subCategory="system" value1="32" value2=" 32" isEqual="true"/>  <TagResult elementname="maxthreadsperproc" subCategory="system" value1="2000000" value2="                    256  " isEqual="false"/><TagResult elementname="mempagesize" subCategory="system" value1="4096" value2="4096" isEqual="true"/><TagResult elementname="ssaname3webserviceserver" subCategory="product" value1="ssasvck> Attempt 1 at server 'null:-1'ssasvck> Server'null:-1' is down" value2="ssasvck> Attempt 1 at server 'null:-1'ssasvck> Server 'null:-1' is down" isEqual="true"/><TagResult elementname="TERM" subCategory="envVariable" value1="xterm " value2="xterm" isEqual="true"/><TagResult elementname="JAVA_HOME" subCategory="envVariable" value1="/home/hqusers1/IIR_1152825121_estilo_9.0.1SP2_32 " isEqual="false"/><TagResult elementname="SSANUL" subCategory="envVariable" value1="/dev/null " value2="/dev/null" isEqual="true"/><TagResult elementname="SSA_LIHOST" subCategory="envVariable" value1="estilo:45682 " value2="benz:7660" isEqual="false"/><TagResult elementname="SSH_CLIENT" subCategory="envVariable" value1="10.65.6.131 4760 22 " value2="10.65.241.204 367222" isEqual="false"/></list>';

$('#compareTable a').live('click', function() {
var elementId=$(this).attr("id");
showHiddenTr(elementId);
});
function showHiddenTr(eid)
{
if($(".differentEnvironmentHiddentr").is(':visible'))
{
    $(".differentEnvironmentHiddentr").hide();
}
else
{
    $(".differentEnvironmentHiddentr").show();
}
}

function populateCompare(cmp)
{
var mytr = new Array();
var mytrs="";
var i=0;
var xml=dummy1;
$('#compareContent').empty();
$('#compareContent').html("

Compare details being loaded

");
if(cmp=="all")
{

    $(xml).find('TagResult').each(function(){
        if($(this).attr("isEqual")=="false")
        {
            mytr[i]='
'+
            ''+$(this).attr("elementname")+'	'+
            ''+$(this).attr("value1")+'	'+
            ''+$(this).attr("value2")+'	'+
            '
';
            mytrs+=mytr[i++];
        }
        else
        {
            mytr[i]='
'+
            ''+$(this).attr("elementname")+'	'+
            ''+$(this).attr("value1")+'	'+
            ''+$(this).attr("value2")+'	'+
            '
';
            mytrs+=mytr[i++];
        }

    });

    $('#compareContent').empty();
    $('
')
    .html('
'+
            '

'+
                'Name	'+
                'Config1	'+
                'Config2	'+
            '

'+mytrs

        +'

')
    .appendTo('#compareContent');

}
if(cmp=="diff")
{
    var env=0;
    $(xml).find('TagResult').each(function(){

        if($(this).attr("isEqual")=="false")
        {
            if($(this).attr("subCategory")=="envVariable")
            {
                if(env==0)
                {
                    mytr[i]='
'+
                    ''+$(this).attr("subCategory")+'	'+
                    '	'+
                    '	'+
                    '
';
                    mytrs+=mytr[i++];
                    mytr[i]='
'+
                    '  '+$(this).attr("elementname")+'	'+
                    ''+$(this).attr("value1")+'	'+
                    ''+$(this).attr("value2")+'	'+
                    '
';
                    mytrs+=mytr[i++];
                    env=1;
                }
                else
                {

                    mytr[i]='
'+
                    '  '+$(this).attr("elementname")+'	'+
                    ''+$(this).attr("value1")+'	'+
                    ''+$(this).attr("value2")+'	'+
                    '
';
                    mytrs+=mytr[i++];
                }
            }
            else
            {
                mytr[i]='
'+
                ''+$(this).attr("elementname")+'	'+
                ''+$(this).attr("value1")+'	'+
                ''+$(this).attr("value2")+'	'+
                '
';
                mytrs+=mytr[i++];
            }

        }

    });

    $('#compareContent').empty();
    $('
')
    .html('
'+
            '

'+
                'Name	'+
                'Config1	'+
                'Config2	'+
            '

'+mytrs

        +'

')
    .appendTo('#compareContent');

}
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){

//LOADING POPUP

$("#btnCompare").click(function(event){
    var count=getCheckedCount();
    if(count==2)
    {
        //show compare
        populateCompare("all");
        //centering with css
        centerComparePopup();
        //load popup
        loadComparePopup();
        //get configs

    }
    else if(count>2)
    {
        $("#messageBox").empty();
        $('')
        .html('To compare select only two configurations')
        .appendTo('#messageBox');

        $("#messageBox").fadeIn().delay(2000).fadeOut('slow');
    }
    else
    {
        $("#messageBox").empty();
        $('')
        .html('Please select two configurations to compare')
        .appendTo('#messageBox');

        $("#messageBox").fadeIn().delay(2000).fadeOut('slow');
    }
});

$('#compareForm input:radio').click(function() {
        populateCompare($(this).val());
  });

//CLOSING POPUP
//Click the x event!
$("#popupCompareClose").click(function(){
    disableComparePopup();
});
//Click out event!
$("#compareBackgroundPopup").click(function(){
    disableComparePopup();
});
//Press Escape event!
$(document).keypress(function(e){
    if(e.keyCode==27 && popupCompareStatus==1){
        disableComparePopup();
    }
});

});

Here is the screen shot you asked for

A: is there any image inside popup, as resizing popup width would result in resized width of image and eventually resized image height
-----Edit----
one thing you may do add this css to popup
.myPopUp
{
 height: whatever_you_like;
 overflow-y: auto;
}

now if height exceeds the height a scroll will appear, i hope this solves the issua

A: I think, you should add css style for #popupCompare before getting its height and width.

A: try this:
$("#popupCompare").css({
    position: "absolute",
    width: "80%",
    top: $(window).height()/2 - $("#popupCompare").outerHeight()/2,
    left: $(window).width()/2 - $("#popupCompare").outerWidth()/2
});

$("#compareBackgroundPopup").css("height", $(window).height());

A: Abhishek,
This is how I am doing center positioning of the modal in my app:
This will handle even if the window in scrolled position.
var winW = $(document).width();
if (winW % 2 > 0) winW = winW - 1;
$("#popupCompare").css('top', (($(window).height() / 2) - ($("#popupCompare").height() / 2) + $(document).scrollTop()));
$("#popupCompare").css('left', winW / 2 - $("#popupCompare").width() / 2);

Let me know if you find it useful.
Thanks

A: The best way for centering a popup is using CSS, not JavaScript. JavaScript comes handy, only when your situation gets really dynamic, like trying to respond the user's scroll, or creating some JavaScript ads on your site, and stuff like that. But this is a static situation. Please consider these guidelines for popup design:

*

*Popup is just a simple modal dialog (overlay if you wish) to interact with user for a simple purpose, something like editing a simple record. So, if your popup gets big in dimensions and you get more and more controls and interactions in there, consider changing your design to redirect the user to another page, instead of popup.

*There are two types of popup: 1) Modal, which means that unless user deal with the popup, he can't access the rest of the page. 2) Non-modal, which means that user still has access to the rest of the page, while interacting with popup.

*Popups usually should be draggable, as there may be need for the user to drag the popup away, so (s)he can see the portion of the page covered by popup.

*A popup should always have a close button somewhere (usually very explicit at the top right corner)

Now, my suggestion is to follow these steps:

*

*Create a div element as the last element of body tag.

*Absolutely position it with this CSS:
#screenCover
   {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      opacity: 0.5; // Consider using filter for Microsoft IE
      z-index: 9000; // Blocking access to the background page, while semi-visible
   }

*Then create another div inside this screenCover div
popupContainer
{
   position: absolute;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   width: 500px; /* This portion can be set dynamically /
   height: 300px; / can be set dynamically /
   margin: auto; / centering popup on background */
}

*Now put your popup controls inside popupContainer.


text:
Q: dropdown should populate names from database I am using html dropdown menu and not asp .net control. I want to populate names of employees from database in dropdown using jquery. What code i have to write in aspx.cs file. And how to bind with json data ? Please reply
My code is

 <script type="text/javascript" language="javascript">
 $(document).ready(function()
 {
 $().ready(function(){
 $.ajax({
 type:"POST",
 data:"{}",
 url:"TestJson.aspx/GetName",
 dataType:"json",
 success:function(msg)
 {
 var dropDown=$("#ddlName");
 dropDown.append($("<option></option>").val('').text('- Select -'));

$.each(data, function () {
    dropDown.append($("<option></option>")

        .text($(this).attr("Name")));
 });
 },
 error:function()
 {
 alert("failed to load");
 }
 });
 });

  </script>
  <style type="text/css">

    #ddlName
    {
        width: 146px;
    }
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="border:1px solid gray; width:400px;">

                    Name

                    <select id="ddlName">
                    <option value="">--Select--</option>
                </select>
        </div>
</form>

My .cs code

  public  static Details[] BindDropdown()
{
 DataTable dt = new DataTable();
    List<Details> details = new List<Details>();

    SqlConnection con = new SqlConnection("Data Source=ST0022;Initial     Catalog=QuickMove_Globe;User ID=sa;Password=good");

       SqlCommand cmd = new SqlCommand("SELECT ClientBranchID,Name FROM     ProspectiveLead", con);

            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            foreach (DataRow dtrow in dt.Rows)
            {
                Details detail = new Details();
                detail.Id = Convert.ToInt32(dtrow["ClientBranchId"].ToString());
                detail.Name = dtrow["Name"].ToString();
                details.Add(detail);
            }

    return details.ToArray();
}
public class Details
{
    public int Id { get; set; }
    public string Name { get; set; }
}

A: In The .aspx Page Code
   <select id="ddlStateName"><option value="0" selected="selected">State</option>
   </select>

in the Web Service we have the following Method
Create the Generic class for The state
public class StateProperty
    {
      public int StateId { get; set; }
      public string StateName { get; set; }

    }

public List<StateProperty> GetAllState()
      {
          _objDataWrapper=new DbWrapper(Common.CnnString,CommandType.StoredProcedure);
          var objStateList = new List<StateProperty>();
          _dataSet=new DataSet();
          try
          {
              // Here you will write query like "select * from state" and fill it dataset
              _dataSet = _objDataWrapper.ExecuteDataSet("Aj_Proc_GetStateList");
              objStateList = BindStateObject(_dataSet.Tables[0]);
          }
          catch (Exception ex)
          {

          }
          return objStateList;
      }

   //BindStateObject method defined here

 private List<StateProperty>BindStateObject(DataTable dataTable)
      {
          var objStateList = new List<StateProperty>();

          try
          {
              if(dataTable.Rows.Count>0)
              {
                  for(var j=0;j<dataTable.Rows.Count;j++)
                  {
                      var objState = new StateProperty
                                         {
                                             StateName = Convert.ToString(dataTable.Rows[j]["AjStateName"]),
                                             StateId = Convert.ToInt32(dataTable.Rows[j]["AjStateId"])
                                         };
                      objStateList.Add(objState);
                  }
              }
          }
          catch (Exception ex)
          {

          }
          return objStateList;
      }

     [WebMethod]
   public ListItem[] GetAllState()
   {
       var data = GetAllState();
       if (data.Count > 0)
           return data.Select(result => new ListItem()
           {
               Text = result.StateName,
               Value =
                   result.StateId.ToString(CultureInfo.InvariantCulture)

           }).ToArray();
       return null;
   }

Then after we have to call this web method through Jquery
function BindState() {
    var countryId = countryObj.val();

        $("#ddlStateName").empty().append('<option selected="selected" value="0">Select State</option>');
        $.ajax({
            type: "POST",
            url: "pathofyourwebservice/GetState",
            async: true,
            data: '{""}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                PopulateControl(response.d, stateObj);

            },
            error: function (xml, textStatus, errorThrown) {
                alert(xml.status + "||" + xml.responseText);
            }
        });
    }
}

//Here i am defining the PopulateControl
function PopulateControl(list, control) {

    if (list.length > 0) {

        control.removeAttr("disabled");

        $.each(list, function () {

            control.append($("<option></option>").val(this['Value']).html(this['Text']));

        });
    }
    else {
        control.empty().append('<option selected="selected" value="0">Not available<option>');
    }
}

Then after call this method on the page in side the document.ready function
$(document).ready(function () {
  BindState();
});


text:
Q: Why can a bit vector reduce space usage by only a factor of eight compared to an array of booleans? I'm reading Cracking the Coding Interview, and there's the question, "Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?"
Assuming ASCII strings, an obvious solution is to store whether a character has been used before in an array of 256 booleans. A more space efficient solution is to instead use a bit vector. My understanding is that would be implemented something like this: an array of integers, where each bit of an integer is either a true or false value. So, let's say we have 32 bit integers. Then we need an array of 8 such integers to get 32*8 = 256 booleans stored in bits. These will be stored in only 256 bits. On the other hand, if a boolean is stored in n bits, we will need n * 256 bits to store the array.
Here's where I'm confused. The book says that using a bit vector decreases space by a factor of 8. This would only be true if n=8, but I don't think booleans are stored in 2 bytes in Java (the language the book uses), so that is not correct. So, what am I doing wrong/why does using a bit vector decrease space by a factor of 8?
EDIT: I know that there are 8 bits in a byte, the above was just a dumb mistake. Question is answered by comments, as well as an explanation for my confusion.


text:
Q: How to debug NativeScript java code in Android Studio? I'm quite new to NativeScript. Currently, one of my projects is using NativeScript to develop cross-platform app. It has a 3rd-party lib which is written in java. But the result is not as good as I expected. I was struggling to find the problem since the console didn't log valuable info regarding to native code.

Instead, I import the project to Android Studio which is under the folder of platform/android. But it logs error when I hit the "run" button.

I want to know:

*

*Is it possible to debug native code directly with VS Code. At least print out java native error or cat log.

*How can I debug native code in Android Studio? How to solve the problem I ran into?

I'd be very appreciated, if anyone can answer my questions. Thanks!

A: Let me start off by saying there's no official integration with Android Studio. All I can provide is a workaround that will make it possible.
Note: The steps provided below are tested with NativeScript CLI 3.1.1 and will probably work also with 3.2.0.
The first problem is you don't have "node" set in your global path so first of all, you need to add it to PATH. Node required for NativeScript to run. You can look at how to set it up here
If you want to be able to run the project with Android Studio you can follow these steps:

*

*After you've done that you need to change the <app_name>/platforms/android/build.gradle file as described here

*The above change will enable you to open <app_name>/platforms/android in Android Studio

*Run <app_name>:clean task from gradle

*Run the  task default for Android Studio, that will prompt you for emulator or device on which to run:


text:
Q: Making Jquery work within a page that was received via ajax So I'm trying to write some jquery stuff within a page(content) that is originally being received via ajax. But its not working. If I make the page non received via ajax, it works perfect. However I wanted the current page(requested via ajax) to work with the jquery search i'm doing. I've put this code on the page requesting the ajax content, not working, and then I tried putting it on the ajax requested content.
The Page that has the ajax content has this:
and its suppose to use the below javascript function
Thank You
<script type="text/javascript">

$(document).ready(function() {

    var data = {items: [
            {value: "21", name: "Mick Jagger"},
            {value: "43", name: "Johnny Storm"},
            {value: "46", name: "Richard Hatch"},
            {value: "54", name: "Kelly Slater"},
            {value: "55", name: "Rudy Hamilton"},
            {value: "79", name: "Michael Jordan"}
        ]};
    $("div.search input").autoSuggest(data.items, {selectedItemProp: "name", searchObjProps: "name"});

});
</script>

A: It's really hard to understand what's going on in your page without seeing more of your code. Would your problem be that you're expecting $(document).ready to be run only after your ajax content is loaded? If that's the case, then you should know that it's run after the page is fully loaded, and ajax requests aren't included in this - they're separate.
If this actually is your problem, you can fix it by moving everything inside of $(document).ready to the ajax callback function.

A: How about putting it into a custom function then calling that function after the content has been loaded?
function stuff() {

    var data = {items: [
            {value: "21", name: "Mick Jagger"},
            {value: "43", name: "Johnny Storm"},
            {value: "46", name: "Richard Hatch"},
            {value: "54", name: "Kelly Slater"},
            {value: "55", name: "Rudy Hamilton"},
            {value: "79", name: "Michael Jordan"}
        ]};

    $("div.search input").autoSuggest(data.items, {selectedItemProp: "name", searchObjProps: "name"});

}

$(function() {
    $('#content').load('something.html', function() {
        stuff();
    });
});


text:
Q: JAX-RS and EJB exception handling I'm having trouble handling exceptions in my RESTful service:
@Path("/blah")
@Stateless
public class BlahResource {
    @EJB BlahService blahService;

    @GET
    public Response getBlah() {
        try {
            Blah blah = blahService.getBlah();
            SomeUtil.doSomething();
            return blah;
        } catch (Exception e) {
            throw new RestException(e.getMessage(), "unknown reason", Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}

RestException is a mapped exception:
public class RestException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    private String reason;
    private Status status;

    public RestException(String message, String reason, Status status) {
        super(message);
        this.reason = reason;
        this.status = status;
    }
}

And here is the exception mapper for RestException:
@Provider
public class RestExceptionMapper implements ExceptionMapper<RestException> {

    public Response toResponse(RestException e) {
        return Response.status(e.getStatus())
            .entity(getExceptionString(e.getMessage(), e.getReason()))
            .type("application/json")
            .build();
    }

    public String getExceptionString(String message, String reason) {
        JSONObject json = new JSONObject();
        try {
            json.put("error", message);
            json.put("reason", reason);
        } catch (JSONException je) {}
        return json.toString();
    }

}

Now, it is important for me to provide both a response code AND some response text to the end user.  However, when a RestException is thrown, this causes an EJBException (with message "EJB threw an unexpected (non-declared) exception...") to be thrown as well, and the servlet only returns the response code to the client (and not the response text that I set in RestException).
This works flawlessly when my RESTful resource isn't an EJB... any ideas?  I've been working on this for hours and I'm all out of ideas.
Thanks!

A: The problem seems to be connected with EJB Exception Handling. By the specification any system exception (that is - any RuntimeException not specifically marked as Application Exception) that is thrown from within a managed bean will be packaged into an EJBException and later, if needed, into RemoteException thrown to the client. That is a situation you seem to be in, and in order to avoid that you can either:

*

*change your RestException into a checked exception and handle it as such

*use @ApplicationException annotation on your RestException

*create EJBExceptionMapper and extract information needed from (RestfulException) e.getCause()

A: A similar case works for me when RestException extends javax.ws.rs.WebApplicationException