text:
Q: How to protect sensitive data on a SPA using JWT tokens I'm thinking about making an app with javascript and make it a SPA.
Using JWT tokens to authenticate the users and set the user roles on the app, what is the best way to protect sensitive content?
Using html templates for logged pages is bad? Should i return always the sensitive content from the api?
Thanks

A: Everything dynamic should be passed through your web service. If you won't use anything improperly (like using SQL drivers without injection prevention) there won't be anything unsafe (for at least first stage).
Also, to prevent MiM attacks, you should use SSL/TLS.

A: You can encrypt your JWT. Such encryption is defined in the RFC7516.
Depending on the programming language used on server side and client side (JS) , you may find libraries that support the JWE.
At jwt.io, you will find a list of those libraries.


text:
Q: Change ScrollView weight programmatically I want to change the weight of a ScrollView, but i can't find the way to do it.
There is my XML:
<ScrollView
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:layout_gravity="center_vertical"
    android:id="@+id/firstScrollView">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        ...
    </LinearLayout>

   **other layout..

</ScrollView>

From code i can only set the height or the width of the scrollView, what should i write for the weight??
    ViewGroup.LayoutParams scrollParams = new ViewGroup.LayoutParams(width,height);
    scrollView.setLayoutParams(scrollParams);

A:  LinearLayout.LayoutParams scrollParams = new LinearLayout.LayoutParams(width,height,2.0f);
 scrollView.setLayoutParams(scrollParams);

The last option in the constructor is the weight

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem suggested by the Pythagorean musica scale Is the set of fractions $3^m/2^n$ dense in the interval [1,2]?
If this can help: for each m there is exactly one n in the interval ($n$=integer part of $m\gamma$ , where $\gamma=\log 3/\log 2$)

A: Yes, the set of such fractions is dense in $[1, 2]$. The proof below is an elaboration of Henning Makholm's answer.

*

*The fractions $\dfrac{3^m}{2^n}$ being dense in $[1, 2]$ is equivalent to the logarithms of those fractions being dense in $[\log 1, \log 2]$.
Proof: This is because the inverse of the logarithm function is continuous: a neighbourhood of $x \in [1, 2]$ contains the image of a neighbourhood of $\log x \in [\log 1, \log 2]$.
In concrete terms, if you want to show that for a particular $x$, for every $\epsilon$ there exists $(m, n)$ such that $|x - 3^m/2^n| < \epsilon$, it's enough to show that for every $\delta$ there exists $(m, n)$ such that $|\log x - \log(3^m/2^n)| < \delta$, as for sufficiently small $\delta$ (possibly depending on $x$ and $\epsilon$), we have $|\log x - \log(3^m/2^n)| < \delta \implies |x - 3^m/2^n| < \epsilon$.

*The logarithm of $\dfrac{3^m}{2^n}$ is $m\log 3 - n\log 2$. We want to prove that the set of such numbers is dense $[0, \log 2]$, or, equivalently, dividing throughout by $\log 2$ (which again we can do because this operation has a continuous inverse, say), we want to prove that the set of numbers of the form $m\frac{\log 3}{\log 2} - n$ is dense in $[0, 1]$.
As you observed, for any integer $m$, there is a unique integer $n = \left\lfloor \frac{m\log 3}{\log 2} \right\rfloor$ such that $m \log 3 - n\log 2$ lies in $[0, \log 2]$, or equivalently, such that $m \frac{\log 3}{\log 2} - n$ lies in $[0, 1]$). So $m \frac{\log 3}{\log 2} - n$ is precisely the fractional part of $m\frac{\log 3}{\log 2}$. The question now is to prove that the fractional parts of $m\frac{\log 3}{\log 2}$ are dense in $[0, 1]$.

*There is a well-known result that if $\alpha$ is irrational, then the set of fractional parts of $m\alpha$ as $m$ ranges over the natural numbers, is dense in $[0, 1]$. This you can see proved on this site, here, here, here and even on Wikipedia. Basically, you can use the pigeonhole principle: if you want to show that the fractional part of some $m\frac{\log 3}{\log 2}$ is within some distance $\frac{1}{q}$ of some number, consider more than $q$ such numbers; two of the fractional parts lie in the same $\frac{1}{q}$ "bucket"; by considering their difference and a suitable multiple, you can put the fractional part into the bucket you want.

*The number $\dfrac{\log 3}{\log 2}$ is irrational, because of $\dfrac{\log 3}{\log 2} = \dfrac{p}{q}$, then it means that $3^q = 2^p$, which is impossible for nonzero $q$. This concludes the proof.

A: Yes.
The set of multiples of $\log 3$ is dense in $\mathbb R$ modulo $\log 2$, because $\frac{\log 3}{\log 2}$ is irrational. If it was rational there'd be a nontrivial power of 2 that was also a power of 3, which contradicts the fundamental theorem of arithmetic.


text:
Q: Printing output of command I'm using gtk-rs to take the value of an input and use it to execute a command with xdotool:
 input.connect_activate(clone!(@weak window => move |entry| {
    let input_text = entry.text();
    let cmd = format!(
        "xdotool search --onlyvisible --name {} windowactivate",
        input_text
    );

    let output = std::process::Command::new("sh")
        .arg("-c")
        .arg(cmd)
        .spawn()
        .unwrap();

    println!("{}", String::from_utf8_lossy(&output.stdout));

    window.close();
}));

I'm getting this compiling error:
error[E0308]: mismatched types
   --> src/main.rs:66:48
    |
66  |         println!("{}", String::from_utf8_lossy(&output.stdout));
    |                        ----------------------- ^^^^^^^^^^^^^^ expected slice `[u8]`, found enum `std::option::Option`
    |                        |
    |                        arguments to this function are incorrect
    |
    = note: expected reference `&[u8]`
               found reference `&std::option::Option<ChildStdout>`
note: associated function defined here
   --> /home/alex/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/string.rs:631:12
    |
631 |     pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
    |            ^^^^^^^^^^^^^^^

So I tried this:
match output.stdout {
    Some(stdout) => {
        println!("{}", String::from_utf8_lossy(&stdout));
    },
    None => {
        println!("No output");
    }
}

But I'm getting the same error.
Update:
I tried:
let output = std::process::Command::new("sh")
    .arg("-c")
    .arg(cmd)
    .output()
    .unwrap();

println!(Output: "{}", String::from_utf8_lossy(&output.stdout));

But nothing is being printed:
Output:

Full code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ea4431b73191c132f4392378cce13604

A: After reading the comments and docs, I managed to print the command with:
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));

But I had to do: xdotool search --onlyvisible --name {} because xdotool search --onlyvisible --name {} windowactivate prints nothing.


text:
Q: node_module errors with AWS lambda, what's the best practice for dependencies? I've been trying to convert and deploy one of our node.js apps into a lambda function and have been having some problems with the node_modules dependencies - saying that it can't find certain modules.  I started by creating a package.json, npm install the dependencies locally then copy the node modules folder up to lambda.
For instance I have a project that requires sequelize and convict and have been getting errors saying that it cannot find the moment module as a sub-dependency.  I see that moment is included in the root of my node_modules but it was not included in the sub folder under the sequelize module.
However, this project runs fine locally.  What is the difference in lambda and what's the best practice for deploying a somewhat long list of node modules with it - just a copy of the node_modules folder?  On some of the other simpler projects I have, the small amount of node_modules can be copied up with no problems.

{
  "errorMessage": "Cannot find module 'moment'",
  "errorType": "Error",
  "stackTrace": [
    "Function.Module._resolveFilename (module.js:338:15)",
    "Function.Module._load (module.js:280:25)",
    "Module.require (module.js:364:17)",
    "require (module.js:380:17)",
    "VERSION (/var/task/node_modules/sequelize/node_modules/moment-timezone/moment-timezone.js:14:28)",
    "Object. (/var/task/node_modules/sequelize/node_modules/moment-timezone/moment-timezone.js:18:2)",
    "Module._compile (module.js:456:26)",
    "Object.Module._extensions..js (module.js:474:10)",
    "Module.load (module.js:356:32)",
    "Function.Module._load (module.js:312:12)"
  ]
}

A: I resolved this by uploading all from a zip file which contains all the data I need for my lambda function.
you can just create your project in your local machine and make all the changes that you need then the file you are going to zip should have this same structure and also see that there is an option to load your code from a zip file.

A: This sounds to me like an issue caused by different versions of npm. Are you running the same version of nodejs locally as is used by Lambda (ie. v0.10.36)?
Depending on the version of npm you're using to install the modules locally,  the node_modules directory's contents are laid out slightly differently (mainly in order to de-duplicate things), and that may be why your dependencies can't find their dependencies in Lambda.
After a bit of digging, it sounds like a clean install (ie. rm your node_modules directory and run npm install) might clean things up for you. The reason why is that it seems that npm doesn't install sub-dependencies if they're already present at the top level (ie. you installed moment before sequelize, etc).


text:
Q: swiftui navigation как показать только последний back struct CategoryScreen: View {

    @State private var categories = [Category]()

    var body: some View {
        NavigationView {
            List(categories, id: \.id) { category in
                NavigationLink(destination: CategoryScreen()) {
                    Text(category.name)
                }
            }.onAppear(perform: loadData)
        }
    }

}```

Создает последовательность баров <Back - как оставлять только последний?

A: Если Вы про такую картину:

То проблема в том, что Вы переходите на NavigationView из NavigationView и т.д. В UIKit подобное привело бы к "падению" приложения, в SwiftUI допустимо.
Для решения этого нужно вынести NavigationView в отдельный компонент, а переходить на компонент, который будет "встраиваться". К примеру:
struct ContentView: View {
    var body: some View {
        NavigationView {
            CategoryScreen(title: nil)
        }
    }
}

struct CategoryScreen: View {
    let title: String?
    @State private var categories: [Category] = (0...10).map { _ in Category() }

    var body: some View {
        List(categories, id: \.id) { category in
            NavigationLink(destination: CategoryScreen(title: category.name)) {
                Text(category.name)
            }
        }
        .navigationBarTitle(title ?? "", displayMode: .inline)
    }
}

Результат:


text:
Q: How do i create a data source in WebSphere Liberty via JMX I am unable to find a code snippet for creating a datasource in Liberty via a Java Client. I looked up the ConnectionManagerMbean, but its documentation says that the Mbean instance wont be available until it is first used.
Can someone point me in right direction. I am kinda new to both Liberty and JMX so please bear with me if this sounds kinda rookyish.
Thanks in advance.

A: The reason you are unable to locate any examples of creating a Liberty data source via JMX is because it is not possible in Liberty to create data sources via JMX.  In Liberty, data sources can be created via server configuration - the dataSource element -  or via the @DataSourceDefinition annotation within an application component or <data-source> element within a deployment descriptor (such as web.xml) of an application.
Once you have created the data source, as you mentioned from the ConnectionManagerMBean documentation, you will need to use the data source first (access it from an application) before the MBean is made available.  This aligns with Liberty's goals of having fast startup time and only loading/initializing what applications actually use.  The behavior you observe sounds consistent with this, and you just need to perform an operation within your application first, and then you should hopefully be able to access the MBean.


text:
Q: Validate to staff_user : Django Restframework I want only staff_user can add product and can add maximum up to 10 products.
I'm probably new to django. I have tried something like below, but i have no idea about how to validate to the staff_user that he can add up to 10 products maximum.
It would be great if anybody could help me what i'm trying to solve is. thank you so much in advance.
models.py
class Cuboid(models.Model):
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=80)
    length = models.ForeignKey('FilterLength', on_delete=models.CASCADE)
    created_on= models.DateTimeField(default=datetime.now())

serializers.py
class CuboidCreateSerializers(serializers.ModelSerializer):
    class Meta:
        model = Cuboid
        fields = "__all__"

views.py
class CuboidCreateAPIView(generics.CreateAPIView):
    model = Cuboid
    queryset = Cuboid.objects.all()
    serializer_class = CuboidCreateSerializers
    permission_classes = [IsStaff]

A: Use field-level validation of DRF
class CuboidCreateSerializers(serializers.ModelSerializer):
    def validate_created_by(self, created_by):
        max_count = 10
        created_count = Cuboid.objects.filter(created_by=self.context['request'].user).count()
        if created_count >= max_count:
            raise serializers.ValidationError("User allowed to create maximum of %s items" % max_count)
        return created_by

    class Meta:
        model = Cuboid
        fields = "__all__"

A: There is a section in the documentation that outlines this:
https://www.django-rest-framework.org/api-guide/permissions/

IsAdminUser
The IsAdminUser permission class will deny permission to any user, unless user.is_staff is True in which case permission will be allowed.

Based on this, I believe you have to check for two things, isAuthenticated and user.is_staff both have to be true. It may be that is_staff already accounts for isAuthenticated.


text:
Q: How to test multiple version of google chrome using chromedriver? selenium web-driver with java then how to use chrome driver for test their lower version of Google chrome

A: From the official wiki page:
Overriding the Chrome binary location
You can specify the location of the Chrome binary by passing the "chrome.binary" capability, e.g. with a typical Chromium install on Debian:
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.binary", "/usr/lib/chromium-browser/chromium-browser");
WebDriver driver = new ChromeDriver(capabilities);

I suggest you try this approach - tell where the binary of lower version is and start ChromeDriver. Never tried it, but I think it might work

A: You would use capabilities to point to the right binary file of the browser to be launced.But not all versions of chrome browser is supported by different versions of chromedriver. You will find exceptions stating that version of browser expected is greater or equal to 30.0.
For ex:- Chromium Browser(33.0.1729.0 )works fine with ChromeDriver 2.7 and not the with the older ones.
You can choose from all the chromedriver version available from the link below:-
http://chromedriver.storage.googleapis.com/index.html

A: Install chrome to custom location, be sure to turn off auto-update.  Use following code to use non-default binary.
    ChromeOptions options = new ChromeOptions();
    options.setBinary("/path/to/binary");

    DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
    desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);

    WebDriver webDriver = new ChromeDriver(desiredCapabilities);


text:
Q: Minimum in a non-linear system I have the linear system:
$$\begin{cases}\dot{x}=y\\
\dot{y}=-ay+x-x^3\end{cases}$$
where $a\geq 0$.
I want to prove that this dynamical system has two minimum.
I found the 3 equilibrium points $(0,0)$, $(1,0)$, $(-1,0)$.
I calculated the jacobian and i don't know how to proceed.
I have read something about minimum points when the Jacobian is positive definitive but these matrices are not.

A: As @GReyes proposed you need to linearize the system at the equilibrium points $\boldsymbol{x}_\text{eq}=[x_\text{eq},y_\text{eq}]^T$, which are $[0,0]^T$ and $[\pm 1,0]^T$.
If we write the system in vector form, by using $\boldsymbol{x}=[x,y]^T$ and $\boldsymbol{f}=[f_1(\boldsymbol{x}),f_2(\boldsymbol{x})]^T$
$$\dot{\boldsymbol{x}}=\boldsymbol{f}(\boldsymbol{x})$$
we can simply get the linarized system matrix $\boldsymbol{A}$ by
$$\boldsymbol{A} = \left.\dfrac{\partial \boldsymbol{f}}{\partial \boldsymbol{x}}\right|_{\boldsymbol{x}=\boldsymbol{x}_\text{eq}}$$
Written out for our problem this is given by
$$\boldsymbol{A}=\begin{bmatrix}
\dfrac{\partial f_1}{\partial x}& \dfrac{\partial f_1}{\partial y}\\
\dfrac{\partial f_2}{\partial x}& \dfrac{\partial f_2}{\partial y}
\end{bmatrix}_{\boldsymbol{x}=\boldsymbol{x}_\text{eq}}$$
$$=\begin{bmatrix}0 & 1\\1-3x^2_\text{eq} & -a\end{bmatrix}.$$
The eigenvalues of this system are given by the characteristic polynomial
$$\chi(s)=s^2+as+(3x^2_\text{eq}-1).$$
If $a>0$ and $3x^2_\text{eq}-1>0$ are fulfilled the system is Hurwitz, hence the equilibrium point is asymptotically stable. You can quickly check these properties for the given equilibrium points. Only the origin is unstable but all other equilibrium points are asymptotically stable in a neighborhood of the equilibrium points.
As @Kwin van der Veen proposed. The phase diagram looks like a landscape with hills (unstable equilibrium points) and valleys (asymptotically stable equilibrium points). If you imagine a ball starting somewhere (initial conditions) in this landscape the ball will converge to one of the asymptotically stable equilibrium points (we exclude the trivial origin as a starting point), by following the dynamics of the system (given by the arrows in the phase diagram provided by @Kwin van der Veen).
The hard part is actually the case $a=0$. For the equilibrium point $[0,0]^T$ you can still use the linearization theorem by Lyapunov. But for the other equilibrium points, you will need to find a Lyapunov function to show stability.
EDIT: I just couldn't resist :D. In order to show the stability of the system at the equilibrium points $[0,\pm 1]^T$ we divide both equations to obtain
$$dy/dx = \dfrac{x-x^3}{y} \implies 1/2y^2-1/2x^2+1/4x^4-c=0.$$
Now, we define $\Phi(x,y)=  1/2y^2-1/2x^2+1/4x^4$ and evaluate this function at the equilibrium points $x_\text{eq}=\pm 1$ to get $\Phi_\text{eq}=-1/4$. Now, we construct a Lyapunov function candidate
$$V(x,y)=\Phi(x,y)-\Phi_\text{eq}=1/2y^2-1/2x^2+1/4x^4+1/4$$
$$=1/4\left[(1-x^2)^2+2y^2\right].$$
You can see that the function $V$ is positive definite in the vicinity of the equilibrium points $[\pm 1,0]^T$ and $V=0$ for the equilibrium points.
It is clear that $\dot{V}=0$. Because $\Phi(x,y)$ and $\Phi_\text{eq}$ are constants. You can also derive this by differentiating $V$ and using the differential equations for $a=0$. Hence, we can conclude that the equilibrium points are stable.


text:
Q: How can I make a PyTorch extension with cmake This tutorial demonstrates how to make a C++/CUDA-based Python extension for PyTorch. But for ... reasons ... my use-case is more complicated than this and doesn't fit neatly within the Python setuptools framework described by the tutorial.
Is there a way to use cmake to compile a Python library that extends PyTorch?

A: Yes.
The trick is to use cmake to combine together all the C++ and CUDA files we'll need and to use PyBind11 to build the interface we want; fortunately, PyBind11 is included with PyTorch.
The code below is collected and kept up-to-date in this Github repo.
Our project consists of several files:
CMakeLists.txt
cmake_minimum_required (VERSION 3.9)

project(pytorch_cmake_example LANGUAGES CXX CUDA)

find_package(Python REQUIRED COMPONENTS Development)
find_package(Torch REQUIRED)

# Modify if you need a different default value
if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
  set(CMAKE_CUDA_ARCHITECTURES 61)
endif()

# List all your code files here
add_library(pytorch_cmake_example SHARED
  main.cu
)
target_compile_features(pytorch_cmake_example PRIVATE cxx_std_11)
target_link_libraries(pytorch_cmake_example PRIVATE ${TORCH_LIBRARIES} Python::Python)

# Use if the default GCC version gives issues.
# Similar syntax is used if we need better compilation flags.
target_compile_options(pytorch_cmake_example PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-ccbin g++-9>)

# Use a variant of this if you're on an earlier cmake than 3.18
# target_compile_options(pytorch_cmake_example PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-gencode arch=compute_61,code=sm_61>)

main.cu
#include <c10/cuda/CUDAException.h>
#include <torch/extension.h>
#include <torch/library.h>

using namespace at;

int64_t integer_round(int64_t num, int64_t denom){
  return (num + denom - 1) / denom;
}

template<class T>
__global__ void add_one_kernel(const T *const input, T *const output, const int64_t N){
  // Grid-strided loop
  for(int i=blockDim.x*blockIdx.x+threadIdx.x;i<N;i+=blockDim.x*gridDim.x){
    output[i] = input[i] + 1;
  }
}

///Adds one to each element of a tensor
Tensor add_one(const Tensor &input){
  auto output = torch::zeros_like(input);

  // Common values:
  // AT_DISPATCH_INDEX_TYPES
  // AT_DISPATCH_FLOATING_TYPES
  // AT_DISPATCH_INTEGRAL_TYPES
  AT_DISPATCH_ALL_TYPES(
    input.scalar_type(), "add_one_cuda", [&](){
      const auto block_size = 128;
      const auto num_blocks = std::min(65535L, integer_round(input.numel(), block_size));
      add_one_kernel<<<num_blocks, block_size>>>(
        input.data_ptr<scalar_t>(),
        output.data_ptr<scalar_t>(),
        input.numel()
      );
      // Always test your kernel launches
      C10_CUDA_KERNEL_LAUNCH_CHECK();
    }
  );

  return output;
}

///Note that we can have multiple implementations spread across multiple files, though there should only be one `def`
TORCH_LIBRARY(pytorch_cmake_example, m) {
  m.def("add_one(Tensor input) -> Tensor");
  m.impl("add_one", c10::DispatchKey::CUDA, TORCH_FN(add_one));
  //c10::DispatchKey::CPU is also an option
}

Compilation
Compile it all using this command:
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_PREFIX_PATH=`python -c 'import torch;print(torch.utils.cmake_prefix_path)'` -GNinja ..

test.py
You can then run the following test script.
import torch
torch.ops.load_library("build/libpytorch_cmake_example.so")

shape = (3,3,3)
a = torch.randint(0, 10, shape, dtype=torch.float).cuda()
a_plus_one = torch.ops.pytorch_cmake_example.add_one(a)


text:
Q: std::array of AVX intrinsics I don't know if there's something missing on my understanding of how AVX intrinsics works with std::array, but I'm having a strange issue with Clang when I combine the two.
Sample code:
std::array<__m256, 1> gen_data()
{
    std::array<__m256, 1> res;
    res[0] = _mm256_set1_ps(1);
    return res;
}

void main()
{
    auto v = gen_data();
    float a[8];
    _mm256_storeu_ps(a, v[0]);
    for(size_t i = 0; i < 8; ++i)
    {
        std::cout << a[i] << std::endl;
    }
}

Output from Clang 3.5.0 (upper 4 floats are garbage data):
1
1
1
1
8.82272e-39
0
5.88148e-39
0
Output from GCC 4.8.2/4.9.1 (expected):
1
1
1
1
1
1
1
1
If I instead pass v into gen_data as an output parameter it works just fine on both compilers. I'm willing to accept that this might be a bug in Clang, however I don't know if this might be undefined behavior(UB). Testing with Clang 3.7* (svn build) and Clang appears to now give my expected result. If I switch to SSE 128-bit intrinsics (__m128) then all compilers give the same expected results.
So my questions are:

*

*Is there any UB here? Or is this just a bug in Clang 3.5.0?

*Is my understanding that __m256 is simply a 32-byte aligned chunk of memory correct? Or is there something else special about it that I have to be careful with?

A: This looks like this is clang bug that is now fixed, we can see this from this bug report , which demonstrates a very similar problem using regular arrays.
Assuming std::array implements its storage similar to this:
T elems[N];

which both libc++ and libstdc++ seem to do then this should analogous. One of the comments says:

However, libc++'s std::array<__m256i, 1> does not work at any optimization level.

The bug report was actually based off of this SO question: Is this incorrect code generation with arrays of __m256 values a clang bug? which is very similar but deals with the regular array case.
The bug report contains one possible work-around, which the OP stated is sufficient:

In my actual code, num_vectors is calculated based on some C++ template parameters to the simd_pack type. In many cases, that comes out to be 1, but it also is often greater than 1. Your observation gives me an idea, though; I could try to introduce a template specialization that catches the case where num_vectors == 1. It could instead just use a single __m256 member instead of an array of size 1. I'll have to check to see how feasible that is.


text:
Q: Unable to observe Viewmodel from one fragment but works from different fragment in Android [Kotlin] In a weird scenario, I am able to fetch the response from an API and see it in one of the fragments by observing the livedata from viewmodel but it doesn't show any response in a different fragment.
I have a fragment where I put some values and these values are further pass through viewmodel -> repository to fetch the data from an api and then I am observing this data using a variable in different fragments.
I am only able to fetch the data in the fragment from where I am sending values but unable to observe from other fragments.
Any possible reason for this?
P.S - If there is any requirement of code let me know I'll add.
Edit 1 : Figured out that there is something called as Shared ViewModel that should be used. So I tried implementing that. Only thing I had to change was changing my viewModel implementations to activityViewModels.
But things doesn't seems to be working still.
Not sure but maybe there can be an issue with my implementation of ViewModel across the app.
Currently I follow this pattern.
Data from api -> Repository (I pass the api in its constructor) -> ViewModel (I pass the repository in its constructor).
As I am passing repository instance in my constructor of the ViewModel I have created a ViewModelFactory which passes the repository when ViewModel is created.
Keeping all this in mind, I have created a global initialization of repository inside the MainApplication class like this :
val myRepoInstance by lazy { myReposiotry(myApiClient) }

and I am implementing it inside the fragment like this :
    private val myViewModelInstance: MyViewModel by activityViewModels {
        ViewModelFactory((context?.applicationContext as MainApplication).myRepoInstance)
    }
//Rest of the code...

A: I have create a similar case and it's working fine, check if helps
Activity  with FragmentA already added and here on click of  a button  I am updating value in ViewModel
FragmentA here I am updating a Value in SharedViewModel
FragmentB where we are observing updated value from sharedViewModel

enter image description here
[
[

A: You need Factory in you first Fragment only not in your second fragment
For First Fragment do this
private val viewModel: SharedViewModel by activityViewModels { SharedViewModel.Factory(...) }
For second fragment do this(don't create factory)
private val viewModel: SharedViewModel by activityViewModels()
For this link for details https://medium.com/@lucasnrb/advanced-viewmodels-part-iii-share-a-viewmodel-between-fragments-59c014a3646


text:
Q: Put  tag in a corner So I want to put a h1 tag in the bottom right corner. What I have currently is below; however, this is very tedious and I want it to always be in the corner. Currently the way I am doing it is based off of my computer's screen, but if someone uses a computer with a different size screen then the tag will not be in the right place. Would there be any other way I could do this so that the tag would be in the same place for all size monitors?

.subH {
  font-family: Sedgwick Ave Display;
  font-size: 10px;
  padding-top: 505px;
  padding-left: 1170px;
  color: white;
}

Created by Hybrid Alpaca Game Studios

A: Use position: fixed
Example:
h1 {
position: fixed;
bottom 6px;
left: 6px;
}


text:
Q: Not able to parse JSON array string I am working on project in which I am sending request ot server for getting JSON array string. I am using following java code to create one JSON array list string.
JSONArray itemList = new JSONArray();
for(int i =0; i<4; i++) {
    String exe = "m";
    final JSONObject jsonObj = new JSONObject();
    jsonObj.put("filePath", 30);
    jsonObj.put("duration", 12222);
    jsonObj.put("bitRate", 1111);
    jsonObj.put("widht", 12);
    jsonObj.put("format", 123);
    jsonObj.put("height", 12);
    jsonObj.put("exe", exe);
    JSONObject jObject = new JSONObject();

    try {
        itemList.put(jsonObj);
        // jObject.put("itemList", itemList);
    } catch (Exception e) {
        System.out.println("ERROR");
    }
}
return itemList.toString();

On client side, in AJAX response, I am getting following String by using above method:
[{"duration":12222‚"height":12‚"widht":12‚"filePath":30‚"format":123‚"bitRate":1111‚"exe":"m"}‚{"duration":12222‚"height":12‚"widht":12‚"filePath":30‚"format":123‚"bitRate":1111‚"exe":"m"}‚{"duration":12222‚"height":12‚"widht":12‚"filePath":30‚"format":123‚"bitRate":1111‚"exe":"m"}‚{"duration":12222‚"height":12‚"widht":12‚"filePath":30‚"format":123‚"bitRate":1111‚"exe":"m"}]

When I am using JQuery to parse it as follows:
$jQ.each($jQ.parseJSON(responseJSON), function(idx, obj) {
    alert(obj.filePath);
});

I am getting JS error as JSON.parse: expected property name or '}'
I am not getting why this error is occuring.

A: According to jsonlint.com, you should put values into "".
Because of the special character &

A: Just looking at the first few lines:
[{"duration":12222‚"height":12‚
This doesn't appear to be valid json. duration is the key and the value is 12222 which is Integer, however you also have string data ‚ next to the int, which makes this invalid json data.
If you have mixed data, encapsulate it with double quote to treat it as a string.

Update
, is html encoded to ‚ - there's your problem.
Try this json string:
[
    {
        "duration": 12222,
        "height": 12,
        "widht": 12,
        "filePath": 30,
        "format": 123,
        "bitRate": 1111,
        "exe": "m"
    },
    {
        "duration": 12222,
        "height": 12,
        "widht": 12,
        "filePath": 30,
        "format": 123,
        "bitRate": 1111,
        "exe": "m"
    },
    {
        "duration": 12222,
        "height": 12,
        "widht": 12,
        "filePath": 30,
        "format": 123,
        "bitRate": 1111,
        "exe": "m"
    },
    {
        "duration": 12222,
        "height": 12,
        "widht": 12,
        "filePath": 30,
        "format": 123,
        "bitRate": 1111,
        "exe": "m"
    }
]

this now validates.

A: Your java environment may be serializing the array incorrectly.
Instead of ' - single bottom quote U+201A - you should have a comma (, U+002C).


text:
Q: Data.com Match Criteria I am having some issues getting matches using the Data.com Match API.  I am able to get matches using the Google example in Data.com's documentation, however, I have been unsuccessful when trying to match other companies.  I am using Fiddler to make the requests.
I know that the attributes property has to come first, but does order matter on any of the other properties?  I have tried ordering my properties to match the Google example, but still had no luck.  Are there certain properties that will increase my chance of a match?  Has anyone else had any luck matching using this API and, if so, could you provide some guidance?
I am submitting a request with the following companies as entities:

{
  "entities": [
    {
      "attributes": {
        "type": "DatacloudCompany"
      },
      "Name": "Google",
      "Website": "www.google.com",
      "Phone": "+1.650.253.0000",
      "City": "Mountain View"
    },
    {
      "attributes": {
        "type": "DatacloudCompany"
      },
      "Name": "Bob Evans Farms",
      "Website": "www.bobevans.com",
      "Phone": "+1.614.491.2225",
      "City": "New Albany"
    }
  ],
  "fields": [
    "AnnualRevenue",
    "City",
    "CompanyId",
    "Country",
    "Description",
    "DunsNumber",
    "Fax",
    "Industry",
    "IsInactive",
    "NaicsCode",
    "NaicsDesc",
    "Name",
    "NumberOfEmployees",
    "Ownership",
    "Phone",
    "Sic",
    "SicDesc",
    "State",
    "TickerSymbol",
    "TradeStyle",
    "Website",
    "YearStarted",
    "Zip",
    "Site"
  ]
}

I am receiving the following response:

[
  {
    "errorCode": 0,
    "errorMessage": null,
    "matchRecords": [
      {
        "entity": {
          "attributes": {
            "type": "DatacloudCompany"
          },
          "Name": "Google, Inc.",
          "Website": "www.google.com",
          "SicDesc": "Information Retrieval Services",
          "DunsNumber": "000215043",
          "Phone": "+1.650.253.0000",
          "TickerSymbol": "GOOG",
          "CompanyId": 215043,
          "AnnualRevenue": 7.517914E+08,
          "NumberOfEmployees": 6150,
          "Zip": "94043-1351",
          "NaicsCode": "517919",
          "Description": "",
          "Site": "Headquarters",
          "Fax": "",
          "YearStarted": "1997",
          "Country": "United States",
          "City": "Mountain View",
          "State": "CA",
          "TradeStyle": "",
          "NaicsDesc": "All Other Telecommunications",
          "IsInactive": false,
          "Ownership": "Public",
          "Sic": "7375",
          "Industry": "Technology"
        },
        "matchDiffs": [
          "Name"
        ]
      }
    ]
  },
  {
    "errorCode": 0,
    "errorMessage": null,
    "matchRecords": []
  }
]

Thanks!


text:
Q: Link text thicker than normal text How can I make the text below thicker while keeping the links as they are?
li
{
    list-style-type:none;
    font-size: 14px;
    line-height:28px;
    font-weight:thick
}

a:link
{
color:#3399CC;
}

...

Im happy as I am&nbsp-&nbspI want to be less thick

Im also happy as I am&nbsp-&nbspI also want to be less thick

A: It looks like you want the links to be bolded and the text to be less thick (ie not-bolded)
Look at the code below, same as yours except I defined font-weight:normal; in the
 and font-weight:700; in your  tags. Here's the working example.
Try this in your code:
li
{
    list-style-type:none;
    font-size: 14px;
    line-height:28px;
    font-weight:normal;
}

a:link
{
font-weight: 700;
color:#3399CC;
}

Im happy as I am&nbsp-&nbspI want to be less thick

Im also happy as I am&nbsp-&nbspI also want to be less thick

A: I think this code has an answer your query.

Im happy as I am  I want to be less thick

Im also happy as I am  I also want to be less thick

    hree


text:
Q: Benchmarking Cordova vs Titanium app Context: At our university a Javascript library for mobile peer-to-peer programming has been developed. Originally, it used Titanium in order to be cross platform. However, if the programmer wants to use our library he needs to use Titanium. Hence, my job was to make it independent of the framework, and adding support for Cordova. Now people can use our library in both, Titanium and Cordova.
I developed an application which uses the library, once in Titanium and once in Cordova. As a last step, we want to compare both versions, using some benchmarks.
We had in mind to compare :

*

*CPU usage

*Memory usage

*Communication speed

*UI responsiveness (if possible?)

For the communication speed between two peers, I had in mind to mark each message with a timestamp at the moment of sending and receiving. Then send a big amount of messages and compute the average.
For CPU and memory usage, i had a look in the Titanium and Cordova docs. In Titanium i found Titanium.Platform.availableMemory. However, i still need to find how i can acces the total memory such that i can monitor the memory usage by doing Total Memory - Titanium.Platform.availableMemory and again compute an average.
Furthermore, i need a way to do the same in Cordova.
I was not able to find a way to access CPU usage of the device. And I am wondering how i could monitor UI responsiveness.
For Cordova, i found an interesting article on automating performance audits.

A: You will never get 100% reliable data by looking at the API's of both platforms. You will need to use the native inspectors.
For example, xCode has pretty good inspectors build in to monitor CPU and memory usage for example. Android has something similar too.
If you "build" for device with Titanium (where I have experience with) it will generate an xCode project for you. This one can be opened by Xcode, and from there you can build it again for device and use the monitoring tools. Cordova projects will do something similar I guess. Not sure how those compile.


text:
Q: Joining two different ContainerBuilder I'm migrating from ASP.Net Framework to ASP.Net Core (3.1) application. I'm new on this. Depency Inyection is managed by Autofac in my old project. So I need to replicate the behavieur.
I need a ConfigureContainer in my Startup class. Something like that:
public class Startup
{

    public void ConfigureContainer(ContainerBuilder builder)
    {
        // Register your own things directly with Autofac, like:

        builder.RegisterType<MyFoo>().As<IMyFoo>();
    }
}

By the other hand, i have some dependencies from Bootstrapper class. Bootstrapper is a class from another project.
This class is called by others project so i can't remove it. It's a kind of BaseContainer with some services that they are used by other projects.
public sealed class  BootStraper
{
    public ContainerBuilder Builder { get; set; }

    public BootStraper()
    {

        Builder = new ContainerBuilder();
        Builder.RegisterType(typeof(Foo1));
        Builder.RegisterType(typeof(Foo2));
        Builder.RegisterType(typeof(Foo3));
        Builder.RegisterType(typeof(Foo4));
        Builder.RegisterType(typeof(Foo5));
   }

   public void RegisterTypeSingleton(Type type)
   {
        Builder.RegisterType(type).SingleInstance();
   }
}

I would like to join both ContainerBuilder in one. How can i do this?
I saw Update() method to do this but it seems it's obsolete
Any Idea?

A: The official site from Autofac: asp-net-core-3-0-and-generic-hosting describes how to integrate with NetCore and Autofac. I also followed this tutorial to accomplish similar requirement like yours.
Just need to change BootStraper class a little bit to become derived class of Autofac.Module. Thus, you can get benefits by just adding very few and clear codes in Startup.cs like this
Startup.cs
public void ConfigureContainer(Autofac.ContainerBuilder builder)
{
    // Register your custom BootStraper types here
    // If the ordering matters, just swtich this to the first or last line
    builder.RegisterModule<BootStraper>();

    // Register your own things directly with Autofac, like:
    builder.RegisterType<MyFoo>().As<IMyFoo>();
}

BootStraper.cs
public sealed class  BootStraper : Autofac.Module
{
    // public ContainerBuilder Builder { get; set; }
    protected override void Load(Autofac.Containerbuilder builder)
    {
        base.Load(builder);

        builder.RegisterType(typeof(Foo1));
        builder.RegisterType(typeof(Foo2));
        builder.RegisterType(typeof(Foo3));
        builder.RegisterType(typeof(Foo4));
        builder.RegisterType(typeof(Foo5));

        // RegisterTypeSingleton() could be replaced by either
        // 1.registering directly here or
        // 2.putting in ConfigureContainer() section in Startup
        builder.RegisterType(typeof(Foo6)).SingleInstance();
    }

   //public void RegisterTypeSingleton(Type type)
   //{
   //     Builder.RegisterType(type).SingleInstance();
   //}
}

Don't forget to add this line while creating host builder.
hostBuilder.UseServiceProviderFactory(new AutofacServiceProviderFactory())

This autofac extension is the NuGet package from Autofac.Extensions.DependencyInjection.


text:
Q: Problem with side by side equation tag and custom tag style Consider the following MWE:
\documentclass{article}
\usepackage{mathtools}
\usepackage{amsmath}

\newtagform{brackets}{[}{]}
\usetagform{brackets}

\AtBeginDocument{\let\latexlabel\label}

\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linkcolor=black,
    filecolor=black,
    urlcolor=black,
}
\urlstyle{same}

\begin{document}

\begin{equation*}
\refstepcounter{equation}\latexlabel{a}
\refstepcounter{equation}\latexlabel{c}
\refstepcounter{equation}\latexlabel{e}
a=b\quad c=d\quad e=f
\tag{\ref*{a},$,$ \ref*{c},$,$ \ref*{e}}
\end{equation*}

\end{document}

When I compile it, it doesn't show the third tag and gives me two errors:

*

*paragraph ended before @firstoffive was complete

*argument of @firstoffive has an extra }
I think the problems are due to the hyperref package because by removing it and substituting \tag* with \tag it doesn't give me any error whatsoever. In addition, when using hyperref I've to manually insert the commas in a math environment in order for them to be shown.
What are those errors? How can I get rid of them and have the file to compile correctly?
Thank you for your time, it is very appreciated.
Edit:
For more clarity, this is what the code erringly compiles to:

This is how I want it to compile, and how correctly compiles without using the hyperref package:

A: In order for the code to compile correctly, \AtBeginDocument{\let\latexlabel\label} has to be loaded after the hyperref package. Doing so, not only the code compiles correctly but the commas in the math environment can and should be removed too.


text:
Q: Best way to make factor levels uniform over a number of data frames I have a number of data.frames that each have a factor.  I want to make sure that they all use the same levels.  What is the proper way to do this?
In the code below you'll see that I reassign the factor for each case using levels from the overall set of levels with a small convenience function changeLevels. I would expect that there is a better way to do this though.
set.seed(1234)
b<-round(runif(100,1,10),digits=2)
set.seed(2345)
b2<-round(runif(100,11,20),digits=2)
set.seed(3456)
b3<-round(runif(50,15,18),digits=2)

#.. all potential levels
bt<-factor(sort(c(b,b2,b3)))
lvls<-levels(bt)

t1<-as.data.frame(table(sample(b,5)))
t2<-as.data.frame(table(sample(b,1)))
t3<-as.data.frame(table(sample(b,1)))
t4<-as.data.frame(table(sample(b,8)))
t5<-as.data.frame(table(sample(b2,20)))
t6<-as.data.frame(table(sample(b3,18)))

t1<-cbind(t1,p="A")
t2<-cbind(t2,p="B")
t3<-cbind(t3,p="C")
t4<-cbind(t4,p="D")
t5<-cbind(t5,p="E")
t6<-cbind(t6,p="F")

d<-data.frame()
d<-rbind(d,t2,t3,t6,t4,t5,t1)

#.. out of order bins
ggplot(d,aes(x=factor(Var1),fill=factor(p))) +
  geom_bar(aes(weight=Freq)) +
  facet_grid( p ~ ., margins=T)+
  ggtitle("out of order bins")

changeFactor<-function(t,lvls){
  temp<-as.numeric(as.character(t))
  factor(temp,levels=lvls)
}

t1$Var1<-changeFactor(t1$Var1,lvls)
t2$Var1<-changeFactor(t2$Var1,lvls)
t3$Var1<-changeFactor(t3$Var1,lvls)
t4$Var1<-changeFactor(t4$Var1,lvls)
t5$Var1<-changeFactor(t5$Var1,lvls)
t6$Var1<-changeFactor(t6$Var1,lvls)

d<-data.frame()
d<-rbind(d,t2,t3,t6,t4,t5,t1)

#.. in order bins
ggplot(d,aes(x=factor(Var1),fill=factor(p))) +
  geom_bar(aes(weight=Freq)) +
  facet_grid( p ~ ., margins=T)+
  ggtitle("in order bins")

A: I think your way "reading" the factors with as.character is the best way when you don't know all their "true" levels.
But since you do know them (they are all stored inside lvls), why not using them directly when you build your ti$Var1 vectors? That is, instead of :
ti = as.data.frame(table(sample(b,5)));                 # automately creates a factor vector ti$Var1 with what is found inside the sample as levels
ti$Var1 = factor(as.character(ti$Var1), levels = lvls); # replaces it with a new factor, created by reading each value of the previous one and assigning it a level from lvls

(which is ultimately what you do),
do directly:
tab = table(sample(b,5));
ti = data.frame(myVar  = factor(names(tab), lvls)       # creates directly the right factor vector with levels drawn from lvls
              , myFreq = as.numeric(tab)
              );

(which is ultimately what you want) (and 'even allows you better control on the names of ti's columns)
Or else, but you will then get empty lines:
factoredSample = factor(sample(b,5), lvls);             # directly associates each drawn value with a level from lvls
ti = as.data.frame(table(factoredSample));              # and table will then also count the non-represented levels within factoredSample

(By the way, I don't know whether or not this was only for asking-the-question purposes, but if you really have to handle so many almost-identical data.frames in your script, you are probably using the wrong data structure.)

A: short answer: keep your data in lists and learn the *pply family
set.seed(1234)
b<-round(runif(100,1,10),digits=2)
set.seed(2345)
b2<-round(runif(100,11,20),digits=2)
set.seed(3456)
b3<-round(runif(50,15,18),digits=2)

#.. all potential levels
bt<-factor(sort(c(b,b2,b3)))
lvls<-levels(bt)

options(stringsAsFactors = FALSE)
f <- function(x, y, z)
  cbind(data.frame(table(sample(x, y))), p = z)

datl <- Map(f, list(b,b,b,b,b2,b3), c(5,1,1,8,20,18), LETTERS[1:6])

changeFactor<-function(t,lvls){
  temp<-as.numeric(as.character(t))
  factor(temp,levels=lvls)
}

datl <- lapply(rapply(datl, f = function(x) changeFactor(x, lvls),
                     classes = 'factor', how = 'replace'),
              data.frame)

d <- do.call(rbind, datl[c(2, 3, 6, 4, 5, 1)])

#.. in order bins
ggplot(d,aes(x=factor(Var1),fill=factor(p))) +
  geom_bar(aes(weight=Freq)) +
  facet_grid( p ~ ., margins=T)+
  ggtitle("in order bins")

long answer:
set.seed(1234)
b<-round(runif(100,1,10),digits=2)
set.seed(2345)
b2<-round(runif(100,11,20),digits=2)
set.seed(3456)
b3<-round(runif(50,15,18),digits=2)

#.. all potential levels
bt<-factor(sort(c(b,b2,b3)))
lvls<-levels(bt)

first, I don't want any unexpected factors popping up, so stringsAsFactors = FALSE
then write a function, f, to do what you want, and check to make sure it works
options(stringsAsFactors = FALSE)
f <- function(x, y, z)
  cbind(data.frame(table(sample(x, y))), p = z)

f(b, 5, 'A')

#   Var1 Freq p
# 1 1.13    1 A
# 2 1.46    1 A
# 3 2.09    1 A
# 4  2.5    1 A
# 5 7.02    1 A

seems to work, so just Map it to lists of arguments and check the output
datl <- Map(f, list(b,b,b,b,b2,b3), c(5,1,1,8,20,18), LETTERS[1:6])

# List of 6
# $ :'data.frame':  5 obs. of  3 variables:
#   ..$ Var1: Factor w/ 5 levels "2.02","3.09",..: 1 2 3 4 5
#   ..$ Freq: int [1:5] 1 1 1 1 1
#   ..$ p   : chr [1:5] "A" "A" "A" "A" ...
# $ :'data.frame':  1 obs. of  3 variables:
#   ..$ Var1: Factor w/ 1 level "1.63": 1
#   ..$ Freq: int 1
#   ..$ p   : chr "B"

so combine everything to use with ggplot
d <- do.call(rbind, datl[c(2, 3, 6, 4, 5, 1)])

library(ggplot2)
#.. out of order bins
ggplot(d,aes(x=factor(Var1),fill=factor(p))) +
  geom_bar(aes(weight=Freq)) +
  facet_grid( p ~ ., margins=T)+
  ggtitle("out of order bins")

changeFactor<-function(t,lvls){
  temp<-as.numeric(as.character(t))
  factor(temp,levels=lvls)
}

again making sure the function does what it is supposed to do on one data frame
changeFactor(datl[[1]]$Var1, lvls)

# [1] 2.02 3.09 3.79 3.89 8.3
# 234 Levels: 1.09 1.12 1.13 1.24 1.36 1.38 1.41 1.46 1.63 1.66 1.81 1.95 ... 19.86

so apply it again to them all at once and check the output
datl <- lapply(rapply(datl, f = function(x) changeFactor(x, lvls),
                     classes = 'factor', how = 'replace'),
              data.frame)
str(datl)
# List of 6
# $ :'data.frame':  5 obs. of  3 variables:
#   ..$ Var1: Factor w/ 234 levels "1.09","1.12",..: 13 28 41 45 81
#   ..$ Freq: int [1:5] 1 1 1 1 1
#   ..$ p   : chr [1:5] "A" "A" "A" "A" ...
# $ :'data.frame':  1 obs. of  3 variables:
#   ..$ Var1: Factor w/ 234 levels "1.09","1.12",..: 9
#   ..$ Freq: int 1
#   ..$ p   : chr "B"
# ...

combine again and plot
d <- do.call(rbind, datl[c(2, 3, 6, 4, 5, 1)])

#.. in order bins
ggplot(d,aes(x=factor(Var1),fill=factor(p))) +
  geom_bar(aes(weight=Freq)) +
  facet_grid( p ~ ., margins=T)+
  ggtitle("in order bins")


text:
Q: NullReferenceException with Assert.That and NunitLite I'm using NunitLite for my unit testing for a Xamarin project.
Environment:

*

*Windows 8.1 64 bit

*Visual Studio 2012

*Test project class library referencing .NET 4.5

*NunitLite V1.0.0 package from NuGet - contains a build for .NET 4.5

*Running tests using Nunit Test Adapter V1.2 from NuGet

With even the simplest test:
[Test]
public void SimpleTest()
{
    Assert.That(1 == 1);
}

I'm getting the exception:

System.NullReferenceException was unhandled by user code
  HResult=-2147467261   Message=Object reference not set to an instance
  of an object.   Source=nunitlite   StackTrace:
         at NUnit.Framework.Assert.IncrementAssertCount()
         at NUnit.Framework.Assert.That(Object actual, IResolveConstraint expression, String message, Object[] args)
         at NUnit.Framework.Assert.That(Boolean condition)
         at SportLogger.Tests.Unit.Core.when_using_venue_manager.SimpleTest() in
       c:\SportLogger\SportLogger.Tests.Unit.Core\CoreTests.cs:line 65   InnerException:

Does anyone have any pointers as to what the problem is?

A: I solved this by using standard Nunit, not NunitLite. I'm not sure why NunitLite doesn't work in a standard Windows test library.
Bearing in mind that NunitLite is meant to be used (in this context) on the iOS and Android projects, switching to Nunit for the core test project, and NunitLite for the iOS and Android test projects fixed the problem.


text:
Q: Specifying specific jar files with maven in ~/.m2/path/to/jarfiles there are to jar files. One is dependencyName.jar and the other is dependencyName-runtime.jar I am trying to use the maven-dependency-plugin to copy the runtime version of the jar but it keeps copying the regular version of the jar.
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>${maven.dependency.version}</version>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>org.jacoco</groupId>
                                <artifactId>org.jacoco.agent</artifactId>
                                <version>${code.coverage.jacoco.version}</version>
                                <type>jar</type>
                                <overWrite>false</overWrite>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

A: Assuming that runtime is a classifier, you should add
<classifier>runtime</classifier>

to your artifactItem.


text:
Q: Setting config values with Powershell I have the following code:
#Set the .config settings
$appSettings = (Get-AzureWebsite -Name $webAppName -Slot $SlotName).AppSettings
$conStrings = (Get-AzureWebsite -Name $webAppName -Slot $SlotName).ConnectionStrings

$xmlDocument = New-Object XML
$path = (Get-ChildItem -Path ${location} -Filter "*.exe.config" -Recurse).Fullname
$xmlDocument.Load($path)

foreach($setting in $XmlDocument.configuration.appSettings.ChildNodes)
{
  $setting.Value = $appSettings[$setting.Key].Value
}

$xmlDocument.Save($path)

and I get the following error when I run this (context is Octopus)
Invoke-Expression : Cannot set "value" because only strings can be used as values to set XmlNode properties.

I can't seem to figure this out as I was expecting the Value to be a string. I am trying to set the values in the xml to be the same as those from the Azure dashboard appsettings (and config strings) but I just cannot get this to work.
How do I correctly set each of the settings?

A: This is what works for me in the end:
#Set the .config settings
$appSettings = (Get-AzureWebsite -Name $webAppName -Slot $SlotName).AppSettings
$conStrings = (Get-AzureWebsite -Name $webAppName -Slot $SlotName).ConnectionStrings

#Load xml config file
$xmlDocument = New-Object XML
$path = (Get-ChildItem -Path ${location} -Filter "*.exe.config" -Recurse).Fullname
$xmlDocument.Load($path)

#Update settings from appSettings
foreach($setting in $appSettings.GetEnumerator())
{

    $targetNode = $XmlDocument.SelectSingleNode("//configuration/appSettings/add[@key='$($setting.Name)']")
    if($targetNode -ne $null)
    {
        Write-Host "Target: $($targetNode.Key) being set to $($setting.Value)"
        $targetNode.Value = $setting.Value
    }
    else
    {
        Write-Host "Target Node was null"
        Write-Host "Setting was Key: $($setting.Name) Value: $($setting.Value)"
    }
}

#Update connection string section
foreach($setting in $conStrings.GetEnumerator())
{
    $targetNode = $XmlDocument.SelectSingleNode("//configuration/connectionStrings/add[@name='$($setting.Name)']")
    if($targetNode -ne $null)
    {
        Write-Host "Target: $($targetNode.Name) being set to $($setting.connectionString)"
        $targetNode.connectionString = $($setting.connectionString)
    }
    else
    {
        Write-Host "Target Node was null"
        Write-Host "Setting was Key: $($setting.Name) Value: $($setting.connectionString)"
    }
}

$xmlDocument.Save($path)

I am fairly new to Powershell and I must have made every mistake going while doing this but it is done now and I have learned something useful. \0/


text:
Q: Issue with CDN strong caching without Cache-Control or Expires headers We're using Azure CDN to serve images, and I'm trying to understand why images are being strong-cached by web browsers even though there is no Cache-Control or Expires headers in the image response.
For example, the following response headers are returned for an image from Azure CDN:
HTTP/1.1 200 OK
Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Content-MD5: KuQCJm6GQyEjejWwmRgRwQ==
Content-Type: image/jpeg
Date: Tue, 21 Nov 2017 00:15:57 GMT
Etag: 0x8D523228F0F4C42
Last-Modified: Sat, 04 Nov 2017 01:22:47 GMT
Server: ECAcc (meb/A744)
X-Cache: HIT
x-ms-blob-type: BlockBlob
x-ms-lease-status: unlocked
x-ms-request-id: 00822b7c-001e-0045-4194-61d246000000
x-ms-version: 2009-09-19
Content-Length: 5143

<<image data>>

As you can see there is an Etag header returned, but no Cache-Control or Expires headers.
When tracing the network traffic (using Fiddler) from the browser (Chrome), we are NOT seeing any subsequent requests for these images.
My understanding of Etags is that subsequent requests for this image should be sent back to the server (weak caching), and then the server can return a 304 not modified response if the file has not changed.
Can anyone shed any light on this?

A: I think you need the header cache-control: must-revalidate to get the browser to check the source and have 304 mot modified returned if there is no change.
This is not optimal in terms of caching though.
You are better to invalidate the js with QS changes ("v=??") or set a short expires / max-age header (60 / 120 seconds, or whatever you can handle in terms of deployment, 5 minutes???).
Having an expires header combined with etags should still mean the browser receives a 304 not modified from the server after expiration.


text:
Q: Monetdb Loader Function Issue - Embedded Python 3 has not been installed This is the error when trying to run a Python loader function through mclient.
TypeException:user.main[4]:'pyapi3.eval' undefined: Embedded Python 3 has
not been installed. Please install it first, then start server with --set embedded_py=3

When typing monetdb get all I can see that embedpy3 is set to yes because I have already done the -- set embedded_py3=yes.
I have installed monetdb through homebrew on macos.

A: The homebrew version of MonetDB was built with the option -DPY3INTEGRATION=OFF, in other words, there is no Python integration in the homebrew version.
If you want, you can try to compile it yourself using the homebrew formula after changing that OFF into ON.

A: As Sjoerd said, the default homebrew build has the CMake option -DPY3INTEGRATION=OFF, which turns off embedded python3 functions.
To install it with this option turned on, you'll need to edit the brew formula and compile it from source (through brew).
First, uninstall the current package:
brew uninstall monetdb
brew cleanup -s monetdb

Then, edit the brew formula:
brew edit monetdb

Find "-DPY3INTEGRATION=OFF" and change it to "-DPY3INTEGRATION=ON"
Finally, install it from source, using the new formula:
brew install -s monetdb

Make sure you have python3 and numpy installed, otherwise it won't work.
NOTE: This still might fail if you have multiple python installations and the one used in the build process does not have numpy installed. In that case, reach out and we'll help you.


text:
Q: Can still see CONSTRAINTs after running ALTER TABLE [mysch].[mytablename] NOCHECK CONSTRAINT ALL but why? I am looking at a piece of code in a proc that seems to disable but never reenable constraints, namely
ALTER TABLE [mysch].[mytablename] NOCHECK CONSTRAINT ALL

but after the actions are taken in the code below, there is nothing to reenable them.
I even tried just running that 'NOCHECK' statement as a single line to see what happens i.e. ignoring the rest of the code in the proc.
I am assuming they are still enabled because if I go to Object Explorer, Tables (plus a right click 'refresh') then script the table out, I can see dozens of lines like
ALTER TABLE [mysch].[mytablename]  WITH NOCHECK ADD  CONSTRAINT [FK_mytable_othertable] FOREIGN KEY([othertable_ID])
REFERENCES [mysch].[othertable] ([othertable_ID])
GO

What is going on here?
I have trawled other objects using Red Gate's SQL Search to look for ALTER TABLE..CHECK statements to no avail.
Is object explorer incorrectly displaying the constraints or is something else at work here?

A: What is going on here?
Someone "disabled" all the constraints on a table, which is somewhat common before large data modifications when the process of checking the constraints slows the process down more than re-enabling them later.
Just because constraints are not checked doesn't mean they're dropped. You can see the NOCHECK syntax in the constraint syntax that you copied in.
You can see which constraints might be disabled, or not trusted, by querying views describing them:
SELECT
    c.name,
    c.is_not_trusted,
    c.is_disabled
FROM sys.check_constraints AS c
WHERE c.is_not_trusted = 1
OR    c.is_disabled = 1;

SELECT
    f.name,
    f.is_not_trusted,
    f.is_disabled
FROM sys.foreign_keys AS f
WHERE f.is_not_trusted = 1
OR    f.is_disabled = 1;

For more details, see my posts:

*

*Data Loading and Referential Integrity

*Untrusted Foreign Keys Still Check New Data
Scripts to re-enable/trust constraints (reproduced from the first link):
SELECT N'ALTER TABLE '
       + QUOTENAME(s.name)
       + N'.'
       + QUOTENAME(o.name)
       + N' WITH CHECK CHECK CONSTRAINT '
       + QUOTENAME(f.name) AS utrusted_fk
FROM sys.foreign_keys AS f
INNER JOIN sys.objects AS o
    ON f.parent_object_id = o.object_id
INNER JOIN sys.schemas AS s
    ON o.schema_id = s.schema_id
WHERE f.is_not_trusted = 1;

SELECT N'ALTER TABLE '
       + QUOTENAME(s.name)
       + N'.'
       + QUOTENAME(o.name)
       + N' WITH CHECK CHECK CONSTRAINT '
       + QUOTENAME(c.name) AS utrusted_ck
FROM sys.check_constraints AS c
INNER JOIN sys.objects AS o
    ON c.parent_object_id = o.object_id
INNER JOIN sys.schemas AS s
    ON o.schema_id = s.schema_id
WHERE c.is_not_trusted = 1;

A: ANSI SQL is very confusing in its syntax. You have two aspects of a constraint:

*

*Is it enabled or disabled?

*If there a potential for having "invalid" data in the table?

For point 2 above, there are two scenarios

*

*You added the constraint without checking existing data

*You disable the constraint and then when you re-enabled it, you didn't check existing data.

The syntax is confusing because it uses the words CHECK for both the concept of "check existing data" and "enable or disable the constraint". This lead to commands such as below. There are no typos in below code!
--Enable constraint without checking existing data
ALTER TABLE t WITH NOCHECK CHECK CONSTRAINT t_ch

--Enable constraint AND check existing data
ALTER TABLE t WITH CHECK CHECK CONSTRAINT t_ch

There is, as Erik show us, meta-data with which you can check this.

*

*The is_not_trusted column tell us whether you added or enabled the constraint without checking existing data (WITH CHECK or WITH NOCHECK)

*The is_disabled tell us if the constraint is enabled or disabled (CHECK or NOCHECK)

I wished that ANSI would have chosen the words DISABLE and ENABLE to disable and enable a constraint, that would make the commands much easier to understand...
Examples with comments:
USE tempdb
GO

DROP TABLE IF EXISTS t
GO

CREATE TABLE t(c1 int)
GO

--Add the constraint without checking existing data
ALTER TABLE t WITH NOCHECK ADD CONSTRAINT t_ch CHECK(c1 > 10)
GO

--Constraint is enabled, below fails
INSERT INTO t VALUES (1)
GO

--Disable constraint
ALTER TABLE t NOCHECK CONSTRAINT t_ch
GO

--Constraint is NOT enabled, below executes successfully
INSERT INTO t VALUES (1)
GO

--Enable constraint without checking existing data
ALTER TABLE t WITH NOCHECK CHECK CONSTRAINT t_ch
GO

--Constraint is enabled, below fails
INSERT INTO t VALUES (1)
GO

--Disable constraint
ALTER TABLE t NOCHECK CONSTRAINT t_ch
GO

--Enable constraint AND check existing data, command fails because of invalid data in table
ALTER TABLE t WITH CHECK CHECK CONSTRAINT t_ch
GO

--Check of data in a table violates a constraint (not ANSI SQL, obviouly)
DBCC CHECKCONSTRAINTS(t_ch)


text:
Q: Await / async - async method runs in Main Thread I just started to learn Async/Await, and I've got a problem. There is a WinForms App with 2 buttons and permanently running status-bar on it. When pressing first button - everithing is fine - cicle running in another thread and UI doesn't freeze. When pressing second - cicle running in Main Thread, so UI freeze. I just can't get it! Why? For me this methods look almost the same. Btw sry my bad english.
 Public Class Form1
    'Async - Create Task from Sync Method
    Private Async Sub btn_async_from_sync_Click(sender As Object, e As EventArgs) Handles btn_async_from_sync.Click
        Dim tsk As New Task(Of Integer)(AddressOf func_for_task)
        tsk.Start()
        Dim val As Integer = Await tsk
        MsgBox(val)
    End Sub
    Private Function func_for_task() As Integer
        Dim val As Integer
        For i = 1 To 999999999
            val += 1
        Next
        Return val
    End Function
    'Async - Use existing Task - Async Method
    Private Async Sub btn_async_use_task_Click(sender As Object, e As EventArgs) Handles btn_async_use_task.Click
        Dim tsk As Task(Of Integer) = func_for_task_async()
        Dim val As Integer = Await tsk
        MsgBox(val)
    End Sub
    Private Async Function func_for_task_async() As Task(Of Integer)
        Dim val As Integer
        For i = 1 To 999999999
            val += 1
        Next
        Return val
    End Function
End Class

A: Don't ignore compiler warnings. In this case, the compiler will warn you that your async method does not use await, and therefore will run synchronously.
In your case, you can use Task.Run to execute func_for_task on a background thread, and await it from your click event handler.
For more info, see the async/await intro on my blog.


text:
Q: Python ValueError: Inserting a list of values using df.loc I have a dataframe df with paths of images. I am performing object detection and want to save the names of the detected objects in a new column (named objects) of the dataframe.
However the code works fine when only 1 object is detected, when there is a list of multiple objects the code gives an error.
ValueError: cannot set using a multi-index selection indexer with a different length than the value
I think there is some problem with my way of inserting values in the dataframe. I have actually created an empty column first and then using loop inserting vaues in the objects column.
Code
train_image_paths = 'data/train_images/' + df['image']    # train_images is the folder containing images and
                                                          #  df['image'] contains all image paths

df['objects'] = ''     # Creating an empty column for storing detected objects

for idx, img in enumerate(train_image_paths):
    ..
    #object detection code    # Performs object detection and
                              # stores the detected objects in a list named detected_objects
    ..

    df.loc[idx, 'objects'] = detected_objects   # Adding the detected objects to the dataframe

return df

Output of df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 34250 entries, 0 to 34249
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   image   34250 non-null  object
dtypes: object(1)
memory usage: 267.7+ KB

A: I think you should create new list or Pandas Series then append it to dataframe.
train_image_paths = 'data/train_images/' + df['image']    # train_images is the folder containing images and
                                                          #  df['image'] contains all image paths

objects = []     # Creating an empty column for storing detected objects

for idx, img in enumerate(train_image_paths):
    ..
    #object detection code    # Performs object detection and
                              # stores the detected objects in a list named detected_objects
    ..

    objects.append(detected_objects)   # Adding the detected objects to the dataframe

df['objects'] = objects
return df

Here is the references: https://www.geeksforgeeks.org/adding-new-column-to-existing-dataframe-in-pandas/

A: Use Series.apply with custom function:
def func(x):
    train_image_paths = 'data/train_images/' + x
    #object detection code
    return detected_objects

df['objects'] = df['image'].apply(func)


text:
Q: Building an app for PC and Android questions So I am looking into building an application that would be for PC and Android devices. Of course they would have different UI but I am trying to figure out where to start with them both using the same back end.
So it would be a quiz game lets say. They would have similar but difference interfaces but they would using the similar backend logic. Anyone have good references to start with. I don't want to end up doing more then I need to. Also trying to figure out what I want to work in. Seems like I would have to use Java and Oracle, but I much rather use C# and SQL.

A: There is no good answer to your question. If I were you, a would create a separated business logic and serve it via Webservices. All UI can implement that interface. By the way there some compact solutions for UI what can run on PC (browser) and on Android (browser or native). What technology you use, depends on the needs and your opinion. If you have big data, you should not use SQL for example. Most of us developing under "Java" on android, so there are many material in that topic. On the server side, you have infinity choice. ;)


text:
Q: Find median of a set of Data in matlab then find Average of that data I am trying to take an input such as:
StarT:
2141865 16
2141865 17
2141865 17
2141865 16
2141865 17
2141865 20
2141865 9
2141865 7
2141865 19
2141865 18
2141865 19
2141865 9
2141865 9
2141865 9
2141865 9
2301367 11
2301367 21
2301367 12
2301367 10
2301367 10
2301367 11
2301367 10
2301367 10
2301367 19
2301367 12
2301367 19
2301367 10
2301367 10
2301367 18
2301367 23
2308980 16
2308980 17

into matlab and find the median of the second column with respect to the first column as an index(matching data sets). I also need to then take the mean of that set of data with certain conditions, such as if the original value is within a certain rang (1.5* larger or smaller) then it must adjust the original value to be either 1.5* bigger or smaller (depending on the difference between it and the mode). I have tried the following code and it is giving me close results but not exactly what I need:
(I do not have the below code setup for calculating the averages as I cannot figure out how to go about that until the mode is correct)
function Mode_Koi_2

StarData = evalin('base', 'StarP');

global medians;

[medians, ~, Groups] = unique(StarData(:,1),'stable');
medians = [medians, accumarray(Groups, StarData(:,2), [], @median)];

end

Now all I need is a loop or accumarray function to compare the median values in 'medians' with the original values for the corresponding ID in 'StarP', and subsequently adjust them if there is the need to (if the value of the original data is smaller or larger as stated above), then find the average of StarP.

A: [medians, ~, Groups] = unique(StarT(:,1),'stable');
medians = [medians, accumarray(Groups, StarT(:,2), [], @median)]

results in
medians =

     2141865           9
     2301367          10
     2308980          16


text:
Q: Get data from key categories in elasticsearch I have these documents:
curl -XPOST -H 'Content-Type: application/json' "http://localhost:9200/test/_bulk?pretty" -d'
{"index":{"_index":"test","_type":"product"}}
{"id_product":"1", "categories":[1,2] }
{"index":{"_index":"test","_type":"product"}}
{"id_product":"2", "categories":[25,28] }

I need to get categories only.
Can I get an output similar to this?
[1,2,25,28]

A: I think there's no way to tell ES to return only categories, but you might use terms aggregation in order to extract all categories that search context have.
Example:
{
  "size":0,
  "aggs":{
    "byCategory":{
      "terms":{
        "field": "categories"
      }
    }
  }
}

This will return something like:
{
  "aggregations": {
    "byCategory": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 1,
          "doc_count": 1
        },
        {
          "key": 2,
          "doc_count": 1
        },
        {
          "key": 25,
          "doc_count": 1
        },
        {
          "key": 28,
          "doc_count": 1
        }
      ]
    }
  }
}

As you see, now you can iterate through buckets.key to extract all categories that are present on search.


text:
Q: Spring Roo: wrapped database driver available for the jpa setup command? I wrapped an existing official jdbc driver (No, it's not an Oracle DBMS) with the addon create wrapper command of Roo 1.2.5.
I've started it with osgi start and osgi ps lists it as running.
I'd like to make it available for database reverse engineer analysis. But as I understand it this mean I need to setup my Roo project with jpa setup and I see no way of using this driver with this command.
How can I make my wrapped driver available for jpa setup? How do I refer to it on the command line at jpa setup --database [the database reference, here]?
The options available here are DATABASE_DOT_COM, DB2_400, DB2_EXPRESS_C,DERBY_CLIENT, DERBY_EMBEDDED, FIREBIRD, GOOGLE_APP_ENGINE, H2_IN_MEMORY, HYPERSONIC_IN_MEMORY, HYPERSONIC_PERSISTENT, MSSQL, MYSQL, ORACLE, POSTGRES and SYBASE.
The only way to get around this that I can see here at the moment would be to install any of the choices jpa setup supplies and then manually changing the DBMS details, but it would seem to me there is another official way.
In the articles I've read concerning this, mostly about Oracle and DBRE, this vital step is ignored, like it's self-explanatory. I'm not a new Roo user, yet how to install a third party database driver not already available with Roo, does seem quite vague actually.
Care to enlighten me and future users on how to do this effectively? If you don't know how exactly, how about some ideas?
Update *
While I have scrapped the idea as I'm suddenly free to choose my own DBMS I don't need it. It would nevertheless be nice to know how to set up JPA with a DB that was not listed.
On the other hand if the list of options suggested by Roo actually is the complete list of Provider supported DBMS's then of course this knowledge would be moot, unless there is a time period between new support from the Provider — Hibernate in my case — and the existing Roo version.

A: You must think in two runtime environment:

*

*Application runtime: you just provide information to connect to Oracle. You don't need any wrapper, just Oracle JDBC driver jar in your maven local repo.

*Roo runtime: Roo runs on a OSGi environment, needs the Oracle JDBC wrapped into a OSGi envelope, so it can be loaded and used by Roo DBRE add-on and connect to DB.

So you must do the follow steps to run DBRE on your project:

*

*Configure your jpa connection in standard way (using jpa setup --database ORACLE ....)

*Use osgi start --file command to your generated wrapper to load Oracle JDBC on OSGi environment

*Use database introspect or database reverse engineer (this commando uses the connection configuration set in step #1)


text:
Q: How to remove sign in functionality from Liferay portal How to remove sign in functionality, which will display on right top corner of the Liferay portal guest page?
I tried to delete the #sign-in from custom.css file of classic theme which is the default theme for Liferay, but it did not work.

A: Instead of changing css in custom.css file of classic theme because it will not load changes of css, provide below css in Control Panel >> Site Pages >>  Look and Feel >> CSS field.
#sign-in{
display:none;
}

A: I think the normal way would be to delete/comment out the velocity script code in theme's portal_normal.vm file.

Then you can be sure, that there is no login code in your generated jsp files.

A: The solution provided by you did not worked for me. But I did changes to your code it started working.
the Change I did is as follows:
.sign-in{
display:none;
}

Instead of '#' I used '.', then its worked for me.
Thank you for the Solution.


text:
Q: if else inside for loop consulting multiple dictionaries I am having issues with the following code because i'm checking multiple dictionaries for a value.
When this value is not found i am getting multiple prints of 'not found'. The else statement should check for all dictionaries and print 'not found' after checking all dictionaries not for each.
class Catalog:

    def __init__(self):
        self.movies_list = [
            {'Titulo:': 'The Ring', 'Autor:': 'random_guy', 'Genero:': 'Horror', 'Duracion:': '115 Minutos',
             'Anio:': '2002',
             'Rating:': '7.1/10'},
            {'Titulo:': 'Locos por la progra', 'Autor:': 'other_guy', 'Genero:': 'Comedy', 'Duracion:': '90 Minutos',
             'Anio:': '2000', 'Rating:': '10/10'}]

        #self.user_input
        self.x = 'The Ring'

    def search(self):
        for dict in self.movies_list:
              for i in dict.items():
                    #self.user_input
                     if self.x in i:
                            print(dict['Titulo:'])
                     else:
                            print('not found')
              break

catalog = Catalog()
catalog.search()

A: Create a boolean value found, if you find the key make the value True. After the for loops check whether the variable is True. If it is false, dont do anything, otherwise, print not found.
I'm not sure of the syntax but it should be something like this:
def search(self):
    boolean found = False
    for dict in self.movies_list:
          for i in dict.items():
                #self.user_input
                 if self.x in i:
                        print(dict['Titulo:'])
                        found = True
    if not found:
         print('not found')

If you want to break after the first match, you can add two breaks, one of them after found = True, the other one is after the outer for loop as if found: break

A: Another option is to return from the method if you key matched input. If nothing found then print 'not found' at the end
def search(self):
        for dict in self.movies_list:
              for i in dict.items():
                    #self.user_input
                     if self.x in i:
                            print(dict['Titulo:'])
                            return;

        print('not found')


text:
Q: How to set an element's textContent, without the string getting trimmed? I'm trying to set an element's text content (a div element) to something the user has given as input. I don't really want to use element.innerHTML = (...) because then it could be parsed as HTML code instead of plain text, so I'm using element.textContent = (...).
 However, there can be spaces at the beginning (and at the end) of the input string, and I don't want the string to be trimmed before inserted into the element.
With innerHTML, I could simply replace all spaces with  , but textContent doesn't show that as a space, but as plain  .
How can I do it? Thanks in advance :)

A: To make whitespace render as it exists in the DOM, you can apply white-space: pre-wrap in CSS:

for (const target of document.getElementsByClassName('target')) {
  target.textContent = "   Some  text with   various spaces  ";
}
.preserve-whitespace {
  white-space: pre-wrap;
}

.target {
  border: 1px solid red;
  float: left;
  clear: left;
  margin-top: 0.5em;
}


text:
Q: SyntaxError: Unexpected token 'export' when import monorepo package I import package in vite.config.ts, it will throw syntax error

But it can be successfully imported in app.vue, I don't know why
my files tree
- packages
  - components
  - yep-ui
- playground
  - vite.config.ts

Here is my repo.
the code trigger question
I would appreciate if someone can help me.


text:
Q: When double "l" is considered American English? I'm struggling with "enroll" and "enrollment". Both answers (this one and this one), given to this question, as well as Wikipedia seems to be suggesting, that double "l" is more common in British English, while single "l" in American English.
However, on contrary to above, when browsing grammarist.com or Longman I can clearly see, that double "l" is claimed to be American English form, while single "l" seems to be British English form.
Is "enrollment" some kind of exception (and if yes, then what kind)? Or why double "l" is sometimes considered British English and other time -- American English?

A: You have to keep in mind that <l> and <ll> are both extremely common in English, regardless of region. For example, bill is always spelled <bill>, and nil is always spelled <nil>; excel is always spelled <excel>, and retell is always spelled <retell>. There are a lot of individual rules, but there's no single over-arching pattern, and the rules don't cover everything. For example, how come lily has one L, while filly has two? (In this respect, <l> vs. <ll> is much like many other aspects of English spelling. English spelling is not quite as random as people like to claim, but, well, there is a lot of arbitrariness.)
So, what you've noticed is that there are (at least) two cases of regional variation involving the choice between <l> and <ll>:

*

*in enrol/enroll and enrolment/enrolment (and a few other such words, such as fulfil/fulfill and fulfilment/fulfillment), the <l> spelling is British and the <ll> spelling is American;

*in words like traveled/travelled and labeled/labelled, the <l> spelling is American and the <ll> spelling is British. (Though labelled and travelled and so on aren't actually all that rare in the US — or they weren't until spell-checkers became prevalent — so this distinction may be exaggerated.)

These may seem contradictory, but really it's just that they're basically unrelated. Both are cases where the arbitariness of <l> vs. <ll> has shaken out differently in the US as in the UK, but there isn't much reason to expect that one region would have happened to end up with <l> in both cases and the other with <ll> in both cases, because there's no connection between the two. Both regions still have <l> in thousands of words and <ll> in thousands of words — mostly the same ones — and these are simply two edge-cases where words got grouped differently on the two sides of the pond.


text:
Q: What is /run/mount/utab? In exploring a hung umount, I bumped into /run/mount/utab in some strace output.
What is the purpose of /run/mount/utab?
Where can I read more about /run/mount/utab:

*

*purpose

*format

*what interacts with it (and how)

A: After a quick read of libmount-tables-update I believe the file is used to store userspace mount options. I'd have a look around here for information around the API's and how to interact with it. The source code for util-linux which contains libmount might also be another place to look.

A:
What is the purpose of /run/mount/utab?

The file is used by mount to store the user who mounted a filesystem. From man mount, under FILESYSTEM-INDEPENDENT MOUNT OPTIONS (and some quick tests)
user   Allow  an ordinary user to mount the filesystem.  The name of the mounting user
       is written to the mtab file (or to the private libmount file in  /run/mount  on
       systems without a regular mtab) so that this same user can unmount the filesys‐
       tem again.

In other words, if you have a drive you want to mount as ordinary user, you probably use an entry in /etc/fstab, containing the UUID of the device (or other identifier) and the option user, for example
UUID=<UUID> <target> ... user ...

When you $ mount -U <UUID> as user user1, mount will write something like the following to /run/mount/utab
SRC=/dev/sdb1 TARGET=<target> ROOT=/ OPTS=user=user1

which allows you to unmount the device.

Where can I read more about /run/mount/utab

The format is straight forward, provided you see the same as I see on my system, and apart from what written above, that's pretty much all I could find, try to check the links from the other answer.


text:
Q: Very large difference in size of html output from R markdown on Windows and Linux We produce an R markdown weekly report which has a large number of small graphs. The ggplots are saved as png and then integrated in the markdown script and encoded in the html. We recently moved the scripts producing this report to a linux machine with CentOS 7 and RStudio Server Open Source. The files produced on the linux machine are 3-4 times as large (20MB to 80MB).
On investigation it seems the reason is that the PNG images are saved as indexed colour on Windows but RGB on linux. I cannot figure out a way to change the way the ggplots are saved on linux. Any tips?
A simple example:
library(ggplot2)

ggplot(mtcars, aes(mpg, hp)) + geom_point() +
  geom_smooth(method = lm, se = FALSE)

ggsave("test_image.png")

Produces an 88 kb image on linux and a 37 kb image on Windows.
Running R 4.0.3 and ggplot 3.3.2 on both machines.
Update: Some more investigation on images produced by linux vs windows:
> image_read(url_windows)
# A tibble: 1 x 7
  format width height colorspace matte filesize density
  <chr>  <int>  <int> <chr>      <lgl>    <int> <chr>
1 PNG      600   2545 sRGB       FALSE   100070 20x20
> image_read(url_linux)
# A tibble: 1 x 7
  format width height colorspace matte filesize density
  <chr>  <int>  <int> <chr>      <lgl>    <int> <chr>
1 PNG     1800   7635 sRGB       FALSE  1046302 59x59

Images on windows are 1/3 the size and density.
So seems there is a simple way of solving this. Thanks for the feedback!


text:
Q: How to use Esapi 1.4.4 package in web application I am currently working on a project that uses JDK 1.4. So its just turned out to be that we have to use ESAPI 1.4.4 which is the only version compatible with JDK 1.4 . I downloaded it from the following path https://github.com/esapi/esapi-java-legacy but it doesnt seem to be a jar file . I couldnt figure out how to include this in my eclipse project or how to bring it into my classpath. Is it possible to get the JAR ??? Someone please guide me how to use it or any sample project for reference is sufficient .Thanks in advance

A: Ditching JDK 1.4 is my top recommendation as well. But if that is not an option for some reason, then I would try pulling down the ESAPI code base from GitHub (https://github.com/ESAPI/esapi-java-legacy), changing the  tag under the maven-compiler-plugin plugin from 1.7 to 1.4 and see if it compiles. Much of it probably will be fine, but you likely will have some huge 3rd party FOSS dependency issues so you will have to adjust those. So, before you go down that route, figure out what exactly it is that you need. If you only need ESAPI's output encoding, use the OWASP Java Encoder Project instead. Various other substitutes are described here: https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API#tab=Should_I_use_ESAPI_3F
Good luck.
-kevin


text:
Q: Does Captain America have an heroic adjective like so many other Marvel characters? You all know the heroic adjectives of Marvel. The Incredible Hulk. The Invincible Iron Man. The Mighty Thor. The Spectacular Spider-Man. The Uncanny X-Men. But from what I can tell, the big-name Captain America doesn't get one of those. It could be that the rank of Captain counts to this purpose, but most of the others have names that work perfectly fine without them (though the Fantastic Four might run into a snatch with this). And the last time I checked, America isn't an adjective.
So does Captain America have one of these heroic adjectives, either in the title of his books or used for him in said books? Or have the writers neven given him one, possibly because he predates the others?

A: Captain America was often referred to during the seventies and eighties as "The Star-Spangled Avenger." When addressed informally by his friends or long-term acquaintances who might not know he was Steve Rogers, he was called "Cap."

*

*Strangely enough, looking back over the years, Captain America's cover did NOT boast a particular tagline until recently when he became "The First Avenger." The stylized red, white and blue, "Captain America" was all Cap needed for a decade or more. Later when he and Falcon teamed up, the logo became "Captain America and the Falcon".

*

*Depending on who you were asking, he might also get the name: "Wing-head" for the wings which were on his costume during certain periods.

*

*Hawkeye was known for his complete disrespect of Captain America in Hawkeye's early days of avenging. He was known to call Captain America such colorful names as "Glamour Pants, Curly, and Methuselah."

A: Captain.

A: What about "The original Avenger" ? That title has been used in the past. Not short like some of the other titles though.


text:
Q: Arcpy.CreateTable_management in Python toolbox not creating table in memory The following creates a table in memory as expected when executed in the Python window [ArcGIS Pro 2.9, Windows 10]:
arcpy.CreateTable_management('memory','dataTable')
When I try to do the same thing in a Python toolbox tool (.pyt), the table does not appear to be created in memory (or anywhere else), although the call does not generate an error:
import arcpy

class Toolbox(object):
    def __init__(self):
        self.label = 'Create table in memory toolbox'
        self.tools = [CreateTable]

class CreateTable(object):
    def __init__(self):
        self.label = 'Create table in memory tool'
        self.canRunInBackground = False

    def getParameterInfo(self):
        return None

    def isLicensed(self):
        return True

    def updateParameters(self, parameters):
        return

    def updateMessages(self, parameters):
        return

    def execute(self, parameters, messages):
        arcpy.CreateTable_management('memory','dataTable')
        return

If I use a file GDB instead of memory, both approaches succeed.  Insights?

A: Shout out to Brennan: setting env.workspace appears to be the answer.  I had been using arcpy.Exists('dataTable') to determine whether the table had been created, but arcpy.ListTables() works too.
It's still curious that the behavior is different when executing the same command in the Python window - in that case not only is the table "found" by arcpy.Exists (without setting env.workspace), but it also immediately appears in the TOC as a "standalone table'.


text:
Q: Connection strings depending on environment I am currently working on a web application using Visual Studio 2015, asp.net mvc 5. I would like to define some connection strings but only for my 'Dev' environment, right now they are defined in Web.config but I'd like them to be only in Web.Dev.config.
I added the following in Web.Dev.config:
<add xdt:Locator="Match(name)" xdt:Transform="SetAttributes(connectionString)" name="SModel" connectionString="same connection string as in web.config" />

<add xdt:Locator="Match(name)" xdt:Transform="SetAttributes(connectionString)" name="CDev" connectionString="same connection string as in web.config"  />

But when I run my application in the Dev environment, it's telling me that the connection strings can't be find.


text:
Q: How to prove differentiability for general case for such function How do I prove that $\dfrac {|a| x \Bbb e ^x} {|b| - \Bbb e ^x + |c|}$ is differentiable, where $a,b,c$ are arbitrary values such that $|b| + |c| \ne \Bbb e^x$?
I tried doing the $\lim _{h \to 0}$ methods to prove it is differentiable for any arbitrary value $u$, i.e. $\lim _{h \to 0} \frac {f(u+h) -f(u)} h$ but it becomes very tedious.
I wonder if there are any other methods we can prove it mathematically? Else, I have to just say since it is an elementary function, thus it is differentiable?
Thank you all!

A: Product rule: If $f,g$ are differentiable at $x$ then so is the
function $\phi(x) = f(x)g(x)$ and $\phi'(x) = f'(x) g(x) + f(x) g'(x)$.
Quotient rule: If $f,g$ are differentiable at $x$, and
$g(x) \neq 0$, then so is the
function $\phi(x) = {f(x) \over g(x)}$ and $\phi'(x) = {f'(x) g(x) - f(x) g'(x) \over g(x)^2}$.
In your case, $f(x) = |a| x e^{x}$, and applying the product rule gives
$f'(x) = |a| x e^{x} + |a| e^{x}$. We have
$g(x) = |b|+|c| -e^x$, and so $g'(x) = - e^x$.
Now substitute into the quotient rule to get the answer.


text:
Q: Verify 2 SQL Server linked servers to Oracle are equal I am migrating SQL Server 2005 to SQL Server 2012.
One of the items to migrate is a linked server to oracle. The configuration of server, DNS, firewall, etc are not on my side.
I need to make sure they are configuring the correct linked server, pointing to the correct database (we have many copys of databases).
What Query can I run in both sql servers to identify the Oracles servers and databases are the same?

A: You can show all linked servers from the sys.servers table on each of the server instances.
select * from sys.servers;

The linked Oracle server will be listed under:
product = `Oracle`
and provider = `OraOLEDB.Oracle`


text:
Q: Decide whether textColor should be white or black based on background I'm trying to determine whether a textColor should be black or white based on the background color, but it seem not to work. first of all i've created an extension which retrieve the rgb values. then i use below algorithm to calculate and then determine if the value is above 186. The issue is that everytime i run the algorithm it always return something around 1, which is way below the 186 which should be the middle which determine if text should be black or white. What am i doing wrong in order to calculate a value around 186? which i've found is what determine if it black or white from this question
How to decide font color in white or black depending on background color?
Extenstion
extension UIColor {
    var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        return (r,g,b,a)
    }
}

ViewDidLoad
    let colorComp = UIColor(rgba: "#f2f2f2").components
    let colorCheck = colorComp.red * 0.299 + colorComp.green * 0.587 + colorComp.blue * 0.114
    print(colorCheck)

in this case red, green and blue returns 0.949019607843137 each.

A: The RGB range is from 0 (blak) to 255 (white) but in this case the range is 0 to 1. You should calculate the new value with this operation:
Value = (1/255)*186 = 0.729;
0xF2 = 242 dec = 242/255 = 0.949


text:
Q: NARS APL: Rational representation and numerator In NARS, fractions are represented using r example 23r45 will be the fraction 23⁄45. The problem is, if I have a variable that contains a rational number, how do I access the numerator? Does a "numerator" function exist such that numerator 23r45 returns 23?

A: There is no built-in "numerator" function, but you can easily construct one:
      num←(⊣÷∨)∘1
      num 23r45
23

For reference, the denominator can be found with:
      den←(⊢÷∨)∘1
      den 23r45
45

And so you can "split" a rational with:
      n_d←(,÷∨)∘1
      n_d 23r45
23 45


text:
Q: Suppose $f: \mathbb{R} \to \mathbb{R}$ is continuous at a. Prove $f \circ f: \mathbb{R} \to \mathbb{R}$ is continuous at $f(a)$. I am having a bit of difficulty with this proof.
I know $|x-a| < \delta \implies |f(x) - f(a)| < \epsilon$.
I know $f$ is only continuous at a, so do I need to prove f is continuous at $f(a)$ before moving on with the proof? If yes, I'm not sure how.
I have the first line $|f(x) - f(f(a))|$, but I'm not sure how to prove, in a general sense, how this is continuous.
Even bypassing proving the f(f(a)) continuity, the bulk of the problem is still an issue: Proving $|x-a| \implies f(f(x)) - f(f(a)) < \epsilon$.
Any help would be appreciated!

A: The statement doesn't hold always...
See the example $f:\mathbb{R} \rightarrow \mathbb{R}$:
$$ f(x)=\begin{cases}  x+2 &\text { when }x\in (-\infty,4) \\ 10 &\text {  when  }x\in [4,\infty] \end{cases} $$
Then:
$$ (f\circ f)(x) = \begin{cases} x+4 &\text { when  }x\in (-\infty,2) \\ 10 &\text{ when } x\in [2,\infty]\end{cases} $$
Clearly $f $ is continuous at $2$, but $f\circ f$ is not continuous at $2$.

A: Some notes to help the OP sort out what the real problem is (to be deleted once the Question is appropriately clarified).
If $f$ were only defined at $x=a$, it would not make much sense to speak of it being continuous.  The definition of continuity at $x=a$ calls for $f$ to be defined on a deleted neighborhood of $a$.
Furthermore if $f(f(a))$ is defined, then $f(a)$ has to belong to the domain of $f$.  Unless we knew $f$ was continuous at $f(a)$ as well as at $x=a$, we would have no reason to expect $f\circ f$ to be continuous at $x=a$.  Counterexamples are easily constructed.
Possibly $f\cdot f$ is the product of $f$ with itself.  In this case, as @LL3.14 suggests, $f$ could be defined everywhere and $f\cdot f$ would be defined everywhere (on the real numbers), and continuity of $f$ at $x=a$ would imply continuity of $f\cdot f$ at $x=a$.


text:
Q: Validating a single character JAVA I'm trying to make my program validate between the use of two single characters that are input by the user, which must be A or M.
Here's my code I have thus far:
static char getCustomerType() {
    System.out.println("Please enter the term for the Policy the client would like");
    System.out.println("A for Annual or M for Monthly. Annual provides the user with a 10% discount");

    String s = inputs.next();

    while (s != 'A' && s != 'M') {
        System.out.println("Incorrect, please try again");
        s = inputs.next();
    }
}

Netbeans however, does not like this stating the inputs.next is never used when I have set it to be used before the while statement?
It also doesn't like the while statement producing incompatible string type referencing boolean to string.
I assume this is because I have declared s as a String?

A: why not write
while ( ("A".equalsIgnoreCase(s) || "M".equalsIgnoreCase(s)) == false)

A: You can have single characeter input from user using below code assuming inputs is your scanner object:

char c = inputs.next(".").charAt(0);

and then you can compare it using != or .equals() or .equalsIgnoreCase()


text:
Q: Start Launcher Selection Programmatically / Android I'm developing an industrial app that's running effectively in a KIOSK mode - that is users must not be able to exit it.
To achieve this I've simply made the app a launcher/home screen replacement.  This works very effectively and so far seems to be working as a method of preventing people getting out.
The only problem I have is that if I'm not careful we're going to end up with bricked devices where we can't get back to a normal launcher application.
What I'm looking for is a method of programmatically presenting the Android Launcher Selection Dialog.
Android seems to do this on it's own when you first launch a launcher, but I can't figure out a way of doing it programmatically.

A:
What I'm looking for is a method of pro grammatically presenting the Android Launcher Selection Dialog.

Intent.createChooser() returns an Intent that will launch a chooser (which I think is what you mean by "Android Launcher Selection Dialog") for a given Intent. So, create an Intent for ACTION_MAIN and CATEGORY_HOME, wrap that in Intent.createChooser(), and call startActivity() on the resulting Intent.

A: If I understand this question right you don't want to get the user out of your app if he don't want it?
I would do it like this:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    return true;
}

Now button clicks will be ignored for the activity. Now you only have to make a menu point for the exit.