text:
Q: How can I draw neuro-fuzzy? I try to reproduce the figure below, but I am having difficulties with the connection between inputs x1 and x2 with the first four blocks of "layer 1" and with connecting layer 1 with the nodes of "layer 2".

here is my code :
    \documentclass[tikz, border=0.125cm]{standalone}
\usetikzlibrary{calc, fit, positioning, quotes}% new libraries
   \begin{document}
\tikzset{
  every neuron/.style={rectangle, draw, minimum size=8mm},
  layer labels/.style={above, align=center},
  cercle/.style={circle,draw,fill=black!25,minimum size=17pt,inner sep=0pt}
        }
    \begin{tikzpicture}[x=16mm, y=16mm, >=stealth]
% neuron nodes with part of labels
\foreach \g  [count=\y] in {1,2,3,4}
\foreach \b/\l in { 0/L}
{
\node[every neuron/.try, neuron \g/.try](n\b\g) at (\b,2.5-\y){}

}
\foreach \m [count=\y] in {1,2}
\foreach \j/\l in { 2/H, 4/S}
{
\ifnum\y<3
\node [every neuron/.try, neuron \m/.try] (n\j\m) at (\j,2.5-\y) {};
\else
\node [every neuron/.try, neuron \m/.try] (n\j\m) at (\j,2.5-\y) {};
\fi
}
% neuron labels not included in neuron nodes
%\foreach \l/\k in {I_K/0, H_L/2}
%\node [above] at (n\k2.north) {$\l$};
% inputs
\foreach \l [count=\i] in {1,2}
\draw [<-] (n0\i.west) -- ++(-1.1,0) node (in\i) [above, midway] {$x_\l$};
%\node (input) [draw, inner ysep=2mm, yshift=-2mm, fit=(in1) (in2)] {};
% w and L outputs
\foreach \l [count=\i] in {1,2}
\draw [->] (n4\i.east) -- ++(1.6,0)
    node (wout\i) [above, midway] {$x_\l$}
   node (Lout\i) [right, draw, minimum size=8mm, label=$L_\i$] {};% Local Model

% output
\node (output) [cercle,right=16mm] at ($(Lout1.east)!0.5!(Lout2.east)$) {};
\draw [->] (output.east) to["$\hat{y}$"] ++(1.1,0);
% neurons interconection
 \foreach \i in {1,2}
 \foreach \j in {1,2}
{
\draw [->] (n0\i) -- (n2\j);
\draw [->] (n2\i) -- (n4\j);
}
\foreach \j [count=\i] in {1,2}
\draw [->] (Lout\i.east) to ["$\hat{y}_\j$"] (output);
% neuron layers labels
\foreach \l [count=\x from 0] in {1,2,3,4,5}
\node [layer labels] at (\x*2,2.2) {Couche \\\l};
%\node [layer labels] at (6,2.2)    {Local \\ Model};
%\node [layer labels] at (8,2.2)    {Output \\ Agregation};
% x-fit L-fit conections

   \end{tikzpicture}

   \end{document}

A: I am not sure exactly what you want, but if you want to have a single point where to start the x_1 and x_2 lines you can use:
\foreach \l [count=\i] in {1,2} {
    \draw [->, red] (-1.1,1.0) -- (n0\i.west)
        node (in\i) [above, midway] {$x_\l$};
}

Code:
\documentclass[border=0.125cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc, fit, positioning, quotes}% new libraries
\begin{document}
\tikzset{
  every neuron/.style={rectangle, draw, minimum size=8mm},
  layer labels/.style={above, align=center},
  cercle/.style={circle,draw,fill=black!25,minimum size=17pt,inner sep=0pt}
        }
    \begin{tikzpicture}[x=16mm, y=16mm, >=stealth]
% neuron nodes with part of labels
\foreach \g  [count=\y] in {1,2,3,4}
\foreach \b/\l in { 0/L}
{
    \node[every neuron/.try, neuron \g/.try](n\b\g) at (\b,2.5-\y){};
}
\foreach \m [count=\y] in {1,2}
\foreach \j/\l in { 2/H, 4/S}
{
\ifnum\y<3
\node [every neuron/.try, neuron \m/.try] (n\j\m) at (\j,2.5-\y) {};
\else
\node [every neuron/.try, neuron \m/.try] (n\j\m) at (\j,2.5-\y) {};
\fi
}
% neuron labels not included in neuron nodes
%\foreach \l/\k in {I_K/0, H_L/2}
%\node [above] at (n\k2.north) {$\l$};
% inputs
\foreach \l [count=\i] in {1,2} {
    \draw [->, red] (-1.1,1.0) -- (n0\i.west)  node (in\i) [above, midway] {$x_\l$};
}
%\node (input) [draw, inner ysep=2mm, yshift=-2mm, fit=(in1) (in2)] {};
% w and L outputs
\foreach \l [count=\i] in {1,2}
\draw [->] (n4\i.east) -- ++(1.6,0)
    node (wout\i) [above, midway] {$x_\l$}
   node (Lout\i) [right, draw, minimum size=8mm, label=$L_\i$] {};% Local Model

% output
\node (output) [cercle,right=16mm] at ($(Lout1.east)!0.5!(Lout2.east)$) {};
\draw [->] (output.east) to["$\hat{y}$"] ++(1.1,0);
% neurons interconection
 \foreach \i in {1,2}
 \foreach \j in {1,2}
{
\draw [->] (n0\i) -- (n2\j);
\draw [->] (n2\i) -- (n4\j);
}
\foreach \j [count=\i] in {1,2}
\draw [->] (Lout\i.east) to ["$\hat{y}_\j$"] (output);
% neuron layers labels
\foreach \l [count=\x from 0] in {1,2,3,4,5}
\node [layer labels] at (\x*2,2.2) {Couche \\\l};
%\node [layer labels] at (6,2.2)    {Local \\ Model};
%\node [layer labels] at (8,2.2)    {Output \\ Agregation};
% x-fit L-fit conections
\end{tikzpicture}
\end{document}

A: You could try the following:
\documentclass[tikz, border=0.125cm]{standalone}
\usetikzlibrary{calc, positioning, quotes} % new libraries

\begin{document}

\tikzset{
  every neuron/.style={rectangle, draw, minimum size=8mm},
  layer labels/.style={above, align=center},
  cercle/.style={circle,draw,fill=black!25,minimum size=17pt,inner sep=0pt}
}

\begin{tikzpicture}[x=16mm, y=16mm, >=stealth]

% neuron nodes with part of labels
\foreach \g  [count=\y from 0] in {1,2,3,4} {
\foreach \b/\l in {0/L} {
    \node[every neuron/.try, neuron \g/.try](n\b\g) at (\b,2.5-\y){};
} }

\foreach \m [count=\y] in {1,2} {
\foreach \j/\l in {2/H, 4/S} {
    \ifnum\y<3
    \node [every neuron/.try, neuron \m/.try] (n\j\m) at (\j,2.5-\y) {};
    \else
    \node [every neuron/.try, neuron \m/.try] (n\j\m) at (\j,2.5-\y) {};
    \fi
} }

% inputs
\foreach \i/\j/\k in {1/2/x,3/4/y} {
    \draw [<->] (n0\i.west) -- ++(-1.1,-.5) node[left] {$\k$} -- (n0\j.west);
}

% w and L outputs
\foreach \l [count=\i] in {1,2} {
    \draw [->] (n4\i.east) -- ++(1.6,0)
    node (wout\i) [above, midway] {$x_\l$}
    node (Lout\i) [right, draw, minimum size=8mm, label=$L_\i$] {};
}

% output
\node (output) [cercle,right=16mm] at ($(Lout1.east)!0.5!(Lout2.east)$) {};
\draw [->] (output.east) to["$\hat{y}$"] ++(1.1,0);

% neurons interconection
\foreach \i [count=\j] in {1,2,1,2} {
    \draw [->] (n0\j) -- (n2\i);
}
\foreach \i in {1,2} {
\foreach \j in {1,2} {
    \draw [->] (n2\i) -- (n4\j);
} }

\foreach \j [count=\i] in {1,2} {
    \draw [->] (Lout\i.east) to ["$\hat{y}_\j$"] (output);
}

% neuron layers labels
\foreach \l [count=\x from 0] in {1,2,3,4,5} {
    \node [layer labels] at (\x*2,3) {Couche \\ \l};
}

\end{tikzpicture}

\end{document}


text:
Q: Erro 500 em Biblioteca Asp.Net Awesome Eu encontrei navegando pela internet essa biblioteca ASP.net Awesome. Achei ela bem funcional e fácil de se usar.
De acordo com a documentação pra se usar um helper chamado Lookup, precisa se ter um controller e chamar o helper no cshtml. O que acontece é que, no meu projeto, tá exatamente igual ao da documentação(o código), e to tendo um erro 500 e não sei exatamente porque.
Já pesquisei e não consegui resolver o erro, será que alguém poderia me ajudar ?

*

*Explicando o Lookup faz: Ele abre um popup com uma lista do que tem em sua tabela pra você selecionar e popular um campo de texto. Tem como fazer um procura pra achar exatamente o que você quer. E é exatamente nesse método Search que ta dando erro, ele teria que carregar todos os meus registros do banco de dados, os nomes dos alunos. mas ele dá erro 500.

O código do controller é esse:
public class AlunoLookupController : Controller
{
    private EntidadesContext db = new EntidadesContext();
    //Aqui ele pega o item que foi selecionado e joga no campo de texto
    public ActionResult GetItem(int? v)
    {
        var o = db.Alunos.SingleOrDefault(f => f.Id == v) ?? new Aluno();

        return Json(new KeyContent(o.Id, o.Nome));
    }
    // E aqui ele faz a busca dos registros no banco e exibe no popup
    //E aqui tabém dá erro, ele não acha nenhum registro e só fica carregando
    public ActionResult Search(string search, int page)
    {
        search = (search ?? "").ToLower().Trim();
        var list = db.Alunos.Where(f => f.Nome.ToLower().Contains(search));

        return Json(new AjaxListResult
        {
            Items = list.OrderBy(n => n.Nome).Skip((page - 1) * 7).Take(7).Select(o => new KeyContent(o.Id, o.Nome)),
            More = list.Count() > page * 7
        });
    }
}

Tenho certeza que problema ta no código que eu puxei de lá, mas não sei o que é que ta acontecendo.
O erro que aparece é o seguinte:

Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.
Detalhes da Exceção: System.NotSupportedException: Only parameterless constructors and initializers are supported in LINQ to Entities.

A: Vamos lá, eu resolvi o problema. O problema é que eu acho que o código é meio antigo, e por isso não funcionou bem do jeito que está no site. Então eu pesquisei e usei como referência esse link aqui. o que acontece é que ele não estava conseguindo conectar com o banco pra fazer a lista, então tive adaptar o código, que está logo abaixo para quem quiser usar a biblioteca também:
public class AlunoLookupController : Controller
{
    private EntidadesContext db = new EntidadesContext();
    public ActionResult GetItem(int? v)
    {
        var o = db.Alunos.SingleOrDefault(f => f.Id == v) ?? new Aluno();

        return Json(new KeyContent(o.Id, o.Nome));
    }

    public ActionResult Search(string search, int page)
    {
        search = (search ?? "").ToLower().Trim();
        var lista = db.Alunos.Where(f => f.Nome.Contains(search)).ToList();
        return Json(new AjaxListResult
        {
            Items = lista.OrderBy(f => f.Nome).Skip((page - 1) * 7).Take(7).Select(o => new KeyContent(o.Id, o.Nome)),
            More = lista.Count() > page * 7
        });
    }
}

Lembrando que esse código ai em cima, tem que estar no controller que você quer manipular a informação, mas fora das actions normais que são criadas, por exemplo Home, ele tem que estar abaixo dessa action, mas na mesma classe como abaixo:
 public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

E aqui em baixo dele o código do controller que o ASP.net Awesome usa:
public class AlunoLookupController : Controller
{
    private EntidadesContext db = new EntidadesContext();
    public ActionResult GetItem(int? v)
    {
        //Os códigos das actions
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Self-hosted Git Server с поддержкой lfs locks Прошу подсказать ПО, которое может выполнять функции self-hosted Git Server с поддержкой lfs locks API
Основные требования к ПО:

*

*Запуск сервиса локально(на своем железе, "облачные" сервисы не подходят)

*Кроссплатформенность(как минимум Windows/Lnux)

*Наличие Web-интерфейса

*OpenSource(крайне желательно)

*FreeWare для небольшой команды(менее 20)

*Поддержка git lfs lock API
У нас много двоичных файлов, над которыми могут работать несколько человек.
Их мерж - боль.
Поэтому файлы нужно блокировать(лочить) на время работы одного из участников с этими файлами.
Сейчас используем GOGS.
Он подходит по всем требованиям, кроме последнего.


text:
Q: Need the last day of the current date to be passed in angular 7 I am trying to pass date to a method in my angular application in shortdate format but the day needs to be last day of the month. How do I do that
This is what I have done
import {formatDate} from '@angular/common';

 this.allocationsComponent.getAllocationsDetails(formatDate(new Date(), 'yyyy/MM/dd', 'en'));

The result is
2019/04/02

A: Try this:
var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
this.allocationsComponent.getAllocationsDetails(formatDate(lastDayOfMonth, 'yyyy/MM/dd', 'en'));

A: Javascript's Date has an interesting quirk: The 0th day of a month is the last day of the previous month:
> var d=new Date();
Tue Apr 02 2019 14:40:02
> d.setDate(0);
Sun Mar 31 2019 14:40:02

A: simple methods and Reduced/single line of code
this.allocationsComponent.getAllocationsDetails(formatDate(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)), 'yyyy/MM/dd', 'en'));


text:
Q: Bluetooth Tethering Windows 10 & Nexus 5x I am trying to setup bluetooth tethering between a Windows 10 Laptop and a (rooted) Nexus 5X Android device, running the latest 6.0.1 version of Android (update from March 2016).
I have managed to pair the two devices, install the Bluetooth network adapter, but I fail to connect the phone as an access point. When I click the "Connect Using..." on the device in the list, I can only find the "Direct connection" which does not do anything. From what I found online, I need to have a "Access Point" option in the dropdown. Also, the device shows in the properties -> Services screen only "Remote Control" and "SMS/MMS" as options. I would assume that there needs to be some kind of "Network" service?


text:
Q: ReferenceError: dhtmlXCellObject is not defined / TypeError: this._hdrInit is not a function I have a map with google maps api, and a table, which I want to connect to the map with dHTMLx Layout. (I'm a beginner, so sorry about the question, but I haven't found any solution yet, and I already checked the references in the code) I have this code:

<head>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">

    <title>Map</title>
    <link rel="stylesheet" type="text/css" href="dhtmlxlayout_dhx_skyblue.css">
    <link rel="stylesheet" type="text/css" href="dhtmlxlayout.css">

    <script type="text/javascript" src="dhtmlxlayout.js"></script>
    <script type="text/javascript" src="dhtmlxcommon.js"></script>
    <script type="text/javascript" src="dhtmlxcontainer.js"></script>
    <script type="text/javascript" src="dhtmlxlayout_deprecated.js"></script>

</head>

<body>

    <script>

        var dhxLayout = new dhtmlXLayoutObject(document.body, "2U");
        dhxLayout.cells("a").setText("Térkép");
        dhxLayout.cells("a").attachURL("googleapi.html");
        dhxLayout.cells("b").setText("Táblázat");
        dhxLayout.cells("b").setWidth(500);
        dhxLayout.cells("b").attachURL("list.html");

    </script>

</body>

What does the 2 error means? ReferenceError: dhtmlxCellObject is not defined & TypeError: this._hdrInit is not a function both in dhtmlxlayout.js
What should I correct? The googleapi.html and list.html are working fine separate.
Thanks!

A: There is a special option for using google maps in dhtmlx layout - attachMap
Online sample
and
  Documentation
will help you
By the way Google doesn't allow to use its servise in iframes
Plus if you don't use deprecated dhtmlx methods, you don't need to include this file in the page


text:
Q: Rails: which test method to use I want to write some tests for my current project.
These tests will be mostly related to saved data in the database.
For example:

*

*If a user registered 7 years ago, provide him gold badge (a boolean
field set to true)

*If registered 3 years ago then bronze badge etc.
Well, the calculations are bit more complicated before the boolean field is set to true. There are about 30-40 test cases that I need to test which are very similar to the above two examples.
I did some reading about Rails testing but I could not figure out the exact difference between integration, unit and functional testing in Rails.
In my case which testing method will be appropriate?

A: I think it depends how you would implement it.
If you're using a cronjob to check for users badges an integration test would be good, to test the whole job enqueuing and stuff.
If you're updating when the user logs in, you can use a model (unit) test.
For example:
class UserTest < ActiveSupport::TestCase
  test "users badge is updated on login if needed" do
    user = User.create ... , golden_badge: false
    travel_to Time.now + 7.years do
      # simulate login, something like: user.login(user: "", pass: "")
      assert user.golden_badge
    end
  end
end

this test would take place in test/models/user_test.rb

A: It depends where exactly the code that updates this field is executed. For example if you check these 'rewards' on the update of a user in user model itself as below:
class User < ActiveRecord::Base
  before_save :check_rewards

  def check_rewards
    self.update(golden_badge: true) if created_at > 5.years.ago
  end

Then the tests would only need to take place in the models/user_spec.rb which is a unit test.
If the code was ran as a cron job every hour, which used a method in a file called check_rewards.rb that would probably belong in two places.
Firstly the 'unit' test of the object that does the updating in services/check_rewards.rb (or commands/check_rewards.rb, or whatever directory) to test the actual functionality is working, like my user spec code above.
Finally you should have an integration test in integration/check_rewards_spec.rb to ensure that the job manager you are using is working as expected, so that the job itself is actually run and has the expected behavior.

A: Unit testing : For testing smallest unit of code. For a specific functionality. Like CRUD operation testing in a controller. Each action will test in unit testing separately.
Integration Testing : For testing a group of functionality or module. Consider if you want to see what a simple user can see and what logged in user can see in a website. So in both cases you need to test login functionality then a particular functionality after that.
Functional testing is completely different. In this you can test either module or combination of modules. It more like to integration testing.
Unit tests tell a developer that the code is doing things right; functional tests tell a developer that the code is doing the right things.
Read more here
In my view you should go for functional testing.


text:
Q: "tube" vs. "tubing" I have always run into word twins like tube vs. tubing.
More pairs: fence vs. fencing, pipe vs. piping, cable vs. cabling, rail vs. railing, etc.
This is an interesting phemonenon. Most of these nouns cannot function as verbs, but adding the ing-form generates a new word with a similar meaning.
Can you please explain the morphology behind this? Does the ing-form bring with it a different connotation? Any nuances between these twins?

A: From the Wiktionary article on "-ing":

Suffix -ing: Used to form uncountable nouns from various parts of speech denoting materials or systems of objects considered collectively.
Roofing is a material that covers a roof.
Piping is a system of pipes considered collectively.

See the suffix -ing has three actions, according to Wiktionary:

*

*Forming gerunds - from verbs, obviously

*Forming the nouns to designate something "collectively", as in your examples

*Forming nouns of the action or the procedure of a verb ("the forging of the sword took hours")

A: Here is another common way these words are used:

When they put the roof on the warehouse, they went with metal roofing.
When you're repairing an air conditioner or the built-in chilled-water
  dispenser of a fridge, you may need to cut off a section of copper
  tubing, to replace a leaky tube.
We needed to repair the fence where the cattle had broken through the
  split-rail fencing.
When you ice the cake, use chocolate icing.

NOTE: We would go to buy 100 foot of copper tubing or a 100-foot roll of cyclone fencing but not a 100 foot of copper *piping. We buy 100 foot of copper pipe. Piping refers to the installed system of pipes.


text:
Q: drawing rectangles in c# I need to draw a set of rectangles, something similar to a calendar which is made up by 28-31 rectangles, but based on their coordinates and width/height (from a database table). I need to be able to add/draw on each of those rectangles, such as adding a smaller square plus some text, on the top of the original rectangle.  My question is what should I use to accomplish that?

A: private void DoSomething()
{
    //these values are just example, should be from a source
    int x=15, y=20, width=100, height=80;
    string bgColor = "#fafafa";

    Panel pnOuter = new Panel();
    pnOuter.Attributes.Add("style", "position:absolute; text-align:center; left:" + x + "px; top:" + y + "px; width:" + width + "px; height:" + height + "px; background-color:" + bgColor + ";");
    Label lbHeader = new Label();
    lbHeader.Text = "Some Header";
    lbHeader.Attributes["class"] = "Header";
    pnOuter.Controls.Add(lbHeader);

    Panel pnInner = new Panel();
    pnInner.Attributes.Add("style", "margin-left:auto; margin-right:auto; width:50px; height:40px; text-align:center;");
    Label lbText = new Label();
    lbText.Text = "some text";
    lbText.Attributes["class"] = "SomeStyle";
    pnInner.Controls.Add(lbText);

    //add inner panel to outer panel
    pnOuter.Controls.Add(pnInner);
}


text:
Q: Flutter: Checking (e) for error type after catch I have the following code to log a user in using Firebase Auth. I'd like to display an error if the password is wrong, but not sure how to test e to see what error happened.
    try {
      final user = await _auth.signInWithEmailAndPassword(
          email: email, password: password);
      if (user != null) {
        Navigator.pushNamed(context, ChatScreen.id);
      }
      setState(() {
        showSpinner = false;
      });
    } catch (e) {
      if (e.errorCode = ???) {      <--- how to test e for the type of error ???
        print(e.error);
      }
    }

Thanks for any help,
Paul

A: Firebase docs can help you with finding all the error codes. When e.code matches with a particular firebase auth code, you can generate your relevant error message.
For instance, for a wrong password entered you could do this.
if (e.code.contains('ERROR_WRONG_PASSWORD')) {
    errorText = 'Wrong Password';
    print(errorText);

Some of the error codes are - ERROR_WEAK_PASSWORD, ERROR_INVALID_EMAIL, ERROR_EMAIL_ALREADY_IN_USE, ERROR_USER_NOT_FOUND, ERROR_WRONG_PASSWORD


text:
Q: How do I manage groups/rooms with node WebSockets? TL;DR below.
I am currently developing a React/Redux SPA that is driven by real-time data. I've decided to use ws, instead of socket.io since socket.io feels a bit high level for what I'm doing, I'd rather manage sockets myself.
In saying that, I'm struggling to find a way to manage the separation of updates/messages per view/route. Since I'm using client-side routing it's per express route won't really work...
Messages between the server and client via WebSockets are JSON with actions like GET_ITEMS then a response of GET_ITEMS_SUCCESS with an array of 'items' and for errors: ..._ERROR etc. This is all fine, since it's just 1 to 1 transaction. Though the problem arises when broadcasting (1 to all) to all relevant clients when the server receives an update.
So, I assume it best practice to limit these broadcasts to the clients that are viewing/want the data. So when viewing, for example, the Item page, there is no point in broadcasting updates to the User data since that is only used on the User page.
I haven't been able to find any common practices when dealing with this sort of situation, just a few small outdated/barely used wrappers for ws that just add a few basic functions to leave/join but don't offer much flexibility with implementation.
What I think MIGHT work is to have an object/array for each 'group'/'room', which stores the clients that are currently listening to updates from a given section. So a user would send an action to INIT_LISTEN (& ``) with a param of category, e.g. ITEM for updates and other actions related to items.

TL;DR
What my question really boils down to is: How do I store a reference to a single socket? (ws client object? ws client ID?) Then, can I store this in an object/array to iterate through like below.
 const ClientRooms = {
      Items: {
           {
                ...ws
           }
           /* ...rest of the client */
      }
 }

or
 const ClientRooms = {
      Items: [ "xyz" ] /* Array of ws ids */
 }

I have a "ping--pong" heartbeat function to keep clients active and prevent silent connection failures/disconnections. I can't find if ws.terminate() still fires the ws close event so I can iterate 'group'/'room' the object/array to find and remove instances of that client.


text:
Q: Can I configure sources location for Maven? I am using specific jar library, provided via Maven vendor-specific repository. There is only jar file in the repository, i.e. no sources and no javadocs.
But I know, that sources are available online, in SVN repository. Can I tell Maven to download sources of specific JAR from specific SVN location and may be from specific revision number?

A: No you can't tell maven to download sources from a SVN repository. Maven expects all kinds of artifacts within the appropriate Maven repository.

A: What you can do is to tell Maven in which Repository to look for the libraries including the resources.
If the sources are not available in a Maven repostory format, you can tell your IDE (e.g. Eclipse) to link them directly from a location on your hard disk.

A: Jars are not stored in SVN repositories, they're stored in artifact repositories when working with Maven. Keeping binary artifacts (such as jar files) under version control is considered bad practice.
If you would like to check if a certain artifact produces a sources or javadoc artifact which is available via Maven Central, then you can check in:

*

*http://search.maven.org/

*http://www.jarvana.com/

*http://findjar.com/
If you have your own Maven repository (such as Nexus, Artifactory), etc, you can use it as well.
If I understand you correctly, your problem is that the sources for these artifacts are not being displayed in your IDE. If this is the case and you are sure they produce source/javadoc artifacts, then you can set up your IDE to resolve these dependencies.
If you're using Eclipse, you will need something along the lines of:
<project ...>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

A: In the pom.xml file you have to set the dependencies, for example:
<dependency>
         <groupId> junit </ groupId>
         <artifactId> junit </ artifactId>
         <scope> test </ scope>
         <version> 4.10 </ version>
</ dependency>

I think you can not see it for revisions, look for the libraries including the resources and dependencies of pom.xml.


text:
Q: Are there infinite sets of axioms? I'm reading Behnke's Fundamentals of mathematics:

If the number of axioms is finite, we can reduce the concept of a consequence to that of a tautology.

I got curious on this: Are there infinite sets of axioms? The only thing I could think about is the possible existence of unknown axioms and perhaps some belief that this number of axioms is infinite.

A: Perhaps surprisingly even the classical (Łukasiewicz's) axiomatization of propositional logic has an infinite number of axioms. The axioms are all substitution instances of

*

*$(p \to (q \to p))$

*$((p \to (q \to r)) \to ((p \to q) \to (p \to r)))$

*$((\neg p \to \neg q) \to (q \to p))$

so we have an infinite number of axioms.
Usually the important thing is not if the set of axioms is finite or infinite, but if it is decidable. We can only verify proofs in theories with decidable sets of axioms. If a set of axioms is undecidable, we can't verify a proof, because we can't tell if a formula appearing in it is an axiom or not. (If a set of axioms is only semi-decidable, we're able to verify correct proofs, but we're not able to refute incorrect ones.)
For example, if I construct a theory with the set of axioms given as

$T(\pi)$ is an axiom if $\pi$ is a representation of a terminating program.

Then I can "prove" that some program $p$ is terminating in a one-line proof by simply stating $T(p)$. But of course such theory has no real use because nobody can verify such a proof.

A: An example of an infinite set of axioms used for practical use is the foundation of non-standard analysis.
Create a first-order language whose symbols include:

*

*Every element of $\mathbb{R}$

*Every element of $\mathcal{P}(\mathbb{R})$

*Every element of $\mathcal{P}(\mathcal{P}(\mathbb{R}))$

*:

Now select a set of axioms to be the set of all true statements in this language.
This language and set of axioms is enough to do lots of things; e.g. any theorem you've learned in calculus can be stated in this language and is automatically a theorem.
By general properties of first-order logic, this set of axioms is consistent and thus there exists a non-standard model! By construction, every theorem you know about 'standard' things is automatically true for non-standard things as well! In this formulation, the transfer principle from non-standard analysis -- every 'standard' object has a nonstandard analog, and every statement of 'standard' analysis is true if and only if its translation to the non-standard model is true -- becomes an utter triviality.
While one can surely attempt to select a smaller set of axioms, there is no actual reason to; for the specific application we have to apply logic in this instance, it is by far easier and more convenient to take all of them.

A: In first order Peano axioms the principal of mathematical induction is not one axiom, but a "template" called an axiom scheme. For every possible expression (or "predicate") with a free variable, $P(n)$, we have the axiom:
$$(P(0) \land \left(\forall n: P(n)\implies P(n+1)\right))\implies \\\forall n: P(n)$$
So, if $P(x)$ is the predicate, $x\cdot 0 = 1$ then we'd have the messy axiom:
$$(0\cdot 0=1 \land \left(\forall n: n\cdot 0 =1\implies (n+1)\cdot 0=1\right))\implies \\\forall n: n\cdot 0 = 1$$
Our inclination is to think of this axiom scheme as a single axiom when preceded by "$\forall P$", but in first-order theory, there is only one "type." In first-order number theory, that type is "natural number." So there is no room in the language for the concept of $\forall P$. In second order theory, we can say $\forall P$.
In set theory, you have a similar rule, the "axiom of specification" which lets you construct a set from any predicate, $P(x,y)$, with two free variables:
$$\forall S:\exists T: \forall x: (x\in T\iff (x\in S\land P(x,S)))$$
(The axiom lets you do more, but this is a simple case.)
which essentially means that there exists a set:
$$\{x\in S: P(x,S)\}$$
Again, there is no such object inside set theory as a "predicate."
For most human axiom systems, even when the axioms are infinite, we have a level of verifiability. We usually desire an ability to verify a proof using mechanistic means, and therefore, given any step in a proof, we desire the ability to verify the step in a finite amount of time.

A: As others have noted, first order PA has an infinite number of axioms. But it is worth stressing that this is not just a superficial feature of the usual mode of presenting the induction axioms via a schema or template. It is provable that there is no finitely axiomatized theory in the language of PA whose theorems coincide with those of PA.

A: Just to make the matter maybe a bit more clear giving another example:
Similar to what André Nicolas stated, $ACF_0$ (the theory of algebraically closed fields of charateristic $0$) is axiomatized by $ACF$(the theory of algebraically closed fields) + $\{\neg\phi_p$ : $p$  is  prime$\}$, where $\phi_p$ says "I have characteristic $p$." $ACF$ is already not finitely axiomatizable itself but I am sure observing that $\{\neg\phi_p$ : $p$  is  prime$\}$ is an infinite set of axioms is way more obvious.

A: Many important theories, most significantly first-order Peano arithmetic, and ZFC, the most commonly used axiomatic set theory, have an infinite number of axioms. So does the theory of algebraically closed fields.

A: Are there infinite sets of axioms?  Yes!
As a trivial (and somewhat meaningless) example, consider the first-order language whose only non-logical symbols are the constant symbol $0$ and the unary function symbol $S$.  Then the following would comprise an infinite set of axioms:

*

*$0 \neq S(0)$;

*$S(0) \neq S(S(0))$;

*$S(S(0)) \neq S(S(S(0)))$;
$\vdots$

*$S ( S ( S ( \cdots ( 0 ) \cdots ) ) ) \neq  S ( S ( \cdots ( 0 ) \cdots ) )$
$\vdots$

For a more meaningful example we have, as others have pointed out, Peano Arithmetic.  More than just being an infinite list of axioms, this theory necessarily has an infinite set of axioms.  By a result of C. Ryll-Nardzewski, (assuming it is consistent) Peano Arithmetic is not finitely axiomatisable: there is no finite set of axioms (in the same language) that has the same collection of formal theorems.  (A similar result holds for ZF(C).)


text:
Q: Issue using aiozmq.rpc with pyqt5 I am trying to do RPC using a Client Server model in PyQt5.
I've modified the client sample code for pyqt5, here is the original code (https://gist.github.com/martinku-tw/a35493bb40d3a91632a276492402a3ab) but I am running into an issue trying to use aiozmq.rpc with pyqt5.
When I try to get the return value from the rpc, I get an error 'TypeError: must be str, not coroutine'.
I am very new to rpc/socket programming and I am not sure if this the right way to do it in PyQt5.
Any help would greatly be appreciated,
I step through the code and looked at the ret object I do not see the return value. From what I could see, I don't think it's hitting the server code.

from PyQt5.QtWidgets import *
import asyncio
from aiozmq import rpc

app = QApplication([])
button = QPushButton('Click to myfunc1 results')

@asyncio.coroutine
async def run_client():
    print('start rpc client...')
    client = await rpc.connect_rpc(connect='tcp://127.0.0.1:5503')
    ret = await client.call.myfunc1(1, 13)

    return ret

def on_button_clicked():

    #ret = run_client().cr_code.co_consts[5]
    ret = run_client()

    alert = QMessageBox()
    alert.setText('myfunc1 results is: ' + str(ret))
    alert.exec_()

button.clicked.connect(on_button_clicked)
button.show()
app.exec_()

I am expecting a return string object from the server but getting this error.
Traceback (most recent call last):
  File "aiozmq_client_qt_1.py", line 22, in on_button_clicked
    alert.setText('myfunc1 results is: ' + ret)
TypeError: must be str, not coroutine
[1]    6689 abort      python aiozmq_client_qt_1.py


text:
Q: Dynamic controls missing in asp.net application on postback event of dynamic control Hi I'm adding dynamic Controls on button click event,In that I hav dropdown control, I'm raising an event to drop down for selected index change, I made auto post back true, When I'm selecting new item from drop down I'm Losing all the dynamic controls

A: Every server control that inherits IPostBackDataHandler interface has a LoadPostData method that processes the postback data. When control is implemented by a class (page, form, placeholders, controls etc), that class calls the LoadPostData method and passes the posted data and key to maintain control states.
All you need to do is to re-instantiate / reinitialize dynamic controls before or within page load event each and every time during postback and add this control to page / forms / placeholders. Then the posted data will automatically be assigned to the control by calling the LoadPostData method by the parent control and control event will fire.
check the article and how to write code for dynamic control -
How to maintain dynamic control events, data during postback in asp.net

A: You have to recreate all dynamically created controls on every postback(in load event at the latest).
You also have to ensure that they get the same ID as before to trigger events and maintain ViewState.
If you know the number of controls to create(which could be stored in ViewState) you can derive the ID from the counter variable by appending it to the control-id. Then you can recreate them with the correct ID  in page's init event.
Recommandable readings:

*

*TRULY Understanding Dynamic Controls

*Page-Lifecycle
Or you use one of the builtin Data-Bound Control like Repeater that do this automatically. You only have to set their DataSource and call DataBind().
Here are answers of me on similar questions with implementations:

*

*C#

*VB.NET (+ C#)


text:
Q: Attribute returns Null Pointer Exception NULL POINTER EXCEPTION HAPPENDS HEREI have 2 recyclerviews and 2 adapters. One is for the shop names, and one for the deliverables per shop. I need to display the deliverables per shop. When I populate my layout component, deliverable imageview returns null.
Here is my code for populating the recyclerview of the deliverables.
public class DeliverableView extends ConstraintLayout {

    @BindView(R.id.iv_deliverable_image)
    ImageView iv_deliverable_image;
    @BindView(R.id.tv_deliverable_name)
    TextView tv_deliverable_name;
    @BindView(R.id.tv_deliverable_size)
    TextView tv_deliverable_size;
    @BindView(R.id.tv_deliverable_quantity)
    TextView tv_deliverable_quantity;
    @BindView(R.id.tv_deliverable_amount)
    TextView tv_deliverable_amount;

    public DeliverableView(Context context) {
        super(context);
    }

    public DeliverableView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DeliverableView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void populate(Entity deliverable) {
        Glide.with(getContext()).load(StringUtil.trimUrlByHeight(deliverable.attributes.image_url, 60)).into(iv_deliverable_image);
        tv_deliverable_quantity.setText(String.valueOf(deliverable.attributes.count));
        tv_deliverable_name.setText(deliverable.attributes.name);
        tv_deliverable_size.setText(deliverable.attributes.size);
        tv_deliverable_amount.setText(StringUtil.getDisplayedBill(deliverable.attributes.amount_in_cents * deliverable.attributes.count));
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        View.inflate(getContext(), R.layout.layout_componet_deliverable, this);
        ButterKnife.bind(this);
    }
}

Below is the code for the adapter of shops. This is where I setup the deliverableadapter and updating it.

public class ViewReceiptShopNameAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    private List<Entity> jobOrders = new ArrayList<>();
    private DeliverableAdapter deliverableAdapter;
    private List<OrderItem> orderItems = new ArrayList<>();v

    public ViewReceiptShopNameAdapter(Context context) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
    }

    public void updateViewShopAdapter(List<Entity> jobOrders) {
        this.jobOrders = jobOrders;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        return new ViewHolderShopName(inflater.inflate(R.layout.layout_view_receipt_shopname, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        final Entity jobOrder = jobOrders.get(position);
//        final OrderItem orderItemList = orderItems.get(position);
        ViewHolderShopName viewHolder = (ViewHolderShopName) holder;
        viewHolder.bindModel(jobOrder);
    }

    @Override
    public int getItemCount() {
        return jobOrders.size();
    }

    class ViewHolderShopName extends RecyclerView.ViewHolder {

        @BindView(R.id.store_name)
        TextView tv_shop_name;
        @BindView(R.id.count_items_delivered)
        TextView tv_items_count;
        @BindView(R.id.rv_receipt_items)
        RecyclerView rv_receipt_items;

        ViewHolderShopName(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        void bindModel(Entity jobOrder) {
//            tv_shop_name.setText(orderItem.shop.attributes.name);
            tv_items_count.setText(String.format("%d items delivered", jobOrder.attributes.deliverables_purchased_count));

            //deliverable adapter
            LinearLayoutManager layoutManager = new LinearLayoutManager(context);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            rv_receipt_items.setLayoutManager(layoutManager);
            deliverableAdapter = new DeliverableAdapter(context);
            rv_receipt_items.setAdapter(deliverableAdapter);

            deliverableAdapter.updateDeliverableAdapter(Arrays.asList(jobOrder.relationships.deliverables.data));

        }
    }
}

This is the DeliverableAdapter.class where I am calling the updateDeliverableAdapter() method.
public class DeliverableAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    private List<Entity> deliverables = new ArrayList<>();

    public DeliverableAdapter(Context context) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
    }

    public void updateDeliverableAdapter(List<Entity> deliverables) {
        this.deliverables = deliverables;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) {
        return new ViewHolderDeliverable(inflater.inflate(R.layout.layout_item_deliverable, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        final Entity deliverable = deliverables.get(position);
        ViewHolderDeliverable viewHolder = (ViewHolderDeliverable) holder;
        viewHolder.bindModel(deliverable);
    }

    @Override
    public int getItemCount() {
        return deliverables.size();
    }

    class ViewHolderDeliverable extends RecyclerView.ViewHolder {

        @BindView(R.id.deliverableView)
        DeliverableView deliverableView;

        ViewHolderDeliverable(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        void bindModel(Entity deliverable) {
            deliverableView.populate(deliverable);
        }
    }
}

This is my Entity.class . I checked AttributesBase includes the need data.
public class Entity implements BaseModel{

    public String id;
    public String type;
    public AttributesBase attributes;
    public RelationshipsBase relationships;

    public boolean isCancelled(){
        return attributes.status.equalsIgnoreCase("cancelled");
    }

    @Override
    public String toString() {
        return new Gson().toJson(this);
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }
}

These are the ATTRIBUTES I am accessing on the AttributesBase.class.

@SerializedName("image-url")
      public String image_url;  @SerializedName("name")
      public String name;  public String size;  public int count;

A: You are trying to bind values which are not present in your class Entity.
As per screen shot attached Entity deliverable contains only two members i.e id and type. and you are trying to access value of image_url which is not present in deliverable object. You will get this error for all the lines where you are trying to set values which are not present in deliverable.
deliverable object does not contains attributes like image_url, count, name, size.
All this places you will get NullPointException.


text:
Q: Stop ypbind from automatically running I want my linux client to stop using nis services. Can someone suggest how to do it.
Yes, I've already searched on the web, and also on serverfault.
As I've mentioned a couple of times on su/so/sf, the search facility is almost half as bad the sites themselves are good.
EDIT:
My Distro is Ubuntu 10.04
EDIT2:
How do I turn it back again.?
Thanks.

A: You aren't getting any answers because you aren't providing enough information.  Instead of complaining about the search feature here, perhaps you could have told us what distro.
If it's a RH based distro, use chkconfig
chkconfig --del ypbind

If it's a Debian based distro use update-rc.d
update-rc.d -f ypbind remove

A: If you just stop the service then you will probably have lots of halts as it tries to use NIS I believe.  If you want to remove NIS from being use I believe what you need to do is edit your /etc/nsswitch.conf file and remove the nis text from it.  Then you also stop the service from starting as Nathan said.


text:
Q: Accessing elements of a class with strings I was working on a problem earlier where I wanted to loop over the elements of a class but I didn't want to use
for attr, value in o.__dict__.iteritems()

since that would only return the elements of that object. I have two objectsA and B and I want to use the attr variable so I can compare A and B but I couldn't find any way to do that. I know there is eval() but that wouldn't work. Here's an example of what I am trying to accomplish
class foo():
    def __init__(self,i=None, j=None):
        self.i = i
        self.j = j

A = foo(5)
B = foo(None, 2)

#If I have the string "i" I want to be able to access attribute i
list_of_attr = [k for k in dir(B) if not k.startswith('__')]

#list_of_attr = ['i','j']
for k in list_of_attr:
   print A.k

#expected output
5
None

instead it throws the error AttributeError: foo instance has no attribute 'k'
I was thinking A.eval(k) might work but it tries evaluate eval() as an attribute
Is there a way to do that or does Python not allow it?

A: A.k means trying to access property named k of A.
Use getattr(A, k).

Using eval:
eval('A.%s' % k)
PS: Please try to refrain from using eval in your code.


text:
Q: Set state to result of database query So I have a function like this to get everything from a database:
  retrieve() {
    db.transaction(
      tx => {
       tx.executeSql('select * from my_table', [], (trans, result) => {
        });
      }
    );
  }

Now I want to set the state of my component to result, but I'm not sure how to achieve this. I've tried adding the following at various points in the retrieve() function but I am unable to achieve any success.
this.setState({
  cardholders: result
});

A: Could you try this?
  retrieve() {
    db.transaction(
      tx => {
       tx.executeSql('select * from my_table', [],  (trans, result) => {
        this.setState({
          cardholders: result
        });
        });
      }
    );
  }

A: I figured it out this way:
db.transaction(
  tx => {
   tx.executeSql('select * from MyScannedCards', [], (trans, result) => {
    var len = result.rows.length;
    for (i=0;i<len;i++){
      cardDetails = result.rows._array[i];
      this.setState({ cardholders: this.state.cardholders.concat(cardDetails) })
    }
    });
  }
);


text:
Q: Glide listener not working if using .asBitmap() On a android project i have this piece of code to get a image in a ImageView
xml
<package.RoundedImageView
                    android:id="@+id/options_photo_icon"
                    android:layout_width="@dimen/registration_icons_height"
                    android:layout_height="@dimen/registration_icons_height"
                    android:maxWidth="@dimen/registration_icons_height"
                    android:maxHeight="@dimen/registration_icons_height"
                    android:src="@drawable/no_image"
                    android:foregroundGravity="center"
                    android:layout_centerHorizontal="true"
                    android:layout_weight="1" />

java
Glide
                    .with(context)
                    .load(url)
                    .asBitmap()
                    .centerCrop()
                    .listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            //do something
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            //do somethig else.
                            return false;
                        }
                    })
                    .into(options_photo_icon);

but i get this error:

Error:(212, 21) error: no suitable method found for
  listener(>) method
  GenericRequestBuilder.listener(RequestListener)
  is not applicable (argument mismatch; > cannot be converted to
  RequestListener) method
  BitmapRequestBuilder.listener(RequestListener)
  is not applicable (argument mismatch; > cannot be converted to
  RequestListener)

if i remove as .asBitmap() i dont get the error, but i need the .asBitmap() for something else.
can't i use the listener if i a asBitmap ?

A: Try this
SimpleTarget target = new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
          imageView.setImageBitmap(resource);
        }
    };
Glide.with(getApplicationContext()).load(profileUrl)
.asBitmap().diskCacheStrategy(DiskCacheStrategy.SOURCE)
.placeholder(R.drawable.profile_placeholder)
.error(R.drawable.profile_placeholder).into(target);

A: // Put asBitmap() right after Glide.with(context)   ,,. 4.0+
// And for SubsamplingScaleImageView use SimpleTarget

  Glide.with(context)
                .asBitmap()
                .load(images[position])
                .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
                .into(new SimpleTarget<Bitmap>(width, height) {
                    @Override
                    public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
                        subsampleImageView.setImage(ImageSource.bitmap(bitmap)); //For SubsampleImage
                    }
                });


text:
Q: Object to shoot a projectile I'm trying to make my tanks shoot, and I did all the code I think I should have done but I don't know why the tanks aren't shooting anything.
import pygame, assetloader
from pygame.locals import *
import random, time, math
import pygame

GRAD = math.pi/180
blue = (0, 0, 255)

wallRects = []

bullets = []

maze = [[] for i in range(25)]

assetloader.set_asset_path("assets/")

I defined the Bullet Class here:
def calculate_dir_with_angle(angle):
        direction = [0, 0]
        if (angle > 0 and angle < 180) or (angle > -360 and angle < -180):
            direction[0] = -1
        elif (angle > -180 and angle < 0) or (angle > 180 and angle < 360):
            direction[0] = 1
        elif (angle > -90 and angle < 90) or (angle > 270 and anlge < 360):
            direction[1] = -1
        elif (angle > 90 and angle < 270) or (angle > -270 and angle < -90):
            direction[1] = 1
        return direction

class Bullet:
    def __init__(self, pos, r, angle):
        self.x = pos[0]
        self.y = pos[1]
        self.r = r
        self.counter = 50
        direction = calculate_dir_with_angle(angle)
        self.vel = [direction[0] * 2, direction[1] * 2]

    def draw(self, screen):
        self.x = int(self.x)
        self.y = int(self.y)
        pygame.draw.circle(screen, (25, 25, 25), (self.x, self.y), (self.r))

    def move(self):
        self.x += self.vel[0]
        self.y += self.vel[1]

        self.rect = pygame.Rect(self.x-self.r, self.y - self.r, 2 * self.r, 2 * self.r)
        for wr in wallRects:
            if self.rect.centery >= wr.top and self.rect.centery <= wr.bottom:
                if self.rect.left <= wr.right and self.rect.left > wr.left:
                    self.vel[0] = -self.vel[0]
                    self.x = wr.right + self.r + 1
                    self.rect.x = wr.right + 1
                elif self.rect.right >= wr.left and self.rect.right < wr.right:
                    self.vel[0] = -self.vel[0]
                    self.x = wr.left + self.r - 1
                    self.rect.x = wr.left - 2 * self.r - 1
            if self.rect.centerx >= wr.left and self.rect.centerx <= wr.right:
                if self.rect.top <= wr.bottom and self.rect.top > wr.top:
                    self.vel[1] = -self.vel[1]
                    self.y = wr.bottom + self.r + 1
                    self.rect.y = wr.bottom + 1
                elif self.rect.bottom >= wr.top and self.rect.bottom < wr.bottom:
                    self.vel[1] = -self.vel[1]
                    self.y = wr.top - self.r - 1
                    self.rect.y = wr.top - 2 * self.r - 1

        if self.counter > 0:
            self.counter -= 1

    def generateRandomPosition():
        row = random.randint(1, 23)
        col = random.randint(1, 23)
        while maze[row][col-1] != 0 or maze[row][col] != 0 or maze[row][col+1] != 0:
            row = random.randint(1, 23)
            col = random.randint(1, 23)

        return row, col

Player 1:
class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, pos):
        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = assetloader.load_image("Tank.png", -1)
        self.rect.x = x
        self.rect.y = y
        self.rect.clamp_ip(screen.get_rect())

        self.rows = pos[0]
        self.cols = pos[1]
        self.x = self.cols * gsize
        self.y = self.rows * gsize
        self.orig_image, self.orig_rect = assetloader.load_image("Tank.png", -1)
        self.orig_rect.x = self.x
        self.orig_rect.y = self.y
        self.orig_gun_pos = self.orig_rect.midtop
        self.ammo = 5

    def checkCollisions(self):

            for b in bullets:
                if b.counter <= 0:
                    if b.rect.colliderect(self.orig_rect):
                        self.dead = True

    def calculate_gun_pos(self):
        self.orig_gun_pos = self.orig_rect.midtop
        new_y = self.orig_gun_pos[1] - self.orig_rect.centery
        new_x = self.orig_gun_pos[0] - self.orig_rect.centerx
        rads = self.dir * GRAD
        gun_x = (new_y * math.sin(rads)) + (new_x * math.cos(rads)) + (self.orig_rect.centerx)
        gun_y = (new_y * math.cos(rads)) - (new_x * math.sin(rads)) + (self.orig_rect.centery)
        self.gun_pos = (gun_x, gun_y)

    def shoot(self):
        if self.ammo > 0:
            self.calculate_gun_pos()
            b = Bullet(self.gun_pos, 3, self.dir)
            bullets.append(b)
            self.ammo -= 1

    def draw(self, screen):
        image = pygame.transform.rotate(self.image, self.dir)
        screen.blit(image, self.rect)

    def update(self):
        oldCenter = self.rect.center

        self.rect = self.image.get_rect()
        self.rect.center = oldCenter
        screen_rect = screen.get_rect()
        keys = pygame.key.get_pressed()

        if keys[K_m]:
            p.shoot()

        if not screen_rect.contains(self.rect):
            self.rect.clamp_ip(screen_rect)

Calling the functions:
size = width, height = 500, 400
gsize = 25
start_x, start_y = 0, 0
bgColor = 255, 255, 255

pygame.init()
screen = pygame.display.set_mode(size)#, pygame.FULLSCREEN)
pygame.display.set_caption("Sample Sprite")
clock = pygame.time.Clock()

p = Player(width/2, height/4, (3,4))

coll_font = pygame.font.Font(None, 30)

going = True
while going:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            going = False
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                going = False

        elif event.type == KEYDOWN:
            if event.key == K_m:
                p.shoot()

        for b in bullets:
               b.move()

    p.update()

    screen.fill(bgColor)

    p.draw(screen)

    pygame.display.flip()

pygame.quit()

How would I call the bullet to actually appear and fire because I have the Bullet class which gets called within the Player class in def shoot(self)  so does anyone have an idea why the bullets aren't appearing?

A: I usually add bullets in this way: I pass the group that contains all sprites  and the bullet group to the player instance and add new bullets to these group in the player's handle_event method.
import pygame as pg
from pygame.math import Vector2

pg.init()
screen = pg.display.set_mode((640, 480))
screen_rect = screen.get_rect()
FONT = pg.font.Font(None, 24)
BG_COLOR = pg.Color('gray12')

BULLET_IMAGE = pg.Surface((20, 11), pg.SRCALPHA)
pg.draw.polygon(
    BULLET_IMAGE, pg.Color('aquamarine1'), [(0, 0), (20, 5), (0, 11)])
PLAYER_IMAGE = pg.Surface((50, 30), pg.SRCALPHA)
pg.draw.polygon(
    PLAYER_IMAGE, pg.Color('dodgerblue1'), [(0, 0), (50, 15), (0, 30)])

class Player(pg.sprite.Sprite):

    def __init__(self, pos, all_sprites, bullet_group):
        super().__init__()
        self.image = PLAYER_IMAGE
        self.orig_image = self.image  # Needed to preserve image quality.
        self.rect = self.image.get_rect(center=(pos))
        self.pos = Vector2(pos)
        self.vel = Vector2(1, 0)
        self.angle = 0
        self.angle_speed = 0
        self.all_sprites = all_sprites
        self.bullet_group = bullet_group

    def handle_event(self, event):
        if event.type == pg.MOUSEBUTTONDOWN:
            # Left button fires a bullet from cannon center with
            # current angle. Add the bullet to the bullet_group.
            if event.button == 1:
                bullet = Bullet(self.pos, self.angle)
                self.bullet_group.add(bullet)
                self.all_sprites.add(bullet)
        elif event.type == pg.KEYDOWN:
            # Rotate self by setting the .angle_speed.
            if event.key in (pg.K_a, pg.K_LEFT):
                self.angle_speed = -3
            elif event.key in (pg.K_d, pg.K_RIGHT):
                self.angle_speed = 3
        elif event.type == pg.KEYUP:
            if event.key in (pg.K_a, pg.K_LEFT):
                self.angle_speed = 0
            elif event.key in (pg.K_d, pg.K_RIGHT):
                self.angle_speed = 0

    def update(self):
        self.pos += self.vel
        self.rect.center = self.pos

        if self.angle_speed != 0:
            self.rotate()

    def rotate(self):
        # Update the angle and the velocity vector.
        self.angle += self.angle_speed
        self.vel.rotate_ip(self.angle_speed)
        # Rotate the image and get a new rect with the previous center.
        self.image = pg.transform.rotozoom(self.orig_image, -self.angle, 1)
        self.rect = self.image.get_rect(center=self.rect.center)

class Bullet(pg.sprite.Sprite):

    def __init__(self, pos, angle):
        super().__init__()
        self.image = pg.transform.rotate(BULLET_IMAGE, -angle)
        self.rect = self.image.get_rect(center=pos)
        # To apply an offset (40 pixels) to the start position,
        # create another vector and rotate it as well.
        offset = Vector2(40, 0).rotate(angle)
        # Add the offset vector to the position vector (the center).
        self.pos = Vector2(pos) + offset
        # Rotate the start velocity vector (9, 0) by the angle.
        self.vel = Vector2(9, 0).rotate(angle)

    def update(self):
        # Add the velocity to the pos to move the sprite.
        self.pos += self.vel
        self.rect.center = self.pos  # Update the rect as well.
        # Remove bullets outside of the screen area.
        if not screen_rect.contains(self.rect):
            self.kill()

def main():
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    # Bullets will be added to this group.
    bullet_group = pg.sprite.Group()
    # Pass the bullet group to the player.
    player = Player((300, 200), all_sprites, bullet_group)
    all_sprites.add(player)

    playing = True
    while playing:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                playing = False
            # Pass events to the player instance.
            player.handle_event(event)

        all_sprites.update()

        screen.fill(BG_COLOR)
        all_sprites.draw(screen)
        pg.display.update()

        clock.tick(30)

if __name__ == '__main__':
    main()
    pg.quit()


text:
Q: Get the Maximum Value for each Summed amount in each Stage I've searched over this and other sites, but couldn't find the exact example to what I'm looking for.
Basically, I have a Games table (sports, to be precise) and need to sum amounts by user and stage, then get the maximum for each stage.
This is my table:
Game_Score_User(GameId, UsrRegId, Stage, Score)
-- Primary key is (GameId, UsrRegId, Stage)

Now, I have different GameId's, but I'm filtering by only one.
Then, for this Game (basketball on this example) you can have several matches on a certain Stage. Let's say a stage is played along two days (so date doesn't matter) and you have 6 matches played within it. Your Users will have entered their predictions before those matches were played. Then, depending on their successed or failed predictions, they will earn some score.(this is done by a program, but I want to explain what's the purpose of this table)
Ok, now we have for each User, some score within a certain Stage. So if we have User 200 and user 240, they MAY have score for those stages (depending if they predicted for any game within that stage or not, otherwise, they get score = 0 for that match or stage respectively).
My understanding is, as you cannot do a MAX(SUM()), you need to solve the SUM within a query, then assign an alias to it, so you can work with it as if it was an actual table, then from that "table" ask for the MAX() value for the field you want, grouping by the correct fields.
I'm guessing I'm grouping by unnecessary values in the sub-query but... if I don't include those attributes in the sub-query for my "table" with alias, then I can't refer to those attributes from the "external" or "main" query. Am I wright? I say this because I get an error telling me that/those attribute/s doesn't/don't exist in that case.
I'm using SQL Server 2008
Bottom line is I need to get GameId, UsrRegId, Stage, and accumulated score in a result from a query which should tell me who won each Stage.
What I have tried so far is the following query, but it only gives me the added score but not the maximum for each stage. I.e., it only tells me the total for each Stage AND user, instead of telling me "this stage was won by this user":
  SELECT JPU.GameId, JPU.UsrRegId, JPU.Stage, MAX(JPU.Score_User) as Winner_Score
  FROM (SELECT GameId, UsrRegId, Stage, SUM(Points) as Score_User
        FROM Game_Score_User
        WHERE GameId = 280 AND
              Stage IN (SELECT Stage
                        FROM Game_Stages
                        WHERE GameId = 280)
        GROUP BY GameId, UsrRegId, Stage) JPU
  GROUP BY JPU.GameId, JPU.UsrRegId, JPU.Stage

A: Okay, so let's back it up a little bit and start with your subquery.
SELECT GameId, UsrRegId, Stage, SUM(Points) as Score_User
        FROM Game_Score_User
        WHERE GameId = 280 AND
              Stage IN (SELECT Stage
                        FROM Game_Stages
                        WHERE GameId = 280)
        GROUP BY GameId, UsrRegId, Stage

The stage in (...) doesn't actually filter anything out of the subquery. It's essentially saying that the gameid must be 280 and the stage must be from a game that has gameid 280. If the stage didn't correlate to the gameId, then it shouldn't be in the Game_Score_User table. In other words, we shouldn't let Johnny place a bet that Steve will beat Chris if Steve and Chris aren't playing any games together.
SELECT GameId, UsrRegId, Stage, SUM(Points) as Score_User
FROM Game_Score_User
WHERE GameId = 280
GROUP BY GameId, UsrRegId, Stage

This portion of your subquery will return the list of total userscores and the game and stage they are associated to. Let's say this query returns the following data:

GameID | UsrRegID | Stage | Score_User
280    | 1        | 1     | 20
280    | 1        | 3     | 4
280    | 2        | 1     | 15
280    | 2        | 2     | 15
280    | 2        | 3     | 15
280    | 3        | 2     | 25
280    | 4        | 1     | 17
280    | 4        | 3     | 12

Now we need to filter this table down to the rows that have the greatest score_user for each stage. The problem with how you are approaching this is that if you want to pull back the GameID, UsrRegId, Stage, and Score_User, you can't just tell sql to grab the max(score_user) and group by all of those columns. It will pull back the same results that I have listed above. A group by will no longer help solve the problem because all of the data is already grouped correctly.
Unfortunately, the only way to really do this is with a self join and we are going to have to aggregate the sum again to make sure the row we are looking at is the max. There are several ways to do this, I personally prefer a not exists.
SELECT JPU.GameId, JPU.UsrRegId, JPU.Stage, JPU.Score_User as Winner_Score
FROM (SELECT GameId, UsrRegId, Stage, SUM(Points) as Score_User
        FROM Game_Score_User gsu
        WHERE GameId = 280
        GROUP BY GameId, UsrRegId, Stage) gsu
Where not exists (Select *
                    From Game_Score_User gsu2
                    WHERE GameId = 280
                    and gsu2.Stage = gsu.Stage
                    GROUP BY GameId, UsrRegId, Stage
                    Having sum(gsu2.points) > gsu.Score_User)

The not exists makes sure that there isn't any score that is greater than the current row. The having is a way to compare aggregate functions and in this case I am using it to check the other sums of the scores for the gameid and stage. not exists only returns true if the results table is empty. This query should result in:

GameID | UsrRegID | Stage | Score_User
280    | 1        | 1     | 20
280    | 2        | 3     | 15
280    | 3        | 2     | 25


text:
Q: Rabl and array of array I couldn't find a solution so I decided to ask here.
I'm having this array (the construction can be changed if needed):
[[{:time=>2014, :amount=>148.24018480434023}, {:time=>2015, :amount=>152.5625744766238}], [{:time=>2014, :amount=>151.06717076828187}, {:time=>2015, :amount=>158.43869963240266}]]

In Rabl template I have:
collection @array, object_root: false

node :collection do |s|
  s
end

And the response is:
[{"collection": [{"time": 2014,"amount": 148.24018480434023},{"time": 2015,"amount": 152.5625744766238}]},{"collection": [{"time": 2014,"amount": 151.06717076828187},{"time": 2015,"amount": 158.43869963240266}]}]

However I would like to get rid off the "collection" nodes and get exactly this response:
[ [{ time: 2014, amount: 138.92 }, { time: 2015, amount: 142.98 }], [{ time: 2014, amount: 141.57 }, { time: 2015, amount: 148.48 }] ]

A: If you want to get rid of the root try
#  config/initializers/rabl_init.rb
Rabl.configure do |config|
  config.include_json_root = false
  config.include_child_root = false
end

https://github.com/nesquena/rabl/issues/4
Similar: Removing child root nodes in RABL

A: I know this is an old question but for posterity sake. The simplest approach is to remove the :collection on the node call. So for your example it would be as below
collection @array, object_root: false

node do |s|
  s
end


text:
Q: get line feeds in php mailto link <form action="../">
<select name="myDestination"
onchange="this.form.WINDOW_NAMER.value++;
ob=this.form.myDestination;
window.open(ob.options[ob.selectedIndex].value
,'Window_Name'+this.form.WINDOW_NAMER.value,
    'toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,width=900,height=500')">

<option value="mailto:bob@bob.com?subject=test&body=Please write soon. Thank  you.">Email </option>
<input name="WINDOW_NAMER" type="HIDDEN" value="1">
</form>
</select>

this code opens a ms outlook new message window. works great, but!
in the body part i want to say
"Please write soon.
Thank you."
notice in my code it always ends up as, "Please write soon. Thank you." on the same line.
i have tried many things to get line breaks, but to no avail.
eg
Please write soon.  Thank you.
Please write soon. \n\n Thank you.
but no go

A: Add %0D%0A which is hex for new line:
<option value="mailto:bob@bob.com?subject=test&body=Please write soon.%0D%0AThank  you.">Email </option>

That will do the trick.
http://jsfiddle.net/hescano/ayCP7/
To add Carbon Copy and Blind Carbon copy use the following:
<option value="mailto:bob@bob.com?subject=test&body=Please write soon.%0D%0AThank  you&bcc=email@email.com&cc=email@email.com">Email </option>


text:
Q: Parse bmrk NSAppleEventDescriptor from final cut pro x In Final cut pro, I shared to my application.
With following code
[[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
            andSelector:@selector(handleAppleEvent:withReplyEvent:) forEventClass:kCoreEventClass andEventID:kAEOpenDocuments];

- (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
    NSLog(@"handleAppleEvent %@", event);
}

I got something like this.
'aevt''odoc'{ '----':[ 'bmrk'(1012/$626F6F6BF403000000000410300000000000000000000000000000000000000000000000000000000000000000000000C00200000400000003030000000200000500000001010000557365727300000009000000010100006D75796F756E676B6F0000000900000001010000446F63756D656E747300000007000000010100006161612E6D7866001000000001060000100000002000000034000000480000000800000004030000BC300600000000000800000...
I expected readable information likes /Users/hansome/Document/a.mov
How can I parse this?

A: I found code without fully understanding.
    NSLog(@"handleAppleEvent 1 %@", event);

    NSAppleEventDescriptor* prop = [event paramDescriptorForKeyword:keyAEPropData];
    NSLog(@"handleAppleEvent prop %@", prop);

    NSAppleEventDescriptor* obj = [event paramDescriptorForKeyword:keyDirectObject];
    NSLog(@"handleAppleEvent obj %@", obj);

    if(obj != nil){
        for(int j=0;j<10;j++){
            NSAppleEventDescriptor* obj2 = [obj descriptorAtIndex:j];
            if(obj2 != nil){
                BOOL isStale;
                NSError* error;
                NSURL* url = [NSURL URLByResolvingBookmarkData:[obj2 data] options:NSURLBookmarkResolutionWithoutUI relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
                NSLog(@"handleAppleEvent bmrk %@", url);
            }
        }
    }


text:
Q: How to upload images in jaggeryjs? This is my sample HTML code
<html>
        <head>
            <title>
                fileupload
            </title>
        </head>
        <body>
            <form action="process.jag" method="post" id="" name="">
                  <!-- File input filed -->
                  <input type="file" name="myFile">

                  <!-- The submit button. It calls the server side function uploadfiles() on click -->
                  <input type="submit" id="" value="Upload File">

            </form>
        </body>
    </html>

This is my jaggery code
<%
    var verb=request.getMethod();
    if (verb=='POST'){

        var log = new Log();
        var file = request.getFile("myFile");
        file.move("C:\Users\vatsal ramesh gosar\Desktop\New folder\form\fileUploadUsingJaggery"+file.getName());

        response.sendRedirect("https://www.google.com");

    }

%>

It is giving a NULL Pointer Exception.
Please help me solve this problem with an efficient code.

A: request.getFile("myFile") does not represent a physical file, rather it represent a stream to the uploaded file. Hence you cannot "move" it using file.move("/moving/path") function. If you want to save the uploaded file, then use the following code snippet.
var uploadedFile = request.getFile("myFile");
var savedFile = new File("/path/to/save/location/" + uploadedFile.getName());
savedFile.open('w');
savedFile.write(uploadedFile.getStream());
savedFile.close();

A: In Jaggery documentation I haven't find any way to upload image into the server. But some alternatives there...
You encode the image into base64 encoding, you may use this way too encode the images on base64
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

then send the encoded String using POST request using Jaggery.


text:
Q: Tic-Tac-Toe Minimax tree Haskell For uni I have this assignment where I need to make Tic-Tac-Toe in Haskell. The problem I'm facing at the moment is creating a minimax tree, the code I found elsewhere for this problem is the following:
minimax :: Player -> Rose Board -> Rose Int
minimax p (MkRose r [])   | hasWinner r == Just p = MkRose 1 []
                          | hasWinner r == Just (nextPlayer p) = MkRose (-1) []
                          | otherwise              = MkRose 0 []

minimax P1 (MkRose r rs) = MkRose (maximum (map root xs)) xs
    where xs = map (minimax P2) rs

minimax P2 (MkRose r rs) = MkRose (minimum (map root xs)) xs
    where xs = map (minimax P1) rs

the hasWinner :: Board -> Maybe Player gives the winner of a tictactoe board if there is one, and data Rose a = MkRose a [Rose a].
The problem im having is that this function makes the minimax tree from the perspective of P1 (if P1 wins, the outcome is 1, if P2 wins, the outcome is -1) regardless of th player you input in the function. What I need is that if p = P2, that games where P1 wins are labeled as -1 and games where P2 wins are labeled as 1. The difficulty is that you can't just flip end values if p = P2, because then P1 needs to look for a minimum instead of a maximum, and vice versa. Does anyone know how i could rewrite this function fixing this issue? Thanks in advance!!


text:
Q: Custom Dimension with "Hit" Scope passing empty value for other hits I have a HTML single page application (it is a single HTML file, where i show page navigation as hiding and showing multiple div elements, so page navigations are not actual page loads, just switching divs)
I have created some 5 custom dimensions of "Session" scope, so they will be always present and tracked with some value.
However, I need a 6th dimension which will be populated only upon doing a particular operation such as clicking a button. So i have created 6th dimension and set its scope as "Hit". In the HTML application, as soon as the user clicks the button, i set the value for that dimension and do a send for that request (it is actually an 'ec' tracking), i can see that the 6th dimension value is also set.
The problem is, After this tracking, if i track any other event tracking or page view tracking, the same value is being passed for the cd6 parameter.
Could you please let me know if i am doing anything wrong here?

A: If you set a custom dimension via set it will apply to all hits that follow:
ga('set', 'dimension1', 'mydata');

will attach the dimension to all following tracking calls (especially bad on a single page app).
You can pass a JSON object as second parameter to the ga("send") call instead and set the dimension there:
ga('send', {
  'dimension1': 'mydata',
});

That way the dimension is only sent with that pageview, later interactions will not be affected.


text:
Q: node_modules folder missing after push to git remote repo Has anyone faced the problem of missing node_modules directory or any other dir after pushing to remote git repo?
I just did a git push origin master yesterday and can't find node_modules directory on my local repo since then.
I have the package.json file in my project dir, so I can just do npm install to get the modules back but wondering why it got deleted at all.
For more info, I have node_modules ignored in .gitignore file along with few others but I can see other ignored files present still in my project dir except node_modules. Anything I'm missing which can cause this? I did backup of my project dir just before pushing it to remote and can see node_modules dir present there.


text:
Q: Using a variable inside getElementByID to set focus() I'm trying to do something that seems like it should be dead simple. I'm trying to use a variable in getElementByID, which expects a quoted literal value. There are multiple fields that I want to run the same validation code on and, if there's an error, return to the field with the problem. Looking at other questions and answers, it seems that what I'm trying to do won't work, so there must be a better option, but I don't know what it is.
Here's what I have:
<!doctype html>

<meta charset="utf-8">
<title>I just want to focus!</title>

<form id="FooForm" name="FooForm" action="foo.php" method="post">

Leave Foo 1 to test focus.

Foo 1: <input type="text" id="Foo1" name="Foo1" onBlur="FocusFoo(this)">

Foo 2: <input type="text" id="Foo2" name="Foo2" onBlur="FocusFoo(this)">

Foo 3: <input type="text" id="Foo3" name="Foo3" onBlur="FocusFoo(this)">

</form>

A: Change your function to:
document.getElementById(FocusMe.id).focus();

since you need to pass the ID not the value to the getElementById function
OR just (easier as noted by the comments)
FocusMe.focus();


text:
Q: NetSuite - Returning an header is not NLAuth scheme error , when I am using OAuth I am trying to call a Restlet from a User Event Script which returns Customer information using Token Based Authentication .
But I receive an user error which says header is not NLAuth scheme
I know this means that I have to use the NLAuth scheme , but why is it giving this error?
Here is the authorization header I am using
 var headers =  { 'Authorization': 'Oauth realm="XXXXX", oauth_consumer_key="XXXXX" , oauth_token="XXXXX", oauth_nonce="XXX",oauth_timestamp="XXXX", oauth_signature_method="HMAC-SHA1", oauth_version="1.0",oauth_signature="XXXXXXXXXX="',
                'content-type': 'application/json'
                };

A: You need to capitalize the "a" in "Oauth"
Oauth -> OAuth

A: Make sure that you are using the account ID for the realm and that it is formatted correctly. 12345_SB1
The underscore must be used if that applies to your account
The letters must be capitalized.

A: Can you try this headers you will get solution
var headers = {
    "Authorization": "NLAuth nlauth_account='your account number',nlauth_email='login email' ,nlauth_signature='password'",
    "Content-Type":"application/json"
}


text:
Q: react useEffect detect if record is found I am doing this
const data = useQuery("query");
It returns {good:'nice'}
I have
useEffect(() => {
   if(!data) {
      // show not found
   }

}, [data])

In the useEffect, data is null in the first rerender, and then becomes the actual value in 2nd render, because useQuery takes time.
I need to show not found record in the above, but I can't distinguish if record was not found or if it's the n-th render where data hasn't been returned yet.
How do you solve this as the best practice ? i don't want to bring another variable to be tracking this. It seems so bad.

A: useQuery returns the property isLoading. You can use this.
Reference


text:
Q: Node.js path.join removes leading period I came home with a work project that I planned on fiddling with on my personal computer, I installed everything, using the exact same environment (Node v0.11.12), etc. Start the project, then I'm greeted with messages complaining that the config loader module cannot locate a file (that exists and is at the path exposed by the error).
Looking closer at the error, I realize that the problem is path.join(). Where
path.join('./foo/bar');
// 'foo/bar'

Which is not good. Why does path.join remove the leading period?
** Note **
The above is simply an example. The program make use of the function like
var configFile = require(path.join(modulePath, 'conf', file));

for example, where modulePath is relative to the current working directory (i.e. ./app/module/)

A: This is correct behavior, and is documented in the Path.join documentation:

Join all arguments together and normalize the resulting path.

It is correct because foo/bar is the normalized (canoncial) form of ./foo/bar, just as it is the normalized form of ./foo/././bar/. or foo/baz/../bar.
(Differences between require('./foo/bar') and require('foo/bar'), and any resulting problems of such, should be specifically addressed in a different question without path.join.)


text:
Q: need to get xml data from soap service I need to get an xml from my supplier containing data that will be proccesed in Excel.
Unfortunatly i have no experience in writing a php script to get that data.
My question is is there any other way to get this data? some specialized software witch will connect to my suppllier wsdl address and fetch that data?
Thank you so much.

A: For testing web services I've always used SoapUI - http://www.soapui.org/
It's a pretty neat tool and has a lot of features. If you use the free version that should do what you need which is call the service and retrieve the data in an XML format

A: I haven't used it myself, but this looks promising:
http://www.urdalen.no/wsdl2php/index.php
This will generate client code from the WSDL provided, and then you just have to write the code to get what you need from the generated PHP code.


text:
Q: MVC / HTML.DropDownListFor / making default option and its value I have CreateForm action in ProductController. This action uses view with model: ProductSupplierViewModel (consists of Product and List<Supplier> Suppliers).
In my CSHTML i have
@Html.LabelFor(m => m.Product.Supplier)
@Html.DropDownListFor(m => m.Product.Supplier.Id, new SelectList(Model.Suppliers, "Id", "Name"), "", new { @class = "form-control" })

BUT, this way i only have my default option set to blank (by using two quotation makrs in html helper).
What i need to know is:

*

*how to set a value="0" to that blank option?

*Does the web have default value if we dont specify one for it or?

Trying to get 0 because in my DataAccessLayer i have CreateProduct(Product p) method where i'll specify:
if(p.Supplier.Id == 0) // from parameter
{
  *put NULL value in this DB field*
}

A: The most simple is:
@Html.DropDownListFor(m => m.Product.Supplier.Id,
    new SelectList(Model.Suppliers, "Id", "Name", 0),
    "Please Select...",
    new { @class = "form-control" })

This creates a default item "Please Select...". However it's mandatory to select an item different than the default.
If selecting an item is not mandatory, you can do:
Controller
model.Suppliers.Insert(0, new Supplier()
{
    Id = 0,
    Name = "Please Select..."
});

View
@Html.DropDownListFor(m => m.Product.Supplier.Id,
    new SelectList(Model.Suppliers, "Id", "Name", 0),
    new { @class = "form-control" })


text:
Q: NPSP errors on creating new contact? I've got an org with 100,000+ contact records. We recently started seeing an issue where new contact creation fails if any of the Address fields are filled in. We recieve the following error:
Review all error messages below to correct your data.
Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or
contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be
selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2.
Data skew exists whereby the number of matching rows is very large (for instance, filtering for a
particular foreign key value that occurs many times)

We don't have any other triggers that fire on Contact records, so could this be a bug within the NPSP? Debugging is tough, since I don't seem to get any info about why, or in what package the error has occured!

A: I found out the answer. NPSP 3.0 had an error in the way it assigned Addresses to Accounts. This has already been corrected in a hotfix put out by the NPSP team. See the NPSP community for more information.


text:
Q: Code Coverage During Deployment I have a small peice of code I'm trying to deploy into production instance from a sandbox. Before deployment code coverage is 79%, I get an error saying it wont deploy because code coverage is 74%. Is it safe to assume the code I'm deploying is bringing down the coverage and therefore won't deploy?

My Web Service class is:
global class ClientAllocation {

WebService static List<Account> getAccount()
{
    string strQuery = 'select Name, CASESAFE_ID__c, Production_environment__c, External_Identifier__c, Member_Web_URL__c, Administration__c, Pensions__c, Broking__c, Helpdesk__c, Helpdesk_Email__c, Helpdesk_Number__c, Account_Owner_Name__c, Darwin_Support_Associate__c, Selection_Window_Open_Month__c from tableName WHERE Type = Client';
    List<Account> sobjList = Database.query(strQuery);

    return sobjList;
    }

}

and my test class is:
@isTest
public class ClientAllocationTest{
public static @isTest void sampleTestMethod(){
    list<Account> alist = ClientAllocation.getAccount();
    // system.assert();
    }
}

Can anyone identify any improvements that can be made to get this deployed? Obviously my code coverage isn't sufficient so the test class maybe?
Much appreciated

A: There is another problem with your test class as you can see in error log. In your strQuery you need to provide ' characters in WHERE clause because you are using a string to check Type field.
It should look like this
select Name, CASESAFE_ID__c, Production_environment__c, External_Identifier__c, Member_Web_URL__c, Administration__c, Pensions__c, Broking__c, Helpdesk__c, Helpdesk_Email__c, Helpdesk_Number__c, Account_Owner_Name__c, Darwin_Support_Associate__c, Selection_Window_Open_Month__c from tableName__c WHERE Type = \'Client\''

A: Please confirm the real data which is covering the code is making your code coverage less.
Make the data in org accordingly and try


text:
Q: ¿Como Cargar una vista dentro de otra? Estoy intentando mediante ajax hacer un append de una vista a otra pero no me funciona estoy trabajando con php y el framework laravel.
Vista .blade.php Principal

Este es mi controlador.php
public function verificarCuenta(Request $request){

    $data = array();
    $html =  view('user.transacciones_table');
    $data = array_add($data, 'html', $html);

    return $data;
}

Esta es la vista que deseo cargar .blade.php

          Prueba
          Prueba

al verificar en el ajax lo que retorno, un arreglo debido a que envió más variables a la vista cuando hago un console.log en mi vista recibo un arreglo vació donde debería estar mi vista.

He intentado en mi ajax cargar la vista con jquery de las maneras
  $("#prueba_html").html(response.html);
  $("#prueba_html").append(response.html);

Sin éxito alguno.
¿Alguien sabe de que manera se puede realizar esto?

A: Intenta con
$html = View::make('user.transacciones_table')->render();

Nota: Debes colocoar el namespace de View no el Facade.


text:
Q: Pre-create collection in Azure Cosmos DB Is there a way to pre-seed or pre-create my needed collections in Azure Cosmos DB? After creating resource on Azure, I am getting an empty database, but my goal is to have my required collections be presented after deploy.
Am I right, that I need to include deploying Azure Cosmos DB into my api deployment pipelines in Azure DevOps?
Thanks for any help.

A: You can create the cosmosdb account using the ARM/Bicep template and then try seeding data with your custom logic.
I have a sample setup for the same.
async function populateDb(data, collectionName) {
  MongoClient.connect(
    endpoint,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      sslValidate: false,
    },
    (error, client) => {
      if (error) {
        throw error;
      }
      database = client.db("yourdb");
      collection = database.collection(collectionName);
      let batch = collection.initializeOrderedBulkOp();

      for (let i = 0; i <= data.length; i += 1) {
        if (data[i]) {
          batch.insert(data[i]);
        }
      }
      batch.execute().then(() => console.log("Seeding completed on " + collectionName + " Collection", new Date().toLocaleString()))
        .c
        });
    });
};


text:
Q: How to ensure Async.StartChild is started before continuing? I am trying to await an event with timeout. I am abstracting this behind a function startAwaitEventWithTimeout. Currently my code looks like this (including some debug output messages):
let startAwaitEventWithTimeout timeoutMs event =
  async {
    Console.WriteLine("Starting AwaitEvent in eventAwaiter")
    let! eventWaiter = Async.StartChild(Async.AwaitEvent event, timeoutMs)
    try
      Console.WriteLine("Awaiting event in eventAwaiter")
      let! res = eventWaiter
      return Ok res
    with :? TimeoutException ->
      return Error ()
  } |> Async.StartChild

Here's a test:
let testEvent = Event<string>()

[<EntryPoint>]
let run _ =
  async {
    Console.WriteLine("Starting event awaiter in main")
    let! eventAwaiter = testEvent.Publish |> startAwaitEventWithTimeout 1000

    Console.WriteLine("Triggering event")
    testEvent.Trigger "foo"
    Console.WriteLine("Awaiting event awaiter in main")
    let! result = eventAwaiter

    match result with
    | Ok str -> Console.WriteLine("ok: " + str)
    | Error () -> Console.WriteLine("TIMEOUT")
  } |> Async.RunSynchronously
  0

Unfortunately, even though everything is "awaited" as far as I can see, it seems the run function proceeds to triggering the event before Async.AwaitEvent has had a chance to subscribe to the event. In short, here is the output I get:
Starting event awaiter in main
Starting AwaitEvent in eventAwaiter
Triggering event
Awaiting event awaiter in main
Awaiting event in eventAwaiter
TIMEOUT

Here is what I would expect:
Starting event awaiter in main
Starting AwaitEvent in eventAwaiter
Awaiting event in eventAwaiter  <-- this is moved up
Triggering event
Awaiting event awaiter in main
ok foo

I can work around the problem by adding e.g. do! Async.Sleep 100 between calling startAwaitEventWithTimeout and triggering the event, but of course this is less than ideal.
Have I done something incorrectly, and is there any way I can reliably ensure that AwaitEvent has been called before I trigger the event?
(Side note: I am doing this because we are calling remote processes over TCP, and all communication from the remote is done via events.)

A: Probably I am missing some requirement but your code can easily be refactored using continuations and the error fixed by itself.
let testEvent = Event<unit>()

let run _ =
  let ts = new CancellationTokenSource(TimeSpan.FromSeconds(float 1))
  let rc r =  Console.WriteLine("ok")
  let ec _ =  Console.WriteLine("exception")
  let cc _ =  Console.WriteLine("cancelled")
  Async.StartWithContinuations((Async.AwaitEvent testEvent.Publish), rc , ec,  cc, ts.Token  )
  testEvent.Trigger()
run()

Edit: If you have a specific requirement to use async workflows, you can convert it by using TaskCompletionSource in TPL.
let registerListener  timeout event=
  let tcs = TaskCompletionSource()
  let ts = new CancellationTokenSource(TimeSpan.FromSeconds(timeout))
  let er _ =  tcs.SetResult (Error())
  Async.StartWithContinuations(Async.AwaitEvent event, tcs.SetResult << Ok , er , er , ts.Token)
  Async.AwaitTask tcs.Task

let run _ =
  let testEvent = Event<int>()
  async {
       let listener = registerListener (float 1) testEvent.Publish
       testEvent.Trigger 2
       let! ta  = listener
       match ta with
         | Ok n -> printfn "ok: %d" n
         | Error () -> printfn "error"
  } |> Async.RunSynchronously

run()

Note that even though it is far easier to understand than spawning/awaiting multiple child computations, most of this code is still boilerplate and I am sure there must far easier solutions for setting a simple timeout value.

A: I do not think that you experience a race condition because you are consistently firing the event before the child computation is even started. Let's change the set-up - like you did for testing - to include a delay before firing.
open System
open System.Threading

let e = Event<_>()

let sleeper timeToFire = async{
    do! Async.Sleep timeToFire
    e.Trigger() }

let waiter = async{
    do! Async.AwaitEvent e.Publish
    return Ok() }

let foo timeToFire timeOut = async{
    Async.Start(sleeper timeToFire)
    let! child = Async.StartChild(waiter, timeOut)
    try return! child
    with :? TimeoutException -> return Error() }

foo 500 1000 |> Async.RunSynchronously
// val it : Result<unit,unit> = Ok null
foo 1000 500 |> Async.RunSynchronously
// val it : Result<unit,unit> = Error null

A race condition will now appear if the delay to firing is equal to the timeout.


text:
Q: AngularJS ng-show not firing when used with map Trying to use a key/value map to determine if an angular controlled element should be displayed :
http://jsfiddle.net/9fR23/181/
But I receive a exception :
angular.js:6173 TypeError: fnPtr is not a function
    at Object.elementFns [as get] (angular.js:6802)
    at Object.$get.Scope.$digest (angular.js:8563)
    at Object.$get.Scope.$apply (angular.js:8771)
    at angular.js:986
    at Object.invoke (angular.js:2873)

Using scope in this way is not illegal ? How to use a key/value map to determine if element should be displayed ? This map will be updated at runtime, so to ensure this update is reflected on UI I need to include apply() method ?
fiddle code :

            {{ person.first + ' ' + person.last }}

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
     var errorMap = new Object()

     errorMap['1'] = 'true'
     errorMap['2'] = 'false';
$scope.errorMap = errorMap

    $scope.people = [
        { id: 1, first: 'John', last: 'Rambo' },
        { id: 2, first: 'Rocky', last: 'Balboa' },
        { id: 3, first: 'John', last: 'Kimble' },
        { id: 4, first: 'Ben', last: 'Richards' }
    ];
});

A: errorMap('1') is not a function, its an object. so you can do this:
ng-show="errorMap['1']"

A: You are trying to call a method on your scope that is called errorMap.
Use square brackets to access it.

            {{ person.first + ' ' + person.last }}


text:
Q: Excel Formula Calculations I'm trying to add a spreadsheet editing function in my iOS app. I am using a gridview to display (not relevant to the question) and I am using LibXL to load the data into the view. That part all works very well but I have no way to calculate the formulas after a cell has been modified.
It appears that when I write a formula with LibXL it is not calculating the new value, just setting the formula value (a string). So when I try to read the number value from that cell it is still set to the last computed number (from excel).
Likewise, if I create cells with numbers and a formula cell to SUM them, it is never actually computed which reads a 0 number value until it's opened in Excel.
I was hoping LibXL was the silver bullet to my problem, but now I'm stuck with just the formula string value (i.e. "SUM(A1:b2)" ) and the last computed value.
I would love it if LibXL simply DID compute values and I just have it all wrong, but I can't see any documentation that says otherwise. If that's not the case are there any Obj-C, C, or C++ libraries that I can use to match the Excel Formula syntax and compute these values?

A: Just adding my previous comment as an answer:
Dave Delong's DDMathParser has the option to add custom functions, check it out here: http://github.com/davedelong/DDMathParser


text:
Q: How to convert Extended Event action mdmget_TimeStampUTC to datetime? SQL Server Extended Events can include an action of mdmtargetpkg.mdmget_TimeStampUTC. It returns a value such as 132085458320550473. How can that be converted to an actual date?
It doesn't appear to be a valid unix timestamp, even using microseconds.
Maybe it's the TimeStamp is actually RowVersion issue-- but this explicitly has "UTC" in it, implying it's a real time.
@@VERSION:
Microsoft SQL Azure (RTM) - 12.0.2000.8
    Jul  3 2019 10:02:53
    Copyright (C) 2019 Microsoft Corporation

A: The value 132085458320550473 is the number of ticks since January 1, 1601. Use the below function to convert it to datetime:
CREATE FUNCTION dbo.ConvertTicksToDateTime ( @Ticks bigint )
  RETURNS datetime
AS
BEGIN
    DECLARE @DateTime datetime2 = '16010101';
    SET @DateTime = DATEADD( DAY, @Ticks / 864000000000, @DateTime );
    SET @DateTime = DATEADD( SECOND, ( @Ticks % 864000000000) / 10000000, @DateTime );
    RETURN DATEADD( NANOSECOND, ( @Ticks % 10000000 ) * 100, @DateTime );
END


text:
Q: Python Non-Loop Way to change array values based on row and column position I am trying to change numpy-array values based on their column and row location and currently am achieving it this way:
for r in range(ResultArr2.shape[0]):
    for c in range(ResultArr2.shape[1]):
        ResultArr2[r,c] = ResultArr2[r,c]-r*1000-c*500

Is there a non-loop way of achieving the same result? I know that Python often works faster if one implements non-loop structure, but I could not find out how to do this.

A: You can use np.mgrid:
arr = np.random.uniform(size=(5,5))

n_rows, n_cols = arr.shape
r, c = np.ogrid[0:n_rows, 0:n_cols]
arr -= 1000 * r + 500 * c

A: Here are a few variants using either mgrid or ogrid or manually creating the same ranges that ogrid generates.
Observations:

*

*for an array of size  1000, the fastest method is more than three times faster than mgrid

*using ogrid or manual it is a bit better to add the two ranges separately, thereby avoiding a full size temporary

*conveniences such as mgrid or ogrid tend to come at a cost in numpy, and indeed the manual method is twice as fast as ogrid
Code:
import numpy as np

from timeit import timeit

A = np.arange(1000).reshape(20, 50)

def f():
    B = A.copy()
    m, n = B.shape
    I, J = np.mgrid[:m*1000:1000, :n*500:500]
    B += I+J
    return B

def g():
    B = A.copy()
    m, n = B.shape
    I, J = np.ogrid[:m*1000:1000, :n*500:500]
    B += I+J
    return B

def h():
    B = A.copy()
    m, n = B.shape
    I, J = np.ogrid[:m*1000:1000, :n*500:500]
    B += I
    B += J
    return B

def i():
    B = A.copy()
    m, n = B.shape
    BT = B.T
    BT += np.arange(0, 1000*m, 1000)
    B += np.arange(0, 500*n, 500)
    return B

def j():
    B = A.copy()
    m, n = B.shape
    B += np.arange(0, 1000*m, 1000)[:, None]
    B += np.arange(0, 500*n, 500)
    return B

assert np.all(f()==h())
assert np.all(g()==h())
assert np.all(i()==h())
assert np.all(j()==h())

print(timeit(f, number=10000))
print(timeit(g, number=10000))
print(timeit(h, number=10000))
print(timeit(i, number=10000))
print(timeit(j, number=10000))

Sample run:
0.289166528998976    # mgrid
0.25259370900130307  # ogrid 1 step
0.24528862700026366  # ogrid 2 steps
0.09056068700010655  # manual transpose
0.08238107499892067  # manual add dim