text:
Q: Apple Pay Web .NET Could Not Create SSL/TLS Secure Channel on Merchant Validation I'm trying to integrate Apple Pay on our production website. I managed to complete the implementation on my local machine and successfully tested it with an Apple sandbox account. However, when we ported the integration to our production environment, on the merchant validation step, it fails with this error: "Could Not Create SSL/TLS Secure Channel".
Some information:

*

*We checked multiple times that the merchant ID, domain name and all other parameters we send for merchant validation are correct

*Our production server supports TLS1.2 and the cipher suites required by Apple pay to work

*The domain validation has been done

*The TLS certificate we send for the merchant validation has been created in compliance with the Apple documentation guidelines and the server process has the right permissions to access it

*We explicitly set the security protocol as TLS 1.2 in the code

*We tried turning off the firewall but it didn't change anything

*Our server uses .NET version 4.5.2

The certificate for TLS handshake is a .pfx file that we made by combining the .pem and .key files obtained during the certificate creation procedure as described in the documentation. We add the certificate directly into the web request via code, like this (vb.net):
 ServicePointManager.Expect100Continue = True
 ServicePointManager.SecurityProtocol = CType(12288, SecurityProtocolType) Or CType(3072, SecurityProtocolType) Or CType(768, SecurityProtocolType) Or SecurityProtocolType.Tls

 Dim _request As HttpWebRequest = HttpWebRequest.Create(_validationUrl)
 Dim _certFile As String = Path.Combine(applePayCertificatePath, applePayCertificateName)
 Dim _certificate As New X509Certificate2(_certFile, applePayCertificatePassword)

 _request.ClientCertificates = New X509CertificateCollection({_certificate})
 _request.ClientCertificates.Add(_certificate)

We searched all the web for a solution but we can't seem to find one. It looks like a server configuration/networking issue since, as I said, it works perfectly on my local machine.
Any insight on the matter would be greatly appreciated.
Thanks


text:
Q: I need a thread in Web/JavaEE container to complete AsyncContext objs in same JVM I need a thread in Web/JavaEE container to fetch information from an external source and complete corresponding AsyncContext objs in same JVM.
I wish to have a zero-added-latency solution, so periodic polling or a timer is ruled out.
I could start a thread but I believe it is frowned upon in a Web container and not portable. Q1. Is it possible to run a thread portably in a Java EE container instead?
Q2. If I want to run a thread in a Web Container anyway, what is the "least of all evil" ways?  InitializeContext? ExecutorService? Thread.run?
Thanks!

A: AsyncContext.html#start is probably the closest you can get.

A: You can use work manager in jsr237 for creating a thread in a Java EE container. : http://jcp.org/en/jsr/detail?id=237. If you want an asynchronous job, you should use JMS.

A: In Java EE 6, you can put the @Asynchronous annotation on an EJB method to have the work in that method be handled by a special thread-pool:
@Stateless
public class SomeBean {

    @Asynchronous
    public void doSomething() {
        // ...
    }
}

Then somewhere else, inject this bean and call the doSomething() method. Control will return immediately.
@WebServlet("/test")
public class SyncServlet extends HttpServlet {

    @EJB
    private SomeBean someBean;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        someBean.doSomething();
    }
}

Note that you might not need something like AsyncContext asyncContext = request.startAsync() here. You would use this only if the asynchronous code would still need to send something to the response.
If you need something akin to a period timer though, and not do something in response to a request, you can use the timer service in a singleton:
@Startup
@Singleton
public class SomeTimerBean {

    @Schedule(hour = "*", minute = "*/30", second = "0", persistent = false)
    public void doStuff() {
        // ...
    }
}

Instead of running periodically, you can also run something like this once using the @TimeOut annotation:
@Startup
@Singleton
public class SomeTimerBean {

    @Resource
    private TimerService timerService;

    @Postconstruct
    public void init() {
         timerService.createSingleActionTimer(0, new TimerConfig(null, false));
    }

    @Timeout
    public void doStuff(Timer timer) {
        // ...
    }
}

You can have variants on this, e.g. SomeTimerBean can also call an @Asynchronous method in an other bean as well to basically have the same effect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Quantifying uncertainty with RVM I am reading about relevance vector machines as a potential methodology to address a regression problem with prediction of a continuous variable, where I more specifically want to work with a model which is suitable for quantifying uncertainty.
In this article they compare RVMs with SVMs, and discuss that unlike SVMs one can attain the associated uncertainty of a prediction when using RVMs. However they also mention that RVMs can get stuck in local optima rather than finding the global optima which SVMs do. How RVMs work is also addressed in How does a Relevance Vector Machine (RVM) work? but from an approach of quantifying uncertainty, is it possible to evaluate an estimate of RVMs, and it's associated uncertainty if we can't ensure it's a global optima?


text:
Q: Updating two entities simultaenously in Java Pong I've started using LWJGL recently since I stopped using Java and wanted a quick refresher with something new tied in. Unfortunately, I've encountered a problem while working on a small Java pong game. I sort of sped through it, but I've reviewed my code multiple times and I cannot figure out what is wrong.
Problem: I can't update multiple entities on the screen at the same time. It is weird because I have no problem moving them, and their values update accordingly according to the debugger, but the graphics will not update on the screen. Here is my code for the main program:
package lwjgl2;

import static org.lwjgl.opengl.GL11.*;

import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

public class Main {

    private Box ball = new Box(640>>1, 480>>1, 5, 5);
    private Box paddle = new Box(10, 10, 10, 40);

    private long lastTime;
    private long getTime(){
        return (Sys.getTime() * 1000) / Sys.getTimerResolution();
    }
    private int getDelta(){
        long currentTime = getTime();
        int delta = (int) (currentTime - lastTime);
        lastTime = getTime();
        return delta;
    }

    public Main() {
        //display
        try{
            Display.setDisplayMode(new DisplayMode(640,480));
            Display.setTitle("Hello");
            Display.create();
        } catch(LWJGLException e){
            e.printStackTrace();
        }
        //ogl
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, 640, 480, 0, 1, -1);
        glMatrixMode(GL_MODELVIEW);

        lastTime = getTime();

        //main loop
        while(!Display.isCloseRequested()){

            glClear(GL_COLOR_BUFFER_BIT);
            if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)){
                Display.destroy();
                System.exit(0);
            }
            paddle.setDX(0.1);
            ball.setDX(0.3);
            ball.setDY(0.2);

            //main game loop goes nyah

            ball.update(getDelta());
            paddle.update(getDelta());
            ball.draw();
            paddle.draw();
            Display.update();
            Display.sync(60);
        }
        //destroy display
        Display.destroy();

    }

    private class Box extends Entity{

        public Box(int x, int y, int height, int width) {
            super(x, y, height, width);
            // TODO Auto-generated constructor stub
        }

        public void update(int delta){
            super.x += dx * delta;
            super.y += dy * delta;
        }

        public void draw(){
            glRecti(x, y, x + height, y + width);
        }

    }

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

}

Like I said, the only entity that will actually render properly on the screen is whatever I call the update() method on first, in this case, the ball. If I call the paddle first, then the paddle will move, but the ball will stay still. I know I must have made a stupid mistake somewhere but I can't find it.
Also, the Entity class, possibly the main culprit:
package lwjgl2;

import java.awt.Rectangle;

public abstract class Entity {

    protected int x;
    protected int y;
    protected int height;
    protected int width;
    protected double dx;
    protected double dy;
    protected Rectangle bounds = new Rectangle();

    public Entity(int x, int y, int height, int width) {
        this.x = x;
        this.y = y;
        this.height = height;
        this.width = width;
        this.dx = 0;
        this.dy = 0;
    }

    public int getX(){
        return x;

    }

    public int getY(){
        return y;

    }

    public double getDX(){
        return dx;

    }

    public double getDY(){
        return dy;

    }

    public void setX(int x){
        this.x = x;
    }

    public void setY(int y){
        this.y = y;
    }

    public void setDX(double dx){
        this.dx = dx;
    }

    public void setDY(double dy){
        this.dy = dy;
    }

    public void update(int delta){

    }

    public void draw(int delta){

    }

}

A: I've figured it out. It happens that updating multiple entities at varying times through the loop isn't a good idea, so you should create a method for updating every entity at once.


text:
Q: Reference request on the relationship between inscribed polytopes and shadows of their facets Two chords of a circle of unit radius have equal lengths if their corresponding arcs have equal lengths.
Suppose a polytope is the convex hull of finitely many points on the unit $(n-1)$-sphere in $\mathbb R^n.$ Each of its $(n-1)$-dimensional facets casts a shadow on the sphere, the light-source being at the center. Suppose a proposition says two such facets have equal $(n-1)$-dimensional volumes if their shadows have equal volumes. I suspect that that is false in general, even if both facets have equally many vertices. (Unlike with chords of circles, their shapes can differ.)
My question is which books or exposititory articles give an introductory treatment of such questions as whether such a proposition as that is true.

A: This particular statement is false. When similar-sounding statements turn out to be true they can sometimes be proved by the methods of integral geometry / geometric probability, by comparing appropriately constructed measures.
Two sources are

*

*"Integral Geometry and Geometric Probability" by Santalo,

*"Introduction to Geometric Probability" by Klain and Rota.

Unfortunately, while it is not difficult to disprove the statement above, I have no nice disproof which demonstrates the use of integral geometry, so I hesitate to post this as an answer. But it seems better than no answer at all.


text:
Q: R/W register outside application address space with Android Native C++ I'll start at the end.
My final goal is to build a C/C++ library with Android NDK which would allow me to directly access registers in the Freescale i.MX 6Solo processor so that I could implement methods which would control hardware GPIO, SPI, I2C and PWM from Java. Once I'd build and compile the methods in a native library, they would be provided to Android programmers for the remainder of the project. My background is primarily in C/C++ micro-controller development but I'm quickly getting oriented in Java as well.
My question:
I have successfully written and compiled the native C++ code and managed to call it from Java. The test program also runs on the target processor, but when I call the native method which would write directly to the desired CPU register the system hangs and I get the error in LogCat:
Fatal signal 11 (SIGSEGV) at 0x20E015C (code=1), thread 3699 (xamp le.nativecall)
Signal 11 and the Segmentation fault (SIGSEGV) mean that my application is trying to access memory outside it's adress space which is exactly what I'm trying to do, namely to write into the register 0x020E015C.
So my question follows: How can I successfuly write into registers outside of the application address space?
What have I tried so far:
I found a promising description of a situation where there's a virtual adress space involved on this site under "Variable Base Addresses", but I'm having some trouble understanding and implementing the solution he proposes. For the record, the line in which I attempt to modify the register is:
*(volatile uint32_t *)GPIO4_16MUX = 0x00000005;

Where I've previously defined GPIO4_16MUX to be 0x20E015C.
Software and Hardware:
Android ADK and Eclipse, building for Android 4.3 with NDK rc10, RIoT Board with Cortex-A9 i.MX 6Solo.

A: In normal, protected memory linux environments like Android, one process can't arbitrarily access absolute memory addresses. Keep in mind that you only see a virtual memory address space within your application anyway - the mappings are set up by the kernel. Even if the address 0x20E015C would happen to be readable/writeable within your process, it doesn't mean that it maps to 0x20E015C on the hardware level (it most probably wouldn't).
You'd either need to modify your kernel to map this memory specifically to your process (or all processes), or more practically, create a kernel driver which exposes the registers as a unix char/block device. Then you can manage the permissions for accessing the device via the normal unix permissions, and any user level process with access to the device can control it.


text:
Q: How to make a for loop that prints horizontally I want a loop that print 5 random numbers that will print vertically
so far I have...
for(let i = 0; i < 5; i++ ) {
let x = Math.floor(Math.random() * 10);
console.log(x)
}

Then when I run it I got 5 random numbers and I just don't know how to print it horizontally

A: Depends on your desired output format, but you can do something like this:

let arr = [];
for (let i = 0; i < 5; i++) {
  let x = Math.floor(Math.random() * 10);
  arr.push(x)
  console.log(x)
}
console.log(...arr)

If you want to do it with commas you dan do it with e.g. .map().

let arr = [];
for (let i = 0; i < 5; i++) {
  let x = Math.floor(Math.random() * 10);
  arr.push(x);
  console.log(x);
}
const len = arr.length;
const commaArray = arr.map((x, i) => i < len - 1 ? x + ',' : x);
console.log(...commaArray);

A: You could just add them all onto a big string and print that at the end!
output = ''
for(let i = 0; i < 5; i++ ) {
    let x = Math.floor(Math.random() * 10);
    output = output + ' ' + x;
}
console.log(output);

A: You can do it like this.
var values=[];
for(let i = 0; i < 5; i++ ) {
   values.push(Math.floor(Math.random() * 10));
}
console.log(values);    //if you want to print an array
console.log(values.join()); //if you want to print as string with coma sepration
console.log(values.join(" ")); //if you want to print as string with empty spaces

A: By printing horizontally I'm assuming you mean in the same line. In that case, you do what was mentioned above, or you can create a string with all the numbers
let string = "";
for(let i = 0; i < 5; i++ ) {
   let x = Math.floor(Math.random() * 10);
   string = `${string} ${x.toString()}`;
}
console.log(string);


text:
Q: Parsing multiple rows of json in Android I want to get a json file from my server and display it in my android app.
For now, it is ok just showing in log console.
I am able to get the whole json file, something like:
[{"name":"john", "surname":"connor"}, {"name":"sarah", "surname":"connor"}]

But, in android if I try to use a string like this, it fails because []
If I try:
JSONObject json=new JSONObject(result); //result has the previous string
Log.i("TEST", json.toString());

I have to delete [ and ] to go ahead and nn log, I just have the first entrance of my json.
If I leave [ and ], it just do nothing. Stop before the first line.
The complete example code is here.

A: Replace  this
JSONObject json=new JSONObject(result); //result has the previous string
    Log.i("TEST", json.toString());

With
JSONArray json=new JSONArray(result); //result has the previous string
    Log.i("TEST", json.toString());


text:
Q: Aspose Formatting What is the correct style property to use to format numbers in aspose(using C#). I would like to do 2 things:
1) Format a five digit number as a zip code.(I'm not quite sure which Style property to use to get the custom excel zipcode format)
2) Format a number(double) so that it does not have any commas and only has 2 trailing decimal points.  I've tried using "###0.00" as the custom style but it does not seem to be working.
Any help would be much appreciated.
Zip Code Code:
    //zipcode code
    Style zipcodeStyle = targetCells[1, 1].GetStyle();
    zipcodeStyle.Custom = "0####";
    targetCells[rowindex - 20, 16].PutValue("01234");//test zipcode
    targetCells[rowindex - 20, 16].SetStyle(zipcodeStyle);

Resulting Excel Value: 1234
Number Code:
    targetCells[rowindex - 20, 45].PutValue("1234.56");
    Style style = targetWs.Cells[rowindex - 20, 45].GetStyle();
    style.Custom = "###0.00";
    targetCells[rowindex - 20, 45].SetStyle(style);
    targetCells[rowindex - 20, 45].Copy(sourceCells[rowindex, 26]);
    //test value: 140,366.75

Resulting Excel Value: 140,366.75

A: Figured it out.  you have to format the string data as text.  The data from the source cells must be put inside the text formula.  For the zip code it should be:
=text(datavalue, "00000")

All  US zipcodes are 5-digits long so the leading zero from the above example will be preserved.  As for the number formatting, it also will be changed to text in order to preserve trailing zeros.  For the number format, it should be:
=text(datavalue, ".00")

The data value above needs to be purged of commas before you can use this method however.  The result will be placed in a cell and you should be able to perform math operations on it as well.


text:
Q: how to use gson handle dynamic response data? (json to java object) Here is Json list of users:
{
    'response': {
        'result': {
            'users': [{
                name: "ABC",
                age: "20",
                gender: "F"
            },
            {
                name: "cbd",
                age: "23",
                gender: "M"
            }]
        }
    }
}

And sometimes return like this
{
    'response': {
        'result': {
            'users': {
                name: "ABC",
                age: "20",
                gender: "F"
            }
        }
    }
}

When it is return single user I can use following java class to covert json to java
class Data{
    private response response;
    class response{
        private result result;
        class result{
            private users users;
            class users{
                private String name;
                private String age;
                private String gender;

            }

        }
    }

}

but if  returns lists of users I get Exception. How can I handle it?

A: To do what you want, you have to change users to a List<User> and write a (simple) custom deserializer. Without custom deserializer Gson won't parse, unless you switch users to Object (but in that case it will return a list of maps).
Before showing you a full example that you can copy and run in your IDE, two notes. User " instead of ' as string delimiter and follow Java naming conventions. Classes must have at least first letter in upper case. Putting lowercase won't change Gson behavior since it looks at class fields name not to class names.
package stackoverflow.questions.q19124387;

import java.lang.reflect.Type;
import java.util.*;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

public class Q19124387 {

   public static class User {
      private String name;
      private String age;
      private String gender;
      @Override
      public String toString() {
         return "User [name=" + name + ", age=" + age + ", gender=" + gender + "]";
      }

   }

   public static class Result {
      private List<User> users = new ArrayList<User>();

   }

   public static class Response {
      private Result result;

   }

   public static class Data {
      private Response response;

   }

   public static class CustomDeserializer implements JsonDeserializer<Result> {

      public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

         Result r = null;

         JsonElement usersField = json.getAsJsonObject().get("users");
         if (usersField.isJsonNull() || usersField.isJsonPrimitive())
            ; // if is null or is a primitive type will return an empty result
         else if (usersField.isJsonObject()) {
            r = new Result();
            r.users.add((User) context.deserialize(usersField, User.class));

         } else if (usersField.isJsonArray()) {
            Type listOfUserType = new TypeToken<List<User>>() {}.getType();
            r = new Result();

            r.users.addAll((Collection<? extends User>) context.deserialize(usersField, listOfUserType));

         }
         return r;

      }

   }

   /**
    * @param args
    */
   public static void main(String[] args) {
      String json1 = " {\"response\": {  \"result\": { \"users\": [{ name: \"ABC\",  age: \"20\", gender: \"F\"  },  { name: \"cbd\",  age: \"23\", gender: \"M\"  }] }  }  }";

      String json2 = "{\"response\": { \"result\": {\"users\": { name: \"ABC\", age: \"20\",gender: \"F\" } } } }  ";

      Gson g = new Gson();
      try {
         Data d1 = g.fromJson(json1, Data.class);
         System.out.println("Parsed json1, list of users");
      } catch (Exception e) {
         System.out.println("Cannot parse json1, list of users");
      }
      try {
         Data d2 = g.fromJson(json2, Data.class);
         System.out.println("Parsed json2, single user");
      } catch (Exception e) {
         System.out.println("Cannot parse json2, single user");
      }

      GsonBuilder gb = new GsonBuilder();
      gb.registerTypeAdapter(Result.class, new CustomDeserializer());
      Gson g2 = gb.create();

      Data d1 = g2.fromJson(json1, Data.class);
      Data d2 = g2.fromJson(json2, Data.class);

      System.out.println("Second user of json1 is " + d1.response.result.users.get(1));
      System.out.println("First user of json2 is " + d2.response.result.users.get(0));

   }

}

this is the execution of code:
Parsed json1, list of user
Cannot parse json2, single user
Second user of json1 is User [name=cbd, age=23, gender=M]
First user of json2 is User [name=ABC, age=20, gender=F]


text:
Q: When combined with Meteor, what AngularJS can do that Handlebars can not? I am considering using AngularJS instead of Handlebars with MeteorJS. I am more familiar with AngularJS, but it doesn't work well out-of-the-box with Meteor. Handlebars is default templating engine used in MeteorJS.
I would like to know the trade-off between the two, e.g., whether AngularJS provides more flexible front-end coding than Handlebars.
My question is: when pairing with Meteor, what AngularJS can do that Handlebars can not in terms of front-end programming?
(Note that people love AngularJS in part b/c of its two-way binding and data model, but Meteor-Handlebars do these very well too).
Update: Please do not vote to close this question if you think it is a duplicate of another question in SO that compares Angular and Handlebars. Meteor added significant power to Handlebars due to its "database on client" approach.

A: Angular and Meteor can be combined, and it's a pretty neat combo. Angular's templating system and its two-way bindings (DOM to JS model) can even be made to go the whole way and be kept in sync with a Meteor collection. Such a pairing of Angular and Meteor means you get instantaneous DOM to database syncing, which is very cool. Angular can't do that by itself, nor can Meteor (without writing more or less tedious event handlers) and even less Handlebars.
The angular-meteor Meteor package is pretty much ngMeteor's successor (it builds on ngMeteor code) and integrates Meteor collections with Angular models, the two templating systems, Meteor Session variables etc.

A: TL;DR: Meteor works best with packages (think jQuery, bootstrap, d3, underscore, stylus, less) since they enhance a framework. Those same packages would enhance Angular too (well, kind of). Angular is an end-to-end framework, so trying to integrate it on top of another end-to-end framework like Meteor is a recipe for headaches.
Handlebars has very similar expressions and bindings that you're probably familiar with in Angular. But while the templating engine is similar, it's the rest of the frameworks that differ greatly.
Angular leans heavily on its internal directives (ng-repeat, ng-form, ng-bind, etc.) to easily tie in javascript (i.e. power) to your markup. There's a lot of magic behind the scenes.
Meteor leans heavily on the pub/sub model and connecting to your true data stores. Their secret sauce comes from easily adding but abstracting packages (handlebars is one of their default packages, but some others are bootstrap, accounts-ui, d3, etc.).
Meteor follows very different ideologies and has different opinions on framework design than Angular does. In my opinion, Meteor's are superior though the project is still in its relative infancy. You'll find that Meteor is really, really good at prototyping quickly, especially if you need to tie in user support and want to use Twitter/Facebook/Google.
You'd be better off choosing one or the other, but if you're not strong on the server side, you could write a pretty slick Meteor app to just act as your API server.

A: If you want to use angularjs with meteor you can just install a package that does that. Then you can use both meteor and angular.
Meteor is realy nice for getting your data from server to client, angular is very nice in getting that data displayed (and stable).
mrt add angular-stack

or
mrt add ngMeteor

A: Generally speaking, AngularJS has passed the version 1.0 milestone and is considered ready for production use while meteor is still alpha software. Consequently, Angular is more polished, has directives, modules and rich third-party libraries like AngularUI.
But if you feel like experimenting with a bleeding-edge framework, don't think you'll have to do super-fancy templating-stuff but need a database built in, go with Meteor!

A: I think you might find this answer helpful.
Also I think it might be a duplicated question.


text:
Q: Android-Optimize line drawing with Canvas I am drawing a hexagonal grid on my entire phone's screen. I am drawing a hexagon by drawing six lines using Canvas. Too many lines are being drawn which makes the app unresponsive. I had to do android:HardwareAccelerated=false to atleast make it work on my Nexus 4 otherwise the app crashed with this error :
06-22 14:11:46.664: A/libc(5743): Fatal signal 6 (SIGABRT) at 0x0000166f (code=-6), thread 5743 (.nadeem.sensus4)

Although the app doesn't crash now, it takes too much time to draw the grid. This is the code of my CustomView which draws the grid :
public DrawView(Context context, Hexagon hex) {
    super(context);
    this.context = context;
    setLayerType(View.LAYER_TYPE_HARDWARE, null);
     this.hex = hex;

}

@Override
public void onDraw(Canvas canvas) {

    double xOff = Math.cos(Math.PI / 6) * hex.radius;//radius is 12 for now
    double yOff = Math.sin(Math.PI / 6) * hex.radius; // third of the hex
                                                        // height

    for (int i = 0; i < 60; ++i) {
        for (int j = 0; j < 40; ++j) {
            double xPos = j * xOff * 2;

            if (i % 2 != 0) { // if the current line is not even
                xPos += xOff; // extra offset of half the width on x axis
            }

            double yPos = i * yOff * 3;
            createHexagon(xPos, // X pos for hexagon center on the scene
                    yPos, canvas);
        }

    }

}

public void createHexagon(double x, double y, Canvas canvas) {

    paint.setColor(Color.BLACK);
    paint.setStyle(Style.STROKE);

    // paint.setStyle(Style.FILL);
    for (int i = 0; i < 6; i++) {
        double angle = 2 * Math.PI / 6 * (i + 0.5);

        double x_i = x + hex.radius * Math.cos(angle);
        double y_i = y + hex.radius * Math.sin(angle);
        if (i == 0)
            wallpath.moveTo((float) x_i, (float) y_i);
        else
            wallpath.lineTo((float) x_i, (float) y_i);
    }
    canvas.drawPath(wallpath, paint);
    canvas = null;
}

I want to ask if there's way to increase the performance or any other alternate way to achieve this grid.

A: Do your drawing in layers.  The first time you draw, draw all your hexagons to a single bitmap.  Then in all future draws, just draw that bitmap to the screen.  Then add in whatever else you need to draw on top of that.  It will save you 14000 draw line commands.
Your other good option is to move to openGL for drawing.  But there is no way you'll ever get 14K lines to draw without hardware acceleration with any real speed.

A: You can achieve the same effect by drawing straight lines and utilizing DashPathEffect to toggle a line from your background colour to your visible colour.

Where the faint lines don't belong is where that particular line segment would be turned off. Since the pattern is predictable, so is your stroke effect. Because you said in a comment that you also need the coordinates of all the vertices, run a separate loop that calculates from a starting point and propagate your vertices list from there.


text:
Q: How can I stick buttons to one another in TableLayout?
1) How can I make all buttons stick to one another so that there is no space between any 2 buttons?
2) How can I make the picture of the bomb be inside the button as backround(I have  it done wrongly)
Here is some code how I added image:
clickedButton.setPadding(0,0,0,0);
        int newWidth = clickedButton.getWidth();
        int newHeight = clickedButton.getHeight();
        Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.b64);
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, true);
        Resources resource = getResources();
        clickedButton.setBackground(new BitmapDrawable(resource, scaledBitmap));

Thank you very much!

A: To make them stick together I would try removing any possible margins, since you already tried padding. If it doesn't work I would try to work some negative values that might do what I wanted.
As for the images in the buttons, I think you could use ImageButton instead of button. Once it is clicked, it changes the background image (or not, I don't understand your game[?]).


text:
Q: How can I Export transparency and text well when using qgis2web in QGIS 3.8?

Hi, I am an amateur who is making a historical map.
As you can see in the picture, I have a problem using qgis2web.
The first picture is a normal scene output from QGIS version 3.8.
The second picture was taken from qgis2web with a Mapbox. Transparency is nice, but the text in the labels is terrible.
The third picture was taken from qgis2web with openlayers. Transparency, text in labels, it's all a mess.
I tested this site a year ago, but it was fine at the time. What should I do ? It's too hard...

A: I finally got the answer!
I set the opacity of the color of the layer.
But the opacity of the layer rendering was 100%.
When I lowered the opacity of layer rendering, not a single symbol, the qgis2web worked successfully.
People who are struggling with this, I hope it helps!

A: Open the HTML file in notepad and scroll down the code until you get to the layer you want the transparency to change. it should look something like:
function style_20YearFlood_2_0() {
        return {
            pane: 'pane_20YearFlood_2',
            opacity: 1,
            color: 'rgba(35,35,35,1.0)',
            dashArray: '',
            lineCap: 'butt',
            lineJoin: 'miter',
            weight: 1.0,
            fill: true,
            fillOpacity: 1,
            fillColor: 'rgba(255,158,23,1.0)',
            interactive: false,

20 year flood in my case was the layer I wanted to be partly transparent.Then just change the "fillOpacity:" to whatever you want. I chose 50% so it now looks like:
function style_20YearFlood_2_0() {
        return {
            pane: 'pane_20YearFlood_2',
            opacity: 0.5,
            color: 'rgba(35,35,35,1.0)',
            dashArray: '',
            lineCap: 'butt',
            lineJoin: 'miter',
            weight: 1.0,
            fill: true,
            fillOpacity: 0.5,
            fillColor: 'rgba(255,158,23,1.0)',
            interactive: false,

Save the file, and then open the html in your browser. It should now be transparent to whatever % you indicated.
Hope this helps!
Ian


text:
Q: R3 Corda Example Nodes Not Working I'm currently trying the Hello World! tutorial (part 1) and followed every step except I upgraded the Gradle distribution URL to 4.3 so the Cordapp would work. It initially opens up with 5 nodes then 2 remain: for PartyA and PartyB. The problem is the Corda interactive shell does not open and these are the items remaining on my screen. Any help is appreciated!
https://i.stack.imgur.com/au2mp.png
https://i.stack.imgur.com/uSvHk.png

A: When running the nodes with runnodes, each node creates its own terminal windows. If a node fails, it will auto-close its terminal window, preventing you from seeing the resulting message.
Instead of starting the nodes using runnodes, try navigating into one of the nodes' folders, and starting the node directly using java -jar corda.jar. If the node fails to start, the error message will appear in the terminal without closing it. This will allow you to diagnose the problem.


text:
Q: CSS issues with horizontal alignment On my website http://goo.gl/KwP9I section "PRESSE ET MEDIAS" I'd like the youtube video to be centered horizontally and next to it (with a few px space) I'd like to see a text box.
I tried various things found via google but nothing is working.
Any idea how to fix this?

A: Add this to your .youtube-player class:
.youtube-player
{
display:block;
margin-left:auto;
margin-right:auto;
}

EDIT:
To get the title next to the video, you have to float:left the video and float:right the div that wraps your
hello

Then to keep white background, after your div with hello you need to add another empty div with style clear:both


text:
Q: Rails with Aptana studio IDE configuration I am using Aptana studio IDE for my rails project. I mapped the installed location of rails path  to the IDE like we usually map the java class path to netbeans . But when i execute a command
bundle install

In windows command prompt it gives me an error.but when i run the same in IDE terminal view it perfectly works . What is the reason . Is rails designed only to work with linux and Mac or something else . Thanks in advance

A: Actually the same problem occurred to me once.when i posted the problem in aptana website all i got is rails is primarily designed to work with linux.so you should get used to work with the ide's linux terminal view.


text:
Q: Remove underline in HyperlinkButton I'm using Blend + Sketchflow Preview for Visual Studio 2012, I want to remove underlines from a HyperlinkButton.
Here is my code:
<HyperlinkButton x:Name="PoliciesTxt" Content="Policies" FontSize="18.667" Foreground="#FF003366" NavigateUri="http://google.com" FontWeight="Bold" CharacterSpacing="-1"/>

I've already tried using the TextDecorations attribute but it doesn't exist in this version of XAML.
Any ideas?

A: You must change the default style HyperlinkButton, copy the code below on your this App.xaml file.
First you must add the following namespace in App.xaml

xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
<Application.Resources>

        <Style x:Key="HyperlinkButtonStyle" x:Name="HyperlinkButtonStyle" TargetType="HyperlinkButton">
            <Setter Property="Foreground" Value="#FF73A9D8" />
            <Setter Property="Padding" Value="2,0,2,0"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="HorizontalContentAlignment" Value="Left"/>
            <Setter Property="VerticalContentAlignment" Value="Top"/>
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="HyperlinkButton">
                        <Grid Cursor="{TemplateBinding Cursor}" Background="{TemplateBinding Background}">
                            <vsm:VisualStateManager.VisualStateGroups>
                                <vsm:VisualStateGroup x:Name="CommonStates">
                                    <vsm:VisualState x:Name="Normal"/>
                                    <vsm:VisualState x:Name="MouseOver">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="UnderlineTextBlock" Storyboard.TargetProperty="Visibility" Duration="0">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name="Pressed">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="UnderlineTextBlock" Storyboard.TargetProperty="Visibility" Duration="0">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="DisabledOverlay" Storyboard.TargetProperty="Visibility" Duration="0">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </vsm:VisualState>
                                </vsm:VisualStateGroup>
                                <vsm:VisualStateGroup x:Name="FocusStates">
                                    <vsm:VisualState x:Name="Focused">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity" Duration="0" To="1"/>
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name="Unfocused"/>
                                </vsm:VisualStateGroup>
                            </vsm:VisualStateManager.VisualStateGroups>
                            <TextBlock
                          x:Name="UnderlineTextBlock"
                          Text="{TemplateBinding Content}"
                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                          Margin="{TemplateBinding Padding}"
                          TextDecorations="Underline"
                          Visibility="Collapsed"/>
                            <TextBlock Canvas.ZIndex="1"
                          x:Name="DisabledOverlay"
                          Text="{TemplateBinding Content}"
                          Foreground="#FFAAAAAA"
                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                          Margin="{TemplateBinding Padding}"
                          Visibility="Collapsed"/>
                            <ContentPresenter
                          x:Name="contentPresenter"
                          Content="{TemplateBinding Content}"
                          ContentTemplate="{TemplateBinding ContentTemplate}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          Margin="{TemplateBinding Padding}"/>
                            <Rectangle x:Name="FocusVisualElement" Stroke="#FF6DBDD1" StrokeThickness="1" Opacity="0" IsHitTestVisible="false" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

    </Application.Resources>

And you also have to apply the style to HyperlinkButton
<HyperlinkButton X:Name="Link" Content="Hola" Style="{StaticResource HyperlinkButtonStyle}"/>

A: Add the following Resrouce to your page (in my case I have just added it to the App.xaml page)
<!--Application Resources-->
<Application.Resources>
<Style x:Key="HyperlinkButtonStyle" TargetType="HyperlinkButton">
<Setter Property="Foreground" Value="White"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="FontSize" Value="16"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="HyperlinkButton">
<Border Background="Transparent">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Pressed">
<Storyboard>
<DoubleAnimation Duration="0" Storyboard.TargetName="TextElement"
Storyboard.TargetProperty="Opacity" To="0.5" />
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="TextElement"
 Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border Background="{TemplateBinding Background}" Margin="{StaticResource
PhoneHorizontalMargin}" Padding="{TemplateBinding Padding}" >
<TextBlock x:Name="TextElement" Text="{TemplateBinding Content}" HorizontalAlignment="
{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding
VerticalContentAlignment}" TextWrapping="Wrap" TextDecorations="none"/>
</Border>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>

Now all you need to do is drop a HyperlinkButton control onto the page and set the style as follows:
<HyperlinkButton Style="HyperlinkButtonStyle" />


text:
Q: Specify path to specific python executable using conda I am using python and conda within ArcGIS Pro 2.2, but am running into some problems with virtual environments. I have cloned a copy of the Arcgis Pro environment (hereafter clone). When I activate clone in the home folder for the original ArcGIS environment (C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3), the python executable is located at C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\python.exe. However, if I activate clone in any other location, the clone looks to the clone's home folder and activates that version of python (located at C:\Users\RDCERWAW\AppData\Local\conda\conda\envs\gee\python.exe). This is causing problems because import arcpy works when I run the python.exe located at .\arcgispro-py3, but not when using the python.exe located at .\gee. Even when I modify the PYTHONPATH to include the path the .\arcgispro-py3\python.exe, the other location is accessed first. I could always start the clone in the .\argispro-py3 folder, but unfortunately spyder keeps looking back at .\gee.
Does anyone know how to code conda so that it look in a specific location first?

A: If you're using sys.path.append(<preferred path>), try using sys.path.insert(0, <preferred path>) instead.
From what I've read, Python searches each path in the order it appears in sys.path.


text:
Q: Matlab motion detection using IP Webcam giving weird colors This code uses an android phone and the app "IP Webcam" (the url is provided by the app) and the phone and laptop are connected via the phone's hotspot. I'm having a little bit of problem with the video colors. They are only shades of yello/white and black. Can someone please help me out with getting a proper video ? or atleast a better one than this? code: http://pastebin.com/RPBCVrzu
I pasted it here as well for convinience:
% vidDevice = imaq.VideoDevice('winvideo', 1, 'YUY2_640x480', ...
% 'ROI', [1 1 640 480], ...
% 'ReturnedColorSpace', 'rgb');
url = 'http://192.168.43.1:8080/shot.jpg';
ss  = imread(url);
optical = vision.OpticalFlow('OutputValue', 'Horizontal and vertical components in complex form');
% maxWidth = imaqhwinfo(vidDevice,'MaxWidth');
% maxHeight = imaqhwinfo(vidDevice,'MaxHeight');
maxWidth=size(ss,2);
maxHeight=size(ss,1);
shapes = vision.ShapeInserter;
shapes.Shape = 'Lines';
shapes.BorderColor = 'Custom';
shapes.CustomBorderColor = [255 0 0];
r = 1:5:maxHeight;
c = 1:5:maxWidth;
[Y, X] = meshgrid(c,r);
 hVideoIn = vision.VideoPlayer;
 hVideoIn.Name = 'Original Video';
hVideoIn.Position = [30 100 640 480];
hVideoOut = vision.VideoPlayer;
hVideoOut.Name = 'Motion Detected Video';
hVideoOut.Position = [700 100 640 480];
nFrames = 0;
while (nFrames < Inf)
%rgbData = step(vidDevice);
rgbData=single(imread(url));
optFlow = step(optical,rgb2gray(rgbData));
optFlow_DS = optFlow(r, c);
H = imag(optFlow_DS)*50;
V = real(optFlow_DS)*50;
lines = [Y(:)'; X(:)'; Y(:)'+V(:)'; X(:)'+H(:)'];
rgb_Out = step(shapes, rgbData, lines');
step(hVideoIn, rgbData);
step(hVideoOut, rgb_Out);
nFrames = nFrames + 1;
end
release(hVideoOut);
release(hVideoIn);
release(vidDevice);

A: 'YUY2_640x480' indicates that the video is coming in in YUV format, rather than RGB.  There are two ways to fix that.  If you type imaqtool, you should see a list of all camera formats visible to MATLAB. If you see something like RGB_640x480, that should give you RGB video.  If not, then try converting the frame you are currently getting to RGB using ycbcr2rgb function.


text:
Q: Is XML to android as HTML is to websites? I answered a very general question on another website recently where I said:
application development involves
Layout, styling and logic.
In web html is for layout. Desktop (windows) XAML and android XML.
I was being simplistic about it because it was a very simple question. Somebody replied that that is not the case stating that:
HTML
<button id="button">Button</button>

var button = document.getElementById("button");

JAVA
<Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" …

Button myButton = (Button) findViewById(R.id.my_button);

Are not equivalents.
At first I thought that there were surely technical differences. However as an analogy the more I think about it is the more it holds up.
The browser reads the html and constructs the DOM. When the javascript is executed it can get a reference to elements in the DOM by requesting it.
It seems to me that the same thing is happening in the java.
The compiler or whatever reads the XML and builds out the layout. in order for the codebehind to refer to to the UI element that was created from the XML it must search for it by id.
I see the same sort of thing in swift, and XAML.
What are the practical differences between the two pieces of code?
What are the theoretical differences?
I am learning and I just want to understand if my reasoning is incorrect and how to improve it. I think they might be different in terms of their what is happening at a low level. But at a higher level they are effectively the same.


text:
Q: calculating probabilities from transition matrix without calculating left eigenvector Consider a  markov chain with transition probability matrix given by
\begin{bmatrix}0.5 &0.5 & 0 \\0&0.5&0.5\\0.33 &0.33&0.33     \end{bmatrix}
let $p^n_{ij}$ denote n-step transition probability from state i to state j then
without calculating left eigenvector show that
$1.\lim_{n\to\infty}p^n_{11}= \frac{2}{9}
$  and
$2.\lim_{n\to\infty}p^n_{13}= \frac{1}{3}
$
i only know how to solve it using left eigen vector , but i am not able to think of quicker way to solve  this .


text:
Q: How can I get all the permutations from a scanner input to array? I am trying to find all permutations of a pin number coming from a scanner. I have got this bit so far which I guess sets an array with custom digits. How can I get this code to show me all the possible options? Bare in mind that I am new to Java so simple explanations would be the best. Thanks
import java.util.Arrays;
import java.util.Scanner;

public class Methods {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] arr = new int[3];

        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter first digit: ");
        arr[0] = sc.nextInt();
        System.out.println("Please enter second digit: ");
        arr[1] = sc.nextInt();
        System.out.println("Please enter third digit: ");
        arr[2] = sc.nextInt();
        System.out.println("Please enter fourth digit: ");
        arr[3] = sc.nextInt();

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

A: Hey you can use the following code to create an array of n length and calculate the permutations:
public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("please enter the length of you array: "); // 4 if you want a 4 digit pincode
  int length = sc.nextInt();

  int[] arr = new int[length];

  for (int i = 0; i < length; i++) {
    System.out.printf("Please enter a value for digit #%s: ", i);
    arr[i] = sc.nextInt();
  }

  StringBuilder bldr = new StringBuilder();
  Arrays.stream(arr).forEach(bldr::append);
  permutation(bldr.toString());
}

public static void permutation(String str) {
    permutation("", str);
}

private static void permutation(String prefix, String str) {
  int n = str.length();
  if (n == 0)
    System.out.println(prefix);
  else {
    for (int i = 0; i < n; i++)
      permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
  }
}

Also check this question for more info about permutations.


text:
Q: Is there a limiting case for this sequence of infinite product representations for the theta function? Starting from the famous infinite product
$$
(1+z)^2(1-z^2)(1+z^3)^2(1-z^4)(1+z^5)^2(1-z^6)\cdots=1+2z+2z^4+2z^9+2z^{16}+\dots
$$
it is easy to show by induction that
$$
\prod_{k\geqslant1}\left((1-z^k)(1-z^{2k-1})^N(1+z^{2k})^{N+1}(1+z^{2k-1})^{N+3}\right)=\sum_{n=-\infty}^{+\infty}z^{n^2}
$$
for any $N\geqslant0$.
Can one give sense to passing to the limit w. r. t. $N\to\infty$ and if yes what does one obtain?
A by-question: it seems that this also holds for all negative $N$ but I somehow cannot prove it, is it true?

A: As it frequently happens with me after seeing it accurately formulated and typed after a while I saw a solution. Unfortunately it is disappointingly simple in that no limiting process of any kind is actually needed.
The point is that there is another very well known infinite product identity
$$
P(t):=\prod_{k\geqslant 1}\left((1-t^{2k-1})(1+t^k)\right)=1;
$$
and the lhs in the needed equality is
$$
P(z^2)^N\prod_{k\geqslant1}\left((1-z^k)(1+z^{2k})(1+z^{2k-1})^3\right),
$$
so $P(z^2)^N$ is $1$ while the terms in the product can be easily regrouped to get
$$
\prod_{k\geqslant1}\left((1-z^{2k-1})(1-z^{2k})(1+z^{2k})(1+z^{2k-1})^3\right)
=\prod_{k\geqslant1}\left((1-z^{4k-2})(1-z^{4k})(1+z^{2k-1})^2\right)
=\prod_{k\geqslant1}\left((1-z^{2k})(1+z^{2k-1})^2\right)
$$
which by the very first equality the question starts with is $\sum_{n\in\mathbb Z}z^{n^2}$.
Thus indeed this works for any $N$ (not just any integer but any number at all).


text:
Q: Can not connect with imap_open but openssl s_client works So after 2 days of trying all the solutions I could find that seemed to apply,  I am still scratching my head.  There must be something I am missing.
I am trying to connect to a postfix/dovecot mail server with php imap_open() within SuiteCRM (it only uses imap, pop3 is not an option).
I can connect from the command line with either openssl s_client -connect mail.mydomain.com:143 -starttls imap or openssl s_client -connect mail.mydomain.com:993. I can issue commands, list the inbox, and logout.  If I try to use php imap_open I get various errors depending on the parameters passed.
Question: why can't a connection be made with imap_open?
It seems to be a php issue. I have checked phpinfo on the mail server and it has imap with ssl support.  The mail server is running on a ubuntu 14.04 LEMP config. PHP Version 5.5.9-1ubuntu4.9. The ssl cert is a wildcard cert.
imap
IMAP c-Client Version   2007f
SSL Support         enabled
Kerberos Support    enabled

openssl
OpenSSL support     enabled
OpenSSL Library Version OpenSSL 1.0.1f 6 Jan 2014
OpenSSL Header Version  OpenSSL 1.0.1f 6 Jan 2014

Here are the postfix and dovecot configs:
postconf -n:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = yes
config_directory = /etc/postfix
inet_protocols = ipv4
mailbox_size_limit = 0
mydestination = localhost
myhostname = mail.livechat4sales.com
mynetworks = 127.0.0.0/8
myorigin = $myhostname
readme_directory = no
recipient_delimiter = +
smtp_tls_mandatory_protocols = !SSLv2,!SSLv3
smtp_tls_note_starttls_offer = yes
smtp_tls_protocols = !SSLv2,!SSLv3
smtp_tls_security_level = may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
smtpd_recipient_restrictions = permit_sasl_authenticated permit_mynetworks reject_unauth_destination
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain =
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_CAfile = /etc/nginx/ssl/geotrust.stapling.crt
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/nginx/ssl/mydomain.wild.crt
smtpd_tls_ciphers = high
smtpd_tls_key_file = /etc/nginx/ssl/mydomain.wild.key
smtpd_tls_loglevel = 4
smtpd_tls_mandatory_protocols = !SSLv2 !SSLv3
smtpd_tls_protocols = !SSLv2,!SSLv3
smtpd_tls_received_header = yes
smtpd_tls_security_level = may
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
virtual_alias_maps = hash:/etc/postfix/virtual
virtual_gid_maps = static:5000
virtual_mailbox_base = /var/mail/vhosts
virtual_mailbox_domains = mydomain.com
virtual_mailbox_maps = hash:/etc/postfix/vmailbox
virtual_minimum_uid = 100
virtual_uid_maps = static:5000

dovecot:
auth_mechanisms = plain login
auth_verbose = yes
login_log_format_elements = user=<%u> method=%m rip=%r lip=%l mpid=%e %c %k session=<%{session}>
mail_location = maildir:~mail/vhosts/%d/%n/
namespace inbox {
  inbox = yes
  location =
  mailbox Drafts {
    special_use = \Drafts
  }
  mailbox Junk {
    special_use = \Junk
  }
  mailbox Sent {
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox Trash {
    special_use = \Trash
  }
  prefix =
}
passdb {
  args = scheme=SHA512-CRYPT username_format=%u /etc/dovecot/users
  driver = passwd-file
}
protocols = " imap lmtp pop3"
service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = postfix
    mode = 0660
    user = postfix
  }
}
service imap-login {
  inet_listener imap {
    port = 143
  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }
}
service pop3-login {
  inet_listener pop3s {
    port = 995
    ssl = yes
  }
}
ssl_cert = </etc/nginx/ssl/mydomain.wild.crt
ssl_cipher_list = HIGH:MEDIUM:+TLSv1:!SSLv2:+SSLv3
ssl_client_ca_dir = /etc/nginx/ssl/
ssl_client_ca_file = geotrust.stapling.crt
ssl_key = </etc/nginx/ssl/mydomain.wild.key
ssl_prefer_server_ciphers = yes
ssl_protocols = !SSLv2 !SSLv3
userdb {
  args = username_format=%u /etc/dovecot/users
  default_fields = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n
  driver = passwd-file
}

Results from testing imap_open:
{mail.mydomain.com:993/service=imap/ssl/tls/validate-cert/secure}INBOX: invalid remote specification
{mail.mydomain.com:993/service=imap/ssl/tls/validate-cert}INBOX: invalid remote specification
{mail.mydomain.com:993/service=imap/ssl/validate-cert/secure}INBOX: [CLOSED] IMAP connection broken (server response)
{mail.mydomain.com:993/service=imap/ssl/novalidate-cert/secure}INBOX: [CLOSED] IMAP connection broken (server response)

This is the only call that returns data, but I think the password is being passed in plain text.  143 was only opened for testing; 993 is preferred.
 {mail.mydomain.com:143/service=imap/tls}INBOX


text:
Q: C# Transparent GUI Hey all. i was wondering how would i make a GUI that is "transparent" in C#. Now im not talking about transparencykey etc.
I want to make a window that uses vistas aero theme but instead of a control in the form i just want it to show more of that seethru aero look. And also i want to remove all buttons and icons and text from the window. How would i do this?
EDIT... I found a PERFECT example of what i want to create. Load up the windows mobility center on vista. How can i create something like that but without the boxes in it.

A: How to Glass into your Client Area
Here is the API I used when I did this for our Windows app a few years ago.
Check out the method ExtendGlassIntoClientArea(Form form, int leftMargin, int topMargin, int rightMargin, int bottomMargin)
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace UserInterface
{
    public enum TextStyle
    {
        Normal,
        Glowing
    }

    public static class Glass
    {
        [DllImport("dwmapi.dll")]
        private static extern void DwmIsCompositionEnabled(ref bool pfEnabled);
        [DllImport("dwmapi.dll")]
        private static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMargins);
        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        private static extern IntPtr CreateCompatibleDC(IntPtr hDC);
        [DllImport("gdi32.dll", ExactSpelling = true)]
        private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);
        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        private static extern bool DeleteDC(IntPtr hdc);
        [DllImport("gdi32.dll")]
        private static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);
        [DllImport("UxTheme.dll", CharSet = CharSet.Unicode)]
        private static extern int DrawThemeTextEx(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, string text, int iCharCount, int dwFlags, ref RECT pRect, ref DTTOPTS pOptions);
        [DllImport("gdi32.dll")]
        static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref BITMAPINFO pbmi, uint iUsage, out IntPtr ppvBits, IntPtr hSection, uint dwOffset);

        [StructLayout(LayoutKind.Sequential)]
        private struct DTTOPTS
        {
            public int dwSize;
            public int dwFlags;
            public int crText;
            public int crBorder;
            public int crShadow;
            public int iTextShadowType;
            public POINT ptShadowOffset;
            public int iBorderSize;
            public int iFontPropId;
            public int iColorPropId;
            public int iStateId;
            public bool fApplyOverlay;
            public int iGlowSize;
            public int pfnDrawTextCallback;
            public IntPtr lParam;
        }

        private const int DTT_COMPOSITED = 8192;
        private const int DTT_GLOWSIZE = 2048;
        private const int DTT_TEXTCOLOR = 1;

        [StructLayout(LayoutKind.Sequential)]
        private struct POINT
        {
            public POINT(int x, int y)
            {
                this.x = x;
                this.y = y;
            }

            public int x;
            public int y;
        }

        [StructLayout(LayoutKind.Sequential)]
        private class BITMAPINFO
        {
            public int biSize;
            public int biWidth;
            public int biHeight;
            public short biPlanes;
            public short biBitCount;
            public int biCompression;
            public int biSizeImage;
            public int biXPelsPerMeter;
            public int biYPelsPerMeter;
            public int biClrUsed;
            public int biClrImportant;
            public byte bmiColors_rgbBlue;
            public byte bmiColors_rgbGreen;
            public byte bmiColors_rgbRed;
            public byte bmiColors_rgbReserved;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct MARGINS
        {
            public int left, right, top, bottom;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;

            public RECT(int left, int top, int right, int bottom)
            {
                Left = left;
                Top = top;
                Right = right;
                Bottom = bottom;
            }

            public RECT(Rectangle rectangle)
            {
                Left = rectangle.X;
                Top = rectangle.Y;
                Right = rectangle.Right;
                Bottom = rectangle.Bottom;
            }

            public Rectangle ToRectangle()
            {
                return new Rectangle(Left, Top, Right - Left, Bottom - Top);
            }

            public override string ToString()
            {
                return "Left: " + Left + ", " + "Top: " + Top + ", Right: " + Right + ", Bottom: " + Bottom;
            }
        }
        public static bool IsCompositionEnabled
        {
            get
            {
                if (Environment.OSVersion.Version.Major < 6)
                    return false;

                bool compositionEnabled = false;
                DwmIsCompositionEnabled(ref compositionEnabled);
                return compositionEnabled;
            }
        }

        public static void ExtendGlassIntoClientArea(Form form, int leftMargin, int topMargin, int rightMargin, int bottomMargin)
        {
            MARGINS m = new MARGINS();
            m.left = leftMargin;
            m.right = rightMargin;
            m.top = topMargin;
            m.bottom = bottomMargin;

            DwmExtendFrameIntoClientArea(form.Handle, ref m);
        }

        public static void DrawText(Graphics graphics, string text, Font font, Rectangle bounds, Color color, TextFormatFlags flags)
        {
            DrawText(graphics, text, font, bounds, color, flags, TextStyle.Normal);
        }

        public static void DrawText(Graphics graphics, string text, Font font, Rectangle bounds, Color color, TextFormatFlags flags, TextStyle textStyle)
        {
            IntPtr primaryHdc = graphics.GetHdc();

            // Create a memory DC so we can work offscreen
            IntPtr memoryHdc = CreateCompatibleDC(primaryHdc);

            // Create a device-independent bitmap and select it into our DC
            BITMAPINFO info = new BITMAPINFO();
            info.biSize = Marshal.SizeOf(info);
            info.biWidth = bounds.Width;
            info.biHeight = -bounds.Height;
            info.biPlanes = 1;
            info.biBitCount = 32;
            info.biCompression = 0; // BI_RGB
            int ppvBits;
            IntPtr dib = CreateDIBSection(primaryHdc, ref info, 0, out ppvBits, IntPtr.Zero, 0);
            SelectObject(memoryHdc, dib);

            // Create and select font
            IntPtr fontHandle = font.ToHfont();
            SelectObject(memoryHdc, fontHandle);

            // Draw glowing text
            System.Windows.Forms.VisualStyles.VisualStyleRenderer renderer = new System.Windows.Forms.VisualStyles.VisualStyleRenderer(System.Windows.Forms.VisualStyles.VisualStyleElement.Window.Caption.Active);
            DTTOPTS dttOpts = new DTTOPTS();
            dttOpts.dwSize = Marshal.SizeOf(typeof(DTTOPTS));

            if (textStyle == TextStyle.Glowing)
            {
                dttOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE | DTT_TEXTCOLOR;
            }
            else
            {
                dttOpts.dwFlags = DTT_COMPOSITED | DTT_TEXTCOLOR;
            }
            dttOpts.crText = ColorTranslator.ToWin32(color);
            dttOpts.iGlowSize = 8; // This is about the size Microsoft Word 2007 uses
            RECT textBounds = new RECT(0, 0, bounds.Right - bounds.Left, bounds.Bottom - bounds.Top);
            DrawThemeTextEx(renderer.Handle, memoryHdc, 0, 0, text, -1, (int)flags, ref textBounds, ref dttOpts);

            // Copy to foreground
            const int SRCCOPY = 0x00CC0020;
            BitBlt(primaryHdc, bounds.Left, bounds.Top, bounds.Width, bounds.Height, memoryHdc, 0, 0, SRCCOPY);

            // Clean up
            DeleteObject(fontHandle);
            DeleteObject(dib);
            DeleteDC(memoryHdc);

            graphics.ReleaseHdc(primaryHdc);
        }

    }
}

A: if WPF, it's a matter of turning transparency on, and setting the right values for the background (additionally, WPF supports AERO natively for borders and what-not).
For traditional winforms... things start getting hard.

A: plus there's always Form.Opacity property of the windows Form.

A: Have you tried to check out this which was referred  in another question?


text:
Q: Using UART's TX & RX for Separate Functinality I am using PIC18F4520.
The project  requirement is to interface GSM module with uC as well as receive commands from PC via serial port.
to achieve this I have connected Microcontroller- TX to GSM module- RX, as GSM module is used just for sending SMS. It is working OK with this connection.(this connection is on TTL level.)
but i want to receive command from PC , so I have connected PC- TX to uC -RX (this connection is through MAX232).
when i connect PC-TX to uC-RX the serial terminal s/w (PC) shows garbage values on RX, and uC also receives garbage values (As I am not sending anything but still Receive interrupt routines gets called continuously ) . there is no issue in program.
but meanwhile the GSM module working fine.
Do i need to terminate the TX line?
I am using just 2 wire serial cable for connection to PC.
Thank You

A: What you want to do can be done, but there are limitations
1) A uart runs at one speed, so you will have to run RX and TX at the same speed.
2) Make sure the logic levels are compatible.
3) Make sure that both the PC and the GSM have the same uart setup, ie stop bits partity bits ect.
Trouble shoot them one at a time. Note the settings and when you get them both working independently then combine them. I would make life easy on yourself and put them on separate uarts.

A: THanks all of you for your help.
The issue is not of baud rate.
The problem is solved by connecting 10k pullup on RX of PIC.
Sorry for late reply


text:
Q: Why am I getting a syntax error when using the Prepare() method? The problem goes away without the 'addCustCmd.Prepare();' I am trying to add customers to a MySQL database and then populate a DataGridView with the data. Without the addCustCmd.Prepare(); method everything works fine. The customer is added to the database and my DGV is populated with new data. But I would like to add security to these inputs and prevent SQL injection, thus the Prepare(); method.
public static void addCust(string cCustomerName, string cAddress, string cAddress2, int cPhone, int cPostalCode, string cCity, string cCountry)
        {
            MySqlConnection addCustConn = new MySqlConnection(connString);
            MySqlCommand addCustCmd = new MySqlCommand("INSERT INTO country VALUES " +
                "(NULL, @countryName, CURRENT_TIMESTAMP," +
                "@user, CURRENT_TIMESTAMP, @user);" +

                "INSERT INTO city " +
                "VALUES(NULL, @city, LAST_INSERT_ID(), CURRENT_TIMESTAMP, @user, CURRENT_TIMESTAMP, " +
                "@user);" +

                "INSERT INTO address " +
                "VALUES(NULL, @address, @address2, LAST_INSERT_ID(), @postalCode, @phone, CURRENT_TIMESTAMP, @user," +
                "CURRENT_TIMESTAMP, @user);" +

                "INSERT INTO customer " +
                "VALUES(NULL, @customerName, LAST_INSERT_ID(), active, CURRENT_TIMESTAMP, @user," +
                "CURRENT_TIMESTAMP, @user);", addCustConn);
            addCustConn.Open();
            addCustCmd.Parameters.AddWithValue("@countryName", cCountry);
            addCustCmd.Parameters.AddWithValue("@city", cCity);
            addCustCmd.Parameters.AddWithValue("@address", cAddress);
            addCustCmd.Parameters.AddWithValue("@address2", cAddress2);
            addCustCmd.Parameters.AddWithValue("@postalCode", cPostalCode);
            addCustCmd.Parameters.AddWithValue("@phone", cPhone);
            addCustCmd.Parameters.AddWithValue("@customerName", cCustomerName);
            addCustCmd.Parameters.AddWithValue("@user", LoginForm.currentUser);

            addCustCmd.Prepare(); //Commenting this out allows the program to run no problems
            addCustCmd.ExecuteNonQuery();

            addCustConn.Close();
        }//end addCust

This is the error that pops up when I try to run it:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO city VALUES(NULL, ?, LAST_INSERT_ID(), CURRENT_TIMESTAMP, ?, CURRENT' at line 1"

A: Each insert operation has to be a separate command to use prepared statements.

SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by ; characters).

Documentation source


text:
Q: how to override mapred.local.dir in mapred-site.xml? I do not have write access to the directory specified by mapred.local.dir in mapred-site.xml (and no write access to mapred-site.xml either) Is there a way I can override this property per session basis for my Hive jobs ?

A: You can try setting it in the Hive session by executing the following query:
set mapred.local.dir='some dir';

This should work. The other option is to change the mapred-site.xml which Hive refers to.
Make sure the configuration is not marked as final. In which case it cannot be overridden.


text:
Q: Intuition for Euler's Partition Theorem Euler's Partition Theorem states the following:

Every number has as many integer partitions into odd parts as into distinct parts.

I played around with small examples (I wrote out the partitions into odd/distinct parts for integers 1 through 10), but can't develop an intuition for why this is true. Any help?

A: You can set up a one-to-one correspondence (aka a bijection) between the partitions of $N$ into odd parts and the partitions of $N$ into distinct parts. I will just illustrate with an example; I leave it to you to formalize it and verify that it works.
Here is one way to partition the number $N=863$ into odd parts: partition it into $22$ ones, $49$ threes, $48$ fives, $25$ sevens, and $31$ nines. From this we derive a partition of $863$ into distinct parts, as follows:
$863$
$=22\cdot1+49\cdot3+48\cdot5+25\cdot7+31\cdot9$
$=(16+4+2)\cdot1+(32+16+1)\cdot3+(32+16)\cdot5+(16+8+1)\cdot7+(16+8+4+2+1)\cdot9$
$=16\cdot1+4\cdot1+2\cdot1+32\cdot3+16\cdot3+1\cdot3+32\cdot5+16\cdot5+16\cdot7+8\cdot7+1\cdot7+16\cdot9+8\cdot9+4\cdot9+2\cdot9+1\cdot9$
$=16+4+2+96+48+3+160+80+112+56+7+144+72+36+18+9$
$=160+144+112+96+80+72+56+48+36+18+16+9+7+4+3+2$.
If we apply this procedure to the partitions of $7$ we get the following correspondence:
$7\ \to\ 7$
$5+1+1\ \to\ 5+2$
$3+3+1\ \to\ 6+1$
$3+1+1+1+1\ \to\ 4+3$
$1+1+1+1+1+1+1\ \to\ 4+2+1$
The relevant arithmetical facts here are unique factorization (every number factors uniquely into a power of $2$ and an odd number) and base $2$ notation (every number is uniquely expressible as a sum of distinct powers of $2$).


text:
Q: How to move .gitignore file from one branch to another from commandline I have created and pasted a .gitignore file to my master branch, and I want to move it to the hometask_1 branch with the windows 10 command line.
I have used the commands below:
git checkout master
git checkout hometask_1 -- .gitignore

After the above commands I am getting the following error:
error: pathspec '.gitignore' did not match any file(s) known to git

A: From this answer, you can move a file from one branch to another with: git checkout otherbranch myfile.txt from the branch where you want the file to end up.
In your case, from the hometask_1  branch, you can run: git checkout master .gitignore.


text:
Q: jQuery not appending some elements while creating them I would like to ask if anybody sees what is going on. I have plenty experience with jQuery append elements while creating them, I made this several times but now Im struggling since 2 hours without being able to find my mistake, perhaps you can help me.
I'm trying to append the following as stated below:
var contactoHolder = $('
', {'class':"contactoUnexpanded",'id':indexed});
contactoHolder.append(infoArray[0]);
$('
', {'class':"editDelete", 'id':indexed+'editDelete'}).appendTo(contactoHolder);
$('', {'class':"edit",'id':indexed+'_edit'}).appendTo('#'+indexed+'editDelete');
$('#'+indexed+'_edit').html('edit');
$('', {'class':"delete",'id':indexed+'_delete'}).appendTo('#' + indexed + 'editDelete');
$('#' + indexed + 'delete').html('delete');
$('', {'class':"contenidoDelContacto", 'id':indexed + 'Content'}).appendTo(contactoHolder);
$('#' + indexed + 'Content').html('
' + infoArray[1] + '
' + infoArray[2] + '
' + infoArray[3] + '
' + infoArray[4]);
$('#content').append(contactoHolder);

The only elementswhen I render that get definitively in the DOM are

  Santiago

I don't know why is not appending the rest of the elements as it should.
Thank you for your help.

A: Your problems start here:
$('', {'class':"delete",'id':indexed+'_delete'}).appendTo('#' + indexed + 'editDelete');

Since you haven't appended any of your elements to the DOM yet, ('#' + indexed + 'editDelete') doesn't match anything. The selector engine only looks at elements currently in the DOM, not those in JavaScript variables.
You can solve this by appending the contactoHolder right away: http://jsfiddle.net/mblase75/ptpgJ/
var contactoHolder = $('
', {'class':"contactoUnexpanded",'id':indexed});
$('#content').append(contactoHolder);
// now the rest of your code

Alternatively, try assigning each new jQuery element a variable name, and reference those variables instead when appending or modifying them. This should be more efficient, but the difference will probably be imperceptible to your users unless you're doing this hundreds or thousands of times in a row:
var div1 = $('
', {'class':"editDelete", 'id':indexed+'editDelete'}).appendTo(contactoHolder);
// ...
$('', {'class':"delete",'id':indexed+'_delete'}).appendTo(div1);

All together: http://jsfiddle.net/mblase75/B33wW/
var contactoHolder = $('
', {
    'class': "contactoUnexpanded",
    'id': indexed
});
contactoHolder.append(infoArray[0]);
var div1 = $('
', {
    'class': "editDelete",
    'id': indexed + 'editDelete'
}).appendTo(contactoHolder);

var span1 = $('', {
    'class': "edit",
    'id': indexed + '_edit'
}).appendTo(div1);
$(span1).html('edit');

var span2 = $('', {
    'class': "delete",
    'id': indexed + '_delete'
}).appendTo(div1);
$(span2).html('delete');

var span3 = $('', {
    'class': "contenidoDelContacto",
    'id': indexed + 'Content'
}).appendTo(contactoHolder);
$(span3).html('
' + infoArray[1] + '
' + infoArray[2] + '
' + infoArray[3] + '
' + infoArray[4]);
$('#content').append(contactoHolder);


text:
Q: Using Scaffold-DbContext with user secrets I'm trying to reverse engineer a db context using EF Core 3.0 as suggested in this document. It suggests that you can put your connection string into a user secret, and then run:
dotnet ef dbcontext scaffold Name=my_key Microsoft.EntityFrameworkCore.SqlServer

I've tried initialising the user secrets as follows:
dotnet user-secrets init
dotnet user-secrets set ConnectionStrings.my_key "Data Source=........... etc."

and then running the above command, I also also tried this (as I was using the PMC tools)
Scaffold-DbContext Name=my_key Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

but both give me the same error:

A named connection string was used, but the name 'my_key' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application

A: The documentation is wrong. You need to include the "ConnectionStrings" prefix in the command as follows:
Scaffold-DbContext Name=ConnectionStrings.my_key Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models


text:
Q: Output of layer consisting pixel value 1 and 0 totally black? I am computing the NDWI of an area , and I used the code below to generate a result of pixel value 1 and 0 only. Pixel value 1 will be displayed in blue means the pixel's NDWI value once had exceeded 0.3 and pixel value 0 will be displayed in white meaning the pixel's NDWI value has never reach 0.3 or more
var gte3 = ndwi.map(function(image){
  return image.gte(0.3);
});
var ndwigt3 = gte3.max();
var ndwigte3Viz = {min: 0, max: 1, palette: ['white', 'blue']};
Map.addLayer(ndwiget3, ndwigte3Viz , 'ndwigte3', false);
I could see the white and blue pixels when i open the layer in code editor, but once i output it with the following code, it turns out to be a total black image
Export.image.toDrive({
  image: ndwigte3,
  description: 'ndwigte3',
  region: Border,
  scale: 30,
  maxPixels:1e13,
  skipEmptyTiles: false
  });

A: The issue is that the visualisation parameters that you specify for the Map.addLayer() are only used for that function.  They haven't in any way modified the original raster.  When you export it, the value goes from 0-1 however, the data is an 8Bit unsigned integer.  Which means if you open it in a generic image viewer, it will give grayscale values (from 0-255) to all your pixels of black.  (all are practically 0)
If you open the tiff in QGIS, it will adapt the vizalization so that the min is black and the max is white by default.  (0-1).
If you modify your code as follows:
// multiply image by 255 making all 1 values to 255
var ndwigtVIZ = ndwigt3.multiply(255)

// Export Image
Export.image.toDrive({
  image: ndwigtVIZ,
  description: 'ndwigtVIZ',
  region: Border,
  scale: 30,
  maxPixels:1e13,
  skipEmptyTiles: false
  });

You should be able to see it fine. (black for non water and white for water)
I am sorry I am unable to help on the colorisation, as I don't know how to do that bit.


text:
Q: scanf asking for two values instead of one When I compile this code, it leads to scanf asking for a value twice when I pick choice A. What am I missing here?
This isn't the first time this is encountered, so I'm suspecting I'm failing to grasp something rather fundamental with scanf.
#include <stdio.h>
#include <stdlib.h>

int main()
{

char choice;
printf("1. 'enter 'A' for this choice\n");
printf("2. 'enter 'B' for this choice\n");
printf("3. 'enter 'C' for this choice\n");

scanf("%c", &choice);

switch (choice)
{
case 'A':
    {
        int a =0;
        printf("you've chosen menu A\n");
        printf("enter a number\n");
        scanf("%d\n", &a);
        printf("%d\n", a);
    }
break;
case 'B':
printf("you've chosen B\n");
break;
case 'C':
printf("you've chosen C\n");
break;
default:
printf("your choice is invalid\n!");
break;
}

return 0;

}

A: scanf("%d\n", &a); should be scanf("%d", &a);
Also read Related question.
In former case after reading an integer and storing into a, scanf's argument string is not exhausted. Looking at \n, scanf would consume all the whitespaces (newline, tab, spaced etc) it sees (And will remain blocked) until it encounters a non-whitespace character. On encountering a non-whitespace character scanf would return.
Learning: Don't use space, newline etc as trailing character in scanf. If the space character is in the beginning of argument string, scanf may still skip any number of white space characters including zero characters. But when whitespace is a trailing characters, it would eat your new line character also unless you type a non-whitespace character and hit return key.

A: Simply remove the newline character from scanf("%d\n", &a); and it will not ask to enter a value twice

A: scanf("%d", &a);

Remove a newline character while scanning

A: // the trailing '\n' in the scanf format string
// is what is causing the dual inputs

// the returned value from I/O statements (I.E. scanf)
// needs to be checked to assure operation was successful

#include <stdio.h>
#include <stdlib.h>

int main()
{

    char choice;
    printf("1. 'enter 'A' for this choice\n");
    printf("2. 'enter 'B' for this choice\n");
    printf("3. 'enter 'C' for this choice\n");

    // note
    //    leading ' ' in format string to consume leading white space
    //    and no trailing '\n'
    if( 1 != scanf(" %c", &choice) )
    { // then, scanf failed
        // handle error condition
        perror("scanf failed for choice");
        exit(EXIT_FAILURE);
    }

    // implied else, scanf successful

    switch (choice)
    {
        case 'A':
        { // braces needed due to variable declaration
            int a = 0; // corrected ':' to ';'
            printf("you've chosen menu A\n");
            printf("enter a number\n");

            // note
            //    leading ' ' in format string to consume leading white space
            //    and no trailing '\n'
            if( 1 != scanf(" %d", &a) )
            { // then scanf failed
                // handle error condition
                perror("scanf failed for number");
                exit(EXIT_FAILURE);
            }
            // implied else, scanf successful
            printf("%d\n", a);
        }
        break;

        case 'B':
            printf("you've chosen B\n");
        break;

        case 'C':
            printf("you've chosen C\n");
        break;

        default:
            printf("your choice is invalid\n!");
        break;
    } // end switch

    return 0;

} // end function: main


text:
Q: URl redirection issue in Django 2 I'm new to Django and trying to build a web app with the following structure. I need your help to understand what Im doing wrong.

The flow of the application is shadesProductUploader.urls will forward '' to authSection for login and after a successful login user should be redirected to mainSection 'home/'.
Urls.py files are
shadesProductUploader.urls
 from django.contrib import admin
 from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('authSection.urls')),

]

authSection.urls
from django.contrib import admin
from django.urls import path, include
from . import views

app_name = 'authSection'

urlpatterns = [
path('', views.login_view, name='login'),
]

mainSection.urls
from django.contrib import admin
from django.urls import path,include
from . import views

app_name = 'mainSection'

urlpatterns = [
path('home/', views.home),
]

and the view.py in authSection
def login_view(request):
next = request.GET.get('next')
form = userLoginForm(request.POST or None)
if form.is_valid():
    username = form.cleaned_data.get('username')
    password = form.cleaned_data.get('password')
    user = authenticate(username=username,password=password)
    login(request,user)
    if next:
        return redirect(next)
    context={'user':user}
    return redirect('home/')
return render(request, 'login.html', {'form': form})

after a successful login I get this error.

What Am I missing? Not sure why I see a Url of  home/ home/

A: Update shadesProductUploader's main section url like this:
urlpatterns = [
        path('',include('mainSection.urls')),
        ... # other urls
    ]

And change in mainSection urls like this:
urlpatterns = [
    path('home/', views.home, name="home"),  # <-- added name here
]

And in view, use it like this:
if next:
    return redirect(next)
context={'user':user}
return redirect(reverse('home'))

Here, we have named our url as home. And we got the url using reverse.


text:
Q: How to provide conditional visibility of a child-item in a RecyclerView in the Adapter class? I am working on a project which implements 2 views for each screen, a normal user view, and an admin view. The admin view is presented with a little more privileges than a normal user like deleting certain posts or the users themselves from the database.
Therefore, I set the visibility of those functional buttons to be GONE if the admin privilege is true (which I pass as a parameter value when initializing the adapter). But what I am struggling with, is where do I set the visibility, in the onCreateViewHolder method or onBindViewHolder method? I have right now set it in the onCreateViewHolder method because I had read on some Stackoverflow answer only that we should avoid heavy operations in onBindViewHolder method. But I would like to know a definitive answer.
Here are the code samples for reference:
The adapter class declaration:
class NoticesAdapter(options: FirestoreRecyclerOptions<NoticeModel>,
                    private val isAdmin: Boolean,
                    private val listener: INoticeListAdapter):
        FirestoreRecyclerAdapter<NoticeModel, NoticesAdapter.NoticeViewHolder>(options)

onCreateViewHolder meothod:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoticeViewHolder {

        val noticeListView = LayoutInflater.from(parent.context).inflate(R.layout.item_notice, parent, false)
        val noticeListViewHolder = NoticeViewHolder(noticeListView)

        if (!isAdmin)
        {
            noticeListViewHolder.deleteNoticeBtn.visibility = GONE
        }

        // On clicking the delete button on a notice by the admin
        noticeListViewHolder.deleteNoticeBtn.setOnClickListener {
            val noticeSnapshot = snapshots.getSnapshot(noticeListViewHolder.adapterPosition)
            listener.deleteNoticeBtnListener(noticeSnapshot)
        }

        return noticeListViewHolder
    }

The onBindViewHolder method:
override fun onBindViewHolder(holder: NoticeViewHolder, position: Int, model: NoticeModel) {
        holder.noticeText.text = model.noticeText
        holder.noticeAuthor.text = MyUtils.getUserName()
        holder.noticePostDate.text = model.datePosted
        holder.noticePostTime.text = model.timePosted

    }

A: A RecyclerView.Adapter what it does is to: recycle items (as the name implies). The list doesn't have one view per item on the data source at the same time. The adapter makes sure to have enough views in memory in order to always render the list smoothly. When a row is leaving the field of view by scrolling, then that view is recycled to be re-used in the next entering view to the screen size.
This means that onCreateViewHolder is called only when a view is needed to be created. Generally at the start of the adapter, also when the user is scrolling fast or erratically and when the data set changes and is needed.
The other method onBindViewHolder is called every time the data on the row needs to be updated in order for the view to get updated. This is called every time a row is entering the view field of the screen.
So the textbook answer is: do it on onBindViewHodlder, because if the attribute isAdmin changes then that row will need to be updated. By doing it on onCreateViewHolder that would only happen one time when the row is created.
But, your isAdmin is a val on the constructor that can not be reassigned, so this means that when the rows are created the button will be hidden or visible forever. And this doesn't matter because your structure is to determine if is admin from another source that is separated from which the row data structure is derived from.
If in some case you want to:

*

*make it more flexible and easier to maintain in the future

*or maybe you know there is going to be a case where there is gonna be a list with admins and not admins rows

Then the solution is to move the isAdming attribute to your NoticeModel, that would imply changing your data structure.
If you want to verify anything sai above, get a data source with plenty of items and then add 2 logs, one on onCreateViewHolder and one in onBindViewHolder. You will see how on create is called only sometimes but on bind is called always.


text:
Q: How to add custom data validator directly without specialized directive? In short I would like to have a custom data validator without writing entire directive for it.
Here is my case -- I have editor component/directive with several input fields. Let's say (this is content of the template of editor directive):
<input ng-model="phrase"></input>
<input ng-model="translation"></input>

The "classic" approach would be to write:
<input ng-model="translation" validator-1 validator-2 validator-3... ></input>

and add appropriate directives for those validators. But I don't like this approach, because those validators are not general purpose, they are tailored for this template only, and adding them suggests there is some kind of composition (that it would be almost OK to change something), and it is not true -- there is atomic entity "input + validators" = "translation".
Thus I would like to add custom validator directly into the code of my editor directive.
How to do it?
So far I was experimenting with finding out what is inside ngModel of my editor directive, but since the editor directive does not have model for entire editor, just for distinct fields (as shown above) I failed at requiring ngModel for my editor.


text:
Q: ASP.NET MVC 5: Custom Login URL based on localized route parameter In ASP.NET MVC 5 you specify the login path URL in method ConfigureAuth(...) which is called from Application_Start():
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login")
});

I need someway to specify the login path according to a localized route parameter.
One way I have in my mind is to redirect the user in Application_AuthenticateRequest() to the desired login page in case Request.IsAuthenticated is false. But I am not really sure whether this is a good idea or not.

A: Using OWIN, you can't assume the Application_AuthenticateRequest IIS programming model. You should assume OWIN's programming model.
Anyway, on the CookieAuthenticationOptions, there's a Provider property. On this there's a ApplyRedirect event you ca handle. In there you could alter the redirect URL.


text:
Q: My UIDatePicker Is Not Coming Propper format here is my code.
extension ProfileViewController {
    private func openDatePicker() {
        let datePicker = UIDatePicker()
        datePicker.datePickerMode = .date
        ageTextFieldOutlet.inputView = datePicker
        let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44))
        let cancleButton = UIBarButtonItem(title: "Cancle", style: .plain, target: self, action: #selector(cancleButtonClicked))
        let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonClicked))
        let flexibleBtn = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        toolBar.setItems([cancleButton, flexibleBtn, doneButton], animated: true)
        ageTextFieldOutlet.inputAccessoryView = toolBar
    }

    @objc func cancleButtonClicked() {
        ageTextFieldOutlet.resignFirstResponder()
    }
    @objc func doneButtonClicked() {
        if let datePiker = ageTextFieldOutlet.inputView as? UIDatePicker {
            print(datePiker.date)
        }
    }
}
// MARK: - UITextFieldDelegate For Age
extension ProfileViewController: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.openDatePicker()
    }
}

And Image For Better Understanding.
I Get this type of selector when I run my project

and I want this type of date selector

A: In newer versions of iOS (13.4+) you need to specify a style if you want the wheel date picker, by default it is automatic, and it usually defaults to compact, in this case when you create a new UIDatePicker you can do this:
        let datePicker = UIDatePicker()
        datePicker.datePickerMode = .date
        datePicker.preferredDatePickerStyle = .wheels
        ageTextFieldOutlet.inputView = datePicker

Docs:

*

*UIDatePicker - Change the Appearance

*UIDatePicker - Styles


text:
Q: Enabling SSLv3 support for PHP 5.4.4 SoapClient With this code:
$soap = new SoapClient('https://test-api.geotrust.com/webtrust/query.jws?WSDL');
I am seeing this error:

PHP Fatal error:  SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://test-api.geotrust.com/webtrust/query.jws?WSDL' : failed to load external entity "https://test-api.geotrust.com/webtrust/query.jws?WSDL"

If you have PHP 5.5, you can do this:
$soap = new SoapClient($url),
array (
"ssl_method" => "SOAP_SSL_METHOD_SSLv23"
)

Any such solution for PHP 5.4.4? I cannot upgrade PHP at this time.
I've already tried the sslv3:// suggestion I found online, but it doesn't work on Debian.
Thanks.

A:
SoapClient::SoapClient(): SSL operation failed with code 1. OpenSSL Error messages: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

It sounds like you don't have an SSL/TLS server listening. You can reproduce it with the following. Note the use of port 80 rather than 443.
$ openssl s_client -connect stackoverflow.com:80
CONNECTED(00000003)
140735323054556:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:787:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 7 bytes and written 320 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---

If you do have an SSL/TLS server listening, then you can try to connect to it using a single protocol:
SSL v3:
openssl s_client -ssl3 -connect example.com:443

TLS 1.0:
openssl s_client -tls1 -connect example.com:443 -servername example.com

TLS 1.1:
openssl s_client -tls1_1 -connect example.com:443 -servername example.com

TLS 1.2:
openssl s_client -tls1_2 -connect example.com:443 -servername example.com

array (
  "ssl_method" => "SOAP_SSL_METHOD_SSLv23"
)

Just bike shedding, but in C we usually use the 2/3 method and then disable useless protocols and options. For example:
const SSL_METHOD* method = SSLv23_method();
if(method == NULL) handleFailure();

SSL_CTX* ctx = SSL_CTX_new(method);
if(ctx == NULL) handleFailure();

/* Cannot fail ??? */
const long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
SSL_CTX_set_options(ctx, flags);

In the code above, we use the 2/3 method, and then we disable SSLv2 (broken), SSLv3 (weak/wounded) and Compression (broken, leaks information). That means we use TLS 1.0 and above for the connection. If TLS 1.2 is available, then its used; else if TLS 1.1 is available, then its used; else TLS 1.0 is used.


text:
Q: Accessibility of variables HI,
i have small doubt related to the accessibility of variables.
int i; //default the linkage is external
const int i; //default linkage is internal
extern int i; //explicitly assigning linkage as external

class a
    {
        int l;  //Default linkage is external
        void f()
        {
          int k; //default linkage is external
        }
    }

this link says
default linkage is extern for non-const symbols and static (internal) for const symbols.
what about int i is it accessible in other file with out having external keyword?
what about the variable present inside the class and functions?
How to aces the function present in anonymous name space & what linkage do they have?
namespace //members of anonymous namespace
{
 class C{};
 int x;
 }

A: int i; has external linkage, and is in a normal namespace, so it is accessible from other files. They will have to declare it extern int i; in the same namespace (in this case, the global namespace) to access it.
Members of an unnamed namespace are not accessible from other files - that's the purpose of the namespace. Although they can have external linkage, their namespace is unique to the current file, so the same declarations in another file will refer to different things, unique to that file.

A: Refer here
Names in unnamed namespace have internal linkage.