text:
Q: How do I update a single record from an spl server 2012 datatable using a c# datareader and a stored procedure? I need to know how to update a single record from a sql server 2012 datatable using c# datareader and a stored procedure. I already have a stored procedure that allows me to update a single record in my datatable. I just can't figure out how to use a c# data reader to update a record in the datatable. For example, say I have a female student in a college class I'm teaching and she gets married, I would need to select her record from my student info datatable and change her last name to her new married name. Thanks in advance for your help.

A: A DataReader is disconnected, read-only. That's why there aren't any methods for updating its values.
You said you have a stored procedure for updating. To execute that you would create the SqlConnection and SqlCommand and add parameters just as you do when you execute the command that generates the SqlDataReader. But instead of calling ExecuteReader() you would typically call ExecuteNonQuery(). That's used for executing a query that doesn't return results. It returns the number of updated rows.

A: You don't need to use DataReader in updating a record in SQL Server. Hence using stored procedure, you just have to declare a parameter in your stored procedure and pass a value to that parameter in C# like so:
CREATE PROCEDURE [dbo].[StoredProcedureName]
    @SOMEPARAMETER AS VARCHAR(50)
AS
BEGIN
    UPDATE tableName
    SET ColumnFromTable = @SOMEPARAMETER
    WHERE !--YourConditionGoesHere
END
GO

And in C# to pass the parameter do it like this:
using(SqlConnection con = new SqlConnection("connectionSTringHere")
{
   SqlCommand cmd = new SqlCommand("StoredProcedureName",con);
   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.Add("@SOMEPARAMETER",SqlDbType.VarChar).Value = "SomeValue";
   cmd.ExecuteNonQuery();
}


text:
Q: How to add Application Insights to existing QnAMaker app I have an existing QnAMaker app which presumably was created without AppInsights. I need to add one to get some logs and analytics.
How can I do this?

A: You should configure it via the related webapp.
If your QnAMaker app's name is myapp1, and you should find the related azure webapp named myapp1, then in the Configuration -> Application settings, add the 3 settinigs:
UserAppInsightsAppId / UserAppInsightsKey / UserAppInsightsName.
For the value of UserAppInsightsAppId, please follow this doc.
For the value of UserAppInsightsKey, please follow this doc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change default SharePoint web page I have an app running on top of sharepoint.
Can I change, through configuration, the default web page for a Sharepoint site to a sub-site page? I tried changing it in IIS but it simply doesn't work: The current default page isn't mapped there, anyway.
I would like to change it from "http://server/default.aspx" to, say, "http://server/test/default.aspx".
Edit: I am using SharePoint 2007

A: Editing the web.config file with these lines (under system.web):
<urlMappings enabled="true">
     <add url="~/" mappedUrl="/test/default.aspx"/>
</urlMappings>

did the trick.

A: A specific sharepoint version would help for more specific commentary, but this would be configured in the SP Siite Admin interface, not directly in IIS.


text:
Q: Custom unpickler for Enumeration I have an enumeration that I'm trying to pickle and unpickle with pickling 0.8.0 and scala 2.11:
object CommandType extends Enumeration {
  val Push, Pop = Value
}

Pickling cannot do it automagically at the moment. The custom pickler-unpickler looks like this:
class CommandTypePickler(implicit val format: PickleFormat)
  extends SPickler[CommandType.Value] with Unpickler[CommandType.Value] with LazyLogging {

  def pickle(picklee: CommandType.Value, builder: PBuilder): Unit = {
    builder.beginEntry(picklee)
    builder.putField("commandType", b =>
      b.hintTag(stringTag).beginEntry(picklee.toString).endEntry()
    )
    builder.endEntry()
  }

  override def unpickle(tag: => FastTypeTag[_], reader: PReader): CommandType.Value = {
    val ctReader = reader.readField("commandType")
    val tag = ctReader.beginEntry()
    logger.debug(s"tag is ${tag.toString}")
    val value = stringUnpickler.unpickle(tag, ctReader).asInstanceOf[String]
    ctReader.endEntry()

    CommandType.withName(value)
  }
}

Serialized enumeration:
{
  "tpe": "scala.Enumeration.Value",
  "commandType": {
    "tpe": "java.lang.String",
    "value": "Push"
  }
}

When unpickling, this throws the following: ScalaReflectionException: : class scala.Enumeration.Value in JavaMirror with sun.misc.Launcher$AppClassLoader@5c3eeab3 of type class sun.misc.Launcher$AppClassLoader with classpath ... not found. What am I doing wrong?


text:
Q: How does this arrays length equal 10? Sorry if this is a stupid question, I'm new to programming and I just don't get this.
I know an array is 0 indexed, but I still don't understand how this code gives me 10.

var array = [];
array[3] = "Hello";
array[9] = "Goodbye";

console.log(array.length);

A: See MDN:

The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

For this situation, the first sentence is a bit misleading, but the second isn't. The largest array-index property that the array object has is 9, so the .length of it is 10 (9 + 1).
What you have there is a sparse array, but sparse arrays are very odd and have numerous unintuitive behaviors (like this one) - they should probably be avoided in almost all cases. To avoid having a sparse array, when assigning to a particular index of an array, make sure that every array index below it also has been assigned a value. (Eg, don't assign to [2] unless [1] and [0] have also had values assigned to them)
If you want to associate arbitrary numbers with data, but using an array would result in it possibly being sparse, then use an object instead, eg
const wordsByNumber = {
  3: 'Hello',
  9: 'Goodbye'
};

A: var array = [];
array[3] = "Hello";
array[9] = "Goodbye";

console.log(array.length);

Now, you have var array = [undefined, undefined, undefined, "Hello", undefined, undefined, undefined, undefined, undefined, "Goodbye"] which means there are now 10 values in your array (most of them being undefined since you skipped indexes).


text:
Q: ActiveX component can't create object occurred in w3wp.exe I am currently having an issue with a classic ASP application I am working on and from what I can tell it might be due to something related to IIS.
It started out with me getting the error:
"An unhandled exception ('ActiveX component can't create object') occurred in
w3wp.exe[XXXX]."

I tried googling, but failed to find anything that could solve my issue.
So I tried to create a small .vbs application. To see if it had anything to do with the component that is used for the "createObject()" method.
dim test
set test = createObject("System.Collections.Sortedlist")
test.add 1, "value 1"
test.add 2, "value 2"
MsgBox(test(1))

And the file ran as it should.
I've tried running the application using both Visual Studio 2015 and 2017.
After I noticed that it sad "Occurred in the w3wp.exe" I tried reinstalling IIS to see if that would change anything, but sadly it has not had any effect.
Update: I am using Windows 10 personally and running the site of my own PC for testing purposes.
"Access Denied" errors and applications with COM activation fail after installing July 2018 Update


text:
Q: Why does a ball when bounced at an angle not come back to you? Say we have a ball. We throw it at the wall at an angle. The ball hits the wall with a force and a direction away from you. The wall then applies a force equal in magnitude and opposite in direction. So the direction was away from you at an angle and now the opposite of that should be back at you right? Then why does the ball bounce off with the same angle on the other side of the perpendicular like a ray of light. Am I missing something here?

A:
The ball hits the wall with a force and a direction away from you. ... the opposite of that should be back at you right?

Indeed, if the force were in the direction you suggest then the motion would be as you describe. This implies that the initial assumption must be incorrect. The force is roughly perpendicular to the wall. It is not directly along the line of motion of the ball.
The wall provides a constraint force. Than means a force that constrains the motion. In the case of a smooth wall, it constrains the motion to not go into the wall, but does not constrain motion away from the wall or along the wall. Such a constraint force is directed normal to the wall and is of sufficient magnitude to prevent any inward motion.

A: Neglecting friction, the wall applies a force that is orthogonal to its surface (and is equal and opposite to the normal component of the force from the ball). Therefore, the velocity of the ball in the plane parallel to the wall is unchanged.

A: The ball does not apply the force in the direction in which it hits the wall. The force exterted is in the direction perpendicular to the surface of the wall.. So it exerts a force that is opposite to only the normal component of the force.. Which makes the ball to recieve equal and opposite force (only in the direction perpendicular to it).. This can be better understood if you resolve the momentum or force when the ball decelerates at contact into its parallel and normal components.. And in addition, The ball thrown has only a fixed velocity, it has no force in principle, The force comes into play only when there is a momentum change, a ball in motion has a fixed momentum, The momentum description is more correct than a description based on forces.

A: Lets look at this figure

( http://wandinger.userweb.mwn.de/TMD/v2_4.pdf)
you throw a ball ,with the velocity   $~v_A~$ and the angle $~\alpha_A~$ towards a wall
the ball hit the wall and come back, in case of inelastic collision (left figure)
with the velocity $~v_A~$ and the angle
$~\alpha_A~$
if the throwing angle $~\alpha_A~$ is zero the ball will come exactly back to you , but a soon as the throwing angle not exact zero the ball will not come exactly back to you.
in "reality"  you have the   semi elastic case so even if the  throwing angle $~\alpha_A~$ is zero the ball will hit the wall an come back with the angle $~\alpha_B\ne 0~$ not exactly to you

A:
Suppose the ball has a velocity vector v1 and hits the floor.
If you think in terms of hard body objects, neither the ball nor the floor can deform, so the ball has to instantly flip its velocity vector to bounce off the floor: collision with the floor will take zero time, and a velocity vector flipping direction in zero time implies infinite acceleration and therefore an infinite force. That doesn't work. So it's better to not use the hard bodies paradigm: the ball will squish a little bit. Even if it's a steel ball bearing, it'll squish.
Bouncing happens because the kinetic energy of the ball is stored as potential energy in the compressed "spring" formed by the elastic material (or the air pressure inside, if it's inflatable). Then this energy is released and converted back into potential energy as it jumps off the floor.
Anyway, if the floor has very low friction, for example a steel ball bearing bouncing on a greased polished steel plate, then the floor's reaction will be normal to the surface and the horizontal component of the ball's velocity vector will not change. So it will bounce off with the vertical component of its velocity vector flipped, and the horizontal component will remain identical (minus losses).
If the floor has friction, as I drew in the second illustration, then it will indeed exert a reaction in the opposite direction as the force applied by the ball, and as you said this reaction will push the ball back to the person who threw it.
However this reaction force does not apply to the center of gravity of the ball, but to the contact area with the floor, so it will apply torque to the ball and tend to make it turn (ie, gain angular momentum).
So the ball's velocity vector does lose a bit of its horizontal component, and also a bit of magnitude, as some of the ball's kinetic energy and momentum are converted into rotational energy and angular momentum.
If the ball was turning before it hit the floor, then that will also influence the direction of the bounce. If you turn it fast enough, and if the angle with the floor is not too low, it is possible to make it bounce back towards you.


text:
Q: How to implement parent-children model with Akka in Scala? I would like to implement a little HTTP Server with Scala and Akka. Specifically, I want to have two kind of actor: EmployeeRouterActor and EmployeeEchoActor.
The fisrt one, I want to use it like a router, I mean, that actor receive all messages and it must create an child (in this case, EmployeeEchoActor) for each message.
Each child, it will receive an Employee message and it must give back a string with the employee information.
Moreover, after child complete its process, the child must die. I think the parent is who has to control lifecycle of their children.
In Akka documentation, I only see about using a single child, like this
How can I do this? Is there any example or any other documentation from Akka site?

A: Something like this:
object EmployeeRouterActor {
  final case class Employee(id: String, name: String)
  final case object StopChild
  final case class ChildResponse(id: String, data: String)
}

final class EmployeeRouterActor extends Actor {
  import EmployeeRouterActor._

  // Make a map which will store child actors
  private var children = Map.empty[String, ActorRef]

  override def receive: Receive = {
    case e @ Employee(id, _)  => getChild(id) ! e
    case ChildResponse(id, _) => stopChild(id)
  }

  // Check whether child exists in context of this actor.
  // If it doesn't, create new one.
  private def getChild(id: String): ActorRef =
    context.child(id).getOrElse {
      val child = context.actorOf(EmployeeEchoActor.apply(), id)
      children += (id -> child)
      child
    }

  private def stopChild(id: String) = {
    children(id) ! StopChild
    children -= id
  }
}

object EmployeeEchoActor {
  def apply(): Props = Props(new EmployeeEchoActor)
}

final class EmployeeEchoActor extends Actor {
  // self.path.name to access its id
  override def receive: Receive = {
    case EmployeeRouterActor.Employee =>
      // do stuff with Employee message...
      context.parent ! EmployeeRouterActor.ChildResponse(self.path.name, "Done!") // Or pipeTo(context.parent)
    case EmployeeRouterActor.StopChild => context.stop(self)
  }
}

Basically, child actors are created and stored in a Map. When they finish their tasks, they reply with the response message to their parent which then stops them.


text:
Q: Regex pattern - Exclude part of string I have a number of strings where I'd like to just pull out an episode name from a string if it exists. Here are a few examples
The Case of the Case
(#1.1)
Cameron Diaz/Mark Ronson & Bruno Mars (#40.7)
Cameron Diaz/Smashing Pumpkins (#24.1)
Candice Bergen/Cher (#13.5)

So a full line consists of "episode name (#s.e)" where s is series number and e is episode number, but as you can see sometimes there can be no series/episode number and sometimes there can be no episode name.
I have the following regex
(.+ )(?! \(\#[0-9]+\.[0-9]+\))

So group 1 should pull out the episode name, the above pattern seems to work ok for all cases apart from The Case of the Case, instead of the full episode name it only pulls out The Case of the any ideas?
To clarify the matches we should get from the above are
The Case of the Case
Cameron Diaz/Mark Ronson & Bruno Mars
Cameron Diaz/Smashing Pumpkins
Candice Bergen/Cher

A: You can use a positive lookahead in your regex instead of a negative lookahead as this:
(.+)(?=\s+\(#[0-9]+\.[0-9]+\))

RegEx Demo
\s matches any whitespace including newline. Lookahead expression will assert presence of "\s(#s.e)" ahead of episode name.

A: EDIT - Based on the comments:
This Regex:
^(.*?)(?=\n?\()(.*)$

Ensures that:

*

*\1 returns only a name (even if there's no (#n.n)

*\2 returns only (#n.n) (even if there's no name)

*Text that doesn't fit this pattern is skipped.

Example (clickable demo):

OR
Based on this:

I literally just want the episode name if it exists

This is drastically simpler:
^[^\(\)]*\b

*

*This also works with POSIX 1003.2 extended Regex (i.e. egrep & busybox router compatible)

Click for demo

Or
Alternative with second group
^([^\(\W].[^\n]*?(?=$| [$\(]))\s*?(\(.[^\(]*?\))?$

Has the added flexibility that it \2 will give you the (#s.e) code.

Click for demo

A: Since you are reading line by line, and you just want the (#<NUM}.<NUM>) part removed from the lines, the simplest solution is to replace with the following regex:
def s = "Cameron Diaz/Mark Ronson & Bruno Mars (#40.7)"
print(s.replaceFirst(/\s+\(#\d+\.\d+\)$/, ""))
// => Cameron Diaz/Mark Ronson & Bruno Mars

If there is no match, the string will come back unmodified. See the regex demo.
The $ matches the end of string. If the episode details may appear in a non-final position in the string, remove the anchor.
Details:

*

*\s+ - 1 or more whitespaces

*\( - a literal (

*#  - a literal #

*\d+ - 1 or more digits

*\. - a dot

*\d+ - 1 or more digits

*\) - a literal )

*$ -  end of string anchor

A: You can do:
^([^(]+)(?: \(\#\d+\.\d+\))?

Demo & Explanation


text:
Q: How can an iframe fill a fancybox I have set up a fancy  box (http://fancybox.net). It's box size resizes itself automatically to the size of the webbroser.
Now i want to have an iframe inside the box to resize itself along with the box.
I have searched responsive iframes but the examples show resposive iframes in relation to browser window.
What i am after is a solution allowing iframe to adjust itself to the box.
This is a simple link that is fired with jquery:

and it opens an iframe within the fancybox

this is the jquery:
$('.Link').click(function(){
        var File = $(this).attr('file');
        var srrc = $(this).attr('srrc');
        //var videoWidth = Number($(this).attr('videowidth')); I can
         optionally set fixed height and width, but i don't want to do that.
        //var videoHeight = Number($(this).attr('videoheight'));

        $('#Player').attr("src", srrc); //this refers to the iframe

This fires the fancybox. I set it at fixed width and height for testing purposes that is to check how the iframe fills the fancybox. Unfortunately at 100%,
it exceeds the fancy box and it is not contained. I want it to be "subordinate"
to the size of the box.
        $.fancybox({
            'autoDimensions'    : false,
            'scrolling'         : 'no',
            'width'             : '800',
            'height'            : '800',
            'hideOnOverlayClick' : false,
            'transitionIn' :'fade',
            'transitionOut' :'fade',
            'overlayColor' :  '#666',
            'overlayOpacity': .9,
            'href' : '#videoPlayer'

             });

A: You need to append the iframe to your fancybox - that way, when you assign a width of 100% it will be relative to its parent element. Currently they are siblings.


text:
Q: What do you call an object in an operad that is not the composition of other objects? I have an operad with object sets $P(n)$. For most $n$, there exists at least one object $x\in P(n)$ such that for all sets of other objects and all compositions thereof, $x$ is not equal to that composition.
Is there a convention for what to call $x$? An atom? An atomic object?

A: I believe $x$ would typically be called "indecomposable", like in algebras.
Note that in order to define correctly what indecomposable means, you need to realize that you can always write $x = \operatorname{id}(x) = x(\operatorname{id},\dots,\operatorname{id})$ where $1$ is the identity of your operad. So you need to discard such trivial compositions.
If you have an operad of sets this works fine, in more general settings you probably need to consider an augmented operad (i.e. an operad equipped with a map $\varepsilon : P(1) \to I$ where $I$ is the unit of your monoidal category, satisfying $\varepsilon \eta = \operatorname{id}_I$ where $\eta : I \to P(1)$ represents the unit). Then an indecomposable is something that isn't in the image of $\bar{P} \circ_{(1)} \bar{P} \to P$, where $\bar{P}$ is the augmentation ideal.


text:
Q: Where is Apache getting date-time from? I am deploying my (PHP, MySQL) app on client local machine. For Expiry I am comparing current date with start date & End Date in DB. If current date is between start date & end date than fine go ahead, other wise user will not be able to login.
How would user By PASS my app expiry logic. I need to know possible tricks where user can bypass my app so that I work on it and make expiry unbeatable.
I need to know from where Apache is taking current date. if from OS then user can change it & bypass my app.

A: I think you are looking for: date_default_timezone_set ( string $timezone_identifier )
http://php.net/manual/en/function.date-default-timezone-set.php
You can also set this in your php.ini config.


text: Q: How can I determine tile clicked on in Isometric XYZ without colliders/gameobjects? I'm working on an Isometric XYZ tile game. I am generating all the tiles from sprites at runtime. They do not have colliders attached. I'm trying to determine which tile a player is clicking on using Input.mousePosition. I have tried a ton of math, and nothing seems to work right. As I move away from the origin of the map (WorldPosition 0,0) my error increases. I have tried applying the math found in isometric tutorials and haven't gotten anywhere. There must be a way to do this, can anyone help?


text:
Q: Vscode installation optional task When passing through vscode selection process, there is an one option that seems confusing.

Add to PATH (requires shell restart)

What does shell refers to? The powershell? Explorer.exe? Or another else? How to restart shell after Vscode installation?

A: By adding VSCode to PATH, you will be able to run some commands related to this IDE anywhere in your operating system.
For Example: This command inside command-line will open VSCode in the current directory:
code .

Note: For your second question, you don't need to restart shell. It will be done automatically.


text:
Q: Reading format "07/11/2022 09:22" as date in R (%d/%m/%y %H:%M:%OS) I have a CSV file with dates on the format "07/11/2022  09:21:00" - which is %d/%m/%y %H:%M:%OS. I want to read them as dates but cannot make it work.
My data:

*

*closed$closed_at: field where the dates are stored.

I tried the following:
<- as.Date(as.character("closed$closed_at"), format = "%d/%m/%y")
<- as.Date(closed$closed_at, format="%d%m%Y")
<- as.POSIXct(closed$closed_at, format="%d-%m-%Y %H:%M:%OS") - although I am aware that it does not make sense.
All of the above brings back the result: "NA"


text:
Q: isn't this wikipedia Definite integrals involving rational or irrational expression wrong!?
isn't this wikipedia Definite integrals involving rational or irrational expression wrong!?
According to my calculations:
$\sin[\frac{(m+1)\pi}{n}]$ while in wiki it is
$\sin[\frac{(m+1)}{n}]$
seems $\pi$ missed.
here is result of my work:
$\int_0^\infty \frac{x^m \, dx}{({x^n+a^n)}^r}=\frac{(-1)^{r-1}\pi a^{m+1-nr}\Gamma [(m+1)/n]}{n\sin[\pi (m+1)/n](r-1)!\Gamma[(m+1)/n-r+1]} \ \ , 0<m+1<nr$
ref:List of definite integrals
Remark:
@icurays1 in your link there is another wrong  $\Gamma [\frac {(m+1)}{(n-p+1)}]$ while it could be $\Gamma [(\frac {m+1}{n})-p+1]$

A: It is definitely wrong.  Take $a=1, m=0, n=2, r=1$.  Then it reads
$$\int_0^\infty \frac{1}{x^2+1}\,dx = \frac{\pi}{2 \sin(1/2)}$$
which is false.  The correct value is $\pi/2$, which agrees with your proposed $\sin\left[\frac{(m+1)\pi}{n}\right]$.
Taking the sine of a rational number is definitely a red flag.


text:
Q: java try/catch problems I want to catch ints entered in a string option Kind of stuck with this question but how I can I make my try catch to only allow strings into the input box. (the relevant code is towards the bottom here sorry about the messy format still quite new to graphical programming) I thought my code below would work however I guess it doesn't and I am not quite sure on now to make it catch for all ints in the sting input as the ints there are being entered as strings. Also if you could look at the email try/catch as well pop up the error box as well if a @ sign is up in since it is somewhat similar. Thanks
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.InputMismatchException;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MainPanel extends JPanel {

    Player myPlayer;
    Player myOtherPlayer;
    private int WIDTH = 1000;
    private int HEIGHT = 1000;
    private int WALLWIDTH = 100;
    private int WALLHEIGHT = 100;
    private ArrayList<Wall> walls = new ArrayList<Wall>();
    String Name;
    String Email;
    int favNum;

    Timer myTimer = new Timer(500, new timerListener());
    JLabel myTimeLabel;
    int time =1;

    public MainPanel()
    {
        setPreferredSize(new Dimension(WIDTH,HEIGHT));
        JLabel myLabel= new JLabel ("Game ends once 30 seconds is receahed:");
        myLabel.setFont(new Font("Serif", Font.BOLD,32));
        myLabel.setForeground(Color.WHITE);
        myTimeLabel= new JLabel (Integer.toString(time));
        myTimeLabel.setFont(new Font("Serif", Font.BOLD,32));
        myTimer.start();

        add(myLabel);
        add(myTimeLabel);
        myPlayer = new Player(0,100, "toad.png", KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT,this, 50, 38);
        myOtherPlayer = new Player(200,200, "toad.png", KeyEvent.VK_W, KeyEvent.VK_S, KeyEvent.VK_A, KeyEvent.VK_D,this, 50, 38);
        createWalls();

    }

    public ArrayList<Wall> getWalls() {
        return walls;
    }

    public void createWalls()
    {
        int j = 0;
        for(int i = 0; i < HEIGHT/WALLHEIGHT; i++)
        {
            for(int k = 0; k < WIDTH/WALLWIDTH; k++)
            {
                if(i == 0 || i == (HEIGHT/WALLHEIGHT-1))
                {
                    walls.add(new Wall(k*WALLWIDTH,j,"road.png", 100, 100));
                }

            }
            j+=WALLHEIGHT;
        }
    }

    private class timerListener implements ActionListener
    {

        public void actionPerformed(ActionEvent e) {
            time++;
            myTimeLabel.setText(Integer.toString(time));
            myTimeLabel.setForeground(Color.WHITE);
            if(time == 31)
            {
                myTimer.stop();
            }
            repaint();
        }

    }

    public void paintComponent(Graphics page)
    {
        super.paintComponent(page);

        page.drawImage(myPlayer.getImageIcon().getImage(), myPlayer.getX(), myPlayer.getY(), null);
        page.drawImage(myOtherPlayer.getImageIcon().getImage(), myOtherPlayer.getX(), myOtherPlayer.getY(), null);

        for(int i = 0; i < walls.size(); i++)
        {
            page.drawImage(walls.get(i).getImageIcon().getImage(), walls.get(i).getX(), walls.get(i).getY(), null);

        }

        page.setFont(new Font("Arial", Font.PLAIN,32));
        page.drawString("Player 1 Score: " + myPlayer.getScore(), 100, 800);
        page.drawString("Player 2 Score: " + myOtherPlayer.getScore(), 100, 850);
        myPlayer.checkOffScreen();

        if(time == 5)
        {
            page.drawString("GAME OVER", WIDTH/2-100, HEIGHT/2);

            try{
                Name = JOptionPane.showInputDialog("What is your name?");
                }catch (NumberFormatException  e) {
                    if (!Name.matches("^[a-z][a-z ]*[a-z]?$")){
                    JOptionPane.showInputDialog("You entered a number, this only accepts alphabetical letters. Please enter your name");}
                }

            try{
                favNum= Integer.parseInt(JOptionPane.showInputDialog("What is your favorite number?"));
                }catch (NumberFormatException  e) {

                JOptionPane.showInputDialog("You entered a text, this only accepts numbers . Please enter your  favorite number");}

            try{
                Email =JOptionPane.showInputDialog("Please enter your email");
                }catch (InputMismatchException  e) {
                JOptionPane.showInputDialog("You enter your email incorrectly. Please include an @ sign with it");}
                }

            }

    }

A: One thing you can do is create an isInteger method...
protected static boolean isInteger(String s) {
    try {
        Integer.parseInt(s);
    } catch(NumberFormatException e) {
        return false;
    } catch(NullPointerException e) {
        return false;
    }
    // String can be changed into an integer
    return true;
}

A: What I am getting from your code is : you want to make sure user inputs correct value in specific field, kind of validation. If you want to make sure user enters correct value for each field then it will be difficult to handle it using single try catch block. You can try below logic, it will not allow user to move further till he entered correct input for a particular field. I have done it for Name field, similarly you can do it for rest of the fields :
boolean error=true;
Name = JOptionPane.showInputDialog("What is your name?");
if (!Name.matches("^[a-zA-Z ]*$")){
    error=true;
}
while(error){
    Name = JOptionPane.showInputDialog("You entered a number, this only accepts alphabetical letters. Please enter your name");
    if (Name.matches("^[a-zA-Z ]*$")){
         error=false;
    }
}


text:
Q: SQL process XML performance: Insert into columns in a table I am having an issue in a SQL procedure and I can't seem to find the proper solution.
The stored procedure is containing one parameter of the XML datatype (name = @data).
An example of the incoming message is the following (the actual message is containing a lot more nodes, but I left them out for simplicity):
<Suppliers xmlns="">
  <Supplier>
    <IDCONO>3</IDCONO>
    <IDSUNO>009999</IDSUNO>
    <IDSUTY>0</IDSUTY>
  </Supplier>
</Suppliers>

In my SQL database I have a table called "Supplier" and it contains the exact same columns as the nodes in the XML (IDCONO, IDSUNO, IDSUTY,..)
I need to loop over the nodes and insert the data in the columns.
I have implemented the procedure below, but this is giving me a lot of perfomance issues on the bigger files (long processing time, even timeouts):
INSERT INTO SUPPLIER
   (IDCONO
   ,IDSUNO
   ,IDSUTY)
SELECT
   T.C.value('IDCONO[1]', 'VARCHAR(50)') as IDCONO,
   T.C.value('IDSUNO[1]', 'VARCHAR(50)') as IDSUNO,
   T.C.value('IDSUTY[1]', 'VARCHAR(50)') as IDSUTY
from @data.nodes('/Suppliers/Supplier') T(C)

Any help is appreciated!
Note that the SQL version is SQL server 2012.
Thanks in advance.

A: The first I would try is the specify the text() node when using the XML datatype to prevent SQL Server from doing a deep search for text elements.
INSERT INTO SUPPLIER
   (IDCONO
   ,IDSUNO
   ,IDSUTY)
SELECT
   T.C.value('(IDCONO/text())[1]', 'VARCHAR(50)') as IDCONO,
   T.C.value('(IDSUNO/text())[1]', 'VARCHAR(50)') as IDSUNO,
   T.C.value('(IDSUTY/text())[1]', 'VARCHAR(50)') as IDSUTY
FROM @data.nodes('/Suppliers/Supplier') T(C)

If that is not good enough I would try OPENXML instead.
DECLARE @idoc INT
EXEC sp_xml_preparedocument @idoc OUT, @data

INSERT INTO SUPPLIER
   (IDCONO
   ,IDSUNO
   ,IDSUTY)
SELECT IDCONO, IDSUNO, IDSUTY
FROM OPENXML(@idoc, '/Suppliers/Supplier', 2) WITH
        (IDCONO VARCHAR(50),
         IDSUNO VARCHAR(50),
         IDSUTY VARCHAR(50))

EXEC sp_xml_removedocument @idoc


text:
Q: User pinned taskbar shortcuts and major upgrades I'm struggling to understand how user pinned shortcuts in windows explorer work in relation to windows installer. I was under the impression that the User Pinned shortcuts were completely user handled, but it seems windows installer will find (and modify) user pinned shortcuts when installer shortcuts are removed.
This is basically two related questions, one relating to early scheduling of uninstall, and relating to late scheduling, and in particular changing from early to late between versions.
Cached "internal" icons from msi's still work after upgrade
Example: Application v1.0 installs a non-advertised shortcut on the desktop, and uses an icon internal to the msi. The user then does "pin to taskbar". Both the taskbar and the desktop shortcut now references an icon copied from the msi into the icon cache, such as %SystemRoot%\Installer\{CB24D097-4E8F-4E8E-8FE3-EACF5954DE56}\MyApp.ico.
Application is upgraded to v2.0 via a Major upgrade with late scheduled removal of v1. The user pinned shortcut will not be corrupted/removed, it keeps the same icon even though the icon (presumably?) belonged only to the v1 installer? Why does this work? Is there ever a risk that the cached icon will be removed in the future, thereby corrupting the user pinned shortcut?
Early scheduling of uninstall corrupts user pinned shortcuts
If application is upgraded from v1.0 to v2.0 with a Major Upgrade using an early uninstall of the previous version, then as the application (temporarily) removes the installer-provided shortcut on the desktop, something also corrupts the user pinned shortcut. The only workaround I have found (short of programatically hacking shortcuts back into place) is to make the installer not remove shortcuts at all, instead removing the .lnk via doing a <RemoveFile on="uninstall"> for the shortcut. (See Wix - Do Not Remove Pinned Taskbar on Install)
Now, this hack works well enough for a chain of major upgrades that all have uninstall scheduled early, and as described in the previous paragraphs - late scheduling seems to always work even without hacks-
However, what if v1.0 is already shipped with late uninstall, and v2.0 is the first upgrade to uninstall the previous version early?
Is there any way I can influence the uninstall of v1.0 in the V2.0 msi? Specifically, can I somehow persuade the v1.0 uninstall to skip the remove shortcuts step?


text:
Q: This view is not constrained vertically I just update Android Studio and playing around with Constraint Layout. There are some errors in xml attribute.

This view is not constrained vertically: at runtime it will jump to
  the left unless you add a vertical constraint less... (Ctrl+F1)  The
  layout editor allows you to place widgets anywhere on the canvas, and
  it records the current position with designtime attributes (such as
  layout_editor_absoluteX.) These attributes are not applied at runtime,
  so if you push your layout on a device, the widgets may appear in a
  different location than shown in the editor. To fix this, make sure a
  widget has both horizontal and vertical constraints by dragging from
  the edge connections.

I follow these steps:
Right click on designing part > Constraint Layout > Infer Constraints

but I can't find Constraint Layout .

A: I have noticed as well that infer constraints doesn't always work. What I do is, I:

*

*Drag the view I want into the constraint layout,

*Align it on the screen how I want it to be displayed,

*Manually create a connection between its left constraint constraint to its parent, or to another view,

*Manually create a connection between its top constraint constraint to its parent, or to another view.

This method of constraining makes it unnecessary for me to infer constraints because all my views are constrained. If I am getting any errors, I clear all constraints and then manually create the connections for each view in the layout.
Here's an image describing what I mean:

I constrained the left and top, and in doing so, nothing needs to be inferred.
Note:

*

*I am using Android 3.0 and a ConstraintLayout version of 1.0.2

*It works well when creating only two connections that are perpendicular to one another, i.e top/left, top/right, bottom/left, bottom/right.


text:
Q: How can I color in one zipcode in a map, RStudio? I made a zipcode map of dallas using  this shapefile: https://gis.dallascityhall.com/shapefileDownload.aspx (Street Files)
dallas_streets %>%
  sample_frac(1) %>%
  group_by(POSTAL_L) %>%
  summarize(geometry = st_convex_hull(st_union(geometry))) %>%
  ggplot() + ggtitle("Zip Code Map of Dallas") +
  geom_sf(aes(fill = as.numeric(POSTAL_L))) +
  geom_sf_text(aes(label = POSTAL_L)) +
  scale_fill_viridis_c(option = "C") +
  theme_minimal()

I want to be able to have the map as greyscale and only one zipcode colored in, please let me know if you can help. Thanks!

A: One way is to just add a column that specifies a key for the fill you want for each zipcode and then link it in the ggplot using scale_fill_manual(). Here, I do red for zip code 75241 and lightgray for all others.
dallas_streets2 <- dallas_streets %>%
  sample_frac(1) %>%
  group_by(POSTAL_L) %>%
  summarize(geometry = st_convex_hull(st_union(geometry))) %>%
  mutate(color = ifelse(POSTAL_L == "75241", "yes", "no"))

dallas_streets2 %>%
  ggplot() + ggtitle("Zip Code Map of Dallas") +
  geom_sf(aes(fill = color)) +
  geom_sf_text(aes(label = POSTAL_L)) +
  scale_fill_manual(values = c("red", "lightgray"),
                    limits = c("yes", "no")) +
  theme_minimal()

A: What if you change scale_fill_vidris_c() to scale_fill_gray() and then add geom_sf(data=filter(dallas_streets, zip=='<zipcode>'), fill='#ff0000') (where I arbitrarily chose red (#ff0000) as the color)? The combined code would look like:
ggplot(dallas_streets) + ggtitle("Zip Code Map of Dallas") +
    geom_sf(aes(fill = as.numeric(POSTAL_L))) +
    scale_fill_gray()+
    geom_sf(data=filter(dallas_streets, zip=='<zipcode>'), fill='#ff0000')
    geom_sf_text(aes(label = POSTAL_L)) +
    theme_minimal()


text:
Q: :Find the area of the shaded region $ABC$ in the figure below For reference:Calculate the area of the shaded region; if: $AP = 4\sqrt2; PB = 4$ and $HN = 4$.(Answer: $\frac{32}{51}(5\sqrt2+4)$)
My progress

$HN(2r-HN)=BH^2\quad\Rightarrow{}\quad 4(2r-4)=4 \therefore  R=\dfrac{5}{2}\\
S_{ABC} = \frac{a.b.c}{4R}=\frac{4.b.c}{10}\therefore \boxed{S_{ABC}= \frac{2.b.c}{5}}\\
S_{ABC}= \frac{S_{APC}}{2}\\
\frac{S_{ABC}}{S_{PAB}}=\frac{4b}{c.4\sqrt2}\implies b=\sqrt2c$
...???
By trigonometry
$S(ABC)=\frac{1}{2}S(APC)=\frac{1}{4}PA⋅PCsin(\overset{\LARGE{\frown}}{APC})=\frac{1}{4}PA⋅PC.sin(\overset{\LARGE{\frown}}{APO}+\overset{\LARGE{\frown}}{CPO})=\\
\frac{1}{4}PA⋅PC.(sin(\overset{\LARGE{\frown}}{CPO})cos(\overset{\LARGE{\frown}}{APO})+cos(\overset{\LARGE{\frown}}{CPO})sin(\overset{\LARGE{\frown}}{APO})$
...???

A: Based on confirmation that $PA$ is tangent, by using power of point of $P$, $BC = 4$ and using similar triangles, $AC = AB \sqrt2$.
If $OH = x, OB = ON = 4 - x$, and applying Pythagoras in $\triangle OBH$
$x^2 + 2^2 = (4-x)^2 \implies x = OH = 3/2, OB = 5/2$
As $\angle BAC = \angle BOH = \theta $ (say)
$\cos \theta = \dfrac{3}{5}, \sin\theta = \dfrac{4}{5}$
Using law of cosine in $\triangle BAC$, $AB^2 + (AB \sqrt2)^2 - 4^2 = 2 AB \cdot AB \sqrt2 \cdot \dfrac{3}{5}$
$\implies AB^2 = \dfrac{80}{15 - 6 \sqrt2} = \dfrac{80}{51} (5 + 2 \sqrt2)$
$S_{\triangle ABC} = \dfrac 12 \cdot AB \cdot AB\sqrt2 \cdot \sin\theta $
$ = \dfrac{2\sqrt2}{5} AB^2  = \dfrac{32}{51}(5 \sqrt 2 + 4)$

If you want to avoid trigonometry, drop a perp from $C$ to $AB$ which meets $AB$ at $G$ then $\triangle ACG \sim \triangle OBH$
so, $ \displaystyle \frac{CG}{AC} = \frac{BH}{OB} \implies CG = \frac{4 \sqrt2}{5} AB$
say, $AB = y$. Then,
$ \displaystyle S_{\triangle ABC} = \frac{2 \sqrt2}{5} y^2 \tag1$
Next, equating area of $\triangle ABC$
$ \displaystyle \frac 12 AK \cdot 4 = \frac{2 \sqrt2}{5} y^2$
$ \displaystyle \implies AK = \frac{\sqrt2}{5} y^2, ~$ where $K$ is the foot of perp from $A$ to $BC$
$ \displaystyle BC = BK + CK = \sqrt{y^2 - AK^2} + \sqrt{2y^2 - AK^2} = 4$
$ \displaystyle \sqrt{y^2 - \frac{2y^4}{25}} + \sqrt{2y^2 - \frac{2y^4}{25}} = 4$
Substitute $z = y^2$ and solve for $z$.
You get two solutions and one of them can be discarded based on given dimensions.
Finally we have, $ \displaystyle z = y^2 = \frac{400+ 160 \sqrt2}{51}$
Now $(1)$ gives you the desired area.


text:
Q: Mysql Cross Schema Queries Based on Row Data So I'm working on a web application which our clients want their user data separated from other client's user data. Since our clients can be collaborative with each other, we can't just create a new instance of the application for each client, since we have to make sure user ids match up and are unique between clients.
Basically there's our "MasterApplication" database which has a "User" table which contains a UserId and the name of the database where to find the remaining user data. Each client has their own database user which only has access to the "MasterApplication" and their own client table.
Here's an example of how it looks.
CREATE DATABASE MasterDatabase
CREATE DATABASE Client1
CREATE DATABASE Client2

CREATE TABLE `MasterDatabase`.`Person` (
  `PersonId` INT NOT NULL AUTO_INCREMENT,
  `DatabaseName` Varchar(20) NOT NULL,
  PRIMARY KEY (`PersonId`)
)

CREATE TABLE `Client1`.`Person` (
      `PersonId` INT NOT NULL,
      `FirstName` Varchar(20) NOT NULL,
      PRIMARY KEY (`PersonId`)
    )

CREATE TABLE `Client2`.`Person` (
     `PersonId` INT NOT NULL,
     `FirstName` Varchar(20) NOT NULL,
      PRIMARY KEY (`PersonId`)
)

INSERT INTO MasterDatabase.Person VALUES (1, 'Client1');
INSERT INTO MasterDatabase.Person VALUES (2, 'Client2');

INSERT INTO Client1.Person VALUES (1, 'Matt');
INSERT INTO Client2.Person VALUES (2, 'Scott');

So Client1 would have a database user which has access to MasterDatabase and Client1 tables. Client2 would have a user with access to MasterDatabase and Client2.
I'm hoping there's some way that I can do a cross schema query easily using the data from the "DatabaseName" field in MasterDatabase, but I can't figure it out. I know for the most part I can store the client's database name in the application logic and just insert it into the query, but there will be a few spots which I'll need to join all clients into one query.
My attempt was to do
SELECT *, `DatabaseName` INTO @DB FROM MasterDatabase.Person
LEFT JOIN @DB.Person ON MasterDatabase.Person.PersonId = @DB.Person.PersonId

But that didn't work as I was hoping. Is there maybe someway I can do it with a procedure? I'm also open to other ideas of separating out the user data per client too if you have any.

A: I think you can do it in stored procedure. It will look something like
DELIMITER //
CREATE DEFINER='root'@'localhost' PROCEDURE GetData(IN user_id INT)
BEGIN
  DECLARE db_name varchar(100);
  SELECT DatabaseName INTO db_name FROM MasterDatabase.Person WHERE  PersonId = user_id;
  SET @t1 =CONCAT('SELECT * FROM ',db_name,'.Person' );
  PREPARE stmt1 FROM @t1;
  EXECUTE stmt1;
END//

UPDATE Sorry, I forgot DEALLOCATE PREPARE stmt1; ; it should be after EXECUTE stmt1;


text:
Q: My images return as blank in PDF document In my app I upload images to my company server
These images are converted to a pdf document and uploaded
I am using the built in PDFdocument for this, now my problem is the pages are dynamic depending on the amount of images the user selects or takes with the camera, the images are put into an ARRAYLIST(String)
I then call the position of the photo and use canvas to paint it to the pdf
Now my problem is the pdf document generates with the appropriate page numbers IE. If the user selects 4 images it returns 4 pages BUT there are NO images
I found the problem My second for loop doesn't work correctly as it doesn't give out a number ad I want it to so basicly
Code For The PDF
    PdfDocument document=new PdfDocument();
            // crate a page description
            PdfDocument.PageInfo pageInfo;
            PdfDocument.Page page;
            Canvas canvas;
            int i;

            Bitmap image;

**here I loop for page Creation**

            for (i=0; i < list.size(); i++)  {

                pageInfo=new PdfDocument.PageInfo.Builder(3000, 6000, 1).create();
                page=document.startPage(pageInfo);

Here I loop to change the position of the images in the array list
this on is not looping through the arraylist positions like it should
for(int t = 0; t< list.indexOf(0); t+=1){

                    canvas=page.getCanvas();
                    image=BitmapFactory.decodeFile(String.valueOf(list.get (t)));
                    image.setDensity(DENSITY_XHIGH);
                    canvas.drawBitmap(image, 1, 1, null);
                    canvas.setDensity(DENSITY_XHIGH);
                }

            document.finishPage(page);
        }

        String directory_path=Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
            File file=new File(directory_path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String timeStamp=(new SimpleDateFormat("yyyyMMdd_HHmmss")).format(new Date());
            String targetPdf=directory_path + timeStamp + ".pdf";
            File filePath=new File(targetPdf);
            try {
                document.writeTo(new FileOutputStream(filePath));
                Toasty.info(this, "PDF Created", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                Log.e("main", "error " + e.toString());
                Toasty.error(this, "Error making PDF" + e.toString(), Toast.LENGTH_LONG).show();
            }
            // close the document
            document.close();

A: 1.Use PrintAttributes.build() to set attributes of the pdf properly

*and pass printattrs to printerpdfDocument(context,/*print attributes obj goes here */)

*Create a Rect() object

*Using rect() object create pageviews in forloop and add these pageview to document

*User FileOutputStream(// your pdf file), pass this  to document, then
fileOutPutstream = new FileOutputStream(pdffilename);
doucument.writeTo(fileOutPutstream);
doucument.close();
fileOutPutstream.close(); // close your stream

Above is rough implementation, this should give you a idea to proceed.


text:
Q: Регулярные выражения в JUnit тестах Допустим, у меня есть такой тест, который проверяет вывод в консоль:
public class ArraysAppMainTest {

    @Rule
    public final SystemOutRule log = new SystemOutRule().enableLog();

    @Test
    public void testMain() {
        ArraysApp.main(new String[] {});
        boolean test = false;
        test = Pattern.matches("[num:][0-99]", this.log.getLog().toString());
        Assert.assertTrue(test);
    }

}

в консоль выводится:

num:66

Цифры генерируются случайно.
Я не очень понимаю регулярные выражения, но я уже перепробовал разные варианты:
num:[0-99]
num:^[0-99]
и т.д.
Но тест не проходит, что я делаю не так?

A: Думаю, так правильно:
num:[0-9]{2}

[0-9]-диапазон символов, но не чисел
{2}-количество символов Можно {1,2} если число может быть однозначным


text:
Q: SQL: How to update from 'tableA pointing to tableB' to 'tableA poiting to tableC pointing to tableB' without losing existing element relation? Basically I want an intermediary Book, between what was a direct link from Line to User. Line elements already exist and can't lose the relation to corresponding already existing User element, so a default Book element needs to be created which handles already existing data.
Tables were created like this:
User (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL
);

Line (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(300),
    id_user INT UNSIGNED NOT NULL,
    FOREIGN KEY (id_user) REFERENCES User(id)
);

Now I need to create some SQL code that would produce tables like this:
User (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL
);

Book (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(300),
    id_user INT UNSIGNED NOT NULL,
    FOREIGN KEY (id_user) REFERENCES User(id)
);

Line (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(300),
    id_book INT UNSIGNED NOT NULL,
    FOREIGN KEY (id_book) REFERENCES Book(id)
);

... except that data already exists. so I have Line elements pointing to User elements and I can't create new tables from scratch. So I need the SQL code to modify the existing structure.
Basically I just want users to have books and books to have lines, instead of users have lines. And already existing lines to get a connection with the owner users. What would be the best approach?
///////////////////////////////////////////////////////
Some sample data representing what my database looks like currently:
Table user(id,username)
- 1, user1
- 2, user2
- 3, user3

Table line(id,title,id_user)
- 1, line1, 1
- 2, line2, 1
- 3, linex, 1
- 4, line1, 2
- 5, liney, 2

The output should be the following database:
Table user(id,username)
- 1, user1
- 2, user2
- 3, user3

Table book(id,title,id_user)
- 1, 'default', 1
- 2, 'default', 2
- 3, 'default', 3

Table line(id,title,id_book)
- 1, line1, 1
- 2, line2, 1
- 3, linex, 1
- 4, line1, 2
- 5, liney, 2

////////////////////////////////
What my pipeline currently looks like, my main problem is producing the final query:
    create table book
      $sql = "CREATE TABLE IF NOT EXISTS book(
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      title VARCHAR(300),
      id_user INT UNSIGNED NOT NULL,

      FOREIGN KEY (id_user) REFERENCES User(id)
    ); ";

    $conn->exec($sql);

    //insert default book corresponding to every user
    $sql = "INSERT INTO Book(title, id_user) SELECT DISTINCT 'default', id FROM User;";
    $conn->exec($sql);

    //insert id_book foreign key into Line table pointing to Book table
    $sql = "ALTER TABLE Line ADD id_book INT;"

    $conn->exec($sql);

    //make Line.id_book foreign key pointing to Line.id
    $sql="ALTER TABLE Line ADD FOREIGN KEY (id_book) REFERENCES User(id);"

    $conn->exec($sql);

    //unfinished
    $sql = "UPDATE
                Line
            SET
                Line.id_book = Book.id
            WHERE
                Line.id_user = Book.id_user"

A: Create table book (like you already did):
CREATE TABLE IF NOT EXISTS book(
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      title VARCHAR(300),
      id_user INT UNSIGNED NOT NULL,
      FOREIGN KEY (id_user) REFERENCES User(id)
);

Populate the new table:
INSERT INTO Book(title, id_user) SELECT 'default', id FROM User;

I removed DISTINCT from your code because id is primary/unique and thus every selected row is guaranteed to be unique.
Add column id_book to the line table:
ALTER TABLE Line ADD id_book INT UNSIGNED;

It must be INT UNSIGNED to match the referenced data type.
Add foreign key:
ALTER TABLE Line ADD FOREIGN KEY (id_book) REFERENCES book(id);

It should reference a book, not a user like in your code.
Update data (Relate the line with the users (first) book):
UPDATE Line
SET Line.id_book = (
  SELECT book.id
  FROM book
  WHERE book.id_user = Line.id_user
  ORDER BY book.id
  LIMIT 1
);

Drop line.id_user column:
-- use "SHOW CREATE TABLE line" to find out the foreign key name
ALTER TABLE Line DROP FOREIGN KEY line_ibfk_1;
ALTER TABLE Line DROP id_user;

http://sqlfiddle.com/#!9/3faa13/1
Note: If a user has two or more books, you don't know wich one to link with a line. In your question you didn't define how to handle this case. So i decided to take the first book by id (ORDER BY book.id LIMIT 1).
The UPDATE statement could also be:
UPDATE Line
SET Line.id_book = (
  SELECT MIN(book.id)
  FROM book
  WHERE book.id_user = Line.id_user
);


text:
Q: Trying to swap the maximum and the minimum numbers in an array I'm trying to swap the maximum and minimum values in an array in my program.
Here is the code:
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int myArray[] = new int[25];

    for (int i = 0; i < myArray.length; i++) {
        System.out.println("Enter a number: ");
        myArray[i] = in.nextInt();
    }
    int maximum = maxNumber(myArray);
    int minimum = minNumber(myArray);

    System.out.println(Arrays.toString(myArray));
}

public static int maxNumber(int[] arr) {
    int maximumValue = arr[0];
    //finds the maximum value in an array
    for (int a = 1; a < arr.length; a++) {
        if (arr[a] > maximumValue) {
            maximumValue = arr[a];
        }
    }
    return maximumValue;
}

public static int minNumber(int[] arr) {
    int minimumValue = arr[0];
    //finds the minimum value in an array
    for (int a = 1; a < arr.length; a++) {
        if (arr[a] < minimumValue) {
            minimumValue = arr[a];
        }
    }
    return minimumValue;
}

I have two separate functions to find the Maximum and Minimum values, but I'm stuck on the actual swapping of the values. The two functions work as I've used them for another program, but I'm not sure if they would work for this program.
At first I was thinking of finding them by setting them equal to each other in some way, but that led to nothing.
Any help would be appreciated.

A: public static void main(String... args) {
    Scanner scan = new Scanner(System.in);
    int[] arr = new int[25];

    System.out.format("Enter array int numbers (%d in total): ", arr.length);

    for (int i = 0; i < arr.length; i++)
        arr[i] = scan.nextInt();

    System.out.println(Arrays.toString(arr));
    swamMinMax(arr);
    System.out.println(Arrays.toString(arr));
}

private static void swamMinMax(int[] arr) {
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;

    for (int i = 0; i < arr.length; i++) {
        min = Math.min(min, arr[i]);
        max = Math.max(max, arr[i]);
    }

    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == min)
            arr[i] = max;
        else if (arr[i] == max)
            arr[i] = min;
    }
}

Output:
Enter array int numbers (25 in total): 1 2 3 4 5 6 7 8 9 10 -1 -1 -1 14 15 16  17 18 19 20 21 22 23 66 66
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1, -1, -1, 1, 1, 1, 17, 18, 19, 20, 21, 22, 23, 66, 66]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 66, 66, 66, 1, 1, 1, 17, 18, 19, 20, 21, 22, 23, -1, -1]

A: You were real close.  I copied some of the code and commented where the changes need to be made.  You can still use your existing code to populate the array from the console.
Also, kudos for assigning the first element in the array to min or max and starting your loop at 1.  A lot of folks don't think about doing that.
int myArray[] = {1,10,-5,99,48,-22,43, 44,100,2};

System.out.println(Arrays.toString(myArray));   // print original array
int maxIdx = maxNumber(myArray);                // get index of max
int minIdx = minNumber(myArray);                // get index of min

// now swap max and min using the returned indices.
int save = myArray[maxIdx];
myArray[maxIdx] = myArray[minIdx];
myArray[minIdx] = save;
System.out.println(Arrays.toString(myArray));   // print the altered array

public static int maxNumber(int[] arr) {
    int maximumValue = arr[0];
    // finds the maximum value in an array
    int idx = 0;                                    //idx = 0 to start
    for (int a = 1; a < arr.length; a++) {
        if (arr[a] > maximumValue) {
            idx = a;                                //save index of current max
            maximumValue = arr[a];
        }
    }
    return idx;                                     // return index of max
}

public static int minNumber(int[] arr) {
    int minimumValue = arr[0];
    // finds the minimum value in an array
    int idx = 0;                                    // idx = 0 to start
    for (int a = 1; a < arr.length; a++) {
        if (arr[a] < minimumValue) {
            idx = a;                                // save index of current min
            minimumValue = arr[a];
        }
    }
    return idx;                                     // return index of min
}

This would print
[1, 10, -5, 99, 48, -22, 43, 44, 100, 2]
[1, 10, -5, 99, 48, 100, 43, 44, -22, 2]

A: You can use IntStream to find indexes of the maximum and minimum elements and then swap their values:
int[] arr = {1, 3, 5, 6, 4, 2, 8, 7, 9, -1, -3};

// indexes of the maximum and minimum elements
int max = IntStream.range(0, arr.length)
        .boxed().max(Comparator.comparing(i -> arr[i])).orElse(-1);

int min = IntStream.range(0, arr.length)
        .boxed().min(Comparator.comparing(i -> arr[i])).orElse(-1);

// swap the values
int temp = arr[max];
arr[max] = arr[min];
arr[min] = temp;

System.out.println(Arrays.toString(arr));
// [1, 3, 5, 6, 4, 2, 8, 7, -3, -1, 9]


text:
Q: PDFBox UTF16 letters Does any body can help me with letter issue in PDFBox I'm trying to print letter "ń" ( polish letter ) and I'm getting something like þÿ J . Dı B R O W 2S0 :K0 3I.
Please help!

A: I came upon the same problem with Bulgarian. In short, I think there isn't an easy solution. Basically you need a utf font. If you use one of the standard 14 type1 fonts (like Helvetica or Courier) - they only support the basic latin alpabet, so they can't do the job. You could load a truetype utf font but pdfbox has a hardocded WinAsciiEncoding for all truetype (type1 as well) fonts which is wrong. You could do what Open office does as far as I can see - create a subset of a font so that you don't embed the whole font file in the pdf. Unfortunately this functionality is missing in pdfbox but there is a Jira and more information:
https://issues.apache.org/jira/browse/PDFBOX-922
If you find a good solution please share!

A: you can change it to unicode characters into LegacyPDFStream Engine  java class


text:
Q: Error calling webservice using JSONP + jquery with IE on remote domain I have a .Net webservice on my app server that returns data formatted as JSONP. I have an HTML test client on that server which works fine using IE, Firefox, & Chrome. If I copy the same HTML to my workstation or deploy to my webserver it works with Firefox & Chrome but in IE I'm getting two javascript errors.

Message: Object doesn't support this property or method Line: 1 Char: 1 Code: 0 URI: http://mydomain/WebServices/LyrisProxy/Services/Lyris/JSONP/Lyris.asmx/AddUser?lyrisInstance="1"&email="myemail@gmail.com"&fullName="My Name"&lyrisList="listname"&format=json&callback=jsonp1274109819864&_=1274109829665

Message: Member not found.
Line: 59
Char: 209
Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

I'm kind of at loss as to what to do to fix this.
Here's my javascript. It's actually not the JSONP causing the error but rather the call to jqModal ev.preventDefault();. I'm trying to go through this now to see why it bombs with an external reference to that on IE.
<script type="text/javascript">
    $(document).ready(function() {
        $("#createUser").live("click", function(ev) {
            var invalidEmailAddressMessage = "That isn't a valid email address.";
            var userSuccessfullyAddedMessage = "Congrats! You've been added to the iStage mailing list.";
            var userAlreadyExistsMessage = "Looks like you're already on our mailing list!";
            var genericErrorMessage = "Something fishy happened. I don't know what to tell you.";

            // check for a valid email address
            var regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if(regEmail.test($("#email").val()) == false) {
                // invalid email address. Show error and let user retry.
                ev.preventDefault();
                $('#lyrisReturnStatus').jqmShow().oneTime(3500, "soon", function() {
                    $('#lyrisReturnStatus').jqmHide();
        });
        $("#output").html(invalidEmailAddressMessage);
        $("#email").select();
        return;
            }

            // Call the proxy to add the user
            var service = new WS("http://apps.ce.org/WebServices/LyrisProxy/Services/Lyris/JSONP/Lyris.asmx", WSDataType.jsonp);
            service.call("AddUser", { lyrisInstance:$("#lyrisInstance").val(), email:$("#email").val(), fullName:$("#fullName").val(), lyrisList:$("#lyrisList").val() }, function(AddUser) {
                var lyrisReturn = JSON.parse(AddUser);
                var goBack;
                var timeout;

                // See if the JSON returned is an error message and handle.
                if(typeof(lyrisReturn.ErrorMessage) !== 'undefined' && lyrisReturn.ErrorMessage != null) {
                    var pos=lyrisReturn.ErrorMessage.indexOf("member already exists");
                    if (pos>=0)
                    {
                        // Member already exists.
                        $("#output").html(userAlreadyExistsMessage);
                        goBack = true;
                    } else {
                        // Generic error.
                        $("#output").html(genericErrorMessage);
                        goBack = false;
                    }
                    timeout = 3500;
                }
                // See if the JSON returned the expected MemberID
                if(typeof(lyrisReturn.MemberID) !== 'undefined' && lyrisReturn.MemberID != null) {
                    $("#output").html(userSuccessfullyAddedMessage);
                    goBack = true;
                    timeout = 2000;
                }

                //Show the modal display with the appropriate messaging and redirect.
                ev.preventDefault();
                $('#lyrisReturnStatus').jqmShow().oneTime(timeout, "soon", function() {
                    $('#lyrisReturnStatus').jqmHide();
                    if(goBack) {
             history.go(-1);
         }
    });

            });
        });
        $('#lyrisReturnStatus').
          jqm({ overlay: 50, modal: true, trigger: false });
    });
</script>

A: Use a debugger to find the line with the error.


text:
Q: How to prevent the Firefox developer tools window from focusing on page reload? I've been annoyed by Firefox developer tools window always restoring from minimized state (focusing) every time the page I'm working on is reloaded.
I'm not sure if this is a quirk or a feature but it's sure annoying as hell.
I've observed this behavior in Firefox Developer Edition 69.0b16 as well as in standard Firefox release 67.0.4 running on Windows 10. Haven't tested other platforms but I might.
So far I've tried looking in the developer tools settings but there's nothing there. Reading all devtools.* items in about:config didn't turn up anything focus-related either.


text:
Q: Detail of all transactions on a specific row I've a User table and It's data can be added/ updated from a User Screen. I want detail of all transactions on any row.
For example, I have data in table like this

Name - Age -  Salary
John    -  25 - $10
Jazy    -  23 - $10

Then some user update john's Age like this

Name - Age -  Salary
John    -  20 - $10
Jazy    -  23 - $15

and then Update its Salary like this

Name - Age -  Salary
John    -  20 - $20
Jazy    -  23 - $15

I want a query to get all transactions on John's records like this

John    -  25 - $10
John    -  20 - $10
John    -  20 - $20

Is there any way to get data like this??

A: Edit: Forgot that Change data capture is already in 2008, you could use it to capture the data, or create your own log/history table using triggers or something similar.
If you were in SQL Server 2016, then you could use temporal tables


text:
Q: Helm configmap template not working when using files ---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Values.configMap.name | quote }}
  labels:
    name: {{ .Values.configMap.name | quote }}
data:
  application.yaml: |-
{{ .Files.Get "application.yaml" | indent 4}}
  otherFile.csv: |-
{{ .Files.Get "otherFile.csv" | indent 4}}

But I want to make the configmap more generic, so I was thinking on something like this:
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Values.configMap.name | quote }}
  labels:
    name: {{ .Values.configMap.name | quote }}
data:
  {{- range $data := .Values.configMap.data }}
  {{ $data }}: |-
    {{ .Files.Get $data | indent 4}}
  {{- end}}

And in the values.yaml to have something like this:
configMap:
  name: app-configmap
  data:
    - application.yaml
    - otherFile.csv

If I don't make it generic it works, but if I try to make it generic I get errors:
executing "app/templates/configmap.yaml" at <.Files.AsConfig>: wrong number of args for AsConfig: want 0 got 1
helm.go:84: [debug] template: app/templates/configmap.yaml:10:9: executing "app/templates/configmap.yaml" at <.Files.AsConfig>: wrong number of args for AsConfig: want 0 got 1

Any hint?


text:
Q: Remarkable limit and L'Hôpital $\lim_{x\to0}\left(\frac{a^x-x\ln a}{b^x-x\ln b}\right)^{1/x^2}$
Compute
  $$
\lim_{x\to0}\left(\frac{a^x-x\ln a}{b^x-x\ln b}\right)^{1/x^2}
$$
  where $a$ and $b$ are positive numbers.

I came to the two different forms of this limit, as $\lim_{x\to0}$

$$e^{\frac{\ln b-\ln b}{\ln a-\ln a+\ln b-\ln b}}$$
$$\frac{x^2\cdot a^x+1-\frac{a^2}x}{x^2\cdot b^x+1-\frac{b^2}x}$$
So, what I want to say is that I can't solve this problem and I'm here for any kind of help.

A: Compute the limit of the logarithm of your function
$$
\lim_{x\to0}\ln\left(
  \left(\frac{a^x-x\ln a}{b^x-x\ln b}\right)^{1/x^2}
\right)=
\lim_{x\to0}
\frac{\ln(a^x-x\ln a)-\ln(b^x-x\ln b)}{x^2}
$$
under the assumption that $a\ne b$ (if $a=b$ the limit is obvious).
Here applying L'Hôpital is quite easy. If you find the limit is $l$, then the required limit is $e^l$.
Note that you can just compute
$$
l_a=\lim_{x\to0}\frac{\ln(a^x-x\ln a)}{x^2}
$$
because the given limit will then be $l_a-l_b$.

A: Assuming that the desired limit is $L$ we can proceed as follows:
\begin{align}
\log L &= \log\left\{\lim_{x \to 0}\left(\frac{a^{x} - x\log a}{b^{x} - x\log b}\right)^{1/x^{2}}\right\}\notag\\
&= \lim_{x \to 0}\log\left(\frac{a^{x} - x\log a}{b^{x} - x\log b}\right)^{1/x^{2}}\text{ (via continuity of log)}\notag\\
&= \lim_{x \to 0}\frac{1}{x^{2}}\log\left(1 + \frac{a^{x} - x\log a - b^{x} + x\log b}{b^{x} - x\log b}\right)\notag\\
&= \lim_{x \to 0}\frac{1}{x^{2}}\cdot\frac{a^{x} - x\log a - b^{x} + x\log b}{b^{x} - x\log b}\cdot\dfrac{\log\left(1 + \dfrac{a^{x} - x\log a - b^{x} + x\log b}{b^{x} - x\log b}\right)}{\dfrac{a^{x} - x\log a - b^{x} + x\log b}{b^{x} - x\log b}}\notag\\
&= \lim_{x \to 0}\frac{1}{x^{2}}\cdot\frac{a^{x} - x\log a - b^{x} + x\log b}{b^{x} - x\log b}\notag\\
&= \lim_{x \to 0}\frac{a^{x} - b^{x} - x\log a + x\log b}{x^{2}}\tag{1}\\
&= \lim_{x \to 0}\frac{a^{x}\log a - b^{x}\log b - \log a + \log b}{2x}\text{ (via L'Hospital's Rule)}\notag\\
&= \frac{1}{2}\lim_{x \to 0}\log a\cdot\frac{a^{x} - 1}{x} - \log b\cdot\frac{b^{x} - 1}{x}\notag\\
&= \frac{(\log a)^{2} - (\log b)^{2}}{2}\notag
\end{align}
If you prefer the easier technique of Taylor series then you need to apply it after step marked $(1)$ and use the expansion $$a^{x} = 1 + x\log a + \frac{x^{2}}{2}(\log a)^{2} + o(x^{2})$$ This way you get the answer immediately.
Thus finally $$L = \exp\left(\frac{(\log a)^{2} - (\log b)^{2}}{2}\right)$$


text:
Q: Is there any way to not freeze up the UI when creating multiple HTMLAudioElement DOM elements The question in the title is pretty self-explanatory. I have this site that allows the user to upload multiple files at a time. And then it will go through and retrieve the duration for each one.
getDuration(file) {
    return new Promise(resolve => {
        let reader = new FileReader();
        reader.onload = e => {
            let audio = new Audio();
            audio.onloadeddata = () => {
                this.duration = audio.duration;
                resolve();
            };
            audio.src = e.target.result;
        };
        reader.readAsDataURL(file);
    });
}

But this, in Chrome at least, freezes up the UI pretty bad while it's doing all that processing. Is there anyway I could avoid this or go about this in a different way?

A: You can already start by not using a FileReader and data:// URIs
The FileReader will read all the File from the disk into memory, with a lot of Files, that's a lot of IO and your disk (HDD or SSD) will not like it.
Then creating a data:// URL from that file is not free operation, so it will take some CPU time.
Finally, the browser will have to decode back that data: URL to raw binary before it's able to even try to decode that data as audio. Once again a few unnecessary steps here, and a lot of wasted memory.
Instead, you could simply create a blob:// URL from the File your users sent and set your <audio>'s src to that. This will be a simple pointer to the actual File on the disk, so the browser will be able to stream-decode it and append only the chunks of data it needs in memory.
To create such a blob:// URL, you have to use the URL.createObejctURL() method.
Note that even though for Files from disk it's not that critical, you should get the good habit to revoke such blob:// URLs after you used it, because they'll blob the File from being Garbage Collected.

function getDuration(file) {
  return new Promise(resolve => {
    const audio = new Audio();
    audio.onloadedmetadata = () => {
      URL.revokeObjectURL(file)
      resolve(audio.duration);
    };
    audio.src = URL.createObjectURL(file);
  });
}
document.querySelector("input").oninput = async (evt) => {
  console.log( await getDuration( evt.target.files[0] ) );
}
<input type="file">


text:
Q: Script behavior changes if browser is headless or not I wrote a web scraping program on python (with selenium) which works very well. The last step was to add a headless functionality.
The problem is that when the script is running headless, at a specific moment (when it should click over a link to refresh the page), terminal gives me this error:
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element ... is not clickable at point (217, 157). Other element would receive the click: ...

The weird thing is that when the same script is not headless, selenium doesn't throw the error and all goes perfectly.
I have tried to reach the element using several methods but same error.
This is when the script decides if the browser is headless or not:
# create driver
if headless:
    chromedriver = './chromedriver'
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)
else:
    driver = webdriver.Chrome('./chromedriver')

The element I'm trying to click looks something like this:

refresh page!

and my script searches it by xpath on  tag.

A: The solution is to ensure that the window size is large enough for the objects to be clickable otherwise the window-size property is set to 0x0 and the objects will be coveing each other:
options.add_argument('window-size=2000x1500')
So to code will look like this:
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('window-size=2000x1500')

This works for chromedriver. I have not checked other headless browsers, but expect the same or similar behavior.

A: Try setting up a window size even if it's headless.
I don't remember this exactly, but I had the same error a couple of years back when I was writing End to End tests on selenium. I think it still needs a viewport size, probably the engine optimizes it to 0x0 by default if headless (?).


text:
Q: Creating shared library containing other libraries i've written a class from that i want to create a shared library. But this class uses other libraries. The call that i use to generate the library is of the form
    g++ -fpic -c [necessary *.cpp files] [necessary includes]
Unfortunately this call leads to an error, namely iostream.h: No such file or directory.
But when i build a testfile using the library code it compiles and works properly.
Where might be the problem?
Thanks for your help.

A: Firstly, I'm pretty sure that you should be using iostream rather than iostream.h so you could try changing that in your source code. E.g.
#include <iostream>

Secondly, you need to check the include directives on the compilation line, as what you're getting is a compilation error indicating that the preprocessor can't find this file. As you haven't listed either your failed or successful commands here, I can't add much more than that.


text:
Q: In app purchase receipt verification in iOS8 We are following the raywenderlinch tutorial from http://www.raywenderlich.com/23266/in-app-purchases-in-ios-6-tutorial-consumables-and-receipt-validation
But there are some error which I am getting when import verificationController classes in our project. Right now, I am using iOS8.
Error is: Implicit declaration of function 'checkReciptSecurity' is invalid in C99

I have also search for sample code of Verification class on apple developer site ,Their page is not found.
Please give me your view to solve this or provide the link of verification classes which are update to iOS8.

A: In VerificationController.h put the function prototype like this :
- (void)verifyPurchase:(SKPaymentTransaction *)transaction completionHandler:(VerifyCompletionHandler)completionHandler;
BOOL checkReceiptSecurity(NSString *purchase_info_string, NSString *signature_string, CFDateRef purchaseDate);

The reason of doing this is the line number calling the function checkReceiptSecurity is before the declaration of function.
You have to modified the VerificationController.m file code.
I have put the modified code here.
#import "VerificationController.h"
#import "NSData+Base64.h"

static VerificationController *singleton;

@implementation VerificationController {
    NSMutableDictionary * _completionHandlers;
}

+ (VerificationController *)sharedInstance
{
    if (singleton == nil)
    {
        singleton = [[VerificationController alloc] init];
    }
 return singleton;
}

 - (id)init
{
self = [super init];
if (self != nil)
{
    transactionsReceiptStorageDictionary = [[NSMutableDictionary alloc] init];
    _completionHandlers = [[NSMutableDictionary alloc] init];
   }
   return self;
}

- (NSDictionary *)dictionaryFromPlistData:(NSData *)data
{
NSError *error;
NSDictionary *dictionaryParsed = [NSPropertyListSerialization propertyListWithData:data
                                                                           options:NSPropertyListImmutable
                                                                            format:nil
                                                                             error:&error];
if (!dictionaryParsed)
{
    if (error)
    {
        NSLog(@"Error parsing plist");
    }
    return nil;
}
return dictionaryParsed;
}

- (NSDictionary *)dictionaryFromJSONData:(NSData *)data
{
NSError *error;
NSDictionary *dictionaryParsed = [NSJSONSerialization JSONObjectWithData:data
                                                                 options:0
                                                                   error:&error];
if (!dictionaryParsed)
{
    if (error)
    {
        NSLog(@"Error parsing dictionary");
    }
    return nil;
}
return dictionaryParsed;
}

#pragma mark Receipt Verification

// This method should be called once a transaction gets to the SKPaymentTransactionStatePurchased or    SKPaymentTransactionStateRestored state
// Call it with the SKPaymentTransaction.transactionReceipt
- (void)verifyPurchase:(SKPaymentTransaction *)transaction completionHandler:(VerifyCompletionHandler)completionHandler
{
BOOL isOk = [self isTransactionAndItsReceiptValid:transaction];
if (!isOk)
{
    // There was something wrong with the transaction we got back, so no need to call verifyReceipt.
    NSLog(@"Invalid transacion");
    completionHandler(FALSE);
    return;
}

// The transaction looks ok, so start the verify process.

// Encode the receiptData for the itms receipt verification POST request.
NSString *jsonObjectString = [self encodeBase64:(uint8_t *)transaction.transactionReceipt.bytes
                                         length:transaction.transactionReceipt.length];

// Create the POST request payload.
NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\", \"password\" : \"%@\"}",
                     jsonObjectString, ITC_CONTENT_PROVIDER_SHARED_SECRET];

NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];

#warning Check for the correct itms verify receipt URL
// Use ITMS_SANDBOX_VERIFY_RECEIPT_URL while testing against the sandbox.
NSString *serverURL = ITMS_SANDBOX_VERIFY_RECEIPT_URL; //ITMS_PROD_VERIFY_RECEIPT_URL;

// Create the POST request to the server.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverURL]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:payloadData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

_completionHandlers[[NSValue valueWithNonretainedObject:conn]] = completionHandler;

[conn start];

// The transation receipt has not been validated yet.  That is done from the NSURLConnection callback.
}

// Check the validity of the receipt.  If it checks out then also ensure the transaction is something
// we haven't seen before and then decode and save the purchaseInfo from the receipt for later receipt validation.
- (BOOL)isTransactionAndItsReceiptValid:(SKPaymentTransaction *)transaction
{
if (!(transaction && transaction.transactionReceipt && [transaction.transactionReceipt length] > 0))
{
    // Transaction is not valid.
    return NO;
}

// Pull the purchase-info out of the transaction receipt, decode it, and save it for later so
// it can be cross checked with the verifyReceipt.
NSDictionary *receiptDict       = [self dictionaryFromPlistData:transaction.transactionReceipt];
NSString *transactionPurchaseInfo = [receiptDict objectForKey:@"purchase-info"];
NSString *decodedPurchaseInfo   = [self decodeBase64:transactionPurchaseInfo length:nil];
NSDictionary *purchaseInfoDict  = [self dictionaryFromPlistData:[decodedPurchaseInfo dataUsingEncoding:NSUTF8StringEncoding]];

NSString *transactionId         = [purchaseInfoDict objectForKey:@"transaction-id"];
NSString *purchaseDateString    = [purchaseInfoDict objectForKey:@"purchase-date"];
NSString *signature             = [receiptDict objectForKey:@"signature"];

// Convert the string into a date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];

NSDate *purchaseDate = [dateFormat dateFromString:[purchaseDateString stringByReplacingOccurrencesOfString:@"Etc/" withString:@""]];

if (![self isTransactionIdUnique:transactionId])
{
    // We've seen this transaction before.
    // Had [transactionsReceiptStorageDictionary objectForKey:transactionId]
    // Got purchaseInfoDict
    return NO;
}

// Check the authenticity of the receipt response/signature etc.

BOOL result = checkReceiptSecurity(transactionPurchaseInfo, signature,
                                   (__bridge CFDateRef)(purchaseDate));

if (!result)
{
    return NO;
}

// Ensure the transaction itself is legit
if (![self doTransactionDetailsMatchPurchaseInfo:transaction withPurchaseInfo:purchaseInfoDict])
{
    return NO;
}

// Make a note of the fact that we've seen the transaction id already
[self saveTransactionId:transactionId];

// Save the transaction receipt's purchaseInfo in the transactionsReceiptStorageDictionary.
[transactionsReceiptStorageDictionary setObject:purchaseInfoDict forKey:transactionId];

return YES;
}

// Make sure the transaction details actually match the purchase info
- (BOOL)doTransactionDetailsMatchPurchaseInfo:(SKPaymentTransaction *)transaction withPurchaseInfo:(NSDictionary *)purchaseInfoDict

{
if (!transaction || !purchaseInfoDict)
{
    return NO;
}

int failCount = 0;

if (![transaction.payment.productIdentifier isEqualToString:[purchaseInfoDict objectForKey:@"product-id"]])
{

    failCount++;
}

if (transaction.payment.quantity != [[purchaseInfoDict objectForKey:@"quantity"] intValue])
{
    failCount++;
}

if (![transaction.transactionIdentifier isEqualToString:[purchaseInfoDict objectForKey:@"transaction-id"]])
{
    failCount++;
}

// Optionally check the bid and bvrs match this app's current bundle ID and bundle version.
// Optionally check the requestData.
// Optionally check the dates.

if (failCount != 0)
{
    return NO;
}

// The transaction and its signed content seem ok.
return YES;
}

- (BOOL)isTransactionIdUnique:(NSString *)transactionId
{
NSString *transactionDictionary = KNOWN_TRANSACTIONS_KEY;
// Save the transactionId to the standardUserDefaults so we can check against that later
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults synchronize];

if (![defaults objectForKey:transactionDictionary])
{
    [defaults setObject:[[NSMutableDictionary alloc] init] forKey:transactionDictionary];
    [defaults synchronize];
}

if (![[defaults objectForKey:transactionDictionary] objectForKey:transactionId])
{
    return YES;
}
// The transaction already exists in the defaults.
return NO;
}

- (void)saveTransactionId:(NSString *)transactionId
{
// Save the transactionId to the standardUserDefaults so we can check against that later
// If dictionary exists already then retrieve it and add new transactionID
// Regardless save transactionID to dictionary which gets saved to NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *transactionDictionary = KNOWN_TRANSACTIONS_KEY;
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithDictionary:
                                   [defaults objectForKey:transactionDictionary]];
if (!dictionary)
{
    dictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:1], transactionId, nil];
} else {
    [dictionary setObject:[NSNumber numberWithInt:1] forKey:transactionId];
}
[defaults setObject:dictionary forKey:transactionDictionary];
[defaults synchronize];

}

- (BOOL)doesTransactionInfoMatchReceipt:(NSString*) receiptString
{
// Convert the responseString into a dictionary and pull out the receipt data.
NSDictionary *verifiedReceiptDictionary = [self dictionaryFromJSONData:[receiptString dataUsingEncoding:NSUTF8StringEncoding]];

// Check the status of the verifyReceipt call
id status = [verifiedReceiptDictionary objectForKey:@"status"];
if (!status)
{
    return NO;
}
int verifyReceiptStatus = [status integerValue];
// 21006 = This receipt is valid but the subscription has expired.
if (0 != verifyReceiptStatus && 21006 != verifyReceiptStatus)
{
    return NO;
}

// The receipt is valid, so checked the receipt specifics now.

NSDictionary *verifiedReceiptReceiptDictionary  = [verifiedReceiptDictionary objectForKey:@"receipt"];
NSString *verifiedReceiptUniqueIdentifier       = [verifiedReceiptReceiptDictionary objectForKey:@"unique_identifier"];
NSString *transactionIdFromVerifiedReceipt      = [verifiedReceiptReceiptDictionary objectForKey:@"transaction_id"];

// Get the transaction's receipt data from the transactionsReceiptStorageDictionary
NSDictionary *purchaseInfoFromTransaction = [transactionsReceiptStorageDictionary objectForKey:transactionIdFromVerifiedReceipt];

if (!purchaseInfoFromTransaction)
{
    // We didn't find a receipt for this transaction.
    return NO;
}

// NOTE: Instead of counting errors you could just return early.
int failCount = 0;

// Verify all the receipt specifics to ensure everything matches up as expected
if (![[verifiedReceiptReceiptDictionary objectForKey:@"bid"]
      isEqualToString:[purchaseInfoFromTransaction objectForKey:@"bid"]])
{
    failCount++;
}

if (![[verifiedReceiptReceiptDictionary objectForKey:@"product_id"]
      isEqualToString:[purchaseInfoFromTransaction objectForKey:@"product-id"]])
{
    failCount++;
}

if (![[verifiedReceiptReceiptDictionary objectForKey:@"quantity"]
      isEqualToString:[purchaseInfoFromTransaction objectForKey:@"quantity"]])
{
    failCount++;
}

if (![[verifiedReceiptReceiptDictionary objectForKey:@"item_id"]
      isEqualToString:[purchaseInfoFromTransaction objectForKey:@"item-id"]])
{
    failCount++;
}

if ([[UIDevice currentDevice] respondsToSelector:NSSelectorFromString(@"identifierForVendor")]) // iOS 6?
{
#if IS_IOS6_AWARE
    // iOS 6 (or later)
    NSString *localIdentifier                   = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSString *purchaseInfoUniqueVendorId        = [purchaseInfoFromTransaction objectForKey:@"unique-vendor-identifier"];
    NSString *verifiedReceiptVendorIdentifier   = [verifiedReceiptReceiptDictionary objectForKey:@"unique_vendor_identifier"];

    if(verifiedReceiptVendorIdentifier)
    {
        if (![purchaseInfoUniqueVendorId isEqualToString:verifiedReceiptVendorIdentifier]
            || ![purchaseInfoUniqueVendorId isEqualToString:localIdentifier])
        {
            // Comment this line out to test in the Simulator.
            failCount++;
        }
    }
#endif
} else {
    // Pre iOS 6
//        NSString *localIdentifier           = [UIDevice currentDevice].uniqueIdentifier;
//        NSString *purchaseInfoUniqueId      = [purchaseInfoFromTransaction objectForKey:@"unique-identifier"];
//        if (![purchaseInfoUniqueId isEqualToString:verifiedReceiptUniqueIdentifier]
//            || ![purchaseInfoUniqueId isEqualToString:localIdentifier])
//        {
//            // Comment this line out to test in the Simulator.
//            failCount++;
//        }
}

// Do addition time checks for the transaction and receipt.

if(failCount != 0)
{
    return NO;
}

return YES;
}

#pragma mark NSURLConnectionDelegate (for the verifyReceipt connection)

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

NSLog(@"Connection failure: %@", error);

VerifyCompletionHandler completionHandler = _completionHandlers[[NSValue valueWithNonretainedObject:connection]];
[_completionHandlers removeObjectForKey:[NSValue valueWithNonretainedObject:connection]];
completionHandler(FALSE);

}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

BOOL isOk = [self doesTransactionInfoMatchReceipt:responseString];

VerifyCompletionHandler completionHandler = _completionHandlers[[NSValue valueWithNonretainedObject:connection]];
[_completionHandlers removeObjectForKey:[NSValue valueWithNonretainedObject:connection]];
if (isOk)
{
    //Validation suceeded. Unlock content here.
    NSLog(@"Validation successful");
    completionHandler(TRUE);

} else {
    NSLog(@"Validation failed");
    completionHandler(FALSE);
}
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([[[challenge protectionSpace] authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
{
    SecTrustRef trust = [[challenge protectionSpace] serverTrust];
    NSError *error = nil;
    BOOL didUseCredential = NO;
    BOOL isTrusted = [self validateTrust:trust error:&error];
    if (isTrusted)
    {
        NSURLCredential *trust_credential = [NSURLCredential credentialForTrust:trust];
        if (trust_credential)
        {
            [[challenge sender] useCredential:trust_credential forAuthenticationChallenge:challenge];
            didUseCredential = YES;
        }
    }
    if (!didUseCredential)
    {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
} else {
    [[challenge sender] performDefaultHandlingForAuthenticationChallenge:challenge];
}
}

// NOTE: These are needed for 4.x (as willSendRequestForAuthenticationChallenge: is not supported)
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([[[challenge protectionSpace] authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
    SecTrustRef trust = [[challenge protectionSpace] serverTrust];
    NSError *error = nil;
    BOOL didUseCredential = NO;
    BOOL isTrusted = [self validateTrust:trust error:&error];
    if (isTrusted)
    {
        NSURLCredential *credential = [NSURLCredential credentialForTrust:trust];
        if (credential)
        {
            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
            didUseCredential = YES;
        }
    }
    if (! didUseCredential) {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
} else {
    [[challenge sender] performDefaultHandlingForAuthenticationChallenge:challenge];
}
}

#pragma mark
#pragma mark NSURLConnection - Trust validation

- (BOOL)validateTrust:(SecTrustRef)trust error:(NSError **)error
{

// Include some Security framework SPIs
extern CFStringRef kSecTrustInfoExtendedValidationKey;
extern CFDictionaryRef SecTrustCopyInfo(SecTrustRef trust);

BOOL trusted = NO;
SecTrustResultType trust_result;
if ((noErr == SecTrustEvaluate(trust, &trust_result)) && (trust_result == kSecTrustResultUnspecified))
{
    NSDictionary *trust_info = (__bridge_transfer NSDictionary *)SecTrustCopyInfo(trust);
    id hasEV = [trust_info objectForKey:(__bridge NSString *)kSecTrustInfoExtendedValidationKey];
    trusted =  [hasEV isKindOfClass:[NSValue class]] && [hasEV boolValue];
}

if (trust)
{
    if (!trusted && error)
    {
        *error = [NSError errorWithDomain:@"kSecTrustError" code:(NSInteger)trust_result userInfo:nil];
    }
    return trusted;
}
return NO;
}
#pragma mark
#pragma mark Base 64 encoding

- (NSString *)encodeBase64:(const uint8_t *)input length:(NSInteger)length
{
NSData * data = [NSData dataWithBytes:input length:length];
return [data base64EncodedString];
}
- (NSString *)decodeBase64:(NSString *)input length:(NSInteger *)length
{
NSData * data = [NSData dataFromBase64String:input];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

char* base64_encode(const void* buf, size_t size) {
size_t outputLength;
return NewBase64Encode(buf, size, NO, &outputLength);
}
void * base64_decode(const char* s, size_t * data_len)
{
 return NewBase64Decode(s, strlen(s), data_len);
}
@end
#pragma mark
#pragma mark Check Receipt signature
#include <CommonCrypto/CommonDigest.h>
#include <Security/Security.h>
#include <AssertMacros.h>
unsigned int iTS_intermediate_der_len = 1039;

unsigned char iTS_intermediate_der[] = {
put the hexacode here
};

BOOL checkReceiptSecurity(NSString *purchase_info_string, NSString *signature_string, CFDateRef purchaseDate)
{
BOOL valid = NO;
SecCertificateRef leaf = NULL, intermediate = NULL;
SecTrustRef trust = NULL;
SecPolicyRef policy = SecPolicyCreateBasicX509();

NSData *certificate_data;
NSArray *anchors;

/*
 Parse inputs:
 purchase_info_string and signature_string are base64 encoded JSON blobs that need to
 be decoded.
 */

require([purchase_info_string canBeConvertedToEncoding:NSASCIIStringEncoding] &&
        [signature_string canBeConvertedToEncoding:NSASCIIStringEncoding], outLabel);

size_t purchase_info_length;
uint8_t *purchase_info_bytes = base64_decode([purchase_info_string cStringUsingEncoding:NSASCIIStringEncoding],
                                             &purchase_info_length);

size_t signature_length;
uint8_t *signature_bytes = base64_decode([signature_string cStringUsingEncoding:NSASCIIStringEncoding],
                                         &signature_length);

require(purchase_info_bytes && signature_bytes, outLabel);

/*
 Binary format looks as follows:

 RECEIPTVERSION | SIGNATURE | CERTIFICATE SIZE | CERTIFICATE
 1 byte           128         4 bytes
 big endian

 Extract version, signature and certificate(s).
 Check receipt version == 2.
 Sanity check that signature is 128 bytes.
 Sanity check certificate size <= remaining payload data.
 */

#pragma pack(push, 1)
struct signature_blob {
    uint8_t version;
    uint8_t signature[128];
    uint32_t cert_len;
    uint8_t certificate[];
} *signature_blob_ptr = (struct signature_blob *)signature_bytes;
#pragma pack(pop)
uint32_t certificate_len;

/*
 Make sure the signature blob is long enough to safely extract the version and
 cert_len fields, then perform a sanity check on the fields.
 */
require(signature_length > offsetof(struct signature_blob, certificate), outLabel);
require(signature_blob_ptr->version == 2, outLabel);
certificate_len = ntohl(signature_blob_ptr->cert_len);

require(signature_length - offsetof(struct signature_blob, certificate) >= certificate_len, outLabel);

/*
 Validate certificate chains back to valid receipt signer; policy approximation for now
 set intermediate as a trust anchor; current intermediate lapses in 2016.
 */

certificate_data = [NSData dataWithBytes:signature_blob_ptr->certificate length:certificate_len];
require(leaf = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certificate_data), outLabel);

certificate_data = [NSData dataWithBytes:iTS_intermediate_der length:iTS_intermediate_der_len];
require(intermediate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certificate_data), outLabel);

anchors = [NSArray arrayWithObject:(__bridge id)intermediate];
require(anchors, outLabel);

require_noerr(SecTrustCreateWithCertificates(leaf, policy, &trust), outLabel);
require_noerr(SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef) anchors), outLabel);

if (purchaseDate)
{
    require_noerr(SecTrustSetVerifyDate(trust, purchaseDate), outLabel);
}

SecTrustResultType trust_result;
require_noerr(SecTrustEvaluate(trust, &trust_result), outLabel);
require(trust_result == kSecTrustResultUnspecified, outLabel);

require(2 == SecTrustGetCertificateCount(trust), outLabel);

/*
 Chain is valid, use leaf key to verify signature on receipt by
 calculating SHA1(version|purchaseInfo)
 */

CC_SHA1_CTX sha1_ctx;
uint8_t to_be_verified_data[CC_SHA1_DIGEST_LENGTH];

CC_SHA1_Init(&sha1_ctx);
CC_SHA1_Update(&sha1_ctx, &signature_blob_ptr->version, sizeof(signature_blob_ptr->version));
CC_SHA1_Update(&sha1_ctx, purchase_info_bytes, purchase_info_length);
CC_SHA1_Final(to_be_verified_data, &sha1_ctx);

SecKeyRef receipt_signing_key = SecTrustCopyPublicKey(trust);
require(receipt_signing_key, outLabel);
require_noerr(SecKeyRawVerify(receipt_signing_key, kSecPaddingPKCS1SHA1,
                              to_be_verified_data, sizeof(to_be_verified_data),
                              signature_blob_ptr->signature, sizeof(signature_blob_ptr->signature)),
              outLabel);

/*
 Optional:  Verify that the receipt certificate has the 1.2.840.113635.100.6.5.1 Null OID

 The signature is a 1024-bit RSA signature.
 */

valid = YES;

outLabel:
if (leaf) CFRelease(leaf);
if (intermediate) CFRelease(intermediate);
if (trust) CFRelease(trust);
if (policy) CFRelease(policy);

return valid;
}


text:
Q: Is it possible to filter tweets as they are being scraped by number of retweets or likes in twint or getoldtweets3? import twint

c = twint.Config()
c.Hide_output = True
c.Search = "TSLA"
c.Lang = "en"
c.Since = "2019-10-01 00:00:00"
c.Until = "2019-10-10 00:00:00"
c.Store_csv = True
c.Output = "TSLA.csv"

twint.run.Search(c)

This code takes a lot of time to execute and gets me 10,600 tweets, most of which add no value. I simply need tweets where retweets or likes are greater than a threshold. Unfortunately, documentation on twint and getoldtweets3 is quite light. Does anyone have any experience with this please?

A: try this code
c.Lang = "en"
c.Search = "TSLA"
StartDate = "2019-10-01"
EndDate = "2019-10-10"
c.Since = StartDate
c.Until = EndDate
c.Filter_retweets = True
c.Store_csv = True
c.min_likes = 5

A: Try to include min_retweets:20 or min_faves:20 (specifying the threshold) in the c.Search object.
c.Search = "TSLA min_retweets:20"


text:
Q: In how many ways can $5$ Indians, $4$ Chinese, and $3$ Americans be assigned to $12$ stations so that no two Americans serve at consecutive stations? On a railway route from Delhi to Jaipur there are $12$ stations . A booking clerk is to be deputed for each of these stations out of $12$ candidates of whom $5$ are Indians , $4$ are Chinese and the rest are Americans . The number of ways of deputing the persons on these stations so that no two Americans serve on two  consecutive stations is
My Approach : Since there are $12$ stations ...and the number of Americans are $3$  , so simply we can select three stations which should not be consecutive .. and the ways to select things which are not consecutive is C($n$$+r$$-$$1$, $r$)..
After substituting value of $n$ as 12 and $r$ as 3 answer is not coming correct ...
Please tell the correct approach...

A: I will assume that people of each nationality are distinguishable.
There are $9!$ ways of arranging the four Chinese and five Indian candidates in a row.  To ensure no two Americans are consecutive, we must place the American candidates in the eight spaces between the other candidates or the two spaces at the ends of the row.  We choose three of these ten spaces in which to place the American candidates.  The Americans can be arranged in the three chosen spaces in $3!$ ways.  Hence, the number of ways the candidates can be assigned so that no two Americans serve at consecutive stations is
$$9!\binom{10}{3}3!$$
Note: The number
$$\binom{n + r - 1}{n - 1} = \binom{n + r - 1}{r}$$
is the number of ways $r$ objects can be selected from $n$ types of objects, which is equal to the number of solutions of the equation
$$x_1 + x_2 + \cdots + x_n = r$$
in the non-negative integers.