text:
Q: Issue after updating from ASP.NET Core 1.0 to 1.1 Following this Official ASP.NET Article I updated from ASP.NET Core 1.0 to 1.1. But when compiling my ASP.NET Core project I get the following error in AccountController.cs file:
Error:
The call is ambiguous between the following methods or properties: 'System.Security.Claims.PrincipalExtensions.FindFirstValue(System.Security.Claims.ClaimsPrincipal, string)' and 'System.Security.Claims.PrincipalExtensions.FindFirstValue(System.Security.Claims.ClaimsPrincipal, string)'

The error is at following at line var email = info.Principal.FindFirstValue(ClaimTypes.Email); at the end of following action method:
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
                return View(nameof(Login));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return RedirectToAction(nameof(Login));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
            if (result.Succeeded)
            {
                _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
                return RedirectToLocal(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
            }
            if (result.IsLockedOut)
            {
                return View("Lockout");
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ViewData["ReturnUrl"] = returnUrl;
                ViewData["LoginProvider"] = info.LoginProvider;
                var email = info.Principal.FindFirstValue(ClaimTypes.Email);
                return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
            }
        }

project.json:
{
  "userSecretsId": "aspnet-ABCTest-6af8ade3-87ff-4468-a9ce-8bb69c696ab8",

  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.1.0",
      "type": "platform"
    },
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
    "Microsoft.EntityFrameworkCore.Tools": "1.1.0-preview4-final",
    "Microsoft.AspNetCore.Mvc": "1.1.0",
    "Microsoft.AspNetCore.Mvc.Core": "1.1.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.1.0",
    "Microsoft.AspNetCore.Authentication.Cookies": "1.1.0",
    "Microsoft.AspNetCore.Diagnostics": "1.1.0",
    "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.1.0",
    "Microsoft.AspNetCore.Identity": "1.1.0",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.0",
    "Microsoft.AspNetCore.Razor.Tools": "1.1.0-preview4-final",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0-preview4-final",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
    "Microsoft.Extensions.Configuration.Json": "1.1.0",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.1.0",
    "Microsoft.Extensions.Logging": "1.1.0",
    "Microsoft.Extensions.Logging.Console": "1.1.0",
    "Microsoft.Extensions.Logging.Debug": "1.1.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.1.0",
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": "1.1.0-preview4-final",
    "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": "1.1.0-preview4-final"  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238"  },

  "frameworks": {
    "netcoreapp1.1": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

A: Try removing "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final" from your dependencies. Mixing packages from different releases - in this case pre-RTM and 1.1.0 is usually the cause for such API ambiguity.


text:
Q: Counting letters in a string returns incorrect number My teacher wants us to write a program that counts the number of letters (A-Z, a-z), numbers, and special characters in an input string. We are only allowed to use <iostream>.
My program counts the letters correctly, but I can't get a correct count of numbers or other characters. Here is my code:
#include <iostream>   //preprocessor directive
using namespace std;

//preprocessor directives

int main ()
{

//declare and initialize variables

    char s[50];
    int i;
    int letter = 0;
    int number = 0;
    int other = 0;

//user input

    cout << "Enter a continuous string of characters with no blank spaces" << endl;
    cout << "(example: aBc1234!@#$%)" << endl << endl;
    cout << "Enter your string: ";
    cin >> s;
    cout <<endl;

//loop through the string

//count letters

    i = 0;
    while (s[i] !=0)
    {
    if ((s[i] >= 'a' && s[i] < 'z') ||
        (s[i] >= 'A' && s[i] < 'Z'))
        letter++;
    i++;
    }

//count numbers

    {
    if ((s[i] >= '0' && s[i] < '9'))
        number++;
    i++;
    }

//count other

    {
    if ((s[i] >= '!' && s[i] < ')'))
        other++;
    i++;
    }

//output results

    cout << "Your string has " << letter << " letters" << endl;
    cout << number << " numbers, and " << endl;
    cout << other << " other characters" << endl;

    return 0;
}

A: Lets take this step by step.  I'm assuming you haven't been exposed to for loops yet, which are much cleaner for this type of iterative problem, so we will stick to while loops for now.  Your code up to the while loop is just fine, so I'll ignore it.  When you get to the while loop you are creating a variable i to keep track of your progress while looping through the character array, and then telling the while statement to loop until it encounters a 0, which stands for the null character (I'd actually change the 0 to '\0' which is exactly the same thing, but states your intentions more clearly).  So this means your loop will go character by character through the string and let you examine each one. So right now inside the while loop you have an if statement that checks if the current character at index i is a letter. If so, increment the letter count.  That is exactly what you want. But then you reach the end of the while loops execution block and return back to the conditional to check if the next character is the null character and then repeat the while block.  The if statements that handle checking if the character is a number or symbol are outside the while loop and therefore will not be executed for each character in the string. Instead they will be executed only once on s[i], which will be the null character since that is the index that i is  still pointing to after the while loop terminates. Your solution should be to move those two if statements into the while loop so that they will be run for each character in the string.
By the way, be careful of your character tests.  You aren't including all the characters.  For instance you are including all characters up to, but not including 'Z'.  Make sure to make those comparisons into <=.  Also more importantly, your check for 'other' characters will only catch some of the other characters on the keyboard.  I won't tell you exactly how to fix this, since it is a school assignment, but I will tell you it will involve using the else clause with your if statement (or even better the else if statement). If you don't know much about it yet, there are some excellent tutorials online.  For instance: http://www.cprogramming.com/tutorial/lesson2.html
Good luck, and have fun!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delete all drawn shapes JAVA I need to delete shapes individually or all of them!
please help I've tried deleting all contents from my arrayList "Figuras"
and removeAll from panel
public class PaintRodo extends JFrame {

    JButton linea, circulo, rectangulo, trazo, llenar,borrar;
    static  int seleccion = 1;
    Color trazoC  = Color.BLACK;
    Color llenarC = Color.lightGray;
    JMenuBar barra;

    public static void main(String[] args) {
        new PaintRodo();
    }

public PaintRodo() {
    this.setSize(1000,700);
    this.setTitle("Paint");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.setBackground(Color.BLACK);
    Box miBox = Box.createHorizontalBox();
    linea= AgregarIcono("./src/linea.png",2);
    circulo= AgregarIcono("./src/circ.png",3);
    rectangulo= AgregarIcono("./src/rect.png",4);
    trazo = AgregarIconoColor("./src/trazo.png",5,true);
    llenar = AgregarIconoColor("./src/llenar.png",6,false);
    borrar =  AgregarIcono("./src/borrador.png",7);
    miBox.add(linea);
    miBox.add(circulo);
    miBox.add(rectangulo);
    miBox.add(llenar);
    miBox.add(trazo);
    miBox.add(borrar);
    panel.add(miBox);
    this.add(panel,BorderLayout.NORTH);
    this.add(new Lienzo(),BorderLayout.CENTER);
    this.setVisible(true);
}

public JButton AgregarIcono (String icono, final int accion){
    JButton boton = new JButton();
    Icon iconos = new ImageIcon (icono);
    boton.setIcon(iconos);

    boton.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e){
        seleccion =accion;

    }

    });
    return boton;

}

public JButton AgregarIconoColor (String icono, final int accion,final boolean grosor ){
    JButton boton = new JButton();
    Icon iconos = new ImageIcon (icono);
    boton.setIcon(iconos);

    boton.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e){
        if(grosor){
            trazoC = JColorChooser.showDialog(null,"Elige el Contorno",Color.BLACK);
        }
        else{
            llenarC = JColorChooser.showDialog(null,"Elige el Relleno",Color.BLACK);
        }

    }

    });
    return boton;

}

public class Lienzo extends JComponent{
    ArrayList<Shape> figuras = new ArrayList<Shape>();
    ArrayList<Color> arrLleno = new ArrayList<Color>();
    ArrayList<Color> arrTrazo = new ArrayList<Color>();
    Point inicio,fin;

    public Lienzo(){

        this.addMouseListener(new MouseAdapter()
        {
            public void mousePressed(MouseEvent e){
                if (seleccion!=1){
                inicio = new Point (e.getX(),e.getY());
                fin=inicio;
                repaint();
                }

            }
            public void mouseReleased(MouseEvent e){
                if (seleccion!=1){
                Shape SAVEfig=null;
                if (seleccion==2){
                     SAVEfig = crearLinea(inicio.x,inicio.y,e.getX(),e.getY());
                }
                else if (seleccion==3){
                     SAVEfig = crearCirculo(inicio.x,inicio.y,e.getX(),e.getY());

                }

                figuras.add(SAVEfig);
                arrLleno.add(llenarC);
                arrTrazo.add(trazoC);
                repaint();
            }

            }
        });//mouselistener

        this.addMouseMotionListener(new MouseMotionAdapter(){
            public void mouseDragged(MouseEvent e){

                fin= new Point (e.getX(),e.getY());
                repaint();

            }

        });//MotionListener

    }//constructor lienzo

    public void paint (Graphics g){

        Graphics2D graFig = (Graphics2D)g;
        graFig.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        graFig.setStroke (new BasicStroke(2));
        Iterator<Color>contadorTrazo= arrTrazo.iterator();
        Iterator<Color>contadorLleno= arrLleno.iterator();
        graFig.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f));
        this.setBackground(Color.LIGHT_GRAY);
        for (Shape i: figuras){
            graFig.setPaint(contadorTrazo.next());
            graFig.draw(i);
            graFig.setPaint(contadorLleno.next());
            graFig.fill(i);
        }

        if (inicio!=null&&fin!=null){
            graFig.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.40f));
            graFig.setPaint(Color.LIGHT_GRAY);
            Shape SAVEfig=null;

            if (seleccion==2){
                SAVEfig=crearLinea(inicio.x,inicio.y,fin.x,fin.y);
            }
            else if (seleccion==3){
                SAVEfig=crearCirculo(inicio.x,inicio.y,fin.x,fin.y);
            }

            graFig.draw(SAVEfig);

        }

    }

    private Rectangle2D.Float crearRectangulo(int x1, int y1,int x2 , int y2){
        int x =Math.min(x1, x2);
        int y =  Math.min(y1, y2);

        int ancho = Math.abs(x1-x2);
        int alto = Math.abs(y1-y2);
        return new Rectangle2D.Float(x,y,ancho,alto);
    }
     private Line2D.Float crearLinea(int x1, int y1, int x2, int y2){
         return new Line2D.Float(x1, y1, x2, y2);
    }

      private Ellipse2D.Float crearCirculo( int x1, int y1, int x2, int y2){
          int x = Math.min(x1, x2);
          int y = Math.min(y1, y2);
          int ancho = Math.abs(x1 - x2);
          int alto = Math.abs(y1 - y2);
          return new Ellipse2D.Float(x, y, ancho, alto);
      }

}//classLienzo

 }//MainClass Paint rodo

I need to delete shapes individually or all of them!
Please help; I've tried deleting all contents from my arrayList "Figuras"
and (removeAll) from panel


text:
Q: Splitting lines at intersections in PostGIS I have oriented polylines (Montreal's train network) and stops (train stations).
My network looks like this:

(closer look):

I'd like to split my tracks at each stations and ideally add fields FromStation, ToStation to my new Train tracks table.
I've used ST_Snap to snap my points to my tracks so there's an intersection. There's no guaranty though that there's a node where it intersects.
I tried some variation using ST_Split. No error, but no results either. Just empty geometry in the end.
My data comes from the gtfs, so for now, I have a shape_id, trip_headsign and route_short_name on each line.
If I could have a resulting table like
shape_id fromstation tostation
2_1      VRM1B       SLR3B
2_1      SLR3B       SLR2B
2_1      SLR2B       SLR1B
etc.

(shape_id 2_1 is the blue line west bound), that would be ideal.
I need somehow to use that to create a personnel allocation model for our inspectors and agents on the network. Each segments will be considered a road in Network Analyst with usage restriction to match the train schedule at each train station... Never found anything like that done, but I've been given the task to at least try.

A: You might need to use the linear referencing functions to get what you want. For each point, use ST_LineLocatePoint to find out what proportion along the line the point is, then for each pairing of points, use ST_LocateBetween to extract the portion of the line between the points. So rather than splitting, you're using linear referencing to extract.
http://postgis.net/workshops/postgis-intro/linear_referencing.html


text:
Q: JPA one-to-many unidirectional relationship using a join table I would like to evaluate JPA on an existing project. The database model and the java classes exists and are currently mapped via self generated code. The database model and the java classes do not fit ideally together - but the custom mapping works well. Nevertheless the usage of JPA in general seems worth a try.
As you see I am new to JPA and have to do the work with xml configuration. Currently I am working on a one-to-many unidirectional relationship using a join table (please do not discuss this szenario here).
A (one - relationship owner) <-> AB (JoinTable) <-> B (many)

The tables look like this
A
--
ID
BREF
...

B
--
ID
...

AB
--
A_BREF      (foreign key to a reference column in A which is NOT the id)
B_ID

I would like to define a unidirectional one-to-many relationship for class A.
class A {

 private List<B> bs;

}

and did it like this:
<one-to-many name="bs">
    <join-table name="ab">
        <join-column name="a_bref">
            <referenced-column-name name="bref" />
        </join-column>
        <inverse-join-column name="b_id">
            <referenced-column-name name="id" />
        </inverse-join-column>
    </join-table>
</one-to-many>

Althoug this does not force an error it is not working. The problem is that the join table does not work on the ID column of A.  The query to select the "B" entities works with the A.ID column value instead of the A.BREF column value to select the entities.
(How) can I make this mapping work (I use eclipselink 2.2.0)?
Thanks for any suggestion!

EDIT:
After looking at a link provided in @SJuan76 answer I slightly modified my mapping to
<one-to-many name="bs">
    <join-table name="ab">
        <join-column name="a_bref" referenced-column-name="bref" />
        <inverse-join-column name="b_id" referenced-column-name="id" />
    </join-table>
</one-to-many>

This now causes the following errors (tested with eclipselink 2.1.0 and 2.2.0)
eclipselink 2.1.0

Exception Description: The parameter
  name [bref] in the query's selection
  criteria  does not match any parameter
  name defined in the query.

eclipselink 2.2.0

Exception Description: The reference
  column name [bref] mapped on the
  element [field bs]  does not
  correspond to a valid field on the
  mapping reference.

By the way - if I remove the referenced-column-name="bref" from the definition I get the same exception for the referenced-column-name="id" on the inverse-join-column element. So I doubt that I have understood referenced-column-name correct. I used it to specify the database column name of the tables which are related to the join table. Is this correct?

SOLUTION:
The final error in my szenario was that I did not have the BREF field definied in my class
class A {
    private long bref; // missing !
    private List<B> bs;
}

and in my orm.xml mapping file for this class
<basic name="bref">
    <column name="bref" />
</basic>

I was not aware that I have to define the used join mapping referenced-column-name attributes somewhere in my mapping classes (as I also did not have the join-table itself or the name attributes of join-column/inverse-join-column mapped to a class or class members.)
Also the tip to check the case issue was helpful for me. I feel now quite to verbose in specifying my mapping as I overwrite all default (uppercase) mappings with lowercase values. As my database is not case sensitive I will use upper case notation if special mapping is needed to go with the default.
+1 for all!

A: In general JPA requires that the foreign keys/join columns reference the primary key/Id of the Entity.  But, this should work with EclipseLink, so please include the SQL that is being generated, and if it is wrong, please log a bug.
How is the Id of A defined, is it just ID or ID and BREF?
You can use a DescriptorCustomizer to customize the ManyToManyMapping for the relationship and set the correct foreign key field name.

A: Can you try defining the field as "BREF" or the same exact case used if you defined it on the attribute mapping, or you can try setting the eclipselink.jpa.uppercase-column-names persistence property to true.  This is likely the issue with "id" when referenced-column-name="bref" is removed, since it is likely the field in the entity defaults to "ID".


text:
Q: How do I make something happen on the screen even without a key being pressed? I am making Pacman in C++ with the Ncurses library. I am able to move Pacman with my code, but I want to move it so that pacman keeps moving even when I am not pressing any key and when I press another direction key, it changes direction. Right now, the pacman only takes one step when I press a key. Also I have to press a key 2 or 3 times before pacman moves in that direction.
if (ch==KEY_LEFT)
{
    int b,row,column;
    getyx(stdscr,row,column);
    int h;
    do    // do-whileloop to move the pacman left until it hits the wall
    {
        column-=1;
        mvprintw(row,column,">");  //print the ">" symbol
        refresh();
        waitf(0.1);      //this pauses the game for 0.1sec
        attron(COLOR_PAIR(1));
        mvprintw(row,column,">");
        attroff(COLOR_PAIR(1));
        refresh();
        waitf(0.1);
        mvprintw(row,(b),"O");  //showing the open mouth of pacman
        refresh();
        waitf(0.1);
        attron(COLOR_PAIR(1));a
        mvprintw(row,column,"O");
        attroff(COLOR_PAIR(1));
        h = getch();
    }
    while(h == KEY_LEFT);
}

right = getch();

loop to move right in an if condition
up = getch();

loop to move up in an if condition
down = getch();

oop for moving down in an if condition.

A: The standard solution to this is the finite-state machine. The character has six or so possible states: standing, moving up, moving right, moving down, moving left, dead. Rather than a keypress directly moving the character, the keypress should change the character's state.
In such a small application, rather than implementing an incredibly flexible finite-state machine, you may use a very simple implementation as such:
enum PlayerState {
    Standing,
    MovingUp,
    MovingRight,
    MovingDown,
    MovingLeft,
    Dead
};

Then, inside your game loop you can add a very simple state check which then takes the appropriate action for the frame.
switch(state) {
case Standing:
    break;
case MovingUp:
    player.PositionY += 1;
    break;
// ...
}

The last step is to hook input, which depends on your method of retrieving input. Using callbacks, an example is:
void KeyDown(Key k) {
    switch(k) {
    case UpArrow:
        if(state != Dead)
            state = MovingUp;
        break;
    case RightArrow:
        if(state != Dead)
            state = MovingRight;
    // ...
    }
}

You can see why in a larger project it would be important to implement a more flexible finite-state machine, but hopefully this example has given you an easy-to-understand idea.

A: You need an equivalent of kbhit, ie. a non-blocking getch. Which really gives the solution, set O_NONBLOCK on the input. See an example here. Once you have this, simply loop contiguously and just check for the key hit, w/o waiting on actual key press.

A: Function getch is blocked until some key is pressed. If you don't want to be blocked then call _kbhit before getch too make sure that there is something in input buffer.
EDIT: Take a look at ncurses functions nodelay and cbreak. They enable asynchronous input.

A: I suggest you take a look at the model-view-controller model, it will help you with this problems and all the other problems that you will have if you continue your program like this.
Edit: shortcut
To move your pacman continuously you will need a separate thread to control it and make it move. Take a look at pthreads for that.
If you keep only the user input in the main run loop of your program, the problem that you have to press the keys a few times will go away too (the problem here is that the processor has to be on the getch() line when you press the key, otherwise it will not be detected.

A: It is pretty easy
for each direction make 4 function
and inside the function,put in the other 3 direction function which get activated by kbhit.
and put a else statement in which it keeps moving forward if you do not  hit a button i.e (!kbhit());
and then put all this in a loop.

If you do this for all the direction functions you should be able to get the desirable outcome.


text:
Q: Entity annotation attributes do not work Here is my entity:
[Table( Name = "PdfMeta" )]
public class Meta
{
    [Key()]
    public int Id { get; set; }

    [Column(Name = "TotalPages")]
    public int TotalPages { get; set; }

    [Column(Name = "PdfPath")]
    public string PdfUri { get; set; }

    [Column(Name = "ImagePath")]
    public string ImageUri { get; set; }

    [Column(Name = "SplittedPdfPath")]
    public string SplittedFolderUri { get; set; }

}

Here is code from context:
      public DbSet<Meta> PdfMeta { get; set; }

Why new table (Metas) has created with ImageUri, PdfUri ... columns? I know that this was done  by convention but I have explisitly specifyed table and columns.

A: Name property of ColumnAttribute has only getter defined. Pass column name in constructor instead:
[Table("PdfMeta")]
public class Meta
{
    [Key]
    public int Id { get; set; }

    [Column("TotalPages")]
    public int TotalPages { get; set; }

    [Column("PdfPath")]
    public string PdfUri { get; set; }

    [Column("ImagePath")]
    public string ImageUri { get; set; }

    [Column("SplittedPdfPath")]
    public string SplittedFolderUri { get; set; }
}

BTW ColumnAttribute defined in EntityFramework.dll. Looks like you have referenced ColumnAttribute from System.Data.Linq.dll


text:
Q: Infinite sum of sine I do not know exactly whether this summation $\displaystyle \sum_{n=1}^{\infty} |\sin(x_{n})|$, with $x_{n}$ approaches $0$, cannot be $\infty$ or not.
But I guess it is actually divergent but does not approach $\infty$ like $\lim \sin(n)$. I try to prove it does not go to $\infty$ by definition of limit but still not succeed.
Updated for my trouble:
If a limit diverges, there are 2 cases.
Case 1: the limit approaches infinity, like lim n.
Case 2: the limit is unidentified, like lim sin(n).
So, I just want to verify that that summation above does not always go to infinity. And, yes, I still cannot do it.

A: $\frac {\sin {|x_n|}} {|x_n|} \to  1$ so the series converges iff $\sum |x_n|$ converges. An example where it diverges is given by $x_n=\frac  1n$. [Note that $|\sin (x_n)|=\sin |x_n|$ at least for large $n$].
An example where it converges is given by $x_n=\frac  1{n^{2}}$.


text:
Q: Unable to lookup JNDI name in Weblogic 12c While deploying a webapp on weblogic I am encountering the below error:
Caused by: org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name [java:comp/env/jdbc/PassmarkToolDB]
        at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:117)
        at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:115)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
        at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
        at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
        at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1631)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568)
        ... 77 more
Caused by: javax.naming.NameNotFoundException: While trying to look up /comp.env.jdbc.PassmarkToolDB in /app/webapp/wscredentialmanager/1012163426.; remaining name '/comp/env/jdbc/PassmarkToolDB'
        at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1180)
        at weblogic.jndi.internal.ApplicationNamingNode.lookup(ApplicationNamingNode.java:143)
        at weblogic.jndi.internal.WLEventContextImpl.lookup(WLEventContextImpl.java:253)
        at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:426)
        at weblogic.jndi.factories.java.ReadOnlyContextWrapper.lookup(ReadOnlyContextWrapper.java:45)
        at weblogic.jndi.internal.AbstractURLContext.lookup(AbstractURLContext.java:135)
        at javax.naming.InitialContext.lookup(InitialContext.java:415)
        at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:114)
        ... 97 more

Can someone please let me know what are the ways to debug this.

A: Did you take look at JNDI Tree in Admin Console?
On Weblogic12c, I'm pretty sure that the JNDI URL is jdbc/PassmarkToolDB and not java:comp/env/jdbc/PassmarkToolDB


text:
Q: Filter JSON objects by key with multiple values I have a JSON file with objects like this:
[
    {
        "name" : "something",
        "brand": "x",
        "category" : "cars"
    },
    {
        "name" : "something2",
        "brand": ["x", "y"],
        "category" : "bikes",
    }
]

To filter by category I do this:
filterObjects(key, value) {
    if (key == 'category') {
        objects.filter(item => item.category == value);
    }
}

But when I try to do this with brand, it only returns the first one.
How can I do to make my filter loop over each value and return both items?

A: I think you should check first whether the field has array value or not:
const filterObjects = (key, value) => {
  return objects.filter(item => {
    // you can access a field of object this way too.
    const itemValue = item[key];

    // check if the field is an array
    if (Array.isArray(itemValue)) {

      // if array, the predicate becomes whether the array contains the value or not
      return itemValue.includes(value);

    // otherwise you can compare the value
    // I recommend you to use === operator rather than == operator
    } else {
      return itemValue === value;
    }
  });
};

A: It's not clear what your intended output is, but assuming you're trying to search for objects containing a given key/value pair:
// key and value to search for:
function filterObjects( key, value ) {
    var r = [];
    objects.forEach( function(obj) {
        if ( obj[key] == value ) {
            r.push( obj );
        }
    })

    return r;
}

let a = filterObjects( 'category', 'bikes' );

A: I'm guessing you're trying to do the following where value === "x":
filterObjects(key, value) {
    if (key == 'brand') {
        objects.filter(item => item.brand == value);
    }
}

For the first element (element [0]), your item.brand === value check becomes "x" == "x" which is true, therefore it passes. But for the element [1], it becomes ["x", "y"] == "x" which is obviously false, so it doesn't pass.
You should probably write a comparison function that returns true when the two values are equal or when the first value is an array that includes the second one and use that function instead of a == check.


text:
Q: When is it acceptable to define a function in a header file? Good Evening,
Im new to C++ but I was under the impression it was a no go to Define functions within header files.
I've been looking at some open source code and it seems a class has been defined within a header file and not split into .h / .cpp.
class Action
{
public:
    virtual ~Action() {}

    virtual string GetName() { return "Action"; }
    virtual void RequestUpdate(ActionContext* context) {}
    virtual void Do(ActionContext* context, double value) {}
    virtual void Touch(ActionContext* context, double value) {}
    virtual double GetCurrentNormalizedValue(ActionContext* context) { return 0.0; }
    virtual double GetCurrentDBValue(ActionContext* context) { return 0.0; }

    int GetPanMode(MediaTrack* track)
    {
        double pan1, pan2 = 0.0;
        int panMode = 0;
        DAW::GetTrackUIPan(track, &pan1, &pan2, &panMode);
        return panMode;
    }
};

There seem to be many other header files defining functions in the same project. Am I missing something here?
Full Header File HERE

A:
When is it acceptable to define a function in a header file?

When all of the following apply:

*

*The function is declared inline (whether explicitly or implicitly).

*

*If you define a non-inline function header and include the header into more than one translation unit, you will violate ODR making the program ill-formed (no diagnostic required).

*Note that when the function is declared inline, it has to be defined in all TU that use it and thus should be defined in a header. Thus, if other conditions below don't apply, the function shouldn't be declared inline.

*Note that implicitly instantiated function templates are inline functions. Thus, unless you have fixed set of template instantiations, template functions practically have to be defined in headers. Same applies to non-template functions within class templates.

*The function doesn't introduce new dependencies to the header.

*

*Dependencies of headers propagate as dependencies to anything that includes the header. This cause increases coupling between components which is undesirable.

*The function doesn't change often.

*

*Headers tend to be included into multiple TU, and modifying a header consequently necessitates re-compilation of multiple TU which slows down development in large projects.

*The function is cheap to compile. (This doesn't matter if the function is in a pre-compiled header)

*

*Headers tend to included into multiple TU, and repeating expensive compilation can significantly slow down compilation from scratch.


text:
Q: Having trouble with C++ Bitmaps I am attempting to produce code that yields an image with 1 pixel set to black, the problem is that the output is 8 horizontal pixels of black when I attempt to set a single pixel to black. I also attempted to set the pixel above to black, but it resulted in a horizontal line 8 pixels above the original.
So my question is, how can I change my code so I end up working with bits instead of bytes in my image? I just want to be able to set a single pixel to black instead of a byte of pixels.
Here is my code:
#include <iostream>
#include <fstream>
#include "windows.h"
using namespace std;

#define IMAGE_SIZE 256
int main(int argc, char* argv[])
{

    BITMAPFILEHEADER bmfh;

    BITMAPINFOHEADER bmih;

    char colorTable[8] = { 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff };

    char bits[IMAGE_SIZE][IMAGE_SIZE];

    ofstream bmpOut("foo.bmp", ios::out + ios::binary);
    if (!bmpOut) {
        cout << "could not open file.";
        return -1;
    }
    bmfh.bfType = 0x4d42;
    bmfh.bfReserved1 = 0;
    bmfh.bfReserved2 = 0;
    bmfh.bfOffBits = sizeof(bmfh) + sizeof(bmih) + sizeof(colorTable);
    bmfh.bfSize = bmfh.bfOffBits + sizeof(bits);

    bmih.biSize = 40;
    bmih.biWidth = IMAGE_SIZE;
    bmih.biHeight = IMAGE_SIZE;
    bmih.biPlanes = 1;
    bmih.biBitCount = 1;
    bmih.biCompression = 0;
    bmih.biSizeImage = 0;
    bmih.biXPelsPerMeter = 2835;
    bmih.biYPelsPerMeter = 2835;
    bmih.biClrUsed = 0;
    bmih.biClrImportant = 0;

    // Here I am initializing a white background for the bitmap image

    for (int i = 0; i < IMAGE_SIZE; i++) {
        for (int j = 0; j < IMAGE_SIZE; j++) {
            bits[i][j] = 255;
        }
    }

    // Here I attempt to set the most bottom left pixel to black and the pixel above it to black as well

    bits[0][0] = 0;

    bits[1][0] = 0;

    char* workPtr;
    workPtr = (char*)&bmfh;
    bmpOut.write(workPtr, 14);
    workPtr = (char*)&bmih;
    bmpOut.write(workPtr, 40);
    workPtr = &colorTable[0];
    bmpOut.write(workPtr, 8);
    workPtr = &bits[0][0];
    bmpOut.write(workPtr, IMAGE_SIZE*IMAGE_SIZE);
    bmpOut.close();

    system("mspaint foo.bmp");

    return 0;
}

Here is a link to the bitmap image produced:
Scaled up for clarity
Thanks

A: Based on BITMAPINFOHEADER documentation it looks like you are setting your bitmap to be read as monochrome by setting bmih.biBitCount = 1. This way every pixel is represented by one bit (black or white only), not byte. Thus, to set bottom-left pixel to black, you need to do bits[0][0] = 127 (127 = 0x7F = 01111111b). To set one above it, I think you would need to do bits[1][0] = 127. In this case I also believe
char bits[IMAGE_SIZE][IMAGE_SIZE/8];
...
for (int i = 0; i < IMAGE_SIZE; i++) {
    for (int j = 0; j < IMAGE_SIZE/8; j++) {
        bits[i][j] = 255;
    }
}
...
workPtr = &bits[0][0];
bmpOut.write(workPtr, IMAGE_SIZE*(IMAGE_SIZE/8));

would be enough.
If you intended to use different color palette, you should set different biBitCount, as described in the docs I linked to at the beginning, I guess you would want bmih.biBitCount = 8 as a healthy default for your code.


text:
Q: Uniqueness of maximal subgroup and order being a power of a prime Let $G$ be a finite group. If $G$ has only one maximal subgroup (a maximal subgroup is a proper subgroup $M$ that given a subgroup $H$ of $G$, $M \subset H \subset G$ implies that $H = M$ or $H = G$), prove that the order of $G$ is a power of a prime.
I've been stuck in this exercise for a few days now and just can't solve it.
I tried applying Cauchy to $p$ and $q$ primes that divide the order of $G$ and also to analyse maximal subgroups containing the generated subgroups of the elements of order $p$ and $q$ given by Cauchy's theorem, but without any success.

A: Hint: Let $x \notin M$, where $M$ is the unique maximal subgroup. What can you say about $\langle x \rangle$?

A: Step 1. A group $G$ cannot be expressed as a union of proper subgroups if and only if $G$ is cyclic.
Step 2. A finite group that has a unique maximal subgroup cannot be expressed as a union of proper subgroups.
Step 3. If $G$ is cyclic of order $n$, and $p$ is a prime dividing $n$, then $G$ has a subgroup of order $n/p$ that is maximal.


text:
Q: Create two different outputs from the same file in webpack I need to change the build process of my react application, so that it creates two different outputs of the same file. At this time it only creates a index.js which is minified but i want another output which is basically the same as the index.js but gziped.
Is it possible to change the webpack config to get 2 files (one minified and the other gziped) from the same entry ?

A: If you want to edit the Webpack config of an app built with create-react-app you have to eject the app, then write your own Webpack config files.. This can be extremely painful, and essentially nullifies (one of) the biggest reasons to use create-react-app..
I think it would be easiest to write a script that does the gzipping for you, after the build is finished.
I put this together real quick to show how you can gzip a file with command line arguments...
How to use: node gzipper.js %SOURCE_FILE_PATH% %DEST_DIR_PATH%

*

*ex: node gzipper.js ./build/index.js ./build

*Supports relative paths and absolute paths.

*Uses 'standard libraries' - requires no additional packages

const fs = require('fs');
const path = require('path');
const zlib = require('zlib');

const SOURCE = path.resolve(__dirname, process.argv[2]);
const DESTINATION = path.resolve(__dirname, process.argv[3]);

const SOURCE_STATS = fs.lstatSync(SOURCE);
const SOURCE_FILE_NAME = path.basename(SOURCE);
const DESTINATION_STATS = fs.lstatSync(DESTINATION);

if(!SOURCE_STATS.isFile() || !DESTINATION_STATS.isDirectory()) {
    throw new Error("[ERROR]::SOURCE must be a file, DESTINATION must be a directory!");
}

const SOURCE_CONTENTS = Buffer.from(fs.readFileSync(SOURCE, 'utf8'));

zlib.gzip(SOURCE_CONTENTS, (error, result) => {
    if(error) throw error;

    const OUT_PATH = `${DESTINATION}\\${SOURCE_FILE_NAME}.gz`;
    fs.writeFileSync(OUT_PATH, result);
});

You could add a script to your package.json file, something like gzip that you add onto the npm build (or yarn build) script, so it runs after build..:
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build && npm run gzip",
    "gzip": "node gzipper.js ./build/index.js ./build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },


text:
Q: MYSQL differs in Output from script I have a problem with the MySQL output formatting while executing the commands from a bash script.
If I execute a command on the command line then, I am able to get the output in formatted as  expected.
$ mysql -u dbclient -pxxxx GEKONYLOGDB -e "select now(),max(time_stamp) from metrics"
+---------------------+---------------------+
| now()               | max(time_stamp)     |
+---------------------+---------------------+
| 2012-12-09 14:25:38 | 2012-12-09 14:25:20 |
+---------------------+---------------------+

But where as if I keep the same command in a script and execute I am not getting the formatted output.
$ cat test
#!/bin/bash
mysql -u dbclient -pxxxx GEKONYLOGDB -e "select now(),max(time_stamp) from metrics"

$ ./test
now()   max(time_stamp)
2012-12-09 14:27:52     2012-12-09 14:27:47

So all I need the same output from script.
Thanks.

A: Pass the -t or --table option to force table output.
mysql --table -u dbclient -pxxxx GEKONYLOGDB -e "select now(),max(time_stamp) from metrics"

From mysql --help:
  -t, --table         Output in table format.

A: If you want to have --table option enabled by default when calling mysql program, please check this SO answer How to store MySQL results to a file in table format.


text:
Q: PHP Posting last dynamic Form I have used a while loop to display Dropdown yes and no which displays a users permissions for each page, so page name and Yes or no drop down for each page.
The form appears correct and displaying correct database value for each user as default. However if I change one of the page permission from yes to no or vice verser its only updating the last of the dropdowns in the database and not the rest the rest thats changed. Any Ideas what I am missing here?
<?php

$sql = "SELECT DISTINCT username FROM users ORDER BY username";
$resultusers = $connect->query($sql);
?>
<?php
 require ("cw/connect.php");

?>
<?php
if(isset($_POST['selectbutton']))
{
    $username = $_POST['selectuser'];

$query = "SELECT
users.username, users.first, users.last, users.id, permissions.PermID, permissions.PermUserID, permissions.PermPagesID, permissions.view, pages.PagesName, pages.PagesLink, pages.PagesID
FROM users INNER JOIN permissions ON users.id = permissions.PermUserID INNER JOIN pages ON permissions.PermPagesID = pages.PagesID WHERE username = ?";

$stmt = mysqli_prepare($connect, $query);

if($stmt){
    //Put whats to be binded from the statement so in this case we want data for this username selected
    mysqli_stmt_bind_param($stmt,"s",$username);

    // here add all the varibles to be pulled from database
    mysqli_stmt_bind_result($stmt, $username, $first, $last, $id, $PermID, $PermUserID, $PermPagesID, $view, $PagesName, $PagesLink, $PagesID);

    mysqli_stmt_execute($stmt);

    mysqli_stmt_fetch($stmt);

?>

First:<?php echo $first; ?>

Last:<?php echo $last; ?>

User:<?php echo $username; ?>

<form action="user-permissions.php" method="post">
<?php
while ($stmt->fetch()) {

echo $PagesName;
echo "
";
echo "<select name=\"permissionSelect\">";

?>

<option value="<?php echo $view; ?>"><?php echo $view; ?></option>
<option value="No">No</option>
<option value="Yes">Yes</option>

</select>

<?php
echo "<input type=\"hidden\" name=\"PermPagesID\" value=\"".$PermPagesID."\">";
echo "<input type=\"hidden\" name=\"PermUserID\" value=\"".$PermUserID."\">";
        }
        ?>
<?php
echo "<input type=\"submit\" name=\"updatep\">";
echo "<form>";

     }

}
?>

<?php
//UPDATE PERSON
 require ("cw/connect.php");

if(mysqli_connect_error()){
    echo mysqli_connect_error();
    exit();

}
if(isset($_POST['updatep']))
{
    $view = mysqli_real_escape_string($connect,$_POST['permissionSelect']);
    $PermPagesID = mysqli_real_escape_string($connect,$_POST['PermPagesID']);
    $PermUserID = mysqli_real_escape_string($connect,$_POST['PermUserID']);

$query = "UPDATE permissions SET view = ? WHERE PermPagesID = $PermPagesID AND PermUserID = $PermUserID";

$stmt = mysqli_prepare($connect, $query);

if($stmt){
    mysqli_stmt_bind_param($stmt, "s", $view);

    mysqli_stmt_execute($stmt);

    mysqli_stmt_fetch($stmt);
    echo "Updated to: ".$username;

    }else{

    echo "object not created";

}
}

?>

A: The reason is because you cannot have the same name used more than once in your form elements. Otherwise, only the last one will be used.
You will need to give them all a different name, or mimic array syntax as follows. For example, instead of:
echo '<select name="permissionSelect">';

Use:
echo '<select name="permissionSelect[]">';

Then in your PHP script you can reference these by looping through them with a foreach:
foreach($_POST['permissionSelect'] as $permissionSelect){
    //handle it here
}

You will need to do this for the other name attributes inside the loop as well.
Lastly, you will notice that I removed you backslashes from your code. This is because you both PHP and HTML can use either single or double quotes. And while there is some difference between the two in PHP, in most cases you can just interchange them. So, if PHP is using single quotes, then use double quotes for your HTML attributes, or vice versa.


text:
Q: How to add information to (gci -filter *.* -recurse).FullName (ie:LastWrite, Modified By, Etc) I am an absolute noob when it comes to Powershell..
Currently I run a simple script to get a file listing across our server.
(gci -filter *.xl* -recurse).FullName > AllExcel.txt

It gives me exactly what I'm looking for, a directory path and the file name all on one line across all subdirectories.
X:\00\This file 1.xls
X:\00\This file 2.xls
X:\aaa\This file Too 1.xls
X:\aaa\This file Too 2.xls
Can I add The date/time the file was last modified for each item? {$_.LastWriteTime}?
If so, can the output be sorted by this date/time? Would prefer newest at the top if possible.
are there also options to get who last modified a file?

A: Instead of a simple text file, I would store the results in a structured CSV file.
Get-ChildItem -Path 'X:\' -Filter '*.xls*' -File -Recurse |
Select-Object FullName, LastWriteTime |
Sort-Object LastWriteTime -Descending |
Export-Csv -Path 'X:\Somewhere\AllExcel.csv' -NoTypeInformation -UseCulture

This will result in a structured CSV file you can open on a machine with the same regional settings as yours to open in Excel
As for who last modified the files:
You could use Get-Acl on each file and with that get the Owner, but whoever owns the file  is not necessarily the one who created/modified it.
You cannot identify creator or user who made the last change in Windows unless have file and folder auditing enabled beforehand, so you can extract the information from the audit logs.


text:
Q: Dealing with cache file locks when using EntityValue in ParallelMap I'm trying to run the following (naturally, I have FAR more zip codes and a much longer list of properties, both truncated for speed of the example):
zipCodes={"40220","46202","46077","40202","80301","80304","90210","90211"};
zipProperties = {
                 EntityProperty["ZIPCode", "AggregateHouseholdIncome"],
                 EntityProperty["ZIPCode", "AverageHouseValue"],
                 EntityProperty["ZIPCode", "Employment"],
                 EntityProperty["ZIPCode", "Population",{"Gender"->"Female"}],
                 EntityProperty["ZIPCode", "Population",{"Gender"->"Male"}]
                };
zipData = ParallelMap[
   With[
     {zip = #},
     Join[{zip}, Entity["ZIPCode", zip][#]& /@ zipProperties]
     ] &,
   zipCodes
   ];

and I'm getting:
(kernel 1) CreateFile::filex :  C:\Users\user1\AppData\Roaming\Mathematica\Knowledgebase\u8cfm00s2kat\u8cfm00s2kat-1709886844729300217.dat.lock already exists.
(kernel 3) EntityValue::nodat :  Unable to download data. Some or all results may be missing.
(kernel 8) ...more of the same...

I'm assuming the nodat error is just a legitimate absence of data, though it could also signify a lack of a result from too many simultaneous requests. I've had that happen before with FinancialData and had to go back and re-retreive values for Missing[] results where I knew that they HAD to exist (like closing prices for valid ticker symbols on dates when trading occurred).
Anyone knows how to get Wolfram curated data from a parallelized process without running into locks?
Thanks in advance!


text:
Q: Greasemonkey to inject Adfly ads Is there any way to convert this into Greasemonkey code?
<script>
var adfly_id = 517450;
var adfly_advert = 'banner';
var frequency_cap = 5;
var frequency_delay = 5;
var init_delay = 3;
</script>
<script src="http://adf.ly/js/entry.js"></script>

It's a website entry script for adf.ly which when added to a website brings up adf.ly ads.
I want to make a script that will load adf.ly links in the browser while surfing.
Please help!
Thank You :)

A: Yes, in theory. You'd just need to write these to the head. They will evaluate outside of the greasemonkey scope if you load them on the page direction. you can even just do a document.body.appendChild after creating script tags. So,
var sc = document.createElement('script');
sc.src = "http://adf.ly/js/entry.js"
document.body.appendChild(sc);

For the other one, it'd probably just be easier to do an unsafeWindow.varname assignment like
unsafeWindow.adfly_id = 517450;
unsafeWindow.adfly_advert = 'banner';
unsafeWindow.frequency_cap = 5;
unsafeWindow.frequency_delay = 5;
unsafeWindow.init_delay = 3;

Though you don't ever want to use these values in your script, as these can be changed by the website itself. Using them gives websites access to more control over a users browser and lets them do things that they would not otherwise be able to do (for example, accessing information from other websites via XSS ajax). Only write to values in unsafeWindow, don't read from them.

A: You'll need to inject the JS into the page.  Avoid unsafeWindow if you can.
Here's a complete Greasemonkey translation of that script:
// ==UserScript==
// @name            _adFly why?
// @include         http://YOUR_SITE/YOUR_PATH/*
// ==/UserScript==

function myCode () {
    //--- Set global variables for adFly.
    window.adfly_id         = 517450;
    window.adfly_advert     = 'banner';
    window.frequency_cap    = 5;
    window.frequency_delay  = 5;
    window.init_delay       = 3;
}

addJS_Node (null, null, myCode);
addJS_Node (null, "http://adf.ly/js/entry.js");

function addJS_Node (text, s_URL, funcToRun) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ    = document.getElementsByTagName('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}


text:
Q: sql output as a ranking If I have a table of random values in a sql table, how can I export and display them as a raking rather than the absolute value... for example.. if the three values are 30 85 and 90 how do i get 30 do display as 1 or 1st, 85 as 2 or 2nd etc

A: MySQL doesn't have analytic function support (ROW_NUMBER, RANK, DENSE_RANK), which is generally what you'd use for requirements like these.
Use:
  SELECT @rownum := @rownum + 1 AS ranking
    FROM YOUR_TABLE t
    JOIN (SELECT @rownum := 0) r
ORDER BY t.value

Example:
  SELECT x.num,
         @rownum := @rownum + 1 AS ranking
    FROM (SELECT 30 AS num
          UNION ALL
          SELECT 85
          UNION ALL
          SELECT 90) x
    JOIN (SELECT @rownum := 0) r
ORDER BY x.num

You could use:
SELECT (SELECT COUNT(*)
          FROM YOUR_TABLE b
         WHERE b.value <= a.value) AS ranking
  FROM YOUR_TABLE a

...but duplicates would have the same ranking value.  And you have to make sure the value comparison is in the correct direction.

A: Try:
set @i = 0;
select myValue,
        @i:=@i+1 as Ranking
from myTable
order by myValue ASC


text:
Q: Calling an AJAX function declared as a VAR, using Applescript I am trying to run a javascript code inside a page using Applescript.
The AJAX function was declared in javascript using something like this
var myFunction = function () {
  // bla bla... here goes the code...
}

I have tried this in Applescript:
do JavaScript "document.myFunction()"

but the code is not running.
any clues? thanks.

A: Global variables are created as properties of the global object (window, for web browsers). Thus window.myFunction would be the proper reference. However, you don't need to specify the global object.
The key is that you must specify in AppleScript the target tab or document. For example:
tell application "Safari"
    do JavaScript "myFunction()" in current tab of window 1
end tell


text:
Q: javascript nested function variable scope I am using javascript to access the API of a database and this is one of my functions
function getAttrVal(ref, attrName)
{
    var result = "null"

    RM.Data.getAttributes(ref, attrName, function(result)
    {
        var attributes = result.data;

        attributes.forEach(function(attr)
        {
            var attrVal = attr.values[attrName];
            println("Check " + attrVal)   // here it is printing 'Check 5' which is correct since attrVal should equal '5'
            result = attrVal;
        });
    });

    return result;   // but here it returns the value 'null'
}

How do I get the variable 'result' to be 5 when it is returned.
It seems to be a variable scope issue.
TIA
Yes I am a dumb noob with javascript!

A: tldr; You're right it's a variable scoping issue.
You have 2 variables defined as result, one within the scope of your forEach iteration and one in the parent scope.
Try renaming the iteration variable:
function getAttrVal(ref, attrName){
    var result = "null";

    RM.Data.getAttributes(ref, attrName, function(_result)
    {
        var attributes = _result.data;

        attributes.forEach(function(attr)
        {
            var attrVal = attr.values[attrName];
            println("Check " + attrVal)   // here it is printing 'Check 5' which is correct since attrVal should equal '5'
            result = attrVal;
        });
    });

    return result;   // but here it returns the value 'null'
}


text:
Q: Find the present value of installment payments of \$1000 now, \$2000 at the end of the first year I was helping a comrade how to answer this engineering economics question. It goes like this:

Find the present value of installment payments of \$1000 now, \$2000 at the end of the first year, \$3000 at the end of second year, \$4000 at the end of the third year, \$5000 at the end of the fourth year, if money is worth 10% compounded annually.

My work
I thought the present worth is the future worth of money 4 years from now.
Using the basic formula $F = P(1+i)^n$, where $F$ is future worth, $P$ is the principal, $i$ is the interest rate, and $n$ is the number of years, we can answer the question using this approach:
When I pay now:
$$\$1000$$
When 1 year has elapsed, I pay $\$2000$ and my $\$1000$ was earning already.
$$\$2000 + \$1000(1+0.1)^1 = \$3100$$
When 2 years has elapsed, I pay $\$3000$ and my $\$2000$ and $\$1000$ was earning already.
$$\$3000 + \$2000(1+0.1)^1 + \$1000(1+0.1)^2 = \$6410$$
When 3 years has elapsed, I pay $\$4000$ and my $\$3000$, $\$2000$ and $\$1000$ was earning already.
$$\$4000 + \$3000(1+0.1)^1 + \$2000(1+0.1)^2 + \$1000(1+0.1)^3 = \$11051$$
When 4 years has elapsed, I pay $\$5000$ and my $\$4000$, $\$3000$, $\$2000$ and $\$1000$ was earning already.
$$\$5000 + \$4000(1+0.1)^1 + \$3000(1+0.1)^2 + \$2000(1+0.1)^3 + \$1000(1+0.1)^4 = \$17156.10$$
The present value of installment payments, therefore, would be:
$$\$1000 + \$3100 +\$6410 +\$11051 +\$17156.10 = \$38717.10$$
Is my answer correct? Is it any good?
Edit
Someone said that I just found the future value, not the present one. With that in mind, to get the present value, do this:
When I pay now:
$$\$1000$$
When 1 year has elapsed, I pay $\$2000$ and my $\$1000$ present value has changed already.
$$\$2000 + \frac{\$1000}{(1+0.1)^1} = \$2909.09$$
When 2 years has elapsed, I pay $\$3000$ and my $\$2000$ and $\$1000$ present value has changed already.
$$\$3000 + \frac{\$2000}{(1+0.1)^1} + \frac{\$1000}{(1+0.1)^2} = \$5644.63$$
When 3 years has elapsed, I pay $\$4000$ and my $\$3000$, $\$2000$ and $\$1000$ present value has changed already.
$$\$4000 + \frac{\$3000}{(1+0.1)^1} + \frac{\$2000}{(1+0.1)^2} + \frac{\$1000}{(1+0.1)^3} = \$9131.48$$
When 4 years has elapsed, I pay $\$5000$ and my $\$4000$, $\$3000$, $\$2000$ and $\$1000$ present value has changed already.
$$\$5000 + \frac{\$4000}{(1+0.1)^1} + \frac{\$3000}{(1+0.1)^2} + \frac{\$2000}{(1+0.1)^3} + \frac{\$1000}{(1+0.1)^4} = \$13301.34$$
The present value of installment payments, therefore, would be:
$$\$1000 + \$2909.09 +\$5644.63 + \$9131.48 + $\$1301.34$= \$31986.54$$
Is my answer now correct? Is it any good?

A: No, you want the present value.  What you have computed is the future value.
The present value can be thought of as the equivalent amount of money that would be paid up front as a lump sum, which has the same time value of money as the cash flow in question.
For example, if I say that $2000$ will be paid to you one year from now, and the effective annual rate of interest is $i = 0.1$, the present value of this payment is the amount which, if held by you over the same amount of time, would equal $2000$ at the end of one year.  That is to say, $$PV(1+i) = 2000,$$ or $$PV = \frac{2000}{1.1} \approx 1818.18.$$  It should be clear that for a positive interest rate, the longer the deferral of the payment, the less its present value, since you have to wait longer to receive it.  So for example, if I said that the same $2000$ will be paid to you in $10$ years from now, the present value is $2000/(1.1)^{10} \approx 771.09$.  That decrease in value is a reflection of the fact that you could take $771.09$ now and assuming a constant effective annual interest rate of $10\%$ per year, it would grow to $2000$ at the end of $10$ years if the interest is compounded annually.
With this understanding, try recomputing the present value of your cash flow.


text:
Q: Função em C que mova todos os zeros para esquerda, o restantes valores devem manter a ordem inicial (Ex.: 5,0,3,0,0,8,0,2 | result: 0,0,0,0,5,3,8,2) Isto foi o que consegui fazer; Está errado, claro
#include <stdio.h>
#define TAM 15

void zeros(int *v, int tam);

void main()
{
     int  v[TAM] = {3,4,0,2,0,5,6,0,0,7,9,1,0,0};

     zeros(v, TAM);
}

void zeros(int *v, int tam)
{
    int vet[TAM];
    int i,j;

    for(i = 0; i < tam; ++i)
    {
        if(v[i] == 0){
            vet[j++] = 0;
        }
    }

    for(i = 0; i < tam; ++i){
        if(v[i] != 0){
            vet[j++] = v[i];
        }
    }

    for(i = 0; i < tam; i++){
        printf("%d", vet[i]);
    }

}

Pretendo uma função simples tal como esta. Desde já agradeço

A: Percebi que o código apenas verifica os elementos que são 0 dentro do vetor, mas não realiza o swap (mudar o elemento 0 para esquerda) de maneira eficiente.
Código com os zeros para esquerda
O código abaixo que eu desenvolvi, ele faz uma verificação se o elemento do vetor é 0, e se for, é realizado um swap ou seja, ele troca de posição com o elemento que não é 0, e assim chegando no resultado que você deseja.
#include <stdio.h>
#define TAM 14

void swap(int *a, int *b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

void zeros(int *v, int tamanho)
{
    int i = 0;
    int count = tamanho - 1;
    for( i = tamanho - 1; i >= 0; --i){
        if(v[i] != 0){
            swap(&v[i], &v[count--]);
        }
    }
}

void main()
{
    int i;

    int  v[TAM] = {3,4,0,2,0,5,6,0,0,7,9,1,0,0};

    zeros(v, TAM);

    for(i = 0; i < TAM; i++){
        printf("%d - ", v[i]);
    }
}

Resultado
0 - 0 - 0 - 0 - 0 - 0 - 3 - 4 - 2 - 5 - 6 - 7 - 9 - 1 -


text:
Q: Why this DeleteView doesn't actually delete the entry in Django? In my Django app the delete view doesn't work. When I click on an entry the page just refreshes and nothing happens. The entry is not deleted from the database. Creating and updating entries works fine. Is there something wrong with any of the files?
microtarjetas/views.py:
class DeleteCardView(DeleteView):
   model = Card
   template_name = 'microtarjetas/delete_card.html'
   form_class = CardForm
   success_url = '/cards/'

templates/microtarjetas/delete_card.html:
{% extends 'base.html' %} {% load static %} {% block content %}

Delete card

Are you sure you want to delete "{{ object }}"?

<form method="post">{% csrf_token %}
       <input type="submit" value="Confirm" />
</form>
{% endblock %}

a snippet from templates/microtarjetas/cards.html:

           {% for card in cards %}

               {{ card.word_en }}
               {{ card.word_es }}
               update
               X

           {% endfor %}

forms.py:
from django import forms
from .models import Card

class CardForm(forms.ModelForm):
   class Meta:
       model = Card
       fields = "__all__"

models.py:
class Card(models.Model):
   word_en = models.CharField(max_length = 30)
   word_es = models.CharField(max_length = 30)

   def get_absolute_url(self):
       return "/cards"

   def __str__(self):
       return f"{self.word_en} --- {self.word_es}"

urls.py:
from django.urls import path
from . import views

urlpatterns = [
   path('', views.HomeView.as_view(), name='home'),
   path('cards/', views.CardsView.as_view(), name='cards'),
   path('cards/new', views.CreateCardView.as_view(), name='create_card'),
   path('cards/<pk>/delete/', views.DeleteCardView.as_view(), name='delete_card'),
   path('cards/<pk>/update/', views.UpdateCardView.as_view(), name='update_card'),
]

I add a {{ form }} tag to the delete_card.html form, it works (although it adds two input fields to the form which are unnecessary):
delete_card.html

A: You are not submitting the form with the form data. You should update the code like this:
<form method="post">{% csrf_token %}
       {{ form }}
       <input type="submit" value="Confirm" />
</form>

More information can be found in the documentation.


text:
Q: How do I get the frequency of my dictionary value as it changes? I am a novice, just started learning how to program.
I will to ask how do I get the frequency/count of a value changed within a key?
for instance:
user_input= input("Enter a word")

dict = {"Coffee": ["I love coffee."], "Tea": ["I love tea."]}

so if the user selects coffee, he/she can amend by adding or delete that value.
He/she is then able to view the number of time the key "coffee" is being amended.

I appreciate the prompt responses from everyone! But maybe this example below will be a little more comprehensive.

if user selects coffee, they can either have the option to delete or append new sentence to the existing key.
So for every value that is being deleted or added: it will be recorded
For example: If I will to change the Coffee's value, that will 1, thereafter, if I will to delete the Coffee's value again, it will be the 2nd time I have amend the value within coffee.
output: Revision changed on "Coffee" : 2

A: I'm not sure if I'm understanding your question correctly, but if I am, then an if statement should do the trick, every time the user picks coffee it'll add one to it's corresponding counter and same thing with tea, then you do whatever you want with those values:
user_input= input("Enter a word")

dict = {"Coffee": ["I love coffee."], "Tea": ["I love tea."]}

if user_input == "Coffee":
    coffee_amend += 1
if user_input == "Tea":
    tea_amend += 1

This is my first time ever responding to anything so please tell me if I did anything wrong; I hope you found this helpful!

A: First modify the structure of the dictionary that you are using like below:
dic = {"Coffee": [["I love coffee."],0], "Tea": [["I love tea."],0]}

As you can see I have maintained, the count of number of times changed and It value at the key.
Now make two functions for changing the value at a particular key and getting the count of number of times value changed at that particular key
def changeKeyValue(dic, key, value):
  dic[key][1] += 1
  dic[key][0] = value

changeKeyValue(dic,'Coffee',None)

def getNumTimes(dic,key):
  return dic[key][1]

Now use these functions to get the result you want :
print("Key value changed", getNumTimes(dic,"Coffee"))

Hope this helped.

A: I am assuming that you want something that interacts with the user. This is not super elegant but it is easy to understand:
dict = {"Coffee": ["I love coffee."], "Tea": ["I love tea."]}
cnt_dict = {}
cont = True
while cont == True:
    user_input = input("Enter a word")
    user_input2 = input('What would you like to do?')
    if user_input2 == 'delete':
        dict[user_input] = '' #sets the value to empty list
    if user_input2 == 'ammend':
        user_input3 = input('What would you like to change to?')
        dict[user_input] = user_input3
    if user_input in cnt_dict.keys():
        cnt_dict[user_input] += 1
    else:
        cnt_dict[user_input] = 1
    print(cnt_dict)
    input_4 = input('continue? (y/n)')
    if input_4 != 'y':
       cont = False

cnt_dict is a dictionary which counts the number of times each key is changed. Hopefully this helps. Edit: Obviously there will be problems if you are trying to add things not currently in dict but you can build off this.


text:
Q: Performing a two tailed test given a contingency table We have a contingency table with 2 rows and 4 columns, how would we test the null hypothesis that the observed count in column 1 is equal or larger than expected, as well as the observed count in columns 2,3,4 is equal or less than the expected?
Namely, we would like to use a two-tailed test instead of a classical one-tailed Fisher's exact or $\chi^2$ test.
I am thinking the possible situation like below
A random sample of 15 undergraduate students reported their sex (1=male, 2=female) and college (A=business, B=engineering, C=liberal arts, D=nursing, E=pharmacy). The results were sorted into cells where, for example, D2 would be the number of female nursing students (13). The results (with column and row totals) are displayed below.
T:
         A    B    C    D    E  total
1:  11    1    1    1    1    15
2:  13    4    1    1    2    21

For me, if I want to do a modified fishers' exact test, I may just need to calculate the following probabilities using hypogeometric distribution,
P1:
        A    B    C    D    E  total
1:  11    1    1    1    1    15
2:  13    4    1    1    2    21

P2:
        A    B    C    D    E  total
1:  12    1    1    1    0    15
2:  13    4    1    1    2    21

P3:
        A    B    C    D    E  total
1:  13    1    1    0    0    15
2:  13    4    1    1    2    21

P4
        A    B    C    D    E  total
1:  14    1    0   0    0    15
2:  13    4    1    1    2    21

    A    B    C    D    E  total

P5
1:  15    0    0    0    0    15
2:  13    4    1    1    2    21

It seems to me that the significance of the contingency table T is the sum up probability of p=P1+P2+P3+P4+P5, if this p is very small, we can accept that the count in column 1 is unexpectedly high and the count in other column is unexpectedly low, right?
Does the above calculation is the same with the fisher's exact test for 2*4 table?


text:
Q: Vlookup checking for multiple values and adding them together I have a table called "data" that has a bunch of data with dates and IDs along with 2 return values(we can call A and B) and a value for the number of hits(C)
I wrote this script:
=IF(ISNUMBER(VLOOKUP(F$1&$A4&"1"&"0",data!$A:$F,6,FALSE)+VLOOKUP(F$1&$A4&"0"&"0",data!$A:$F,6,FALSE)),VLOOKUP(F$1&$A4&"1"&"0",data!$A:$F,6,FALSE)+VLOOKUP(F$1&$A4&"0"&"0",data!$A:$F,6,FALSE),0)

My current formula adds and returns the approiate value only if both A=1 and B=0 and A=0 and B=0 values are found. If only A=1 and B=0 is found or only A=0 and B=0is found then it will just return 0.
I want to check the data table and return all values(C) that have either A=1 and B=0 or A=0 and B=0 for that specific date and ID number. I also want to add the values together. How can I edit my formula to do this?


text:
Q: Any Hosted CI service that natively support JUnit XML reports? Does anyobdy know a good solid CI service that provides the common features of build parallelization BUT also support for Junit reports?
The current ones that we have looked at (semaphoreapp, circleCI, travisCI,...) are good but relatively useless as we have to manually investigate what tests failed, since when, and how often, thus negating a lot of the benefits of a hosted service.
Things that we're looking to know (and are all provided by JUnit / Jenkins):

*

*If the build failed, because of what test cases?

*Total Number of Failures / Total Number of Tests (trends to better analyze things)

*Individual Track record of any test (so we know exactly when it was broken, whether it's intermittent,...)

A: You mentioned the most famous CI services but there are alternatives where you can get a higher customization level, like installing plugins, fine configuration, etc.
CloudBees and ClinkerHQ are both based on Jenkins offered as a service. You can also get very useful metrics (coverage, failures, graphs, execution times, etc.) thanks to Jenkins Plugins and SonarQube. I think Jenkins and SonarQube are a perfect couple for you.
Notifications are very important too. You want to be notified when something is wrong. This feature is available on both.
Regards,
Antonio.
DISCLAIMER: I'm deeply involved in ClinkerHQ


text:
Q: Comparing numbers in form $x^y$ Let's consider two numbers in form $x_1^{y_1}$ and $x_2^{y_2}$
How can we compare those two numbers without evaluating them ?
Can we use logarithms to check it ? If yes - how ?
Thanks in advance.
P.S It's not my homework :)

A: Yes, we can. The key is that
$$\log_b a = \frac{\log_{b'} a}{\log_{b'} b}$$
and that taking logarithms of positive numbers (I assume you're working with positive $x_1,x_2$) with respect to the same base preserves inequalities. Thus we can take $\log_{x_1} x_1^{y_1} = y_1$
and
$$\log_{x_1} x_2^{y_2} = \frac{\log_{x_2} x_2^{y_2}}{\log_{x_2} x_1} = \frac{y_2}{\log_{x_2}{x_1}}$$
and compare these two numbers instead, which is easier.

A: Let's assume $x_i > 1$ and $y_i > 0$, because other cases can be handled analogously (just be careful when negatives crop up).  Certain cases are easy.  If both $x_1 \geq x_2$ and $y_1 \geq y_2$, then $x_1^{y_1} \geq x_2^{y_2}$.  The more interesting cases occur when there is a mixed relationship, such as $x_1 \leq x_2$ and $y_1 \geq y_2$. In fact, let's assume the latter two inequalities and consider the following:
$$\begin{align*}
  x_1^{y_1} &\geq x_2^{y_2} \\
  &\Leftrightarrow \\
  \log_{x_1} x_1^{y_1} &\geq \log_{x_1} x_2^{y_2} \\
  &\Leftrightarrow \\
  y_1 &\geq y_2 \log_{x_1} x_2
\end{align*}
$$
Without doing much calculation, we may be able to bound $\log_{x_1} x_2$ by two consecutive integers (recall, that $\log_{x_1} x_2$ is the exponent that when applied to $x_1$ results in the value $x_2$).  So, if we know that $n \leq \log_{x_1}x_2 \leq n+1$, it's easy to multiply $y_2$ by $n$ or $n+1$ and compare to $y_1$.  Unfortunately, if $y_1$ is very close to $ny_2$, we may not have a fine enough estimate to make the decision about the inequality.  In that event, you may have to use a calculator anyway.

A: Take logarithms.
If $\log(x_1^{y_1})>\log(x_1^{y_1})$ i.e. $y_1\log(x_1)>y_2\log(x_2)$, then $x_1^{y_1}>x_2^{y_2}$ and vice versa.


text:
Q: .htaccess and filtering $_GET Hello I am writing a profile page script, in this script I check the value of an incoming $_GET variable and validate that it is an integer, I then validate this value against a $_SESSION value to confirm that they can only access their own accounts. The code looks like this:
// validate $_GET field
if(isset($_GET['identity']) && filter_var($_GET['identity'], FILTER_VALIDATE_INT, array('min_range' => 1))) {

if(isset($_SESSION['user_identity']) && ((int)$_SESSION['user_identity'] === (int)$_GET['identity'])) { // if session exists and is === $_GET['identity']
// Proceed with code

This works fine for instance if I try to pass '0','2-2','abc' or no value as the $_GET value the query correctly fails and redirects them to the home page.
What I then tried to do was alter my .htaccess file to map the URLs to 'profile/1' just to tidy it up.
RewriteRule ^profile$ profile.php
RewriteRule ^profile/([0-9]+)$ profile.php?identity=$1 [NC,L]

What I found now is that the page doesn't redirect any more using those invalid $_GET parameters above. It just tries to find 'profile/abc.
Does anyone know why?

A: I use this and it works for me:
RewriteEngine On
RewriteBase /
RewriteRule ^profile$ profile.php
RewriteRule ^profile/([a-z0-9\-]+)$ profile.php?identity=$1 [NC,L,QSA]

Now, how did you get profile/abc? if you try to pass letters in the rule it wont work since you only specify numbers ([0-9]+). If you want to pass letters you will need to use:
RewriteRule ^profile/([a-z0-9\-]+)/?$ profile.php?identity=$1 [NC,L,QSA]


text:
Q: Postgres SQL: INSERT from DELETE I have a table with id,user_id,timestamp and I'm trying to INSERT into the table, the user_id from a DELETE from table where id=some_number and timestamp. So what I'm trying to achieve looks like:
INSERT INTO table (user_id,timestamp)
VALUES (
    (DELETE FROM table WHERE id=some_number returning user_id),
    current_timestamp+'1 day'
)
RETURNING *;

I am getting a syntax error doing this... Can someone help me here plz...?

A: You can use a data modifying common table expression:
with deleted as (
  DELETE FROM some_table
  WHERE id = 42
  returning user_id
)
INSERT INTO other_table(user_id, "timestamp")
select user_id, timestamp '2020-01-04 21:32:34'
from deleted;


text:
Q: Get memory type and speed without sudo On CentOS, lshw and dmidecode can tell you memory type (e.g. DDR3) and speed but need sudo or root.
Looks like /sys/devices/system/edac/mc/mc*/dimm*/dimm_mem_type has the memory type info but not the speed. Docs.
Is there a way of getting this same info (memory type and speed) without sudo? E.g. via /sys?

A: The memory speed information is only available from DMI.  It's easy to confirm that when lshw looks up the information, it's grabbing it via DMI.  Even when run as root, lshw -short -C memory -disable dmi without DMI only knows the total memory.
That means this question is really rephrasing how to get DMI decoding without root.  Two relevant sources:

*

*How to get dmidecode information without root privileges?

*https://savannah.nongnu.org/support/?109063
To summarize the ideas in those two:

*

*"If you want to let non-root users access all the DMI information, you could change the permissions of files under /sys/firmware/dmi/tables to 444 (or set the group to something meaningful for your system, and set the permissions to 440) in some init script."

*You can fight with sudo to grant access to dmidecode/lshw.

*If you can alter system startup you could have an init script output the DMI info to a text file somewhere.

But if you don't have some cooperation with root, there is no way to find this out.


text:
Q: Is Create Spatial Type necessary When I enable an enterprise geodatabase for a database in postgresql, the st_geometry type get installed with it. So Is it necessary to use "Create Spatial Type" tool to create st_geometry type in postgresql again?
One benefit of this tool is to upgrade existing st_geometry type. But for a fresh install, is it necessary?

A: It is never necessary to use Create Spatial Type on a properly configured enterprise geodatabase.
Create Spatial Type is a limited subset of Enable Enterprise Geodatabase, where only the SDE.ST_GEOMETRY datatype is wanted. Quoting the documentation (emphasis mine):

This allows you to use the ST_Geometry SQL type to store geometries
  in a database that does not contain a geodatabase

Your "benefit" is an unsupported use pattern, which might cause corruption of a geodatabase (preventing function when in a hybrid state and/or proper upgrade).  I strongly discourage the use for this purpose.
In fact, I've only had one case where I needed to use Enable Enterprise Geodatabase (and that was on Oracle); at all other times I've used Create Enterprise Geodatabase (after creating the database exactly as I wanted it with createdb, createuser, and psql -- the "Create" tool skips unnecessary steps).


text:
Q: GIS analysis to find duplicate geometries I have a big shapefile that contains all the buildings and houses of the town that I work in (approx. 90,000 features). The data of the buildings/houses are saved by the town's surveying engineers and due to bad practice and the access of different surveyors to that data, many buildings/houses have been saved twice and show up in the map as duplicates.
Some of them are exactly duplicated (they appear one over the other) while others are duplicated with a space between the two objects (like one object is inside the other - see the attached screen shot).

I want to clean that data so that I have only the correct buildings/houses in the town so my question is:
Is there any GIS analysis or SQL expression that I can run to find all the duplicated features (both the exact ones and the ones that are located inside others)? I have both ArcGIS and QGIS so I am open to all your suggestions.

A: I would use Python's itertools and a SearchCursor for a very efficient way to find the spatial relationships you are after.  You can incorporate the geometry methods overlaps, contains, and equal to get at the geometry properties.

*

*Start off by creating a function to better organize the workflow and
for repeatability
def findOverlaps(x):

*Open a search cursor to loop over individual feature geometry
with arcpy.da.SearchCursor(x, ['OID@', 'SHAPE@']) as cur:

*use itertools.combinations() to return subsequences of elements
from the input iterable cur
for feature1,feature2 in itertools.combinations(cur, 2):

*Access the geometry properties with the following methods:
equals(), overlaps(), and contains().  These are set-up in a
logical sequence--you can tweak this to meet your specific
objectives if necessary.
    if feature1[1].equals(feature2[1]):
        print "{} equals {}".format(feature1[0],feature2[0])
    if feature1[1].overlaps(feature2[1]):
        print "{} overlaps {}".format(feature1[0],feature2[0])
    if feature1[1].contains(feature2[1]):
        print "{} contains {}".format(feature1[0],feature2[0])

*Run it...
enter code herefindOverlaps(fc)

import itertools, arcpy

fc = r'C:\path\to\your\fc'

def findOverlaps(x):
    with arcpy.da.SearchCursor(x, ['OID@', 'SHAPE@']) as cur:
        for feature1,feature2 in itertools.combinations(cur, 2):
            if feature1[1].equals(feature2[1]):
                print "{} equals {}".format(feature1[0],feature2[0])
            if feature1[1].overlaps(feature2[1]):
                print "{} overlaps {}".format(feature1[0],feature2[0])
            if feature1[1].contains(feature2[1]):
                print "{} contains {}".format(feature1[0],feature2[0])

findOverlaps(fc)

The screenshot shows a variety of features that are overlapping, overlapping & identical, and unique.

A: in QGIS, Topology Checker plugin can propably solve your problem

A: You can do this in SQL using a spatial self join. You don't state which SQL dialect you are using, so this example uses Postgres/Postgis, but it could be easily adapted to Oracle or SQL Server. Assuming a table called buildings, with geometry stored in a column called geom:
SELECT a.id, b.id from buildings a, buildings b WHERE
  ST_INTERSECTS(a.geom, b.geom) AND a.id < b.id;

This will find the intersects. If you want total equality then replace ST_Intersects with ST_Equals. Or, just combine the two:
SELECT a.id, b.id from buildings a, buildings b WHERE
   (ST_INTERSECTS(a.geom, b.geom) OR ST_EQUALS(a.geom, b.geom))
   AND a.id < b.id;

Note, the a.id < b.id means that you only consider half the cases in the self join, which makes it a) faster and b) gives you a list you can use to delete half of the overlapping polygons without deleting them all. Clearly, this is still an O(n²) algorithm, but in practice, will be a lot quicker if you have a spatial index in place -- which is really a total requirement for any non-trivial data set.
You might need to massage this a little bit to fit some definition of overlapping -- you don't want to delete neighboring houses that have been badly surveyed.

A: I have an idea what may work for you.  It is going to be based off some assumptions, but it would help narrow down your list of possible identical features.  This would not be an automated process, but it would require manually looking at the duplicates.  Based off the comments, it seems like the automated tools don't compare attributes so this would help you not accidentially delete features.
Using ArcMap
(1) Make a copy of your shapefile in case things go wrong.
(2) Add a column to your shapefile as a double.
(3) Calculate area for each feature using the most descriptive (most precise) format you can.  Something where rounding may not be an issue.
(4) Run a summary (summarize) on that column.  Make sure you select a unique identifier in the summarize and mark both first and last.
(5) In your output table, look for those records where the count field is higher than 1.
(6a) Manually check the features and repeat the process until there are no more duplicates.
(6b) You could just create a list of those unique ids and delete the features through arcpy, but you run the chance of possibly having two unidentical features with the same area.
Another Technique Using ArcPy
As I was constructing the above answer, I thought of the possibility that somehow the multiple authors of this data may have actually used the same unique identifiers for duplicated features.  IF that is the case, you may be able to find duplicates through looping in arcpy.
The way I would think about doing this using ArcPy could be taxing on your system and take a little bit.
(1) Make a copy of your shapefile (in case again)
(2) Add a new column to denote duplicates.  Something that takes like a 'y' or 'n' or 0 or 1 or whatever would work.
(3) Create a list in python to store the unique identifier.
(4) Run an Update Cursor (arcpy.UpdateCursor('LAYERNAME')).  For each record, check you list to see if it contains that identifier and mark your column for duplicates if it is there.
myList = []
rows = arcpy.UpdateCursor("layername")
for row in rows:
  if str(row.UniqueIdentifier) in myList:
    #value duplicated
    row.DuplicateColumnName = "y"
  else:
    #not there, add it
    myList.append(row.UniqueIdentifier)
  rows.updateRow(row)

(5) Then you can compare or do whatever you want with those marked columns.
There are probably better ways to do these comparisons, but those are two that I believe should work or at least get you started.
Edit
Based on the comment by elrobis, you could utilize the minimum bounding rectangle to further decrease the chance of removing incorrect features.
Using ArcMap, you can run the Minimum Bounding Geometry tool in Data Management.  After checking over the options, I think using the CONVEX_HULL option would probably be best.
If you compare the MBG_APodX/Y1, MBG_APod_X/Y2 fields along with MBG_Orientation for duplicates, you should be able to get a good idea of duplicated features.  I would suggest using the Summarize method I described above to compare.  Pick one of the vertices (coordinates) from the bounding rectangle to find duplicates.  You may get a few incidental 'matches', but once you add in the other vertices plus orientation, it would be a fairly safe bet that the results features are duplicates.
Although I haven't used it and am not quite sure of the results from this tool, you might find examining the resulting shapefile easier if you used the Summary Statistics tool in ArcMap.  It looks like you can summarize multiple columns that way instead of my single column option.
I don't think there would be a completely automated way of doing this without having the worry of possibility deleting a not duplicate feature.  These methods should help limit the number of features you would need to manually review though.

A: The Topology Checker plugin is a good tool if used correctly. You still have to have a fundamental understanding of your data AND you have to make the 'corrections' manually. The plugin will highlight what it thinks are errors. It is up to you to then examine each and make the appropriate decision for you and your data. With 90 000 items in your layer, you may be home by Christmas!

A: In QGIS you can create a Virtual Layer with the query:
select a.id, a.geometry
from yourlayername a
join yourlayername b
on st_equals(a.geometry, b.geometry)
where a.id<b.id

Which will join the layer to itself where the geometries are the same but have different id's


text:
Q: Mysql query to delete woocommerce products in certain category We need to delete ~20.000 products that are in a certain category. We would like to do that by mysql directly.
With that query, all products get deleted:
DELETE FROM wp_term_relationships WHERE object_id IN
(SELECT ID FROM wp_posts WHERE post_type IN ('product','product_variation'));
DELETE FROM wp_postmeta WHERE post_id IN (SELECT ID FROM wp_posts WHERE post_type IN
('product','product_variation'));
DELETE FROM wp_posts WHERE post_type IN ('product','product_variation');

How can we just delete products inside category XY?
Thanks for help

A: Here's an example of a query...
SELECT r*
     , p.*
     , m.*
  FROM wp_term_relationships r
  JOIN wp_posts p
    ON p.id = r.object_id
  JOIN wp_postmeta m
    ON m.post_id = p.id
 WHERE p.post_type IN ('product','product_variation');


text:
Q: PyQt5, как получить источник enterEvent? В приложении, написанном на Python с использование PyQt5 есть кнопка.
someButton = QPushButton(objectName='button1')

На эту кнопку назначен ивент enterEvent, срабатывающий когда курсор наводится на эту кнопку
def some_func(event):
    print('Some text')

someButton.enterEvent = some_func

Но что если таких кнопок несколько и я хочу получить информацию о том, какая кнопка послужила триггером ивента? Если бы это был сигнал вроде clicked, то я мог бы легко получить такое.
def some_func():
    print(self.sender())

someButton.clicked.connect(some_func)

Но для enterEvent такое не работает, self.sender() возвращает None
Может виджет-триггер можно как-то получить из event, или же как-то иначе подключить enterEvent?
Желательно без переопределения кнопки в отдельный класс.

A: У вас есть два варианта.
Согласно документации:

[virtual protected] void QWidget::enterEvent(QEvent *event)
Этот обработчик событий может быть повторно реализован в подклассе
для приема событий вxода в виджет, которые передаются в параметре события.
Событие отправляется виджету, когда курсор мыши входит в виджет.

from PyQt5.Qt import *

class Button(QPushButton):
    def __init__(self, num):
        super().__init__()

        self.setText(f"Кнопка {num}")
        self.setObjectName(f"button{num}")

    def leaveEvent(self, event):
        print(f'leaveEvent: {self.text()}')

    def enterEvent(self, event):
        print(f'enterEvent: {self.text()}')

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        layout = QVBoxLayout(self)

        for i in range(5):
            btn = Button(i+1)
            layout.addWidget(btn)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Другой вариант, который используется в практике - это установка фильтра событий.

void QObject::installEventFilter(QObject *filterObj)
Устанавливает фильтр событий filterObj на этот объект.

from PyQt5.Qt import *

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        layout = QVBoxLayout(self)

        for i in range(5):
            btn = QPushButton(f"Кнопка {i+1}", objectName=f"button{i+1}")
            btn.installEventFilter(self)
            layout.addWidget(btn)

    def eventFilter(self, obj, event):
        if event.type() == QEvent.Leave:
            print(f'QEvent.Leave: obj={obj.text()}, {obj.objectName()}')
            return True
        elif event.type() == QEvent.Enter:
            print(f'\nQEvent.Enter: obj={obj.text()}, {obj.objectName()}')
            return True

        return super().eventFilter(obj, event)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

A: В этом случае на помощь к вам придет lambda:
def func(event: QEnterEvent, sender: QPushButton):
    print('Event:', event)
    print('Sender:', sender.text())

if __name__ == "__main__":
    app = QApplication([])
    # ...

    button = QPushButton("Button 1")
    button.enterEvent = lambda e, btn=button: func(e, sender=btn) # Можно и без sender=, но для наглядности
    button.show()

    button = QPushButton("Button 2")
    button.enterEvent = lambda e, btn=button: func(e, sender=btn)
    button.show()

    button = QPushButton("Button 3")
    button.enterEvent = lambda e, btn=button: func(e, sender=btn)
    button.show()

    button = QPushButton("Button 4")
    button.enterEvent = lambda e, btn=button: func(e, sender=btn)
    button.show()

    sys.exit(app.exec_())


text:
Q: Determine all probability distributions

Let $(\mathbb{N}_0,\mathcal{P}(\mathbb{N}_0),\mathbb{P})$ be a probability space and $A_k:=\left\{k,k+1,k+2,\ldots\right\}$ for $k\in\mathbb{N}_0$. Assume that
    $$
\mathbb{P}(A_{k+l}|A_k)=\mathbb{P}(A_l)~~~\text{for all}~~~k,l\in\mathbb{N}_0.
$$
    Determine all probability distributions $\mathbb{P}$ on $\mathcal{P}(\mathbb{N}_0)$ with this property.

I did not find a real understanding to this task. Can you give me some help how to start this task?
Of course I made some efforts, which lead me to:
$$
\mathbb{P}(A_{k+l}|A_k)=\frac{\mathbb{P}(A_{k+l}\cap A_k)}{\mathbb{P}(A_k)}=\mathbb{P}(A_l)~~~\Leftrightarrow~~~\mathbb{P}(A_{k+l}\cap A_k)=\mathbb{P}(A_k)\mathbb{P}(A_l).~~~~~(*)
$$
For $l=0$ it is $\mathbb{P}(A_{k+l}\cap A_k)=\mathbb{P}(A_k)$, so that $(*)$ says that $\mathbb{P}(A_l)=1$.
For $l>0$ it is $\mathbb{P}(A_{k+l}\cap A_k)=\mathbb{P}(A_{k+l})$, so that $(*)$ says that $\mathbb{P}(A_{k+l})=\mathbb{P}(A_k)\mathbb{P}(A_l)$.
Furthermore, the usual properties of a probability measure have to be fullfilled, i.e. $\mathbb{P}(\emptyset)=0$, $\mathbb{P}(\mathbb{N}_0)=1$, $\mathbb{P}\left(\biguplus_n B_n\right)=\sum_n \mathbb{P}(B_n)$ for disjoint $B_n\in\mathcal{P}(\mathbb{N}_0)$.
But to be honest, I do not know how to use this... or if this is the right beginning...

A: Let write $A_k$ as $(X\geq k)$, since that's a more normal way of writing it.  Then the statement we're given is
$$P(X \geq k + \ell \; |\; X \geq k) = P(X \geq \ell).$$
We can rewrite this as
$$P(X \geq k + \ell) = P(x \geq \ell)\,P(X \geq k)$$
Write $p_i$ for $P(X = i)$.  Then
$$P(X \geq k) = 1 - p_0 - p_1 - \cdots - p_{k-1}$$
so the previous expression becomes
$$(1 - p_0  - \cdots - p_{k+\ell-1}) = (1 - p_0  - \cdots - p_{k-1})(1 - p_0  - \cdots - p_{\ell-1})$$
Take $\ell = 1$:
$$(1 - p_0  - \cdots - p_{k}) = (1 - p_0  - \cdots - p_{k-1})(1 - p_0)$$
You should be able to see what to do from there.

A: Let $a=P(A_1)$, then $a$ is in $[0,1]$ and $P(A_{k+1}\mid A_k)=a$ for every $k$, which, since $A_{k+1}\subset A_k$, implies $P(A_{k+1})=aP(A_k)$ for every $k$. An easy induction shows that $P(A_k)=a^k$ for every $k\geqslant0$, hence $P(\{k\})=(1-a)a^k$ for every $k\geqslant0$ since $\{k\}=A_k\setminus A_{k+1}$. The sequence $(A_k)$ is nonincreasing with intersection $\varnothing$ hence $P(A_k)\to P(\varnothing)=0$ when $k\to\infty$, that is, $a$ is in $[0,1)$. Finally:

If $P(A_1)=0$, $P(\{0\})=1$ hence $P$ is the Dirac measure at $0$. If $P(A_1)$ is in $(0,1)$, $P$ is the geometric distribution with parameter $a$. And $P(A_1)=1$ is impossible.


text:
Q: is this efficient MYSQL Query? I'm using vbulletin 5 and getting message from the host that MYSQL Query was killed because it was running over 1 minutes .. I looked at the query and feel there is something wrong with it .. though I don't have enough experience to judge
here is the query ..
SELECT DISTINCT node.starter AS nodeid
  FROM node as node
    JOIN closure AS closure ON node.nodeid = closure.child
    LEFT JOIN node AS starter
      ON starter.nodeid = IF(node.starter = 0, node.nodeid, node.starter)

  WHERE node.contenttypeid <> 19
    AND node.contenttypeid IN ('22','26','23','21','20','25')
    AND closure.parent = '2'
    AND node.nodeid <> closure.parent
    AND node.contenttypeid <> '15'
    AND node.userid <> '28030'
    AND (node.public_preview = 1
      OR
        (
          (
            (
              (
                starter.parentid IN (1,2,3,6,13,14,15,16,17,18,19,20,21,22,23,24,25,26,247197,257065,7,8,9,12,51,59,62,27,32,33,36,44,45,50,35,34,37,38,39,40,61,60,57,43,42,46,47,28,29,30,31,41,48,49,52,53,54,55,56,58,63,65,64,247199,247200,66)
              )
              AND node.showapproved > 0
              AND node.viewperms > 1
              AND node.showpublished > 0
            )
          )
        OR starter.parentid = 9 AND node.userid IN (0)
      )
    )

  ORDER BY node.lastcontent DESC,node.nodeid ASC
  LIMIT 500


text:
Q: Python performing t-test only on pairs hi a while back i got help to make this function, but im royally stuck now.
        from scipy.stats import ttest_ind
    def input_file_to_dict(f):
            return dict((key, int(value)) for value, key in map(lambda line:line.split(), f))

    with open("count-pos.txt") as f:
            word_counts1 = input_file_to_dict(f)

    with open("count-neg.txt") as f:
            word_counts2 = input_file_to_dict(f)

find all words that are in list1 and in list2
    out = open('t-test_output.txt', 'w')
    common_words = set.intersection(set(word_counts1.keys()),    set(word_counts2.keys()))
    for line in common_words:

        t,p = ttest_ind([word_counts1[k] for k in common_words], [word_counts2[k] for k in common_words])

        print >> out, (t,p)

As one can see Im trying to compare two lists that contain frequency of words, however some words dont appear in both sample sizes. I wish to perform a t-test on each word pair, to determine their variance. However,
This is giving me the same t-value and p-value pair over and over again.
Anyone got some ideas?
Example files look like this:
count-pos.txt
529 the
469 want
464 it
449 de

A: This line is calculating the same values each time in your loop because you pass in the counts for all common_words every time:
t,p = ttest_ind([word_counts1[k] for k in common_words], [word_counts2[k] for k in common_words])

Do you need to loop through all the common_words?


text:
Q: Reading a Google Spreadsheet into Ruby Objects (or settle for a file download) I think it's probably simplest to start with my use case:
I'm trying to read the contents of a Google Spreadsheet into ruby, and then use that data for other purposes. This needs to happen server-to-server.
Here's what I've tried:

*

*First I tried to use this google drive gem. Since my interaction needs to be server to server (i.e. a service account), I couldn't get this to work (someone please let me know if they've managed this!)

*Next, I tried using the latest google-api-ruby gem, and, following its documentation, was successfully able to authenticate my service account, and have been able to get lists of files, etc. So basically the API is authenticated and working.

The latest issue is that Google Spreadsheets can't be downloaded using the normal download_dest parameter on the get_file method (sorry - would post links to relevant documentation here, but don't have enough rep to do so). So I'm not really sure how to proceed with downloading the relevant file (I understand how to get an export_link), but have no clue how to then prepare the next request).
Any help would be greatly appreciated :)
Here's some basic code for reference -
require 'googleauth'
require 'google/apis/drive_v2'

scopes = ['https://www.googleapis.com/auth/drive']
ENV["GOOGLE_APPLICATION_CREDENTIALS"] = 'path/to/my/creds.json'
auth = Google::Auth.get_application_default(scopes)

drive = Google::Apis::DriveV2::DriveService.new
drive.authorization = auth

ss = drive.get_file('my_spreadsheet_id')
export_url = ss.export_links
# what now?