问:
Making a very simple graph with uibezierpath
my question was

I want to create a simple line graph with certain values. This is done in a view within the mainviewcontroller. I created a UIview named chart. I pass the data to the chart when its retrieved from the API. I figured out how to draw the axis but I am stuck now. I cant find anything on google on how to set labels on intervals and to make the points appear dynamically.

draw the xasis and its labels.

draw the dots in the graph.

My salution

i figured out how to do all the things i asked for.

The code I have now:

```<code>class ChartView: UIView {

//some variables
var times: [String] = []
var AmountOfRain: [Double] = []
let pathy = UIBezierPath()
let pathx = UIBezierPath()
var beginwitharray = Array<CGFloat>()

// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
    // Drawing code

    //draw the y line
    pathy.move(to: CGPoint(x: 30, y: 10))
    pathy.addLine(to: CGPoint(x: 30, y: 10))
    pathy.addLine(to: CGPoint(x: 30, y: frame.size.height - 30))
    UIColor.black.setStroke()
    pathy.lineWidth = 1.0
    pathy.stroke()

    //draw the x line
    pathx.move(to: CGPoint(x: 30, y: frame.size.height - 30))
    pathx.addLine(to: CGPoint(x: 30, y: frame.size.height - 30))
    pathx.addLine(to: CGPoint(x: frame.size.width - 30, y: frame.size.height - 30))
    UIColor.black.setStroke()
    pathx.lineWidth = 1.0
    pathx.stroke()

    //when the data arrives form the SUPER slow duienradar API refresh it with the data
    if beginwitharray != []{
        //remove the label retriving data
        let label = viewWithTag(1)
        DispatchQueue.main.sync {
            label?.removeFromSuperview()
        }
        //create the dots in the graph
        var point = CGPoint()
        //simple way to do 2 loop in 1 loop.
        var intforbeginarray = 0
        let stoke = UIBezierPath()
        //get the first 6 itmes out of the rain array cuz of space issues
        let first6aumountarray = AmountOfRain[0...5]
        stoke.move(to: CGPoint(x: 30, y: self.frame.size.height - 30))

        //loop trough the data in the amounts array
        for amount in first6aumountarray{
            //determen the hight of the dot
            let InitialHeight = (CGFloat(amount) * (self.frame.size.height - 30))/6
            let pointHeight = (frame.size.height - 30) - InitialHeight

                //make the point so we can draw it using UIbezierpath()
                point = CGPoint(x: beginwitharray[intforbeginarray] + 20, y: pointHeight)
                intforbeginarray += 1

                //create the dot
                let dot = UIBezierPath()
                dot.addArc(withCenter: point, radius: CGFloat(5), startAngle: CGFloat(0), endAngle: CGFloat(360), clockwise: true)
                UIColor.black.setFill()
                dot.lineWidth = 30
                dot.fill()

                //create the line between dots will give a warning on the last one cuz the last one doenst go anyway
                stoke.addLine(to: point)
                stoke.move(to: point)
                stoke.lineWidth = 1
                UIColor.black.setStroke()
        }
        //make the strokes
        stoke.stroke()
    }
}
func getvalues(RainData: [Double], TimesData:[String]){

    //assing the data to the subview
    self.AmountOfRain = RainData
    self.times = TimesData

    //xaxis values
    let maxint = [0, 1, 2, 3, 4, 5, 6]

    //calculate the hight spacing to fit the graph
    let heightperstep = ((self.frame.size.height - 5)/6)-5
    var beginheight = self.frame.size.height - 35

    //calculate the width spacing to fit the graph
    let widthperstep = ((self.frame.size.width - 5)/6)-5
    var beginwith = CGFloat(30)

    //extra check to see if we have data at all.
    if times != []{
        //get the first 6 items out of the times array for use in our graph
        let first6 = times[0...5]
        //draw the label on the main queue
        DispatchQueue.main.sync {
            //draw the xaxis labels accroding to the spacing
            for number in maxint{
                let label = UILabel(frame: CGRect(x: 5, y: beginheight, width: 25, height: 15))
                label.text = "\(number)"
                self.addSubview(label)
                beginheight = beginheight - heightperstep
            }
            //draw the yaxis labels according to the spacing
            for time in first6{
                let label = UILabel(frame: CGRect(x: beginwith, y: self.frame.size.height - 20, width: 55, height: 15))
                label.text = time
                self.addSubview(label)
                beginwitharray.append(beginwith)
                beginwith = beginwith + widthperstep
            }
        }
    }
    //redrawthe graph with new data.
    setNeedsDisplay()
}}
</code>```

Any help would be appreciated. I also can't use a lib or a pod since this is a school project and I need to create a simple graph.

EDIT:

Completed my code, cleared up an error when running this code

What I did first was to draw the x-asis and the y-axis. After this I considered reasonable values for the aumountofrain data. this turns out cannot really be higher then 6. Since I could fit around 6 labels in the space I have the steps where easy go down by 1 till I hit 0. The calculations I did are for my specific frame height. After I figured it all out and the padding for the y-asxis. It was a matter of figuring out how to get the dots in the right place. Since I already have the data in the beginwitharray I just needed to calculate the height. Then it was simply loop trough the data and draw each dot. Then I just had to connect the dots using the uibezierpath.

i hope my troubles will save someone a lot of time when they read how i done it.

答:
This might be helpful: Draw Graph curves with UIBezierPath

Essentially what you need to do is for every data set you have you need to know the y-axis range of values and based on those ranges assign each value a CGFloat value (in your case inches of rain needs to correlate to a certain CGFloat value). Let's say you have your set amountOfRain = [0.1, 1.3, 1.5, 0.9, 0.1, 0] so your range is var rangeY = amountOfRain.max() - amountOfRain.min(). now lets find out where your first data point 0.1 should go on your graph by converting inches of rain to a CGFloat value that corresponds to the axis you've drawn already, this equation is just basic algebra: let y1 = (amountOfRain[0]/rangeY)*((frame.size.height-30) - 10) + 10 now it looks like your rain samples are at regular intervals so maybe let x1:CGFloat = 10 now you can add a dot or something at the CGPoint corresponding with (x1,y1). If you did this with all the data points it would create a graph that has your maximum value at the top of the graph and minimum value at the bottom. Good Luck!

Body:
my question was

I want to create a simple line graph with certain values. This is done in a view within the mainviewcontroller. I created a UIview named chart. I pass the data to the chart when its retrieved from the API. I figured out how to draw the axis but I am stuck now. I cant find anything on google on how to set labels on intervals and to make the points appear dynamically.

draw the xasis and its labels.

draw the dots in the graph.

My salution

i figured out how to do all the things i asked for.

The code I have now:

class ChartView: UIView {

//some variables
var times: [String] = []
var AmountOfRain: [Double] = []
let pathy = UIBezierPath()
let pathx = UIBezierPath()
var beginwitharray = Array<CGFloat>()

// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
    // Drawing code

    //draw the y line
    pathy.move(to: CGPoint(x: 30, y: 10))
    pathy.addLine(to: CGPoint(x: 30, y: 10))
    pathy.addLine(to: CGPoint(x: 30, y: frame.size.height - 30))
    UIColor.black.setStroke()
    pathy.lineWidth = 1.0
    pathy.stroke()

    //draw the x line
    pathx.move(to: CGPoint(x: 30, y: frame.size.height - 30))
    pathx.addLine(to: CGPoint(x: 30, y: frame.size.height - 30))
    pathx.addLine(to: CGPoint(x: frame.size.width - 30, y: frame.size.height - 30))
    UIColor.black.setStroke()
    pathx.lineWidth = 1.0
    pathx.stroke()

    //when the data arrives form the SUPER slow duienradar API refresh it with the data
    if beginwitharray != []{
        //remove the label retriving data
        let label = viewWithTag(1)
        DispatchQueue.main.sync {
            label?.removeFromSuperview()
        }
        //create the dots in the graph
        var point = CGPoint()
        //simple way to do 2 loop in 1 loop.
        var intforbeginarray = 0
        let stoke = UIBezierPath()
        //get the first 6 itmes out of the rain array cuz of space issues
        let first6aumountarray = AmountOfRain[0...5]
        stoke.move(to: CGPoint(x: 30, y: self.frame.size.height - 30))

        //loop trough the data in the amounts array
        for amount in first6aumountarray{
            //determen the hight of the dot
            let InitialHeight = (CGFloat(amount) * (self.frame.size.height - 30))/6
            let pointHeight = (frame.size.height - 30) - InitialHeight

                //make the point so we can draw it using UIbezierpath()
                point = CGPoint(x: beginwitharray[intforbeginarray] + 20, y: pointHeight)
                intforbeginarray += 1

                //create the dot
                let dot = UIBezierPath()
                dot.addArc(withCenter: point, radius: CGFloat(5), startAngle: CGFloat(0), endAngle: CGFloat(360), clockwise: true)
                UIColor.black.setFill()
                dot.lineWidth = 30
                dot.fill()

                //create the line between dots will give a warning on the last one cuz the last one doenst go anyway
                stoke.addLine(to: point)
                stoke.move(to: point)
                stoke.lineWidth = 1
                UIColor.black.setStroke()
        }
        //make the strokes
        stoke.stroke()
    }
}
func getvalues(RainData: [Double], TimesData:[String]){

    //assing the data to the subview
    self.AmountOfRain = RainData
    self.times = TimesData

    //xaxis values
    let maxint = [0, 1, 2, 3, 4, 5, 6]

    //calculate the hight spacing to fit the graph
    let heightperstep = ((self.frame.size.height - 5)/6)-5
    var beginheight = self.frame.size.height - 35

    //calculate the width spacing to fit the graph
    let widthperstep = ((self.frame.size.width - 5)/6)-5
    var beginwith = CGFloat(30)

    //extra check to see if we have data at all.
    if times != []{
        //get the first 6 items out of the times array for use in our graph
        let first6 = times[0...5]
        //draw the label on the main queue
        DispatchQueue.main.sync {
            //draw the xaxis labels accroding to the spacing
            for number in maxint{
                let label = UILabel(frame: CGRect(x: 5, y: beginheight, width: 25, height: 15))
                label.text = "\(number)"
                self.addSubview(label)
                beginheight = beginheight - heightperstep
            }
            //draw the yaxis labels according to the spacing
            for time in first6{
                let label = UILabel(frame: CGRect(x: beginwith, y: self.frame.size.height - 20, width: 55, height: 15))
                label.text = time
                self.addSubview(label)
                beginwitharray.append(beginwith)
                beginwith = beginwith + widthperstep
            }
        }
    }
    //redrawthe graph with new data.
    setNeedsDisplay()
}}

Any help would be appreciated. I also can't use a lib or a pod since this is a school project and I need to create a simple graph.

EDIT:

Completed my code, cleared up an error when running this code

What I did first was to draw the x-asis and the y-axis. After this I considered reasonable values for the aumountofrain data. this turns out cannot really be higher then 6. Since I could fit around 6 labels in the space I have the steps where easy go down by 1 till I hit 0. The calculations I did are for my specific frame height. After I figured it all out and the padding for the y-asxis. It was a matter of figuring out how to get the dots in the right place. Since I already have the data in the beginwitharray I just needed to calculate the height. Then it was simply loop trough the data and draw each dot. Then I just had to connect the dots using the uibezierpath.

i hope my troubles will save someone a lot of time when they read how i done it.


来源: stackexchange

问:
Dealing with jumps/discontinuities in Modelica
I was wondering if anyone had any tips or tricks in terms of dealing with jumps/discontinuities in Modelica. I'm using OpenModelica, and a simplified example code for my problem is shown below.

```<code>model PowerGenerator
  Modelica.SIunits.Power P(start=0);
  output Modelica.SIunits.Energy E;
equation
if (5 < time) and (time < 15) then P = 3;
  else P = 0;
  end if;
  der(E) = P;
end PowerGenerator;
</code>```

How can I make the jumps at 5 and 15 sec into continuous transitions, where the derivative of the slope is finite? I've tried the noEvent and smooth functions, but I haven't been able to make them do what I need.

Edit:
The issue in my main model is that these events induce chattering, and so I also need it to work in real-time. Also in my full model, the events are state events, and so the time is not known.

答:
Perhaps a behavior like the code below is what you were looking?

```<code>model PowerGenerator
  Modelica.SIunits.Power Plow;
  Modelica.SIunits.Power Phigh;
  Modelica.SIunits.Power P(start=0);
  output Modelica.SIunits.Energy E;

  Modelica.SIunits.Power Pold(start=0);
  output Modelica.SIunits.Energy Eold;

equation
  if (5 < time) and (time < 15) then
    Pold = 3;
  else
    Pold = 0;
  end if;
  der(Eold) = Pold;

  Plow = Modelica.Media.Air.MoistAir.Utilities.spliceFunction(3,0,time-5,1);
  Phigh = Modelica.Media.Air.MoistAir.Utilities.spliceFunction(0,3,time-15,1);
  P = Modelica.Media.Air.MoistAir.Utilities.spliceFunction(Phigh,Plow,time-10,1);
  der(E) = P;
end Power Generator;
</code>```

Below is the plot of the outputs:

ContentLicense: CC BY-SA 3.0

Body:
I was wondering if anyone had any tips or tricks in terms of dealing with jumps/discontinuities in Modelica. I'm using OpenModelica, and a simplified example code for my problem is shown below.

model PowerGenerator
  Modelica.SIunits.Power P(start=0);
  output Modelica.SIunits.Energy E;
equation
if (5 < time) and (time < 15) then P = 3;
  else P = 0;
  end if;
  der(E) = P;
end PowerGenerator;

How can I make the jumps at 5 and 15 sec into continuous transitions, where the derivative of the slope is finite? I've tried the noEvent and smooth functions, but I haven't been able to make them do what I need.

Edit:
The issue in my main model is that these events induce chattering, and so I also need it to work in real-time. Also in my full model, the events are state events, and so the time is not known.

Body:
Perhaps a behavior like the code below is what you were looking?

model PowerGenerator
  Modelica.SIunits.Power Plow;
  Modelica.SIunits.Power Phigh;
  Modelica.SIunits.Power P(start=0);
  output Modelica.SIunits.Energy E;

  Modelica.SIunits.Power Pold(start=0);
  output Modelica.SIunits.Energy Eold;

equation
  if (5 < time) and (time < 15) then
    Pold = 3;
  else
    Pold = 0;
  end if;
  der(Eold) = Pold;

  Plow = Modelica.Media.Air.MoistAir.Utilities.spliceFunction(3,0,time-5,1);
  Phigh = Modelica.Media.Air.MoistAir.Utilities.spliceFunction(0,3,time-15,1);
  P = Modelica.Media.Air.MoistAir.Utilities.spliceFunction(Phigh,Plow,time-10,1);
  der(E) = P;
end Power Generator;

Below is the plot of the outputs:


问:
Join two tables with same rows in SQL
Suppose I have two table like this:

```<code>table 1:               table 2:
id      city           id      heading
1201     X             1201     A
1202     Y             1201     B
1203     Z             1202     C
1204     U             1202     D
                       1204     F
</code>```

I want Output like this:

```<code>id  city id  heading
1201 X   1201  A
*null*   1201  B
1202 Y   1202  C
*null*   1202  D
1203 Z   *null*
1204 U   1204 F
</code>```

Kindly Help me with this.

Python is also acceptable if possible.

答:
You are looking for full outer join :

```<code>SELECT * FROM table1 FULL OUTER JOIN table2 on table1.id=table2.id
</code>```

Title: Join two tables with same rows in SQL

Body:
Suppose I have two table like this:

table 1:               table 2:
id      city           id      heading
1201     X             1201     A
1202     Y             1201     B
1203     Z             1202     C
1204     U             1202     D
                       1204     F

I want Output like this:

id  city id  heading
1201 X   1201  A
*null*   1201  B
1202 Y   1202  C
*null*   1202  D
1203 Z   *null*
1204 U   1204 F

Kindly Help me with this.

Python is also acceptable if possible.

Body:
You are looking for full outer join :

SELECT * FROM table1 FULL OUTER JOIN table2 on table1.id=table2.id


问:
How to filter a numpy array based on two conditions: one depending on the other?
I am using the cv2 library to detect key points of 2 stereo images and converted the resulting dmatches objects to a numpy array:

```<code>kp_left, des_left = sift.detectAndCompute(im_left, mask_left)
matches = bf.match(des_left, des_right)  # according to assignment pdf
np_matches = dmatch2np(matches)
</code>```

Then I want to filter matches if the key points are filtering, after y-direction, which should not differ bigger than 3 pixels:

```<code>ind = np.where(np.abs(kp_left[np_matches[:, 0], 1] - kp_right[np_matches[:, 1], 1]) < 4)
</code>```

AND those key points should also not have a difference smaller than < 0. Then it means the key point is behind the camera.

```<code>ind = np.where((kp_left[np_matches[ind[0], 0], 0] - kp_right[np_matches[ind[0], 1], 0]) >= 0)
</code>```

How to combine those 2 conditions?

答:
The general form is this:

```<code>condition1 = x < 4
condition2 = y >= 100
result = np.where(condition1 & condition2)
</code>```

The even more general form:

```<code>conditions = [...] # list of bool arrays
result = np.where(np.logical_and.reduce(conditions))
</code>```

Body:
I am using the cv2 library to detect key points of 2 stereo images and converted the resulting dmatches objects to a numpy array:

kp_left, des_left = sift.detectAndCompute(im_left, mask_left)
matches = bf.match(des_left, des_right)  # according to assignment pdf
np_matches = dmatch2np(matches)

Then I want to filter matches if the key points are filtering, after y-direction, which should not differ bigger than 3 pixels:

ind = np.where(np.abs(kp_left[np_matches[:, 0], 1] - kp_right[np_matches[:, 1], 1]) < 4)

AND those key points should also not have a difference smaller than < 0. Then it means the key point is behind the camera.

ind = np.where((kp_left[np_matches[ind[0], 0], 0] - kp_right[np_matches[ind[0], 1], 0]) >= 0)

How to combine those 2 conditions?

Body:
The general form is this:

condition1 = x < 4
condition2 = y >= 100
result = np.where(condition1 & condition2)

The even more general form:

conditions = [...] # list of bool arrays
result = np.where(np.logical_and.reduce(conditions))


问:
Access multiple versions of a package in Java
We have several applications that use Apache HTTPClient 3 to make HTTP requests. Recently we have also began creating web service clients that use HTTPClient 4 for various reasons. The Apache stance is that "major releases are not backwards compatible". While I would love to update all of our projects to use version 4, that's simply not feasible.

So, while my main question is rather general, my particular question is. How can I use HTTPClient version 3 and 4 in the same application? In our case an application can be a web, desktop, or command line app.

I have read the SO question for java-dynamically-load-multiple-versions-of-same-class which seems semi close but I don't care so much about the dynamic part. In fact I would like the JARs to be shipped with the app (example, WEB-INF/lib for web apps) I also see OSGi mentioned a lot in questions similar to this one but it seems to be overkill or perhaps overly complex (maybe a simple example could prove otherwise).

In the end I want to be able to hand a team a set of jars that they can drop in and it just works independent of their project using HTTP Client 3.

答:
Use multiple class loaders, one for each HTTP Client you wish to embrace.

The simplest way is to extend URLClassLoader and hack it to hardcode the classpath for each version separately.  Then you just need to make sure the rest of the code knows which version of the HTTP client to use (and accesses the correct classloader to get to it).

ContentLicense: CC BY-SA 2.5


问:
How To Use Custom Nameserver On Free Cloudflare?
I have a problem.

I own a small hosting company. I am trying to add Cloudflare to my site as a free CDN. The only problem is when I sign up I have to change the nameservers to their nameservers. I already have nameserver DNS set up through GoDaddy, so how do I add them to CloudFlare? My main site uses my company's nameservers already but whenever I add them the site goes offline.

When I go into Cloudflare's DNS records I click on the dropdown, click NS, and there's two boxes that say 'Name' and 'Nameserver'. Does this mean I input 'NS1' into 'Name' and 'NS1.DOMAIN.COM' into 'Nameserver'? Where do I input my server's IP addresses?

Is there another way of accomplishing this with the free version of Cloudflare?

答:
An old question (no doubt you found the answer long ago), but nevertheless still an interesting one!  I recently faced this issue and would like to share what I did.

If I understand the question correctly, you are using child nameservers at your registrar to point your customers' domains to your server?

In cloudflare, after you have added your primary domain, you can also specify the NS record to allow customer domains to continue to use your custom / child nameservers at your registrar.

In the DNS records control panel, simply choose NS from the dropdown field, then in the Name field, add your child nameserver, then in Ip4address field, add the nameserver so it looks like e.g.

NS   yourdomain.com   managed by ns1.yourchildnameserver.com

Do the same for NS2 and your customer domains should continue to resolve without any issues.

In the end of course, it would be better to add each customer domain into CF ad point their DNS directly to your server, but the above steps should work as an interim measure.

Hope this helps someone else.


问:
how to convert date time to only time in c#
i want to convert datetime format to only time format.

data type - string

```<code>op- 5/31/2017 8:43:20 PM
req op - 8:43 (in 24 hours format)
</code>```

code

```<code>TankDetailsModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();
</code>```

答: You can use .ToString ("HH:mm")</p>

Body:
i want to convert datetime format to only time format.

data type - string

op- 5/31/2017 8:43:20 PM
req op - 8:43 (in 24 hours format)

code

TankDetailsModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();

Body: You can use .ToString ("HH:mm")


问:
Maven exec:java run executable plugin dependency jar results in NPE
I'm making a maven application that uses a sparql endpoint service. I'd like to have a maven goal to download the sparql endpoint and start the service but it seems that maven have some problems to configure the classpath.

I'm using blazegraph and its artifact at https://mvnrepository.com/artifact/com.blazegraph/bigdata-jar.

Here it is my plug-in configuration in pom.xml:

```<code><plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.6.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>com.bigdata.rdf.sail.webapp.StandaloneNanoSparqlServer</mainClass>
                <includePluginDependencies>true</includePluginDependencies>
                <includeProjectDependencies>false</includeProjectDependencies>
                <executableDependency>
                    <groupId>com.blazegraph</groupId>
                    <artifactId>blazegraph-jar</artifactId>
                </executableDependency>
                <addOutputToClasspath>false</addOutputToClasspath>
            </configuration>
            <dependencies>
                <!-- https://mvnrepository.com/artifact/com.blazegraph/blazegraph-jar -->
                <dependency>
                    <groupId>com.blazegraph</groupId>
                    <artifactId>blazegraph-jar</artifactId>
                    <version>2.1.4</version>
                    <scope>runtime</scope>
                    <type>jar</type>
                </dependency>
            </dependencies>
        </plugin>
</code>```

The debug output hints that the plug-in can't find the artifact:

```<code>Caused by: java.lang.NullPointerException
at org.codehaus.mojo.exec.AbstractExecMojo.findExecutableArtifact(AbstractExecMojo.java:278)
at org.codehaus.mojo.exec.ExecJavaMojo.determineRelevantPluginDependencies(ExecJavaMojo.java:650)
at org.codehaus.mojo.exec.ExecJavaMojo.addRelevantPluginDependenciesToClasspath(ExecJavaMojo.java:568)
at org.codehaus.mojo.exec.ExecJavaMojo.getClassLoader(ExecJavaMojo.java:520)
at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:301)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
... 27 more
</code>```

What am I missing?

Edit 1
This question is not a duplicate of What is a NullPointerException, and how do I fix it? because the exception is thrown by Maven since it can't find the right artifact in the list of dependencies (but it should).

Edit 2
Thanks to @Sean Patrick Floyd I've partially solved the issue. There are still some problem in the classpath configuration, I guess. Now Maven finds the main class and the jar but after the execution I get an other NPE in compiled code. Looking in the open source code of blazegraph it seems that it can't open a resource inside the executable jar.

Here is the line that causes NPE:

```<code>System.setProperty("jetty.home",
            jettyXml.getClass().getResource("/war").toExternalForm());
</code>```

https://github.com/blazegraph/database/blob/master/bigdata-jar/src/main/java/com/bigdata/rdf/sail/webapp/StandaloneNanoSparqlServer.java#L142

答:
The <executableDependency> mechanism is used for binaries, not for JARs, see the usage page. Remove that part, these settings should be sufficient:

```<code><mainClass>com.bigdata.rdf.sail.webapp.StandaloneNanoSparqlServer</mainClass>
<includePluginDependencies>true</includePluginDependencies>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm making a maven application that uses a sparql endpoint service. I'd like to have a maven goal to download the sparql endpoint and start the service but it seems that maven have some problems to configure the classpath.

I'm using blazegraph and its artifact at https://mvnrepository.com/artifact/com.blazegraph/bigdata-jar.

Here it is my plug-in configuration in pom.xml:

<plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.6.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>com.bigdata.rdf.sail.webapp.StandaloneNanoSparqlServer</mainClass>
                <includePluginDependencies>true</includePluginDependencies>
                <includeProjectDependencies>false</includeProjectDependencies>
                <executableDependency>
                    <groupId>com.blazegraph</groupId>
                    <artifactId>blazegraph-jar</artifactId>
                </executableDependency>
                <addOutputToClasspath>false</addOutputToClasspath>
            </configuration>
            <dependencies>

                <dependency>
                    <groupId>com.blazegraph</groupId>
                    <artifactId>blazegraph-jar</artifactId>
                    <version>2.1.4</version>
                    <scope>runtime</scope>
                    <type>jar</type>
                </dependency>
            </dependencies>
        </plugin>

The debug output hints that the plug-in can't find the artifact:

Caused by: java.lang.NullPointerException
at org.codehaus.mojo.exec.AbstractExecMojo.findExecutableArtifact(AbstractExecMojo.java:278)
at org.codehaus.mojo.exec.ExecJavaMojo.determineRelevantPluginDependencies(ExecJavaMojo.java:650)
at org.codehaus.mojo.exec.ExecJavaMojo.addRelevantPluginDependenciesToClasspath(ExecJavaMojo.java:568)
at org.codehaus.mojo.exec.ExecJavaMojo.getClassLoader(ExecJavaMojo.java:520)
at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:301)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
... 27 more

What am I missing?

Edit 1
This question is not a duplicate of What is a NullPointerException, and how do I fix it? because the exception is thrown by Maven since it can't find the right artifact in the list of dependencies (but it should).

Edit 2
Thanks to @Sean Patrick Floyd I've partially solved the issue. There are still some problem in the classpath configuration, I guess. Now Maven finds the main class and the jar but after the execution I get an other NPE in compiled code. Looking in the open source code of blazegraph it seems that it can't open a resource inside the executable jar.

Here is the line that causes NPE:

System.setProperty("jetty.home",
            jettyXml.getClass().getResource("/war").toExternalForm());

https://github.com/blazegraph/database/blob/master/bigdata-jar/src/main/java/com/bigdata/rdf/sail/webapp/StandaloneNanoSparqlServer.java#L142

Body:
The <executableDependency> mechanism is used for binaries, not for JARs, see the usage page. Remove that part, these settings should be sufficient:

<mainClass>com.bigdata.rdf.sail.webapp.StandaloneNanoSparqlServer</mainClass>
<includePluginDependencies>true</includePluginDependencies>


问:
Pattern matching using information from theorems
I have the following question, look in the code.

```<code>  (* Suppose we have type A *)
  Variable A: Type.

  (* Also we have a function that returns the type (option A) *)
  Definition f_opt x: option A := ...

  (* Then, I can prove that this function always returns something: *)
  Theorem always_some: forall x, exists y, f_opt x = Some y.
  Admitted.

  (* Or, equivalently: *)
  Theorem always_not_none: forall x, f_opt x <> None.
  Admitted.
</code>```

Now I would like to get a version of f_opt that always returns a value of type A. Something like this:

```<code>  Definition f x: A :=
    match f_opt x with
      | Some y => y
    end.
</code>```

But I get the following error:

Non exhaustive pattern-matching: no clause found for pattern None.

I understand that I need to do some kind of work with types, but I do not understand what exactly i should do.

答:
You will need to put your existential proof always_not_none in Set or Type to do so:

```<code>Theorem always_some: forall x, { y: A &  f_opt x = Some y}.
...
Qed.
</code>```

Then you can do the following (or use refine or Program):

```<code>Definition f (x: B) : A :=
   let s := always_some x in let (x0, _) := s in x0.
</code>```

Body:
I have the following question, look in the code.

  (* Suppose we have type A *)
  Variable A: Type.

  (* Also we have a function that returns the type (option A) *)
  Definition f_opt x: option A := ...

  (* Then, I can prove that this function always returns something: *)
  Theorem always_some: forall x, exists y, f_opt x = Some y.
  Admitted.

  (* Or, equivalently: *)
  Theorem always_not_none: forall x, f_opt x <> None.
  Admitted.

Now I would like to get a version of f_opt that always returns a value of type A. Something like this:

  Definition f x: A :=
    match f_opt x with
      | Some y => y
    end.

But I get the following error:

Non exhaustive pattern-matching: no clause found for pattern None.

I understand that I need to do some kind of work with types, but I do not understand what exactly i should do.

Body:
You will need to put your existential proof always_not_none in Set or Type to do so:

Theorem always_some: forall x, { y: A &  f_opt x = Some y}.
...
Qed.

Then you can do the following (or use refine or Program):

Definition f (x: B) : A :=
   let s := always_some x in let (x0, _) := s in x0.


问:
The requested URL /edit.php was not found on this server
I just get this error below. It does work on localhost. Any ideas?
Any advise on how to google this error would help a lot as well, as I am not sure where the problem might be.

"The requested URL /edit.php was not found on this server."

```<code><?php
include ('includes/connection.php');
include ('includes/functions.php');
include ('includes/header.php');

$jobId  = $_GET["id"];
$query  = "SELECT * FROM Freight, WHERE id = '$jobId'";
$result = mysqli_query($connection, $query);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $jobArrival            = $row["Arrival"];
        $jobDeparture          = $row["Departure"];
        $jobClient             = $row["Client"];
        $jobAirportOfDeparture = $row["AirportOfDeparture"];
        $jobAirportOfArrival   = $row["AirportOfArrival"];
        $jobAdditionalInfo     = $row["AdditionalInfo"];
        $jobBoxType            = $row["BoxType"];
        $jobTemp               = $row["Temp"];

        // prideti is dezes table
        // $pavadinimas           = $row["pavadinimas"];
        // $likutis               = $row["likutis"];

        if (isset($_POST['update'])) {
            $jobArrival            = validateFormData($_POST['jobArrival']);
            $jobDeparture          = validateFormData($_POST['jobDeparture']);
            $jobClient             = validateFormData($_POST['jobClient']);
            $jobAirportOfDeparture = validateFormData($_POST['jobAirportOfDeparture']);
            $jobAirportOfArrival   = validateFormData($_POST['jobAirportOfArrival']);
            $jobAdditionalInfo     = validateFormData($_POST['jobAdditionalInfo']);
            $jobBoxType            = validateFormData($_POST['jobBoxType']);
            $jobTemp               = validateFormData($_POST['jobTemp']);
            $query                 = "UPDATE Freight SET Arrival            = '$jobArrival',
                                                         Departure          = '$jobDeparture',
                                                         Client             = '$jobClient',
                                                         AirportOfDeparture = '$jobAirportOfDeparture',
                                                         AirportOfArrival   = '$jobAirportOfArrival',
                                                         AdditionalInfo     = '$jobAdditionalInfo',
                                                         BoxType            = '$jobBoxType',
                                                         Temp               = '$jobTemp'
                                                     WHERE id = '$jobId'";
            $result = mysqli_query($connection, $query);
            if ($result) {
                header("Location: formdisplay.php");
            } else {
                "Klaida" . mysqli_error($connection);
            }
        }
    }
}
else {
    echo "Nera irasu!!!!!!!!!!!!!!";
}

if (isset($_POST['istrinti'])) {
    $query = "DELETE FROM Freight WHERE id ='$jobId'";
    $result = mysqli_query($connection, $query);
    if ($result) {
        header("Location: formdisplay.php?alert=deleted");
    }
    else {
        echo "Error" . mysqli_error($connection);
    }
}

mysqli_close($connection);
?>

<h1> Iraso koregavimas</h1>
<table>
    <tr>
        <td>Arrival</td>
        <td>Departure</td>
        <td>Client</td>
        <td>Airport Of Departure</td>
        <td>Airport Of Arrival</td>
        <td>Additional Info</td>
        <td>Box Type</td>
        <td>Temp</td>
    </tr>
    <tr>
        <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>?id=<?php echo $jobId; ?>">
            <td>
                <input  type    = "text"
                        value   = "<?php echo $jobArrival ?>"
                        name    = "jobArrival">
            </td>
            <td>
                <input  type    = "text"
                        value   = "<?php echo $jobDeparture ?>"
                        name    = "jobDeparture">
            </td>
            <td>
                <input  type    = "text"
                        value   = "<?php echo $jobClient ?>"
                        name    = "jobClient">
            </td>
            <td>
                <input  type    = "text"
                        value   = "<?php echo $jobAirportOfDeparture ?>"
                        name    = "jobAirportOfDeparture">
            </td>
            <td>
                <input  type    = "text"
                        value   = "<?php echo $jobAirportOfArrival ?>"
                        name    = "jobAirportOfArrival">
            </td>
            <td>
                <input  type    = "text"
                        value   = "<?php echo $jobAdditionalInfo ?>"
                        name    = "jobAdditionalInfo">
            </td>
            <td>
                <input  type    = "text"
                        value   = "<?php echo $jobBoxType ?>"
                        name    = "jobBoxType">
            </td>
            <td>
                <input  type    = "text"
                        value   = "<?php echo $jobTemp ?>"
                        name    = "jobTemp">
            </td>
            <td>
                <input  type    = "submit"
                        name    = "update"
                        value   = "update"
                        href    = "formdisplay.php"></td>
            <td>
                <input  type    ="submit"
                        name    ="istrinti"
                        value   ="istrinti"
                        href    ="formdisplay.php">
            </td>
        </form>
    </tr>
</table>
</code>```

答:
Problem SOLVED. Problem on line 143, few wrong spaces.
Took me only a week to find it :)
Code has to look like this <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>?id=<?php echo $jobId ?>">

Body:
I just get this error below. It does work on localhost. Any ideas?
Any advise on how to google this error would help a lot as well, as I am not sure where the problem might be.

"The requested URL /edit.php was not found on this server."

<?php
include ('includes/connection.php');
include ('includes/functions.php');
include ('includes/header.php');

$jobId  = $_GET["id"];
$query  = "SELECT * FROM Freight, WHERE id = '$jobId'";
$result = mysqli_query($connection, $query);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $jobArrival            = $row["Arrival"];
        $jobDeparture          = $row["Departure"];
        $jobClient             = $row["Client"];
        $jobAirportOfDeparture = $row["AirportOfDeparture"];
        $jobAirportOfArrival   = $row["AirportOfArrival"];
        $jobAdditionalInfo     = $row["AdditionalInfo"];
        $jobBoxType            = $row["BoxType"];
        $jobTemp               = $row["Temp"];

        // prideti is dezes table
        // $pavadinimas           = $row["pavadinimas"];
        // $likutis               = $row["likutis"];

        if (isset($_POST['update'])) {
            $jobArrival            = validateFormData($_POST['jobArrival']);
            $jobDeparture          = validateFormData($_POST['jobDeparture']);
            $jobClient             = validateFormData($_POST['jobClient']);
            $jobAirportOfDeparture = validateFormData($_POST['jobAirportOfDeparture']);
            $jobAirportOfArrival   = validateFormData($_POST['jobAirportOfArrival']);
            $jobAdditionalInfo     = validateFormData($_POST['jobAdditionalInfo']);
            $jobBoxType            = validateFormData($_POST['jobBoxType']);
            $jobTemp               = validateFormData($_POST['jobTemp']);
            $query                 = "UPDATE Freight SET Arrival            = '$jobArrival',
                                                         Departure          = '$jobDeparture',
                                                         Client             = '$jobClient',
                                                         AirportOfDeparture = '$jobAirportOfDeparture',
                                                         AirportOfArrival   = '$jobAirportOfArrival',
                                                         AdditionalInfo     = '$jobAdditionalInfo',
                                                         BoxType            = '$jobBoxType',
                                                         Temp               = '$jobTemp'
                                                     WHERE id = '$jobId'";
            $result = mysqli_query($connection, $query);
            if ($result) {
                header("Location: formdisplay.php");
            } else {
                "Klaida" . mysqli_error($connection);
            }
        }
    }
}
else {
    echo "Nera irasu!!!!!!!!!!!!!!";
}

if (isset($_POST['istrinti'])) {
    $query = "DELETE FROM Freight WHERE id ='$jobId'";
    $result = mysqli_query($connection, $query);
    if ($result) {
        header("Location: formdisplay.php?alert=deleted");
    }
    else {
        echo "Error" . mysqli_error($connection);
    }
}

mysqli_close($connection);
?>

 Iraso koregavimas

        Arrival
        Departure
        Client
        Airport Of Departure
        Airport Of Arrival
        Additional Info
        Box Type
        Temp

        <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>?id=<?php echo $jobId; ?>">

                <input  type    = "text"
                        value   = "<?php echo $jobArrival ?>"
                        name    = "jobArrival">

                <input  type    = "text"
                        value   = "<?php echo $jobDeparture ?>"
                        name    = "jobDeparture">

                <input  type    = "text"
                        value   = "<?php echo $jobClient ?>"
                        name    = "jobClient">

                <input  type    = "text"
                        value   = "<?php echo $jobAirportOfDeparture ?>"
                        name    = "jobAirportOfDeparture">

                <input  type    = "text"
                        value   = "<?php echo $jobAirportOfArrival ?>"
                        name    = "jobAirportOfArrival">

                <input  type    = "text"
                        value   = "<?php echo $jobAdditionalInfo ?>"
                        name    = "jobAdditionalInfo">

                <input  type    = "text"
                        value   = "<?php echo $jobBoxType ?>"
                        name    = "jobBoxType">

                <input  type    = "text"
                        value   = "<?php echo $jobTemp ?>"
                        name    = "jobTemp">

                <input  type    = "submit"
                        name    = "update"
                        value   = "update"
                        href    = "formdisplay.php">

                <input  type    ="submit"
                        name    ="istrinti"
                        value   ="istrinti"
                        href    ="formdisplay.php">

        </form>


问:
SharedPreferences and ViewPager Unique Key
In school we have to develop our first Android app. Android is new to me and I'm here to learn something.

Today I worked the first time with SharedPreferences to save information about an ImageButton state. The layout uses a ViewPager. There are 10 items which the user can swipe. The ViewPager contains a TextView that counts the items. That works fine: e.g. the TextView of the first items shows [1/10] and the last one [10/10]. After the TextView you can find an image. That works also pretty good.

Now to my problem: under the Image I have installed an ImageButton. It signals if an item is a favorite or not. Favorite is pictured as red heart and no favorite as grey heart (default ImageResource).

This is my ViewPager of the main layout:

```<code><android.support.v4.view.ViewPager
    android:id="@+id/image_swipe"
    android:layout_width="match_parent"
    android:layout_height="590dp"
    android:layout_marginTop="130dp" />
</code>```

And this is the pagers layout:

```<code><TextView
    android:id="@+id/image_count"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Here we count..."
    android:textColor="@android:color/black"
    android:textSize="16sp" />

<ImageView
    android:id="@+id/swipe_image"
    android:layout_width="match_parent"
    android:layout_height="365dp"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp"
    android:layout_marginTop="30dp"
    android:adjustViewBounds="false"
    android:onClick="onClickImage" />

<ImageButton
    android:id="@+id/favourite_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_gravity="center"
    android:background="@android:color/transparent"
    android:scaleType="fitCenter"
    android:src="@drawable/heart"
    android:onClick="onClickFav" />
</code>```

All items need an unique key in order to save every items ImageButton state. The key is composed of the String "fav" and a counter (can be 1-10). That means we have 10 unique keys: fav1 - fav10. When the page is created for the given item position, I try to check if something is stored for the given key.

There can be 2 possible values behind a key: 0 and 1. 0 means no favorite, 1 is a favorite. If there is not yet any key set, the value will be 0 which is the default ImageButton state. After getting the value of the item key, the ImageResource of the ImageButton can be set.

The next step when creating the page, is to save a new key. That key has the name "count" and indicates which item is loaded at this moment.

All I just told you is in this adapter method (instantiateItem):

```<code>     /*
        Create the page for the given position
        Set image resources and text about current position
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
        TextView textView = (TextView) item_view.findViewById(R.id.image_count);
        ImageButton imageButton = (ImageButton) item_view.findViewById(R.id.favourite_button);

        imageView.setImageResource(image_resources[position]);
        textView.setText("["+(position+1)+"/10]");

        SharedPreferences prefs = context.getSharedPreferences("favInfo", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        // get the unique key consisting of fav and the current item position
        String key = "fav" + (position+1);

        String value = prefs.getString(key, "0");

        // check if value of favorite key is 0
        // set image resource dependent on what value is set
        if (value.equals("1")) {
            imageButton.setImageResource(R.drawable.heart_red);
        } else {
            imageButton.setImageResource(R.drawable.heart);
        }

        int p = (position+1);
        String count = Integer.toString(p);

        // store index of current adapter item as shared pref
        editor.putString("count", count);
        editor.commit();

        container.addView(item_view);

        return item_view;
    }
</code>```

So this was when a item is loaded. After that the user can click on the ImageButton which activates following onClick method in the main activity:

```<code>/*
    Method for click actions on the favorite button
    @heart grey heart symbolizes no favorite (flag 0)
    @heart_red red heart symbolizes marked as favorite (flag 1)
*/
public void onClickFav(View v) {
    ImageButton favouriteButton = (ImageButton) findViewById(R.id.favourite_button);

    SharedPreferences prefs = getSharedPreferences("favInfo", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    // get the count value of the item which is loaded at the moment
    String count = prefs.getString("count", "");

    // get the unique key consisting of fav and the count text
    String key = "fav" + count;

    // get value stored with that key, default: if no value exists take 0
    String value = prefs.getString(key, "0");

    // check if value of favorite key is 0,
    // set image resource dependent on what value is stored behind the key
    if (value.equals("0")) {
        favouriteButton.setImageResource(R.drawable.heart_red);
    } else {
        favouriteButton.setImageResource(R.drawable.heart);
    }

    String isFav;

    // switch value to opposite
    if (value.equals("0")) {
        isFav = "1";
    } else {
        isFav = "0";
    }

    // store shared preferences
    editor.putString(key, isFav);
    editor.commit();
}
</code>```

Basically what I do here is: get the current item ("count" key) and build the unique key with it. Then check the value behind it and set the ImageResource accordingly. After that I change the value to opposite and save the unique key.

My problem: there happens something, but not the right thing. When the user clicks the ImageButton, the ImageButton of the item before are after it changes. e.g. the user clicks the ImageButton of item 7. Not the ImageButton of item 7 changes, but the ImageButton of item 6 or 8.

答:
The problem is that instantiateItem () is not called every time you swipe the screen.
Your adapter instantiates each pager layout when the first activity is loaded.
By the way, the main activity expects to call instantiateItem () every time the screen changes.

So, instead of updating count in instantiateItem (), you need to find a method that is called each time the screen is toggled.
For example, you can detect transitions in the pager tab bar and do the following:

```<code>navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(final int position) {
            // set "count" this position
        }
    });
</code>```

P.S

For efficient processing, it is better to pass the selected screen index directly to the activity rather than using the preference each time the screen is switched.

Body:
In school we have to develop our first Android app. Android is new to me and I'm here to learn something.

Today I worked the first time with SharedPreferences to save information about an ImageButton state. The layout uses a ViewPager. There are 10 items which the user can swipe. The ViewPager contains a TextView that counts the items. That works fine: e.g. the TextView of the first items shows [1/10] and the last one [10/10]. After the TextView you can find an image. That works also pretty good.

Now to my problem: under the Image I have installed an ImageButton. It signals if an item is a favorite or not. Favorite is pictured as red heart and no favorite as grey heart (default ImageResource).

This is my ViewPager of the main layout:

<android.support.v4.view.ViewPager
    android:id="@+id/image_swipe"
    android:layout_width="match_parent"
    android:layout_height="590dp"
    android:layout_marginTop="130dp" />

And this is the pagers layout:

<TextView
    android:id="@+id/image_count"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Here we count..."
    android:textColor="@android:color/black"
    android:textSize="16sp" />

<ImageView
    android:id="@+id/swipe_image"
    android:layout_width="match_parent"
    android:layout_height="365dp"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp"
    android:layout_marginTop="30dp"
    android:adjustViewBounds="false"
    android:onClick="onClickImage" />

<ImageButton
    android:id="@+id/favourite_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_gravity="center"
    android:background="@android:color/transparent"
    android:scaleType="fitCenter"
    android:src="@drawable/heart"
    android:onClick="onClickFav" />

All items need an unique key in order to save every items ImageButton state. The key is composed of the String "fav" and a counter (can be 1-10). That means we have 10 unique keys: fav1 - fav10. When the page is created for the given item position, I try to check if something is stored for the given key.

There can be 2 possible values behind a key: 0 and 1. 0 means no favorite, 1 is a favorite. If there is not yet any key set, the value will be 0 which is the default ImageButton state. After getting the value of the item key, the ImageResource of the ImageButton can be set.

The next step when creating the page, is to save a new key. That key has the name "count" and indicates which item is loaded at this moment.

All I just told you is in this adapter method (instantiateItem):

     /*
        Create the page for the given position
        Set image resources and text about current position
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
        TextView textView = (TextView) item_view.findViewById(R.id.image_count);
        ImageButton imageButton = (ImageButton) item_view.findViewById(R.id.favourite_button);

        imageView.setImageResource(image_resources[position]);
        textView.setText("["+(position+1)+"/10]");

        SharedPreferences prefs = context.getSharedPreferences("favInfo", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        // get the unique key consisting of fav and the current item position
        String key = "fav" + (position+1);

        String value = prefs.getString(key, "0");

        // check if value of favorite key is 0
        // set image resource dependent on what value is set
        if (value.equals("1")) {
            imageButton.setImageResource(R.drawable.heart_red);
        } else {
            imageButton.setImageResource(R.drawable.heart);
        }

        int p = (position+1);
        String count = Integer.toString(p);

        // store index of current adapter item as shared pref
        editor.putString("count", count);
        editor.commit();

        container.addView(item_view);

        return item_view;
    }

So this was when a item is loaded. After that the user can click on the ImageButton which activates following onClick method in the main activity:

/*
    Method for click actions on the favorite button
    @heart grey heart symbolizes no favorite (flag 0)
    @heart_red red heart symbolizes marked as favorite (flag 1)
*/
public void onClickFav(View v) {
    ImageButton favouriteButton = (ImageButton) findViewById(R.id.favourite_button);

    SharedPreferences prefs = getSharedPreferences("favInfo", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    // get the count value of the item which is loaded at the moment
    String count = prefs.getString("count", "");

    // get the unique key consisting of fav and the count text
    String key = "fav" + count;

    // get value stored with that key, default: if no value exists take 0
    String value = prefs.getString(key, "0");

    // check if value of favorite key is 0,
    // set image resource dependent on what value is stored behind the key
    if (value.equals("0")) {
        favouriteButton.setImageResource(R.drawable.heart_red);
    } else {
        favouriteButton.setImageResource(R.drawable.heart);
    }

    String isFav;

    // switch value to opposite
    if (value.equals("0")) {
        isFav = "1";
    } else {
        isFav = "0";
    }

    // store shared preferences
    editor.putString(key, isFav);
    editor.commit();
}

Basically what I do here is: get the current item ("count" key) and build the unique key with it. Then check the value behind it and set the ImageResource accordingly. After that I change the value to opposite and save the unique key.

My problem: there happens something, but not the right thing. When the user clicks the ImageButton, the ImageButton of the item before are after it changes. e.g. the user clicks the ImageButton of item 7. Not the ImageButton of item 7 changes, but the ImageButton of item 6 or 8.

Body:
The problem is that instantiateItem () is not called every time you swipe the screen.
Your adapter instantiates each pager layout when the first activity is loaded.
By the way, the main activity expects to call instantiateItem () every time the screen changes.

So, instead of updating count in instantiateItem (), you need to find a method that is called each time the screen is toggled.
For example, you can detect transitions in the pager tab bar and do the following:

navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(final int position) {
            // set "count" this position
        }
    });

P.S

For efficient processing, it is better to pass the selected screen index directly to the activity rather than using the preference each time the screen is switched.


问:
A suitable PC for Visual Studio 2010 programming
I'm planning on buying a new PC for programming under Visual Studio 2010. My main other usages are:

Programming under Microsoft Visual Studio.

Running VMWare Virtual Machines.

Probably multi-monitor (if my budget lets me buy an extra one)

Here are my questions:

Do I need to purchase a high performance display adapter considering my usage described above? or a medium-range one will suffice? In general, I'd like to know how much a display adapter could affect my usages?

Which CPU could perform better? Core i7, Core 2 Quad, AMD?  I have a limited budget but I really need a good performance and buying a good CPU/MB/RAM is my first priority.

答:
A good video card is not a must have, unless you want to develop advanced 3D with Visual Studio (which is an option after all). WPF and multi-monitor can work on any video card you would buy nowadays.

What is an absolute requirement is 4GB of RAM, just for Visual Studio 2010 alone under Win7 (x64 obviously, since the x86 version cannot use 4GB of RAM). Adding Virtual machines raises that need. This has no up limit since it really depends on how many VMs you're planning to run at the same time and what application will run on them. Add 1GB minimum per VM running Win7, a lot more if they are supposed to run databases, source control or any heavy load application.

Also, for the VMs, it is almost mandatory to have them use separate physical hard drives if they are going to run simultaneously, if you don't you will experience stone age level disk performance for both the host and the VMs (unless it's all on SSD, which I never tried).

Would I be buying a computer for programming now I would definitely buy an SSD to host Win7, VS and the projects, it would really be comfy (my current desktop takes several minutes to boot and load my projects, anything that improves loading is good).

On the CPU side, you might want to spend money on the number of cores rather than the actual speed (frequency) of the processor. All CPUs have decent performance, but your computer may slow down a lot if you're running several VMs on a 2-core CPU.
the i7 chip is a really good one, but I don't think you would gain a lot buy spending big amounts of money on high-end Intel chips. Go for a good price/perf ratio with lots of cores, which for your budget will be a 4-core i5 or a 6-core Phenom II X6 (I personnally would prefer the X6 but I don't want to sound partial).

More generally, if your host or your VMs are meant to run stuff DBs or continuous integration build or source control servers that are accessible to a lot of people, you might want to use another computer as your developping computer, since availability will be important (that means no reboots, avoid hardware and software failures). You might want to buy a good mobo, and an excellent power supply, plus a good tower with sufficiently numerous fans. And you might want to think of what you're going to use for backups.

Edit: this last line almost excludes pre-built computers, since afaik computer makers will almost always include cheap power supply and motherboard even in high-end computers, because those points are not advertised.


问:
WCAG Compliance - Element with role="button" and no content
I'm trying to develop a WCAG compliant web app, currently codesniffer is giving me lots of:

This element has a role of "button" but does not have a name available
  to an accessibility API. Valid names are: element content.

From this HTML:

```<code><span unselectable="on" class="k-select" aria-label="abcd" role="button"  alt="abcd" title="abcd" value="abcd">
  <span class="k-icon k-i-calendar"></span>
</span>
</code>```

Setting alt, value, title and aria-label seem to do no good.
How can I have a WCAG compliant element with role="button" with no text inside it?

答:
Adam is right to convert this to a <button>. That is the best approach from the start and also means you can dump the role="button". It also means you get accessibility of interaction for free (you don't have to listen for a Space bar or Enter key, for example).

Instead of trying to make the <button> itself have the accessible name, put it on the icon. If you do that consistently, you can be certain the icon always has an accessible name, regardless of whether or not it is in a control like a button or a link.

So consider this HTML:

```<code><button class="k-select">
  <span class="k-icon k-i-calendar">Calendar</span>
</button>
</code>```

Now you have a normal button that has not been jury-rigged with attributes to try to make it accessible. The icon, on the other hand, has text within it now, and that becomes the accessible name.

Now apply this CSS rule to visually hide that text:

```<code>.k-icon {
  position: absolute;
  top: auto;
  overflow: hidden;
  clip: rect(1px 1px 1px 1px); /* IE 6/7 */
  clip: rect(1px, 1px, 1px, 1px);
  width: 1px;
  height: 1px;
  white-space: nowrap; /* https://medium.com/@jessebeach/beware-smushed-off-screen-accessible-text-5952a4c2cbfe */
}
</code>```

I usually have this as a utility class (.visually-hidden) so that I can apply it wherever.

FontAwesome talks about an approach similar to this on its site for making its icons accessible.

With this approach, you do not need any ARIA, any one-off code solutions, nor any script. This works for your icons first (the real issue) and means when those icons are used elsewhere (links, buttons, etc) they are accessible.

Also, neither alt nor value is valid for a button. aria-label is unnecessary. Definitely avoid title.

Body:
I'm trying to develop a WCAG compliant web app, currently codesniffer is giving me lots of:

This element has a role of "button" but does not have a name available
  to an accessibility API. Valid names are: element content.

From this HTML:

Setting alt, value, title and aria-label seem to do no good.
How can I have a WCAG compliant element with role="button" with no text inside it?

Body:
Adam is right to convert this to a <button>. That is the best approach from the start and also means you can dump the role="button". It also means you get accessibility of interaction for free (you don't have to listen for a Space bar or Enter key, for example).

Instead of trying to make the <button> itself have the accessible name, put it on the icon. If you do that consistently, you can be certain the icon always has an accessible name, regardless of whether or not it is in a control like a button or a link.

So consider this HTML:

<button class="k-select">
  <span class="k-icon k-i-calendar">Calendar</span>
</button>

Now you have a normal button that has not been jury-rigged with attributes to try to make it accessible. The icon, on the other hand, has text within it now, and that becomes the accessible name.

Now apply this CSS rule to visually hide that text:

.k-icon {
  position: absolute;
  top: auto;
  overflow: hidden;
  clip: rect(1px 1px 1px 1px); /* IE 6/7 */
  clip: rect(1px, 1px, 1px, 1px);
  width: 1px;
  height: 1px;
  white-space: nowrap; /* https://medium.com/@jessebeach/beware-smushed-off-screen-accessible-text-5952a4c2cbfe */
}

I usually have this as a utility class (.visually-hidden) so that I can apply it wherever.

FontAwesome talks about an approach similar to this on its site for making its icons accessible.

With this approach, you do not need any ARIA, any one-off code solutions, nor any script. This works for your icons first (the real issue) and means when those icons are used elsewhere (links, buttons, etc) they are accessible.

Also, neither alt nor value is valid for a button. aria-label is unnecessary. Definitely avoid title.


问:
Why does this OSGi Import-Package not work?
I'm going through this OSGi tutorial (with Eclipse, with the PDE addon installed):

http://www.vogella.com/tutorials/OSGi/article.html

Until task 10 everything worked fine. But now I have a problem:

The "Import-Package: org.osgi.framework;version="1.3.0" (which was auto-generated, probably because of the generated Activator class) shows the following error:
"No available bundle exports package 'org.osgi.framework'"

In the Activator class I also get resolve error for classes like BundleActivator and BundleContext. I fixed this problem by using an external jar (org.eclipse.osgi), but I'm pretty sure this isn't the right way to do it, since you're supposed to declare any dependencies in the MANIFEST file.

But how do I add the org.eclipse.osgi jar so the import package line in the manifest is enough?

My entire manifest file:

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Internal
Bundle-SymbolicName: com.osgi.beispiel.one.bundle.internal
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.osgi.beispiel.one.bundle.Activator
Bundle-Vendor: OSGI
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Import-Package: org.osgi.framework;version="1.3.0"
Bundle-ActivationPolicy: lazy

答: The reason for "No available bundle exports package 'org.osgi.framework'" in my workspace was an invalid ${eclipse_home}. The checkbox at "Window - Preferences - Target Platform - Running Platform" was marked with a red icon. I followed "Edit...", select "${eclipse_home}", "Edit...", and checked "This install uses the default configuration area". After leaving the dialogs with "Finish" resp. "OK", the problem was solved.</p>


问:
Need to Format this JSON properly and display in HTML using AJAX
I have a JSON that looks like this, I get it from a PHP file that calls Yahoo Finance API,

It's the first time I see a JSON like this.

I looked everywhere but all I manage to do is console log it... I'd like to display it into a table, or a ul, with AJAX
I'd like to access everything and display just what I need or everything.

I tried a bunch of different code snippets from everywhere but couldn't make it work, in three days !...

I'm using scheb/yahoo-finance-api on packagist for that, if it helps.

Thanks for your help.

{
    query: {
        count: 1,
        created: "2017-06-07T12:34:44Z",
        lang: "en-US",
        results: {
            quote: {
                symbol: "APLL",
                Symbol: "APLL",
                LastTradePriceOnly: "0.119",
                LastTradeDate: "6/6/2017",
                LastTradeTime: "11:13am",
                Change: "+0.023",
                Open: "0.119",
                DaysHigh: "0.119",
                DaysLow: "0.110",
                Volume: "300"
            }
        }
    }
}

$(function(){
$("#get-data").click(function() {
    //do ajax here and load data
    var showData = $('#show-data');
    var $data = $.getJSON("data.php", function(data) {

        // $data = $data.responseText;
        function buildTree(data, container) {
            $data.forEach(function(node) {

                var el = document.createElement(node.tag);

                if (Array.isArray(node.content)) {
                    buildTree(node.content, el);
                }
                else if (typeof(node.content) == 'object') {
                    buildTree([node.content], el);
                }
                else {
                    el.innerHTML = node.content;
                }

                container.appendChild(el);
            });

        }

        console.log($data);
        buildTree($data, document.body);
    });
});
```

});

That's the one I have for now, I deleted all the others, I took it form here and modified it with no success tho..
Thank you for answering :)

答:
Is this what you want to achieve?

// let's assume this is your data
var data = {
    query: {
        count: 1,
        created: "2017-06-07T12:34:44Z",
        lang: "en-US",
        results: {
            quote: {
                symbol: "APLL",
                Symbol: "APLL",
                LastTradePriceOnly: "0.119",
                LastTradeDate: "6/6/2017",
                LastTradeTime: "11:13am",
                Change: "+0.023",
                Open: "0.119",
                DaysHigh: "0.119",
                DaysLow: "0.110",
                Volume: "300"
            }
        }
    }
};

// prints one li with key and value
function printTree(key, value, container) {
  var li = $('

');
  if (typeof value === 'object') {
    // value is a nested object, create a new
 element for it
    li.append(key + ': ');
    var ul = $('

');
    for (var index in value) {
      printTree(index, value[index], ul); // call the function recursively
    }
    li.append(ul);
  } else {
    li.text(key + ': ' + value);
  }
  container.append(li);
}

printTree('data', data, $('#container')); // call the function for the first time```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="container"></code>```

Body:
I have a JSON that looks like this, I get it from a PHP file that calls Yahoo Finance API,

It's the first time I see a JSON like this.

I looked everywhere but all I manage to do is console log it... I'd like to display it into a table, or a ul, with AJAX
I'd like to access everything and display just what I need or everything.

I tried a bunch of different code snippets from everywhere but couldn't make it work, in three days !...

I'm using scheb/yahoo-finance-api on packagist for that, if it helps.

Thanks for your help.

{
    query: {
        count: 1,
        created: "2017-06-07T12:34:44Z",
        lang: "en-US",
        results: {
            quote: {
                symbol: "APLL",
                Symbol: "APLL",
                LastTradePriceOnly: "0.119",
                LastTradeDate: "6/6/2017",
                LastTradeTime: "11:13am",
                Change: "+0.023",
                Open: "0.119",
                DaysHigh: "0.119",
                DaysLow: "0.110",
                Volume: "300"
            }
        }
    }
}

$(function(){
$("#get-data").click(function() {
    //do ajax here and load data
    var showData = $('#show-data');
    var $data = $.getJSON("data.php", function(data) {

        // $data = $data.responseText;
        function buildTree(data, container) {
            $data.forEach(function(node) {

                var el = document.createElement(node.tag);

                if (Array.isArray(node.content)) {
                    buildTree(node.content, el);
                }
                else if (typeof(node.content) == 'object') {
                    buildTree([node.content], el);
                }
                else {
                    el.innerHTML = node.content;
                }

                container.appendChild(el);
            });

        }

        console.log($data);
        buildTree($data, document.body);
    });
});

});

That's the one I have for now, I deleted all the others, I took it form here and modified it with no success tho..
Thank you for answering :)

Body:
Is this what you want to achieve?

// let's assume this is your data
var data = {
    query: {
        count: 1,
        created: "2017-06-07T12:34:44Z",
        lang: "en-US",
        results: {
            quote: {
                symbol: "APLL",
                Symbol: "APLL",
                LastTradePriceOnly: "0.119",
                LastTradeDate: "6/6/2017",
                LastTradeTime: "11:13am",
                Change: "+0.023",
                Open: "0.119",
                DaysHigh: "0.119",
                DaysLow: "0.110",
                Volume: "300"
            }
        }
    }
};

// prints one li with key and value
function printTree(key, value, container) {
  var li = $('<li></li>');
  if (typeof value === 'object') {
    // value is a nested object, create a new <ul> element for it
    li.append(key + ': ');
    var ul = $('<ul></ul>');
    for (var index in value) {
      printTree(index, value[index], ul); // call the function recursively
    }
    li.append(ul);
  } else {
    li.text(key + ': ' + value);
  }
  container.append(li);
}

printTree('data', data, $('#container')); // call the function for the first time

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="container">


问:
How to convert a PDF from Word with PHPOffice
I don't have any plan how can I convert an Word document, which I have as a string (blob) from my database, to a PDF via the PHPOffice library.

Concept:

I fetch an existing word document as an string from the database

Pass the string through an constructor or an function of PHPOffice library.

Then get via another function the PDF as an string

And last output the string with Content-Type: application/pdf to the user.

Nr. 1 and 4 I already implemented. But I don't know how to accomplish nr. 2 and 3. Can someone help me?

Code:

```<code>//DB-Connection, Composer autoload, ...

$id = htmlspecialchars(trim($_REQUEST["id"]));

$get_data = $con->query("SELECT * FROM word_documents WHERE id='$id'"); //Get the blob
$data = $get_data->fetch();
if ($get_data->rowCount() == 1) {
    header("Content-Type: application/pdf");
    header("Content-Disposition: inline; filename=" . $data["name"]);

    //TODO: Print the PDF as an string

} else {
    echo "File not found";
}
</code>```

答:
After I tried some functions from the PhpOffice library, I've finally found an solution.

So with the library at self, you can not load and save it directly from a string to a string. You have to create files currently.

```<code>//Set header to show as PDF
header("Content-Type: application/pdf");
header("Content-Disposition: inline; filename=" . $data["name"]);

//Create a temporary file for Word
$temp = tmpfile();
fwrite($temp, $data["data"]); //Write the data in the file
$uri = stream_get_meta_data($temp)["uri"]; //Get the location of the temp file

//Convert the docx file in to an PhpWord Object
$doc = PhpOffice\PhpWord\IOFactory::load($uri);

//Set the PDF Engine Renderer Path. Many engines are supported (TCPDF, DOMPDF, ...).
\PhpOffice\PhpWord\Settings::setPdfRendererPath("path/to/tcpdf");
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');

//Create a writer, which converts the PhpWord Object into an PDF
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($doc, 'PDF');

//Create again an temp file for the new generated PDF.
$pdf_temp = tmpfile();
$pdf_uri = stream_get_meta_data($pdf_temp)["uri"];

//Save the PDF to the path
$xmlWriter->save($pdf_uri);

//Now print the file from the temp path.
echo file_get_contents($pdf_uri);
</code>```

I choose the TCPDF engine, because it was very easy to install. Just simply download the files from the Git Repository or the website and load it in to an folder.

Of course, finally it might be not the best solution, but for me, it is just a preview of an word document.

So this script was inspired also by the following two links:

Load and save Word files

Render PDF

Body:
I don't have any plan how can I convert an Word document, which I have as a string (blob) from my database, to a PDF via the PHPOffice library.

Concept:

I fetch an existing word document as an string from the database

Pass the string through an constructor or an function of PHPOffice library.

Then get via another function the PDF as an string

And last output the string with Content-Type: application/pdf to the user.

Nr. 1 and 4 I already implemented. But I don't know how to accomplish nr. 2 and 3. Can someone help me?

Code:

//DB-Connection, Composer autoload, ...

$id = htmlspecialchars(trim($_REQUEST["id"]));

$get_data = $con->query("SELECT * FROM word_documents WHERE id='$id'"); //Get the blob
$data = $get_data->fetch();
if ($get_data->rowCount() == 1) {
    header("Content-Type: application/pdf");
    header("Content-Disposition: inline; filename=" . $data["name"]);

    //TODO: Print the PDF as an string

} else {
    echo "File not found";
}

Body:
After I tried some functions from the PhpOffice library, I've finally found an solution.

So with the library at self, you can not load and save it directly from a string to a string. You have to create files currently.

//Set header to show as PDF
header("Content-Type: application/pdf");
header("Content-Disposition: inline; filename=" . $data["name"]);

//Create a temporary file for Word
$temp = tmpfile();
fwrite($temp, $data["data"]); //Write the data in the file
$uri = stream_get_meta_data($temp)["uri"]; //Get the location of the temp file

//Convert the docx file in to an PhpWord Object
$doc = PhpOffice\PhpWord\IOFactory::load($uri);

//Set the PDF Engine Renderer Path. Many engines are supported (TCPDF, DOMPDF, ...).
\PhpOffice\PhpWord\Settings::setPdfRendererPath("path/to/tcpdf");
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');

//Create a writer, which converts the PhpWord Object into an PDF
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($doc, 'PDF');

//Create again an temp file for the new generated PDF.
$pdf_temp = tmpfile();
$pdf_uri = stream_get_meta_data($pdf_temp)["uri"];

//Save the PDF to the path
$xmlWriter->save($pdf_uri);

//Now print the file from the temp path.
echo file_get_contents($pdf_uri);

I choose the TCPDF engine, because it was very easy to install. Just simply download the files from the Git Repository or the website and load it in to an folder.

Of course, finally it might be not the best solution, but for me, it is just a preview of an word document.

So this script was inspired also by the following two links:

Load and save Word files

Render PDF


问:
How to implement swipeview QtQuick 2.5
I have QT 5.5 and it won't support SwipeView. I tried doing with listView but I am not getting what I expected. I want a similar functionality code in QT 5.5 like the code given below which is written in QT 5.6. Please help</p>

```<code>import QtQuick 2.6
import QtQuick.Controls 2.0
import QtQuick.Window 2.0
Window {
    visible: true
    width: 200
    height: 400
    title: qsTr("Hello World")

    id: page

    SwipeView {
        id: swipeView
        anchors.fill: parent
        currentIndex: 0
        Page {
                    Label {
                        text: qsTr("First page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Second page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Third page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Fourth page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Fifth page")
                        anchors.centerIn: parent
                    }
                }
    }

    Rectangle
    {
        id:minus
        width:parent.width/2
        height:100
        anchors.left:parent.left
        anchors.bottom:parent.bottom
        color:"red"
        MouseArea
        {
            anchors.fill:parent
            onClicked:{
                if(swipeView.currentIndex>0)
                    swipeView.currentIndex--
            }
        }
    }
    Rectangle
    {
        id:plus
        width:parent.width/2
        height:100
        anchors.right:parent.right
        anchors.bottom:parent.bottom
        color:"green"
        MouseArea
        {
            anchors.fill:parent
            onClicked:{
                if(swipeView.currentIndex<4)
                    swipeView.currentIndex++
            }
        }
    }

}
</code>```

答:
If you cannot update your Qt version, you can indeed approximate a SwipeView using a ListView, a VisualItemModel, and a default qml property.

SwipeView.qml

ListView
{
    id: root

    // Allow to add pages as you would for a QtQuick.Controls 2 SwipeView
    // Each item you declare in your SwipeView will be reparented to itemModel
    default property alias items: itemModel.children

    // SwipeView is horizontal
    orientation: Qt.Horizontal

    // Hide out of bounds pages
    clip: true

    // Do not stop between two pages
    snapMode: ListView.SnapToItem

    // Update currentIndex as you swipe through the pages
    highlightRangeMode: ListView.StrictlyEnforceRange

    model: VisualItemModel {
        id: itemModel
        // Used to bind the pages size to the swipeView size
        onChildrenChanged: {
            for(var i=0;i<children.length; i++)
            {
                children[i].width = Qt.binding(function(){return root.width})
                children[i].height = Qt.binding(function(){return root.height})
            }
        }
    }

}
```

<p><strong>Page.qml</strong></p>

<pre class="lang-qml prettyprint-override"><code>Item {
    property string title

    Rectangle
    {
        anchors.fill: parent
        border.width: 1
    }

    Text
    {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: parent.top
        anchors.topMargin: 20
        text: title
    }
}
</code>```

PageIndicator.qml

Row
{
    id: root

    property int count
    property int currentIndex
    property Component delegate: bullet
    property bool interactive
    spacing: 5

    Component
    {
        id: bullet
        Rectangle
        {
            height: 10
            width: height
            radius: height/2
            color:"black"
            opacity: currentIndex==index?0.8:0.2
        }
    }

    Repeater
    {
        model: root.count
        Loader
        {
            property int index: model.index
            sourceComponent: delegate
        }
    }
}
```

<p><strong>main.qml</strong></p>

<pre class="lang-qml prettyprint-override"><code>import QtQuick 2.5
import QtQuick.Controls 1.4

ApplicationWindow
{
    id: window
    visible: true
    width: 300
    height: 300

    SwipeView
    {
        id: swipeView
        anchors.fill: parent
        Page
        {
            title: "Page 1"
        }
        Page
        {
            title: "Page 2"
        }
        Page
        {
            title: "Page 3"
        }
    }

    PageIndicator
    {
        id: pageIndicator
        anchors.bottom: swipeView.bottom
        anchors.bottomMargin: 10
        anchors.horizontalCenter: swipeView.horizontalCenter
        count: swipeView.count
        currentIndex: swipeView.currentIndex
    }
}
</code>```

Title: How to implement swipeview QtQuick 2.5

Body:
I have QT 5.5 and it won't support SwipeView. I tried doing with listView but I am not getting what I expected. I want a similar functionality code in QT 5.5 like the code given below which is written in QT 5.6. Please help

import QtQuick 2.6
import QtQuick.Controls 2.0
import QtQuick.Window 2.0
Window {
    visible: true
    width: 200
    height: 400
    title: qsTr("Hello World")

    id: page

    SwipeView {
        id: swipeView
        anchors.fill: parent
        currentIndex: 0
        Page {
                    Label {
                        text: qsTr("First page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Second page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Third page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Fourth page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Fifth page")
                        anchors.centerIn: parent
                    }
                }
    }

    Rectangle
    {
        id:minus
        width:parent.width/2
        height:100
        anchors.left:parent.left
        anchors.bottom:parent.bottom
        color:"red"
        MouseArea
        {
            anchors.fill:parent
            onClicked:{
                if(swipeView.currentIndex>0)
                    swipeView.currentIndex--
            }
        }
    }
    Rectangle
    {
        id:plus
        width:parent.width/2
        height:100
        anchors.right:parent.right
        anchors.bottom:parent.bottom
        color:"green"
        MouseArea
        {
            anchors.fill:parent
            onClicked:{
                if(swipeView.currentIndex<4)
                    swipeView.currentIndex++
            }
        }
    }

}

Body:
If you cannot update your Qt version, you can indeed approximate a SwipeView using a ListView, a VisualItemModel, and a default qml property.

SwipeView.qml

ListView
{
    id: root

    // Allow to add pages as you would for a QtQuick.Controls 2 SwipeView
    // Each item you declare in your SwipeView will be reparented to itemModel
    default property alias items: itemModel.children

    // SwipeView is horizontal
    orientation: Qt.Horizontal

    // Hide out of bounds pages
    clip: true

    // Do not stop between two pages
    snapMode: ListView.SnapToItem

    // Update currentIndex as you swipe through the pages
    highlightRangeMode: ListView.StrictlyEnforceRange

    model: VisualItemModel {
        id: itemModel
        // Used to bind the pages size to the swipeView size
        onChildrenChanged: {
            for(var i=0;i<children.length; i++)
            {
                children[i].width = Qt.binding(function(){return root.width})
                children[i].height = Qt.binding(function(){return root.height})
            }
        }
    }

}

Page.qml

Item {
    property string title

    Rectangle
    {
        anchors.fill: parent
        border.width: 1
    }

    Text
    {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: parent.top
        anchors.topMargin: 20
        text: title
    }
}

PageIndicator.qml

Row
{
    id: root

    property int count
    property int currentIndex
    property Component delegate: bullet
    property bool interactive
    spacing: 5

    Component
    {
        id: bullet
        Rectangle
        {
            height: 10
            width: height
            radius: height/2
            color:"black"
            opacity: currentIndex==index?0.8:0.2
        }
    }

    Repeater
    {
        model: root.count
        Loader
        {
            property int index: model.index
            sourceComponent: delegate
        }
    }
}

main.qml

import QtQuick 2.5
import QtQuick.Controls 1.4

ApplicationWindow
{
    id: window
    visible: true
    width: 300
    height: 300

    SwipeView
    {
        id: swipeView
        anchors.fill: parent
        Page
        {
            title: "Page 1"
        }
        Page
        {
            title: "Page 2"
        }
        Page
        {
            title: "Page 3"
        }
    }

    PageIndicator
    {
        id: pageIndicator
        anchors.bottom: swipeView.bottom
        anchors.bottomMargin: 10
        anchors.horizontalCenter: swipeView.horizontalCenter
        count: swipeView.count
        currentIndex: swipeView.currentIndex
    }
}


问:
How to make Silverlight version of existing C# code that relies on System.Drawing namespace
We have pretty much C# 2.0 code that heavily relies on System.Drawing namespace. Also there is some WinGDI dependencies (via interop).

How would you recommend to tackle the problem of making functionally equivalent Silverlight version of the code? We want to reuse code as much as possible because we want to continue develop both versions of the code.

Maybe there is some articles/books you could recommend?

UPDATE: The code is a non-visual component. Not an application. There is no 3rd party dependencies.

答:
If there is no GUI and you are still using lots of System.Drawing I guess what this component does is related to manipualtion of images in memory.

If that's the case, due to the very high cost of porting all the code, if at all possible, you can consider to change your architecture.

Have the old code in the server side, where you can freely use these APIs, and expose the required functionality to your Silverlight application through some web service. If the component has no GUI it should be very feasible.

Edit: Adding suggestions of how this might be appropriate for developers

Maybe this might still work - if your developer plans to deploy this Silverlight control in a web page, then he probably has a web server on which he can place your component to be accessible for the Silverlight code.

If the developer plans to deploy your Silverlight code in Out-of-Browser mode, you can make a version that would embed the old component (for example as a COM object).

An addition alternative to the above, would be to host this component yourself on a server, or on some public cloud such as Windows Azure.


问:
Python linear search not working
For some reason this python linear search will not work. Every time I run it and input a value that is in the list, it does not tell me that the item is in the list and just runs through.
It does not give any syntax error so must be something logical. Any ideas?</p>

```<code>def linearSearch():
numbers = [3, 5, 54, 6, 17, 8, 32, 65, 87, 54]
pointer = 0
print("What would you like to search for?")
searchTerm = input()
try:
    val = int(searchTerm)
except ValueError:
    print("Please enter an integer")
    linearSearch()
while pointer < len(numbers):
    if numbers[pointer] == searchTerm:
        print("Item has been found at " + pointer)
    else:
        pointer = pointer + 1
</code>```

答:
You should use val which is an int and not searchTerm which is a string when you compare with numbers[pointer].
Plus, don't forget to break your loop, else it will run indefinitely!

```<code>if numbers[pointer] == val:
        print("Item has been found at " + str(pointer))
        break
</code>```

edit Also added a str(pointer) because it will thrown an error in Python3+ when you try to add int with string.

Title: Python linear search not working

Body:
For some reason this python linear search will not work. Every time I run it and input a value that is in the list, it does not tell me that the item is in the list and just runs through.
It does not give any syntax error so must be something logical. Any ideas?

def linearSearch():
numbers = [3, 5, 54, 6, 17, 8, 32, 65, 87, 54]
pointer = 0
print("What would you like to search for?")
searchTerm = input()
try:
    val = int(searchTerm)
except ValueError:
    print("Please enter an integer")
    linearSearch()
while pointer < len(numbers):
    if numbers[pointer] == searchTerm:
        print("Item has been found at " + pointer)
    else:
        pointer = pointer + 1

Body:
You should use val which is an int and not searchTerm which is a string when you compare with numbers[pointer].
Plus, don't forget to break your loop, else it will run indefinitely!

if numbers[pointer] == val:
        print("Item has been found at " + str(pointer))
        break

edit Also added a str(pointer) because it will thrown an error in Python3+ when you try to add int with string.


问:
How to put a gray overlay on an image in CSS
I'd like to create a website that has a banner on every page with an image that has a gray overlay. In that way, white text on the image becomes more visible.
The result should look exactly like this: http://skoopopweg.weebly.com/programma.html.

I found ways to dull the image, but not to put an overlay on top of it.
Can anybody help?

This is my code in CSS for this class of images thus far:

```<code>.img-with-overlay{width:100%; position:relative;}
</code>```

And in html:

```<code><img class="img-with-overlay" src="img1.jpg" />
</code>```

答:
.image_div{
  width:100px;
  height:100px;
  position:relative;
  display:flex;
  justify-content:center;
  align-items:center;
}

.image_div img{
  max-width:100%;
  max-height:100%;
}

.image_div .img_overlay{
  position:absolute;
  top:0;
  left:0;
  height:0;
  bottom:0;
  width:100%;
  height:100%;
  background:rgba(0,0,0,0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image_div">
  <img src="http://cl.jroo.me/z3/q/R/R/d/a.aaa-Unique-Nature-Beautiful-smal.jpg">
  <div class="img_overlay">

  </div>
</div></code>```

Here is JSFiddle

Is this the same that you are looking for?

Hope this helps.

Body:
I'd like to create a website that has a banner on every page with an image that has a gray overlay. In that way, white text on the image becomes more visible.
The result should look exactly like this: http://skoopopweg.weebly.com/programma.html.

I found ways to dull the image, but not to put an overlay on top of it.
Can anybody help?

This is my code in CSS for this class of images thus far:

.img-with-overlay{width:100%; position:relative;}

And in html:

Body:
.image_div{
  width:100px;
  height:100px;
  position:relative;
  display:flex;
  justify-content:center;
  align-items:center;
}

.image_div img{
  max-width:100%;
  max-height:100%;
}

.image_div .img_overlay{
  position:absolute;
  top:0;
  left:0;
  height:0;
  bottom:0;
  width:100%;
  height:100%;
  background:rgba(0,0,0,0.4);
}

<div class="image_div">
  <img src="http://cl.jroo.me/z3/q/R/R/d/a.aaa-Unique-Nature-Beautiful-smal.jpg">
  <div class="img_overlay">

  </div>
</div>

Here is JSFiddle

Is this the same that you are looking for?

Hope this helps.


问:
Accessing Configuration Settings in a static context
It is possible to access the configuration settings value in a static context?

For instance, here is the code, which fails with a red line stating that one "cannot access non-static property 'Settings' in static context."  All I need is the value of the setting.

```<code>namespace MyCompany.Sample.EmailConnector.Provider.Implementation
{
    class GmailEmailConnectorProvider : EmailConnectorProvider
    {
        private string clientSecret = Settings.ClientSecret; // Here is the error
                                         ^^

        public override Email SendTestEmail(string address, string message)
        {
            throw new NotImplementedException();
        }
    }
}
</code>```

答:
You can also use the Default static property:

```<code>private string clientSecret = Settings.Default.ClientSecret;
</code>```

Body:
It is possible to access the configuration settings value in a static context?

For instance, here is the code, which fails with a red line stating that one "cannot access non-static property 'Settings' in static context."  All I need is the value of the setting.

namespace MyCompany.Sample.EmailConnector.Provider.Implementation
{
    class GmailEmailConnectorProvider : EmailConnectorProvider
    {
        private string clientSecret = Settings.ClientSecret; // Here is the error
                                         ^^

        public override Email SendTestEmail(string address, string message)
        {
            throw new NotImplementedException();
        }
    }
}

Body:
You can also use the Default static property:

private string clientSecret = Settings.Default.ClientSecret;


答:
```<code>TankDetailsModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString("HH:mm");
</code>```

this might help you

Title: how to convert date time to only time in c#

Body:
i want to convert datetime format to only time format.

data type - string

op- 5/31/2017 8:43:20 PM
req op - 8:43 (in 24 hours format)

code

TankDetailsModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();

Body:
TankDetailsModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString("HH:mm");

this might help you