text:
Q: Draw a line against to indicate the max value in Amcharts I am plotting a graph which contains a lot of data.
96 plots a day and the user can fetch data for a maximum range of 62 days.
I am using Amcharts to implement the same.
I need to show the user a line against the highest value of the graph.
Can someone please help me if Amcharts provides a functionality to display the max value on the graph.
Because if it doesn't i would have to reiterate the entire object just to insert the max value in every json array which doesnt seem like a good idea.
Thanks

A: There's no need to iterate through all of the data. When the chart builds itself, it calculates min and max values for each value axis anyway. We can tap into those auto-calculated values and add a Guide for each of them.
We can use chart's "rendered" event to do it. When this event happens, we know that the chart is build and thus minimum and maximum values are calculated.
The value axis object will contain maxReal and minReal properties, which we will use. We will add a Guide for those values to indicate highest and lowest points.
Here's how the code looks for it:
chart.addListener( "rendered", function( event ) {
  // get chart and value axis
  var chart = event.chart;
  var axis = chart.valueAxes[0];

  // create max guide
  var guide = new AmCharts.Guide();
  guide.value = guide.label = axis.maxReal;
  guide.lineAlpha = 0.2;
  guide.lineThickness = 2;
  guide.lineColor = guide.color = "#00cc00";
  axis.addGuide( guide );

  // create min guide
  var guide = new AmCharts.Guide();
  guide.value = guide.label = axis.minReal;
  guide.lineAlpha = 0.2;
  guide.lineThickness = 2;
  guide.lineColor = guide.color = "#cc0000";
  axis.addGuide( guide );
} );

And here's a a complete working code of the chart:

var chart = AmCharts.makeChart( "chartdiv", {
  "type": "serial",
  "theme": "light",
  "path": "http://www.amcharts.com/lib/3/",
  "dataProvider": [ {
    "year": "1969",
    "value": -0.011
  }, {
    "year": "1970",
    "value": -0.068
  }, {
    "year": "1971",
    "value": -0.19
  }, {
    "year": "1972",
    "value": -0.056
  }, {
    "year": "1973",
    "value": 0.077
  }, {
    "year": "1974",
    "value": -0.213
  }, {
    "year": "1975",
    "value": -0.17
  }, {
    "year": "1976",
    "value": -0.254
  }, {
    "year": "1977",
    "value": 0.019
  }, {
    "year": "1978",
    "value": -0.063
  }, {
    "year": "1979",
    "value": 0.05
  }, {
    "year": "1980",
    "value": 0.077
  }, {
    "year": "1981",
    "value": 0.12
  }, {
    "year": "1982",
    "value": 0.011
  }, {
    "year": "1983",
    "value": 0.177
  }, {
    "year": "1984",
    "value": -0.021
  }, {
    "year": "1985",
    "value": -0.037
  }, {
    "year": "1986",
    "value": 0.03
  }, {
    "year": "1987",
    "value": 0.179
  }, {
    "year": "1988",
    "value": 0.18
  }, {
    "year": "1989",
    "value": 0.104
  }, {
    "year": "1990",
    "value": 0.255
  }, {
    "year": "1991",
    "value": 0.21
  }, {
    "year": "1992",
    "value": 0.065
  }, {
    "year": "1993",
    "value": 0.11
  }, {
    "year": "1994",
    "value": 0.172
  }, {
    "year": "1995",
    "value": 0.269
  }, {
    "year": "1996",
    "value": 0.141
  }, {
    "year": "1997",
    "value": 0.353
  }, {
    "year": "1998",
    "value": 0.548
  }, {
    "year": "1999",
    "value": 0.298
  }, {
    "year": "2000",
    "value": 0.267
  }, {
    "year": "2001",
    "value": 0.411
  }, {
    "year": "2002",
    "value": 0.462
  }, {
    "year": "2003",
    "value": 0.47
  }, {
    "year": "2004",
    "value": 0.445
  }, {
    "year": "2005",
    "value": 0.47
  } ],
  "valueAxes": [ {
  } ],
  "graphs": [ {
    "id": "g1",
    "bullet": "round",
    "lineColor": "#d1655d",
    "lineThickness": 2,
    "negativeLineColor": "#637bb6",
    "valueField": "value",
    "bulletField": "bullet-g1",
    "labelText": "[[label-g1]]"
  } ],
  "chartCursor": {
    "categoryBalloonDateFormat": "YYYY",
    "zoomable": false
  },
  "dataDateFormat": "YYYY",
  "categoryField": "year",
  "categoryAxis": {
    "minPeriod": "YYYY",
    "parseDates": true,
    "minorGridAlpha": 0.1,
    "minorGridEnabled": true
  }
} );

chart.addListener( "rendered", function( event ) {
  // get chart and value axis
  var chart = event.chart;
  var axis = chart.valueAxes[0];

  // create max guide
  var guide = new AmCharts.Guide();
  guide.value = guide.label = axis.maxReal;
  guide.lineAlpha = 0.2;
  guide.lineThickness = 2;
  guide.lineColor = guide.color = "#00cc00";
  axis.addGuide( guide );

  // create min guide
  var guide = new AmCharts.Guide();
  guide.value = guide.label = axis.minReal;
  guide.lineAlpha = 0.2;
  guide.lineThickness = 2;
  guide.lineColor = guide.color = "#cc0000";
  axis.addGuide( guide );
} );
#chartdiv {
  width: 100%;
  height: 500px;
}


text:
Q: How to version front-end projects? Semantic versioning brings the follow approach:

*

*MAJOR version when you make incompatible API changes

*MINOR version when you add functionality in a backwards-compatible manner

*PATCH version when you make backwards-compatible bug fixes

However a frontend project doesn't have an API, its doesn't break compatibility of usage, then, what the arguments to change the versions in frontends?
Please, sugestions.

A: Proposal
Given the importance of the installation-requirements of an application to installer-users, I propose that semver be used to version end-user applications using the installation-requirements as the public API with installer-users as the consumers of this API.
In practice, increment the:
•   MAJOR version when you make incompatible API changes (e.g. installer-users have to modify their infrastructure (phone/tablet/PC/web-server/firewall config/etc) in some way),
•   MINOR version when you add functionality in a backwards-compatible manner (e.g. passing additional data to an already-provisioned API or adding any end-user functionality that does not affect the installation-requirements), and
•   PATCH version when you make backwards-compatible bug fixes (e.g. fixing any end-user bug that does not affect the installation requirements).
By treating the installer-users as the consumers of an end-user application, and the installation-requirements as the public API, I believe that semver does make sense and is valuable as a communications mechanism for end-user applications.
https://medium.com/@u_glow/making-sense-of-semantic-versioning-for-end-user-software-applications-a3049d97478b

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET MVC 3: Output specific view for concrete implementation I have an IEnumerable of a base type as my model.
I need to display a different bit of HTML in a list depending on what the concrete type is.
So the resulting list might look similar to this in HTML:

Points - Item 1 - 10 points Remove

Media - Item 2 - your_uploaded_image.jpg Remove

Content - Item 3 Remove

It's likely I will add another type to this later so solutions like the following aren't really what I'm after.
@foreach(var item in Model)
{
   if(item is PointImpl)
   {
       var pointItem = item as PointImpl;

Points - @pointItem.Name - @pointItem.Points points Remove

   }
   else if(item is MediaImpl)
   {
       var mediaItem = item as MediaImpl;

Media - @mediaItem.Name - @mediaItem.FileName  Remove

   }
   /*
       More implementations
   */
}

I've had a look at model metadata template hint but that doesn't really help because my model is an IEnumerable..
I was thinking about a custom Html Helper looking at an attribute on the concrete type but think there might be a built in way of doing this?

A: Instead of the ugly foreach simply use display templates:
@model IEnumerable<SomeBaseViewModel>

    @Html.DisplayForModel()

and then define display templates for all child types. For example:
~/Views/Shared/DisplayTemplates/PointImpl.cshtml:
@model PointImpl

    Points - @Model.Name - @Model.Points points
    Remove

and: ~/Views/Shared/DisplayTemplates/MediaImpl.cshtml:
@model MediaImpl

    Media - @Model.Name - @Model.FileName
    Remove

See, no more ifs, no more loops, no more vars. Everything works by convention (templates must be situated in the ~/Views/Shared/DisplayTemplates or ~/Views/SomeController/DisplayTemplates folder and should be named as the name of the concrete type - PointImpl.cshtml, MediaImpl.cshtml, ...). Based on the concrete type the corresponding display template will be rendered and this automatically for each element of the main model collection.


text:
Q: Drawing a line without duplicating in Winforms Hi, I would like to draw a straight line in a picturebox in winforms using mouse events. i use mouse down, mouse move and mouse up events to draw a line. However, as i move my mouse, several other lines are also being drawn.
I would really appreciate if anyone can provide a guide as to how to solve this problem.
I have also attached snippets of my code for your reference. Thank you in advance!
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {

        mousepress = true;
        x1 = e.Location.X;
        y1= e.Location.Y;
        if (counter>0)
        {
            this.Invalidate();
            pictureBox1.Refresh();
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {

        Graphics g = pictureBox1.CreateGraphics();
        Pen newpen = new Pen(Color.Blue, 1);

        if (mousepress)
        {
            g.DrawLine(newpen, x1, y1, e.Location.X, e.Location.Y);
            x2 = e.Location.X;
            y2 = e.Location.Y;
            angle = GetAngle(x1, y1, x2, y2);
        }
        Invalidate();

    }

  private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        mousepress = false;
        double tempX=e.Location.X, tempY=e.Location.Y;

        {
            textBox_coordinates.Text = "Index: " + i + Environment.NewLine + "X: " + x2
         + Environment.NewLine + "Y: " + y2 + Environment.NewLine + "Angle: " + angle;
            i++;

        }

        counter++;
    }

A: In the MouseMove event you have to refresh the PictureBox also to clear the line(s) you have drawn in the previous call(s). And never forget to dispose the unmanaged graphics resources after allocating them, unless you want a memory hole.
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    // vvv take care of automatic disposal
    using (Graphics g = pictureBox1.CreateGraphics())
    using (Pen newpen = new Pen(Color.Blue, 1))
    {
        if (mousepress)
        {
            pictureBox1.Refresh(); // <-- get rid of the previous lines

            g.DrawLine(newpen, x1, y1, e.Location.X, e.Location.Y);
            x2 = e.Location.X;
            y2 = e.Location.Y;
            angle = GetAngle(x1, y1, x2, y2);
        }
        // Invalidate(); // check if necessary!
    }
}

Edit: Another way to get what you want is to intercept the paint event and do your line drawing there (after the inherited drawing of PictureBox). I guess most people would consider this a more clean solution because that's precisely what the paint event is for. But if you just want to get your narrow task quickly done, the solution suggested above is enough.

A: Something like that...
public partial class Form1 : Form
{
    bool mousepressed;
    int x1=0, y1=0,x2=0,y2=0;
    Pen newPen = new Pen(Color.Blue, 2);
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        mousepressed = true;
        x1 = e.X;
        y1 = e.Y;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (mousepressed)
        {
            x2 = e.X;
            y2 = e.Y;
            pictureBox1.Refresh();
        }
    }
    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawLine(newPen, x1, y1, x2, y2);
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        mousepressed = false;
    }
}


text:
Q: barcode: generate code with set width I have code like this

When I set style it's break line, so how i can set width this barcode smaller than it ?

A: By this case, I answer my own for share to someone if meet problem as me
1 -> barWidth: 1,
2 -> barHeight: 50,
3 -> moduleSize: 5,
4 -> showHRI: true,
5 -> addQuietZone: true,
6 -> marginHRI: 5,
7 -> bgColor: "#FFFFFF",
8 -> color: "#000000",
9 ->fontSize: 10

Reference there


text:
Q: How to connect to Slack via slackr package in R I'm trying to set up the slackr package in R to allow me to post to Slack through RStudio, but it seems the connection isn't working.
I've installed the package, set up the required App in my Slack Workspace, have a webhook and access tokens, manually granted all of Scopes needed in Slack, set up the config file and have confirmed via the cmd line that this works by sending a message to the channel through that successfully. Unfortunately nothing is working via R.
slackr_msg(paste("test"),
,channel = "#it-reports")

slackr_ims(api_token="xoxb-...")

When run the above both produce Error: Join columns must be present in data. x Problem with 'id'. which I can't find anybody else experiencing. It sounds like an issue with the user, but the app is in the channel, has permission to access all public channels, and this error appears regardless of whether I try and send it via my logged in account or just from the bot. When I just try and return something simple like listed channels with slackr_channels I get NULL. I've tried both OAuth Access Token and Bot User OAuth Access Token with all permissions needed in the scope but neither are letting me access Slack.

A: I'm not sure you still need an answer, but in case anyone else is looking - I've run into the same issue.  I think the underlying method that your slack channel name "#my_excellent_named_channel" is converted to the channel id is deprecated.
"https://slack.com/api/channels.list" has been changed to "https://slack.com/api/conversations.list" in the methods.
I couldn't find a better way than brute forcing my channel id because I only need to publish to a notifications channel.
nextCursor=""
for (j in c(1:10)){
  resp<-GET(url = "https://slack.com/api/conversations.list",
            query = list(token=YOUR_BOT_TOKEN,
                         cursor=nextCursor
            ))

  foo=fromJSON(content(resp, as="text"))

  for (i in c(1:100)){
    if(foo$channels[[i]]$name %like% 'my_excellent_named_channel'){
      print(paste(nextCursor, "\n"))
      print(paste(i,foo$channels[[i]]$name,"\n"))
      print(paste(foo$channels[[i]]$id))
    }
  }

  nextCursor=foo$response_metadata[[1]]
}

You'll probably need to run through a few more than the 10 top level iterations, but if you go too fast it locks you out. I then just exchanged the channel name in my config file for the channel id, and rewrote the functions to avoid the conversion.
Here's slackMsg (conversion of slackrMsg)
slackMsg=function (txt = "", channel = Sys.getenv("SLACK_CHANNEL"), username = Sys.getenv("SLACK_USERNAME"),
          icon_emoji = Sys.getenv("SLACK_ICON_EMOJI"), api_token = Sys.getenv("SLACK_API_TOKEN"),
          ...)
{
  if (api_token == "") {
    stop("No token specified. Did you forget to call slackr_setup()?",
         call. = FALSE)
  }
  if (icon_emoji != "") {
    icon_emoji <- sprintf(", \"icon_emoji\": \"%s\"", icon_emoji)
  }
  output <- paste0(txt, collapse = "\n\n")
  loc <- Sys.getlocale("LC_CTYPE")
  Sys.setlocale("LC_CTYPE", "C")
  on.exit(Sys.setlocale("LC_CTYPE", loc))
  resp <- POST(url = "https://slack.com/api/chat.postMessage",
               body = list(token = api_token, channel = channel,
                           username = username, icon_emoji = icon_emoji, text = output,
                           as_user = TRUE, link_names = 1, ...))
  warn_for_status(resp)
  return(invisible())
}

Don't forget to give your bot chat.write permissions in your Slack App.


text:
Q: Formidable pro appointment field copy data value I need to copy a appointment field (simply schedule appointments plugin) to other data Field, any people help tks
Reply from ssa:
This will mainly require using hooks from the Formidable Forms fields since those are what will be modified/updated. Then, the Appointment ID will need to be translated into the dates/times format needed.
We have an example of this here:
$appointment = new SSA_Appointment_Object( 123 );
// where 123 is the appointment ID database reference
$start_date = $appointment->start_date;
// date-time string like Y-m-d H:i:s (in UTC timezone)
$start_date = $appointment->start_date_datetime;
// DateTimeImmutable object (in UTC timezone)

copy appointment field to other data Field on formidable pro


text:
Q: Aggregate data - Difference in Differences Analysis I am currently working on a DID analysis on the causal effect of a vacancy tax on the breaking and entering rate in the city.
The purpose of the tax is to create an incentive for people to put empty and under-utilized homes onto the market. It taxes homes that are empty for more than 6 months in the reference year.
My theoretical framework consists of social disorganization theory and broken window theory. The reasoning is that more empty homes means more opportunity for crimes, so less empty homes means less opportunity for crimes.
The tax (treatment) took effect right away at the beginning of 2017.
I have data of the numbers of breaking and entering for the treatment city and control city from 2014 to 2017 (3 pre-treatment and 1 post-treatment periods). I can get more pre-treatment data if needed but I believe 3 should be enough to establish trend assumption.
Can I use my current data to do a difference in differences analysis? I am new to DID and I am not quite sure how to create an appropriate equation.
Thank you in advance for your help!

A: You have enough data to estimate the DID effect, but too few data points to calculate standard errors correctly or to probe parallel trends: you have eight data points (and really just two observed 4 times) and you are estimating 4 parameters. This means your ability to extend this result to other places will be very limited since you cannot quantify the uncertainty of the estimated effect. But you can get the effect by hand rather than using regression.
Here is an example using a dataset on the weights of two pigs:
. webuse pig, clear
(Longitudinal analysis of pig weights)

. keep if inlist(id,1,2)
(414 observations deleted)

. keep if week <= 4
(10 observations deleted)

. xtset id week

Panel variable: id (strongly balanced)
 Time variable: week, 1 to 4
         Delta: 1 unit

. gen treated = id == 2

. gen post    = week == 4

. list, clean noobs

    id   week   weight   treated   post
     1      1       24         0      0
     1      2       32         0      0
     1      3       39         0      0
     1      4     42.5         0      1
     2      1     22.5         1      0
     2      2     30.5         1      0
     2      3     40.5         1      0
     2      4       45         1      1

. diff weight, period(post) treated(treated) cluster(id)

DIFFERENCE-IN-DIFFERENCES ESTIMATION RESULTS
Number of observations in the DIFF-IN-DIFF: 8
            Before         After
   Control: 3              1           4
   Treated: 3              1           4
            6              2
--------------------------------------------------------
 Outcome var.   | weight  | S. Err. |   |t|   |  P>|t|
----------------+---------+---------+---------+---------
Before          |         |         |         |
   Control      | 31.667  |         |         |
   Treated      | 31.167  |         |         |
   Diff (T-C)   | -0.500  |    .    |    .    |    .
After           |         |         |         |
   Control      | 42.500  |         |         |
   Treated      | 45.000  |         |         |
   Diff (T-C)   | 2.500   |    .    |    .    |    .
                |         |         |         |
Diff-in-Diff    | 3.000   |    .    |    .    |    .
--------------------------------------------------------
R-square:    0.46
* Means and Standard Errors are estimated by linear regression
**Clustered Std. Errors
**Inference: *** p<0.01; ** p<0.05; * p<0.1

. xtreg weight i.post##i.treated, fe vce(cluster id)
note: 1.treated omitted because of collinearity.

Fixed-effects (within) regression               Number of obs     =          8
Group variable: id                              Number of groups  =          2

R-squared:                                      Obs per group:
     Within  = 0.4568                                         min =          4
     Between = 1.0000                                         avg =        4.0
     Overall = 0.4560                                         max =          4

                                                F(0,1)            =          .
corr(u_i, Xb) = -0.0695                         Prob > F          =          .

                                     (Std. err. adjusted for 2 clusters in id)
------------------------------------------------------------------------------
             |               Robust
      weight | Coefficient  std. err.      t    P>|t|     [95% conf. interval]
-------------+----------------------------------------------------------------
      1.post |   10.83333          .        .       .            .           .
   1.treated |          0  (omitted)
             |
post#treated |
        1 1  |          3   1.40e-15  2.1e+15   0.000            3           3
             |
       _cons |   31.41667          .        .       .            .           .
-------------+----------------------------------------------------------------
     sigma_u |  .35355339
     sigma_e |  8.2965856
         rho |  .00181269   (fraction of variance due to u_i)
------------------------------------------------------------------------------

Other suggestions:

*

*You may want to normalize B&E by population if your two cities are of unequal size.

*If you can get more cities and additional pre-treatment data, you could use a synthetic cohort approach which will work a lot better with a single treated unit than DID.


text:
Q: Domus Memory Used Issue With Xen On CentOS Anyone know why I'm receiving this error? I compiled latest libvirt from source, I also tried with various rpm.
I would like to get memory used by domus and it looks like it's not working with Xen 3 on CentOS 5.
virsh #  dommemstat mydomainname
error: Failed to get memory statistics for domain mydomainname
error: this function is not supported by the connection driver: virDomainMemoryStats

virsh # domcontrol mydomainname
error: this function is not supported by the connection driver: virDomainGetControlInfo

Any help will be appreciated.


text:
Q: Implementar funções em aplicação web2py usando jQuery Olá. Não sei se é o termo correto, mas eu tenho uma aplicação feita usando web2py como framework. Eu sei absolutamente nada de jQuery mas a página inicial do site que eu criei está demorando muito pra carregar e eu queria tentar usar aquela função infinite scroll e todo texto que eu vejo por aí sobre isso usa jQuery. Então estou disposto a aprender o básico afim de entender os snippets que tornam possível essa função.
Gostaria de saber se eu teria que aprender apenas jQuery ou é necessário aprender alguma outra linguagem para implementar o infinite scroll na aplicação — pergunto isso porque sempre que vejo algo sobre jQuery, em algum momento Ajax aparece junto — e se é tranquilo e intuitivo, uma vez aprendido o necessário, deixar tudo funcionando em uma aplicação já existente.
Muitíssimo obrigado.

A: A resposta deve vir de você mesmo. E a pergunta que se deve fazer é:

quero compreender o código que corre na minha página?

*

*Sim!

Entäo aprender e usar uma biblioteca como jQuery ou MooTools é uma boa ideia pois poupa muito código. Acelera a escrita de um código que faz essa funcionalidade.

*

*Näo!

Pague a alguém que faça isso por sí.


text:
Q: Texmaker editor and others show incorrect cyrillic symbols I'm trying to build a template from this russian journal. But no editor can recognize what encoding is used. It is supposed to be 'cp866' but it looks like this
à ®æ¥áá ®ä®à ¬«¥¨¨ áâ âì¨ á ¯®¬®éìî REV\TeX~4

instead of
Процесс оформления статьи с помощью REV\TeX~4

The other examples of a text that are shown incorrectly are here and there.
Is there a problem with my OS?

A:
It appears to be IBM866 format


text:
Q: How do I access multiple records from the same table using SQLDataAdapter? This almost works. I get an error at the last line that looks like it's complaining about the C1 reference. Is there a simple way around this? There is nothing wrong with the query or connection.
  Dim CmdString As String
    Dim con As New SqlConnection
    Try
        con.ConnectionString = PubConn
        CmdString = "select * from " & PubDB & ".dbo.Suppliers as S " & _
            " join " & PubDB & ".dbo.Address as A" & _
            "  on S.Supplier_Address_Code = A.Address_IDX" & _
            " join " & PubDB & ".dbo.Contacts as C1" & _
            "  on S.Supplier_Contact1 = C1.Contact_IDX" &
            " join " & PubDB & ".dbo.Contacts as C2" & _
            "  on S.Supplier_Contact2 = C2.Contact_IDX" &
            " WHERE S.Supplier_IDX = " & LookupIDX

        Dim cmd As New SqlCommand(CmdString)
        cmd.Connection = con
        con.Open()

        Dim DAdapt As New SqlClient.SqlDataAdapter(cmd)
        Dim Dset As New DataSet

        DAdapt.Fill(Dset)
        con.Close()

        With Dset.Tables(0).Rows(0)

            txtAddress1.Text = .Item("Address1").ToString
            txtAddress2.Text = .Item("Address2").ToString
            txtSupplierName.Text = .Item("Address_Title").ToString
            txtAttn.Text = .Item("Attn").ToString
            txtBusinessPhone1.Text = .Item("C1.Contact_Business_Phone").ToString

A: You would not include the "C1" table alias as part of your column name.  It will be returned from your query as Contact_Business_Phone.
For accessing multiple rows you could use the indexer as you are in the example above "Rows(0)" by placing your With block into a For loop and accessing the "Rows(i)" with your loop variable.  However, this would not help much as your are assigning this to individual text boxes, so you'd only see the last value on your page/screen.

A: The alias C1 is used by SQL Server and is not persisted to the result set. Have you taken this query into SQL Management Studio to see the results?
Since you requested all columns (*) and joined to the Contacts table twice, you'll end up with duplicate column names in the result. For example, if the Contacts table has a LastName field, you'll end up with TWO LastName columns in your result.
I haven't tried to duplicate this in my local environment, but I can't imagine the data adapter is going to like having duplicate column names.
I recommend specifically including the columns you want to return instead of using the *. That's where you'll use the alias of C1, then you can rename the duplicate columns using the AS keyword:
SELECT C1.LastName AS [Supplier1_LastName],
       C2.LastName AS [Supplier2_LastName],
...

This should solve your problem.
Good Luck!

A: You should only be pulling back the columns that you're in fact interested in, as opposed to *.  It's sort of hard to tell exactly what data exists in which tables since you're pulling the full set, but at a quick guess, you'll want in your select statement to pull back A.Address1, A.Address2, A.AddressTitle, ?.Attn (not sure which table this actually derives from) and C1.Contact_Business_Phone.  Unless you actually NEED the other fields, you're much better off specifying the individual fields in your query, besides having the possible duplicate field issue that you're running into here, it can also be a significant performance hit pulling everything in.  After you clean up the query and only pull in the results you want, you can safely just reference them the way you are for the other fields, without needing a table alias (which as others have pointed out, isn't persisted to the result set anyways).


text:
Q: How to view the packages/tools that will be installed by Ubuntu Make? e.g. If I use following command:
$ umake web

How to list all the tools/ide/packages installed by this command?

A: From the manpage:
* Command 'web': usage: umake web [-h] {visual-studio-code,firefox-dev}
       ...

   positional arguments:
              {visual-studio-code,firefox-dev}

       visual-studio-code
              Visual Studio focused on modern web and cloud

       firefox-dev
              Firefox Developer Edition

It looks like only Visual Studio Code and Firefox Developer Edition are installed by umake web. The other subcommands are also listed in the manpage, for example:
* Command     'android':     usage:     umake     android     [-h]
       {android-ndk,android-sdk,android-studio} ...

   positional arguments:
              {android-ndk,android-sdk,android-studio}

       android-ndk
              Android NDK

       android-sdk
              Android SDK

       android-studio
              Android Studio (default)


text:
Q: What is the point of the remainder term in the Taylor series Take the first order taylor approximation:
We say $f$ is differentiable at $x_0 \in S^o$ if $\exists \space \nabla f(x_0)$ and a function $R: \mathbb{R}^n \to \mathbb{R}$ such that
$f(x) = f(x_0) + \langle \nabla f(x_0), x-x_0 \rangle + R(x-x_0)$
I don't understand what the point of the Remainder term is? Is it just trying to say there is a degree of error involved in the taylor approximation (which is the first two terms if I am not mistaken?)
What does this limit: $\lim_{x \to x_0} \frac{R(x-x_0)}{\| x-x_0 \|}=0$ convey in terms of information? If this implies that $R(x-x_0)$ grows slower than $\|x-x_0\|$ why is that useful?

A: The behavior of the error is the only thing that really lets us know that it's a good approximation.
I can, for example, write $x^3=5x\sin(x)+xe^x+R(x)$, where $R(x) = x^3 -5x\sin(x)-xe^x$, and call $R$ the error. Is this useful in any way?

A: Any function approximates another. For instance, here are two approximations of $f$:
$$f(x) \approx f(x_0),$$
$$f(x) \approx f(x_0) + \langle \nabla f(x_0), x-x_0 \rangle.$$
If we don't know how close we approximate $f$, these formulas are of little use. The remainder answers this question.
In addition, if you had a remainder that is as large as the some term in the development (which generalizes to higher orders), it would be useless to consider this term. So we require that the remainder decreases faster (when you get closer to $x_0$) than the smallest term.


text:
Q: Read .coverage file outside VS2010 I generated .coverage file using the Performance Tools in VS2010. I can follow all steps to get the .coverage file in command line.
but i have VS2010 Professional version, so that i cannot open the .coverage file and see the coverage inside VS2010 (or can I do so?). Is there a way to see the results another way, using freeware etc... ?
For instance is there a way to get the Microsoft.VisualStudio.Coverage.Analysis.dll and have it working fully in VS2010 PRO ?
Thanks


text:
Q: How to force preprocessor to use desired data type in C/C++?
I would like to test bit size of unsigned long using macro. One would think that if you specify 0UL it will evaluate as unsigned long, but according this short example it is not true. I compiled it using MinGW on 32bit architecture, so ~0UL should get me 0xFFFFFFFF:
#if (((~0UL) >> 31) >> 1) // expected 0, double shift to get around mod 32 limit
   #define UL_BIT_SIZE 64
#else
   #define UL_BIT_SIZE 32
#endif

printf("%d, %X\n", UL_BIT_SIZE, ((~0UL) >> 31) >> 1);

Output:    64, 0
Funny thing is that if I change UL to L or simply skip the postfix it's working as expected. Can anyone please explain what's the problem here, what's the cause and how can it be solved?

A: C preprocessor does not know types or C keywords.
Preprocessor arithmetic is done with the largest integer type from stdint.h which is intmax_t or  uintmax_t depending on the sign of the operands.


text:
Q: Create sequence of degrees and radii that may contain 0 and convert to cartesian coordinates in R I am needing to create a path between two points for which distance and degrees are known, and then convert the result to Cartesian coordinates using R. The origin for both points is 0,0. The radii always vary in length. The direction is always anti-clockwise.
I have been unable to work out how to do the degrees sequence as the range sometimes may include 0°. The start and end degrees will vary so I need method that can handle any range <= 180°. In other words, the difference between the start and end angle will never exceed 180°.
The issue is illustrated in the code below:
rad <- seq(943.0975, 939.5975, length.out = 1000)
deg <- seq(67.8352, 247.8352, length.out = 1000)

The rad vector works correctly but the deg vector is incorrect as it ends up following a clockwise direction. Doing a descending seq() means it doesn't cross 0°.
How is a range of degree values that contains 0° handled in this instance?

A: Unable to find a concise method, this is how I handled the issue. It involves a process that generates two vectors for degrees - one for everything to the "left" of 0° and one for everything to the "right" of 0°. It is "messy" around the 0° in that the difference between the two values directly to the left and right of 0° may not be == turni, but given the size of endturnp the issue is not perceptible. This code only works if degdiff <= 180°.
Declared variables
degA <- 67.8352   # Start point degrees
radA <- 943.0975  # Start point radius
degB <- 247.8352  # End point degrees
radB <- 939.5975  # End point radius
endturnp <- 2030  # Number of points to plot between start and end point

Derived variables
degdiff <- (outdegs - outdege + 180) %% 360 - 180     # Degrees difference between start and end
degdiff <- ifelse(degdiff < 0, degdiff * -1, degdiff) # Convert to positive number if negative
turni <- degdiff / endturnp                           # Get degrees increment between degA and degB based on "endturnp"

Generate degree vector from degA to degB
if(degA < degB) { # If range includes 0 degrees
   leftlen <- 0:floor((360 - degB) / turni) # Return length vector for degrees > 180 & < 360
   leftdeg <- sort(degB + (leftlen * turni), decreasing = T) # Calculate degrees
   rightlen <- 0:floor(degA/turni) # Return length vector
   rightdeg <- degA - (turni * rightlen) # calculate degree
   indexdeg <- append(rightdeg,leftdeg) # Combine degrees vectors
   } else {
      indexdeg <- seq(degA, degB, length.out = endturnp) # Create index
}

Generate radii vector from degA to degB
indexrad <- seq(radA, radB, length.out =  length(indexdeg))

Combine radii and degrees vectors and calculate xy coordinates
arcpath <- data.frame(rad = indexrad,
                      deg = indexdeg,
                      x = NA,
                      y = NA)

arcpath$x <- arcpath$rad * sin(pi * 2 * arcpath$deg / 360)
arcpath$y <- arcpath$rad * cos(pi * 2 * arcpath$deg / 360)

And finally, plot result
ggplot() +
  geom_path(data = arcpath, aes(x = x, y = y),
        linewidth = .4,
        lineend = "square")


text:
Q: security review: chimera report - Cross-Domain JavaScript Source File Inclusion I'm preparing for my first security review for an application which has an external web app.
I'm looking at the Chimera report and I'm seeing the error: Cross-Domain JavaScript Source File Inclusion. This is because my web app has static files hosted on AWS S3.
An example <script type="text/javascript" src="https://my_app.s3.amazonaws.com/js/js.js"></script>
The report states that the risk level is low, is the something I need to resolve or something that can be explained away as I go through the review?


text:
Q: Get filenames from directory from same extension but without the extension (MATLAB) I'm fairly new at MATLAB, so forgive if I'm saying stuff that is completely wrong. I am trying to write a little program that reads in the files from a certain directory with extension .xlsx and then assigns the columns to vectors. When I manually give up the file names, my program looks like this:
files = {'130926','130927'}
file_number = 1;
file_amount = length(files);
while file_number <= file_amount
file_name = files(file_number);
cd('C:\place_where_I_store_my_files');
A = xlsread(char(strcat(file_name)));
J = A(:,1);
J_sp = A(:,2);
file_number = file_number + 1
end

I've tried a lot of different things to read in the files automatically among wich:
files = {'*.xlsx'}

But it all yields errors.
Thanks for reading.
Matthias

A: Use the dir function with a wildcard search.
my_path = 'C:\place_where_I_store_my_files';
xlsfiles = dir(fullfile(my_path, '*.xlsx'));
for ii = 1 : length(xlsfiles)
  disp(fullfile(my_path, xlsfiles(ii).name));
end

The above code will display the names of all xlsx files in the directory you specify.

A: How about this :-
>> list = dir('C:\path\*.xlsx');
>> names=cellfun(@(x)x(1:end-5),{list.name},'UniformOutput', false);

Access using names{1}, names{2}... so on
This creates an anonymous function that works on cells of names received from dir command.
Type : help dir and help cellfun for more details at command prompt

A: FYI, this did it for me:
files = dir('C:\Users\Matthias\Desktop\KUL\2e_Master\Thesis\MBR_data\MBR_online\*cs.xlsx')
file_number = 1;
file_amount = length(files);
while file_number <= file_amount
file_name = files(file_number).name;
cd('C:\place_where_I_store_my_files');
A = xlsread(char(file_name));
J = A(:,1);
J_sp = A(:,2);
file_number = file_number + 1
end

Greetings,
Matthias


text:
Q: Quarto Book: make body content Wider Love love quarto. So well developed! Thanks again. I'm using the book output format and it looks great. However I know the screen sizes it will be used on and would really like the main content (id=quarto-document-content) to be wider, pushing the toc to the right of the screen. How would I do this? Something like (just close-ish examples)

*

*sidebar: 15%

*quarto-document-content: 80%

*toc: 5%

Many thanks!


text:
Q: How to make infinite-scroll plugin works in a DIV? There is a fixed-height div, which has scrollbar. When its only-child element ol being scrolled to the bottom, the ol needs to load more new li.
I'm using jQuery infinite-scroll plugin.
I can't get the plugin to work in the aforementioned situation on desktop browsers.
In iOS, it sorta works, and is buggy. When I scroll the ol to the bottom, it doesn't load. And then when I try to scroll the ol more (it actually can't be scrolled more), it successfully loads.
Here is a simple demonstration of my code.
Here is the demonstration code.

A: Taken from the infinite-scroll documentation:

To scroll inside an element having overflow, use the local behavior.

So rather than having a #container element that has the overflow, just use the infinite scroll on the list:
$('#container').infinitescroll({
    behavior: 'local',
    binder: $('#container'),
    bufferPx: 0,
    navSelector  : '#nav',    // selector for the paged navigation
    nextSelector : '#nav a',  // selector for the NEXT link (to page 2)
    itemSelector : 'li'       // selector for all items you'll retrieve
});

Having the ol as the #container:
<ol id="container">

Here's a working example and there's the relevant documentation.
EDIT
It seems that to use the local behaviour, you need to override a method responsible for determining if the scroll is near the bottom (although this doesn't seem to appear anywhere in the documentation). There is a file in the repository  /behaviors/local.js that would need to be included to make this work, but I tried it and is doesn't seem to work properly. So instead you can use this code to take care of the those computations:
jQuery.extend(jQuery.infinitescroll.prototype, {
   _nearbottom_local: function infscr_nearbottom_local()
   {
       var opts   = this.options;
       var binder = $(opts.binder);

       return (binder.scrollTop() + binder.innerHeight() >= binder[0].scrollHeight - opts.bufferPx);
   }
});


text:
Q: failed to extract data from json with jq command I've this json.
I want to extract test fields which their values equal to true.
I tried with jq and got that error, pls any fix ?
$- jq '.[].name | select(.[].test == "true")' ddd

jq: error (at ddd:12): Cannot iterate over string ("AA")

[
{
"name": "AA",
"program_url": "https://www.google.com",
"test": false
},
{
"name": "BB",
"program_url": "https://yahoo.com",
"test": true
}
]

A: Are you looking for this? It iterates over the array .[], selects those item objects whose .test field evaluates to true (implicit), and traverses further down to the .name field. Using the --raw-output (or -r) option renders the output raw text (instead of JSON string in this case).
jq -r '.[] | select(.test).name' ddd

BB

Demo


text:
Q: How to migrate state passed in React-Router to Redux Store? So far, I have been using React with React-Router and when passing data between URLs, I have been passing the state as
this.props.history.push(Routes.transactionEdit, this.state.transaction);

This is documented here
and in the Component, I would use it as
constructor(props) {
    super(props);
    this.state = {
        userId: props.history.location.state.userId,
        transactionId: props.history.location.state.id,
        createdAt: props.history.location.state.createdAt,
        name: props.history.location.state.name,
        amount: props.history.location.state.amount,
    }
}

However, I learned that managing state in Redux is a better idea and it helps test the store separately from how the views look. and I liked that idea because I care about the clean-testable code.
I started refactoring code and for many parts where I need data from the database, I was able to migrate the code using thunk pattern. However, with this use case where the state is sent as part of history.push, I don't know how to put this state into the Redux Store.
Question
How do I migrate the state in this.props.history.push(Routes.transactionEdit, this.state.transaction); (during push) to the Redux store, so that it can be managed outside of React Component?
Thanks

A: You'll need to setup a specific action that is specifically meant for taking a component's state and pushes it to Redux's store. Of course you'll need to have your reducer respond appropriately to that action.
If youre new to Redux, this might be opening a big can of worms.


text:
Q: CORS error on XHR request but only on android (iOS works fine...) I have an android/iOS app made with Capacitor that serve a html file that make XHR request to my server.
It works fine on iOS emulator/device, but not on android emulator. I get the following error
File: http://example.com/ - Line 0 - Msg: Access to XMLHttpRequest at 'https://example.com/api/users/me?_=1644242401129' from origin 'http://example.com' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I do have an Access-Control-Allow-Origin set. Proof is that it works on iOS with the following origin allowed :
capacitor://example.com
But on android, it looks like the origin used is http://example.com as the errors says.
I did allow this url on my headers 'Access-Control-Allow-Origin' but it still fail and get me the same error.

    $allowed_domains = [
        'https://example.com',
        'http://example.com',
        'capacitor://example.com', //iOS working fine
    ];

    if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {

        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
        header('Access-Control-Allow-Credentials: true');
    }

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

       header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
       header('Access-Control-Allow-Headers: origin, content-type, accept, API');
       header('content-type: application/json; charset=utf-8');
       http_response_code(200);
       exit;
    }

A: Solved it by removing the following entry in capacitor.config.json
  "server": {
    "hostname": "example.com"
  },

This changed my origin to http://localhost for android and to capacitor://localhost for iOS.
Allowed both origins on my server and now it works on android but not on iOS.
Cookies are not sent with my XHR requests anymore on iOS (working fine on android).
So i guess the solution is to build on iOS with the server hostname, and build on android without it. Great..


text:
Q: Iterating laravel form that update rows in column based off value of adjoining column I have a SQlite database with 50 states and I want to create an input for each of the 50 states. The input would update the individual states' "totals" in the database with the number input in it's text field. I have created a form which is about 110 lines long, but I am certain I could do this via iteration in blade templating. I just don't know how to make the form fields correspond to one particular state in the array of states.
The DB has an Eloquent model named Distributors and looks as follows:
ID   |  State  | Total
1    |  PA     |  0

I am pretty sure I could make this thing work if I created separate input values for all fields and used the
DB::table('distributors')->where('state', '==', 'PA')
->update(array('total' => 'Input::get('total')'));

But there has to be an easier, more automated way... any direction would be appreciated.

A: Pass all states into your view:
$states = DB::table('distributors')->lists('state');

return view('whatev', compact('states'));

Then iterate over them in your view:
@foreach ($states as $state)

        Total for {{ $state }}:
        <input type="text" id="{{ $state }}" name="totals[{{ $state }}]">

@endforeach

Then loop over them to save them:
foreach (Input::get('states') as $state => $total) {
    DB::table('distributors')->where('state', $state)->update(compact('total'));
}


text:
Q: Core Data (After Adding Unique Constraint) : annotation: repairing missing delete propagation for to-many relationship
This issue started occurring after we added Unique key i.es Constraint.

Frequently updating Meeting managed object deletes the event managed object which has a to-one inverse relationship from meeting managed object.

Error CoreData: annotation: repairing missing delete propagation for to-many relationship meetingList on object 0x60c00009c4d0 (0x60c000621e40 ) with bad fault 0x60800009ac20 (0x60800023a360 )

Data Model
I have three entities in my core data model i.es
(CDEvent, CDMeeting, CDMLCheckin) .

Entity Properties and Relationship as described below:
Relationship

Properties:
CDEvent

CDMeeting

CDMLCheckin

Unique Constraint:

*

*CDEvent entity has eventUUID as unique constraint.

*CDMeeting entity has meetingUUID as unique constraint.

Relationship

*

*CDEvent <->>CDMeeting

*

*From CDEvent to CDMeeting is to-many relationship with delete rule cascade, inverse relationship from CDMeeting to CDEvent is to-one with delete rule nullify.

*CDEvent <->>CDMLCheckin

*

*From CDEvent to CDMLCheckin is to-many relationship with delete rule cascade, inverse relationship from CDMLCheckin to CDEvent is to-one with delete rule nullify.

Full Description : https://docs.google.com/document/d/1y2DQhBBLqjAP9eWbx5YpQhH7oVigxT_mcJDnPLlOMtQ/edit?usp=sharing
Note

*

*If i remove Unique Constraint eventUUID from CDEvent everything works fine.

Please help us here as we are struck from more than a week :(

A: I hope I can help, having a unique constraint with To-Many Relationship Entities you need to keep some points in mind

*

*Use Inverse Relationship of every CoreData relation

*Unique Constrains Attributes should never be Optional

When you create NSManagedObjectContext make sure you set MergePolicy.
[_context setMergePolicy: mergePolicy];

*

*NSMergeByPropertyStoreTrumpMergePolicy

*NSMergeByPropertyObjectTrumpMergePolicy

*NSOverwriteMergePolicy
Also could you try changing the nullify delete rule to no action ?


text:
Q: Dynamic Panel Data Model With Mulitway Fixed Effects I am considering the following model: $$y_{it}=\rho y_{it-1}+\beta x_{it}+\delta_i+\delta_{rt}+\epsilon_{it}.\tag{1}$$ Here $y$ is an outcome variable, $x$ our variable of interest, $\delta_i$ denotes subregion fixed effects and $\delta_{rt}$ region $\times$ year fixed effects. (For example, $i$ denotes a grid cell in country $r$: see http://grid.prio.org/). Models such as the one above are suggested in [1] at p. 745.
My question is simple, but there seems to be no answer to it: How do I acquire a consistent estimate of $\beta$ in the model above (for serially uncorrelated or correlated error terms), theoretically and practically?
The usual approach is to apply the difference operator $\Delta$, giving us the model $$\Delta y_{it}=\rho\Delta y_{it-1}+\beta\Delta x_{it}+\eta_{rt}+\Delta\epsilon_{it},\tag{2}$$ where $\eta_{rt}\equiv\Delta\delta_{rt}$. Notice that $\delta_i$ vanishes. The problem with the original model is that $\epsilon_{rt}$ is correlated with $y_{rt}$, and thus strict exogeneity does not hold and pooled OLS would give us biased estimates. In this new, differenced model, $\Delta\epsilon_{it}$ is however correlated with $\Delta y_{it-1}$. To solve this one usually instruments $\Delta y_{it-1}$ with $y_{it-2}$, which is uncorrelated with $\Delta\epsilon_{it}$ assuming no serial correlation in the error term; this leads to the Anderson-Hsiao estimator. Another approach is to use the Arrelano-Bond estimator. $\eta_{rt}$ can be modelled as a linear combination of dummies.
Is this the correct way to theoretically estimate $\beta$? Or do I also need to instrument $x_{it}$ or $\eta_{rt}$ to acquire a consistent estimate of $\beta$? I have seen no formal treatment of the case with multiway fixed effects, $\delta_{rt}$. Also, there seems to be no command in Stata allowing me to account for a large set of dummies (I tried to include a dummy for each $(r,t)$, but I have 55 countries over 14 years, resulting in $770-55$ dummies). I have tried to use the $\texttt{xtdpdsys}$ command in Stata, but it cannot account for $\eta_{rt}$ from what I can see, and $\texttt{reghdfe}$ using $y_{it-2}$ as an instrument (see above), but it gives me a negative $R^2$, suggesting a very bad fit and that my idea to absorb region $\times$ year fixed effects does not work.
Idea
One thought I had was to use the ideas in [2]. There may be a varying number of subregions in each region, but we may average as follows: Let $\Delta \bar{y}_{\cdot rt}=\frac{1}{N_r}\sum_{i\text{ in region }r}\Delta y_{irt}$, where $N_r$ is the number of subregions in region $r$. This is done for all variables in (2). Subtracting $\Delta \bar{y}_{\cdot rt}$ from both sides of (2) then gives us $$(\Delta y_{it}-\Delta \bar{y}_{\cdot rt})=\rho(\Delta y_{it}-\Delta \bar{y}_{\cdot rt})+\beta(\Delta x_{it}-\Delta \bar{x}_{\cdot rt})+(\Delta \epsilon_{it}-\Delta \bar{\epsilon}_{\cdot rt}).$$ I do not know if the arguments in [2] can be directly transferred to this case, as I have different number of subregions $i$ in different regions $r$.
Notes
Suggested pseudo-Stata code using the Arellano-Bond estimator with xtdpdsys:
xtdpdsys y x rtdummies*, nocons lag(1)

Suggested pseudo-Stata code using the Anderson-Hsiao estimator with reghdfe:
reghdfe diff(y) x (diff(lag(y)) = lag(lag(y))), absorb(rt)

References
1 Dell, M., Jones, B. F., & Olken, B. A. (2014). What do we learn from the weather? The new climate–economy literature. Journal of Economic Literature, 52(3), 740-798.
2 Balazsi, L., Matyas, L., & Wansbeek, T. (2015). The estimation of multidimensional fixed effects panel data models. Econometric Reviews, 1-23.


text:
Q: page would render without any css file I'm having an issue with an EJS file not rendering as expected. I'm using ExpressJS. When the user put a name of a product at add-product end point i redirect him to the home page, the page would render without any css file like this :
home page before the css file
after reload the page i get the desired template:
the desired page
Product Names are in json file, so i used the fs.promises modules
My Controllers are :
const Product = require('../models/product')
exports.getAddProducts=(req,res,next)=>{
    res.render('add-product',{pageTitle: 'Add Product', path:'/admin/add-product'});
}
exports.postAddProducts=(req,res,next)=>{
    const product = new Product(req.body.title);
     product.save();
    res.redirect('/');
}
exports.getProducts=async (req,res,next)=>{
    let products=[];
    try {
        products = await Product.fetchAll();
    } catch (error) {
        console.log(error)
    }
    res.render('shop',{products ,path:'/' ,pageTitle:'Shop'})
}

the my Modules is
module.exports = class Product{
    constructor(title){
        this.title=title;
    }
    async save(){
        const p = path.join(rootDir,'data','products.json')
        try {
            const fileContent = await fs.readFile(p)
            let products = JSON.parse(Buffer.from(fileContent).toString())
                products.push(this)
                await fs.writeFile(p,JSON.stringify(products))
        } catch (error) {
            console.log(error);
            return [];
        }
    }
    static async fetchAll(){
        const p = path.join(rootDir,'data','products.json')
        try {
            const fileContent = await fs.readFile(p)
            return JSON.parse(Buffer.from(fileContent).toString())
        } catch (error) {
            console.log(error)
            return []
        }
    }
}

and my main app go like this
app.set('view engine','ejs');
app.set('views','views')

app.use(express.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname,'public')))
// app.use(express.static('public'))

app.use('/admin',adminRoutes);
app.use(shopRoutes)
//app.use(userRoutes);

//handle 404 page
app.use('/',errorController.get404)

app.listen(3000,()=>{console.log('server up to date: ')
})


text:
Q: java,how to consult sql lite if a value of a variable "varConsult" is in column "protocolo" in table "pessoajuridica", i tryed this:
ResultSet existetabela = stm.executeQuery ("SELECT * FROM pessoajuridica WHERE protocolo ="  + varConsult );
System.out.println(existetabela);

but it only return a strange String -> org.sqlite.RS@1f959518
i was expecting the value..
remembering, sql lite and java :S
i want to use the value that it return to compare, if it return any value, means that it exist, so it will not add to the sql, if dont return anything = can add!!!
("if exist" doesnt work for me, says that its a invalid argument in the sql command line --')

A: You can use ResultSet#next() method to test whether there was any result set returned:
if (existetabela.next()) {
    // Result was fetched
    // Assuming type of protocol is String (Can be anything)
    String protocol = existetabela.getString("protocolo");

} else {
    // No result
}

Now, let's move ahead to the major issue. You should use PreparedStatement, to save yourself from SQL Injection.

A: You need to iterate inside the result set to retrive the actual data that were found:
while (existetabela.next()){
 System.out.println(existetabela.getObject("protocolo"));
}

Did you look at PreparedStatement ?


text:
Q: How can i install MonoGame into Visual Studio 2013? How can I install MonoGame templates for Visual Studio 2013?

A: The Paul McCowat's answer is correct.
Also, if you doesn't have visual studio 2012 in your machine, just create the folders hierarchy as he said. (C:\Users[your user name]\Documents\Visual Studio 2012\Templates\ProjectTemplates\Visual C#)
Then the Monogame installer can find the folder to copy the templates.
Update:
I don't have visual studio 2012 installed in my machine, so I had some problems to resolve in this way.
I edited some files on every template I wanted to use, searching for references of DLLs of visual studio 2012, then i changed the versions of these DLLs from 11 to 12.
Now it works!

A: Assuming you want C# templates:

*

*Install MonoGame from here

*Find the Visual Studio templates folder (usually C:\Users[your user name]\Documents\Visual Studio 2012\Templates\ProjectTemplates\Visual C#)

*Copy the MonoGame folder to the Visual Studio 2013\Templates\ProjectTemplates\Visual C# folder.

A: UPDATED 7 January 2014
For people who want to use Monogame can download the 3.2 which provide the support for 2013.
The installer are available  at http://build.monogame.net/job/develop-win/lastSuccessfulBuild/artifact/Installers/Windows/
If you try this way you don't need to do any kind of copy-paste for project templates.
UPDATED 9 January 14
3.2 build have some trouble now. Check the very common issue here http://monogame.codeplex.com/discussions/467277

A: You can find a tutorial on this website. It is a github repository of the MonoGame project so the link should work as long as the framework is being developed.
You can also check out this 4-part tutorial on youtube.

http://www.youtube.com/watch?v=FYCWl2jU0zI
http://www.youtube.com/watch?v=ZedtwoL9_M0
http://www.youtube.com/watch?v=TR_JWVI2lEk
http://www.youtube.com/watch?v=7h5uHUck79A

A: Now Mono 3.4 can be downloaded for Visual Studio directly and the installer automatically installs the templates into Visual Studio. Installers are available here.


text:
Q: Create and reference a string literal via LLVM C interface I'm trying to create a string literal via LLVM C API, and get a C style pointer to its first member. LLVMBuildGlobalStringPtr does the trick nicely, but I can't use it because my source string might contain nulls.
I cannot seem to find documentation on how to create an initialized, unnamed, constant global string.
I've tried using LLVMConstString to create the string and LLVMConstIntToPtr to get its address (and, then, GetElementPointer to convert to i8*). I can get LLVM to compile it, but the resulting object file does not contain the string, and the code returns a pointer that seems random.

A: I've found the answer. The following code segment seems to do the trick:
LLVMValueRef defineStringLiteral( const char *sourceString, size_t size ) {
    LLVMTypeRef strType = LLVMArrayType( LLVMInt8Type(), size );
    LLVMValueRef str = LLVMAddGlobal(module->getLLVMModule(), strType, "");
    LLVMSetInitializer(str, LLVMConstString( sourceString, size, true ));
    LLVMSetGlobalConstant(str, true);
    LLVMSetLinkage(str, LLVMPrivateLinkage);
    LLVMSetUnnamedAddress(str, LLVMGlobalUnnamedAddr);
    LLVMSetAlignment(str, 1);

    LLVMValueRef zeroIndex = LLVMConstInt( LLVMInt64Type(), 0, true );
    LLVMValueRef indexes[2] = { zeroIndex, zeroIndex };

    LLVMValueRef gep = LLVMBuildInBoundsGEP2(builder, strType, str, indexes, 2, "");

    return gep;
}


text:
Q: Loop through multiple dataframes in python Python novice here and I am looking for a concise way to write my program. I want to read multiple csv files and clean them for outliers and after that I want to normalize the columns and then create a combined dataset from the normalized columns. The input csv file has many columns and I want to normalize all the columns. Here in the code I have written an example for 2 columns.
the code i wrote works fine, but its tedious and cumbersome. I have it written for 3 datasets. In reality I could be looking at a lot more. Any help on how to loop this and make it look concise?  Thanks
    import numpy as np
    import pandas as pd
    gr_P10 = 40
    gr_P50 = 65
    gr_P90 = 90
    rt_P10 = 10
    rt_P50 = 25
    rt_P90 = 50

    def get_quantiles(input_log):
      p10_log = np.percentile(input_log, 10)
      p50_log = np.percentile(input_log, 50)
      p90_log = np.percentile(input_log, 90)
    return p10_log, p50_log, p90_log

    def normalize(input_log, x_90, x_50, x_10, p90_log, p50_log, p10_log):
      mmin = (x_50-x_10)/(p50_log-p10_log)
      mmax = (x_90-x_50)/(p90_log-p50_log)
      if (input_log < p50_log ):
        output_log = x_50 +(mmin*(input_log-p50_log))
      else:
        output_log = x_50 +(mmax*(input_log-p50_log))
    return output_log

# Read data and removing outliers
#Data1
a = pd.read_csv('Data1.csv')
zscore = np.abs(stats.zscore(a))
a = a[(zscore < 3).all(axis=1)]
#Data2
b = pd.read_csv('Data2.csv')
zscore = np.abs(stats.zscore(b))
b = b[(zscore < 3).all(axis=1)]
#Data3
c = pd.read_csv('Data3.csv')
zscore = np.abs(stats.zscore(c))
c = c[(zscore < 3).all(axis=1)]
# Normalizing Data
# Normalizing Data1
p10_log, p50_log, p90_log = get_quantiles(a['GR'])
a['GR_NORM'] = a.apply(lambda x: normalize(x['GR'],gr_P90, gr_P50, gr_P10, p90_log, p50_log, p10_log ), axis =1)

p10_log, p50_log, p90_log = get_quantiles(a['RT'])
a['RT_NORM'] = a.apply(lambda x: normalize(x['RT'],rt_P90, rt_P50, rt_P10, p90_log, p50_log, p10_log ), axis =1)
# Normalizing Data2
p10_log, p50_log, p90_log = get_quantiles(b['GR'])
b['GR_NORM'] = b.apply(lambda x: normalize(x['GR'],gr_P90, gr_P50, gr_P10, p90_log, p50_log, p10_log ), axis =1)

p10_log, p50_log, p90_log = get_quantiles(b['RT'])
b['RT_NORM'] = b.apply(lambda x: normalize(x['RT'],rt_P90, rt_P50, rt_P10, p90_log, p50_log, p10_log ), axis =1)
# Normalizing Data3
p10_log, p50_log, p90_log = get_quantiles(c['GR'])
c['GR_NORM'] = c.apply(lambda x: normalize(x['GR'],gr_P90, gr_P50, gr_P10, p90_log, p50_log, p10_log ), axis =1)

p10_log, p50_log, p90_log = get_quantiles(c['RT'])
c['RT_NORM'] = c.apply(lambda x: normalize(x['RT'],rt_P90, rt_P50, rt_P10, p90_log, p50_log, p10_log ), axis =1)
# Forming new combined dataset with normalized values
new_a = a['GR_NORM','RT_NORM'].copy()
new_b = b['GR_NORM','RT_NORM'].copy()
new_c = c['GR_NORM','RT_NORM'].copy()
new_dataset = pd.concat([new_a,new_b, new_c], ignore_index= True)

A: You just need to use functions more to get rid of duplicate code. Try replacing the second half with something like this:
# Read data and removing outliers
#Data1

def read_data(data):
    a = pd.read_csv(data)
    zscore = np.abs(stats.zscore(a))
    a = a[(zscore < 3).all(axis=1)]

    #Normalizing Data
    p10_log, p50_log, p90_log = get_quantiles(a['GR'])
    a['GR_NORM'] = a.apply(lambda x: normalize(x['GR'],gr_P90, gr_P50, gr_P10, p90_log, p50_log, p10_log ), axis =1)

    p10_log, p50_log, p90_log = get_quantiles(a['RT'])
    a['RT_NORM'] = a.apply(lambda x: normalize(x['RT'],rt_P90, rt_P50, rt_P10, p90_log, p50_log, p10_log ), axis =1)

    return a['GR_NORM','RT_NORM'].copy()

data = ['Data1.csv','Data2.csv','Data3.csv']

new_dataset = pd.DataFrame()

for x in data:
    new_dataset = new_dataset.append(read_data(x))

A: Unless I'm overlooking something, you can just write a function for that.

A: N_files = 3
for i in range(1, N_files):
    a = pd.read_csv(f"Data{i}.csv")  #this will loop through open all your files


text: Q: Evaluation box in home page magento 2 I want to create a box for customer to évaluate my store. The evaluation must be in the form of stars. If a guest is loged in so the évaluation is directly saved else the clic on the registratoion of the évaluation will redirect him to the login/register page. I searched on the net but did'nt find any information can you please help me find a solution thanks in advance :)


text:
Q: how I setup view matrix? how I setup view matrix so that it works similer to 3ds max. in max if there a object which points to the left and you run over it, it will points to the left, even if you are looking at it from the other side. I want this for my 3d editor. thanks in advance.

A: You have to extract upward & side vectors from your camera and use them to align an object to a camera's view plane. This way your object will always be faced to the camera.


text:
Q: SUM CASE adding from joined table instead main table I have a query that retrieves from a customer:

*

*sum of time expent on his tickets (every ticket can have 1 or more interventions)

*average resolution time

*category of each ticket

The query:
SELECT SUM(f.duree) as total_time, SUM(timestampdiff(second, t.datec, t.date_close))/COUNT(distinct t.rowid) as average_resolution, COUNT(distinct t.rowid) as tickets,
                SUM( CASE t.category_code WHEN 'WITHOUT_MAINTENANCE' THEN 1 ELSE 0 END) as sin_mantenimiento,
                SUM( CASE t.category_code WHEN 'WITH_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento,
                SUM( CASE t.category_code WHEN 'WITH_BILLABLE_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento_facturable,
                SUM( CASE t.category_code WHEN 'NO_BILLABLE_COASER_WARRANTY' THEN 1 ELSE 0 END) as no_facturable_garantia_coaser,
                SUM( CASE t.category_code WHEN 'OFERTADO' THEN 1 ELSE 0 END) as ofertado
                FROM llx_ticketsup as t
                JOIN llx_element_element as ee on ee.fk_source = t.rowid
                JOIN llx_fichinter as f on f.rowid = ee.fk_target
                WHERE t.fk_soc = 47 AND t.fk_statut = 8

where

*

*llx_ticketsup is main tickets table

*llx_fichinter is table where interventions from tickets are stored

*llx_element_element is table between tickets and interventions

My problem is, if one ticket has more than 1 intervention, on sum of category types to know how many are from this category and how many from the other, it sums interventions instead tickets. For example, if query returns 2 tickets and they have a total of 6 interventions, it returns 6 tickets of category WITHOUT_MAINTENANCE, instead 2 tickets of category WITHOUT_MAINTENANCE.
Whats wrong? Thanks.

A: Nothings 'wrong' that's expected behaviour try using a sub query to get the duration. Something like
SELECT (select sum(f.duree) from llx_fichinter as f on f.rowid = ee.fk_target) as total_time, SUM(timestampdiff(second, t.datec, t.date_close))/COUNT(distinct t.rowid) as average_resolution, COUNT(distinct t.rowid) as tickets,
                SUM( CASE t.category_code WHEN 'WITHOUT_MAINTENANCE' THEN 1 ELSE 0 END) as sin_mantenimiento,
                SUM( CASE t.category_code WHEN 'WITH_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento,
                SUM( CASE t.category_code WHEN 'WITH_BILLABLE_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento_facturable,
                SUM( CASE t.category_code WHEN 'NO_BILLABLE_COASER_WARRANTY' THEN 1 ELSE 0 END) as no_facturable_garantia_coaser,
                SUM( CASE t.category_code WHEN 'OFERTADO' THEN 1 ELSE 0 END) as ofertado
                FROM llx_ticketsup as t
                JOIN llx_element_element as ee on ee.fk_source = t.rowid

                WHERE t.fk_soc = 47 AND t.fk_statut = 8

If that doesn't work add sample data and expected result to the question as text so we can play with it.


text:
Q: Regex: how to get rid of \n in a string? when I run the script:
import re

s = '\n Surface de la terrasse\n \n 32\n\n \n \n m²\n \n \n mètres carrés\n \n \n \n'

print(s.split())

['Surface', 'de', 'la', 'terrasse', '32', 'm²', 'mètres', 'carrés']

How do I get a list in the following format instead?
['Surface de la terrasse','32','m²','mètres carrés']

A: First split on newlines, then strip all whitespace from beginning and end, then remove empty strings:
>>> print([line.strip() for line in s.split('\n') if line.strip()])
['Surface de la terrasse', '32', 'm²', 'mètres carrés']

A: print(list(filter(None, map(str.strip, s.split("\n")))))

Output:
['Surface de la terrasse', '32', 'm²', 'mètres carrés']
>>>


text:
Q: Maven build success with several warnings while downloading dependency from remote repository BitBucket I would like to can download a dependency present on BitBucket remote repository from an another project Maven. To reply the case I've created a remote repository like this: https://bitbucket.org/[user]/mvn-repo
Then, I've created two projects Maven: test and test2 (The project test has only a static method of testing).
Here's test project's POM:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>internal repository</id>
            <url>https://bitbucket.org/[user]/mvn-repo/raw/master/</url>
        </repository>
        <repository>
            <id>Maven Central</id>
            <url>http://repo.apache.maven.org/maven2/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

while here's test2 project's POM:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.test</groupId>
    <artifactId>test2</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.test</groupId>
            <artifactId>test</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>internal repository</id>
            <url>https://bitbucket.org/[user]/mvn-repo/raw/master/</url>
        </repository>
        <repository>
            <id>Maven Central</id>
            <url>http://repo.apache.maven.org/maven2/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

I've taken the following steps:

*

*Installed the project test on the local repository Maven with
command: mvn clean install -DcreateChecksum=true

*Copied the project test (as such as org/test/test) from local repository Maven to the folder /git-repo/mvn-repo, then I've pushed on BitBucket remote repository.

*Removed folders org/test/test from local repository Maven.

*Executed command: mvn clean install -DcreateChecksum=true under the project folder test2.

This is the result
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------------< org.test:test2 >---------------------------
[INFO] Building test2 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
Downloading from internal repository: https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml
Progress (1): 1.1 kB
Progress (1): 1.5 kB

[WARNING] Checksum validation failed, expected <html> but is 76a18682367c7eaeca8fb5d2bb5006d22d76280b from internal repository for https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml
Progress (1): 1.1 kB
Progress (1): 1.5 kB
[WARNING] Could not validate integrity of download from https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml: Checksum validation failed, expected <html> but is 3b29c9ec739d87fb529567cc27e22b3d7d5c4feb

[WARNING] Checksum validation failed, expected <html> but is 3b29c9ec739d87fb529567cc27e22b3d7d5c4feb from internal repository for https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml
Downloaded from internal repository: https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml (1.5 kB at 248 B/s)
[WARNING] The metadata C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\maven-metadata-internal repository.xml is invalid: unexpected character in markup   (position: START_TAG seen ...t>\nvar elements = document.forms[0].elements;\nfor (var i = 0; i < ... @10:21)
[WARNING] The metadata C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\maven-metadata-internal repository.xml is invalid: unexpected character in markup   (position: START_TAG seen ...t>\nvar elements = document.forms[0].elements;\nfor (var i = 0; i < ... @10:21)
Downloading from internal repository: https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.pom
Progress (1): 1.1 kB
Progress (1): 1.5 kB

[WARNING] Checksum validation failed, expected <html> but is bcb4b6aa3538fce8d8a804e9727bb7866e65681d from internal repository for https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.pom
Progress (1): 1.1 kB
Progress (1): 1.5 kB
[WARNING] Could not validate integrity of download from https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.pom: Checksum validation failed, expected <html> but is 3546a61a9b568724edfc34f29b202cbafa0e8769

[WARNING] Checksum validation failed, expected <html> but is 3546a61a9b568724edfc34f29b202cbafa0e8769 from internal repository for https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.pom
Downloaded from internal repository: https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.pom (1.5 kB at 282 B/s)
[WARNING] The POM for org.test:test:jar:0.0.1-SNAPSHOT is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
Downloading from internal repository: https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.jar
Progress (1): 1.1 kB
Progress (1): 1.5 kB

[WARNING] Checksum validation failed, expected <html> but is c30cfc686fdc8a1aedb311222b4af1b3b5780e9e from internal repository for https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.jar
Progress (1): 1.1 kB
Progress (1): 1.5 kB
[WARNING] Could not validate integrity of download from https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.jar: Checksum validation failed, expected <html> but is c0a924f008f5bc6fe27dfc0344e9f18f34e09efb

[WARNING] Checksum validation failed, expected <html> but is c0a924f008f5bc6fe27dfc0344e9f18f34e09efb from internal repository for https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.jar
Downloaded from internal repository: https://bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/test-0.0.1-SNAPSHOT.jar (1.5 kB at 300 B/s)
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ test2 ---
[INFO] Deleting C:\Users\[user]\eclipse-workspace-oxygen\test2\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ test2 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ test2 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\Users\[user]\eclipse-workspace-oxygen\test2\target\classes
[WARNING] error reading C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\test-0.0.1-SNAPSHOT.jar; error in opening zip file
[WARNING] error reading C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\test-0.0.1-SNAPSHOT.jar; error in opening zip file
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ test2 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ test2 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ test2 ---
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ test2 ---
[INFO] Building jar: C:\Users\[user]\eclipse-workspace-oxygen\test2\target\test2-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ test2 ---
[INFO] Installing C:\Users\[user]\eclipse-workspace-oxygen\test2\target\test2-0.0.1-SNAPSHOT.jar to C:\Users\[user]\.m2\repository\org\test\test2\0.0.1-SNAPSHOT\test2-0.0.1-SNAPSHOT.jar
[INFO] Installing C:\Users\[user]\eclipse-workspace-oxygen\test2\pom.xml to C:\Users\[user]\.m2\repository\org\test\test2\0.0.1-SNAPSHOT\test2-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 19.060 s
[INFO] Finished at: 2018-09-14T20:38:42+02:00
[INFO] ------------------------------------------------------------------------

Maven build shows several warnings even if it returns a build success. The file test-0.0.1-SNAPSHOT.jar result be corrupted. How can I resolve the problem?
Thanks for your help in advance.
UPDATE
I've changed the test project's POM for attempting to execute the command mvn deploy -X, however Maven returns the same result:
Downloading from internal repository: https://my_user@bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml
[WARNING] Checksum validation failed, expected <html> but is d409bb497c4f4faa046afbad1028304f2fc3fcf2 from internal repository for https://my_user@bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml
[WARNING] Could not validate integrity of download from https://my_user@bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml
org.eclipse.aether.transfer.ChecksumFailureException: Checksum validation failed, expected <html> but is fe062c89ef7cbebdf7ed304fd17eab147d9b7c5a
    at org.eclipse.aether.connector.basic.ChecksumValidator.validateExternalChecksums (ChecksumValidator.java:174)
    at org.eclipse.aether.connector.basic.ChecksumValidator.validate (ChecksumValidator.java:103)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$GetTaskRunner.runTask (BasicRepositoryConnector.java:456)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run (BasicRepositoryConnector.java:360)
    at org.eclipse.aether.util.concurrency.RunnableErrorForwarder$1.run (RunnableErrorForwarder.java:75)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$DirectExecutor.execute (BasicRepositoryConnector.java:583)

[WARNING] Checksum validation failed, expected <html> but is fe062c89ef7cbebdf7ed304fd17eab147d9b7c5a from internal repository for https://my_user@bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml
Downloaded from internal repository: https://my_user@bitbucket.org/[user]/mvn-repo/raw/master/org/test/test/0.0.1-SNAPSHOT/maven-metadata.xml (1.5 kB at 248 B/s)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.473 s
[INFO] Finished at: 2018-09-22T20:37:00+02:00
[INFO] ------------------------------------------------------------------------

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project test: Failed to update metadata org.test:test:0.0.1-SNAPSHOT/maven-metadata.xml: Could not parse metadata C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\maven-metadata-internal repository.xml: unexpected character in markup   (position: START_TAG seen ...t>\nvar elements = document.forms[0].elements;\nfor (var i = 0; i < ... @10:21)  -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project test: Failed to update metadata org.test:test:0.0.1-SNAPSHOT/maven-metadata.xml: Could not parse metadata C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\maven-metadata-internal repository.xml: unexpected character in markup   (position: START_TAG seen ...t>\nvar elements = document.forms[0].elements;\nfor (var i = 0; i < ... @10:21)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)

Caused by: org.apache.maven.plugin.MojoExecutionException: Failed to update metadata org.test:test:0.0.1-SNAPSHOT/maven-metadata.xml: Could not parse metadata C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\maven-metadata-internal repository.xml: unexpected character in markup   (position: START_TAG seen ...t>\nvar elements = document.forms[0].elements;\nfor (var i = 0; i < ... @10:21)
    at org.apache.maven.plugin.deploy.DeployMojo.execute (DeployMojo.java:193)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)

Caused by: org.apache.maven.artifact.deployer.ArtifactDeploymentException: Failed to update metadata org.test:test:0.0.1-SNAPSHOT/maven-metadata.xml: Could not parse metadata C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\maven-metadata-internal repository.xml: unexpected character in markup   (position: START_TAG seen ...t>\nvar elements = document.forms[0].elements;\nfor (var i = 0; i < ... @10:21)
    at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy (DefaultArtifactDeployer.java:146)
    at org.apache.maven.plugin.deploy.AbstractDeployMojo.deploy (AbstractDeployMojo.java:167)
    at org.apache.maven.plugin.deploy.DeployMojo.execute (DeployMojo.java:157)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)

Caused by: org.eclipse.aether.deployment.DeploymentException: Failed to update metadata org.test:test:0.0.1-SNAPSHOT/maven-metadata.xml: Could not parse metadata C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\maven-metadata-internal repository.xml: unexpected character in markup   (position: START_TAG seen ...t>\nvar elements = document.forms[0].elements;\nfor (var i = 0; i < ... @10:21)
    at org.eclipse.aether.internal.impl.DefaultDeployer.upload (DefaultDeployer.java:436)
    at org.eclipse.aether.internal.impl.DefaultDeployer.deploy (DefaultDeployer.java:268)
    at org.eclipse.aether.internal.impl.DefaultDeployer.deploy (DefaultDeployer.java:223)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.deploy (DefaultRepositorySystem.java:384)
    at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy (DefaultArtifactDeployer.java:142)
    at org.apache.maven.plugin.deploy.AbstractDeployMojo.deploy (AbstractDeployMojo.java:167)
    at org.apache.maven.plugin.deploy.DeployMojo.execute (DeployMojo.java:157)

Caused by: org.eclipse.aether.RepositoryException: Could not parse metadata C:\Users\[user]\.m2\repository\org\test\test\0.0.1-SNAPSHOT\maven-metadata-internal repository.xml: unexpected character in markup   (position: START_TAG seen ...t>\nvar elements = document.forms[0].elements;\nfor (var i = 0; i < ... @10:21)
    at org.apache.maven.repository.internal.MavenMetadata.read (MavenMetadata.java:108)
    at org.apache.maven.repository.internal.MavenMetadata.merge (MavenMetadata.java:74)
    at org.eclipse.aether.internal.impl.DefaultDeployer.upload (DefaultDeployer.java:432)
    at org.eclipse.aether.internal.impl.DefaultDeployer.deploy (DefaultDeployer.java:268)
    at org.eclipse.aether.internal.impl.DefaultDeployer.deploy (DefaultDeployer.java:223)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.deploy (DefaultRepositorySystem.java:384)
    at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy (DefaultArtifactDeployer.java:142)
    at org.apache.maven.plugin.deploy.AbstractDeployMojo.deploy (AbstractDeployMojo.java:167)

Caused by: org.codehaus.plexus.util.xml.pull.XmlPullParserException: unexpected character in markup   (position: START_TAG seen ...t>\nvar elements = document.forms[0].elements;\nfor (var i = 0; i < ... @10:21)
    at org.codehaus.plexus.util.xml.pull.MXParser.nextImpl (MXParser.java:1523)
    at org.codehaus.plexus.util.xml.pull.MXParser.next (MXParser.java:1317)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.checkUnknownElement (MetadataXpp3Reader.java:145)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.parseMetadata (MetadataXpp3Reader.java:676)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.read (MetadataXpp3Reader.java:954)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.read (MetadataXpp3Reader.java:557)
    at org.apache.maven.repository.internal.MavenMetadata.read (MavenMetadata.java:100)
    at org.apache.maven.repository.internal.MavenMetadata.merge (MavenMetadata.java:74)
    at org.eclipse.aether.internal.impl.DefaultDeployer.upload (DefaultDeployer.java:432)
    at org.eclipse.aether.internal.impl.DefaultDeployer.deploy (DefaultDeployer.java:268)

[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

A: try this on your pom:
<properties>
    <bitBucketUser>${user}</bitBucketUser>
</properties>

<repositories>
    <repository>
        <id>internal repository</id>
        <url>https://bitbucket.org/${bitBucketUser}/mvn-repo/raw/master/</url>
    </repository>
    <repository>
        <id>Maven Central</id>
        <url>http://repo.apache.maven.org/maven2/</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

and then execute your clean install mvn clean install -Duser=yourBitBucketUser


text:
Q: Rotating and translating a 2D image with OpenGL fixed function My code draws a texture on a 2D quad which should be translated, rotated and scaled:
double width = ... //window width
double height = ... //window height
double imagewidth = ...
double imageheight = ...
vec2 usertranslation = ... //additional translation in x,y direction from user input
double rot_angle = ... //rotation angle from user input

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, 0.0, height, 0.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

// translate to the top center of the image and add user input translation
double transx = (width - imagewidth) / 2 + usertranslation.x;
double transy = height - imageheight + usertranslation.y;
glTranslatef(transx, transy, 0);

//this currently rotates around the center of the image, but what I need
//is to rotate the image around the center of the window.
glTranslatef(imagewidth / 2, imageheight / 2, 0);
glRotatef(rot_angle, 0, 0, 1.0);
glTranslatef(-imagewidth / 2, -imageheight / 2, 0);

//bind the texture and draw the quad
drawTexturedQuad();

Now my question is, what do I need to change to let the image always rotate around the center point of the window. I already tried somehting like this for the rotation:
glTranslatef(imagewidth / 2, imageheight - usertranslation.y - height, 0);
glRotatef(rot_angle, 0, 0, 1.0);
glTranslatef(-imagewidth  / 2, -(imageheight - usertranslation.y - height), 0);

But then I get a inverted top down translation if the image was rotated for 180 degrees (the image moves in the oposite direction on translation).

A: To rotate around the center of the screen (0,0) you can change your entity's position according these equations:
x = x * cos(angle) - y * sin(angle)
y = x * sin(angle) - y * cos(angle)
Where x and y are the positions of your entity and angle is the angle of rotation. If you want to face the same point after rotation, like the center of the rotation, you also have to rotate your entity around its center by negative angle. This is the same what a rotation matrix use, but
If you want to rotate around a specific point you have to use coordinates relative to that point. Thats easy just substract the center point coordinates of the coordinates of your entity, do the rotation and add your center coordinates to your new position.
This is important because you were relative to an other point not the center and this is how vectors work.


text:
Q: Extract all Images from PDF with Python, and retain their transparency I see a number of solutions on the web and here for extracting images from a PDF with PyMuPDF, PyPDF2, and others, but none them successfully retain transparency information, are using deprecated code that no longer works, or the questions have gone unanswered. The examples I try show a black background where the transparency should be.  If I open the PDF in photoshop and pull out the image it is transparent backgrounded as I would expect. So I know the information is in there somewhere.  Does anyone have an example that does this with Python?
Here is an example of a post with solutions that do extract images, but they all convert to the wrong file format, or save as png but missing transparent aspects.
Extract images from PDF without resampling, in python?

A: PDF Images are not what you seem to expect. So lets take one sample, but all inserts can be done differently (otherwise there would be no need for different extraction apps). PDF was not designed for splitting retrospectively, many objects were simplified for toner ink for transfer on usually white paper, thus transparency was an afterthought, needing 4th version (%PDF-1.4++)
Here is a file with nothing other than what appears to be a single transparent image. Note it says its object 19, but there is nothing else!

Lets query what is in the file with poppler utility since most python libraries depend on that or GhostScript.
Poppler\poppler-22.04.0\Library\bin>pdfimages -list tt.pdf
page   num  type   width height color comp bpc  enc interp  object ID x-ppi y-ppi size ratio
--------------------------------------------------------------------------------------------
   1     0 image     950   575  gray    1   8  image  no        27  0    72    72 42.4K 7.9%
   1     1 image     950   575  index   1   8  image  no        19  0    72    72 2454B 0.4%
   1     2 smask     950   575  gray    1   8  image  no        19  0    72    72 42.4K 7.9%

What we can now see is there are 3 images and 2 of them are number 19, so now we see there are two images 27 and 19 but 19 also  has an overlay (softMask).
This is where PDF cannot store a RGBA file as one object but it needs split in to RGB image and a Greytone for the transparency. so here are the 2 images viewed in a graphics viewer. And many libraries need some IMage library to blend them back into one PNG.

An alternative library is MuPDF
MuPDF\1.20.0-tesseract>mutool extract -a tt.pdf
extracting image-0019.png
extracting image-0020.png
extracting image-0027.png

The simplest cli extractor is thus MuPDF so PyMuPDF should be able to export a similar blend. (However since I use single line programs without the overheads python imposes, I cant confirm the code needed in this specific case.)
Side Note that using a different image extractor that should maintain transparency provided a different view of contents and extracted the transparent image plus a smaller thumbnail, which on looking at producer (Adobe Illustrator) explains much of the differing graphics issues.
pdfcpu_0.3.12>pdfcpu  images  list tt.pdf
pages: all
2 images available
page  obj#  id  type width height colorspace comp bpc interp size filters
=========================================================================
   1    19 Im0 smask   950    575    Indexed    3   8        2 KB FlateDecode
        13     thumb   105     57    Indexed    3   8         171 ASCII85Decode,FlateDecode

         <xmp:Thumbnails>
            <rdf:Alt>
               <rdf:li rdf:parseType="Resource">
                  <xmpGImg:width>256</xmpGImg:width>
                  <xmpGImg:height>156</xmpGImg:height>
                  <xmpGImg:format>JPEG</xmpGImg:format>
...
<photoshop:LayerText>Testing</photoshop:LayerText>
...
<rdf:li>Cyan</rdf:li>
<rdf:li>Magenta</rdf:li>
<rdf:li>Yellow</rdf:li>
<rdf:li>Black</rdf:li>
...
<</BC 23 0 R/G 24 0 R/S/Luminosity/Type/Mask>>

In fact there were several references to masks !


text:
Q: Add BrinIndex to existing PostgreSQL database using Django I am running a website using Django, of which the database runs on PostgreSQL. To increase performance I want to add a BrinIndex to a model that is naturally ordered on disk.
I have added the index to my models definition as follows.
from django.contrib.postgres.indexes import BrinIndex

class Measurement(models.Model):
    class Meta:
        indexes = (
            BrinIndex(fields=['time'])
        )

    time = models.DateTimeField(
        'Time of measurement',
        null=True
    )

But running
python3 manage.py makemigrations

Returns an error
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pycharm\django_manage.py", line 52, in <module>
    run_command()
  File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pycharm\django_manage.py", line 46, in run_command
    run_module(manage_file, None, '__main__', True)
  File "C:\Python36\lib\runpy.py", line 205, in run_module
    return _run_module_code(code, init_globals, run_name, mod_spec)
  File "C:\Python36\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Python36\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:/Users/*USERNAME*/*PROJECT_NAME*\manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\core\management\__init__.py", line 347, in execute
    django.setup()
  File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\apps\registry.py", line 112, in populate
    app_config.import_models()
  File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:/Users/*USERNAME*/*PROJECT_NAME*\*APP_NAME*\models.py", line 300, in <module>
    class Measurement(models.Model):
  File "C:\Users\*USERNAME*\*PROJECT_NAME*\venv\lib\site-packages\django\db\models\base.py", line 298, in __new__
    new_class._meta.indexes = [copy.deepcopy(idx) for idx in new_class._meta.indexes]
TypeError: 'BrinIndex' object is not iterable

Am I doing something wrong? Can this index not be added afterwards?

A: here is the problem of your code
when defining tuples with a single value you have to put "," at the end of the value otherwise python won't recognize it as a tuple for example:
a = ('value1') #is a string not a tuple
a = ('value1',) #is a tuple

here is what your code should look like:
from django.contrib.postgres.indexes import BrinIndex
class Measurement(models.Model):
    class Meta:
        indexes = (
            BrinIndex(fields=['time']),  # "," is added here
        )

    time = models.DateTimeField(
        'Time of measurement',
        null=True
    )

A: A couple of things to try:

*

*You can't always have an index on a NULL field. I don't know the inner workings of BrinIndex but it's something you might like to check.

*Your model definition should include a db_index attribute:
from django.contrib.postgres.indexes import BrinIndex

class Measurement(models.Model):

    time = models.DateTimeField(
        'Time of measurement',
        db_index=True,
        null=True
    )

    class Meta:
        indexes = (
            BrinIndex(fields=['time'])
        )


text:
Q: How do I show all my customers on a widget in ThingsBoard? Given that I have this kind of hierarchy in my Thingsboard:
-Root Customer
--Customer 1
---Child 1.1
--Customer 2
---Child 2.1
---Child 2.2

, where Customer 1 and Customer 2 have their own admin accounts I need to show all customers that a user has access to on a widget.
The problem is that I can not make a correct alias for a widget to get "all my customers" as a list.

*

*Root Customer must see Customer 1 and Customer 2 and their children.

*Customer 1 should see "Child 1.1" and "Child 1.2"

*Customer 2 should see "Child 2.1" and "Child 2.2"

I have tried:

*

*Entity list, but it there is no option to show all (or idk how to do it)

*Entity name, but there is no wildcard of that I know, so I can only filter them, but not show all

*Relation query, but it doesn't show Customers inside any chosen Customer

So question is: How do I make a proper alias to show "My Customers" in the widget

A: I found the answer myself.
Ownership in Thingsboard is not a Relation. So you have to manually create those relations inside the entity as they are not automatically created.
So even if Root Customer owns Customer 1, they are still not related unless you explicitly created that relation.
So Customer Hierarchy page shows you hierarchy based on ownership, but widgets only show it by Relation.