MariaDB Won't Start After Installing

Question: I'm running an Ubuntu 20.4 server and I've recently removed mysql-server and mysql-client and am trying to get MariaDB up and running. I've installed both mariadb-server and mariadb-client. I stop and then try to restart maria db. I get the general error message:
Job for mariadb.service failed because the control process exited with error code.
See "systemctl status mariadb.service" and "journalctl -xe" for details.

I then run systenctl status mariadb.service and get the below:
mariadb.service - MariaDB 10.6.4 database server
     Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
    Drop-In: /etc/systemd/system/mariadb.service.d
             └─migrated-from-my.cnf-settings.conf
     Active: failed (Result: exit-code) since Thu 2021-09-23 13:26:03 CDT; 8s ago
       Docs: man:mariadbd(8)
             https://mariadb.com/kb/en/library/systemd/
    Process: 97366 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, status=0/SUCCESS)
    Process: 97377 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
    Process: 97379 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $? -eq 0 ]   &&>
    Process: 97387 ExecStart=/usr/sbin/mariadbd $MYSQLD_OPTS $_WSREP_NEW_CLUSTER $_WSREP_START_POSITION (code=exited, status=1/FAILURE)
   Main PID: 97387 (code=exited, status=1/FAILURE)

Sep 23 13:26:03 notised.xyz systemd[1]: Starting MariaDB 10.6.4 database server...
Sep 23 13:26:03 notised.xyz sh[97384]: [114B blob data]
Sep 23 13:26:03 notised.xyz sh[97384]: Fatal error in defaults handling. Program aborted
Sep 23 13:26:03 notised.xyz mariadbd[97387]: [106B blob data]
Sep 23 13:26:03 notised.xyz mariadbd[97387]: Fatal error in defaults handling. Program aborted
Sep 23 13:26:03 notised.xyz systemd[1]: mariadb.service: Main process exited, code=exited, status=1/FAILURE
Sep 23 13:26:03 notised.xyz systemd[1]: mariadb.service: Failed with result 'exit-code'.
Sep 23 13:26:03 notised.xyz systemd[1]: Failed to start MariaDB 10.6.4 database server.

I then run journalctl -xd and get these results:
-- A start job for unit cloud-final.service has finished successfully.
--
-- The job identifier is 153.
Sep 23 14:16:57 notised.xyz systemd[1]: Reached target Cloud-init target.
-- Subject: A start job for unit cloud-init.target has finished successfully
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- A start job for unit cloud-init.target has finished successfully.
--
-- The job identifier is 148.
Sep 23 14:16:57 notised.xyz systemd[1]: Startup finished in 6.792s (kernel) + 2min 3.586s (userspace) = 2min 10.379s.
-- Subject: System start-up is now complete
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- All system services necessary queued for starting at boot have been
-- started. Note that this does not mean that the machine is now idle as services
-- might still be busy with completing start-up.
--
-- Kernel start-up required 6792915 microseconds.
--
-- Initial RAM disk start-up required INITRD_USEC microseconds.
--
-- Userspace start-up required 123586997 microseconds.
Sep 23 14:17:01 notised.xyz CRON[2544]: pam_unix(cron:session): session opened for user root by (uid=0)
Sep 23 14:17:01 notised.xyz CRON[2552]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Sep 23 14:17:01 notised.xyz CRON[2544]: pam_unix(cron:session): session closed for user root
Sep 23 14:17:10 notised.xyz kernel: [UFW BLOCK] IN=eno1 OUT= MAC=90:2b:34:56:57:f0:74:ac:b9:eb:12:94:08:00 SRC=192.168.1.16 DST=192.168.1.62 LEN=222 TOS=0x00 PREC=0x00 TTL=64 ID=0 DF PROTO=UDP SPT=57572 DPT=5514 LEN=202

I have port 3306 fully open on UFW, so not quite sure why there is the UFW BLOCK error showing.
I've tried purging everything related to mysql and mariadb and reinstalled mariadb multiple times, but run into the same issue.
Comment: This can happen if MySQL server was not completely removed. Can you [edit] your question to include the steps you followed to uninstall MySQL Server? This will make it easier to know where to start looking for issues
Comment: There is no such Ubuntu version as 20.4. What is the REAL version.
Comment: You question doesn't specifically state your goal. Did you actually want to start MySQL or MariaDB? It seems like the latter but your answer below suggests you actually wanted to start MySQL so it's not really a solution to the question. Can you try to focus your question on one specific problem and then, if you post an answer, on the solution to that specific problem? Thanks.
Answer: OK, so after a lot of messing around with this I ended up completely removing/purging MariaDB and everything to mysql.
I ran:
sudo apt purge mariadb* *mariadb mysql* *mysql
sudo apt autoremove
sudo apt update && sudo apt full-upgrade -y

sudo find / | grep mysql I then removed any remaining files for mysql
sudo find / | grep mariadb I then removed any remaining files for mariadb
sudo deluser --remove-home mysql

sudo delgroup mysql

This is probably overkill, but I was getting frustrated with this. After removing everything I just went back to mysql and installed mysql-server. Was able to get it up and running this time with no issues.
I THINK there may have been an issue with a symlink from when I originally had mysql instead of MariaDB, but after just nuking it and starting over from scratch I was able to get it working.
Comment: Welcome! Your answer isn't really an answer to your question which ostensibly was how to start MariaDB. Purging both and reinstalling MySQL isn't a solution to that but a solution to the problem of starting MySQL. For the question and answer to be useful to the community your question should state explicitly what you wanted to achieve (either starting MariaDB or MySQL) and your answer should state explicitly how you achieved a solution to the problem you stated in your question. This answer currently is more suited to a comment under the question briefly mentioning that you went back to MySQL.
Comment: @authentictech *actually*, technically it *is* a solution if you have MySQL and MariaDB data still around, it can clobber and break each other.  Also consider this individual is also the OP, and this 'solved' the problem for them - we might just choose instead to close the post as "no longer relevant" as it might not help future readers, but that's a close voter review decision, not a moderator's decision.

MariaDB Won't Start After Installing


3-way light switch,faulty sensor switch or incorrect wiring?

Question: I am looking to replace one my 3-way toggle switch to a 3-way sensor switch (Leviton DOS05). After wiring per instruction provided, the second switch (non-sensor) does not work unless the sensor switch is on.
Here's a wiring diagram of my setup:

When I tested the lines with a voltage pen, both travelers do not have any voltage reading when the sensor is off. I'm pretty certain that the load and line wires are installed correctly, so I'm not sure if there's an issue with my 3-way sensor switch, or if this is a case of incorrect wiring.
Toggle switch:

Sensor switch:
Answer: Based on the installation instructions, I think you have most of this correct, as wacky as it looked to me at first.
However, there is definitely one thing wrong: Line vs. Load.
Line refers to incoming power. That is, if you have all the wires separated out and not attached to anything and turn on power, that is the one wire that will have power.
Load refers to outgoing power - i.e., to the light fixture.
According to the instructions, load should be in the sensor box and line should be in the regular switch box. Which is what your diagram shows. Except that you have the light fixture connected to line. Which would be wrong if that were the case. But based on the diagram, I think you actually have line and load reversed - i.e., the wire going into the sensor box - showing with an arrow towards the sensor, implying that it is incoming power - marked as load. If indeed the two are swapped then effectively the sensor is the first switch, controlling whether any power is going out to the second switch and then to the light. Some smart 3-way switches work that way, but this one works the opposite way - power first to the ordinary switch, which sends power on via the travelers to the sensor switch.
The way it works is that the ordinary switch is wired so that there is always power on Traveler 2. There is also power on Traveler 1 in one of the switch positions ("up" in the example wiring diagram). So the sensor switch is actually powered by Traveler 2 (which is why that is labeled as "Line/Load" on the sensor switch) and Traveler 1 is used as a signal, and in fact is labeled as Traveler (singular, no #) on the sensor switch. This actually means you could use a standard (not 3-way) switch in place of the "ordinary 3-way switch" and it would work just as well, as long as it was wired in a matching fashion. The instructions don't list it that way because for retrofit purposes the assumption is that you already have a 3-way switch in place.
Can this be fixed? Maybe. It depends on what wires/cables you have in each box. It may be very simple to rearrange things, or it may be hard. I am pretty sure it will be possible, assuming you have a typical /3 with ground cable in between the two boxes, because you are not relying on neutral (this switch can work using ground instead of neutral) so there should be a way to make it all work. Need annotated pictures showing the wiring in both boxes to figure out a complete answer.
Comment: Hi there, I've added wiring pictures for both switches, would this be sufficient?
Comment: Thanks for the clarification! You are right that I incorrectly annotated the line and load, and that the sensor switch is connected to the line wire instead of the load wire specified in the instruction sheet. If I wanted to keep this wiring configuration, would the only solution be to use a 3-way sensor that works with a line connection?
Comment: Not necessarily. It is *possible* that the wires can be rearranged such that it could work "in reverse". But unknown without a lot more detail - e.g., pictures of the actual switches/wires.
Comment: That does help a bit. A couple of questions: 1 - Are the wires loose individual wires in conduit, or are they sets (black/white, black/red/white) in cables? 2 - It sure looks like you have neutrals, why aren't you using them?
Comment: I'm not too sure whether the wires are set or individual. The original switch (and the whole house) wiring was done by the electrician and he wired the switches without neutral. I followed suit to be consistent since the sensor switch didn't require neutral either
Comment: I *think* you have conduit, but I can't tell from the pictures. Feel where the wires are coming into each metal box. If they are loose then that's conduit. If they are tight and you can feel (or better, see) a small bit of cable sheath around each group of wires, then they are cables. That matters because the solution often involves adding another wire, which is practical (but a new skill to learn) with conduit but not with cable. As far as why the old switches didn't have neutral, **dumb switches (i.e., no motion, smart, timer, etc.) don't use neutral**. Ideally you want to use neutral to
Comment: power switches that need it, but some switches (like the one you just bought) *can* work legally using ground instead of neutral. That is the exception to the rule, and neutral is still better in certain ways. In your case, each wire-nutted-group-of-white-wires is a bunch of neutrals - you remove the wire nut, add the new switch neutral to the bunch and put back on the wire nut (or possibly a new wire nut depending on the number of wires).
Comment: Yes, the wires are contained inside a metallic conduit. I will also add the neutral for the sensor switch if I need to rewire this again.


Argument of varying types?

Question: how do I make a argument of varying types?
I want to do m.add(5) or m.add(float[][]). How would I do that?
void add(? n) {
    for (int i = 0; i < cols; i++) {
           for (int j = 0; j < rows; j++) {
            data[i][j] += n;
           }
        }
    }
}

Comment: You can provide two different function definitions. Such function overloading is possible in processing as long as either the number or the types of the arguments differ (as they would in your case).
Answer: You're looking for something called method overloading. You can google that for a ton of results, but basically you'd want to define the function twice:
void add(float n){
  // do the thing
}

void add(float[][] n){
  // do the thing
}

In theory you could also take an Object parameter and then use the instanceof keyword to figure out what type was actually passed in, but that's a hackier approach.

Argument of varying types?


Can't upgrade from Ubuntu 12.04.5 (precise pangolin) to 14.04.1 (Trusty Tahr)

Question: I am currently running Ubuntu 12.04.5 (LTS) and want to upgrade to Ubuntu 14.04.1 (LTS).
Unfortunately, when I open up the update-manager it gives me an option to upgrade to  12.10, I don't want to do this since I've heard that it is perfectly possible to upgrade between LTS versions. do-dist-upgrade also ends up telling me the same thing.
Is there any possible way to upgrade to Ubuntu 14.04.1 from 12.04.5?
Answer: Open the updatemanager and click on the settings-button (left bottom of the screen) .
Now seek for the tab 'updates' and click the selector on the last line (...newer versions of Ubuntu) for LTS (not any version, but only the LTS-version) . You'll be prompted for your password to make the changes valid.
Run again for updates (with good working internet-connection) you should see now the possibility for an upgrade to the next LTS-version (do so) / From there on follow the on-screen instructions.
Mind you: I'd like to give you the advise to do a fresh install of 14.04 LTS ; not only is it much quicker to do, but it is technically better to run a 'clean' installation of this Ubuntu-version (you'll have a 100% good working Ubuntu). Upgrades can go wrong sadly.
So, before you do anything: MAKE BACK UPS of your important data !!!
Good Luck !


Assign variable to function - Swift 3

Question: How do I assign a function to a variable then perform  action based on the result? Im using xcode 10.
class ViewController: UIViewController {

  func foo(bar: Int = 10) -> Int {

   return 1

  }

  var demo = foo(bar: Int = 1) // cannot assign immutable expression...
  var test = 10

  let result = demo - test
}

Im expecting result to equal 9
Error Im getting at demo is Cannot use instance member foo within property initializer; property initializers run before self...
Disclaimer: I'm new to swift; coming from ruby.
Comment: 1 - 10 is -9, not 9.
Comment: @i_am_jorf Correct but that's not the issue. See error.
Comment: The OP (and the code you have right now) has an error in the "demo" declaration. Remove the "Int = " portion in that line. That will always yield the error stated, which is not the same error as you have commented in my answer.
Answer: Your syntax is a bit mangled.

Add underscores to the func signature to improve readability.
Pass in a variable only when you want to overwrite the default.
Recode this sample func to not always return 1, but return what was passed into it (or the default).
func foo(_ bar: Int = 10) -> Int {
    return bar
}

var demo = foo()   // returns the default of 10
var test = foo(1)  // returns the parameter passed in, which is 1

let result = demo - test

EDIT: The actual question was lost in the errors fixed above. The OP is to have foo(bar:) be a computed property. So the final solution would be:
var _foo:Int = 10
var foo:Int {
    get {
        return _foo
    }
    set {
        _foo = newValue
    }
}

Tested in a viewDidLoad():
print(foo)  // prints 10
foo = 1
print(foo)  // prints 1

Please note:

You cannot do anything like have a "constant default" to a computed property. Since this is an instance property, you set it once only.
You cannot turn a function into a property. Yes, functions are first-class citizens in Swift, but this only means you can "treat them like a variable" by passing them into another function.
I tried a few variations (adding "= 10" to the declaration, making the Int an Optional, removing the get from things, and it either doesn't build or crashes.

If you really need to have a default of 10, compute what is passed into things, and have it available globally, I recommend refactoring your concept to use one or the other of these solutions.
Comment: You'll need to add more code. It sounds like you are coding something else than what you've posted. (1) Is foo inside a property? A specific class? An enum? (2) If in a class, what is the initializer? (3) In fact, what initializer **is** raising this error?
Comment: Yes but Im getting an error I dont understand: `Cannot use instance member foo within  property initializer; property initializers run before  self...`
Comment: @Sylar Please update your question with additional context regarding this error.
Comment: Im inside  `UIViewController` sorry.
Comment: Ok. SO if you aren't in a playground, I believe if you (1) put my **foo()** as a "raw" function in that view controller and (2) put my calls in **viewDidLoad() - after the super.viewDidLoad() - ** and then looked at the result, things should build and run. That's what I meant by asking for more code. You must be putting your foo() someplace else.
Comment: Error is gone if I place the call in `viewDidLoad` but I need it as a global variable.
Comment: Search here and elsewhere for "Swift calculated property". That should show you how to code the remainder you need for this. **ALSO**, consider editing your title - it's misleading. Good luck!
Comment: I'll have a go at this later tonight (UK). Thanks
Answer: Here are some syntax possibilities, depending on what you need the code to do:
var test = 10

// Simple value
let demo = foo(bar: 1)
let result = demo - test

// Closure calling function
let demo2 = { foo(bar: 1) }
let result2 = demo2() - test

// Pointer to function
let demo3 = foo
let result3 = demo3(1) - test

Assign variable to function - Swift 3


Springboot @Bean NoSuchMethodError

Question: I was using dependency spring-boot-starter-security 2.7.15 . This package used spring-security-config 5.7.5 as a dependency which has a CVE. In maven, I upgraded the dependencyManagement for spring-security-config 5.7.5 -> 5.7.10. Now, when I start my spring boot and run my tests, I get this error in my SecurityWebFilterChain Bean: Error creating bean with name 'platformSecurityWebFilterChain' defined in com.x.SecurityConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.server.SecurityWebFilterChain]: Factory method 'platformSecurityWebFilterChain' threw exception; nested exception is java.lang.NoSuchMethodError: 'org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.pathMatchers(org.springframework.web.util.pattern.PathPattern[])'
My bean looks like this:
@Bean
  public SecurityWebFilterChain platformSecurityWebFilterChain(
      ServerHttpSecurity httpSecurity,
      JwtAuthorizingFilterProperties jwtAuthorizingFilterProperties) {
    return httpSecurity
        .authorizeExchange()
        .pathMatchers({redacted})
        .permitAll()
...other stuff

clearly, maven is able to find the .pathmatchers. I am just not sure how its not internally able to find pathpattern.
Thanks!
Comment: The part you've redacted from your question will help us explain why you're getting this error. However, you can figure this out pretty quickly by looking at the javadocs for ServerWebExchangeMatchers; they have different signatures.  Even if you get past this, you'll likely encounter other issues, these are often not backward compatible.
Answer: Most probably it is because of the library version conflict issue which not all of your spring security libraries are in the same version. Guess that it is because you are using spring-security-web 5.7.5 and spring-security-config 5.7.10 ?
But I don't understand why you need to specifically update spring-security-config to 5.7.10 as by default spring-boot 2.7.15 (and hence spring-boot-starter-security 2.7.15) should already upgrade the spring-security to 5.7.10 in spring-boot 2.7.14 (See this).
So try to make sure all the spring-security libraries (e.g spring-security-web) are in the version 5.7.10 which align with your spring-boot version 2.7.15 should solve your problem.

Springboot @Bean NoSuchMethodError


android HTTP request with post data

Question: Alright so I have the following situation, I got a java app, where users can login, once they do it will generate a random key, I wish to send this key to my website using http requests.
On the web side I will insert it into the database for later use, this is already working.
Now at this moment I am very stuck with the java side. I am using the following code to try the http request:
private void startRegistration(String username, String password) {

    String myRandomString = randomString(6);
    String deviceId = "abc";
    startToast(myRandomString);

    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        insertDevice(myRandomString, deviceId);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@TargetApi(Build.VERSION_CODES.KITKAT)
public void insertDevice(String randomString, String deviceId) throws IOException {

//        String urlParameters  = "key=" + randomString + "&device_id="+ deviceId;
//        byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
//        int    postDataLength = postData.length;
    String request        = "http://website.com/test";
    URL    url            = new URL( request );

    HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setDoOutput( true );
        conn.setInstanceFollowRedirects( false );
        conn.setRequestMethod( "GET" );
        conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty( "charset", "utf-8");
//            conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
        conn.setUseCaches( false );

    try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
//            wr.write( postData );
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, "test", duration);
        toast.show();
       }
   }

On the web side I have a route set to catch this request and simple throws a log::info so I can check if the request even ever gets there, this looks like follow:
public function create() {

    Log::info('I got here, hurray!');
}

now when I hit the URL in my browser I can see the log appearing, when I use my app, I don't. But there are no errors thrown either.
At the end I'd like to use a POST request and send both the random key, and device ID to the website. any help is much appreciated
Comment: you can use [OkHttp](http://square.github.io/okhttp/) Library. It will make your task much easier that way.
Comment: http://stackoverflow.com/questions/11766878/sending-files-using-post-with-httpurlconnection following link will help you
Comment: you don't seem to be calling `conn.connect()`...
Answer: You are setting up the connection but you're not triggering the request. You can perform the request by calling conn.connect() or "operations that depend on being connected" (javadoc)
Here's an example of a POST request:
public void insertDevice(String randomString, String deviceId) {

    String request = "http://website.com/test";
    URL url = new URL(request);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("POST");

    String urlParameters = "key=" + randomString + "&device_id=" + deviceId;
    byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

    conn.setDoOutput(true);

    try (OutputStream os = conn.getOutputStream()) {
        os.write(postData);
    }

    conn.connect();

    // Get response code, e.g. 200.
    // conn.getResponseCode();

    // Read server response data with conn.getInputStream() or conn.getErrorStream().

    conn.disconnect();
}

Comment: Sadly this is still not popping my logs on the web server, but no errors are thrown either.
Comment: @killstreet not even a fixed version o GET hit the server?
Comment: never mind, it was working just the server log had a little delay, you are amazing :) thank you so much!

android HTTP request with post data


Three Ruby classes, more than three problems?

Question: I have three Ruby files in the same directory:
classthree.rb
otherclass.rb
samplecode.rb

Here are the contents of classthree.rb:
require './samplecode.rb'
require './otherclass.rb'

class ClassThree

  def initialize()
    puts "this class three here"
  end

end

Here are the contents of samplecode.rb:
require './otherclass.rb'
require './classthree.rb'

class SampleCode

  $smart = SampleCode.new
  @sides = 3
  @@x = "333"

  def ugly()
    g = ClassThree.new
    puts g
    puts "monkey see"
  end

  def self.ugly()
    s = SampleCode.new
    s.ugly
    puts s
    puts $smart
    puts "monkey see this self"
  end

  SampleCode.ugly

end

Here are the contents of otherclass.rb:
require './samplecode.rb'
require './classthree.rb'

END {
  puts "ending"
}

BEGIN{
  puts "beginning"
}

class OtherClass

  def initialize()
    s = SampleCode.new
    s.ugly
  end

end

My two questions are:

There has to be a better way than require './xyz.rb' for every class in the directory. Isn't there something like require './*.rb'?
When I run ruby otherclass.rb I get the following output:

Why do I get "beginning" and "ending" twice each??
Comment: Consider converting your project to a Ruby gem. Rubygems is a module system for Ruby that works by managing the library search path. Hacking around `$LOAD_PATH` should never be needed.
Comment: Also see [this](http://stackoverflow.com/questions/735073/best-way-to-require-all-files-from-a-directory-in-ruby) question.
Comment: Extract from your code whatever that is not related to your point. Show the minimum required to show your point.
Answer: At 1 - The best way to deal with it is to create another file. You can call it environment.rb or initialize.rb, and it would require all the needed files.
$LOAD_PATH.unshift File.dirname(__FILE__)

require 'samplecode.rb'
require 'classthree.rb'
require 'classthree.rb'

Now you only need to require this file once on the start of the application.
At 2 - You started from file 'otherclass.rb'. It displays the first 'beginning' bit and then it loads samplecode.rb file. At this point, 'otherclass.rb' has not been loaded yet - it was not required by any other file. hence samplecode.rb is rerunning whole otherclass.rb, which is being required there. Rerunning doesn't reload 'samplecode.rb' as it was already required (require checks first whether file was or was not required). That's why you're seeing those messages twice.


Avoiding duplicate objects in Java deserialization

Question: I have two lists (list1 and list2) containing references to some objects, where some of the list entries may point to the same object. Then, for various reasons, I am serializing these lists to two separate files. Finally, when I deserialize the lists, I would like to ensure that I am not re-creating more objects than needed. In other words, it should still be possible for some entry of List1 to point to the same object as some entry in List2.
MyObject obj = new MyObject();
List<MyObject> list1 = new ArrayList<MyObject>();
List<MyObject> list2 = new ArrayList<MyObject>();
list1.add(obj);
list2.add(obj);

// serialize to file1.ser
ObjectOutputStream oos = new ObjectOutputStream(...);
oos.writeObject(list1);
oos.close();

// serialize to file2.ser
oos = new ObjectOutputStream(...);
oos.writeObject(list2);
oos.close();

I think that sections 3.4 and A.2 of the spec say that deserialization strictly results in the creation of new objects, but I'm not sure. If so, some possible solutions might involve:

Implementing equals() and hashCode() and checking references manually.
Creating a "container class" to hold everything and then serializing the container class.

Is there an easy way to ensure that objects are not duplicated upon deserialization?
Thanks.
Comment: I don't think this is possible.  For objects to be shared between the streams you must always read/write both streams together.  But if you must do that, why not combine them into one stream?
Answer: After deserialization of the second list you could iterate over it's the elements and replace duplicates by a reference to the first list.
According to 3.7 The readResolve Method the readResolve() method  is not invoked on the object until the object is fully constructed.
Comment: @stacker - your second sentence is true but not pertinent.  The `readResolve()` method does not need to return `this`.
Comment: @Stephen C - The intention was to mention that using readResolve() wouldn't help to prevent instantiation of unneeded objects.
Comment: This will probably be the least painful solution.
Answer:
I think that sections 3.4 and A.2 of the spec say that deserialization strictly results in the creation of new objects, but I'm not sure. If so, some possible solutions might involve: ...

2, Creating a "container class" to hold everything and then serializing the container class.

I read these statements as "if I my understanding about deserialization always creating new objects is incorrect, then solution #2 of writing both lists wrapped in a container class to a single stream is an acceptable solution."
If I am understanding you correctly, this means you think writing out through a single container containing both lists won't work because it will still result in duplicate objects ("strictly results in ... new objects"). This is incorrect.  When writing out the graph of objects (your wrapper class), each object is only serialized once, no matter how many occurrences in the graph.  When the graph is read back in, that object is not duplicated.
http://java.sun.com/javase/6/docs/api/java/io/ObjectOutputStream.html

The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.

So, if you can, use option #2.

Creating a "container class" to hold everything and then serializing the container class.
Comment: @finnw - Sorry, I'm not neglecting that.  Yes, the asker did initially say 2 streams, but he later says, as I quoted above, `I think ... strictly results in the creation of new objects, but I'm not sure`). He goes on to say that, if his understanding was wrong (it was), that `possible solutions` include creating a wrapper and writing a single stream (`2. Creating a 'container class' to hold everything and then serializing the container class.`)  I was trying to be clear quoting his text above, but I'll clarify my answer to try to clear up the confusion.
Comment: -1. You are neglecting the fact that there are 2 streams.  The reference sharing mechanism works only within a single ObjectInputStream, not between 2 independent streams.
Answer: You can override the readResolve() method to replace what's read from the stream with anything you want.
private Object readResolve() throws ObjectStreamException {
  ...
}

This is typically used for enforcing singletons. Prior to Java 5 it was also used for typesafe enums. I've never seen it used for this but scenario but I guess there's no reason it couldn't be.
Now this will work with individual objects that you control but I can't see how you'd make it with a List. It could ensure that the objects returned in that list aren't duplicated (by whatever criteria you deem).
Comment: This is the right approach.  However, the OP needs to realize criterion for determine if objects are duplicate must be based on the values of the objects' fields ... not the objects' identities.


Left recursive ANTLR grammar

Question: I have written a grammar but getting a left recursive error.
grammar Lang;

options
{
    output  = AST;
    language    = C;
    ASTLabelType= pANTLR3_BASE_TREE;
    backtrack   = true;
}

start   : primary_expression+
    ;

primary_expression
                : '{' expression '}'
                | expression ',' expression
                ;

expression
                : logical_or_expression
                | logical_or_expression '?' expression ':' expression
                | logical_or_expression '?' ':' expression
                | logical_or_expression '?' expression
                ;

logical_or_expression
                : logical_and_expression
                | logical_and_expression '|' logical_or_expression
                ;

logical_and_expression
                : primary_expression
                | primary_expression '&' logical_and_expression
                ;

I am getting the following error:

[12:41:35] error(210):  The following sets of rules are mutually left-recursive [primary_expression, logical_and_expression, logical_or_expression, expression]
  [12:41:35] Aborting because the following rules are mutually left-recursive:
      [[Lang.primary_expression,index=2,line=19], [Lang.logical_and_expression,index=5,line=36], [Lang.logical_or_expression,index=4,line=31], [Lang.expression,index=3,line=24]]

Corrected grammar
grammar Lang;
options
{
    // Note that in the C implementation, all implementations of trees and
    // adaptors pass around pANTLR3_BASE_TREE, which contains a super pointer
    // to your own implementation of a tree node and tree and so on. Hence
    // the node type is ALWAYS pANTLR3_BASE_TREE and there is no need to define
    // the type (the definition is silently ignored if you leave it there)
    //
    //output    = AST;
    language    = C;
    //ASTLabelType= pANTLR3_BASE_TREE;
    backtrack   = true;
}

start   : primary_expression+
    ;

primary_expression
                : '{' expression '}'
                | expression ',' expression
                ;

expression
                : logical_or_expression
                | logical_or_expression '?' expression ':' expression
                | logical_or_expression '?' ':' expression
                | logical_or_expression '?' expression
                ;

logical_or_expression
                : logical_and_expression
                | logical_and_expression '|' logical_or_expression
                ;

logical_and_expression
                : STRING
                | STRING '&' logical_and_expression
                ;

/* We're going to ignore all white space characters */
WS
    :   (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
    ;

STRING
    :   ('a'..'z' | 'A'..'Z' | '0'..'9' | '_')+
    ;

Comment: I am using antlrworks-1.4.3.jar.
Comment: With v4 the error remains same:
Comment: C:\Users\agupta\Desktop>java -cp antlr-4.0-complete.jar org.antlr.v4.Tool Lang4.g
error(119): Lang4.g::: The following sets of rules are mutually left-recursive [primary_expression, logical_and_expression, expression, logical_or_expression]
Comment: As I told, I am new to grammars, so this must be the mistake. Can you suggest me how to correct this. I just want a grammar to handle the following => "," "{" "}" "?:" "|" "&"
Comment: Thanks for the hint :). I have corrected the grammar by adding the terminals and generated the code.
Answer: Antlr 4 can handle direct left recursive, but can not cope with indirect left recursive. In the first case, "primary_expression" and "logical_and_expression: primary_expression ..." formed indirect left recursive. But now antlr4 can not generate 'c' codes.
grammar test3;

options
{
    language    = Java;
}

start   :
    expression+
    ;

expression :
    primary_expression
    | expression '&' expression
    | expression '|' expression
    | expression '?' expression ':' expression
    | expression '?' expression
    | expression '?' ':' expression
    | expression ',' expression
    | '{' expression '}'
    ;

primary_expression : // variable or constant definition, such as
    VARIABLE
    | NUMBER
    ;
VARIABLE :
    ('A'..'Z')+
    ;

NUMBER :
    ('0'..'9') +
    ;

Left recursive ANTLR grammar


Ubuntu 13.10 Macbook Air Mavericks Parallels 9 Black Screen

Question: I can install Ubuntu 13.10 in parallels ok and then log in.  Problem is Ubuntu does an update and I get black screen / desktop such that I can't see any app windows that I open.  I've tried a few of the other suggestions and they don't work for me.
Comment: What other suggestions? Please include what you have already tried and links to any sites you have got solutions from. That will help us a lot. Thanks!
Comment: I tried the solutions offered in this post:  http://askubuntu.com/questions/360732/ubuntu-13-04-under-parallels-desktop-black-desktop-after-x-windows-update
Comment: RPi Awesomeness - just wondering if you had a chance to consider what might be the way to resolve the issue?  I could wait for another release?
Answer: Same problem here with a MacBook Pro. Here's what worked for me after I updated 13.10 and received a black screen, although the toolbar on the left was showing. It was simple, but I don't know why it worked.

Shut down the Ubuntu VM (13.10)
In Parallels 9 config for the VM, go to Hardware > Video, and disable 3D acceleration.
Restart Ubuntu 13.10. You will now get a completely black screen.
Shut down the Ubuntu VM once more.
Again, in Parallels config for the VM, go to Hardware > Video and reenable 3D acceleration.
Restart, and you're back in business (No black screen and everything properly updated).
Comment: The same fix worked for me with Ubuntu 14.04 in Parallels 10. Thanks!
Comment: I only wish you had posted this 3 days earlier, when I was last looking at this question and despairing. =)
Comment: You are a genious.
Comment: Parallels 9 updated itself and the same problem returned (Ubuntu 14.01). This set of steps worked to fix it again.
Comment: great, thanks! (I needed to find the shut down option on the icon in the taskbar of my iMac by right clicking the icon and navigating to the actions menu. took me ages to find it!
Answer: What worked for me was this:

Switch to console (focus on black screen and press Fn+Ctrl+Alt and whilst holding that press F1)
Log in with user parallels (or what ever user your using)
Follow this article on installing the tools from command prompt - http://kb.parallels.com/en/113394

Basically, once I found the image and placed it on the CDROM drive I mounted within the os:
sudo mount /dev/cdrom /media/<username>/CDROM

Then executed the install program and updated the tool!
Comment: Fantastic. Thanks for this. I tried absolutely everything - I wasn't getting _anything_ on the screen - once it booted it was black. Switching to console (which was Cmd+Ctrl+Fn+F1 for me .. not Alt/Opt), worked great. Up it popped and I logged in. Cheers.
Answer: [I just realized the post above me has a MUCH simpler solution, by rechecking the video acceleration in the VM settings. Doh!]
I have a solution. Reinstalling Parallels Tools blindly does the trick.
This just happened to me, with Mavericks, Parallels 9.0.24172, Ubuntu 13.10 and updates installed on 1 Mar 2014. On reboot, I could see the login screen, then after logging in, I could see the Unity "Launcher" or whatever the call the row of icons on the left, but the rest of the screen was black. If I click to start any apps, like Firefox, the icon in the bottom of the Parallels screen indicate that the re is disk activity as the app starts, but the screen remains black.
To fix:

From the Parallels Desktop "Virtual Machine" menu, choose "Reinstall Parallels Tools..."
You will see the CD-Rom and Hard Disk icons in the bottom of the Parallels window blink green
Wait about 10 seconds until the Hard Disk icon settles down
Blindly type your password (make sure Parallels has focus in Mavericks)
You'll see the Hard Disk icon blinking green some more.
After a few minutes (I waited 5, just to be safe), make sure Parallels still has focus, and hit the Return key. Parallels will reboot.
Voilá! On reboot and re-login, the desktop is visible

Just before I installed the Ubuntu updates, Parallels Tools had reinstalled itself, due to a new version of the Tools since I last used the VM, but it seems that certain kinds of Linux updates break the video driver. As stated above, always make a Parallels snapshot before running Ubuntu update, just to be safe.
Comment: Worked with Ubuntu 13.04, Parallels 9.0.24251 and Yosemite. Thanks a lot for the fix!
Answer: I experienced the blank screen issue with Parallels 9.0, Ubuntu 13.04,  Mavricks on a macbook air. This worked for me

Shutdown
In Parallels 9 config for the VM, go to Hardware > Video, and disable 3D acceleration.
Restart and update Parallels tools
Enable 3D acceleration
Answer: Same problem here with a MacBook Pro. Here's what worked for me after I updated 13.10 and received a black screen, although the toolbar on the left was showing. It was simple, but I don't know why it worked.
Shut down the Ubuntu VM (13.10)
In Parallels 9 config for the VM, go to Hardware > Video, and disable 3D acceleration.
Restart Ubuntu 13.10. You will now get a completely black screen.
Shut down the Ubuntu VM once more.
Again, in Parallels config for the VM, go to Hardware > Video and reenable 3D acceleration.
Restart, and you're back in business (No black screen and everything properly updated).

Using Parallels Desktop 10 and installed Ubuntu 14.04.1
The solution:

Do a fresh install of Ubuntu 14.04.1 via it's ISO image with Parallels Desktop 10.
Once you are logged into Ubuntu do a manual install of Parallel Tools, reboot.
Login and run in a terminal;
sudo apt-get update
sudo apt-get upgrade
sudo reboot

Log in and you should see your black screen!
Using Parallels Desktop's menu do a Shutdown.
In Parallels Desktop Control Center do a Configure ...
Under Hardware -> Video disable 3D Acceleration.
Restart Ubuntu.
Login to Ubuntu and run the Software Updater.
Wait for it to do its thing and shutdown.
Go back into Parallels Desktop Control Center and reenable 3D Acceleration
Restart Ubuntu and login.


Questions about Fubini's theorem

Question: I learned the following from Hunter's Applied Analysis.
Denote the Schwartz space
$${\mathcal S}({\mathbb R}^n):=\{\varphi\in C^{\infty}({\mathbb R}^n):\sup_{x\in{\mathbb R}^n}|x^{\alpha}\partial^{\beta}\varphi(x)|<\infty\quad\text{for every}\quad\alpha,\beta\in{\mathbb Z}_+^n\}.$$
If $\varphi\in{\mathcal S}({\mathbb R}^n)$, then the Fourier transform $\hat{\varphi}:{\mathbb R}^n\to{\mathbb C}$ is the function defined by
$$\hat{\varphi}(\xi):=\frac{1}{(2\pi)^{n/2}}\int_{{\mathbb R}^n}\varphi(x)e^{-i\xi\cdot x}dx,\quad \xi\in{\mathbb R}^n.$$
Suppose that $f,\varphi\in{\mathcal S}$. Then we have
$$\begin{align}\int\hat{f}(\xi)\varphi(\xi)d\xi&=\int\frac{1}{(2\pi)^{n/2}}\bigg(\int
f(x)e^{-i\xi\cdot x}dx\bigg)\varphi(\xi)d\xi\\
&=\int f(x)\frac{1}{(2\pi)^{n/2}}\bigg(\int\varphi(\xi)e^{-i\xi\cdot x }d\xi\bigg)dx\\
&=\int f(x)\hat{\varphi}(x)dx.
\end{align}$$
This is the motivation of the definition of the Fourier transform of tempered distributions.
Here is my question:

How can I get the second equality by Fubini's theorem?

The form I know about the theorem is
$$\int_{A}\bigg(\int_B f(x,y)dy\bigg)dx
=\int_{B}\bigg(\int_A f(x,y)dx\bigg)dy
=\int_{A\times B}f(x,y)d(x,y)$$
But I am wondering what is $f(x,y)$ in the case above.
Comment: The trick is to move everything inside the integrals and what is there will be the thing to which you'll have to apply Fubini. So you'll apply it to $g(x,\xi) = \frac{1}{(2\pi)^{n/2}} f(x) \varphi(\xi) e^{-\xi \cdot x}$.
Comment: @Theo: +1.Thanks for your answer! I focus too much on the "difference" to notice the trick. Could you write your comment as an answer?
Comment: Okay, will do. But I don't have much more to say. By the way, there is a $dx$ missing in the equation you ask about.
Answer: The function to which you'll have to apply Fubini is $$g(x,\xi) = \frac{1}{(2\pi)^{n/2}} f(x) \varphi(\xi) e^{-\xi \cdot x}.$$
I think you can check for yourself that this is a function in $\mathcal{S}(\mathbb{R}^{n}\times\mathbb{R}^{n}) \subset L^{1}(\mathbb{R}^n \times \mathbb{R}^n)$, so it is a function to which we can apply Fubini.
The calculation itself is straightforward: start with the first equation, move everything inside the integrals, switch the order of integration and pull the things out, so as to arrive at the second equation, the one you're asking about.

Questions about Fubini's theorem


Map measurements

Question: Recently, the range of the Gate ability of Twisted Fate has been reduced from Global Range to 5500 units. The problem is, you can't possibly measure your range before activating the Destiny skill.
Do someone know about the different measure of the 5v5 map?
Of course I could learn play to play to know approximately where I can TP or not... but that is not efficient. If I could know it in advance.
It seems that mid-top to mid-mid is not possible. From my few games with this new configuration, it seems that the range might represents 1/3 of the map.
Comment: Hm. Has Pantheon's ult also been reduced to 5500? Does the range upgrade with level (like Nocturne)? It's not inconceivable that Riot might fix this in a future patch, as it seems like oversight more than anything.
Comment: @RavenDreamer Pantheon's ultimate has also been reduced to 5500. Range does not upgrade with level. I don't want to discuss balance of champions, but I feel I got ******. Com'on, you can't even see the radius without casting the first step of the Ultimate?!
Comment: Doesn't it show the range on mouse over the spell icon ?
Comment: @Dalshim I need to check that.
Answer: When mousing over the ability icon a white circle will appear on the minimap representing the abiliy's range. Check out Patch Preview Video 126.96.36.199 at 1:32. It clearly shows the range of Twisted Fate's Ultimate on the minimap (5500 if you look closely at the tooltip) in the lower right corner. It looks like it is approximately 2/3 of the total map distance in height but roughly, maybe just less than, 1/2 the distance from Blue to Purple on the diagonal.
Answer: Here is a rough answer of what the distance 5500 represents :

5500 range is about from your Inhibitor to the outer mid turret.

EDIT : What's important here is :

Range doesn't improve with skill level
Range isn't big enough for lane swap, you first need to get closer before using ult.
Comment: Assuming you have a move speed of 400 units/second it takes you at least 13.75 seconds to move a distance of 5500 units. Having 400 ms would require you have a base of 330 (the highest base in the game shared by roughly three characters) and boots +2 and/or some masteries/runes etc. To make the walk in 10 seconds would require you have 550 ms which is not practical for most characters.
Comment: @Bravo840 Indeed I didn't think about quickly calculating it. But totally true. Had found this quote on another forum dealing the same problem, I'll edit to prevent misunderstanding. Thanks for the comment.

Map measurements


facebook page referrer

Question: I have set up my own Facebook page and would like to track analytics but use my own tools. Is it possible to track the referrer information?
Answer: <code>$_SERVER[HTTP_REFERER]</code> will provide it in PHP. But keep in mind, for various reasons, this can be unreliable.

facebook page referrer


override error message (The value 'xxx' is not valid for Age) when input incorrect data type for input field asp.net mvc

Question: I've tried to override error message when input incorrect data type in input field on HTML form.
For example I have the model like this.
public class Person
{
    public string FirstName {get;set;}
    public int Age {get;set;}
}

For view, I put text input for Age to get it value.
When type some string in Age text box like 'test' and press submit button.
I got this error message
The value 'xxx' is not valid for Age
However, I want to change this message and try many way. There 's nothing effect this message value.
Please could you help me to solve this problem.
Comment: For future reference, if you want to get responses to your questions in the future, you might want to consider marking your questions as answered.
Comment: Thank for your comment, I've review my question and check if it is solved.
Answer: After spending a couple of hours looking around, I see no one really has a suitable answer to this. I have found a solution that works for me so I thought I'd post it.
The problem for me was validating a nullable int. When a non valid value was entered by the user, the default message "The value 'dsfd' is not valid for Issue'.
The solution I came up with was to remove the errors from the model state and add my own.
The classes to perform the validation are below:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
public class ValidInteger : ValidationAttribute
{
     protected override ValidationResult IsValid(object value, ValidationContext validationContext)
     {
         if (value == null || value.ToString().Length == 0)
         {
             return ValidationResult.Success;
         }
         int i;

         return !int.TryParse(value.ToString(), out i) ? new ValidationResult(ErrorMessage) : ValidationResult.Success;
     }

}

 public class ValidIntegerValidator : DataAnnotationsModelValidator<ValidInteger>
 {
     public ValidIntegerValidator(ModelMetadata metadata, ControllerContext context, ValidInteger attribute)
         : base(metadata, context, attribute)
     {
         if(!attribute.IsValid(context.HttpContext.Request.Form[attribute.ObjectId]))
         {
             var propertyName = metadata.PropertyName;
             context.Controller.ViewData.ModelState[propertyName].Errors.Clear();
             context.Controller.ViewData.ModelState[propertyName].Errors.Add(attribute.ErrorMessage);
         }
     }
 }

Don't forget you'll also need to register the adapter in the global Application_Start()
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(ValidInteger), typeof(ValidIntegerValidator));

And decorate your property with the new attribute
[ValidInteger(ErrorMessage = "Please enter a valid number for issue")]

Comment: I needed to change [attribute.ObjectId] to [metadata.PropertyName] for this to work, as @Christna also said.
Comment: Helpful answer, but it doesn't work out of the box when your `Request.Form` is filled with a collection of items. For instance: `MyObj[0].MyProp`, `MyObj[1].MyProp`, etc. because the `metadata.PropertyName` will be `MyProp`. So how can I find the full key?
Answer: The response from wechel dated February 27, 12 worked for me, except that I needed to replace the line
    if(!attribute.IsValid(context.HttpContext.Request.Form[attribute.ObjectId]))

with
    if (!attribute.IsValid(context.HttpContext.Request.Form[metadata.PropertyName]))

I am guessing that the change is needed because I am using MVC4 and the code snippet provided was written in an earlier version of MVC?
Answer: You can use DataAnnotations to override the default error messages in MVC, as well as provide your own validation for whatever fields you need to.  See the following:
http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs
If you are using EF, you will need to create a MetaData class off the EF generated class and then add the data annotations.  The end of the 2nd article covers how to write these classes for entity framework.
In your specific case you will want to do something like:
using System.ComponentModel.DataAnnotations;

public class Person
{
   public string FirstName {get;set;}

   [Range(0, 110, ErrorMessage = "<your error message>")]
   public int Age {get;set;}
}

UPDATE I did forget one thing that is easy to overlook, you need to include the following JS files for the data annotations to be picked up client side without having to do a post:

MicrosoftAjax.js
MicrosfotMvcValidation.js

These should be stock in the Scripts folder of your project (if you are using MVC 2), and you need to include them either on your page or in your master page,

you will also need to include
<% Html.EnableClientValidation(); %>
on the page in question.
The client side validation will not let you submit the form until all fields meet validation requirements, as Kaspars Ozols points out you will still need to call Model.IsValid on your controller.
Comment: If you want the 'easy' way out you can always do the following in your view: <%: Html.TextBoxFor(m => Model.Age) %> <%: Html.ValidationMessageFor(m => Model.Age, "Please input number only")%>
Comment: Thank you very much for your help. Scott Lance. However, it quite doesn't solve my problem since error occurs in type converter I think.
Comment: there is also a "Numeric" data annotation
Comment: Is your view strongly typed?  If the view is strongly typed, then the validation enforces that a value of type int is entered, otherwise you will receive the error message.
Comment: Yes, it is strongly type view model. I just want to override the error message when binder cannot covert value to int. For example,
I fill value 'test' for Age text box. After posting form, there should be error message "Please input number only." not The The value 'test' is not valid for Age.
Comment: If you are not using a strongly typed view for whatever reason you can see if the Html.ValidationMessage helper works for you.  See: http://msdn.microsoft.com/en-us/library/system.web.mvc.html.validationextensions.aspx
Comment: Right, the data annotation should take care of that if the value in the input cannot be coerced to the type of the field (in this case int).  So if your if everything is hooked up right, you should see the error message that you put in your data annotation when you type 'test' in the age box.
Comment: Thank you very much Scott Lance. This solves my problem with simple way. :)
Comment: The last paragraph is just wrong! Model.IsValid still needs to be called as I can pass bad data by tailoring correct HTTP POST request.
Comment: @Kaspars Ozols - You are correct, if you are trying to forge a POST then it will bypass the validation.  I've updated my answer to reflect that you should still call Model.IsValid to be safe
Answer: I just wanted to show the Range attribute error message so I used the answer from wechel and Christna and changed it so the RangeAttribute is used. After adding the Validator class, only a custom Validator needs to be created and registered in the global.asax as shown in wechel's answer.
You also need to add a validation message with name "FieldRangeValidation" to your resource bundle. In my project it contains the following text: "Value must be between {0} and {1}"
public class ValidIntegerRangeValidator : DataAnnotationsModelValidator<RangeAttribute>
{
    public ValidIntegerRangeValidator(ModelMetadata metadata, ControllerContext context, RangeAttribute attribute)
        : base(metadata, context, attribute)
    {
        try
        {
            if (attribute.IsValid(context.HttpContext.Request.Form[metadata.PropertyName]))
            {
                return;
            }
        }
        catch (OverflowException)
        {
        }

        var propertyName = metadata.PropertyName;
        context.Controller.ViewData.ModelState[propertyName].Errors.Clear();
        context.Controller.ViewData.ModelState[propertyName].Errors.Add(string.Format(Resources.Resources.FieldRangeValidation, attribute.Minimum, attribute.Maximum));
    }
}

Answer:         if (ModelState["Age"].Errors.Count > 0)
        {
            ModelState["Age"].Errors.Clear();
            ModelState["Age"].Errors.Add("<your error message>");
        }

Comment: What if I have other types of validation error messages for the Age field. Your method wouldn't work because you are clearing other possible error messages


How to handle external errors when using Tonic where I must use tonic::Status?

Question: I am making a Tonic-based gRPC microservice that uses the Redis client. I can't figure out an example of implicitly converting a RedisError into a tonic::Status when an asynchronous error occurs.
async fn make_transaction(
    &self,
    request: Request<TransactionRequest>,
) -> Result<Response<TransactionResponse>, Status> {
    let mut con = self.client.get_async_connection().await?;
    con.set("my_key", 42).await?;
    ...
}

The connection from Redis client can fail as well as the set. I would rather not use .map_err() since that seems to break the async.
I was thinking I need to implement the trait From<Status> and From<RedisError> but not sure how to do it. This is my attempt, but it doesn't work since Tonic wants a tonic::Status, not a ApiError struct that I made:
pub struct ApiError {}

impl From<tonic::Status> for ApiError {
    fn from(err: Status) -> ApiError {
        ApiError {  }
    }
}

impl From<RedisError> for Status {
    fn from(err: redis::RedisError) -> ApiError {
        ApiError {  }
    }
}

Comment: Did you manage to solve this issue?
Answer: I managed to get around this type of problem by using a custom type as a transition vessel for the original error (which is RedisError in your case), so something like the following might work for you as well:
pub struct ApiError {}

impl From<RedisError> for ApiError {
    fn from(err: RedisError) -> Self {
        Self { }
    }
}

impl From<ApiError> for Status {
    fn from(err: ApiError) -> Self {
        Self::internal("Failed talking to Redis")
    }
}

async fn set_key(client: ..., key: &str, value: i64) -> Result<(), ApiError> {
    let mut con = client.get_async_connection().await?;
    con.set(key, value).await?
    ...
}

async fn make_transaction(
    &self,
    request: Request<TransactionRequest>,
) -> Result<Response<TransactionResponse>, Status> {
    set_key(self.client, "my_key".into(), 42).await?
}

I am not sure if this is the best way, but seems to do the job.


Knockout bind textbox to select text

Question: Recently I started learning front-end development so don't be surprised if this question is too dumb.
What I'm trying to do is to bind textbox to select text, not it's id. Here is a jsfiddle: https://jsfiddle.net/1rtzfLr1/.
Here is my HTML:

  <input type="text" data-bind="value: type" />
  <button type="button" data-bind="click: $parent.removeObject">-</button>

  <select data-bind="options: types, optionsValue: 'id', optionsText: 'title', optionsCaption: 'Type...', value: itemToAdd().type"></select>
  <button id="create-object-button" type="button" data-bind="click: addObject">+</button>

And JS:
function model() {
  var self = this;

  self.objects = ko.observableArray();
  self.types = ko.observableArray([new Type(1, 'one'), new Type(2, 'two'), new Type(3, 'three')]);
  self.itemToAdd = ko.observable(new Object());

  self.addObject = function() {
    self.objects.push(self.itemToAdd());
    self.itemToAdd(new Object());
  };

  self.removeObject = function(object) {
    self.objects.remove(object);
  };

  function Object(type) {
    var self = this;
    self.type = type;
  }

  function Type(id, title) {
    var self = this;
    self.id = id;
    self.title = title;
  }
};

ko.applyBindings(new model());

The thing is that I want to display two instead of 2 in textbox, but at the same time this is a part of form which is supposed to be submitted and on form submission I'd like to submit 2 value as in real application it is java enum name.
Thanks and sorry if it the question is too messy.
Answer: sorry not positive what you are after but maybe something like this?
http://jsfiddle.net/LkqTU/31963/
js
function type(id, title) {
  var self = this;
  self.id = ko.observable(id);
  self.title = ko.observable(title);
};

var initialArray = [
  new type(1, 'one'),
  new type(2, 'two'),
  new type(3, 'three')
]

function model() {
  var self = this;

  self.types = ko.observableArray(initialArray);
  self.options = ko.observableArray(initialArray);
  self.selectedtype = ko.observable('');
  self.removeObject = function(p) {
    self.types.remove(p);
  }
  self.addObject = function() {
    self.types.push(new type(
      self.selectedtype().id(),
      self.selectedtype().title()));
  }
}

var mymodel = new model();

$(document).ready(function() {
  ko.applyBindings(mymodel);
});

html

    :
    <input type="text" data-bind="value: title" />
    <button data-bind="click: $parent.removeObject">

  -
  </button>

<select data-bind="options: options,
                       optionsText: 'title',
                       value: selectedtype,
                       optionsCaption: 'Choose...'"></select>
<button data-bind="click: addObject">+</button>

</button>

Knockout bind textbox to select text


Django server is not working on Virtual Server

Question: I have a server that is using Ubuntu. I have uploaded my Django project to the server. And ran the command:
python manage.py runserver 0.0.0.0:80
But when I try to go the website in browser I get The requested URL could not be retrieved error.
What can be the reason of that?
Comment: what is the result if you run : python manage.py runserver  without the ip and port ?
Comment: @DimitrisKougioumtzis The problem was that my internet provider blocked the IP address of  the housting provider so I just used VPN and everything worked pretty well
Answer: python manage.py runserver {YOUR_PUBLIC_IP}:80

Also you need to check firewall settings, make sure that 80 port is opened
Comment: Yeah! Thanks but the problem was that my internet provider blocked the IP address of  the housting provider so I just used VPN and everything worked pretty well :)


How can I generate a 2D matrix of natural numbers wth zero in ascending order in shell script or another programming language?

Question: I need to generate matrices of natural numbers in ascending order with zero (0), but they are very large ones and it will be hard to write them by hand.
What I want is to generate matrices like this:
0   1   2   3
4   5   6   7
8   9   10  11
12  13  14  15

How can I do that in shell script or another programming language.
Answer: In python:
print('\n'.join([' '.join([str(x*n+y) for y in range(0,k)]) for x in range(0,n)]))

Well, you might want to use tabulate or something to keep it aligned..
Answer: $ seq 0 15 | xargs -n4
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15

Use column for alignment:
$ seq 0 15 | xargs -n4 | column -t
0   1   2   3
4   5   6   7
8   9   10  11
12  13  14  15

Use with variable:
$ n=8 && seq 0 $((n*n-1)) | xargs -n$n
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63


Why do the tournaments have "place holder picks"?

Question: While watching the League of Legends tournament teams ban between 3-4 champions, you'll see picks like Eve, Xerath or someone very atypical of tournament play.
Someone will do this while the rest of the team goes serious picks. When they remake the game (which I also don't understand the perpose of) they do joke bans and inevitably the person with the Eve (or whichever) will pick someone else.
Why do they do this?
Comment: What tournament did you see that in, Os Snor? I've never seen that happen.
Comment: Because the player doesn't have the champion, but they want to hold it for someone else on their team. Why doesn't that player just pick it in the first place? To avoid being countered.
Comment: i have no idea what your talking about, and java's answer doesnt help any.
Comment: The tournament that was sponsored by arqade.
Answer: The order in which champions are picked is important. As an example, if you start by picking Katarina, the enemy might pick Blitzcrank, Soraka or any number of champions which can immediately shut her ult down. However, if you're last pick and the enemy doesn't have much hard CC, Katarina would be a safe pick!
In draft games players can swap champions after everyone has chosen one, so if your AP mid feels like Katarina might be a good choice but happens to be one of the first picks, s/he can choose a champion for a different role and defer the Katarina pick until it's too late for the enemy to react. But if the last pick on your team doesn't have Katarina s/he can't pick her and you won't be able to swap...
Well, tournament games aren't supposed to be about how many AP champions your support player owns! Your last pick player chooses a different (usually unpopular) champion and announces through chat which champion it really is. After picks are done in this fashion, the game is remade with everyone picking the champions they would have swapped to. In this case no one cares about bans as long as you don't ban anyone that was picked :)
You can also do this the other way around, having someone pick up a contested pick early on even if s/he doesn't own that champion.
Comment: i still dont get it.
Comment: @Ender In the initial draft stage, a player might want to pick a champion to swap to another player on his team. If s/he doesn't own that champion, s/he picks a placeholder and tells everyone what champion it is. After the remaining picks are done, the game is abandoned and a new one is created where everyone picks the champion they would have had after the swap.
Answer: First of all, let's clarify the question.  This situation will only happen during online tournaments.  During offline LAN events, players have infinite RP and IP as well as every champion purchased.  During online tournaments though, players use their standard LOL profiles.  As a result, there is a decent chance that some summoners will be missing heroes.  When that happens, a placeholder champion that never gets actual play like Eve is chosen instead and replaced with the intended hero later on.
As for why they don't just pick the heroes as soon as they are available? In the current meta, the top and middle lanes are solo lanes.  Since solo lanes are 1v1 battles, having to face an enemy who counters you can be too much to overcome.  As a result, teams try to pick these two lanes last, in order to avoid getting countered.
Comment: but if someone picks evelyn and then swaps her for the champion they wanted evelyn is still on the team roster...
Comment: Ender, there are normally two games.  The first is in Draft mode for picks.  After that, the game is recreated with the champions that everyone meant to pick.   Since the game is recreated, the placeholder Eve doesn't actually need to be picked.
Comment: how is the game recreated? why? when did this become prevalent? is there somewhere I can go to learn about this?
Comment: Ender:

1) The game is recreated by the players leaving the game and creating another one.
2) Recreating the game allows everyone to pick the champion they will be playing according to the bans in the previous game.
3) It became prevalent when players started playing custom games either to scrimage each other or to participate in online competetive events. These custom games have limitations (such as champion availability) that offline games on dedicated servers do not.
4) This behavior is generated by player customs, not dictated by Riot rules.  So no.
Answer: They use this placeholder mainly because the player does not have a certain champion. They switch champions to counterpick so not every player gets their own champion. They will switch at the end. As I saw on a stream yesterday Player 4 did not have shyvana, so they used eve as a placeholder. Then the team sayst he name of the champion they want in chat to the other team. After that they will just pick serious picks. Then they restard and they will do everything again but now everyone will pick the champion he wants. This will not occur in soloqueue and ranked :P.


Edit Crontab File of Remote System Hard Drive

Question: I have attached the HD from another machine as /temp_volume.
I would like to edit the root user's crontab on the attached hard drive. As I understand it the crontab file is located in /temp_volume/var/spool/cron/crontabs/root.
After I have edited the crontab file, I plan to put the HD back in the other machine and turn it on. I do not want the other machine to start up with the crontab "as is". Otherwise, I would just log into that machine and run "crontab -e" as root.
Is it acceptable to edit this file with "vim" or any other standard text editor to update the attached drive's root crontab?
Answer: Check that /temp_volume/var/spool/cron/crontabs/root exists. On modern Ubuntu systems, root's crontab is in /etc/crontab (/temp_volume/etc/crontab in your case) and has a different format. See man 5 crontab.


Outputting data to an NSString from a plist

Question: I'm extracting some string data from a plist:
<dict>
<key>Feb 7, 2000</key>
<array>
    <string>7</string>
    <string>8</string>
</array>
<key>Jan 27, 2001</key>
<array>
    <string>8</string>
    <string>7</string>
</array>

and using the following code to output the data in a UILabel:
  NSString * myString = [NSString stringWithFormat:@"%@",self.data];

    myLabel.text = myString;

the output is being displayed as ( 7, 8)
does anyone know how i might go about removing the parenthesis and comma. and also separating the values so I could display something like first: 7 second: 8
Answer: Example:
<dict>
<key>Feb 7, 2000</key>
<array>
    <string>7</string>
    <string>8</string>
</array>
<key>Jan 27, 2001</key>
<array>
    <string>8</string>
    <string>7</string>
</array>
</dict>

Code:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

for(id key in dict) {
    NSLog(@"First:%@ Second:%@", [[dict objectForKey:key] objectAtIndex:0],  [[dict objectForKey:key] objectAtIndex:1]);
}

Output:
First:7 Second:8
First:8 Second:7

EDIT (response to comment)
First you need to determine the keys within the NSMutableDictionary.
Load the .plist file, loop through and add the keys to an NSMutableArray.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
NSMutableArray *keys = [[NSMutableArray alloc] init];
for(id key in dict) [keys addObject:[NSString stringWithFormat:@"%@",key]];

Make sure the array can be accessed by the UIPickerView.
The UIPickerView should be able to retrieve the keys like this:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    return [keys objectAtIndex:row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    return [keys count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}

Finally, update the UILabel like this:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    theLabel.text = [NSString stringWithFormat:@"First:%@ Second:%@",
                      [[dict objectForKey:[keys objectAtIndex:row]] objectAtIndex:0],
                      [[dict objectForKey:[keys objectAtIndex:row]] objectAtIndex:1]];
}

The UIPickerView now contains the following rows:
Feb 7, 2000
Jan 27, 2001

When for example "Jan 27, 2001" is selected, the UILabel shows:
First:8 Second:7

Comment: quick question. that outputs every single string value. how would i go about outputting just the string values for just one particular key. the key in this case would be one selected in a UIPicker. thanks again.


[FireDAC][Phys][SQLite] ERROR: near "(": syntax error

Question: I encountered this problem when moving the query to FireDAC Query
SELECT row_number() OVER (ORDER BY Men7a_Row) AS RowNum,
       Nom_Prénom,
       Compte AS [Compte::Varchar(10)],
       Men7a_Value,
       Men7a_Date
  FROM R1
 WHERE Men7a_Date BETWEEN :DS AND :DF
 LIMIT 25 OFFSET 25;

Line problem
row_number() OVER (ORDER BY Men7a_Row)
Error
[FireDAC][Phys][SQLite] ERROR: near "(": syntax error.
Comment: Probably your version of SQLite is not 3.25+ when window functions were introduced.
Comment: SQLite version 3.33
Comment: The query is working correctly in SQliteStudio
Comment: Run `select sqlite_version()` and check the result in your app, not in SQLiteStudio.
Comment: I set it in FireDAC Query From Delphi app
Answer: I had the same issue.
In my case I was running a 32-bit program and had to change the EngineLinkage property in the FDPhysSQLiteDriverLink component to slDynamic and reference a 32-bit version of sqlite3.dll in the VendorLib property of that same FD component.
After that, no more syntax errors!!!
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Syscall/sysenter on LLVM

Question: How do I write the LLVM bitcode required to emit an architecture-specific system call instruction?
More specifically, clang supports inline assembly, and clearly supports emitting system calls (otherwise libc and vdso could not be compiled).  How does the translation work for this, and how can I tickle it to reproduce this behavior?
I understand LLVM itself may not understand the calling interface and register schedule used by various architectures in a sufficiently high-level manner to be expressed in LLVM bytecode (e.g. that may be filled in elsewhere).  However, there's clearly a stage where this information can be added.
How do I do this, starting at whatever stage comes after "C source with inline assembly"?
A satisfactory answer would include an example of how to invoke a five-argument int 0x80 system call.  I choose five since that requires spilling to the stack, and I choose int 0x80 since it's easily understood and on the most common platform.
Comment: In LLVM assembly ("bitcode") an inline assembly statement is represented as a call instruction that "calls" an inline assembly expression (which is a string containing the "arch-specifc" assembly instruction(s), plus constraints and a couple of flags). There's no other representation of "arch-specific" assembly within a function, and you can easily generate an example of this using inline assembly in C. So I don't see the point of your question.
Comment: Is there no relevant open source example you can study?
Comment: Why not use inline assembly to make system calls?
Comment: Chris: No, not that I've found.
Comment: Ross: It's an excercise in LLVM's flexibility for code generation.

Rather than "C with inline assembly", I'm looking for "LLVM bitcode with inline assembly".

At some point in the transformation of "C with inline assembly" to "assembled machine code", there must be an intermediate stage with both LLVM bitcode **and** arch-specific assembly.

I'm looking for an example of this, specifically with an `int 0x80` and setting appropriate registers.
Comment: Well, any example how to do it quickly and correctly would be great.
Answer: Posting an answer here since exa has put up a bounty.
I realized this was somewhat a silly question to ask after Ross Ridge's comments, and some playing around with clang.
Let's assume we have the following program, which uses inline assembly to directly call write().
#include <stdio.h>
int main(void)
{
    char *buf = "test\n";
    ssize_t n;
    asm volatile (
        "movl $0x00000002, %%edi\n"  /* first argument == stderr */
        "movl $0x00000006, %%edx\n"  /* third argument == number of bytes */
        "movl $1, %%eax\n"  /* syscall number == write on amd64 linux */
        "syscall\n"
        : "=A"(n)         /* %rax: return value */
        : "S"(buf));      /* %rsi: second argument == address of data to write */
    return n;
}

We can compile this with either gcc or clang and get roughly the same result.
$ gcc -o syscall.gcc syscall.c
$ clang -o syscall.clang syscall.c
$ ./syscall.gcc
test
$ ./syscall.clang
test

If we wish to see the exact LLVM instructions which would be used to emit this code, we can simply use the -emit-llvm flag.  As you can see, there is a call i64 asm sideeffect line which has the full inline assembly string.
$ clang -S -emit-llvm syscall.c
$ cat syscall.ll
; ModuleID = 'syscall.c'
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-pc-linux-gnu"

@.str = private unnamed_addr constant [6 x i8] c"test\0A\00", align 1

; Function Attrs: nounwind uwtable
define i32 @main() #0 {
  %1 = alloca i32, align 4
  %buf = alloca i8*, align 8
  %n = alloca i64, align 8
  store i32 0, i32* %1
  store i8* getelementptr inbounds ([6 x i8]* @.str, i32 0, i32 0), i8** %buf, align 8
  %2 = load i8** %buf, align 8
  %3 = call i64 asm sideeffect "movl $$0x00000002, %edi\0Amovl $$0x00000006, %edx\0Amovl $$1, %eax\0Asyscall\0A", "=A,{si},~{dirflag},~{fpsr},~{flags}"(i8* %2) #1, !srcloc !1
  store i64 %3, i64* %n, align 8
  %4 = load i64* %n, align 8
  %5 = trunc i64 %4 to i32
  ret i32 %5
}

attributes #0 = { nounwind uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { nounwind }

!llvm.ident = !{!0}

!0 = metadata !{metadata !"Ubuntu clang version 3.5-1ubuntu1 (trunk) (based on LLVM 3.5)"}
!1 = metadata !{i32 134, i32 197, i32 259, i32 312}

Comment: Seems right. I didn't realize I can use clang to get the demo with correct answer :]

Syscall/sysenter on LLVM


How to pass implicit parameters

Question: I am not sure if this is the right way to ask the question, but here it goes.
I have a class say
class T_shape(Shape):
    def __init__(self, center):
         coords = [Point(center.x - 1, center.y),
                   Point(center.x,     center.y),
                   Point(center.x + 1, center.y),
                   Point(center.x,     center.y + 1)]
    Shape.__init__(self, coords, 'yellow')
    self.center_block = self.blocks[1]

This class has been coded by someone else, I just wanted to ask what would be the right way to pass the parameters. Center is this case is tuple like (3,4). But when I try to pass it directly in this manner, it says 'tuple' object has no attribute 'x'.
Any help would be appreciated.
Comment: Could pass a [collections.namedtuple](http://docs.python.org/3/library/collections.html#collections.namedtuple) (in lieu of any other documentation that indicates what to do...)
Answer: I am not sure what kind of object center is, or T_shape constructor is expecting?
But you can achieve with namedtuple.
from collections import namedtuple
center = namedtuple('center', ['x', 'y'], verbose=True)
center = center(x=3,y=4)
t_shape = T_Shape(center)

How to pass implicit parameters


My cold water valve Seems to have a cap. Is this normal and how can I remove it?

Question: I'm in the process of connecting my washing machine but noticed that my cold water supply valve seems to have a cap on it. My hot water one doesn't. Is this normal? How can I remove this, it doesn't budge when I try to turn it.
Comment: Looks like a dust cover or maybe it had a drip so they used the cap to seal it off.
Comment: Maybe the hot water valve had one too and it fell off.  It looks like it's just for comfort.
Comment: It does not look like a washing machine valve and it appears to be under a cabinet.
Answer: It has ridges on it so try twisting it counterclockwise with some adjustable pliers or channellocks.
Comment: Yep  - it's just frozen w/ crud.   But -- do be sure the valve itself is closed before removing!


setcookie isn't working

Question: I see a lot of people have asked similar questions, so please forgive if I'm repeating but I couldn't find the answer in other posts.
This is just a test page, running on localhost. I have an HTML login page, sending form data to PHP script, which is checking details in a MySQL db. Playing with setting a cookie with results, but can't get it to work.
$user = $_POST['USER'];
$pass = $_POST['PASS'];

$res = $con->query("SELECT * FROM users WHERE username = '".$user."' AND password = '".$pass."'");
$row_no = $res->num_rows;
if ($row_no > 0) {
    $row = $res->fetch_assoc();
    $username = $row['username'];
    $password = $row['password'];

    setcookie('cookie1', $user, time() + 3600);

    if (isset($_COOKIE['cookie1'])) {
        echo "cookie set";
    }
    else {
        echo 'cookie not set';
    }

    echo "Hello " . $username . ', your password is ' . $password;
}
else {
    echo "Sorry, either your username or password is wrong";
}

I think I understand that the cookie isn't available on the page for which it is set, but even if I reload the page the $_COOKIE variable is empty.
The result of the isset part of the script is always 'cookie not set'. I have also tried setting the domain on the cookie to '/'.
Any help gratefully received.
(ps the MySQL part works fine)
Comment: Obligatory: Your code is vulnerable to [SQL injection](http://en.wikipedia.org/wiki/SQL_injection)
Comment: What happens if an user post it's password as: "";'delete from users;' ???
Comment: Your cookie life is only 1 hour.  Check to see if the server isn't 1 hour behind the client browser. See my post below for details.
Comment: Thanks for the injection reminders. This is a test page on localhost. I will of course sanitise if I make it live.
Answer: Doing something like
setcookie(...);
var_dump($_COOKIE[...]);

will always fail.
In it's default state on processing a user request the  $_COOKIE superglobal represents an array of data of all cookies sent from the browser along with the request.  The setcookie() function does nothing to alter this array for the request that is currently being processed.
It should however show up on the next request from the user.
If for some reason, you wanted your current request processing logic to "understand" that a cookie being sent back with the response headers has been set, you can manually set the value in the $_COOKIE array like:
setcookie(...);
$_COOKIE[...] = 'some value';
var_dump($_COOKIE);

You also need to verify that you have not sent any output to the browser before using setcookie().  If you are developing with display_errors on and error_reporting(E_ALL) you should see a warning.  Also you can look in basic web development tools for your browser to inspect the response headers to see if the cookie is being sent.
Comment: Thanks for the answer. I was actually reloading the same page to force a new request for the cookie. I changed the JS to redirect to another page on the domain and it began working. But your answer has given me a better understanding of why this is the case.
Answer: Also, check the time on the client and server.  Your server is setting the cookie to live an hour from the time it currently has.  Lifetime of cookies is determined by the client--the browser may be discarding the cookie immediately if the time on the client browser is more than an hour ahead of the server.   You can test this by setting the cookie significantly longer, like time() + 36000 (10 hours).
The cookie is available in the $_COOKIE array on the NEXT PAGE REQUESTED and NOT in the current page right after your setcookie() call.
Comment: I suppose using session variables would work, without rewriting his code much.
Comment: Op explicitly said, "_I think I understand that the cookie isn't available on the page for which it is set, but even if I reload the page the $_COOKIE variable is empty._"
Answer: The reason why this isn't working is because as Ray pointed out, the cookie is available on the next page requested. The reason for this is because the cookie information is transferred in the HTTP header. So your code is basically doing this:
-Hey, when I send this page to the user, tell him to create this cookie.
-(Before sending the page to the user) Hey, use the cookie that the user has.
But he doesn't have that cookie yet because you haven't sent the page to him (and therefore the HTTP header wasn't sent yet telling him to create the cookie)
Answer: Click here for PHP Documentation on setcookie();
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including  and  tags as well as any whitespace.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.
Answer: from http://php.net/manual/en/function.setcookie.php

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.

setcookie isn't working


error: cannot access KObject -- class file for kotlin.jvm.internal.KObject not found

Question: I am trying to integrate Kotlin with an existing java application.  So to test it i create a simple kotlin file and a unit test (in java), that will do something simple.  The purpose of the unit test is to ensure all the configure is correct and in fact i can call kotlin class from java.
This is where i get a little stuck, while executing the build using gradle, i get the following error:
<code>[ERROR] [system.err] Sample.class: warning: Cannot find annotation method 'name()' in type 'JetValueParameter'
[ERROR] [system.err] SampleTest.java:19: error: cannot access KObject
[ERROR] [system.err]         sample.setStatusCode(Sample.Status.OK);
[ERROR] [system.err]                                        ^
[ERROR] [system.err]   class file for kotlin.jvm.internal.KObject not found
[ERROR] [system.err] 1 error
[ERROR] [system.err] 24 warnings
</code>
I have the kotlin runtime on the classpath, i have also added in kotlin-jdk-annotations just for good measure.  I also have the kotlin plugin configured in gradle.
I'm hitting my head against a brick wall, it'd be a shame as i like kotlin as a replacement for java.  However this issue might scupper my plans.
Any help would be greatly appreciated!!!
Update:
Gradle build script:
<code>apply plugin: 'java'
apply plugin: 'kotlin'

sourceCompatibility = 1.7
version = '1.0'

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile "org.jetbrains.kotlin:kotlin-stdlib:0.9.976"
}
buildscript {
    ext.kotlin_version = '0.9.976'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:0.9.976"
        classpath 'org.jetbrains.kotlin:kotlin-stdlib:0.9.976'
    }
}
</code>
Java Version: 1.7.x
Kotlin version: 0.9.976
Gradle Version: 1.6
Comment: Post your build.gradle file, please.
Comment: Please share exact versions of Kotlin compiler, runtime and the Kotlin plugin for Gradle you are using. Also, please tell us how exactly you run your test. Any other configuration details would be appreciated as well.
Comment: Updated my question, to include the gradle script, kotlin, java and gradle versions.
Comment: Try adding `compileKotlin {kotlinOptions.annotations = file('annotations')}` to your build.gradle
Comment: @vzamanillo hasn't made any difference, i still get the warnings and error.
Answer: I figured out the issue, as we are using a convoluted gradle setup (it's loading 5 other scripts ;(), the gradle script wasn't adding the kotlin runtime to the path.  Once i fixed that it seems to work.


SSIS 2012 Error-Unable to connect to Integration Services

Question: I am facing the below Error when connecting to Integration Services from SSMS.I don't have SSIS 2005 installed,don't know what this error message is.
Please Help.
Connecting to the Integration Services service on the computer "localhost" failed with the following error:
"The specified service does not exist as an installed service.".
This error can occur when you try to connect to a SQL Server 2005 Integration Services service from the current version of the SQL Server tools.
Instead,add folders to the service configuration file to let the local Integration Services service manage packages on the SQL Server 2005 instance.
Comment: You need to establish if SSIS is running as a service.  You can verify this from either Admin Tools->Services or SQL Server Configuration Manager.
Comment: Any update on this? I'm running into this with SQL 2016 and SSMS 2017 (the only one available to download, no v16).
Answer: Are you connecting to SSIS from the local server or remotely?  The later SSMS versions (16.x and 17.x) will only connect to their respective versions. Microsoft is planning to retire this method in favor of the SSISDB, which is more secure.  Link to the official statement from Microsoft (in the note box).
If connecting remotely, you may need to setup DCOM permissions.  Browse to "grant permissions to the service" under the provided link.


Sql : How to calculate table values using formula

Question: Here is original Query :, it generates o/p with two columns name (label, count) :
label      count
Fails      1
Pass       3

and here is query I wrote which generates above data
select r.pname as resolution
,lb.label
,count(r.pname) as occurences
from issuelink
inner join jiraissue p on issuelink.source = p.id
inner join jiraissue c on issuelink.destination = c.id
inner join issuelinktype t on issuelink.linktype = t.id
inner join resolution r on c.resolution = r.id
inner join issuestatus istat on p.issuestatus = istat.sequence
inner join label lb on c.id = lb.issue
where t.linkname = 'jira_subtask_link'
and p.pkey in (@pkey)
and c.issuetype in ('13')
and r.pname not in ('Fails Smoke Test - General Failure', 'Fails Smoke Test - New Firmware Available')
and label in ('SmokeTest', 'fullcert', 'bfv', 'papercert')
group by r.pname;

As per your suggestion I tried using cross function, however its throwing an error of "please check syntax":
select  100.0 * fail.cnt / (fail.cnt + pass.cnt) as c
from    (
        select  r.pname as label
        ,       count(r.pname) as cnt
        from issuelink
        inner join jiraissue p on issuelink.source = p.id
        inner join jiraissue c on issuelink.destination = c.id
        inner join issuelinktype t on issuelink.linktype = t.id
        inner join resolution r on c.resolution = r.id
        inner join issuestatus istat on p.issuestatus = istat.sequence
        inner join label lb on c.id = lb.issue
        where t.linkname = 'jira_subtask_link'
        and p.pkey in ('SRPDTVTPV-3')
        and c.issuetype in ('13')
        and r.pname not in ('Fails Smoke Test - General Failure', 'Fails Smoke Test - New Firmware Available')
        and label in ('SmokeTest', 'fullcert', 'bfv', 'papercert')
        group by r.pname
        ) as fail
cross join
        (
        select  r.pname as label
        ,       count(r.pname) as cnt
        from issuelink
        inner join jiraissue p on issuelink.source = p.id
        inner join jiraissue c on issuelink.destination = c.id
        inner join issuelinktype t on issuelink.linktype = t.id
        inner join resolution r on c.resolution = r.id
        inner join issuestatus istat on p.issuestatus = istat.sequence
        inner join label lb on c.id = lb.issue
        where t.linkname = 'jira_subtask_link'
        and p.pkey in ('SRPDTVTPV-3')
        and c.issuetype in ('13')
        and r.pname not in ('Fails Smoke Test - General Failure', 'Fails Smoke Test - New Firmware Available')
        and label in ('SmokeTest', 'fullcert', 'bfv', 'papercert')

        group by r.pname
        ) as pass
where   fail.label = 'Fails Certification'
        and pass.label = 'Passes Certification'

Answer: Here's one way using a cross join:
select  100.0 * a.count / (a.count + b.count) as c
from    YourQuery a
cross join
        YourQuery b
where   a.label = 'a'
        and b.label = 'b'

Here's another approach using aggregates, a bit more tricky but only uses YourQuery once:
select  100.0 * cnt_a / (cnt_a + cnt_b) as c
from    (
        select  max(case when label = 'a' then count end) as cnt_a
        ,       max(case when label = 'b' then count end) as cnt_b
        from    YourQuery
        ) as SubQueryAlias

Comment: What do you mean by "header"?  Is it a leading row?  If so, what are your column names?  Perhaps you can show an example at [SQL Fiddle](http://sqlfiddle.com/)
Comment: Hi Andomar, label and count are headers of the o/p table, would that still work ?
Comment: my column names are label and count.
Comment: Ok that's what I guessed, this answer should work for that?  If it doesn't, please post an error or problem that occurs.
Comment: Getting error on sql syntax, editing question and pasting the query.
Comment: Pasted the query in the body of this page.
Comment: Looks like your just missing parenthesis `()`, I updated the query in your answer
Comment: Hi Andomar,It doesn't like .count on first line after 100.0 * 'Fails Certification', says "you have an error in your sql syntax......"
Comment: Ah ok, if you alias a table to `a` you've got to refer to it like `a`.  Updated query again.  Also renamed `count` to `cnt`, it's better to avoid using a keyword as a column name.


How can I fix a Core Image's CILanczosScaleTransform filter border artifact?

Question: I want to implement an image downscaling algorithm for iOS. After reading that Core Images's CILanczosScaleTransform was a great fit for it, I implemented it the following way:
public func resizeImage(_ image: UIImage, targetWidth: CGFloat) -> UIImage? {
    assert(targetWidth > 0.0)

    let scale = Double(targetWidth) / Double(image.size.width)

    guard let ciImage = CIImage(image: image) else {
        fatalError("Couldn't create CIImage from image in input")
    }

    guard let filter = CIFilter(name: "CILanczosScaleTransform") else {
        fatalError("The filter CILanczosScaleTransform is unavailable on this device.")
    }

    filter.setValue(ciImage, forKey: kCIInputImageKey)
    filter.setValue(scale, forKey: kCIInputScaleKey)

    guard let result = filter.outputImage else {
        fatalError("No output on filter.")
    }

    guard let cgImage = context.createCGImage(result, from: result.extent) else {
        fatalError("Couldn't create CG Image")
    }

    return UIImage(cgImage: cgImage)
}

It works well but I get a classic border artifact probably due to the pixel-neighborhood base of the algorithm. I couldn't find anything in Apple's doc about this. Is there something smarter than rendering a bigger image and then crop the border to solve this issue?
Answer: You can use imageByClampingToExtent.

Calling this method ... creates an image of infinite extent by repeating
  pixel colors from the edges of the original image.

You could use it like this:
...
guard let ciImage = CIImage(image: image)?.clampedToExtent() else {
    fatalError("Couldn't create CIImage from image in input")
}

See more information here: Apple Doc for clampedtoextent
Comment: That + some CGRect sizing done right (ie `floor`calls) = ✌ — Thanks @Stephan