string trimmer slits bottom screen door

Question: I live in a condo with a back doorwall, but no patio. The doorwall opens directly onto lawn.
In summer, the grounds crew comes through with a weed trimmer and (since no patio) trims right up the to house.
In doing so, they repeatedly cut a slit in the bottom of the screen door, allowing bugs and dirt to enter the house. I've repaired the screen twice, but they just cut through again.
Short of installing a patio that I probably won't use very much, is there any cheap way to fix/prevent this problem?
I've googled for this problem, but it returns no references at all. I find it hard to believe that I have encountered something completely unique.
Comment: Make them pay for the damaged screen? After a couple of times they might remember to stop doing it.
Comment: Add a couple of rows of pavers in front of the door? Take a 4" x 4' strip of hardware cloth, trim so the wires stick out of all four edges, bend wires 90°, push through bottom of screen from the outside, and then fold the wires all the way to hold the screen in place?
Answer: I solved a similar problem (cat scratching a low screen) by attaching a piece of clear acrylic plastic to the frame, just high enough to prevent damage, and still allowing ventilation through the upper part of the screen. I would guess 8 - 10 inches across the bottom would be sufficient to guard against string trimmers.
My frame was wood, so drilling some holes for screws was easy. Might be harder if you have aluminum. Also, the cut edge of the acrylic was not especially nice looking.
Answer: You could get a new door?

... but seriously, I think sending them the invoice for the repair is the more appropriate action.
Answer: A steel pet protector should be sufficient.  I would personally add a little edge to it to trim the weedeater lines if they get too close.
Answer: 1/8" or 1/4" hardware cloth (galvanized or stainless steel mesh, which a string trimmer can't cut - also a stock pet protection measure) over the screen.  Rather than the "poke through the edges of the screen" method suggested in the first comment, this is normally screwed right to the face of the door, with some trim, 12-18" high (or the bottom screen panel, depending on door design.)
But billing them for the negligent damages is still the correct thing.

string trimmer slits bottom screen door


Mixing component based design and the model-view(-controller) pattern

Question: 'm developing a 2D game and I want separate the game engine from the graphics.
I decided to use the model-view pattern in the following way: the game engine owns game's entities (EnemyModel, BulletModel, ExplosionModel) which implement interfaces (Enemy, Bullet, Explosion).
The View receives events when entities are created, getting the pointer to the interface: in this way the View can only use the interface methods (i.e. ask for informations to perform the drawing) and cannot change the object state. The View has its onw classes (EnemyView, BulletView, ExplosionView) which own pointers to the interfaces.
(There is also an event-base pattern involved so that the Model can notify the View about entity changes, since a pure query approach is impraticable but I wont' discuss it here).
*Model classes use a compile-time component approach: they use the boost::fusion library to store different state componets, like PositionComponent, HealthComponent and so on.
At present moment the View isn't aware of the component based design but only of the model-view part: to get the position of an enemy it calls the Enemy::get_xy() method. The EnemyModel, which implements the interface, forwards this call to the PositionComponent and returns the result.
Since the bullet has position too, I have to add the get_xy method to Bullet too. BulletModel uses then the same implementation as the EnemyModel class (i.e. it forwards the call).
This approch then leads to have a lot of duplicate code: interfaces have a lot of similar methods and *Model classes are full of forward-methods.
So I have basically two options:
1) Expose the compoment based design so that each component has an interface as well: the View can use this interface to directly query the component. It keeps the View and the Model separated, only at a component level instead of a entity level.
2) Abandon the model-view part and go for pure component based design: the View is just a component (the RenderableComponent part) which has basically full access to the game engine.
Based on your experience which approach would be best?
Answer: MVC isn't easy for games as when the game becomes larger (including menu, enemies, levels, GUI...) and transitions, it'll break.
Component or entity-system are pretty good for games.
As a simpler case for you, you may consider using a HMVC. You'll still have issues with transitions, but at least your code will be grouped together in a more clean manner. You probably want your tank's code (rendering and logic) to get close together.
Comment: HMVC is really just some bullshit made up by somebody who wanted to use inheritance to share lots of code and not have to rewrite or copy-and-paste stuff.  Otherwise I agree on your remarks about entity-based systems being well-suited for games.  Games need to handle interrupts such as the features offered in UnRealScript that allow the programmer to say "do this every 2 real-world seconds" sort of interrupts.  For a formal treatment of interrupts, read Graham Hutton's What is the meaning of all these interruptions? (for Haskell).
Comment: If HMVC only reduces duplicated code, it's already good. It's good, in my point of view, only for components (or something that behaves like a component you could drop in a UI without further work). A strict HMVC (passing only via controllers) is pretty much like having multiple MVC projects.
Comment: I think this is simply a matter of technical misinterpretation on your behalf.  The original HMVC description does not use passing only via controllers.  The major difference between HMVC and PAC is that in PAC you pass only via controllers, and views and models cannot talk directly to one another.  I also think it is conceptually wrong to say HMVC "is pretty much like having multiple MVC projects", since reuse of domain knowledge cannot be had for free.  Real-world systems are not composable for free, and can have deadlocks, livelocks, service interrupts interfering with real-time specs, etc.
Comment: To be clear, what I am objecting to is system control hierarchies that only exist to reuse code.  This is especially true if you hijack a code reuse mechanism like OO inheritance, because then your generalization/specialization relationships are tightly coupled to your reuse patterns and not your problem domain. Since GUIs are extremely fungible systems and do not have stable definitions for what they represent, other than meta-things, you can't use inheritance in a reliable way. Trying to will lead to Open-Closed Principle violation and breaking class invariants. Use logic programming instead
Comment: I agree. HMVC isn't probably best for such anyway (PAC/strict HMVC or lose HMVC). PS: You may be interested in [immediate mode GUI](http://mollyrocket.com/861) (sure it's GameDev).
Comment: I've seen immediate mode GUI presentation before. Thanks.
Answer: I'll give my two cents worth. From the problem you're describing, it seems to me that you need an abstract class that will do the operations that are common amongst all of your classes (like the get_xy, which should apply to bullet, enemy, explosion, etc.). This class is a game entity that does the basic grunt work. Inheriting classes can override it if they want.
This abstract class should be the core of all your interfaces (luckily you're in C++ where there is no physical difference between a class, and abstract class and an interface). Thus the Views will know about the specific interfaces, and still have the generic entity methods.
A rule of thumb I have for design - if more than one class has the same data members or methods, it should probably be a single class from which they inherit.
Anyway, exposing the internal structure of your Model classes is not a good idea. Say you'll want to replace boost with something else? You'd have to re-write the entire program, not just the relevant parts.
Answer: There have been presentation architectures designed especially for agent-based systems, such as Presentation-Abstraction-Control.  The hard part in designing such a system is that you ultimately end up hardwiring sequences of collaborations between the agents.
You can do this, but don't use OO inheritance to model the message passing hierarchy.  You will regret it.  If you think about it, you are really not interested in using the OO inheritance relationship, since the interfaces defined are really just a "Record of functions" that the object can respond to.  In that case, you are better off formally modeling your communication protocol.
If you have questions, please ask -- this is not an obvious solution and easy to get wrong.
Comment: Can you provide me some good links about the PAC?

Also, I can undersstand the tip about avoiding inheritance. As a matter of fact I'm not using that in the View part.
Comment: Wikipedia has the first search hit for "Presentation-Abstraction-Control" [1], and it has an extensive References section. See the first paper listed, by Joëlle Coutaz, and at [2] you can get a free copy of the paper.  [1] http://en.wikipedia.org/wiki/Presentation-abstraction-control [2] http://iihm.imag.fr/publs/1987/Interact87.PAC.pdf
Comment: I forgot to mention that you might want to have a look at Croquet and Alan Kay's Croquet Consortium.  Unfortunately the demo is no longer available online as I recall.  But the ideas are pertinent.  (Alan invented the laptop and coined the term "object-oriented programming", and is a Turing Award winner.)


Login to WinApi C# using Angular

Question: I get this error when I send Post. Do you know what I have to do? Login to WinApi C#

XMLHttpRequest cannot load http://localhost:56305/Token. Response to
  preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:64757' is therefore not allowed
  access. The response had HTTP status code 400.

My code
<code>//linki
    $scope.addLink = "http://localhost:56305/Token";

    $scope.addData = function () {
        if ($scope.password != "" && $scope.email) {
            $http({
                method: "POST",
                url: $scope.addLink,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                headers: {'X-Requested-With' :'XMLHttpRequest'},
                data: { grant_type: 'password', username: $scope.email, Password: $scope.password }
            }).then(function mySucces(response) {
                $scope.stateHideError = true;
                $scope.stateHideSuccess = false;
                Authorization.go('carInsurance');
            }, function myError(response) {
                $scope.stateHideError = false;
                $scope.stateHideSuccess = true;
                $scope.error = "Wystąpił błąd - Problem z wysłaniem parametrów";
            });
        }
        else {
            $scope.stateHideError = false;
            $scope.stateHideSuccess = true;
            $scope.error = "Wystąpił błąd - nie podałeś wszystkich wymaganych wartości.";
        }
    };
</code>
PtrScn

I would like send something like this

I added this to WinApi C#
<code>    <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*"/>
        </customHeaders>
    </httpProtocol>
</code>
and now I have this error

XMLHttpRequest cannot load http://localhost:56305/Token. Response for
  preflight has invalid HTTP status code 400
Answer: This is a sample article, how to enable CORS
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Your server rejects requests from your js application,because your js is loaded from different URL

Login to WinApi C# using Angular


Getters and Setters in AngularJS

Question: confirm("Ohhh, hello there, is it Ok to click Cancel?");

I think that this is, basically, a question about CRUD on Angular. I'm kind of confused about getters and setters, mainly because Angular do almost all the job in getting and setting things because of its two way data binding. I want to know what's the best scalable way to create getters and setters so I wont need to modify my functions in the future.
On the first Arrangement, I'm trying to be as simple as I can be, but I feel uncomfortable in getting and getting to set.
Arrangement 01:
$scope.getData = function(){
  $http.get(url + '/data')
  .then( function (res) {
    return res.data; } );
};

$scope.setData = function () {
  $scope.data = $scope.getData();
};

$scope.insertData = function (data) {
  $http.post(url + '/data', { data: data})
  .then( function (res) {
    // nothing here. } );
};

On this second Arrangement, however, I'm trying to go directly where I need to. When I fetch data from the server, I'm automagicaly setting my $scope.data to the retrieved data;
Arrangement 02:
$scope.getData = function () {
  $http.get(url + '/data')
  .then( function (res) {
    $scope.data = res.data;
  });
};

$scope.insertData = function (data) {
  $http.post( url + '/data', { data: data })
  .then( function (res) {
    $scope.getData(); //To update.
    //OR $scope.data.push(res.data);
  });
};

Looking further, I've found this on the Angular Docs, but what's the point in using a getter/setter if Angular already do it? Looking into  other technologies, it's hard to compare, because Angular has auto-get.
I don't even know how to formulate this question. But, basically, I want to know how could my getters and setters harm my future application and if there's a good way and why to create getters and setters in Angular.
Thanks for any advice.
Comment: Services is the answer. Use the `.factory({});`
Comment: Thanks, @AliGajani . How would it help? I don't want to auto-create functions, I want to know the best practices.
Answer: You good practice is to wrap your logic into Service. You have to know that in Angular, all services are Singleton, there is only a single instance of a Service.
I've made a simple example, by using $q.defer() which is the promise manager from the deferred API.
$q.defer() get 2 methods :

resolve(value) : which resolve our associated promise, by giving her the final value
reject(reason) : which resolve an promise error.

Controller
(function(){

function Controller($scope, $q, Service) {

  //Use promise manager
  var defer = $q.defer();
  ///Create our promise
  var promise = defer.promise;

  $scope.data = [];

  var newData = [
    {
      name:'john',
      age: 25
    },
    {
      name: 'toto',
      age: 13
    }
  ];

  Service.get().then(function(data){
    //Retrieve our data
    $scope.data = data;

    //Set new data to our factory
    Service.set(newData);

    //Retrieve new data
    Service.get().then(function(data){
      //Resolve new data
      defer.resolve(data);
    });

  });

  //Retrieve new dataset
  promise.then(function(data){
    $scope.data = data;
  })

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

Service
(function(){

  function Service($q){

    var data = [0,1,2,3,4];

    function set(value){
      data = value;
    }

    function get(){
      return $q(function(resolve){
        //Simulate latency
        setTimeout(function(){
          //Resolve our data
          resolve(data);
        }, 1000);
      });
    }

    return {
      get: get,
      set: set
    };

  }

  angular
    .module('app')
    .factory('Service', Service);

})();

HTML

{{data}}

So, you can set some data by using the service, and retrieve it when you want. Don't forget that service is singleton.
You can see the Working Plunker
Comment: Thank you, @Paul Boutes, you've shown the technical aspects. I'll strength my studies on promises and services so I can better understand your code. But, in the theoretical way, you helped me a lot. Thanks!
Answer: In JavaScript you typcially don't use getters and setters like in OOP languages, especially because you do not have a notion of privateness (so anyone can access your fields). ES5 has getters and setters, but it also adds this missing capabilities of hiding implementation details. In case you want getters and setters for additional logic in your AngularJS app, you could simply define additional fields which are updated using $watch.
Furthermore you solution with sending an HTTP request on every change is a it of an overhead if you do this per field. What you instead to is writing directly to fields.
While e.g. WPF/C# requires you to define setters to raise OnPropertyChanged, you don't need this in AngularJS. Everything that you write in AngularJS will automatically trigger a so-called $digest cycle, where it checks for changes that have been made. It will then automagically update your user interface, give that you use template bindings or ng-model directives.
Comment: In the application, I'm 'getting' and 'setting' every template change and after every change that needs the DOM to be updated. So, @Darneas , I should forgot the OOP and focus on the Event orienteds?
Comment: @RodrigoSouza: I updated my answer. You should do away with OOP in JavaScript. Not that it breaks things, but you add complexity without getting anything from it. All benefits of doing getters and setters in OOP are not present in JavaScript, so everything that remains is very complex code for simple tasks ;-).
Comment: This made me feel better. A friend of mine looked at my code and said 'why aren't you using getters and setters?', I said 'Well, it's too complex', but then he talked about complexity and scalability. So, I can use my getters to fetch data from the server and bind it to the local Scope objects without doing any bad thing to my maintainability of code?
Comment: Now you are getting to a esoteric question. Maintainable code is code, which is well understood and can adapt easily to changing demands. AngularJS might at the beginning look very magic to you, but this is normal. Adding artifical complexity to it, in order to "make it understandable" helps nothing. A reader has to learn Angular and should cope with that. And for these advanced Angular developers, getter and setters are only unnecessary complexity..
Comment: You made your point pretty solid, @Darneas. And I do like it!  "A reader has to learn Angular and should cope with that", I loved this! Thank you a lot.
Answer: If you think like pure Javascript, is basic the same logic, what angular does is create modules for you to use the best practice, so it is easy to use them.
function DataService($http) {
  this.get = function() {
    return $http.get(...);
  }

  this.create = function(newData) {
    return $http.post(...);
  }

  ..
}

and using angular, like Ali Gajani sayd, you basically can do this,
angular.module('myApp').service('DataService', ['$http', DataService]);

or with a factory style
function DataService($http) {
  var myPrivateVariable = "something";

  function get() {
    return $http.get(...);
  }
  ...

  // expose them public
  return {
    get: get
  };
}

angular.module('myApp').factory('DataService', ['$http', DataService]);

Comment: Well, thank you, @Guilherme. I'll combine all your answers. :)

Getters and Setters in AngularJS


How can I replace delay() by millis()?

Question: After a while, I get my final result I want but I can't use delay because I need different time for different strip, so I need to replace delay() by millis() in this code:
#include <FastLED.h>
#define NUM_LEDS1 10
#define NUM_LEDS2 6
#define DATA_PIN1 6
#define DATA_PIN2 7
CRGB leds1[NUM_LEDS1];
CRGB leds2[NUM_LEDS2];

void setup() {
  FastLED.addLeds<NEOPIXEL, DATA_PIN1>(leds1, NUM_LEDS1);
  FastLED.addLeds<NEOPIXEL, DATA_PIN2>(leds2, NUM_LEDS2);
}

int dot_delay1[ ] = { 100,200,300,400,500,600,700,800,900,1000 };
int dot_delay2[ ] = { 100,200,300,400,500,600 };

void loop() {
  for(int dot = 0; dot < NUM_LEDS1; dot++)
    for(int dot = 0; dot < NUM_LEDS2; dot++)
    {
      leds1[dot] = CRGB::Blue;
      leds2[dot] = CRGB::Blue;
      FastLED.show();
      leds1[dot] = CRGB::Black;
      leds2[dot] = CRGB::Black;
      delay( dot_delay1[ dot ] );
      // this is where I need to put the second delay,
      // but I can't put more then 1 delay.
      // I need to refactor my code with millis() function instead of delay()
    }
}

Comment: Specify the used language in the tags.
Comment: @AlexanderPetrov Thanks is my first post here :)
Answer: You can use non-blocking code patterns, which are executed in special frequencies or times. In the following, I give you an short example how you can replace a delay(1000) and a delay(5000) without blocking the main loop. In addition, you can check stackoverflow for similar posts (e.g. Pause without Delay() arduino).
// 1 sec. frequency
unsigned long interval=1000;    // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.

// 5 sec. frequency
unsigned long interval1=5000;    // the time we need to wait
unsigned long previousMillis1=0; // millis() returns an unsigned long.

void setup() {
   //...
}

void loop() {

 // other CMD's...

 // replace delay(1000)
 if ((unsigned long)(millis() - previousMillis) >= interval) {
    previousMillis = millis();
    // every first second
    // ...
 }

 // other CMD's...

 // replace delay(5000)
 if ((unsigned long)(millis() - previousMillis1) >= interval1) {
    previousMillis1 = millis();
    // every fifth second
    // ...
 }

 // other CMD's...
}

Comment: like you see in my first code example i have a `int dot_delay1[ ] = { 100,200,300,400,500,600,700,800,900,1000 };` is for 10 delay for the same strip ( and the strip have 10 pixel so 10 delay value) anyway clue how to do this for millis()? how to make a multiple `millis(100,200,300)` like my example?
Answer: I see you're using NeoPixels! It just so happens that Adafruit has some great tutorials on using millis() and micros() for timing purposes instead of delay(). They also include good material on interrupts, if you're feeling ambitious and want to separate your timing from your main function entirely (a worthwhile undertaking, if you have the time and resources).
Part 1 (basics of using millis()):
https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview
Part 2 (introduces interrupts):
https://learn.adafruit.com/multi-tasking-the-arduino-part-2/overview
Part 3 (puts everything together):
https://learn.adafruit.com/multi-tasking-the-arduino-part-3/overview

Edit 1:
Alright, I edited your code, adding in a loop that checks for both delay periods to be done using millis(). I attempted to stick to the variable naming conventions that you've been using, for easy readability. There were also some other issues with your code syntax that I cleaned up. Make sure to effectively comment your code so that it's understandable, for yourself and for others!
Hopefully this works the way you want it to!
/*The goal of the sketch is to run multiple strip where each dot could be
controlled on/off one after the others but with different times on/off between each
pixel on each strip. All be independent and separate and automated and structured
already like FastLED library recommendation.*/

// Library include
#include <FastLED.h>

#define NUM_LEDS1 10
#define NUM_LEDS2 6

// Define pin (each strip be connected on)
#define DATA_PIN1 5
#define DATA_PIN2 6

// Declare some strip name and attribute (number of led per strip)
CRGB leds1[NUM_LEDS1];
CRGB leds2[NUM_LEDS2];

void setup() {
  FastLED.addLeds<NEOPIXEL, DATA_PIN1>(leds1, NUM_LEDS1);
  FastLED.addLeds<NEOPIXEL, DATA_PIN2>(leds2, NUM_LEDS2);
}

int dot_delay1[] = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
int dot_delay2[] = {100, 200, 300, 400, 500, 600};

void loop() {
  for (int dot1 = 0; dot1 < NUM_LEDS1; dot1++) {
    for (int dot2 = 0; dot2 < NUM_LEDS2; dot2++) {
      // LED turns blue
      leds1[dot1] = CRGB::Blue;
      leds2[dot2] = CRGB::Blue;
      // Show LED status
      FastLED.show();
      // LED turns black
      leds1[dot1] = CRGB::Black;
      leds2[dot2] = CRGB::Black;
      // Create timing variables
      unsigned long previousMillis = millis();
      unsigned long currentMillis = millis();
      // Create boolean variables to monitor if the delays have triggered yet
      bool delayFlag1 = false, delayFlag2 = false;
      // Loop continuously
      while (1) {
        currentMillis = millis();
        // If the first delay time has passed, delayFlag1 is true
        if ((unsigned long)(millis() - previousMillis) >= dot_delay1[dot1]) {
          delayFlag1 = true;
        }
        // If the second delay time has passed, delayFlag2 is true
        if ((unsigned long)(millis() - previousMillis) >= dot_delay2[dot2]) {
          delayFlag2 = true;
        }
        // If both delay times have passed (both delay flags are true), exit while loop
        if ((delayFlag1 && delayFlag2) == true) {
          break;
        }
      }
    }
  }
}

This new code should work, I've tested it and it works as expected on my machine.
As a side note, your original question was "How can I replace delay() by millis()?". This question has been answered both by myself and by the previous answer author, user3704293. In the future it may be helpful to separate your questions to get higher quality answers and to better serve those who are searching for answers to the same questions. Once your question is answered, as I hope this question is now, you should accept the answer that is the best for you.
Let me know if it all works out!

Edit 2:
To have LEDs change independently of each other, replace the loop() function in the previous code with this one.
void loop() {
  // Create timing variable
  unsigned long previousMillis = millis();
  // Loop through all LEDs
  for (int dot = 0; dot < NUM_LEDS1; dot++) {
    // If the first delay time has passed, change first LED strip
    if ((unsigned long)(millis() - previousMillis) >= dot_delay1[dot1]) {
      leds1[dot - 1] = CRGB::Black;
      leds1[dot] = CRGB::Blue;
    }
    // If the second delay time has passed, change second LED strip
    if ((unsigned long)(millis() - previousMillis) >= dot_delay2[dot2]) {
      leds2[dot - 1] = CRGB::Black;
      leds2[dot] = CRGB::Blue;
    }
    // Show LEDs
    FastLED.show();
  }
  // Turn last LED Black
  leds1[9] = CRGB::Black;
}

Comment: Yes is like 2 weeks now i check all this tutorial...but feel lost cause iam not native coder and i try to fix my code allready uphere.
Comment: @FrançoisEricKing I'll edit my post and attempt to figure out a solution to your promises, give me a little while. I haven't personally used NeoPixels, so I'll do my best, but no promises! It would also help if you clarified exactly what the "second delay" would be used for.
Comment: The second delay is the serie of delay for the.second strip led :)
Comment: Thanks for the clarification, let me know if the code I posted works for you.
Comment: i test it wow thanks  but is not work. First pixel of each strip going to blue but nothing more. here is a pastebin of you code and i put more detail in comment inside the file... maybe that help to understand. http://pastebin.com/d9SW62du
Comment: The answer is edited and should work for you now. Please consider my written comments at the end of the answer.
Comment: thanks for reply. I tested the new corrected code and is not work like expected. delay/milles 1 is look ''linked'' to delay/millis 2 array...both array delay need to be completely indepandant and without any interaction on each other. Is look like if i change value in dot_delay1, dot_delay2 (or strip2) have changing delay too. I try to figure out what is linked and fork something for completely indepandant control on each strip...not i relation or linked :) Thanks
Comment: Sorry it's not working the way you wanted. If this answer is sufficient for your original question, please accept it. I also posted some code that makes the LEDs behave how you want them to. I added this in a new edit because the original code may be useful for someone searching for the answer to your original question. The best thing to do in the future is ask individual questions about each question / problem you have. As you can see, I've answered a number of your questions here :) Welcome to Stack Overflow!

How can I replace delay() by millis()?


Can I recover my lost R&D materials?

Question: There isn't much documentation on this game since it came out recently but does anyone know if I can recover lost R&D materials if I kill my past self? Also can I recover them if I am two generations from that hater?
Basically this was the situation:

Lvl 7 me (character A) had a bunch of R&D materials
I died and didn't have the credits to use the revive service (had already used the free one)
Got a new character (character B) and that one died almost immediately

Can I still recover the lost materials from Character A with my Character C (current instance).
I am sure it was probably mentioned in the tutorial messages but I skimmed most of those.
Answer: Yes you can, earn more kill coins and buy back character A. Do it before character A is killed as a hater and lost forever, though.

Can I recover my lost R&D materials?


How to redirect everyone from my website apart from me?

Question: Basically, all I want to know is what is in the title of this question:
RewriteBase /

RewriteEngine On
RewriteBase /
RewriteCond %{REMOTE_HOST} !^22.214.171.124
RewriteCond %{REQUEST_URI} !/www.mywebsite.site10.net/Stuff/randomfile.html\.html$
RewriteRule .* http://www.google.com [R=302,L]

126.96.36.199 being my IP address
Comment: does the redirection page have to be a html? or can i redirect them to Google.com?
Comment: The system I have at the moment works, but the website is being used to host data that other people have uploaded. I want to allow only ME to view the data on the website but I want people to be able a program I made (keylogger etc) and upload information from their computer to my website, but only I can view it. How could I edit it to do that?
Answer: Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_HOST} !^xxx\.xxx\.xxx\.xxx
RewriteRule \.html$ /anotherPage.html [R=302,L]

where xxx.xxx.xxx.xxx is your ip and anotherPage.html is the redirection page.
This is a 302 moved temporarily redirection http://en.wikipedia.org/wiki/HTTP_302


I installed nativescript but tns command isn't running on mac

Question: I installed a native script without a problem. But try to create a new project it can't find tns command.

firstname.lastname@example.com postinstall
  /Users/turgut/.npm-global/lib/node_modules/nativescript

node postinstall.js

Autocompletion is already enabled
Installation successful. You are good to go. Connect with us on
  http://twitter.com/NativeScript.
You have successfully installed the NativeScript CLI! To create a new
  project, you use: tns create
To build your project locally you use: tns build
NOTE: Local builds require additional setup of your environment. You
  can find more information here:
  https://docs.nativescript.org/start/quick-setup
To build your project in the cloud you can use: tns cloud build

NOTE: Cloud builds require Telerik account. You can find more
  information here:
  https://docs.nativescript.org/sidekick/intro/requirements
If you want to experiment with NativeScript in your browser, try the
  Playground: https://play.nativescript.org
If you have any questions, check Stack Overflow:
  https://stackoverflow.com/questions/tagged/nativescript and our public
  Slack channel: https://nativescriptcommunity.slack.com/

firstname.lastname@example.com updated 67 packages in 6.648s

By the way, when I first installed it. It can find the command but when I restart the mac this problem pop upped. I already out text it ->

Installation successful. You are good to go. Connect with us on
  http://twitter.com/NativeScript.
You have successfully installed the NativeScript CLI! To create a new
  project, you use: tns create
To build your project locally you use: tns build

what is the problem here?
Comment: i couldn't solve it. and then I start writing react native. much more easier.... @Pramod
Comment: Did you solve it? I am facing this issue.
Answer: Are you using nvm?
If so, in your terminal, first check whether nativescript has been installed for the version of node you are using:
nvm ls
You should see an arrow pointing to the current version of Node in use.
Now navigate to ~/.nvm/versions/node/ and select the current version of node you are using. Next, bury down into lib/node_modules you should see the nativescript folder in here.
If not, you may have installed nativescript to another node version. Check the other versions node_modules further to find out which it was installed to.
Once you've figured this, simply tell nvm to use that version of node:
nvm use {version}
followed by
tns --version
to check the install status of nativescript.
Answer: you need to add the path to your system variables


Appropriate grounding of small mobile network rack

Question: I am building a small (6U) self-contained networking rack in an enclosed case which will accept only power and coax from the residence. The only external connections on the rack are an IEC C14 inlet and an F-type coax connector.
Inside the rack case, I have various pieces of equipment like a UPS, PDU, and patch panel, which all have grounding terminal screws on the back. My plan is to bond them together with the rack rails functioning as a bonding busbar, and finally to ground the bonding system using the ground conductor on the C14 inlet.
Based on my understanding of the design and intent of these systems, this will ensure that if a short occurs with the rack case or any of the cases of the bonded equipment inside of the rack, this voltage will have a safe path to the building's electrical service panel via the wall receptacle ground. (Be assured I will test continuity between all parts of the bonded system.)
Have I correctly interpreted the best approach to grounding for this build, given that the finished case is not to be installed in locations where a separate building ground system will be available? Or is have I misunderstood everything and it would actually be safer to not bond or ground any of the equipment in the rack beyond their regular 3-prong grounded power cables?
Answer: Yes, that's correct.
What you Really don't want is for a device to have a hot-ground fault... and then, the chassis of that device is now floating at 120VAC from ground.  And because it's in a rack, the chassis of all the other devices are floating too.  And then you touch anything, and BLAM!
But if you are using UL listed* equipment (as you should), this should all be done for you by the equipment.

* or competitor NRTL, such as CSA or ETL.
Answer: Are mechanical bonds required for proper grounding or safety of rack mounted equipment that is connected with  3 wire (grounded)connections?
The bonding of the exterior case in this case is more of a shielding than a safety.
Most rack mounted systems have faraday shielding this is to block the radio frequency interference not as a safety.
My most recent example of this was a properly grounded system that was picking up noise from the adjacent rack mounted equipment to the point it delayed the opening of a surgery suite that had been completely remodeled it is powered by a UPS (very clean power) the mfg added shielding to the device and this eliminated +90% of the electrical noise the bonding was the same the only change was the shielding that was added.
So the bonding of rack mounted equipment is not so much a safety for electrical shorts but to prevent or reduce the emissions or reception of radio frequency interference.
Comment: You can get shielded racks, but common racks are *not* shielded, and bonding is **only** to ensure equipotential.
Comment: @vidarlo, all equipment must meet FCC guidelines for emissions, however with multiple pieces of equipment mounted in close proximity the shielding is needed it has nothing to do with electrical safety , but many internet only electricians do not have the background to understand this , thus the reason I provided the real life example.
Comment: Stop it. Go look up some [more or less random rack cabinet](https://download.schneider-electric.com/files?p_Doc_Ref=SPD_JKUR-8YXQTQ_EN). There's not a ***single*** mention of noise in the manual - but there's plenty of references to safety earth. And yes, I *do* work with instrumentation, I know a thing or two about noise. As I said shielded racks *do* exist - but the primary role of the normal stamped metal cabinets is holding servers, not providing shielding.
Comment: As a pro I see this very issue and provided an example , but you can blindly follow , I guess the reason why licensed electricians don't hang around, just saying!
Comment: Yes, you claimed that the bonding was to provide shielding, ***not*** safety. Sorry, that is plain wrong. As shown in the manual the ***main*** function according to manufacturer is safety; equipotential bonding. Furthermore, ad hominem attacks that is plain wrong leaves something to be desired. For what it's worth, I'm certainly what would be considered professional in the electrical trade as well. So far, you've not backed up the claims of your answer; only attacked me.
Comment: Let's compare state certified electrical license's , you state I am wrong , parallel grounding paths is a code violation the frame grounding is for RFI.
Comment: Sigh. It's not parallel grounding paths. It's equipotential bonding of exposed metal parts. It's not RFI; the *manual* states it's protective earth. To provide RFI dampening, metal gaskets would be far more effective. So far, you've repeated your claim that it's *mainly* for shielding purposes. Furthermore, the world is *bigger* than the US.
Comment: All I'm asking is that you provide some references to substantiate your claim that the bonding is *primarily* to provide EM shielding, as you in your question state *Most rack mounted systems have faraday shielding this is to block the radio frequency interference not as a safety.* - which in my opinion could be borderline *dangerous* assumption.
Answer: Presuming you're in the US where it is possible to have non-grounded power sockets, I would suggest:

hard-wiring the input lead to the rack case, and to a 3 pin US style plug that cannot be removed.

clearly label the outside that a 3 pin earthed supply is required for reliable functioning of the unit

Add the same information into any paperwork/documents/agreements.

You still can't stop some end user from cutting the plug off and wiring on a new one, using a ground-stopping adapter, or some other shennanigans, but you're now on a better footing if they do.
Naturally you'll use 3 pin grounded connections inside the case and have it all secured down against vibration.  Also put a good tamper-evident seal on any access panels.


Consistent Flash Player Crash ONLY on YouTube

Question: It could be similar to one of the bugs listed on LaunchPad (#689158), but may not be.  Basically, I used to occasionally get a crash on YouTube and opening a new browser or rebooting (don't remember which) took care of the problem.  However, now, EVERY time I try to open a video on YouTube, I get the frowning  block and the message, "The Adobe Flash plugin has crashed."  However, Hulu would also call for Adobe, right?  But I can see videos there.
Comment: You don't even need a flash player to use youtube! You just need a browser thst can handle html5! Btw flash isn't that great, html is the future! :)
Comment: This question should instead be filed as a bug report, thanks! [Instructions here](http://askubuntu.com/questions/5121/how-do-i-report-a-bug).
Answer: An alternative would be to use Minitube
Its a Flash Free Youtube Player.
It has a nice UI and works well on older systems
Answer: Solution can be found at http://www.bwebcentral.com/cms/drupal/node/6560
basically you turn off hardware acceleration in the Adobe Settings.

Go to: http://www.youtube.com/my_speed#
Find the "Show Test Video" and follow the link. A video should come up.
Right Click the Video Window. A dialog should appear.
Click: "Settings...". A small window opens.
At the bottom of this window you will find icons. click the first icon on the left.
Uncheck "enable hardware acceleration."
That's it.

More info here: hxxp://ubuntuforums.org/showthread.php?t=1699227


Black screen when trying to run the liveCD or install on an Acer 5742z

Question: Since the 11.04 version, on live CD or on a instalation Ubuntu doesn't work. I install it, or launch the live cd and the screen is all black, no image. I know ubuntu its runing but the screen is still black and I don't know how to fix it.
I have an Acer 5742z.
Answer: I've had lots of issues with different hardware on the new installers. I find a lot are linked to ACPI/APIC.
Try starting the installation with the boot options modified to disable APIC first (apic=off), and then if unsuccessful, ACPI (acpi=off).
Check this article for more info.


what's a good way to get file size?

Question: In our customized C# logging system, we use streamWriter = File.CreateText(fileNameStr); to create a file and open a stream for write.
Now we want to monitor the file size to see if it reach the max required size. What I did is the following:

create a FileInfo object for about file: currFileInfo = new FileInfo(fileNameStr);
get file size after each write: curFileInfo.Refresh(); fileSize = curFileInfo.Length;
compare the file size with max file size, if bigger, close the current one and create a new file.

I have print out to see how long it will take to refresh the FileInfo, many times it will take about 15msec.
So I am thinking there may be a better way to do this. what's your suggestion?
Comment: Most of the common logging frameworks support this functionality out the box, preferable to trying to write it yourself IMO.
Answer: This should work:
streamWriter.BaseStream.Position;

This should contain the current position of the stream and if you're using it for appending only, this should contain the correct file size.
Answer: FileSystemWatcher fsw=new FileSystemWatcher(filePath);
fsw.NotifyFilter=NotifyFilters.Size;
fsw.Filter="fileName";
fsw.Changed += new FileSystemEventHandler(YourHandler);
fsw.EnableRaisingEvents = True;

Comment: +1 Good idea, but you should mention what this code does and how. It's a different from 5yrs' approach in that it creates a monitor which will fire events. So the approach here is event driven as opposed to a polling system that the OP started with.

what's a good way to get file size?


I need some alias for the $ to JQ in Jquery

Question: I need to use JQ instead of using $ for my jquery code.
For example my current code in Jquery is:
  $('.addbutton').click(function () {
      if ($('#ddlList option:selected').val() != null) {
         //Do something
      }
  });

and I want it to work as:
JQ('.addbutton').click(function () {
      if (JQ('#ddlList option:selected').val() != null) {
         //Do something
      }
  });

Is it possible? how I can achieve this thing?
Answer: You can use the noConflict() version if you want - If you have another library which also used $ to refer the core library
var JQ = jQuery.noConflict()

If you want a simple alias and is not worried about any other libraries then you can simple use
var JQ = jQuery;

Add this after jQuery library is included

Comment: Where to add this statement? In every page where I want to use jquery?
Comment: @BhaveshKachhadiya just after the jQuery library is included
Comment: @AnupPJohny Do we use $ and JQ both in
Comment: if you use `noConflict` the `$` will no longer refer to jQuery so you won't be able to refer to jQuery using `$`
Answer: Use noConflict()
var JQ = jQuery.noConflict()

Answer: Use the noConflict method with a true parameter. That will restore everything in the global scope as it was before jQuery was loaded, and return a reference to the jQuery object. As long as you choose a unique name for the identifier that you want to use, jQuery won't conflict with anything:
var JQ = jQuery.noConflict(true);

To use jQuery with any other library, do it in this order to make it free of conflicts:
1. Include your other library.
2. Include jQuery.
3. Use the code above.


Is there a framewok / API I could use to export iPhone-SDK's ABRecordRef instances to vCard?

Question: I'm looking at source code from Funambol, but the dependencies are so huge, I'm rethinking of using them, not to mention the code is based on OC++. Can anyone help me out on this?
Thanks.
Answer: No, afraid not.
You can either try to find a library / sample code in C/C++/ObjC that will generate a vCard from provided information, or attempt to roll your own.
You can find more information about vCard including the specs here; http://www.imc.org/pdi/


In firefox, when a select has position and a z-index, why do change events not fire on tab?

Question: Looking for any information on why a change event would fire on a  without position or z-index, and why it wouldn't fire if those styles do exist. This problem occurs in Firefox only.
Change event does not fire on tab
<select style="position: relative; z-index:1"><option>1</option><option>2</option></select>

Change event does not fire on tab
<select><option>1</option><option>2</option>

Change event sample code (using jQuery
$('select').on('change', function(e){ console.log(e.type) });

Please see this CodePen for a working example.
Comment: Ahh, yeah, that was my first comment... `Is it possibly your browser?` Yeah, I'm using Chrome. ... So my bad for not reading the specification in the title, but it's worth noting that those specifications should ALSO be put in the body of the question, and optimally, relevant tags should be added.
Comment: It works for me. When I hit `tab` it prints `blur` on both respectively. Is it possibly your browser? BTW, the code in your post is invalid - you mean `...z-index: 1;"`
Comment: @slime select elements naturally can be tabbed to without tabindex, I dont believe that is relevant to the problem
Comment: Found this https://bugzilla.mozilla.org/show_bug.cgi?id=126379... looking for more. I'm using 33.1.1.
Comment: Both work fine and your code isn't valid.
Comment: NOTE: the issue is only observed when using the keyboard to change the select.
Comment: @philtune - I updated that sample code, it being invalid does not effect the outcome, take a look at the Codepen. As the title mentions - the "change" event does not fire in the second case - I am aware the "blur" event does.
Comment: @philtune are you using firefox? The change event does not fire on the second box for me when: focusing the select, pressing down, pressing tab.
Comment: I don't think `z-index` would have to do anything with this issue.
Comment: @A.Wolff the title clearly states firefox =)
Comment: If you're anticipating tab usage, why not use the tabindex attribute?
Comment: @philtune copy that - will do in the future.
Comment: Hmm, now I'm getting the issue on BOTH select elements in Firefox. Can't get either to work using the up/down arrows. Well crap... I just now realized all my form applications with `select` have the same issue in Firefox. They've been QA'd, so I wonder if this is a bug with a newer version. I'm glad you posted this then!
Comment: @philtune interesting. What version of FF are you using? I still see the behavior on FF34 Mac. Are you pressing tab after using the up/down arrows?
Comment: Both sides are behaving exactly the same for me in Firefox, but when using the keyboard to go between the options, the change is not fired, not until you hit enter on the option you just selected.
Comment: What is the purpose of this CSS rule: `.rel select:focus {...}` I mean why setting it?
Comment: This looks like it's a "won'tfix": https://bugzilla.mozilla.org/show_bug.cgi?id=110800... they say it's not *supposed* to fire on arrow clicks. (though this is super old, so not sure if it's still relevant)
Comment: @philtune It should when input loses focus
Comment: @philtune I am not expecting it to fire when you press arrow, but when you press tab after pressing arrow - the left example **does** fire a change event on FF34 Mac (for me)
Comment: @A.Wolff Fair question. This is a reduced test case of a problem I'm seeing where a select element has a "focus" state with a large dropshadow. When a select is focused without the z-index, the dropshadow can be clipped by sibling elements in some cases. This is neither here nor there in regards to this bug - but there's the context anyway =)
Comment: OIC, well then I'm back to "it works for me" on FF. Hitting `tab` on either seems to fire the blur. Your event (`e.type`) is "blur" and that's what it's printing.
Comment: @philtune Again we're looking for the change event, not blur. And "e" would be _any_ event that takes place on the select.
Comment: @Greg If i remove `position: relative;` from this CSS rule `.rel select:focus {...}` it works as expected for me on FF
Comment: I think it's a faulty assumption that tabbing = change event. It fires when it's truly changed, not when it loses focus. I'm FF34 on Windows here and it works exactly as it's expected to.
Comment: @A.Wolff yes exactly - the question is why does removing relative cause it to work.
Comment: @slime I hear you - but tabbing does work in the left instance to select (at least for me an some others)
Comment: Doh, i'm must be tired, sorry to make you lose so much time answering useless comment, i should read better question, my bad, again...
Answer: It appears this problem can be resolved by setting position before the select receives focus, like so:
select { position: relative; }
select:focus { z-index: 1; }

I would still be curious if anyone has insight into why this happens when changing the position of the select on :focus


Emberjs model not fully loaded before afterModel being fired

Question: I have an action that retrieves some data from the DB and then I wanted to check that the data it have received is correct before it continues on with authentication. I am using invite codes to allow people to log into a public site that is for private corporate use only. I am able to get the data just fine, but the aftermodel is firing before the request is completed. I am making a call to an azure mobile service and the call is still in pending (according to chrome) when the aftermodel is firing off. Seems like it hasn't received the data at that point.
What is the best method to get this verification working properly? Once it verifies it would then allow them to log in with an external provider.
Answer: Please, look at this discussion: Ember authentication best practices?
If you don't need an Auth engine, then you could implement "verifying data" in beforeModel hook. Why beforeModel? Because if data is not correct, then app should redirect user to another page, and beforeModel is made for this logic: http://emberjs.com/guides/routing/preventing-and-retrying-transitions/#toc_aborting-transitions-within-code-model-code-code-beforemodel-code-code-aftermodel-code
Comment: I am verifying this against an invite code that is housed in a table in azure mobile services. How can I validate the invite token this way? I thought beforemodel was triggered before the query would happen.
Comment: In beforeModel: 1. Abort transition. 2. Call verifying API by ajax. 3. If success, then transition.retry (redirect to other route otherwise).


JSON and reference

Question: I receive data as a JSON object, like this:
[{"transid":1091, "payee":"McDonalds", "amount":-549},
 {"transid":1092, "payee":"McDonalds", "amount":-342},
 {"transid":1093, "payee":"McDonalds", "amount":371}]

I know I can access the data like this:
alert(obj[0].amount);

But I would like to be able to access the data like this:
obj[transid].amount

where transid is a previously declared and assigned variable, like this:
var transid = 1091;
alert(obj[transid].amount);  //returns -549

If this is even possible, I assume the JSON object would have to be restructured (I don't have any control over how I receive the JSON object), but I don't really have any idea how to go about this.  I've tried Googling and SOing, but I am just not sure what to look for.
Edit: I've looked at the proposed duplicate question as suggested by Travis J, and I do not agree that this is a duplicate.  I'm not asking to loop through data.  I'm asking for methods to reference by a specific index, given JSON that I don't control how it comes to me.  The accepted answer in the proposed duplicate shows how I envision the code to look (in the second code box), but I don't think it really answers my question.  Another answer in the proposed duplicate, posted by Hakan Bilgin, suggests using defiantjs, which would probably work.  However, there are many other methods, some of which have been provided as answers to this question already.
Comment: This question is not exactly about simply finding things in JavaScript objects, but about a **syntax** for doing so. There are reasonably interesting approaches to making things work like the OP suggests, including both some preprocessing but also things like object proxies, which are not addressed by the supposed duplicate. Should re-open.
Comment: Travis J's answer to the duplicate question (currently 2nd, not accepted) has a brute force search method. It looks pretty well made, but the asker is interested in getting data sorted by index. The duplicate question's top answer covers what to do with indexed data, but not how to convert. [This question](http://stackoverflow.com/questions/4215737/) has some code for a starting point, but not an exact duplicate by any means. Voting to reopen.
Comment: @bruno and ekuusela: Thanks for the responses.  I wish I could mark both as accepted answers!  I like the .filter method better than the .forEach method, but so far this is only because I don't yet know the overhead of either solution.  Let's say I have 100000 elements.  Which would have less of a time impact?  Restructuring the 100000 elements then accessing the data directly, as per ekuusela, or filtering the data as per bruno?  I'll test later when I get home, but I appreciate both answers.  I'll accept one later.
Answer: You can use filter like
obj.filter(function(o){
    return o['transid'] === 1091;
})[0].amount // -549

You can add the above function to Array's prototype like
Array.prototype.get = function(id){
    return Array.prototype.filter.call(this,function(obj){
        return obj['transid'] === id;
    })[0].amount
}

And use it like
obj.get(1091); // -549

It is up to you to add proper validation like dealing with not found keys and duplicates.
Comment: As written, this throws an exception if the caller asks for a transid that isn't in the collection. Otherwise, this is the easiest method.
Comment: `filter` keeps iterating even after the correct object is found. You might want to use `some` instead so you can break the loop.
Comment: @bruno, thanks for the reply.  I followed the lead from ekuusela's comment above about `.some`.  My understanding from reading is that `.some` returns true/false, which I don't think would work with your answer.  However, using the `.find` polyfill, I think that works as intended.  Thanks!
Comment: with `some`, you'd have to assign the found value to some other variable and use that instead of the return value of `some`. Using `find` is better if you have the polyfill. `var result; a.some(function(e) { if (e.id === id) { result = e; return true; }});`
Answer: You can create a new object from that one. Something like this

var transactionArray = [
  {"transid":1091, "payee":"McDonalds", "amount":-549},
  {"transid":1092, "payee":"McDonalds", "amount":-342},
  {"transid":1093, "payee":"McDonalds", "amount":371}
];

var transactionsById = {};
transactionArray.forEach(function(element) {
    transactionsById[element.transid] = element;
});

var transid = 1091;
alert(transactionsById[transid].amount); //returns -549

Where transactionArray is what you refer to as obj in your question.
Comment: This is what the asker needed that wasn't in the duplicate question. +1
Comment: Thanks for the help on this.  I've played with both your and Bruno's answer.  Yours does provide me the syntactical solution I sought.  I do, however, like the `Array.prototype` solution (I ended up using `.find` instead of `.filter`).  So I will have to feel it out more... which cake do I choose?  Chocolate with chocolate sprinkles, or triple chocolate with no sprinkles?

JSON and reference


In Java how can I figure out how many of a certain letter appears in a string with recursion?

Question: So I need to use recursive programming to figure out how many times a certain letter appears in a word. For example, the word "complete" would have 2 e's. I kind of know what I need to do but I am just not sure how to do it. I currently have a scanner set up to take the word from the user, but that is all I have coded at the moment. I feel like the pseudocode should be something like;
Take word from user
if (letter <= 0)
return 1;
else
 return length of characters in word
I am guessing that I use the length or charAt method somehow?
I really need some guidance here, like how does the recursion come in? Is that because it breaks down the word until it finds the amount of "e's" remaining? Would the base case be 0?I really appreciate the help! I am really new to this. Thank you very much.
Comment: The number of the occurrences of 'x' in a string is 1 or 0 plus the number of occurrences of 'x' in that string without the first character. Try working with that. P.S. An empty string has exactly zero such occurrences.
Comment: Hint: The base case should be empty string or single character. Then think about how you would do it manually for one more character than that. Generalize to one more than N. Turn that into code. (This is not a good place to use recursion, by the way; it's a problem much more easily solved with simple iteration.)
Answer: You'll need to use substring and charAt. Here's the pseudocode:
CountLetter(string, letter)
1. if string.length() == 0 then return 0
2. if string.charAt(0) == letter then
3.     return CountLetters(string.substring(1), letter) + 1
4. else then return CountLetter(string, letter)

Basically, recursive calls should use smaller versions of the string.
Comment: Thank you very much! Substring makes more sense to me. Appreciate it.
Answer: Since this is homework, I'll give you hints. Think of it this way:
num_occurrence(char, str) = num_occurrence(char, str[0]) + num_occurrence(char, str[1:])

Now think of what you can do meaningfully in the following cases:

num_occurrence(char, str) where str is an empty string. Can you return a meaningful value for the number of occurrences of char in an empty string?
num_occurrence(char, str) where str is a single letter. What value would you return in this case? It depends on what the character is inside str, right?
num_occurrence(char, str) where str has more than one character. Can you break this down in terms of the above cases?
Comment: Thank you for the help, appreciated!
Answer: Instance of doing this with a recursive method, assuming you store the word in a String word variable :
String word //(your word)

public int howMany(char c, String word) {
    // stop condition
    if(word.length == 0) {
        return 0;
    }

    if(word.charAr(index) == c) {
      return 1 + howMany(c, word.substring(1, word.length));
    }
    else {
      return 0 + howMany(c, word.substring(1, word.length));
    }
}

The trick is to call the method with the world without its first letter, and do it again, and again, until there is no more letter.
Comment: "The trick is to call the method with the world without its first letter, and do it again, and again, until there is no more letter." That really clicked!! Thank you!
Comment: btw: the simplest / most appreciated way to say "thank you" here is to upvote useful answers (and to accept one if applicable)
Answer: Here's what you can do:
   public static void main( String[] args ) {

        String myString = "Your test string here...";

        List< Character > alreadyDone = new ArrayList< Character >( );

        for ( Character myChar: myString.toCharArray( ) ) {

            if ( alreadyDone.contains( myChar ) ) {
                continue;
            }

            System.out.println( myChar + ": " + getCount( myString, myChar ) );
            alreadyDone.add( myChar );
        }

    }

    // recursive method to calculate the occurrence of a character in a string

    private static int getCount( String string, char myChar ) {

        if ( string.length( ) == 0 ) {
            return 0;
        }

        if ( string.charAt( 0 ) == myChar ) {
            return 1 + getCount( string.substring( 1 ), myChar );
        }

        return getCount( string.substring( 1 ), myChar );
    }

Comment: Thank you for the help! This makes more sense now :)
Answer: The pseudocode probably should be more like this:

If the word is empty, return 0
If the first letter is an 'e', return 1 + the number of 'e's in the rest of the word
Otherwise, return the number of 'e's in the rest of the word.

In Java, you get the rest of the word with word.substring(1). This method of counting is quite inefficient but ok for the purpose of learning recursion.
Comment: Thanks for the guidance! Substring - that is exactly what I was needing :)


Collecting files based on excel data

Question: I routinely create lists of p/n's. I need to order for my business in excel. Once I figure out what I need, I then have to manually collect all of said files, so I can attach them to an email to send out for a quote.
Is there a way to automatically search for, and collect the files, I need based on the list I create in Excel? Also, I collect two file types (.dxf and .pdf).
Answer: Define the files path in AttachmentPath as an array.
Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory.
Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network).

Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM

Function SendCDOMail(sTo As String, sSubject As String, sBody As String, _
                     Optional sBCC As Variant, Optional AttachmentPath As Variant)
    On Error GoTo Error_Handler
    Dim objCDOMsg       As Object

    Set objCDOMsg = CreateObject("CDO.Message")

    'CDO Configuration
    With objCDOMsg.Configuration.Fields
        '
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort
        'Server port (typically 25, 587)
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        'SMTP server IP or Name
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.hitterslongrun.com"
        'Type of authentication, NONE, Basic (Base64 encoded), NTLM
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
        'SMTP Account User ID
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "firstname.lastname@example.com"
        'SMTP Account Password
        .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "Uhdje!@@0#"
        'Use SSL for the connection (False or True)
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
        .Update
    End With

    'CDO Message
    objCDOMsg.Subject = sSubject
    objCDOMsg.From = "firstname.lastname@example.com"
    objCDOMsg.To = sTo
    objCDOMsg.TextBody = sBody
    ' Add attachments to the message.
    If Not IsMissing(AttachmentPath) Then
        If IsArray(AttachmentPath) Then
            For i = LBound(AttachmentPath) To UBound(AttachmentPath)
                If AttachmentPath(i) <> "" And AttachmentPath(i) <> "False" Then
                    objCDOMsg.AddAttachment AttachmentPath(i)
                End If
            Next i
        Else
            If AttachmentPath <> "" And AttachmentPath(i) <> "False" Then
                objCDOMsg.AddAttachmentAttachmentPath
            End If
        End If
    End If
    objCDOMsg.Send

Error_Handler_Exit:
    On Error Resume Next
    Set objCDOMsg = Nothing
    Exit Function

Error_Handler:
    MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: SendCDOMail" & vbCrLf & _
           "Error Description: " & Err.Description, _
           vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

Reff www.devhut.net/

Collecting files based on excel data


What is this wooden sheet behind my drywall?

Question: I bought a home recently which was built in 2004.
I installed a TV mount on a stud and I am now trying to run cable behind drywall, but when I cut through my drywall I found wood sheet behind my drywall. What is that for? Can I cut through that wood?
As shown in the picture, the TV is mounted on a stud and stud finder is also attached to that stud for reference.
Comment: Hello, and welcome to Stack Exchange. Any idea if this is across the whole wall? What's behind the wall? If you tap at various locations, does it sound different? I see a couple of holes; how thick is the wood?
Comment: I don't think it's uncommon for structure design to include such panels to provide additional shear strength in strategic locations. One wall supporting my stairwell has same.
Comment: It looks like it is all across the wall. it is really thin wood sheet., may be 1/2-1".
But behind and above that wall there is a staircase. May be it is support for that.
Is it safe to cut across that support wall or should I avoid it?
Comment: If it is chipboard and between 1/2-1" thick then you should be able to screw the tv mount (depending on final weight) directly through the drywall into the chipboard. But as you have screwd it throughinto the stud work, it wont be going anywhere. When you make the hole in the chipboard make sure it is smaller than the drywall, it will make it easier to repair later as you have something to bond on to.
Answer: It's undoubtedly a shear wall to resist lateral loads, especially if you live in a "high wind" area or a seismically active area.
It could also be a reinforced wall for shelving.
Yes, you can cut through it, or cut openings in it, whether it's a shear wall or not. I would not make an opening more than 1/4 the height of the wall and not more than square shaped...don't make it a large rectangle. Also, I'd install framing members at the edge of the opening. (If it's a load bearing wall, you'll need to install a header.)


Understanding npm install command of Tailwind CSS for React

Question: Consider this npm command from the Tailwind docs:
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

So there is tailwindcss@npm:@tailwindcss/postcss7-compat and @tailwindcss/postcss7-compat. What is the difference between them? What do the double points in tailwindcss@npm:@tailwindcss/postcss7-compat mean?
Answer: @tailwindcss/postcss7-compat is the stand-alone TailwindCSS package with compatibility with PostCSS 7.
tailwindcss@npm:@tailwindcss/postcss7-compat is used to alias @tailwindcss/postcss7-compat as tailwindcss, meaning @tailwindcss/postcss7-compat will now be referenced as tailwindcss everywhere in the project.
From npm documentation:

npm install <alias>@npm:<name>
Install a package under a custom alias. Allows multiple versions of a same-name package side-by-side, more convenient import names for packages with otherwise long ones, and using git forks replacements or forked npm packages as replacements. Aliasing works only on your project and does not rename packages in transitive dependencies. Aliases should follow the naming conventions stated in validate-npm-package-name.


Unable to install Skype despite following earlier thread(s)

Question: I have been bashing my head against a wall with this one; despite having trawled several relevant threads and asked in freenode, I'm still stuck.
The following thread is the closest to my issue:
Can't install Skype 4.3 on Ubuntu 14.04 64 bit
Gave a 14.04 64-bit system to my dad but haven't been able to get skype running for him. The libqtwebkit4 one is given as the problem, but it is already installed - I've checked. I've also run all of the instructions in the linked thread to no avail. Partner repositories are enabled, but I can't install from apt-get either.
nothing@computer:/home/Shared$ sudo dpkg -i skype-install.deb
Selecting previously unselected package skype.
(Reading database ... 234518 files and directories currently installed.)
Preparing to unpack skype-install.deb ...
Unpacking skype (18.104.22.168-1) ...
dpkg: dependency problems prevent configuration of skype:
 skype depends on libqtwebkit4 (>= 2.1.0~2011week13).

dpkg: error processing package skype (--install):
 dependency problems - leaving unconfigured
Processing triggers for mime-support (3.54ubuntu1.1) ...
Processing triggers for gnome-menus (3.10.1-0ubuntu2) ...
Processing triggers for desktop-file-utils (0.22-1ubuntu1) ...
Processing triggers for bamfdaemon (0.5.1+14.04.20140409-0ubuntu1) ...
Rebuilding /usr/share/applications/bamf-2.index...
Processing triggers for hicolor-icon-theme (0.13-1) ...
Errors were encountered while processing:
 skype
nothing@computer:/home/Shared$

Halp?
Comment: Try running `sudo apt-get install -f` to install missing dependencies. How do you know libqtwebkit4 is installed?
Comment: Already did that, it removes the package without errors, but I'm still unable to install, I get the same libqtwebkit error.

I know libqtwebkit4 is installed because if I try to install it the response 'libqtwebkit4 is already the newest version'.
Comment: Where did you get that `skype-install.deb` file? The best way to install Skype on Ubuntu is to enable Canonical Partners and then install it the usual way, which on the command line would be: `sudo apt install skype` (https://help.ubuntu.com/lts/ubuntu-help/addremove-sources.html#canonical-partner)
Comment: As in the linked thread I got it via "wget -O skype-install.deb http://www.skype.com/go/getskype-linux-deb", but I have also tried with "sudo apt-get install skype" to no avail.
Answer: Try this:
sudo apt-get purge skype*
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install skype

Comment: sudo apt-get install skype
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies.
 skype : Depends: skype-bin
E: Unable to correct problems, you have held broken packages.
Comment: @user339367: Did you enable Canonical Partners? What if you run: `sudo apt install skype skype-bin` (try apt instead of apt-get, somtimes it's 'smarter')


How to obtain errors in Yii

Question: I've got Yii-based site, the system I don't know originally and it came to me from other man and there's "Error 500 Trying to get property of non-object"
I read a ton of literature regarding logging errors in Yii, but nothing seems to work for me. Here's what I have in main.php for logging:
<code>'log' => array(
    'class' => 'CLogRouter',
    'routes' => array(
        array(
            'class' => 'CFileLogRoute',
            'enabled' => true,
            'categories' => 'system.*',
            'levels'=>'error, warning, trace, profile, info',
            'showInFireBug' => true
        ),
    ),
),
</code>
the thing is, the domain hosting error log doesn't have errors in it (while it has all the time for other sites, having troubles).
I tried enabling php errors through .htaccess, I tried doing it in main.php - nothing works.
Please help - how can I see the errors in more details and finally fix them in Yii?..
Comment: please post screen of the error page
Answer: Add this on your main.php file to show error logs. Then the Application Log will be  shown below in every page.
<code>'log' => array(
 'class' => 'CLogRouter',
 'routes' => array(
    array(
        'class' => 'CFileLogRoute',
        'levels' => 'trace, info, error, warning,
  vardump',
     ),
    // uncomment the following to show log
 messages on web pages
    array(
        'class' => 'CWebLogRoute',
        'enabled' => YII_DEBUG,
        'levels' => 'error, warning, trace, notice',
        'categories' => 'application',
        'showInFireBug' => false,
      ),
   ),
),
</code>
Edit:
Here you have to consider that Yii writes logs after the main script is ended, So if you terminate your script using die() command, you never let Yii write it down. To avoid such problems you should terminate the script using Yii::app()->end() command.
See More:
http://www.yiiframework.com/doc/guide/1.1/en/topics.logging#message-routing
Comment: unfortunately this doesn't help :(
Comment: Can you make a try after changing the categories to 'categories'=>'system.db.*', On CWebLogRoute class
Comment: sorry, doesn't help too :(
Comment: I feel like I will have to look through all the code to find out whether we have 'die' there after the person did the site..

How to obtain errors in Yii


.NET - Which system assemblies are annotated for nullable reference types?

Question: I'm trying to find the status of .NET system assemblies regarding the nullable reference types feature of C# 8.
Non-annotated code, or code written with earlier language versions will be treated as "null-oblivious", meaning the compiler won't generate any warnings regarding nullability.
This is really annoying when it comes to using system assemblies from a nullable enabled context, as there's no way to tell if null-checking is required or not.
Is there any way to check if an assembly is annotated for nullable reference types?
Or is there some official status page about this?
Answer: In VS 16.10, you should be able to see whether nullability was enabled in an external assembly by using go-to-definition on a symbol from that assembly that you're using in your code. If nullability was enabled, you should see <code>#nullable enable</code> at the top of the file. This also appears to work in VS Code when using the latest C# extension.

Note that in VS this currently requires disabling "navigation to decompiled sources (experimental)" in Options -> Text Editor -> C# -> Advanced.
As far as a status page--it might help you to look over this issue in the dotnet runtime repo, which outlines when certain system assemblies were nullable-annotated.


How to resend queries to server every time a component is called in react-apollo and graphql

Question: I have this project, kinda like Facebook. The idea is, when a user is in their profile page, they should see a list of their friends' usernames. Upon clicking on each username, the app is taking the id of that person from the url, then sending a graphql query to the server, to fetch all relevant details of that person.
Below is the method that gets called when a user clicks on the username of any friend. This works as expected:
onClickFriend(e) {
    e.preventDefault()
    this.props.history.push(`/friends/${ e.target.id}`)
}

Then in the component that handles the url visited by the user (ie the component to show friends profile) contains the following code:
import React from 'react'
import PostsColumn from "./posts/PostsColumn"
import NewPostForm from "./posts/NewPostForm"
import {fetchFriendProfile} from "../queries/queries"
import {graphql} from 'react-apollo'
import {withRouter } from 'react-router'

const FriendProfile=({data})=>{
    const {loading, error, fetchFriendProfile} = data
    if (loading) return
Loading...

    if (error) return
{error}(

    const {username, birthday, profile_picture} = fetchFriendProfile
    return (

                <img src={`/uploads/${profile_picture}`} alt="Profile picture" width="200" height="200"/>

{username}

{new Date(birthday).toDateString()}

                    <NewPostForm/>

                {/*<PostsColumn />*/}

    )
}
export default graphql(fetchFriendProfile)(withRouter(FriendProfile))

And the graphql query is:
import {gql} from 'apollo-boost'
const fetchPalPosts = gql`
  {
 fetchFriendPosts(id:"${window.location.pathname.split('/')[2]}") {
    username
    birthday
    profile_picture
    }
    }
    `
export { fetchFriendProfile}

At first when the site loads, I see the list of usernames of all  my friends, and clicking on any user the first time, I get all the relevant details. However, when I go back and click on another user, this profile component gives me the profile details of the first user I clicked. The url is changing to reflect the id of this new clicked person, but the component does not display the correct details. Only when I reload the page that I get the correct details. Doing some debugging I realize that a query to the server is not even being made when I click any of these usernames as from the second time on wards. Only when I reload the page is when the query is being made. I need help to know
how to resend queries to server every time a component is called in react-apollo and graphql. (Am a beginner to graphql)
Answer: In addition to the query, the graphql HOC accepts a configuration object as its second parameter that allows you to fine-tune how your query behaves. You can, for example, define the fetchPolicy which determines how Apollo uses the cache. By default, when fetching the same query, Apollo will hit the server the first time and then use the cache for subsequent calls (this is called cache-first). If you want your component to always hit the request when it mounts, you can set the fetch policy to network-only:
export default graphql(fetchFriendProfile, {
  options: (props) => ({
    fetchPolicy: 'network-only',
  }),
})(withRouter(FriendProfile))

You can read more about fetch policies here.
That said, you don't need to change the fetch policy to achieve your desired behavior. Part of the problem is that you're effectively hardcoding the id input -- instead, you should be passing in any dynamic inputs as variables with each query. That means your query needs to look something like this:
# Note: the actual type for $id will have to match your schema!
query WhateverNameYouLike ($id: ID!){
  fetchFriendPosts(id: $id) {
    username
    birthday
    profile_picture
  }
}

Then you can pass in your variable like this:
export default graphql(fetchFriendProfile, {
  options: (props) => ({
    variables: {
      id: window.location.pathname.split('/')[2],
    },
  }),
})(withRouter(FriendProfile))

Side note: it looks like you're also using React Router, so you should be able to grab the id from match.params instead of parsing the location yourself. Read more here.
Lastly, it's important to realize that Apollo normalizes the data it caches -- and it relies on the data's id (or _id) property to do so. So if you want the cache-first behavior to work as expected, you need to either a) make sure you always request the id field in your queries, or b) tell Apollo to use a different field as the id by configuring InMemoryCache accordingly. It sounds like you already have an id field, so it's simple enough to modify your query to include it:
query WhateverNameYouLike ($id: ID!){
  fetchFriendPosts(id: $id) {
    id
    username
    birthday
    profile_picture
  }
}

You can read more about cache normalization and how to use dataIdFromObject to customize InMemoryCache's default behavior here.


How to change keyboard layout in Lubuntu 15.10?

Question: I have recently upgraded my PC from Lubuntu 14.10 to 15.10. Before the upgrade my keyboard layout matched my Danish keyboard. But after the upgrade I probably have a standard English/US layout.

Preferences/Language Support, doesn't let me configure the keyboard layout.
Preferences/Keyboard and Mouse, only let me configure stroking delay and similar.

I don't know about iBus and fcitx, as far as the tooltip infomation tells me, its for more complex languages such as Chinese.
I don't have a US icon in the taskbar, no keyboard and/or language icon at all.
Things I have tried:

Running the following in a terminal works, but only until the next reboot:
setxkbmap -layout dk

I got the following parameter in the file /etc/default/keyboard:
XKBLAYOUT="dk"

Installing and running the app Lxkeymap changes the keyboard to Danish when I run it, but rebooting will change the layout back to US.

I don't want anything fancy, I just want to set my keyboard layout to Danish. How can I do that?
Comment: You can try with [this](https://help.ubuntu.com/community/Lubuntu/Keyboard#Keyboard_Layouts) guide
Comment: If that does not work, you can try the terminal command `setxkbmap -layout dk` (I think that `dk` should mean Danish...)
Comment: Try to edit `/etc/default/keyboard`. That should survive a reboot. ;)
Comment: In Ubuntu Unity, the correct System Settings section is "**Text Entry**" and not "Keyboard". Do you have that in Lubuntu too?
Comment: Having an old PC, I try to avoid Unity, thus using Lubuntu. But I normally have no clue as where to change stuff. I cannot find any **Text Entry** and Lubuntu don't seem to have a **System Settings** application like Unity.
Comment: It does, but it doesn't survive a reboot.
Comment: @Gunnar Hjalmarsson I've updated my question based on your suggestion. It could be that something is overriding my settings somewhere.
Comment: @Sneetsher, I've also included your suggestion in my question, though sadly it only helps *momentarily*.
Comment: @trunk96, sorry I didn't see the link *under* this in your comment. I have already found that guide, but since I don't have the *Keyboard Layout Handler* (or a button with *US* written on it in the taskbar), I cannot use it.
Comment: @Sneetsher, your suggestion seems to work. I guess this is yet another situation, where a distribution upgrade has gone wrong. I suppose this normally should work *out of the box*.
Comment: @Sneetsher, feel free to add an answer and I'll mark it. Thanks for your help!
Comment: yes @Chau this is kind of workaround . There is something may be hard to dig for it.
Answer: Some googling and a test led me to this:
Right click the panel -> Add / Remove Panel Items -> Add -> Keyboard Layout Handler
That adds an icon to the panel, and by right clicking it and selecting "Settings", a GUI tool for managing keyboard layouts shows up.
To add languages, "keep system layout" should be unchecked.
Comment: Works on lubuntu 18.04
Comment: Works on lubuntu 16.04
Answer: I believe this solution only works if systemd is implemented? It works for me in Lubuntu 16.04. Let's check first if this works.
Go to the terminal and type in
localectl status

You should have this (partically the VC Keymap and X11 layout). If there isn't a command or something, I'm out of ideas.
 System Locale: LANG=en_AU.UTF-8
                LANGUAGE=en_AU:en_GB:en
     VC Keymap: us
    X11 Layout: us

If so, the following should fix it.
localectl set-keymap dk
localectl set-x11-keymap dk

I had set the GB keyboard instead of the US keyboard myself so my situation is quite similar. Unfortunately I don't have much know-how so maybe the following has changed more than you would want, but I haven't experienced any problems myself.
Solution adapted from Meuh's answer: https://unix.stackexchange.com/a/307767
Comment: works like a charm, this should be selected as correct answer ^_^
Comment: `localectl set-keymap de` worked perfect for setting german keyboard layout. Thx
Answer: On Lubuntu, complementing solutions above: Right-click on the bottom panel, and add the Keyboard Layout Handler.
At this point it only handles "US English", and the US flag appears (can be changed to text).
To add support to the US International (with dead keys), right click on the flag and enter to Settings.
In the Keyboard Layouts frame, click +Add. A nice list with flags of all countries in the world is displayed. Select US English again, but observe the diminutive triangle shaped icon to the left of it: it will expand to a rather complete list of variants, one of which is the wanted US Intl. with dead keys.
You can pick the key combination to activate it (I use Right Alt). Once installed you can also click on the flag icon in the panel: each click toggles the layout.
Now you have the wanted layout, in my case I frequently write in Spanish on a US keyboard. Apostrophe+vocal gives you the accents, also the ñ. áéíóúü.
Comment: The only that worked great even inside playonlinux programs!
Answer: As previous tries did not solve the problem, here is a workaround:
echo "setxkbmap -layout dk" >> ~/.xsessionrc

Referance: https://wiki.debian.org/Keyboard
Answer:
In Lubuntu, open up a terminal window with ctrl-alt-t
type sudo apt install lxkeymap
type your password
close terminal window
click on the startbutton, preferences, lxkeymap
click on your country in the left column
click on your keyboard choice in the right column
click Apply
you can test how the keys work in the line at the bottom of the lxkeymap window
close lxkeymap window

For me, having bought a laptop with an English keyboard, but being a Dutch user, so wanting to be able to type "e for an ë, the combination of United Kingdom and English (UK, international with dead keys) works fine. Before that the combination of United States and English (US, international with dead keys) worked fine.
Comment: This does not answer the question. The OP stated that "Installing and running the app Lxkeymap changes the keyboard to Danish when I run it, but rebooting will change the layout back to US."
Answer: Had a similar problem with the german qwertz keyboard in a Lubuntu variant for eeepc.
After some search I installed the Lxkeymap tool.
It adds the missing selection options to the LXDE GUI.
Comment: You could add the steps you did in detail to installing the tool, this would improve your answer.
Answer: Why not just edit  /etc/default/keyboard and change XKBLAYOUT to whatever value you want to set(dk, gb, us etc). I did this to change from uk layout to us layout, works after a reboot.
Comment: Welcome to AskUbuntu! You may have noticed that this question asks specifically about Lubuntu 15.10. If your answer relates to a more recent version, it would be useful to [edit] that information into your post. If not, and you are still using 15.10 I highly recommend that you [upgrade](https://askubuntu.com/questions/110477/how-do-i-upgrade-to-a-newer-version-of-ubuntu) to a newer version. Cheers!


How do i use javascript to read a text file and display it on my website?

Question: This is what i tried now:
<code><script>
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}
</script>
<script>
readTextFile("http://newsxpressmedia.com/files/theme/test.txt");
</script>
</code>
But it's not working the page throw like meassage without a message error. Just popup a window since it's not working.
What i want to do on my site is to read the file content line by line an display it on my website.
The does exist on the link: http://newsxpressmedia.com/files/theme/test.txt
Comment: Try using a relative path without specifying the domain.
Comment: Doing this on chrome like browsing to it: http://newsxpressmedia.com/files/theme/test.txt show me the file content. Now i tried to this in my site:  readTextFile("files/theme/test.txt"); it's not giving error now but also not showing anything.
Answer: Is your site same as newsxpressmedia.com? If not it is a cross-domain issue. Browsers do not allow ajax calls to access different domain. More info.
Comment: Yes typing newsxpressmedia.com in chrome lead to my website and typing in chrome newsxpressmedia.com/test.txt lead and show the test.txt content. Or newsxpressmedia.com/files/theme/test.txt
Comment: I tried your code on Chrome console and it seems to be working. I saw the alert message with the contents of the file test.txt. What exactly you want to do?
Comment: palanik you are right it is working but it's showing the text content like a messageBox in a popup window. I want it to show the content of the text file in a small window that is part of my html page and the user can scroll up down to see all the text. Just like the automatic scrolling text there is now in my site when you enter my site.
Answer: This sounds like a same origin security issue.   Without some special cross origin permissions from the target domain, the browser won't let you do ajax to a site that's at a different domain than your web page.
See MDN's page on the same-origin policy for details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript
See MDN's page on CORS for cross origin permissions: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS, but this requires cooperation from the target site.

The typical work-arounds are either to have your server work as a proxy so you can request the file from your server and your server gets the file from the actual web site or find a way to use an iframe in your web page.


Does SQL-Lite Database for android support key constraints

Question: Can we create relationships between tables in android sql lite database.
Comment: This was not helpful: http://www.sqlite.org/docs.html?  This seems definitive: http://www.sqlite.org/foreignkeys.html.  What was wrong with this document?
Answer: Yes, since API Level 8 (Froyo).
Comment: Foreign key constraints were only added in SQLite version 3.6.19, and API Level 8 (Froyo) was the first Android platform to use a recent enough version of SQLite. See http://www.sqlite.org/changes.html


Parse json from Yahoo pipes using jquery/ javascript

Question: This is the format of the json that I get from Yahoo pipes.
 {"count":3,
        "value":{
            "title":"Freak count feed",
            "description":"Pipes Output",
            "link":"http:\/\/pipes.yahoo.com\/pipes\/pipe.info?_id=565sdf6as5d4fasdac94835f",
            "pubDate":"Sat, 15 Jan 2011 05:53:12 -0320",
            "generator":"http:\/\/pipes.yahoo.com\/pipes\/","callback":"",
            "items":[
                {"title":"photos count",
                "y:title":"photos count",
                "description":"6"},
                {"title":"videos count",
                "y:title":"videos count",
                "description":"null"},
                {"title":"blogs count",
                "y:title":"blogs count",
                "description":"7"}
                ]
                            }
        }

I have the Yahoo pipes url. How do i parse the json from the url using jquery to get the count from the 'description' for each content type?
Answer: Try -
var data = json string

$(data.value.items).each(function(index, element){
    alert(element.title+' : '+element.description);
})

Demo - http://jsfiddle.net/T6ra3/
Answer: If you are using jquery for handling the ajax request you can do the following and everything will be already be safely parsed and evaluated.
$.get(url, arguments, function(data){...},"json");

Adding json to the end of a $.get $.post or $.ajax call will automatically parse the json for you. This also works with "xml" if you want to.
Afterwards you just access it like:
$.post(url, {arg1:"arg1", arg2:"arg2"},
   function(data){
      alert(data.value.items[0].title);
      alert(data.value.items[0].description);
   }, "json");


Best way to do some tile floor repair

Question: So the house I bought had a guy who wishes he was good at doing renovation work but really just sucked. And cut a lot of corners. He didn't put any cement board down under any of the tiled floors.. ie second floor wash room, hallway full bathroom and master bathroom.
End result: my floors are audibly cracking from the thin set cracked underneath the tile and grout is falling out from between the tiles. There are areas with no grout at all because of the floor movement.
Are there any ways to do anything about this, other than just regrouting the entire floor? Or pulling up all tile, installing cement board and redoing all the floors?
Comment: I suspect it's not just missing cement board. It's probably bad grout, bad mortar, bad install (not back buttering the tile, uneven mortar bed, etc.)
Comment: That said, I've done three floor tile tasks just adding 3/4" OSB to the existing subfloor, screwing it every 6" and applying two coats of paint to keep the OSB from slurping water from the mortar, and to reduce the chance of water damage later.  One is a laundry room, so wet happens.  The other two are hearths with steel stoves on them.  No cracks yet after 15 years.
Answer: My experience has shown me if the mortar is crumbling and tile cracking the base is not thick enough to start with. Even a perfect mix cannot stand up to flex!
In existing structures my normal plan is to remove existing flooring. Next I put down backer board first with thinset under the backer board and screw it down. Next I put the tile down again with thinset, the additional level of backer board with thinset on each side has not failed be in 40 years,
First I must say I check the Base , if I walk on it and it feels solid I STILL add the backer in most cases. I am 6'5" and a big guy and at 250 as a skinny guy if I see or feel any flex I add structure and that is the reason I have not had a tile failure similar to yours.
I can say most DIY tile jobs that fail because the base ( sub floor two thin, no backer) mixing is easy , if two wet it is not as strong  and ends up two thin.  but not usually a problem, under mixing with dry clumps is really to spot as big chunks flake with no base problems.
I would be looking at the base on a first floor and especially on a second floor with the problems described.
Answer: There's no easy fix. I'd remove the existing tile flooring and check the size of the supporting joists, then 1) check thickness of the subfloor and underlayment, if any...2) then install cement board and 3) install new tile as per the Ceramic Tile Council of North America (CTNA) guidelines.
https://www.tcnatile.com/products-and-services/publications.html
First, the supporting floor joists must be strong enough to support a tile floor. They cannot deflect or the tile will crack, etc. verify that the joists have a maximum of 1/360 th deflection...there are tables to calculate the deflection based on load, spacing and span.
If the structure is adequate, then 1) check the thickness of the subfloor and underlayment. If your joists are 16" on center, you'll need a minimum of 5/8" plywood (or equivalent) and a minimum of 1/2" underlayment.
2) Cement board is recommended to be set in 1/4" thinset. (Get a trowel with 1/4" grooves.) Fasten the cement board to the joists using the recommended size and spacing of screws.
3) Install the tiles on the cement board following their precise instructions, including curing times.
As you can see, this not an easy task. Make sure you follow the TCNA guidelines exactly, including making sure the floor joists are strong enough and you have the proper thickness of subfloor and underlayment.
Typically, cracked tile is due to movement (deflection) in the structure.
Comment: Good info. I'm not really sure what's under the tile and carpet at this point other than the fact I know it's a hardwood floor. The previous owners simply carpeted over the hardwood in the bedrooms and hallways. A strange little fact is that there is a noticeable height difference between the tile floors and the carpeted floors. I will find out next weekend when I demo the master bathroom but it seems they cut out all the hard wood floor and tiled over whatever subfloor is under it without adding cement board.

Best way to do some tile floor repair


How do I enable the bcdiv function in PHP 7.0?

Question: The PHP function bcdiv is not available by default. How do I enable that in PHP configuration?
Answer:
Install module bcmath
sudo apt-get install php-bcmath

(note: on ubuntu 16.04^ with PHP 7.0^ use php7.0-bcmath package instead)

Restart apache service eventually
sudo service apache2 restart

Comment: The answer should note that this wont work on php 7.0. At least on my machine it didnt work. Next asnwer - worked.
Answer: Install module bcmath in PHP 7.0, you should try:
sudo apt-get install php7.0-bcmath

And restart php engine or apache
Comment: This answer should note that [`php7.0-bcmath` is available in 16.04 and newer releases](http://packages.ubuntu.com/search?keywords=php7.0-bcmath&searchon=names&suite=all&section=all) only.
Answer: If you're using Docker, then you can install it using docker-php-ext-install:
# Dockerfile
FROM php:7.4-fpm-alpine

RUN docker-php-ext-install bcmath