text:
Q: Ignoring constant when solving Legendre equation of order 1 using reduction of order method I'm studying a course on ODEs and there is an example given where Legendre's equation is solved using reduction of order as follows:
$$(1-x^2)y''-2xy'+2y=0, \ \ \ P_1(x)=x \\  y(x)=xv, y' = v+xv',y''=2v'+xv'' \\\implies (1-x^2)(2v'+xv'')-2x(v+xv')+2xv=0 \\ \implies \frac{v''}{v'}=\frac{-2}{x}+\frac{1}{1-x}+\frac{1}{1+x}$$
after rearranging and solving the partial fraction decomposition. From here the integral is taken of both sides to give $$\log{v'} = -2\log{(x)}+\log{(1-x)}+\log{(1+x)} $$and it is stated that constants of integration do not matter at this point, which I do not understand. On exponentiation and integrating again the final answer is given as $$v=\frac{-1}{x}+\frac{1}{2}\log{\left(\frac{1+x}{1-x}\right)}\left[ + C \right]  $$
Similarly here the constant is bracketed as if it is optional. If v was solved with constants of integration I believe the answer would be of the form $$ v=C_1\left[\frac{-1}{x}+\frac{1}{2}\log{\left(\frac{1+x}{1-x}\right)}\right]+C_2$$
Is this solution considered 'the same' because of being just a multiple of the previous solution (so not linearly independent)? Is it standard to ignore the constant of integration with this method or would it be safer to leave it in?

A: We get $v'=x^{-2}(1+x)(1-x)e^{C}$ if we add a constant $C$. When you integrate this you get another constant but the DE is not satisfied unless the second constant is $0$. So the solution we get is simply $C_1$ times the solution we get without adding a constant where $C_1=e^{C}$. It is obvious that if $y$ is a solution to the DE so is any constant multiple of it. So there is a no point in adding the constant during the process of finding $y$. We can always introduce the constant factor at the end.


text:
Q: ajax with php mailer error: 404 I have set up an ajax call on a form to send a post event to my php mailer script. However, the post goes to the url /undefined rather than mailer.php and the error 'The requested URL /undefined was not found on this server.' with code 404 is returned. Here is the ajax script:
$("#contactForm").on("submit", function (event) {
  if (event.isDefaultPrevented()) {
    // handle the invalid form...
    formError();
    submitMSG(false, "Did you fill in the form properly?");
  } else {
    // everything looks good!
    event.preventDefault();
    submitForm();
  }
});

function submitForm(){
  // Initiate Variables With Form Content
  var email = $("#email").val();

  $.ajax({
    type: "POST",
    url: "mailer.php",
    data: "email=" + email,
    complete : function(text){
      if (text == "success"){
        console.log(text);
        formSuccess();
      } else {
        formError();
        submitMSG(false,text);
      }
    }
  });
}

function formSuccess(){
  $("#contactForm")[0].reset();
  submitMSG(true, "Awesome! We'll be in touch.")
}

function formError(){
  $("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
    $(this).removeClass();
  });
}

I have placed my PHP script in the same folder, but there seems to be an error finding the php script.
<?php
    // My modifications to mailer script from:
    // http://blog.teamtreehouse.com/create-ajax-contact-form
    // Added input sanitizing to prevent injection

    // Only process POST reqeusts.
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $name = strip_tags(trim($_POST["name"]));
                $name = str_replace(array("\r","\n"),array(" "," "),$name);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $message = trim($_POST["message"]);

        // Check that data was sent to the mailer.
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        // Set the recipient email address.
        // FIXME: Update this to your desired email address.
        $recipient = "test@test.com";

        // Set the email subject.
        $subject = "Hello";

        // Build the email content.
        $email_content .= "hello";

        // Build the email headers.
        $email_headers = "From: $name <test@test.com>";

        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            // http_response_code(200);
            echo "success";
        } else {
            // Set a 500 (internal server error) response code.
            // http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission, please try again.";
    }

?>

I also have a .htaccess file:
RewriteEngine On
RewriteBase /
# redirect html pages to the root domain
RewriteRule ^index\.html$ / [NC,R,L]

# remove trailing html on routes
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Read/Write data in file or SQlite for Android? The main dilemma I am stuck into is whether I should use Room database or Files to save my data.
Please skip the security, encryption/decryption part for now.
The thing is I need to store complex object like of a usual transaction like below
Transaction(id, entryTime, exitTime, pricingScheme, amount, vehicleNumber, etc etc.)
So I am having a device with just 1 gb of RAM and when data increases by like 1000 entries then the query takes a lot of time to get the searched data and sometimes device hangs.
I know the Room Lib is highly optimised but lets also consider the below scenario for sometime.
So I got this suggestion from someone to store the data in text files after certain limit lets say after 700 entries store the data in file.
I will write data line by line as mentioned below.
749463(some ID) Transaction1 (Json)
804830(some ID) Transaction2 (Json)
But the main issue arises here is how I can query the data from a text file?
Is there any was other than reading the file line by line and comparing the ids to get the desired entry?
This doesn't sound very practical right, I reacted the same so just need your reviews/directions on this before I start my POC project.
Or is there any other way of handling the above situation?
Any help/suggestion is highly appreciated.
Thanks.


text:
Q: Intersection of invariant subsets of a local group action I don't understand some facts about invariant subsets of a local group action. Basically (to save you reading definitions) local actions are germs of partial actions which in turn are just like regular actions with the difference that the domain doesn't need to be all of $G\times M$. For the sake of context I'm going to reproduce the definition of a local group action on a topological manifold.
Definition. Let $G$ be a Lie group and $M$ a topological. A partial action of $G$ on $M$  is a continuous map
$\rho: \mathrm{dom}(\rho)\rightarrow M$
where $\mathrm{dom}(\rho)\subset G\times M$ is an open subset containing $\{e\}\times M$ ($e$ es the identity element of $G$). The map $\rho$ satisfies the following two conditions:
(i) $\rho(e,x)=x$ for all $x$
(ii) If $(g_2,x)\in \mathrm{dom}(\rho)$ and $(g_1,(\rho(g_2,x)) )\in\mathrm{dom}(\rho)$, then $(g_1g_2,x)\in \mathrm{dom}(\rho)$ and $\rho(g_1,(\rho(g_2,x)) )=\rho(g_1g_2,x)$.
Definition. There is an equivalence class of partial actions: Two partial actions $\rho_1$ and $\rho_2$ are equivalent if there is an open subset $D\subset \mathrm{dom}(\rho_1)\cap\mathrm{dom}(\rho_2)$ such that $\rho_1|_{D}=\rho_2|_{D}$. An equivalence class $[\rho]$ of partial actions is called a local action.
An subset $Y$ of $M$ is $[\rho]$-invariant if there is a representative $\varphi\in [\rho]$ such that whenever $y_0\in Y$ and $(g,y_0)\in \mathrm{dom}(\varphi)$ then $gy_0\in Y$.
Actual Question. Supposedly the intersection of any number of invariant subsets is invariant. This is where I am confused. For a finite collection if subsets this is very clear: If $\{Y_i\}_{i=1}^n$ are $[\rho]$-invariant then for each $i$ there is a $\varphi_i\in[\rho]$ satisfying the definition of invariance. We can take $D= \cap_{i=1}^n\mathrm{dom}(\varphi_i)$ and restrict any of the $\varphi_i$ to obtain the required partial action. IF we have an infinite number of invariant subsets then this is not so clear anymore since the intersection of the domains could be non-open (it could even be $\{e\}\times M$).
How can I prove this?
I've tried a proof by contradiction: Supposing $\cap Y_i$ is not invariant would yield a sequence $\{g_i\}$ in $G$ which (I think but I'm not sure) could be made to converge to $e$. After that if I try to use the continuity of the $\varphi_i$ I could obtain a contradiction to (i) in the definition of partial action.


text:
Q: Использование button в tkinter Столкнулся с проблемой, что при передаче command в Button функции, она выполняется до срабатывания даже mainloop. Можно ли как то этого избежать?
Пример:
def submit(entry):
    a = entry.get()
    if a == 'Enter smth':
        messagebox.showerror('Ошибка', 'Введите число')
        return
    else:
        foo(a)

entry = Entry(main)
entry.insert(0,'Enter smth')

run = Button(main,
             text=" Enter ",
             command=submit(entry)
             )

main.mainloop()

mainloop() не выполняется, при обработке command программа сразу переходит в функцию, видит, что в поле введена строка и выводит ошибку, после чего закрывает програму.

A: Просто в кнопке надо заменить command = submit(entry) на command = lambda: submit(entry) и все хорошо запашет.


text:
Q: Using List.h in C files, Ubuntu10.10 I am running Ubuntu 10.10 on an IBM R51 machine. When I access list.h to read it(manually/humanly) I open /usr/src/linux-headers-2.6.35-22/include/linux .
But when coding a C program in terminal, I cant invoke any #include because it is not in the default /usr/include folders.
When I change the statement to reflect the path  by typing #include "/usr/src/linux-headers-2.6.35-22/include/linux/list.h" it returns errors as list.h in turn calls other header files which are mentioned as located in "linux" folder
The header files are as you must be aware:
"linux/poison.h", "linux/prefetch.h" and "asm/system.h"
So if I have to copy each, I can but prefetch in turn calls other dependencies, which are not present in /usr/include directory. I hope you understand.
How can I solve this problem?

A: Are you sure these headers are really what you need ?  The standard C headers should be under /usr/include
Anyhow you need to pass the header search path to the compiler via the '-I' flag.
Pass the path via -I
-I/usr/src/linux-headers-2.6.35-22/include/linux

Then in your C code
#include "list.h"

Link to GCC manual & preprocessor directives

A: *

*adding -I/usr/src/linux is a no-go, since unsanitized header files are not meant to be used from user programs

*you could manually copy list.h to your own project and sanitize

*or use a library that is specifically for userspace and provides the same functionality (since you already used libHX elsewhere, you might want to continue reading into the linked list chapter)

A: The header files you are using are designed for internal use of the Linux kernel. They were not designed to be used by a userland program.
If you MUST use these headers (the Linux kernel list implementation is brilliant), copy the headers into your program source directory. Copy each file that is referenced, edit each one to remove whatever assumptions exist about being used in-kernel, and recurse until you're finished. I might suggest to make your own prefetch() macro that simply does nothing, rather than try to untangle <linux/prefetch.h>. Do the same for <linux/poison.h>, and untangle <linux/types> and <linux/stddef.h> (not too hard here :) as best you can.
And also be sure you license your project GPLv2 (and specifically GPLv2, the Linux kernel's COPYING file is quite strict that GPLv2 is the only license that applies; there is debate whether the GPL allows specifying only one version, but that is the license Linus chose ages ago, and the license that is valid on all files unless specified otherwise).


text:
Q: How can one efficiently implement flattening and unflattening of neural network parameters in Axon (Elixir)? To train a neural network with other optimization algorithms e.g Genetic Algorithms one needs to flatten the weights of the neural network into a vector, compute the updates using the vector weights then transform the weights back again into a format that the neural network can use. In Axon the weights/params are implemented as a map of Nx tensors. Ideally one would traverse the map in a depthwise version/recursively and flattening and combining the weights into a single vector. To implement the reverse of this one would need a way to keep track of the weight shapes, types and names. Then use that to rebuild the parameters map. I have a naive implementation of this that achieves the purpose. However, I am wondering if there is better way to achieve the same results without having to recreate tensors each time they are flattened or unflattened.
Here is my implementation:
defmodule Params do
  def flatten(params) do
    params
    |> to_flat_map()
    |> Map.values()
    |> Enum.reduce(fn x, acc ->
      Nx.concatenate([Nx.flatten(acc), Nx.flatten(x)])
    end)
  end

  def unflatten(params, template) do
    template
    |> Enum.reduce({%{}, -1, params}, fn {key, tensor_opts}, {params_map, idx, params} ->
      start_idx = idx + 1
      stop_idx = start_idx + Tuple.product(tensor_opts[:shape]) - 1

      opts = Keyword.take(tensor_opts, [:type, :names])
      curr_param = Nx.reshape(params[start_idx..stop_idx], tensor_opts[:shape], opts)
      params_map = Map.put(params_map, key, curr_param)

      {params_map, stop_idx, params}
    end)
    |> then(&elem(&1, 0))
    |> Enum.reduce(%{}, fn {k, v}, params_map ->
      put_in(params_map, Enum.map(String.split(k, "."), &Access.key(&1, %{})), v)
    end)
  end

  def extract_template(params) do
    params
    |> to_flat_map()
    |> Enum.map(fn {k, v} -> {k, [shape: Nx.shape(v), type: Nx.type(v), names: Nx.names(v)]} end)
    |> Enum.into(Map.new())
  end

  defp to_flat_map(params) when is_map(params) and not is_struct(params) do
    for {k, v} <- params, sub_key = to_string(k), sub_map <- to_flat_map(v), into: %{} do
      case sub_map do
        {key, val} -> {sub_key <> "." <> key, val}
        val -> {sub_key, val}
      end
    end
  end

  defp to_flat_map(params), do: [params]
end

For example consider this simple model:
model =
  Axon.input({nil, 2})
  |> Axon.dense(2, activation: :relu)
  |> Axon.dense(1, activation: :sigmoid)

With the following parameters obtained after calling Axon.init on the model:
%{
  "dense_0" => %{
    "bias" => #Nx.Tensor<
      f32[2]
      EXLA.Backend<host:0, 0.2002877735.2882928648.84100>
      [0.0, 0.0]
    >,
    "kernel" => #Nx.Tensor<
      f32[2][2]
      EXLA.Backend<host:0, 0.2002877735.2882928648.84101>
      [
        [0.2250952422618866, -0.2300528585910797],
        [0.8318504691123962, 1.00990629196167]
      ]
    >
  },
  "dense_1" => %{
    "bias" => #Nx.Tensor<
      f32[1]
      EXLA.Backend<host:0, 0.2002877735.2882928648.84102>
      [0.0]
    >,
    "kernel" => #Nx.Tensor<
      f32[2][1]
      EXLA.Backend<host:0, 0.2002877735.2882928648.84103>
      [
        [0.5544151663780212],
        [1.0918326377868652]
      ]
    >
  }
}

Calling Params.flatten on the parameters yields the following:
#Nx.Tensor<
  f32[9]
  EXLA.Backend<host:0, 0.2002877735.2882928648.84108>
  [0.0, 0.0, 0.2250952422618866, -0.2300528585910797, 0.8318504691123962, 1.00990629196167, 0.0, 0.5544151663780212, 1.0918326377868652]
>

The above vector can then be passed through the various operators of genetic algorithms such as crossover and mutation. After that to get prediction from the model, we need to convert the vector back to a map of weights for each of the layers. First we need a template/blueprint of the model's weights their shapes, types and names, which we can get by calling Params.extract_template and obtain:
%{
  "dense_0.bias" => [shape: {2}, type: {:f, 32}, names: [nil]],
  "dense_0.kernel" => [shape: {2, 2}, type: {:f, 32}, names: [nil, nil]],
  "dense_1.bias" => [shape: {1}, type: {:f, 32}, names: [nil]],
  "dense_1.kernel" => [shape: {2, 1}, type: {:f, 32}, names: [nil, nil]]
}

Then we can use the vector and the template and call Params.unflatten to obtain a map of weights that we can use with Axon.predict.
%{
  "dense_0" => %{
    "bias" => #Nx.Tensor<
      f32[2]
      EXLA.Backend<host:0, 0.2002877735.2882928648.84109>
      [0.0, 0.0]
    >,
    "kernel" => #Nx.Tensor<
      f32[2][2]
      EXLA.Backend<host:0, 0.2002877735.2882928648.84111>
      [
        [0.2250952422618866, -0.2300528585910797],
        [0.8318504691123962, 1.00990629196167]
      ]
    >
  },
  "dense_1" => %{
    "bias" => #Nx.Tensor<
      f32[1]
      EXLA.Backend<host:0, 0.2002877735.2882928648.84112>
      [0.0]
    >,
    "kernel" => #Nx.Tensor<
      f32[2][1]
      EXLA.Backend<host:0, 0.2002877735.2882928648.84114>
      [
        [0.5544151663780212],
        [1.0918326377868652]
      ]
    >
  }
}

The issue here is that at each step we create multiple tensors and we have to do the reshaping operations. For genetic algorithms this may be quite cumbersome as we have multiple solutions at each step. I would like to know how one can solve this issue of flattening and unflattening efficiently or is there an approach with Genetic Algorithms for neural networks where the weights do not have to be flattened?


text:
Q: How add extra middleware in grup route? I create admin panel and want give access to some role like admin, mod, support, god etc. But in the same group one of route i would like give access only for God and Admin. Can i do this in one group or should i create separate group for this route (separate group or add middleware to one route only) but i prefer separate group.
Route::group(['prefix' => 'admin', 'middleware' => ['roles'], 'roles' => ['administrator', 'moderator', 'support']], function () {
        Route::get('/', 'AdminController@index')->name('admin.index');
        Route::get('users', 'AdminController@users')->name('admin.users');
        Route::get('messages', 'AdminController@messages')->name('admin.messages');
    });

And separate group
Route::group(['prefix' => 'admin', 'middleware' => ['roles'], 'roles' => ['administrator']], function () {
        Route::get('finance', 'AdminController@finance')->name('admin.finance');
    });

How can i do in one group. I tried but i have access all the to the finance method even if i am support only.

A: This will only work as separate groups, as Laravel will apply all the middleware requirements to routes in the group in one go.
The other option is to use nested groups (if appropriate), but this would essentially be the same as separate groups:
Route::group(['prefix' => 'admin', 'middleware' => ['roles'], 'roles' => ['administrator', 'moderator', 'support']], function () {
    Route::get('/', 'AdminController@index')->name('admin.index');
    Route::get('users', 'AdminController@users')->name('admin.users');
    Route::get('messages', 'AdminController@messages')->name('admin.messages');

    Route::group(['prefix' => 'admin', 'middleware' => ['roles'], 'roles' => ['administrator']], function () {
        Route::get('finance', 'AdminController@finance')->name('admin.finance');
    });
});


text:
Q: Add a span with custom id in Spring sleuth (2.1.0) I wanted to add a logic in my application such that if my HttpServletRequest has "traceId" in header, I dont want to create new traceId and carry the same id over to next services.
I can do that by creating a filter before TraceFilter which consumes this traceId from request and creates a span with same id. Can someone help in achieving this?
I have following doubts:

*

*SPAN_CREATION: How to create a span with existing traceId?

*SPAN_KEY: How do I set that span into my request so that sleuth takes it up and doesnt create a new span?

I am trying following code:
@Order(TraceWebServletAutoConfiguration.TRACING_FILTER_ORDER - 1)
public class HeaderInjectFilter  extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String searchId = extractTraceIdFromRequest((HttpServletRequest) request);
        if(!StringUtils.isEmpty(searchId)){
            request.setAttribute(SPAN_KEY, spanForId(searchId));
        }
        chain.doFilter(request, response);
    }

    private Span spanForId(final String traceId) {
        return SPAN_CREATION;
    }
}

Thanks in advance.


text:
Q: Тормоза в консоле и некорых GUI посте замены видеокарты RTX 3050, Fedora Сегодня заменил видеокарту GTX650Ti -> RTX3050
Драйвера переустановил, все как полагается. В Блендере заметил разницу сразу, т.е. рендер стал шустрее. Т.е. с видеокартой все оК.
Но в консоли, в частности mc стал жутко тупить. Если кликнуть на файл, то его выделение занимает секунды три. Так же  "неуверенно" перемещается стрелками.
В редакторе xed тормоза при наборе текста для .bashrc Но, для других, даже длинных xml файлов такого нет. Сами символы еще ничего, но, конкретно пробел, секунды три. И неуверенно работает перемещение стрелками, Home, End.mousepad работает без тормозов. Сейчас, тоже при наборе вопроса, тормозов нет.
Память, проц не перегружены. Видеопамять также в норме.
Только что попробовал зайти под новым пользователем. Все летает, как и нужно.


text:
Q: native nodejs mouse and keyboard event listener I am looking for a package for listening mouse and keyboard events system wide.
I am using electron and nodejs.
I tried:

*

*iohook and it did not work in MacOS (supports macOS High Sierra 10.13.2 and older)
https://wilix-team.github.io/iohook/os-support.html.
This doesn't work for Catalina.

*gkm works fine however it needs Java (JVM)
https://www.npmjs.com/package/gkm
github https://github.com/tomzx/gkm
I did lots of search but did not manage to find any others that will help.
Are there any mouse/keyboard listeners which supports mac/windows new versions; and which does not depend on other languages?

A: So since I couldn't find a good alternative nodejs module to iohook that hasn't died off years ago and no longer works... I decided to make my own by updating a fork (which is itself a fork of the OG iohook, lol)
It also has a feature the original didn't... Key code to key name parsing! (Note: Probably only fully works in a US QWERTY layout, but MOST of the keys should be right in any layout)
You can find it here: https://github.com/Pecacheu/node-iohook
Or install it with npm install iohook2


text:
Q: Wpf, doubleanimation on fontstretch property How to make an animation which changes FontStretch? This is what I've tried:
<Style TargetType="TextBlock" x:Key="TextBlockStyle">
  <Style.Triggers>
    <EventTrigger RoutedEvent="Button.MouseEnter">
      <EventTrigger.Actions>
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation Storyboard.TargetProperty="FontStretch" To="UltraCondensed" Duration="0:0:0.3"/>


text:
Q: MongoDB returns an already deleted document I have a problem with deleting a document properly:
When a delete request from the client is made, mongoose runs a successful findByIdAndDelete() query, and after receiving a response, the client makes a new request for all documents -> find({}), but mongo returns a list which includes the already deleted document. Only when I refresh the page manually it returns an updated list.
That confuses me because when I make the same set of operations for editing a document -> findByIdAndUpdate(), mongo returns a list with the updated document
What am I doing wrong?


text:
Q: Problem: horizontal scrollbar for flex datagrid I have 10 columns in datgrid so i want datagrid to be horizontally scrollable.
Im getting vertical scrollbar(auto generated without specifying vertical scroll policy on) for mxDatagrid but Im not getting horizontal scrollbar.
how to solve this?
Im using flex 4.

A: please make the horizontalScrollPolicy="on" then it will display the scroll
and i also refer this link
this might be helpful to u
Faster Horizantal scroll


text:
Q: Get an array of values from a key inside a dict object that it is also a dict I am trying to transform the response object:
[
    {
        'var0055':53,
        'var0048': 'Adolf'
    }
    {
        'var0055':16,
        'var0048': 'Julia'
    }
]

into data_var0055:
[53,16]

I have tried:
data_var0055 = []
i = 0

for item in response:
      data_var055[i] = item['var055']
      i += 1

but it is not returning the array [53,16].

A: Some fixes for your code

*

*You are getting the value for key var055, but you want the value for key var0055 instead

*You don't need to use an index for appending to the list data_var055, you can use list.append instead
So the code will change to
data_var0055 = []

#Iterate over the response and append value for key var0055
for item in response:
      data_var0055.append(item['var0055'])

Or you can simplify it in a list comprehension like so:
res = [item['var0055'] for item in response]

Output will be
[53, 16]


text:
Q: Wallaby integration tests pass individually, fail when run together I'm using Wallaby (0.17.0) for acceptance tests with phantomjs (2.1.1), and the latest Elixir (1.4.5) and Erlang (20). I've written a few acceptance tests, each of which passes when run individually, but when I run them together (via mix test test/acceptance) they fail because things that should be on the page aren't. It's as if all the tests are running in the same browser, even though Wallaby should "manage multiple browsers for you."
I believe I've set everything up according to the setup section of the README, although I'm not running the tests with async: true because my app uses sockets and Phoenix.Ecto.SQL.Sandbox doesn't play well with async. To be clear, the tests also fail with async: true, I just also get DBConnection.OwnershipErrors in each when attempting to connect to the socket.
Is there anything else necessary to ensure each test is run in its own phantomjs browser, or to clear out sessions between test runs?


text:
Q: Flexbox styling different in IE I'm trying to build a basic button toolbar using flexbox. Everything looks exactly how I want it in all browsers except IE 11: https://jsfiddle.net/qoo5fmnv/1/
Am I doing something wrong here or is the styling I'm after not possible with IE flexbox?
Note by removing flex-direction: column from flex-container a everything looks as expected. Similarly by removing flex: 1 from flex-container span and flex-container section everything looks fine. The combination of the two together seem to be messing things up.


text:
Q: Parse Correct encoding with Kotlin rest template I want to get the labels from the wiki api.
And I am using rest template in Kotlin with Spring.
I also tried OKHttp in Java but get the same results.
It worked in Postman.
 val uri = "https://www.wikidata.org/w/api.php?action=wbgetentities&ids=Q1726&format=json&props=labels&languages=de|zh"

        val restTemplate = RestTemplate()
        val result = restTemplate.getForObject(uri, ByteArray::class.java)
        if (result != null)
            print(String(result, charset("UTF-8")))

Output is
{"entities":{"Q1726":{"type":"item","id":"Q1726","labels":{"zh":{"language":"zh","value":"\u6155\u5c3c\u9ed1"},"de":{"language":"de","value":"M\u00fcnchen"}}}},"success":1}[B@6a71619f

I expect it to be "München" and "慕尼黑"
How to I parse the encoded strings correctly?

A: This answer did the trick.
Using StringEscapeUtils from org.apache.commons.text because the other is deprecated.


text:
Q: VirtualBox reinstalling & updating has left me with Too Many Network Adapters. How Do i remove them? I have too many network adapters. I have had to reinstall, repair VirtualBox a few times, and I have three NICs in my laptop.
I definitely don't need to have 14 bridged networking drivers though, and I cannot uninstall them. I only want to keep the new ones that came with VirtualBox 4.1.20.
When I go into the registry there are tons of places with these adapters. I have searched online up to 10 pages of Google, and VirtualBox forums, and no one has mentioned this problem nor explained how to delete these annoying extra network adapters.
Please offer some assistance or at least tell me how anybody else has dealt with this. I only need 1 host-only network adapter, 1 bridged networking adapter for each of my network cards. Take a look:

A: Try this procedure to cleanup useless adapter:
1- Create a restore point before!
2- Delete ghost adapters (displayed in soft colour): [underlined in yellow in my screen capture]
   Realtek Network Adapter #5, 6, 4, 7, 3 and 2

3- Disable Yellow Triangles Adapters [underlined in green in my screen capture]
   Realtek Network Adapter Vbox NO NUMBER, #5,4
   *and*
   Vbox Miniports #13,19

4- Reboot
5- KEEP Realtek Network Adapter NO NUMBER unchanged!
6- Trial and error process:
   Disable successively all Realtek Vbox bridged EXCEPT one

   then launch VirtualBox to see if it's working with the remaining enabled adapter.

   Repeat this action until you'll find the right one.

Hope this help. Let us know.


text:
Q: ASP.NET UpdatePanel Time Out I'm making a request from an UpdatePanel that takes more then 90 seconds. I'm getting this timeout error:

Microsoft JScript runtime error:
  Sys.WebForms.PageRequestManagerTimeoutException: The server request
  timed out.

Does anyone know if there is a way to increase the amount of time before the call times out?

A: There is a property on the ScriptManager which allows you to set the time-out in seconds. The default value is 90 seconds.
AsyncPostBackTimeout="300"

A: Please follow the steps below:
Step 1: In web.config, set httpRuntime maxRequestLength="1024000" executionTimeout="999999"
Step 2: Add the following setting to your web page's ScriptManager: AsyncPostBackTimeout ="360000"
This will solve your problem.

A: In my case the ScriptManager object was created in a Master Page file that was then shared with the Content Page files. So to change the ScriptManager.AsyncPostBackTimeout property in the Content Page, I had to access the object in the Content Page's aspx.cs file:
protected void Page_Load(object sender, EventArgs e)
{
     . . .
     ScriptManager _scriptMan = ScriptManager.GetCurrent(this);
     _scriptMan.AsyncPostBackTimeout = 36000;
}

A: This might be configurable by changing the ASP script timeout in IIS.
It's located in the properties of your web site, virtual directory, configuration button, then on the options tab.
or set it by setting the Server.ScriptTimeout property.

A: This did the trick (basically just ignoring all timeouts):

A: Well, I suppose that would work if you just want the request thrown away with the potential that it never completely executed...
Add an AsyncPostBackTimeOut property to the ScriptManager tag to change your default timeout from 90 seconds to something more reasonable for your application.
Further, look into changing the web service receiving the call to move faster.  90 seconds may as well be infinity in internet time.

A: The problem you are facing is when your application runs into a timeout on a SQL database query. It's taking more time than the default to return the output. So you need to increase the ConnectionTimeout property.
You can do it in several ways:

*

*A connection string has a ConnectionTimeout property. It is a property that determines the maximum number of seconds your code will wait for a connection of the database to be opened. You can set connection timeout in connection string section in web.config.
<connectionstrings>
    <add name="ConnectionString"
         connectionstring="Database=UKTST1;Server=BRESAWN;uid="      system.data.sqlclient="/>

 <asp:ToolkitScriptManager runat=" server=" AsyncPostBackTimeOut=" 6000=">

    </add>
</connectionstrings>

*You can put AsyncPostBackTimeout="6000" in .aspx page
<asp:ToolkitScriptManager runat="server" AsyncPostBackTimeOut="6000">
</asp:ToolkitScriptManager>

*You can set timeout in SqlCommand, where you are calling the stored procedure in .cs file.
command.CommandTimeout = 30*1000;

Hope you have a solution!


text:
Q: How to extract oldest date using batch file I'm trying to figure out how to extract the oldest date among the list of file in specific folder,and then save it in a .txt file?
FOR EXAMPLE :
Each time you run the script I need to have the oldest  date only  in text file:
txt file shoud display - 20200726
Name

*

*File_1_20200726

*File_2_20200701

Thanks :-)

A: Since you didn't provide any code, here is a powershell code, perhaps this can help you to make your own ?
$p = '\S+(\d{8})'
$MyString = @('File_1_20200726','File_2_20200701','File_2_20200781','File_0_20200725','File_hhsjj_ggee','Filewithoutdigits') | sort
$MyString | %{ [regex]::matches($_,$p) } | %{ $_.Groups[1].Value }

Output :

20200725
20200726
20200701
20200781

A: You can exploit your date format to make this super easy using the sort or a for loop command in cmd.
I'm a bit torn but going with rhe slower for loop or rhe sort, since it seems you do or do not wa t the number before rhe date to factor in? And rhe file names may not be uniform.
I willtherefore assume you just want the oldest date and that it always comes after rhe 2nf underscore.
@( SETLOCAL ENABLEDELAYEDEXPANSION
  SET "Folder=C:\Path\To\FilesFolder"
  SET "txtfile=C:\Path\For\DateFile.txt"
  SET "DIF=0"
  SET "CURRENT=10000000"
)

CALL :Main

( ENDLOCAL
  EXIT /B
)

:Main
  For /F "Tokens=3" %%_ IN ('
    DIR /B/A-D "%Folder%\*_*_*"
  ') DO (
    SET /A "DIF= _ - CURRENT"
    IF /I !DIF! LSS 0 SET /A "CURRENT= _"
  )
  Echo.%CURRENT%>>"%txtfile%"
  Echo.%CURRENT%
GOTO :EOF


text:
Q: Call to undefined method Magento\Backend\Model\View\Result\Page\Interceptor::setUrl() In my custom module to displaying the button on customer edit page (adminhtml), when hit the custom button it will call my custom controller after executed again I am redirecting to customer edit page. Here My custom controller is called, but when it redirecting Error is throwing.

Error: Fatal error: Call to undefined method
  Magento\Backend\Model\View\Result\Page\Interceptor::setUrl() in
  C:\xampp\htdocs\magentoee21\app\code\SR\StackExchange\Controller\Adminhtml\Stackexchange\Customer.php
  on line 22 Call Stack

and my code is:
root/app/code/SR/StackExchange/view/base/ui_component/customer_form.xml
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="buttons" xsi:type="array">
            <item name="custom_button" xsi:type="string">SR\StackExchange\Block\Adminhtml\Edit\CustomButton</item>
        </item>
    </argument>
</form>

root/app/code/SR/StackExchange/Block/Adminhtml/Edit/CustomButton.php
<?php

namespace SR\StackExchange\Block\Adminhtml\Edit;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

class CustomButton extends \Magento\Customer\Block\Adminhtml\Edit\GenericButton implements ButtonProviderInterface
{

    /**
     * @return array
     */
    public function getButtonData()
    {

        if($this->getCustomerId()){
            return [
                'label' => __('Custom Button'),
                'on_click' => sprintf("location.href = '%s';", $this->getCustomerUrl()),
                'class' => 'action-secondary',
                'sort_order' => 10
            ];
        }
    }

    /**
     * Get URL for back (reset) button
     *
     * @return string
     */
    public function getCustomerUrl()
    {
        $params = [
            'id' => $this->getCustomerId(),
            'store' => 0
        ];

        return $this->getUrl('stackexchange/stackexchange/customer',$params);
    }

}

//Admin controller
 <?php

    namespace SR\StackExchange\Controller\Adminhtml\Stackexchange;

    use \Magento\Customer\Controller\Adminhtml\Index\Edit;
    use Magento\Framework\Controller\ResultFactory;

    class Customer extends \Magento\Customer\Controller\Adminhtml\Index\Edit
    {

        public function execute()
        {
            $resultRedirect = $this->resultPageFactory->create(ResultFactory::TYPE_REDIRECT);
            $customer_Id = (int) $this->getRequest()->getParam('id');
            $store = $this->getRequest()->getParam('store');
            $customer = $this->_customerRepository->getById($customer_Id);

            //file_put_contents('Customer.txt', print_r($customer_Id,true), FILE_APPEND);

//Method 1
            //$resultRedirect->setPath('customer/index/edit/',['id' => $customer_Id, 'store' => $store,'_current' => true]);
            //return $resultRedirect;

//Method 2
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;

        }

    }

I have tried 2 different methods, but it's not working for me.
Could you please throw me right direction.

A: I have resolved my self to changing the controller method
public function execute()
        {
            $resultRedirect = $this->resultPageFactory->create(ResultFactory::TYPE_REDIRECT);
            $customer_Id = (int) $this->getRequest()->getParam('id');
            $store = $this->getRequest()->getParam('store');
            $customer = $this->_customerRepository->getById($customer_Id);

            //file_put_contents('Customer.txt', print_r($customer_Id,true), FILE_APPEND);

//Method 1
            //$resultRedirect->setPath('customer/index/edit/',['id' => $customer_Id, 'store' => $store,'_current' => true]);
            //return $resultRedirect;

//Method 2
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;

        }

to
public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $customer_Id = (int) $this->getRequest()->getParam('id');
        $store = $this->getRequest()->getParam('store');
        $customer = $this->_customerRepository->getById($customer_Id);
        $resultRedirect->setPath('customer/index/edit/',['id' => $customer_Id, 'store' => $store,'_current' => true]);
        return $resultRedirect;
    }

Now it's working fine. If some one have better answer feel free to update this.


text:
Q: ReturnUrl and preserve scroll position? How do I indicate position on page in returnUrl?
  returnUrl= HttpContext.Current.Request.RawUrl

A: You could include some type of a tag in the url and then have some javascript that runs to scroll to the right section based on the tag you have supplied.
StackOverflow does it based on the postid passed in with the url.  StackOverflow includes a #1234567 at the end of the url and then auto scrolls the tag's anchor in a section.
You should refer to the following question to see how to implement the scrolling to an anchor:
Programmatically scroll to an Anchor Tag


text:
Q: Storing Pickled Data in Mysql I am trying to use pickle to store an object in mysql, but no matter what I do, I can't seem to unpickle the data.
My mysql database
http://i.imgur.com/xCyZtIO.png
My mysql connect function
conn = MySQLdb.connect (host = "localhost", user = "user", passwd = "password", db = 'database', use_unicode=True)

Storing the data
cursor.execute('UPDATE matchmaking set `elo` = %s WHERE `token` = %s', (pickle.dumps(Rating()) , y[0] ))

Loading the data
cursor.execute('SELECT * FROM matchmaking where `gameid` = %s LIMIT 200', (row[0]))
player1 = pickle.loads(player[x][2])

KeyError: '"'
print player[x]

(u'35dc00eeb1fa2a49efcae7d2a8233cef', 1L, '"ccopy_reg\n_reconstructor\np0\n(ctrueskill\nRating\np1\nc_builtin_\nobject\np2\nNtp3\nRp4\n(dp5\nS\'tau\'\np6\nF0.35999999999999993\nsS\'pi\'\np7\nF0.014399999999999998\nsb."', 2L)

A: You have double quotes around the pickled string. Use .strip('"') to get rid of them before loads. I don't know why you get the extra quotes but I'm not really familiar with MySQL.


text:
Q: A question on enlarging the "/boot" space with the "GParted" When I try to update, I see
Not enough free disk space on `/boot`

I know I can use sudo apt-get autoremove, but there are only two versions 4.4.0-45 and the current one 4.4.0-47 as you can see in picture one:

So I decided to enlarge /boot space with GParted.
However, I can't resize /dev/sda11 where /boot is. I think it is the small "key" following /dev/sda11 as you can see in picture two:

What should I do to solve the problem?
If it matters, it is Ubuntu 16.04 LTS

A: Your partition table is pretty cramped for space. You would have to do a reinstall with lvm for flexibility to be able to enlarge partitions as you see fit.What I would do is just 'sudo apt-get autoremove' to uninstall your old, unused kernels. That will remove them from the /boot directory and free some space.


text:
Q: Trouble overriding a method in Gallery view in Android OKay gang, forgive me if this question is ubernoobness, but i am having trouble overriding a couple of methods of the Gallery class in my CustomGallery class, which is extended from Gallery.  can someone tell me why this is okay to override:
@Override
 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
 {
  return super.onFling(e1, e2, 0, velocityY);
 }

but this one creates an error - "The method onFinishedMovement() of type CustomGallery must override a superclass method":
@Override
 private void onFinishedMovement()
 {
        //
    }

As far as I can tell they are all members of the same class, but clearly I am missing something.  Thanks for any help understanding this!

A: onFinishedMovement() is private method of Gallery so it's not accessible outside the class in which it is defined ( including inherited classes)


text:
Q: Sub-Referencing an Array in C++ I'm developing a simple processor emulator, and one of my specs says that all registers must be sub-accessible down to the bytes (It's a 32-bit processor, so there are 4 byte registers for every normal register). When I need to access a register, I need some way to figure out whether I'm going to be getting a uchar, ushort, uint or float based on its ID. I know ahead of time which registers point to which type, but there's no way I know of storing the register pointers that will allow me to, disregarding the return types, perform arbitrary arithmetic with those values. I thought maybe C++11 could help me out here, but I don't know where to look.
I've considered typecasting the pointers in a switch statement, but I'd have to redo that switch statement in the function actually asking for the values, because a function can't change return type mid-execution.
I've considered using templated objects to point out the registers, but I can't store templated objects with different template parameters in the same array (or can I?)

A: It turns out there's no easy way to solve this. However, I was able to store the types of the array elements in a parallel array of integers. I would ask for the type, and use a switch statement to cast to the necessary types and perform calculations. The source can be found on GitHub.

A: Generally unions are... tricky and you should avoid them . But in a case of a CPU-emulator I would argue, since registers are exactly acting as unions are designed, this might be one of the rare cases you can/should use them.
unions opens the door to a lot of type-unsafety. But since your CPU will also just execute the instructions on the registers in a non-typesafe manner (presumably), just make a register a union. They are quite not-C++11, but pure C (only tiny additions in C++11).
union Register {
    uint32_t val;
    struct {
        uint16_t lo;
        uint16_t hi;
    } u16;
    struct {
        uint8_t b0;
        uint8_t b1;
        uint8_t b2;
        uint8_t b3;
    } u8;
 };

Or similar.
Of course you could implement a type-checking CPU, or a simulator that executes only type-safe code, but I guess that is beyond the  scope of your task.


text:
Q: P-value of alternative hypothesis - Can you simply take the difference of the chi2 goodness-of-fit tests? I guess this is the kind of question extremely hard to Google if you're lacking just the right word.
My situation is: I have some experimental data points, and I have two models: the "simple model" (null hypothesis, H0) and the more complex model (H1), with two more degrees of freedom. I try and fit each model separately to my data, and to assess how good the fit is, I compute a chi2 goodness-of-fit test.
I notice that chi2(H0) > chi2(H1), and I want to compute the p-value (a 3-sigmas significance allowing me to reject H0).
A colleague tells me that I can compute chi2' = chi2(H0) - chi2(H1) and the corresponding degrees of freedom: ndof' = ndof(H1) - ndof(H0) = 2.  And then, I can integrate the chi2 distribution (with 2 d.o.f.) from chi2' to infinity, which yields the p-value. The colleague says that taking the difference of chi2 values "comes from some theorem", which they ofc cannot find.
So far I have failed to find references to such method (nor help from anyone knowledgeable in statistics). Is that the right way of computing the significance?
If not, what would be a correct way of assessing by how much H1 is favoured over H0 ?

A: Regarding the first part of your question, try writing out the $\chi^2$ and likelihood $\cal L$ (product of probabilities at each data point), and see if $-2 \ln {\cal L }= \chi^2$.  The result your colleague is referring to sounds like Wilk's theorem for the distribution of the ratio of two nested likelihoods (certain restrictions apply).
Regarding your second question, in any case, you should be able to run simulations of H0, calculate test statistic $\chi2'$ for each simulation, and with that distribution of $\chi2'$ see where your experimental value falls to determine a p-value.
Lastly, regarding what you noticed earlier, as you add degrees of freedom, the $\chi^2$ can only remain constant or decrease.


text:
Q: haproxy backend limit not going higher than 1000 I have my backend maxconn set to 5000 but the limit will not go up from 1000. The global maxconn in the screenshot is 2k. I changed that to 10, but the backend limit will not go above 1k

here is my config
global
  user haproxy
  group haproxy
  log /dev/log local0
  log-tag loggy
  chroot /var/lib/haproxy
  daemon
  quiet
  stats socket /var/lib/haproxy/stats mode 777 level admin
  pidfile /var/run/haproxy.pid
  maxconn 10000

defaults
  timeout connect 10s
  timeout client 60s
  timeout server 120s
  timeout tunnel 1h
  log global
  mode http
  balance roundrobin
  option httplog
  option dontlognull
  option redispatch
  stats uri /haproxy-status

frontend http-in
  default_backend servers
  bind *:80
  maxconn 10000
  acl is_record_http hdr(Upgrade) -i websocket
  use_backend servers-record if is_record_http
  use_backend servers if !is_record_http

frontend httpssl-in
  default_backend servers-ssl
  bind *:443
  maxconn 10000
  use_backend servers-ssl-record if { req_ssl_sni -i something.something.com }
  use_backend servers-ssl if { req_ssl_sni -i www.something.com }
  tcp-request inspect-delay 10s
  tcp-request content accept if { req_ssl_hello_type 1 }
  mode tcp

backend servers
  server server-app something.com

backend servers-record
  server server-record something.com

backend servers-ssl
  server server-app-ssl something.com
  acl clienthello req_ssl_hello_type 1
  acl serverhello rep_ssl_hello_type 2
  tcp-request inspect-delay 5s
  tcp-request content accept if clienthello
  stick on payload_lv(43,1) if clienthello
  stick store-response payload_lv(43,1) if serverhello
  maxconn 5000
  mode tcp
  stick-table type binary len 32 size 30k expire 30m
  tcp-response content accept if serverhello

backend servers-ssl-record
  server server-record-ssl something.com
  acl clienthello req_ssl_hello_type 1
  acl serverhello rep_ssl_hello_type 2
  tcp-request inspect-delay 5s
  tcp-request content accept if clienthello
  stick on payload_lv(43,1) if clienthello
  stick store-response payload_lv(43,1) if serverhello
  maxconn 5000
  mode tcp
  stick-table type binary len 32 size 30k expire 30m
  tcp-response content accept if serverhello

A: Per answers here, here and here and the documentation:
The backend limit is the value of fullconn which is by default 10% of maxconn of frontend. You should only have to worry about the fullconn parameter if you have set up minconn parameter in server lines (to use dynamic maxconn), otherwise you can ignore it.
So the maximum amount of connections is sum of maxconn of your backed values which will only be limited if the global maxconn value is lower than the sum of the backend values.


text:
Q: Characters in text file not recognized I'm nearing the end of a car club project and one of the two remaining problems is a text file I imported, split, parsed, and displayed in a table. Most of the punctuation is not recognized, things like quotes, apostrophes, and dashes, regular stuff like that. Best I can tell this is not a unicode issue. Maybe a font issue? I tried different fonts. I also ran the file through Notepad which usually does a good job stripping out formatting codes.
Here's a screen shot - http://www.kstreetstudio.com/OMC/images/IndexPage.jpg
Here's the code I use to load the file.
function FileRead(U)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        X=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        X=new ActiveXObject("Microsoft.XMLHTTP");
    }

  X.open('GET', U, false );
  X.setRequestHeader('Content-Type', 'text/html')
  X.send();
    return X.responseText;
}

Any idea what's going wrong?
Thanks in advance.

A: The problem was certain characters not displaying correctly, in particular long dashes and left and right quotes and apostrophes. I was able to find/replace them and the problem went away.


text:
Q: AIC or ANOVA to compare models? What are the relative merits of each approach, and which circumstances call for one rather than the other?
To some extent I have a specific example in mind, which I've discussed here. In that example I am comparing various linear mixed models. However, I'm interested in general principles that can be applied across various research questions.


text:
Q: How can I log the value of passed parameters to a function? My aim is to create a logging function that lists the name of a function and the list of passed parameters.
An example would be the following:
func MyFunc(a string, b int){

   ... some code ...

   if err != nil{
       errorDescription := myLoggingFunction(err)
       fmt.Println(errorDescription)
   }

}

func main(){
   MyFunc("hello", 42)
}

// where MyLoggingFunction should return something like:
// "MyFunc: a = hello, b = 42, receivedError = "dummy error description"

So far it seems that in Go there is no way to get the name of the parameters of a function at runtime, as answered in this question, but I could give up this feature.
I've managed to get the function name and the memory address of the passed parameters by analysing the stack trace, but I'm hitting a wall when it comes to print somehow the parameters starting from their address (I understand that it might not be trivial depending on the type of the parameters, but even something very simple will do for now)
This is an implementation of the logging function I'm building (you can test it on this playground), is there away to print the parameter values?
func MyLoggingFunction(err error) string {
    callersPCs := make([]uintptr, 10)
    n := runtime.Callers(2, callersPCs) //skip first 2 entries, (Callers, GetStackTrace)
    callersPCs = callersPCs[:n]

    b := make([]byte, 1000)
    runtime.Stack(b, false)

    stackString := string(b)

    frames := runtime.CallersFrames(callersPCs)
    frame, _ := frames.Next()

    trimmedString := strings.Split(strings.Split(stackString, "(")[2], ")")[0]
    trimmedString = strings.Replace(trimmedString, " ", "", -1)
    parametersPointers := strings.Split(trimmedString, ",")

    return fmt.Sprintf("Name: %s \nParameters: %s \nReceived Error: %s", frame.Function, parametersPointers, err.Error())
}

If there are other ideas for building such logging function without analysing the stack trace, except the one that consists in passing a map[string]interface{} containing all the passed parameter names as keys and their values as values (that is my current implementation and is tedious since I'd like to log errors very often), I'd be glad to read them.


text:
Q: Is "overloading" in "operator overloading" just semantic? Kotlin is one of the languages that allow us to easily define behavior for various predefined operators, operation named operator overloading - https://kotlinlang.org/docs/reference/operator-overloading.html
My question is regarding the overloading part of the operation.
From what I see default the language only declares operators for the basic types - https://github.com/JetBrains/kotlin/blob/01a613dca4042dde8d2374ff0e6610cb9eddc415/core/builtins/native/kotlin/Primitives.kt
If I'm reading this correctly our custom types would not have any of this special methods - operators available by default. And indeed if we're to try
class A { }
val a = A()
System.out.println(a + a)

the compiler would try to find a suitable operator plus method to call but ultimately give a compilation error.
But if we do declare our own operator plus method
class A {
    operator fun plus(other: A) = "Hello!"
}
val a = A()
System.out.println(a + a)

we would indeed have "Hello!" printed.
The above mechanism is called "operator overloading" but without a previous method with the same name we do not in fact use the OOP method overloading we all are accustomed to - https://en.wikipedia.org/wiki/Function_overloading.
So between the two mechanisms - operator overloading and method overloading there is really no connection, other than an unfortunate name clash?

A: Looks like you are confused about operators in general.
The thing about operators is that they are just inline functions and the operator keyword is just a language construct to give you the ability to group operators with classes.
Where you can find answers about this is definitely the source code. If we take a look at the tests, we can find the following:
// "Create local variable '-'" "false"
// ACTION: Create extension function 'A.minus'
// ACTION: Create member function 'A.minus'
// ACTION: Replace overloaded operator with function call

Sadly, I cannot find the source code where operator is transformed, but most certainly this must be the procedure where the operator overload is replaced with function call.


text:
Q: Can't get all author using WP_User_Query I am trying to show all authors as well as the pagination of the result. So using bellow code it's not returning any users.
// Pagination vars
$current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1;

$users_per_page = 12; // RAISE THIS AFTER TESTING ;)

$args = array(
    'number' => $users_per_page,
    'paged' => $current_page,
    'role' => 'Author',
);

$users = new WP_User_Query( $args );

$total_users = $users->get_total(); // How many users we have in total (beyond the current page)
$num_pages = ceil($total_users / $users_per_page); // How many pages of users we will need

if ( $users->get_results() ) {

    foreach( $users->get_results() as $user )  {
        // $firstname = $user->first_name;
        // $lastname = $user->last_name;
        // $email = $user->user_email;
        $author_thumb_url = get_avatar_url( $user->ID );
        echo '
';
            echo '
';
                echo '
';
                    echo '';
                echo '
';
                echo '
';
                    echo '
'. $user->first_name . ' ' .  $user->last_name . '
';
                    echo '
'. get_the_author_meta( 'description', $user->ID ) . '
';
                echo '
';
            echo '
';
        echo '
';
    }
}
?>

In args I have also used 'role' => 'author' and 'role__in' => 'author' but no result is showing.

A: Your loop might be incorrect.  This is working for me.  I also wrapper your columns in a row and container.
Try
// Pagination vars
$current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1;

$users_per_page = 12; // RAISE THIS AFTER TESTING ;)

$args = array(
    'number' => $users_per_page,
    'paged' => $current_page,
    'role' => 'author',
);

$users = new WP_User_Query( $args );

$total_users = $users->get_total(); // How many users we have in total (beyond the current page)
$num_pages = ceil($total_users / $users_per_page); // How many pages of users we will need

if ( $users->results ) {
    echo '

';
    foreach( $users->results as $user )  {
        // $firstname = $user->first_name;
        // $lastname = $user->last_name;
        // $email = $user->user_email;
        $author_thumb_url = get_avatar_url( $user->ID );
        echo '
';
            echo '
';
                echo '
';
                    echo '';
                echo '
';
                echo '
';
                    echo '
'. $user->first_name . ' ' .  $user->last_name . '
';
                    echo '
'. get_the_author_meta( 'description', $user->ID ) . '
';
                echo '
';
            echo '
';
        echo '
';
    }
    echo '

';
}
``


text:
Q: Submitting for App Store in 4.2: Strange "Whitespace" error from XCode submission validation I originally submitted and was approved with the 4.1 SDK.  I upgraded to the 4.2 and was making some fixes, and when I tried to submit to the App Store I got this message:
"Filename may not contain whitespace."
My info.plist had the default ${Executable} as the Executable File property.  I went ahead and changed it.  Tried rebuilding, and got the same error. Strange thing though, the filename that XCode was assigning was a match to my "Bundle Display Name," which is what controls how the app is named in Springboard.  I changed the Bundle Display Name property to have No_Spaces, and the app passed validation.
I don't really want my app to have an underscore in the name, so I'm wondering if this is a bug or if I missed something somewhere.  Keep in mind that NOTHING other than some code tweaks changed between submission and approval in 4.1, and submitting in 4.2

A: Look at this Thread:
https://devforums.apple.com/message/282652#282652
Known problem with XCode 3.2.5

A: Change the Product Name in the Distribution Build Settings for your app's Target, and remove spaces from that name.  It's one of 5 "names" for an app (Target name, Product Name, Bundle display name, Bundle Identifier, iTunes store name), which can all be different.  You can still have spaces in your iTunes name and the under-the-icon Bundle display name.


text:
Q: How to calculate BLEU Score without the brevity penalty code:
import nltk
from nltk.translate.bleu_score import sentence_bleu
score1 = sentence_bleu(ref1, cand)

How can I ignore brevity penalty from the BLEU score calculated here?

A: If you look at the source code in NLTK, you can see the brevity penalty is hardcoded in the computation, just before the final score is returned, on the following line.
s = bp * math.exp(math.fsum(s))

You can surely copy and modify the source code. There is also the breivity_penalty function, which allows you to compute it yourself and divide the score again.
Also, be aware that the implementation of BLEU in NLTK is different from the original reference implementation that was recently fully replicated in the sacrebleu package. The main problem is that the reference implementation of BLEU used non-standard tokenization rules which NLTK does not implement. All current machine translation literature reports BLEU scores using sacrebleu.
With sacrebleu, you can get the sentence level BLEU like this:
import sacrebleu
bleu = sacrebleu.sentence_bleu("I am the walrus.", ["I am the walrus."])

The output is a tuple that contains the final score as well as the individual components: the n-gram precisions and the brevity penalty.


text:
Q: A question on maximal subgroups of a finite group. Let $K$ be a finite non-Abelian simple group , $G=K\times K$ ,  and  $H=\{(x,x)\in G\big|x\in K\}$.
Question:
Is $H$ a maximal subgroup of $G$?

A: Let $H'$ be a subgroup of $G$ strictly containing $H$. Show that the set $K'\subseteq K$ defined by the $x\in K$ such that $(x, e)\in H'$ is a normal, non-trivial subgroup of $K$. Here are hints for each of the three properties I mentioned:
Subgroup: Use that $H'$ is a subgroup of $G$, along with the definition of $K'$
Non-trivial: Because $H'$ strictly contains $H$, it contains at least one $(x, y)$ with $x, y\in K, x\neq y$. Now multiply that element with $(y^{-1}, y^{-1})$
Normality: If $x\in K'$, and $y\in K$, then $(y, y),(x, e)$ and $(y^{-1}, y^{-1})$ are all elements of $H'$


text:
Q: Android device connection with classic bluetooth and BLE at the same time I am new to android bluetooth programming, wanted to know about bluetooth connections. I have connected  a tab to another android phone using ble,  at the same can I connect the tab to classic bluetooths as well? Is this possible to connect tab to a ble device and another android phone at the same time?

A: Yes this should be possible and Android doesn't impose any restrictions on this. Have a look at the links below for more information:-

*

*Simultaneous Bluetooth and BLE connections

*Bluetooth SPP and BLE connection at the same time

*Bluetooth classic vs BLE on Android

*The ultime guide to Android BLE development


text:
Q: Checkout Correct Tag in Git I have a git repository of the stable kernel builds
my remote 'origin' is as follows
origin  git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git (fetch)
origin  git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git (push)

Now as per kernelnewbies.org i have to use the following command to get a snapshot of a particular kernel version
git checkout -b stable tag

I did this
git checkout -b v2.6.34.12

but when i check the kernel version using
make kernelversion

I get the latest version that is 3.11.6.
Is the git command correct or am i missing something?

A: Your problem is that this:
git checkout -b v2.6.34.12

creates a new branch called v2.6.34.12 that is located at whatever you happen to have checked out at the moment - v2.6.34.12 is the argument to the -b option, and names the branch that you want to create.
Instead, you want this:
git checkout -b mybranch v2.6.34.12

to create a new branch (called, imaginitively, mybranch), and start it at the v2.6.34.12 tag (but be careful, at this point, as you've already created a branch with the name v2.6.34.12 that you should probably delete first as git rev-parse will likely find the branch before it finds the tag - you could specify the last argument above as refs/tags/v2.6.34.12 to explicitly request the tag instead of a similarly named branch).

A: usage: git checkout -b|-B <new_branch> [<start point>]

just add <start point>
git checkout -b formake v2.6.34.12

your
git checkout -b v2.6.34.12

equals
git checkout -b v2.6.34.12 HEAD

it creates a new branch named v2.6.34.12 from master


text:
Q: CSS conflict in react using swiper.js library I created two sliders using swiper.js in react. The css rules for both the sliders are different and had to target same css classes that library provided. When I integrate both the components in react, css conflict happens. How do I resolve this ?
eg: 1st component slider css rule
.swiper-container {
  position: relative;
  width: 100%;
  padding-top: 50px;
  padding-bottom: 150px;
}

2nd component slider css rule
.swiper-container {
  max-width: 500px;
  border-radius: 15px;
  overflow: hidden;
  padding-left: 10px;
  padding-right: 10px;
  margin-bottom: 16px;
  margin-left: 0;
  margin-right: 0;
}

The 2nd component css rule will override the first component css rule which I dont want that happen
Any way to solve this ?

A: what you can do is adding a container class for each slider and use that container class to prefix your css rules.
as an example:
// import Swiper core and required components
import SwiperCore, {A11y, Navigation, Pagination, Scrollbar} from 'swiper';

import {Swiper, SwiperSlide} from 'swiper/react';

// Import Swiper styles
import 'swiper/swiper.scss';
import 'swiper/components/navigation/navigation.scss';
import 'swiper/components/pagination/pagination.scss';
import 'swiper/components/scrollbar/scrollbar.scss';

// install Swiper components
SwiperCore.use([Navigation, Pagination, Scrollbar, A11y]);

export default () => {
    return (
        <>

                <Swiper
                    spaceBetween={50}
                    slidesPerView={3}
                    navigation
                    pagination={{clickable: true}}
                    scrollbar={{draggable: true}}
                    onSwiper={(swiper) => console.log(swiper)}
                    onSlideChange={() => console.log('slide change')}
                >
                    <SwiperSlide>Slide 1</SwiperSlide>
                    <SwiperSlide>Slide 2</SwiperSlide>
                    <SwiperSlide>Slide 3</SwiperSlide>
                    <SwiperSlide>Slide 4</SwiperSlide>
                    ...
                </Swiper>

                <Swiper
                    spaceBetween={50}
                    slidesPerView={3}
                    navigation
                    pagination={{clickable: true}}
                    scrollbar={{draggable: true}}
                    onSwiper={(swiper) => console.log(swiper)}
                    onSlideChange={() => console.log('slide change')}
                >
                    <SwiperSlide>Slide 1</SwiperSlide>
                    <SwiperSlide>Slide 2</SwiperSlide>
                    <SwiperSlide>Slide 3</SwiperSlide>
                    <SwiperSlide>Slide 4</SwiperSlide>
                    ...
                </Swiper>

        </>
    );
};

CSS
.container-1 .swiper-container {
    position: relative;
    width: 100%;
    padding-top: 50px;
    padding-bottom: 150px;
}
.container-2 .swiper-container {
    max-width: 500px;
    border-radius: 15px;
    overflow: hidden;
    padding-left: 10px;
    padding-right: 10px;
    margin-bottom: 16px;
    margin-left: 0;
    margin-right: 0;
}

A: You don't need to use same class for multiple component.
Do like this to void conflicts.
.s1 for first swiper slider and .s2 for second one.

var s1 = new Swiper('.s1', {
    slidesPerView: 4,
    spaceBetween: 10,
    pagination: '.sp1',
    paginationClickable: true,
});
var s2 = new Swiper('.s2', {
    slidesPerView: 4,
    spaceBetween: 10,
    pagination: '.sp2',
    paginationClickable: true,
});
.s1 {
 background: pink;
 margin-bottom: 30px;
}

.s2 {
 background: lime;
}

.swiper-slide {
  border: 1px solid #115599;
}
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.css">

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9

Slide 10

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9

Slide 10


text:
Q: I have two dataset and need to comapre string from one data set columns with other dataset column in R I have two dataset and need to comapre string from one data set columns with other dataset column in R:
Below are the details. Case can be ignore
Can any one help me on this please.
First Dataset:

instancename	hostname	sid

instance1	server1	 	sid1

instance2	server2	 	sid2

instance3	server3	 	sid3

instance4	server4	 	sid4

instance5	server5	 	sid5

instance6	server6	 	sid6

Second Dataset:

short_description	description

Kindly activate Server1 information	Kindly activate all sid3 and there is issue with instance3

server2: issue on instance2	find a sloution for this issue

Please fix the issue	issue is on Sid6

can you please check instance5 on server5	Sid5. Please look into this issue asap.

sid1: performance issue	server1 and sid1. Performance issue

Can you please check the issue	Can you please check the issues

I need final dataset like below

short_description	description	Final_output

Kindly activate Server1 information	Kindly activate all sid3 and there is issue with instance3	Server1,sid3,instance3

server2: issue on instance2	find a sloution for this issue	server2,instance2

Please fix the issue	issue is on Sid6	Sid6

can you please check instance5 on server5	Sid5. Please look into this issue asap.	server5,Sid5

sid1: performance issue	server1 and sid1. Performance issue	sid1,server1

Can you please check the issue	Can you please check the issues	no matches found

A: since you provided data in html format, i will have to read it into r to be a table:
b ="

short_description	description

Kindly activate Server1 information	Kindly activate all sid3 and there is issue with instance3

server2: issue on instance2	find a sloution for this issue

Please fix the issue	issue is on Sid6

can you please check instance5 on server5	Sid5. Please look into this issue asap.

sid1: performance issue	server1 and sid1. Performance issue

Can you please check the issue	Can you please check the issues

"

dat2= xml2::as_xml_document(paste0("",b,""))%>%
  rvest::html_table()%>%
  {.[[1]]}

serv_instance = gsub("(?|.*?((?i)server\\d+|instance\\d+|sid\\d+)|.+)","\\1",do.call(paste,dat2),perl=T)

final_output = replace(gsub("(?<=\\d)(?=[A-Za-z])",", ",serv_instance,perl=T),!nchar(serv_instance),"No match found")

cbind(dat2,final_output)

                          short_description                                                description             final_output
1       Kindly activate Server1 information Kindly activate all sid3 and there is issue with instance3 Server1, sid3, instance3
2               server2: issue on instance2                             find a sloution for this issue       server2, instance2
3                      Please fix the issue                                           issue is on Sid6                     Sid6
4 can you please check instance5 on server5                    Sid5. Please look into this issue asap. instance5, server5, Sid5
5                   sid1: performance issue                        server1 and sid1. Performance issue      sid1, server1, sid1
6            Can you please check the issue                            Can you please check the issues           No match found


text:
Q: How do you nest a paragraph of text within another paragraph? What's the best way to recreate this InDesign-created text-within-text style in LaTeX (LuaTex)?

A: Looks like a job for the wrapfig package.
\documentclass{article}
\usepackage{xcolor}
\usepackage{wrapfig}
\usepackage{lipsum}
\usepackage{setspace}
\begin{document}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur dictum gravida mauris. Nam arcu libero, nonummy eget, consectetuer id, vulputate a, magna. Donec vehicula augue eu neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ut leo. Cras viverra metus rhoncus sem. Nulla et lectus vestibulum urna fringilla ultrices. Phasellus eu tellus sit amet tortor gravida placerat. Integer sapien est, iaculis in, pretium \begin{wrapfigure}{r}{0.4\textwidth}\raggedright\setstretch{1.3}
            \textcolor{red}{\hrule height 2pt}

            \medskip

            \lipsum[2]

            \textcolor{red}{\hrule height 2pt}
\end{wrapfigure}
quis, viverra ac, nunc. Praesent eget sem vel leo ultrices bibendum. Aenean faucibus. Morbi dolor nulla, malesuada eu, pulvinar at, mollis ac, nulla. Curabitur auctor semper nulla. Donec varius orci eget risus. Duis nibh mi, congue eu, accumsan eleifend, sagittis quis, diam. Duis eget orci sit amet orci dignissim rutrum.

\lipsum[3-4]

\end{document}


text:
Q: Highcharts Scatter Plot Performance I'm new to Highcharts and have been tinkering with it a bit on jsFiddle.
A fiddle independent example would look something like this:
<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>

Anyways, I have a series that consists of a large set (~16k) of (datetime,float) Cartesian points that I wish to visualize on a scatter plot.  I got what I wanted, but it appears to make my browser really sluggish. Particularly if I re-size the window or hover over tooltips.  Looking for any advice or tips to optimize the performance or point out (no pun intended) something else I should be doing instead for this kind of visualization.

A: A couple of things you could do are to remove animation on the chart itself, and the tooltip.  Also if you can get away with it, you could only render a tooltip for every 10th point.
http://jsfiddle.net/Jx5n2/3653/
chart: {
    renderTo: 'container',
    type: 'scatter',
    zoomType: 'xy',
    animation:false
},

tooltip:{
    animation:false,
    formatter:function(){
        if(this.x % 10 != 0) return false;
        return 'The value for '+ this.x +
                ' is '+ this.y +'';
    }
},


text:
Q: Differences between iPhone and iPod Touch I am looking for the cheapest way to test websites and HTML email on a device that behaves like "the latest iPhone running the latest iOS". I have heard that the iPod Touch 6 is supposedly identical to the iPhone 6, except for not having a GSM radio chip.
From a developer perspective, what are the differences between the iPhone and the iPod Touch? Do they run the exact same OS? And if I eventually move on to proper iOS apps, will these behave exactly the same on an iPod Touch?

A: iPod touch runs iOS exactly like an iPhone... same updates and same apps, the only thing is that you can't use the hardware that the iPod doesn't have (GSM).


text:
Q: Null value passed in Safari to server We have a C#.NET MVC 4 application with MVVM on the client side. When performing a particular action in the application the parameters in the client that are going to be passed to the webAPI are OK but once in the webAPI the controller receives a null parameter instead so it gives an error.
   This happens only the first time we perform the action, the second time works fine and this ONLY happens when running the application on Apple Safari (it works fine in Microsoft Internet Explorer, Google Chrome and Mozilla Firefox).
   Any ideas?
   Thanks in advance.


text:
Q: Posts with Custom Fields does not appear Plugin used: Types
I have created posts with Custom Posts and the regular Posts by Wordpress. However, the custom posts does not appear on the website. Only the regular posts appears.
Here I have created Custom Posts:

Here I have created posts with the regular Wordpress posting:

Here are the 2 latest posts within the category 9 (Featured) supposed to be shown:

As you see, it does not show the one made with Custom Post. This is not the only example, but this is the easiest one to explain.
Code

            <?php
                $catquery = new WP_Query( 'cat=9&posts_per_page=2' );
                while($catquery->have_posts()) : $catquery->the_post();
            ?>

                            <?php the_post_thumbnail( 'singlepost-thumb' ); ?>

                                <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?>

                                <?php the_content(); ?>

                            <a href="<?php the_permalink() ?>" rel="bookmark">
                                <button class="btn thin luft" type="button">Se prosjekt</button>

                <?php endwhile; ?>

Anyone?
I will post detailed if you want, I just need to know what you want to know.
Is there a function I need to make Custom Fields Post to work?
Suggestions:

*

*Functions.php, something is wrong here

*Types, something is wrong the setup

A: The problem was solved by making it display all post types:
$args = array(
    'cat' => 9,
    'posts_per_page' => 2,
    'post_type' => 'any',
);
new WP_Query($args);


text:
Q: How to place an Admob ads bottom center of the screen?(Using java code to place.) I used this code to place my admob ads, but these code will show the ads on top left of the screen, How to place the ads bottom center of the screen?  please help :)
mAdView = new AdView(this, AdSize.BANNER, "xxxxx");
FrameLayout layout = (FrameLayout)findViewById(R.id.game_layout);
layout.addView(mAdView);
FrameLayout.LayoutParams adsParams = new FrameLayout.LayoutParams(LayoutParams.);
mAdView.setGravity(Gravity.BOTTOM);
mAdView.loadAd(new AdRequest());

A: The Height and Width layout Params for the FrameLayout should be FILL_PARENT. By Default it consider the height layout Param as WRAP_CONTENT and because of that even you have set the GRAVITY to BOTTOM your ads displayed on TOP.
SET the Layout Params as I said.

A: You can also use
mAdView.setX([float x]);
mAdView.sety([float y]);

to set the position of Your ads.

A: adView = new AdView(Cocos2dxActivity.this, AdSize.SMART_BANNER, "mediationId");
adView.setGravity(Gravity.BOTTOM);


text:
Q: Offline World Satellite Map Without Labels(Android) I want to include a MapView in my Application. I have been playing around with the Google Api a bit and it worked quite well.
But now I want to have a map completely offline.
I know there are a lot of possibilities to do this.
The problem is that I would like to have a world map without any labels such as country names, state names, city names and so on.
I just want a map with country borders. It should be possible to zoom in and out and to set markers at specific locations. It should also be possible to tap somewhere in the screen and to get the coordinates in a specific format (e.g WGS84).
Also it would be pretty nice if it would be a satellite overview or something like the mapquest view on OpenStreetMap.org .
I know that there are things like Osmdroid or Mapsforge. But I havent seen a possibility to disable all the (for me) unnecessary labels yet.
Correct me if i am wrong :)
Thank you in advance.

A: In mapforges you can set label text size. I've never tried to set it to 0 to see if they disapear.
If not, as source code is available in http://code.google.com/p/mapsforge/, you can override the label drawing and recompile it.
Regards.


text:
Q: I have problems with thread Before that, I had hidden fields and displayed new ones. All this happened in 1 activity. Now I decided to break them into 2 activities. So that when you press the button immediately moved to the main thread. Now I have trubl with "Only the original thread that created a view hierarchy can touch its views." Also I add Handler.
public class Main3Activity extends AppCompatActivity {
    Button button1;
    TextView tv;
    ListView listView1;
    private static String TAG_SCHEDULE = "raspisanie";
    private static String TAG_ID = "id";
    private static String TAG_PREDM = "urok";
    private static String TAG_TIME = "id_day";

    ArrayList<HashMap<String, String>> scheduleList;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        scheduleList = new ArrayList<HashMap<String, String>>();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                ListAdapter adapter = new SimpleAdapter(Main3Activity.this, scheduleList, R.layout.activity_column, new String[]{TAG_TIME, TAG_PREDM}, new int[]{R.id.Coldayid, R.id.ColUrok});

                ListView lv = (ListView) findViewById(R.id.listView1);
                lv.setAdapter(adapter);
            }
        };
    }

    public String url1 = "https://domex666.000webhostapp.com/rasp4.php?id_group=";
    public void tester(View view) {
        updateHTTP();
    }
    public String getURL() {
         button1 = (Button) findViewById(R.id.button1);
        Intent intent = getIntent();
        tv = (TextView) findViewById(R.id.tv);
        String grp = intent.getStringExtra("grp");
        String uri = "";
        tv.setText(grp);
        String id_group = tv.getText().toString();
        uri = url1 + id_group;
        Log.d("URL Request >>",uri);
        return uri;
    }
    protected void updateHTTP() {
        scheduleList.clear();
        Log.d("GO GO >>","START THIS PROGRAMM");

        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {
                try{
                    String newURL = getURL();
                    URL url = new URL(newURL);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(15000);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream stream = conn.getInputStream();
                    String data = convertStreamToString(stream);
                    Log.d("DATA >> ",data);
                    JSONObject dataJsonObj = new JSONObject(data);
                    JSONArray products = dataJsonObj.getJSONArray(TAG_SCHEDULE);

                    for(int i = 0; i < products.length();i++) {
                        JSONObject schedule = products.getJSONObject(i);
                        String id_sched = schedule.getString(TAG_ID);
                        String predm = schedule.getString(TAG_PREDM);
                        String time = schedule.getString(TAG_TIME);
                        HashMap<String, String> sched = new HashMap<String, String>();
                        sched.put(TAG_ID, id_sched);
                        sched.put(TAG_PREDM, predm);
                        sched.put(TAG_TIME,time);
                        scheduleList.add(sched);
                    }

                    Message msg = new Message();
                    msg.obj = scheduleList;
                    handler.sendMessage(msg);
                    Log.d("Request >>>>","SUCCESS");
                } catch (Exception e) {
                    Log.d("ERROR ctaciv>",e.getMessage());
                }
            }

        });

        thread.start();
    }

    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

}


text:
Q: Redshift skip the first character of split_part() I have a table column like below:
| cloumn_a           |
| ------------------ |
| Alpha_Black_1      |
| Alpha_Black_2323   |
| Alpha_Red_100      |
| Alpha_Blue_2344    |
| Alpha_Orange_33333 |
| Alpha_White_2      |
|                    |

Usually, when I want to split with any symbol or character I am using the split_part(text, text, integer) so split_part(column_a, '_', 1)
I need to remove the numeric part of each variable and keep only the text part like Alpha_Black.
I cannot use the trim function because the numeric part can change
How can I skip the first underscore and split from the second one?

A: I would suggest using REGEXP_REPLACE here:
SELECT
    column_a,
    REGEXP_REPLACE(column_a, '_\\d+$', '') AS column_a_out
FROM yourTable;

Demo


text:
Q: MicrosoftMvcAjax breaks jQuery validate plugin
Possible Duplicate:
jquery validate & ajax.beginform

I'm trying to use the jQuery validate plugin to validate a form (Ajax.BeginForm). When I enter invalid data on the form the error messages are shown but the form will submit anyway.
How do I stop MicrosoftMvcAjax from submiting an invalid form?
Thanks in advance

A: Ok, I got it!
All I need to do is pass the validate function to the OnBegin event in the AjaxOptions:
<% using (Ajax.BeginForm("SendMail", "Mail", new { @id = "MailForm", @class = "cmxform" }, new AjaxOptions { UpdateTargetId = "dialog", OnBegin = "validate" }, new { @id = "MailForm" }))
       { %>


text:
Q: Join with all values match in second table I have 3 tables Users, UserRoles, Roles.
I'm trying to select users who has exact roles.
SELECT *
FROM Users
LEFT JOIN UserRoles ON UserRoles.UserId = Users.UserId
LEFT JOIN Roles ON Roles.RoleId = UserRoles.RoleId
WHERE Roles.RoleId IN (1,2)

I'm getting valid result but, I get users who are also only in RoleId = 1 or only in RoleId = 2.
How can I select only users who contains 2 (or more) exact roles?

A: If you want to be sure both roles exist, you can test for both roles e.g.
SELECT *
FROM Users U
WHERE EXISTS (
  SELECT 1
  FROM UserRoles UR
  INNER JOIN Roles R ON R.RoleId = UR.RoleId
  WHERE UR.UserId = U.UserId and R.RoleId = 1
)
AND EXISTS (
  SELECT 1
  FROM UserRoles UR
  INNER JOIN Roles R ON R.RoleId = UR.RoleId
  WHERE UR.UserId = U.UserId and R.RoleId = 2
);

Note the use of aliases for clarity. And inner join's since there shouldn't be a null case.

A: If you want the User ID of users that have 2, or more, roles, use a HAVING:
SELECT U.UserID
FROM dbo.Users U
     JOIN dbo.UserRoles UR ON U.UserID = UR.UserID
     JOIN dbo.Roles R ON UR.RoleID = R.RoleID
GROUP BY U.UserID
HAVING COUNT(R.RoleID) >= 2;

If you want to them have specific roles you just add the WHERE to limit them; like you have in your attempt. If you're looking for 3 specific roles, just ensure you change the HAVING to >=3 (or the appropriate number).

A: You can use analytical function as follows:
select * from
(SELECT u.*, count(distinct Roles.RoleId) over (partition by Users.UserId) as cnt
FROM Users
LEFT JOIN UserRoles ON UserRoles.UserId = Users.UserId
LEFT JOIN Roles ON Roles.RoleId = UserRoles.RoleId
WHERE Roles.RoleId IN (1,2) ) t
where cnt = 2


text:
Q: Export all tables in database using SQLCMD I'm looking to export all tables from a SQL Server Standard Edition database with data into CSV files onto a remote linux server. I setup FreeTDS and am able to connect, do SQLCMD or bcp successfully.
I know we can use SQLCMD but I was wondering if there is a way that we can write each table into its individual CSV file using a single connection instead of looping through every table in the database and writing to a CSV file.
Any thoughts if its possible?
Thanks in advance,
simak

A: I looked into doing this years ago and looked into both BCP and SSIS. Neither one really provided for great flexibility. BCP needed format files to get the text-qualifiers, etc. But this was for a dynamic backup solution for a subset of tables to get archived nightly. SSIS seemed a bit more dynamic (though not fully), but couldn't do a few of the things that BCP could. I needed something that could dynamically accept changes to tables (include new tables, don't require removed tables) AND changes to columns (as I needed to do "SELECT * FROM {SchemaName}.{TableName};") AND dynamic text-qualification AND column headers, etc.
If you have a static set of tables, then SSIS, using a ForEach container, would be one way to do this (again, assuming the desire is to stay away from BCP due to requiring multiple calls).
Using PowerShell would probably also be an option that would allow for more flexibility than SSIS.
However, if you need something fully dynamic and/or need to stick with a single connection  per each DB (all tables in that DB) or even a single connection per server (all tables for all databases), then the only way I have ever found to handle this is the one that I created. It is a SQLCLR stored procedure called DB_BulkExport which has parameters for @Query and @FilePath that allow for easily cycling through a list of all databases, then per each one cycling through a list of tables, and building both the query and filename from those pieces. You could write a fairly simple stored proc that uses a cursor to get the Database and Table names and call this proc, hence being a single call to SQLCMD.EXE to call that one proc. Or it can be scheduled via SQL Agent without needing to enable xp_cmdshell.
This procedure -- DB_BulkExport -- is part of the SQL# library (which I am the creator of), though it is only available in the Full (i.e. paid for) version, not in the Free version. I generally do not mention stuff here that is not available in the Free version, but as I said, I am not aware of any other existing means of automating this type of process. Of course, anyone is free to write this themselves, either as a SQLCLR proc as I have done, or as a stand-alone .NET app, or using PowerShell. It is more than a few lines of code in C# and I suspect it is also not overly simplistic in PowerShell either (but I haven't tried and don't have enough experience with PowerShell to really know).

EDIT:
Regarding how I have used the above mentioned stored proc in at least one instance: It was used to export data nightly, for long-term archival, the oldest day from a large table that was itself a common, short-term archival of data from 20 source servers.

*

*It would extract maybe 10 million rows for a given date

*The table held 150 - 450 million rows (fluctuation due to several factors)

*It would grab all records for the oldest date and export them to a delimited file

*1 day was 5 million rows (avg)

*Each row was 1240 bytes (avg; 2 URLs plus a few other text fields, etc)

*The file was 3 GB - 6 GB depending on the day

*It exported to a local temp folder so that it didn't need to go across the network.

*The archival process then:

*

*used the File_GZip function -- which can handle zip64 (i.e. source files over 4 GB) -- to compress the text file down to 1 GB - 2 GB (no, it didn't take much memory; buffer is 8k)

*used File_Copy to copy the .gz file to a networked archive folder

*used File_Delete to remove the local file(s)

*If the above steps completed successfully, the date of the data that was just archived was placed into a queue table for another SQL Agent job to pick up and incrementally (in small batches as the table was constantly being filled from the 20 source servers) delete the records from the archive table.
So to amend the description above of the archival process: it would extract the oldest date that was not in this queue table.

*Once all of the records had been deleted the date being deleted would be removed from the queue table.

Ideally there would be a local drive that would not have pagefile, mdf, or ldf files on it that could be used for the extraction and compression. For the long-term archival process noted above, that server was a dedicated archive that just collected data for a few tables from the 20 source servers. Hence the only querying of the data 99% of the time was the SELECT * FROM ArchiveTable to do the extract; the other 1% of the time it was research.


text:
Q: Утечка памяти при использовании Vuex Пишу MMO RTS. На фронте использую Vue. С заданной периодичностью, с сервера, по WebSoket, прилетают обновленные данные. Естественно, данные помещаются во Vuex, за которым следят компоненты.
Обнаружил, что с каждым новым коммитом увеличивается потребление памяти. Если оставить вкладку открытой, то браузер вылетает.
Ниже код демонстрирующий проблему: запустите, откройте консоль - вкладка Memory -  и наблюдайте

const data = {
  lvl: 0,
  a: {
    lvl: 1,
    b: {
      lvl: 2,
      c: {
        lvl: 3
      }
    }
  }
}
const store = new Vuex.Store({
  state: {
    count: 0,
    data: []
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    set_data(state, payload) {
      state.data = payload;
    }
  },
  actions: {
    increment(context) {
      setInterval(() => {
        context.commit('increment');
        const newData = JSON.parse(JSON.stringify(data));
        context.commit('set_data', newData);
      }, 500);
    }
  }
});

var app = new Vue({
  store,
  el: '#app',
  template: `

{{count}}
`,
  data() {
    return {
      count: 0,
      d: window.performance.memory.totalJSHeapSize
    };
  },
  created() {
    this.$store.dispatch('increment');
  },
  watch: {
    '$store.state.data': {
      deep: true,
      handler() {
        this.count = this.$store.state.count;
      }
    }
  }
});

Новость для меня печальная). Четкого понимания, как решить проблему - пока нет.
UPD
Обнаружился нюанс: если html-файл, с этим примером, открыть не через сервер, а полному пути в адресной строке, то утечки нет.

A: Я думаю что дело не VUEX, а в компонентах что на него подписаны.
Скорее всего один из их складывает данные в локальную коллекцию или массив и после изменения хранилища не чистит их.
Попробуй отключить все подписки на изменения, компонент за компонентом пока не найдешь.

A: Как оказалось,проблема была во Vuex. Если подключить последнюю версию (3.1.2), то это убирает утечку в моем демо-примере.

const data = {
  lvl: 0,
  a: {
    lvl: 1,
    b: {
      lvl: 2,
      c: {
        lvl: 3
      }
    }
  }
}
const store = new Vuex.Store({
  state: {
    count: 0,
    data: []
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    set_data(state, payload) {
      state.data = payload;
    }
  },
  actions: {
    increment(context) {
      setInterval(() => {
        context.commit('increment');
        const newData = JSON.parse(JSON.stringify(data));
        context.commit('set_data', newData);
      }, 500);
    }
  }
});

var app = new Vue({
  store,
  el: '#app',
  template: `

{{count}}
`,
  data() {
    return {
      count: 0,
      d: window.performance.memory.totalJSHeapSize
    };
  },
  created() {
    this.$store.dispatch('increment');
  },
  watch: {
    '$store.state.data': {
      deep: true,
      handler() {
        this.count = this.$store.state.count;
      }
    }
  }
});

Но, к сожалению, в моем приложении утечка не исчезла. Но это уже другая история
Продолжение истории: В итоге, пришел к выводу, что утечка максимально себя проявляет в дев-режиме. Поэтому у меня 2 подозреваемых: сам vue/vuex и vue-dev-tools, при этом, после иследования срезов памяти, больше склоняюсь к vue-dex-tools. Т.к. утечка памяти, сама по себе "пахнет" не очень хорошо, я все равно постарался ее минимизировать. Для этого мне пришлось во всех "тонких местах" (watch, computed, store ...) присвоение объектов делать после их глубокого копирования. После таких манипуляций, в дев-режиме, стала заметна работа сборщика мусора. В конечном счете, объем потребляемой памяти все равно растет, но стали заметны откаты. Что же касается прод-режима, то там стало все замечательно.


text:
Q: Wordpress 4.* adds paragraph in shortcodes while using get_template_* I've a big problem. I'm using several shortcodes within my template but the output is always wrong. It adds several
 tags to my output, even when I add filters.
The
 are set even when there are no open
 tags.
Here's a part of my code. I tried everything to remove the paragraphs but no result.
I've shrinked the code for easier reading.
function pull_team_shortcode($atts) {
    $output = '';
    $tplgenerator = new Team_Template_Generator();
    $output .= $tplgenerator->generate_output();
    $output = trim($output);
    return "
" . bic_rm_wpautop($output) . "
";
}

add_shortcode('simple-team', 'pull_team_shortcode', 25);

A simple truncated class to load a template and return it back.
class Team_Template_Generator {
  public function generate_output() {
        ob_start();
            set_query_var('myposts', get_posts($args));
            get_template_part($this->templates . $this->template_name);
            $var = ob_get_contents();
            ob_get_clean();
            return trim($var, ".\r\n");
        }
    }
}

and a template..
<?php
$extra_class = get_query_var("extra_class");
$title = get_query_var("title");
$subtitle = get_query_var("subtitle");
?>

    <div class="row<?php if ($extra_class != "") echo " " . $extra_class; ?>">

                <?php
                if ($title != "" || $subtitle != "") {
                    ?>

                        <?php
                        if ($title != "") {
                            echo '
' . esc_html($title) . '
';
                        }
                        ?>

                            <?php
                            if ($subtitle != "") {
                                echo esc_html($subtitle);
                            }
                            ?>

                <?php } ?>

                    <?php
//valid meta fields:
// short_bio, email, designation, web_url, telephone, location, social, profile_title, profile_linkedin, _thumbnail_id
                    foreach (get_query_var("myposts") as $post) {
                        //     echo "
" . print_r($post, true) . "
";
                        $meta = get_post_custom($post->ID);
                        ?>

                                <?php the_post_thumbnail("medium", array('class' => 'img-responsive')); ?>

<a href="<?php echo $meta['profile_facebook'][0]; ?>">

<a href="<?php echo $meta['profile_twitter'][0]; ?>">

<a href="<?php echo $meta['profile_linkedin'][0]; ?>">

<?php echo trim($post->post_title); ?>

<?php echo trim($meta['profile_title'][0]); ?>

<?php echo trim($post->post_content); ?>

                    <?php } ?>

this is a part of the output which adds
 tags even if they are not open before.

Christian Stimmer

Sales Leader

Christian Stimmer Data

Before i have included the file for adding the short code i've added in functions.php the following hack:
remove_filter('the_content', 'wpautop');
add_filter('the_content', 'wpautop', 99);

but this didn't change anything. Any idea why it still generated
 tags around?

A: Just to check: have you tried removing wpautop and not adding it again? Do you still get the extra lines?


text:
Q: matplotlib: how do I easily fit the plot to the canvas May be that is a simple question - but I tried to solve it several times - and just can't make it work. My problem is that - my plot is larger than the canvas:
Is there a way to make plot fit to the canvas - without changing the canvas size?
Here's the code that I use to make a plot (thanks to the Louis):
da = plt.figure()
l1 = da.add_subplot(111).plot(dummyZ, delta_a, "k-")
da.add_subplot(111).set_xlabel(r"$z/L$")
da.add_subplot(111).set_ylabel(r"$\delta a(z)$")
da.add_subplot(111).grid(True)
da.savefig("da.png")

And here's the preambule:
import matplotlib.pyplot as plt
plt.rcParams['font.size']=18

Edit:
That's what I'm using now:
da = plt.figure()
l1 = da.add_subplot(111).plot(dummyZ, delta_a, "k-")
da.add_subplot(111).set_xlabel(r"$z/L$")
da.add_subplot(111).set_ylabel(r"$\delta a(z)$")
da.add_subplot(111).grid(True)
da.subplots_adjust(left=0.2, bottom=0.15) # !!!
da.savefig("da.png")

A: If I understand correctly the question, you want more room on the left to get the scale title ?
This is to be done with
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

I had it with a simple
subplots_adjust(top=0.8)

to adjust the top of one of my draws.
Hope this could help.