Piano Maintenance

Question: What should be done to maintain an upright piano?
I am not asking about tuning it, but what can be done so it does not have to be tuned as often?
I heard someone once say about a particular piano that the strings should be oiled.
Are there things that can be done to help prevent the keys from sticking?
If so, how should it be done, and how often?
Answer: All pianos benefit from being in very stable environments, not too dry, not humid, and a static temperature.  This will help to keep it in tune for longer.  Realize though that playing the instrument will knock it out of tune and the more you play the faster it will happen.  Also, if the pin block is shot, it will go out of tune fast no matter what you do, because the tuning pins will slip.  Additionally, regular tunings will help keep it in tune longer.  I know that sounds a bit silly but it's true.  If you wait until the piano is REALLY out of tune, the tuner will have to move the pitch farther which will stretch the strings and make them less stable.
In short the best thing to do is control the environment, and get it tuned regularly, twice a year is enough for most pianos.  There isn't really anything else you can do to keep it in tune longer.
Also, do NOT oil the strings.  This is the quickest route to spending tons of money to replace the strings.
Comment: If you are have sticking keys and other problems, it should be looked over by a piano technician, even if you don't have him tune it.  Sticking keys are usually caused by bits of felt getting places they shouldn't, although changes in humidity can cause it as well.  I would encourage you to not try to service the piano yourself unless you know what you're doing or are ok with possibly breaking something that may be expensive to repair.
Comment: That's correct.  A piano in a stable environment and a moderate amount of playing shouldn't need more than 2 tunings a year.  You can get away with 1 if you don't mind a few months of badness. : )  How long is yours staying in tune?
Comment: So there is nothing you can really do besides keeping it in a stable environment? (Like away from heater vents and widows and such.)
Comment: Unfortunately not.  Also, if it was moved from their place to yours, that will have knocked it out of tune some as well.
Comment: I have not had it all that long, a friend was moving and gave it to me as they could not bring it with them.

Aside from tuning, what about things such as preventing keys from getting stuck or anything of that sort?
Comment: You don't say whether your piano has a wooden or an iron frame. If it's wooden, there is far more chance it'll go out of tune.The iron frame is much more stable,so have a look, and if it's wooden, probably because the piano is very old, it's worth considering getting a different piano, as you'll save a lot on not re-tuning as often.
Answer: You can get a climate-control system installed in the piano.  Dampp-Chaser is one brand.  It has both a water system to increase humidity and a header to decrease humidity, and works automatically to increase or decrease as necessary.  In addition to helping the instrument stay in tune, it will help prevent sticking keys.  The cost is several hundred dollars, so it's worthwhile only for a very good piano.
Answer: In addition to ecline6's answer: In very dry places (large appartment houses typically), you can place couple glasses of water into the piano to keep the humidity at a bit higher level. You obviously have to add water to the glasses from time to time, it usually lasts about a month.
There are 3 reasons:

Wood in general doesn't like too dry places.
During the summer, the humidity often rises rapidly for short periods of time, and you reduce the shock to the piano by keeping the water inside.
The water itself (and the wet air) slightly stabilizes the temperature inside the piano, helping to reduce the temperature shocks it might get. Remember that slow change from 18C to 25C is much nicer to the piano than a fast one.
Comment: Okay I know that you're discussing about piano maintenance, and that i should be asking this question separately, but I'm a little concerned if these piano maintenance (especially about the wood) is also applicable to a drumset? I'm concerned about the wood materials used in drumset, i guess that piano woods are stronger than those in the drumset, and if a piano has that kind of maintenance, will it be also applicable to a drumset?
Comment: @Jez'r570 I did not know that drum sets went out of tune!
Comment: what i meant is the durability of its wood.
Comment: @Jez'r570 I suppose it is not such an issue with drums, since the wood is thinner and the instuments smaller, making it less affected by changes of conditions, but I have no experience with drums you see...

Piano Maintenance


How to debug a value from a function if it is called inside return statement?

Question: I want to know how to get the value from a function if it is inside a returning statement.
For instance, I have the following function;
function a () {
    return b(); // How to know the value returning from b() if I put the debuger in this line??
}

If I put a debugger in the return statement, It enters that line, but when I press F10, it already returns and I can't see the value displayed. How do I get this value before changing the page?
As a work around, what I'm doing currently is creating an additional line before returning:
const result = b(); return result;

But, this is a work around and it's hard to do it everything, because there are thousands of lines like this in the code, and everytime I need to change back to the previous state before submitting the code to production, otherwise it's not accepted.
Comment: Maybe you can do instead `const result = b(); return result;` like in 2 lines, so you will see in the variable called `result`.
Comment: Yes, I know this, but this is a workaround. I will have to change the code back to the previous state before sending to production, otherwise it won't pass the review.
Comment: I suspect you cannot, because that's a single statement. You need a workaround like a temp variable (what you're doing) or maybe a watch expression (though I guess that would execute the function twice).
Answer: You need to step into the b() function, F11
Comment: Alright, but what if that function that I'm pressing F11 is also returning a function? And the one after that, and so on, when it eventually enters a node_module and it goes on and on forever.
Comment: once it breaks on "return b()", set breakpoint on a line inside b() and hit continue.
Comment: or you can just highlight b() and select Evaluate if you want to know what b() would return
Comment: What I meant is that function b() can have an return c() as his return statament, then I would need to press F11 inside in it aswell
Answer: There are different methods to return values from a function which are pointers,structures and array.
In this you have to do execute a function and return a value to the calling function.


XmlDocument doesn't save character entities

Question: I am currently reading a xml file with Xmldocument and write some values. The parts I am reading are looking like this:
<para styleclass="Normal" style="margin-top:12px; line-height:1.0; tabstops:none;">

      <para><text styleclass="Normal" style="font-size:9pt; font-weight:bold; vertical-align:baseline; color:#000000;" translate="true"> </text></para>

      <para style="text-align:center;"><text styleclass="Normal" style="font-size:9pt; font-weight:bold; vertical-align:baseline; color:#000000;" translate="true">Windows 32</text></para>

      <para style="text-align:center;"><text styleclass="Normal" style="font-size:9pt; font-weight:bold; vertical-align:baseline; color:#000000;" translate="true">Windows 64</text></para>

      <para style="text-align:center;"><text styleclass="Normal" style="font-size:9pt; font-weight:bold; vertical-align:baseline; color:#000000;" translate="true">Linux</text></para>

      <para><text styleclass="Normal" style="font-size:9pt; font-weight:bold; vertical-align:baseline; color:#000000;" translate="true">SomeDll.dll</text></para>

      <para style="text-align:center;"><text styleclass="Normal" style="font-size:9pt; vertical-align:baseline; color:#000000;" translate="true">22.214.171.124</text></para>

      <para style="text-align:center;"><text styleclass="Normal" style="font-size:9pt; vertical-align:baseline; color:#000000;" translate="true">18.104.22.168</text></para>

      <para style="text-align:center;"><text styleclass="Normal" style="font-size:9pt; vertical-align:baseline; color:#000000;" translate="true">to be defined</text></para>

As you can see, in the second para there is a character entity (& # 3 2 ;). I don't edit it, just going over it. After I've done my editing, I save the file with the .save method.
The problem is, the character entity gets saved to what it represents, in this case a space " ". If I now open the xml file again in my programm I get an exception because that value is null. Is there any way to save character entities to their entity form?
Comment: possible duplicate of [XDocument.Save() removes my
 entities](http://stackoverflow.com/questions/8811873/xdocument-save-removes-my-xa-entities)
Answer: Given the difficulty of identifying which entities were converted - For example there are many spaces in your sample - it would be very difficult to convert them back.
It might be easier if you modify you loading program to allow for instances where the entities are converted.


Finding empty directories in Python

Question: All,
What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created.
dir = 'Files\\%s' % (directory)
os.mkdir(dir)
cmd = 'wget -r -l1 -nd -np -A.jpg,.png,.gif -P %s %s' %(dir,  i[1])
os.system(cmd)
if not os.path.isdir(dir):
    os.rmdir(dir)

I would like to test to see if a file was dropped in the directory after it was created. If nothing is there...delete it.
Thanks,
Adam
Comment: Please do not use os.system to call wget. Use subprocess.Popen
Comment: Define "empty". What if there are subdirectories? Should they be checked for data? Should they also be deleted if there is no data in them?
Comment: I don't have any subdirectories in this case just a single folder that may or may not have pics in it.
Comment: In essence: `isempty = lambda path : not next(os.scandir(path), None)`
Comment: Don't use os.listdir or try, except statements. os.scandir is orders of magnitude faster.
Answer: import os

if not os.listdir(dir):
    os.rmdir(dir)

LBYL style.
for EAFP, see mouad's answer.
Comment: If the directory contains thousands of files, would `os.listdir(dir)` return size be a issue? @Corey Goldberg
Answer: I will go with EAFP like so:
try:
    os.rmdir(dir)
except OSError as ex:
    if ex.errno == errno.ENOTEMPTY:
        print "directory not empty"

os.rmdir will not delete a directory that is not empty.
Comment: +1: Simple.  Direct.  And it delegates **all** the tricky decision-making to the OS where it belongs.
Comment: How about `else: raise`?
Comment: nice but: `NameError: name 'errno' is not defined` you need `import errno`!
Comment: Note that this function silently drops all other errors (such as `EACCESS`), which you may want to report.  Note that fixing that naively would probably result in reporting errors for non-empty directories, which you probably want to ignore.  Not as simple as it seems :-)
Answer: Try:
if not os.listdir(dir):
    print "Empty"

or
if os.listdir(dir) == []:
    print "Empty"

Answer: This can now be done more efficiently in Python3.5+, since there is no need to build a list of the directory contents just to see if its empty:
import os

def is_dir_empty(path):
    with os.scandir(path) as scan:
        return next(scan, None) is None

Example usage:

if os.path.isdir(directory) and is_dir_empty(directory):
    os.rmdir(directory)

Answer: What if you did checked if the directory exists, and whether there is content in the directory... something like:
if os.path.isdir(dir) and len(os.listdir(dir)) == 0:
    os.rmdir(dir)

Answer: If the empty directories are already created, you can place this script in your outer directory and run it:
import os

def _visit(arg, dirname, names):
    if not names:
        print 'Remove %s' % dirname
        os.rmdir(dirname)

def run(outer_dir):
    os.path.walk(outer_dir, _visit, 0)

if __name__ == '__main__':
    outer_dir = os.path.dirname(__file__)
    run(outer_dir)
    os.system('pause')

Answer: Here is the fastest and optimized way to check if the directory is empty or not.
empty = False
for dirpath, dirnames, files in os.walk(dir):
    if files:
        print("Not empty !") ;
    if not files:
        print("It is empty !" )
        empty = True
    break ;

The other answers mentioned here are not fast because , if you want use the usual os.listdir() , if the directory has too many files , it will slow ur code and if you use the os.rmdir( ) method to try to catch the error , then it will simply delete that folder. This might not be something which u wanna do if you just want to check for emptyness .
Comment: Using `os.scandir` is fast, with the advantage of being clearer and not needing to generate lists that aren't use.
Answer: I have follews Bash checking if folder has contents answer.
Mainly it is similiar approach as @ideasman42's answer on https://stackoverflow.com/a/47363995/2402577, in order to not to build the complete list, which would probably work on Debian as well.

there is no need to build a list of the directory contents just to
  see if its empty:

os.walk('.') returns the complete files under a directory and if there thousands it may be inefficient. Instead following command find "$target" -mindepth 1 -print -quit returns first found file and quits. If it returns an empty string, which means folder is empty.

You can check if a directory is empty using find, and processing its
  output

def is_dir_empty(absolute_path):
    cmd = ["find", absolute_path, "-mindepth", "1", "-print", "-quit"]
    output = subprocess.check_output(cmd).decode("utf-8").strip()
    return not output

print is_dir_empty("some/path/here")

Finding empty directories in Python


Google Drive / Facebook / Dropbox - Upload file from My Website

Question: So I have Mywebsite (ex. MyWeb.Com)
(ASP MVC )
And Users Can upload their photo to my site. Now I want after upload give options upload to Google Drive/Dropbox/Facebook . But user need Login for it.
I not have idea how do it. How make Login forms on my web, and how send files to their account
P.S - Sorry for my English
Please give me some tips.
Thank you
Answer: for Google Drive you can use simply use JavaScript please go through below link
Run a Drive app in JavaScript


Setting up a probability problem - What is the best way to interpret rolling two dice?

Question: Consider the following problem: If I roll two fair six-sided dice, what is the probability of me rolling two numbers that add up to $10$?
Obviously, the only unordered ways to do this is to roll $(4, 6)$ or $(5, 5)$. My inclination is to say the probability is $3/36 = 1/12$ on the basis that of the $36$ ordered rolls, the only ways to get the roll to sum to $10$ is if it's $(4, 6), (5, 5)$, or $(6, 4)$. To justify the ordered interpretation, I consider the "thought-experiment" that I roll, but immediately cover one die. Looking at the first (unconvered) die, I know I have a $3 / 6 = 1 / 2$ chance of rolling something I want, i.e. I must roll a $4, 5$, or $6$. But then I know that if I rolled a $4, 5$, or $6$, then there is only a $1 / 6$ chance that the second die (i.e. the one that has until now been covered) is what it must be. That is, if I rolled a $4$ then there is only a $1 / 6$ chance that the second die is the $6$ I need, and similarly for the other options. Thus I have a $1 / 36 + 1 / 36 + 1 /36 = 1 / 12$ chance.
My trouble with this is that it also seems a bit counter-intuitive because when I roll, I could not care less which die said which; that is, if I had a red die and a black die in my hand, then after I roll I have no interest in whether the red was a $4$ and the black a $6$ or vice versa. So my question: Is this interpretation of the question in terms of ordered pairs correct? That is, is it correct to say that the unordered roll $(5, 5)$ is only half as likely as the unordered roll $(4, 6) = (6, 4)$? Thanks in advance.
Comment: Yes.  And red and black die is a good way to see it.  There are 3 ways.  red can be 4,5,6 and the black will have to be 6,5,4.  It's counter intuitive but intuition is fundamently wrong.
Comment: Your red and black is a good approach. The fact that you don't care which is red and which is black is what makes $4+6$ twice as likely as $5+5$. There are two ways to do the first and only one to do the second.
Answer: I'm not sure what you are looking for from a solution (the comments seem to resolve your concerns). Keep in mind with probability, you don't care just about the outcomes, but how likely they are to occur. Because rolling (4,6) is twice as likely, you should count it twice in the sum.
Alternatively, create precise definitions of events, so you don't have to guess based on intuition. For example, the sample space is all the combinations of two dice -- that is (1,2,3,4,5,6) x (1,2,3,4,5,6) -- and there are 3 outcomes that are acceptable here, thus the answer is 3/36.
There is no reason to count dice rolls by unordered pairs, since you'll just have to complicate things later on.


Get both the real and shown width of an image using JavaScript

Question: I have several images in an HTML document. The width of those elements is often modified due to a max-width CSS property that is applied to all of them.
I want to know whether it is possible to get both the real width of the .jpeg/.png/.whatever image files and the width that is being shown to the user, this is, I want to be able to know whether the images are being resized due to the max-width property or not.
Resizing the images with JavaScript after the page has loaded instead of using max-width is not acceptable.
Comment: @monq, Welcome to web development...
Comment: Duplicate of http://stackoverflow.com/questions/10478649/get-actual-image-size-after-resizing-it and
Comment: Why don't you create an element off-page and use that to determine width?
Comment: see also http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome could help
Comment: @Brad it looks like a very ugly approach for me.
Comment: possible duplicate of [Get image size after resize JavaScript](http://stackoverflow.com/questions/7682772/get-image-size-after-resize-javascript)
Answer: The answer (pointed by someone who just deleted it) is to use naturalWidth.
Comment: FYI, naturalWidth/Height aren't implemented in IE<9 to the best of my knowledge. It's safer (for now) to measure the image off-page -- or at least as a fallback mechanism.
Comment: @svidgen I have one question: Why IE doesn't automatically update to latest version? Or why do ever people use lower version of any browser than the latest? This is one thing I can't ever understand.
Comment: @Ms.Nobody As someone who once tried to do frantic weekend debugging of an automatic Chrome update that made everyone everywhere unable to use our product because of a randomly-introduced Flash incompatibility/security dialog, I can assure you; there are legitimate reasons.
Answer:

window.addEventListener("load", function() {
  var imgs = document.querySelectorAll('img');
  for (var i = 0; i < imgs.length; i++) {
    var imgTag = imgs[i];
    var image = new Image();
    image.src = imgTag.src;
    output.innerHTML = "Width: " + image.width + " Height: " + image.height;
  }
});
img {
  max-width: 200px;
}

I just put this together, and it seemed to work.
It depends on the JavaScript Image type. I also used "onload" rather than DOMContentLoaded, so that when querying about the image, we can be certain that it's already been loaded and doesn't need to wait for its onLoad callback.


AngularJS + route - Failed to execute 'replaceState' on 'History': A history state object with URL '...' cannot be created in a document

Question: Bom Dia Pessoal,
Alguém já teve o problema da aplicação XDK / cordova ficar em looping quando inicializa. Esse erro só ocorre no dispositivo.
Ela fica "reinicializando" até ocorrer o erro abaixo
Answer: Achei a solução para o problema
Inicialmente vendo essa postagem percebi onde estava o erro
https://stackoverflow.com/questions/25790349/angularjs-infinite-loop-with-ng-view
O problema é que meu sistema entrava em um loop infinito porque as condições da roda não eram supridas, então para solucionar o meu problema foi necessário duas ações.

Quando configurar a roda não usar $locationProvider.html5Mode(true);
Quando criar a navegação usar # Home

Reforço que isso resolveu o meu problema, pode ser que não seja usual para todos.
Segue o roteamento completo
var app = angular.module('app',['ngRoute']);

app.config(function($routeProvider, $locationProvider)
{
   // remove o # da url
   //$locationProvider.html5Mode(true);

   $routeProvider

   // para a rota '/', carregaremos o template home.html e o controller 'HomeCtrl'
   .when('/', {
       templateUrl : 'views/home.html',
       controller : 'HomeCtrl',
       controllerAs : 'ctrl'
   })

   // para a rota '/sobre', carregaremos o template sobre.html e o controller 'SobreCtrl'
   .when('/sobre', {
      templateUrl : 'views/sobre.html',
      controller  : 'SobreCtrl',
      controllerAs : 'ctrl'
   })

   // para a rota '/contato', carregaremos o template contato.html e o controller 'ContatoCtrl'
   .when('/contato', {
      templateUrl : 'views/contato.html',
      controller  : 'ContatoCtrl',
      controllerAs : 'ctrl'
   })

   // caso não seja nenhum desses, redirecione para a rota '/'
   .otherwise ({ redirectTo: '/' });
});

Esse é meu index.

Home

Sobre

Contato

Por final meus controllers
app.controller('HomeCtrl', function($rootScope, $location)
{
    $rootScope.activetab = $location.path();
    var ctrl = this;

    ctrl.init = function()
    {
        console.log(Date());

        $location.replace();
    }

});

app.controller('testeCtrl', function($rootScope, $location, $scope)
{
    $rootScope.activetab = $location.path();
    $scope.titulo = "Titulo 1";

});

app.controller('SobreCtrl', function($rootScope, $location)
{
   $rootScope.activetab = $location.path();
   var ctrl = this;

   ctrl.init = function()
   {
        console.log("Sobre init");
   }
});

app.controller('ContatoCtrl', function($rootScope, $location)
{

   $rootScope.activetab = $location.path();

   var ctrl = this;

   ctrl.init = function()
   {
        console.log("Contato init");

        if($rootScope.contatoCount ==null)
            $rootScope.contatoCount = 0;

        $rootScope.contatoCount++;
   }
});


kinit pre-authentication fails

Question: I have a CentOS 6.4 that someone set up a while back.
The admin is not sure how he installed it, but it works very well with Kerberos.
I used authconfig to set the domain and the Kerberos settings.
I use ktpass on a windows domain controller and transferred the keytab.
kinit -k works fine and I can use it for nfsv4 Kerberos mounts.
This is all pretty standard.
My problem is I have a customer that installed 6.7 with a base install and we cannot get kinit to work correctly.
We set these RPMs.
$ yum install krb5-libs krb5-workstation pam_krb5 \
       cyrus-sasl-gssapi samba-* nfs-utils nfs4-acl-tools tcpdump -y

Each attempt to get the system to pickup a tgt returns the generic.
$ kinit -k nfs/oldlabsystem
kinit: Preauthentication failed while getting initial credentials

I went back and installed 6.4 in the same way and now 6.4 has the problem. I pulled a list of the rpms from my working 6.4 and used yum to install the same RPMs.
No luck here.
A network traces show as:
AS-REQ
AS-REP error-code: eRR-PREAUTH-REQUIRED (25)
AS-REQ
error-code: eRR-PREAUTH-FAILED (24)

I went back and created new keys for my working system to make sure my method of generated the keys were correct. My working 6.4 system has no problem.
On the non-working 6.4 system, I can do a kinit username and supply the user password with no problem. But I cannot do a kinit -k if I do a kinit and supply the password set with kpass I end up with
kinit: Preauthentication failed while getting initial credentials

In frustration I went back and created a user account and then generated a keytab from it. This also failed with the same error. Then on the user account in AD I turned off pre-authentication and then the kinit returned this.
[root@ ~]# kinit -k nfs/nfstestsystem.rockies.beta
kinit: Password incorrect while getting initial credentials

I suspect the keytab is somehow getting corrupted or the OS is using the keys incorrectly.
My problem is these errors are so generic it is almost impossible to find anything of value on the message boards: lab-admin-krb5.
I tried to post these questions on the CentOS forums, but I did not get very far.
An strace of both kinit shows essentially the same calls to the same libraries.
Comment: I think this may be a problem with ktpass. I can take the working keys and put it on the non-working system. this would rule out linux.
Answer:
list out the keytab with klist and paste it here
show us get_principal output - do you have pre authentication set?
show us the kdc logs

This will clarify your issue.

kinit pre-authentication fails


How to get each db result value count

Question: How to get values count in db_select
My query is:
<code>$last_item = '2015-07-19';
$query = db_select('field_data_appointment_date','ap');
$query->join('field_data_appointment_slot','aps','aps.entity_id = ap.entity_id');
$query->fields('aps',array('appointment_slot_value '));
$query->condition('ap.appointment_date_value', '%' . db_like($last_item) . '%', 'LIKE');
$result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);
dsm($result);
</code>
and my result is:
<code>... (Array, 4 elements)
0 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 10.00-11.00
1 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 10.00-11.00
2 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 10.00-11.00
3 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 11.00-12.00
</code>
I need result like count of
<code>:10.00-11.00 is 3
:11.00-12:00 is 1
</code>
Anyone help me out
Comment: What do you want to do? Give more details. maybe non straight query on Database solution exists.
Answer: Not fully understanding the output you really want to achieve, but here's examples on how to count the results coming from the database
get count with db_select
OR
rowCount
Let me know if any of those work for you.

How to get each db result value count


Permissions on cron scripts?

Question: I've got some php scripts that I need to schedule for every hour.
(a) How do I schedule them from the command line / shell?
(b) What permissions / ownership should I set on them?

Edit 1:
Hi guys - the website is being run by 'apache' user. Which user does the cron script run as? root or apache or something else?
Comment: In response to your edit, your crontab runs as you.  If you need it to run as the webserver, do what Rikih said and put the files on the webserver, then replace the crontab command with `/usr/bin/curl http://example.com/scheduled_php/runme.php` (or `/usr/bin/wget`)
Answer: crontab -e will open the crontab editor for your personal crontab, assuming the admin allows them.  Here you'd put a line like
0 * * * * /usr/bin/php /home/matt_tm/php/runme.php

once for each script, with /usr/bin/php being the full path to your commandline php binary, and the full path to the php file you want to run.
That will run the script the 0th minute (:00) of every hour, every day of the month, every month, and every day of the week (you might want to spread them out so one script starts at 0, one starts at the 5th minute and so on).  The commands in your personal crontab are run as your account, so all your script needs in this case is for your account to be able to read the script, execute the php binary, and have access to all the files the script needs.
Answer: As an alternative to DerfK answer you could also start each PHP with the line.
#!/path/to/php

and chmod the file to be executable.
Your crontab line will now look like this:
0 * * * * /path/to/php/script.php

Answer: (a) you can using php-cli or wget/curl (other utilities)
(b) execute permission. if the php script need to create the file, make sure the permission same as the user running.
Answer: to schedule them, edit the cronfile for the user they should run as. "man crontab" should tell you how to do this.
as to what ownership, it all depends what the scripts are supposed to do. if they modify some resource, then the script has to either have user or group permission to modify the resource (assuming this resource is a local file). often the most sensible way to do this on a unix-like system is through group permissions.

Permissions on cron scripts?


R: Mediation Analysis, output shows an ACME of 0

Question: My first mediation analysis and something is wrong...The relationship between the independent variable ("Bedingung") and the dependent variable ("Liking") is significant as is the relationship between the IV and the mediator ("Similarity"). When including the mediator into the regression the relationship between the IV and DV decreases significantly (partial mediation?). But for some reason when testing whether the partial mediation is significant, the ouput shows an ACME equal to zero (see screenshot).
Can someone help?

Here is my whole code :)
<code>#Mediatoranalyse
##step 1, Effekt von UV auf AV, hier signifikant
med.fit <- lm(Liking ~ Bedingung, data = d)
summary(med.fit)

##step 2 gucken, ob signifikanter Effekt der UV auf Mediator
out.fit <- lm(Similarity ~ Bedingung, data = d)
summary(out.fit)
###ist signifikant

##step 3, gucken, ob der Zusammenhang zwischen UV und AV trotz Mediator noch besteht
SimiMediation <- lm(Liking ~ Bedingung + Similarity, d)
summary(SimiMediation)
###partielle Mediation, der Effekt verschwindet nicht, wird aber kleiner

##step 4 jetzt testen, ob signifikant

med.out <- mediate(out.fit, med.fit, sims = 3000, boot = TRUE,
                   treat ="Bedingung", mediator = "Similarity")
summary(med.out)
</code>
Comment: the ouput is the picture above showing an ACME = 0 :)
Answer: Your call to mediate is wrong. Label the arguments to prevent confusion. Otherwise the first object is assigned as the model for the mediator, the second object is assigned as the model for the outcome. You've reversed these.  See <code>?mediate</code> for details.


algorithm that determine whether there exists a duplicate integer with expected runtime $O(n)$

Question: Consider an input of unsorted array; we want to determine whether exists a duplicate integer; the algorithm should have expected runtime $O(n)$.
Note: We want to analysis the expected runtime by counting the number of comparisons in the algorithm.
I know that the brute force requires $\Theta(n^2)$ complexity and the best case is $\Theta(1)$.
However, for expected runtime analysis; is this equivalent to average case ? Where we consider all possible of runtime complexity and taking expectation over them?
Since the algorithm will be based on the number of comparisons we make.
the all possible number of comparisons we will make would be a set
$\{1,2,3,4,...,n-1,n,n+1,...,2n-3, ......\}$ (where $1,..,n-1$, are number of comparisons might be made when compare $A[0]$ to others, and so on; and $n$ is size of array); then taking expectation, but how do I decide the probability of each number of comparisons? For example, if the algorithm terminates with only one comparison, then $A[0] == A[1]$, but I don't how do I determine this probability ?
Comment: @Ellery: Yes, but the default assumption when we're talking about complexity is that we're interested in the _worst_ case complexity. And in the worst case, when you're comparing two integers, you may need to _read the entire input_ before you can be sure whether they're equal or not.
Comment: thanks for the mention; I have fixed it
Comment: What are the elements of your input array? I read your question as meaning they were arbitrary integers. Or are the integers bounded?
Comment: @RobArthan they just positive integer without bound
Comment: @j4nbur53 yes, sorry for the unclarity
Comment: So for $n=2$, you want an algorithm that can determine whether two integers _of arbitrary size_ are equal in constant time? That is obviously not possible.
Comment: @HenningMakholm I mean that the best case occurs when first two integer are duplicate, then algorithm terminates when doing the first comparison; then no matter how long the array is, the best is constant time; that's my understanding of best case run time
Comment: @HenningMakholm Oh, I see, but we assume that input is in the memory; by brute force, the algorithm dominated by the number of comparisons
Comment: @ElleryL: That doesn't matter. If the input is in memory, you still need to _inspect every bit of the input_ before you can be sure whether the two numbers are equal or not. There's no way around that. I'm not talking about I/O, simply about the fact that your algorithm needs to process every bit of the input -- if it doesn't, an adversary will be able to construct an input that fools it.
Comment: As you say at the end, you don't have enough information to find out the probability of the first comparison "succeeding" and terminating the algorithm.  More assumptions are needed to impose a probability distribution and obtain the "expected" runtime.
Answer: Assuming that each of the input numbers are represented as a particular string of symbols from a finite alphabet, you can build a trie representing the numbers you have seen so far, while reading them. That will automatically detect duplicates for you, while doing a constant amount of work per input symbol.
Comment: Your method will automatically detect duplicates, but will it do so in $O(1)$ expected time on reading each new input?
Comment: @RobArthan: Yes -- assuming that the input alphabet is fixed in advance,
Comment: @HenningMakholm: And that the input *length* is bounded by a fixed constant, although I suppose at that point we're pressing into the question of what precisely we are counting.
Comment: @Hurkyl: No, that is not necessary. I'm assuming the standard convention that the $n$ in $O(n)$ measures the _number of symbols_ in the input.
Comment: @j4nbur53: The standard assumption here is that a pointer large enough to represent any location in the input can be manipulated in constant time.
Comment: @j4nbur53: Or if you want to be even more formal about it, assume a RAM where the constant-time operations are incrementing or decrementing a register by _one_, and the input is given in a sequence of registers initialized to $0$ or $1$ each.
Comment: @j4nbur53: In the model of my last comment, register values can be as large as you want, except that the only way to create a large integer is to count up to it one by one. (The machine must have instructions to _copy_ values between memory locations).
Comment: @j4nbur53: The cost model usually assumed (the one that leads to the familiar textbook asymptotics for standard algorithms) assumes I can. You can define a different model if you want to, but it won't be the standard one -- and then something like "you can decide whether a string is a palindrome in linear time" which intuitively ought to be true, are probably not true in that model anymore.
Comment: @j4nbur53: Correct -- but that just says that a Turing machine is not a useful model for reasoning about the time complexity of algorithms that run on real computers. (Turing machines would never even be mentioned in complexity, were it not for the remarkable and unexpected fact the "polynomial time" does turn out to be the same complexity class between Turing machines and more realistic models. Lower than that, Turing machine timing doesn't have much practical significance).
Answer: The algorithm depends very much on the nature of the input.
If the input consists of $n$ integers of some bounded size, then we can consider each integer as a single symbol from a possibly quite large, but finite alphabet. Let there be $k$ symbols in the alphabet; then $k$ is a fixed constant for any input, and any input of length $>k$ contains a duplicate by the pigeonhole principle.
For example, if the input is an array of any length containing $32$-bit integers, then $k=2^{32}.$
The algorithm for this kind of problem begins by counting up to $k+1$ integers in the input. If the count reaches $k+1,$ the algorithm returns "a duplicate exists"; otherwise it performs up to $k(k-1)$ comparisons (the brute force method). So in the worst case we have $k+1$ steps of counting and $k(k-1)$ comparisons; but since $k$ is a fixed constant, the running time of the algorithm is bounded, and the entire algorithm runs in worst-case $O(1)$ time. (The time constant for that $O(1)$ time may be quite large, however.)
A more interesting kind of input allows the integers of input to be strings of digits of any length. Now we have to say what it means to have an input of size $n$; a reasonable interpretation is that $n$ is the sum of the lengths of all the strings (or the sum of the lengths plus the number of strings, to allow for demarcation of the strings). Then Henning Makholm's solution (using a trie) runs in $O(n)$ worst-case time, which implies it has $O(n)$ expected time.
Another possible interpretation is that we allow the integers to be strings of arbitrary length, but we assume there is some probability distribution that governs the value of each integer. That is, if $m$ is a given integer, then there is some probability $P(m)$ that the next input integer will equal $m.$
In that interpretation there is some fixed probability $P_0$ that two integers selected at random from the input will be the same. The expected length of an integer (a bound on the expected time required to compare two integers) is also a fixed value.
If the first pass of the algorithm merely compares the first and second integers of input, then the third and fourth, then fifth and sixth, etc., then as the length of input goes toward infinity the chance of finding a match approaches $1$ and the expected number of comparisons before finding the match (when there is one) approaches a constant.
The expected number of comparisons when we compare all possible pairs of input integers (up to the first matching pair) is a little more complicated to deal with, since the pairs are not all independently distributed, but maybe one can show that it's also bounded as $n$ goes to infinity; if so, the expected running time of the entire algorithm is $O(1).$
Answer: Hash table search and insert are usually both considered $O(1)$ in the average. So if you start with an empty hash table, go through all the elements search and insert at the same time, you find the element in the average at index $k=(n+1)/2$ assuming there is only one duplicate, so you need $O(n)$ hash computations and equality comparisons (inside the hash table) or less.
If you dont use a hash table, but an ordinary list, checking for the collision is $O(m)$ where m is the length of the ordinary list, assuming we dont detect a collision. Taking again the average under the same distribution as before we get $1/6\,n\,(n + 2)$. So you would then need $O(n^2)$ equality comparisons (inside the ordinary list) or less.
The different program codes look very similar (in Java):
Hash table:
HashSet res = new HashSet();
for (int i=0; i<A.size(); i++) {
    if (res.contains(A.get(i))     /* O(1) */
      return true;
    res.add(A.get(i));             /* O(1) */
}
return false;

Ordinary list:
ArrayList res = new ArrayList();
for (int i=0; i<A.size(); i++) {
    if (res.contains(A.get(i))     /* O(m) */
      return true;
    res.add(A.get(i));             /* O(1) */
}
return false;

We can now make the probability model I was using more explicit. I am using a random variable $X$, for the number of iterations of the outer for loop. The variable is in the range $\{0, .., n\}$, $0$ means a duplicate was found in the first iteration and true was return. $n$ means no duplicate was found and false was return.
I did work with $P[X=i] = 1/(n+1)$ an uniform distribution. The effort of the programm can be viewed as the expected value $E[Y]$ of another random variable $Y = f(X)$, that computes the effort for performing the loop X times. For the hash table we have $Y = X$, and for the ordinary list we have $Y = 1/2\,X\,(X+1)$, neglecting the add() and only considering the contains().
Hash table:
$$E[Y]=E[X]=\sum_{i=0}^n P[X=i] i=\frac{1}{n+1} \frac{1}{2} n (n+1)=\frac{1}{2} n$$
Ordinary list:
$$E[Y]=E[\frac{1}{2} X (X+1)]=\sum_{i=0}^n P[X=i] \frac{1}{2} i (i+1)=\frac{1}{n+1} \frac{1}{6} n (n + 1) (n + 2) = \frac{1}{6} n (n+2)$$
The distribution that was chosen can be viewed as an upper bound, distributions that are more realistic or that also consider that there are multiple duplicates, would give a higher weight to lower values of $X$, which also means a higher weight to lower values of $Y = f(X)$, and thus in the end a lower value of $E[Y]$.
Comment: thanks for the advice of hashtable with direct address;  but can you explain more about the expected run time with the brutal force as well ?
Comment: Brute force, is just using an ordinary list, you get O(n^2) and not O(n). The better formula is 1/6 n (n + 2), but the dominant term is also n^2.
Comment: What does "hash table insert is usually considered $O(1)$ on average" mean? That sounds like nonsense to me.
Comment: See the wikipedia article that I have linked. A full fledge hash table has a load factor, expands itself from time to time and has linked lists, for where the hash collides but the key is still distinct. This gives around amortized O(1) for contains() and add(), as if you were using the key as a direct address.
Comment: But the metric is such that we count computing the hash value and doing the comparison, even if big objects are involved, as one step. As the OP asked "We want to analysis the expected runtime by counting the number of comparisons in the algorithm." Which is a simplification and in reality, for example when using bignums, this is not true.
Comment: BTW: The Java implementation can only grow, it has only a high water mark. This implementation of mine has also a low water mark, and can shrink as well: https://github.com/jburse/jekejeke-devel/blob/master/utils/headless/matula/util/data/SetHash.java


Getting 404 on a specific path /pricing with Apache server

Question: I've set up an Apache server on Ubuntu 20.04
The site loads fine when I load the home page first (https://leadzilla.ai) and after that when I click on the pricing button and it takes me to https://leadzilla.ai/pricing and the that page loads fine as well.
But when I go directly to https://leadzilla.ai/pricing in the browser, I get a 404
Here is what I have in /etc/apache2/sites-available/leadzilla.ai.conf
<VirtualHost *:80>
    DocumentRoot /var/www/leadzilla.ai
    ServerName leadzilla.ai
    ServerAlias www.leadzilla.ai

    <Directory /var/www/leadzilla.ai>
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Allow from all
    </Directory>

RewriteEngine on
RewriteCond %{SERVER_NAME} =leadzilla.ai [OR]
RewriteCond %{SERVER_NAME} =www.leadzilla.ai
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

I have this config in /etc/apache2/sites-available/leadzilla.ai-le-ssl.conf
<IfModule mod_ssl.c>
<VirtualHost *:443>
    DocumentRoot /var/www/leadzilla.ai
    ServerName leadzilla.ai
    ServerAlias www.leadzilla.ai

    <Directory /var/www/leadzilla.ai>
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Allow from all
        #Deny from all
        #Allow from 127.0.0.1
        #Allow from ::1
    </Directory>
    <Directory /var/www/leadzilla.ai/blog>
        AllowOverride All
    </Directory>

Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/leadzilla.ai/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/leadzilla.ai/privkey.pem
</VirtualHost>
</IfModule>

I have Wordpress on https://leadzilla.ai/blog so that has to be taken care of as well.
Here is what I have tried:
RewriteRule ^pricing$ pricing.html [NC]
I added it before the other rewrite rule but that doesn't seem to be working. Any ideas?
[EDIT]
This is solved now. The issue was a Next.js config, not an Apache config.
I put in exportTrailingSlash: true in my module.exports and it worked
Answer: I find this to be curious behavior. But if you have a RewriteRule in the <VirtualHost *:443>, then you should also have RewriteEngine On.
Are there any symbolic links in your directory at all. Anything like foo -> foo.html?
Are there any directories like /var/www/html/pricing/ in your directory structure?
Also, remember, that all of your traffic ends up on HTTPS, which means that only the <VirtualHost *:443> is in play. The other virtual host entry only is used long enough to redirect from HTTP to HTTPS. Any rewrite rules for the :80 VirtualHost do not apply on HTTPS.
Comment: I see. I don't have any symlinks and the structure of the directory is pretty simple as well. Here is a snapshot: https://share.getcloudapp.com/GGuJOORo

Could the issue be due to WordPress?

I have Wordpress in the `blog` folder and in the picture above and the .htaccess looks like this: https://share.getcloudapp.com/mXubkk56
Comment: Wordpress isn't the issue.

There's something else going on here. You're using some sort of web framework or web application, something that I am unfamiliar with. When I click from the homepage to one of your subpages, it works, but I don't see the usual HTTP traffic. My guess is you are using Next.js (?) which means you should look to its configuration if you are indeed using it.
Comment: Yes I am using Next.js but I've run `npm run build` and exported static index.html, CSS and JS files in a directory and put in on the server. I'll take a stab at next.js configuration with Apache


Install clientside PDF editor with WebPack + npm: At all possible?

Question: I want to create PDF's clientside (in the browser). I'm using WebPack to bundle my javascript application and npm to install the needed libraries. I've tried the following without success:

pdfmake
jspdf
pdfkit

Has anyone here gotten this setup to work with any of these (or some other) libraries? Mind sharing how?
Answer: You can use pdfmake-client which is a wrapper to the pdfmake library that serves the client build over npm.
In general pdfmake does have a client build but serves the node version over NPM, this is likely a good case for a PR for that project so it will serve the correct version.
Answer: I was able to get jspdf to work, but the version from npm didn't work.
First I ran npm install jspdf --save
Then I downloaded the the lastest code from https://github.com/MrRio/jsPDF
and ran npm run build
then I replaced node_modules\jspdf\dist\jspdf.min.js with the one I just built.
Then the following code worked
<code>import jsPDF from 'jspdf';

var doc = new jsPDF();
doc.text(20, 20, 'Hello world.');
doc.save('Test.pdf');
</code>
I'm using webpack and nothing needed to be added to the config
More samples of usage can be found here: https://parall.ax/products/jspdf


How do I migrate a SharePoint 2010 site to a new server and new SQL instance

Question: I have a SharePoint 2010 site on a test server and database.
I would like to move my site to a production server and a new SQL instance.
What is the best way to do this?
Was really easy, here are the PowerShell commands for exporting and importing.
Export-SPWeb -Identity http://OLDSITE/ -Path \\SERVER\backup\sharepoint\SiteExport.cmp -IncludeUserSecurity -IncludeVersions All -Verbose

Import-SPWeb -Identity http://NEWSITE/ -Path \\SERVER\backup\sharepoint\SiteExport.cmp -Verbose -Force

Answer: Unless you installed sharepoint using a SQL Alias you will need to create a DNS alias/host file with the old name of the SQL server that points to the new one, and the instance name will need to be the same.

Stop SharePoint
Backup the databases on the old database server
add logins to the new server with sysadmin rights
script out SharePoint jobs from old database server
rename old database server
create DNS alias that point old database server name to the new database server name
restore database backups to the new database server
run job script on new database server
restart SharePoint after a ping resolves the old name to the new server (use ipconfig /flushdns to force update)
Comment: Edited question to include solution.


Populate dropdown list get data from different MySQL tables

Question: I need your help to solve a silly problem.
I have 2 tables in my database (contents and categories).
I have populated my MySQL table called "categories", and now I want to see in a form the old category stored in the database while I modify it to a new one.
Unfortunately what I wrote shows only the list of the categories get from the database table.
<select name="PostedCat">
    <?php

    $query_category = "SELECT * FROM categ";
    $result_category =  mysql_query($query_categ) or die (mysql_error());

    while($categ = mysql_fetch_assoc($result_category)){
    ?>
        <option value="<?php echo $categ['cat_title']; ?>" ><?php echo $categ['cat_title']; ?></option>
    <?php
    }
    ?>
</select>

With this code I can see the categories stored in the database, but how can I get the "old" selected one? The stored one?
Hope in some help, but I'm blind at the moment.
Thank you in advance.
Comment: What "Old category" ? selected by what ? stored where ? the category of contents ?
Comment: Is the contents of the categories database going to change? If not, it would be best to just have an array of the categories rather than a db.
Comment: Yes, the categories could be added/modified/deleted as for the content.
Answer: Assuming your old category is in $oldcat, just do

$query_category = "SELECT * FROM categ";
$result_category =  mysql_query($query_categ) or die (mysql_error());

while($categ = mysql_fetch_assoc($result_category)){
?>
    <option value="<?php echo $categ['cat_title']; if ($categ['cat_title']==$oldcat) echo '" selected="true'; ?>" ><?php echo $categ['cat_title']; ?></option>
<?php
}
?>

Comment: I might be able to help you, If you give more info ... echo `""` inside the loop and post teh output
Comment: Thank you, I moving back home from work and I will add some more code and details.

Thank you again for the kindness
Answer: So, thank you again for the kindness. Here is what I did.
I have a page with the list of all my contents and near each one of those I have and "Edit" button. When I click it, I go to a new page with a filled form that takes data directly from MySQL and place quite everything in the correct field.
In the function.php I have:
function getPost($id) {
    $id = (int) $id;
    $query = mysql_query("SELECT * FROM contents WHERE id = '$id'") or die (mysql_error());

    return mysql_fetch_array($query);
}

In the edit.php I have this for example:
<?php $editedpost = getPost($_GET['id']); ?>
<form action="editingPost.php" method="post">

        Title
        <input type="text" name="ContentTitle" value="<?php echo $editedpost['content_title']; ?>" />

        Category

            <select name="ContentCategory">
                <?php
                $query_category = "SELECT * FROM categ";
                $result_category =  mysql_query($query_categ) or die (mysql_error());

                while($categ = mysql_fetch_assoc($result_category)){
                ?>
                    <option value="<?php echo $categ['cat_title']; ?>" >Here I would like to see the data stored in the database, that I choosed before.</option>
                <?php
                }
                ?>
            </select>

        <input type="submit" name="submit_post_new" />
        <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />

</form>


Amazon automatically deletes a S3 Bucket

Question: I'm making an RDP application, using the Amazon S3 Bucket service, to store images for viewing, and later deletion.
My current flow is as follow:

I take a screenshot of the computer screen
I then take this screenshot and upload it to my S3 Bucket as a JPEG.
After this image has been viewed, I will make a DeleteObjectRequest to delete this image.

This whole process, is repeated once every half a second. So this doesn't actually store the images for very long, only the transfer rate is high.
This process also only runs, when the RDP Service I made is enabled, which could range from 30 seconds to 5 minutes. (So that's maximum of 600 upload requests, and 600 delete requests).
Now, taking into consideration these conditions, why would Amazon delete my Bucket automatically? Is this a restriction, an automatic abuse-mechanism or is it simply a bug?
What could I do to prevent this?
Upload code I use
TransferUtility aws = new TransferUtility(accessKeyId, secretAccessKey, Amazon.RegionEndpoint.EUWest1);

aws.Upload(imageFile, bucketName, imageKey + ".jpg");

Delete request code I use
var dor = new DeleteObjectRequest();
dor.Key = key;
dor.BucketName = bucketName;

Amazon.S3.AmazonS3Client sc = new Amazon.S3.AmazonS3Client(accessKeyId, secretAccessKey, Amazon.RegionEndpoint.EUWest1);
var response = sc.DeleteObject(dor);

Comment: @KevinJensenPetersen when does the bucket get deleted? When you delete an object? And then the next upload fails?
Comment: AWS doesn't automatically delete S3 buckets. Something else is going on. What exactly leads you to think the bucket is being deleted?
Comment: @MarkB Because it get's removed/deleted from my S3 ? It's no longer there, and this has happened twice.
Comment: @Mahdi I really can't tell. It just happens at some point. I've even noticed it got deleted when I didn't make any requests what so ever.
Comment: Turn on [AWS CloudTrail](http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-getting-started.html), wait for the bucket to disappear again, then look at the CloudTrail logs and look for the `DeleteBucket` API call. It will show which User/Role made the API request to delete the bucket.
Answer: I've not heard of AWS deleting buckets proactively -  but there are limits on how many buckets you can create (I believe it is 100 without increasing an account override).
I do question why you keep creating and deleting buckets however - I would think you would be better of creating a bucket and then adding and deleting objects within that bucket, instead of deleting the bucket itself. There is no charge for having an empty bucket, if that is your concern.
Also, make sure the region you are creating the bucket in, is the same place you are looking to see the bucket - just in case you are looking in the wrong place.
Comment: Maybe I wasn't too clear in my answer. I don't actually create and delete buckets, but only the objects INSIDE the 1 bucket.
Comment: So is your bucket disappearing, or the images in the bucket?
Comment: E.J Brennan, the bucket is disappearing.


How to display registration form fields based on the taxonomy term?

Question: I have three taxonomy terms. And I want to display different fields in the registration form based on the taxonomy term.
I want something like this.
taxonomy term 1:
Registration form fields: Name, Email, Password, City, phone
taxonomy term 2:
Registration form fields: Name, Email, Password, Country
taxonomy term 3:
Registration form fields: Name, Email, Password, State, phone
Is it possible? if yes then please guide me.
Answer: On Drupal 7 you've a new API named State API. You can use it to hide or show your fields.
Answer: I think we can try with combination of two module.

field_collection
conditional_fields


Setting repository location on SVNKit's SvnGetStatus

Question: I need to get the current revision of a local working copy.
So far I've come up with this: (EDITED)
private static long resolve(File workingDirectory) throws SVNException {
    SvnOperationFactory svnOpFactory = new SvnOperationFactory();
    SvnGetStatus svnGetStatus = svnOpFactory.createGetStatus();
    svnGetStatus.setSingleTarget(SvnTarget.fromFile(workingDirectory));
    svnGetStatus.setDepth(SVNDepth.EMPTY);
    SvnStatus status = svnGetStatus.run();
    return status.getRevision();
}

I can't find a place to actually specify the location of my working copy, not even in the documentation.
How can I tell SvnGetStatus where to look for the working copy?
Answer: Try setting it as the target of the operation:
svnGetStatus.setSingleTarget(SvnTarget.fromFile(wcLocation))

Comment: @j0ntech You need to `run()` the operation and then fetch the revision number out of the response that `run` returns - `getRevision()` on the operation itself just gives you the revision number you passed as a parameter to the operation (or didn't pass, in this case, hence -1).
Comment: @j0ntech you may be better off using `SvnGetInfo` (the equivalent of `svn info` on the command line) rather than `SvnGetStatus` - by default the "status" operation doesn't return anything if the item you're asking about has no uncommitted changes.
Comment: That still returns the revision as `-1` just like with no target set.
Comment: @j0ntech you should probably `setDepth(SVNDepth.EMPTY)` first so it just fetches the status for that particular item rather than recursing into all the descendants.
Comment: Okay, I didn't think of actually running the operation. I've modified it (see the edit), but now the `SvnStatus` object is null, `run()` returns nothing.
Comment: @IanRoberts is right, "status" reports only locally changed files and directories. Use SvnGetInfo instead.


Align child to top of inline parent in Internet Explorer

Question: I want to align an element to the top of the enclosing inline element. Therefore I'm using this code:
HTML:

    Watch me align!

CSS:
#outer {
    position: relative;
}

#inner {
    position: absolute;
    top: 0;
    left: 0;
    background-color: white;
}

img {
    vertical-align: top;
}

This code works in Firefox and Chrome: The text is positioned in the top-left corner of the image. But in Internet Explorer the text sticks to the bottom of the image.
You can see this in my Fiddle.
After reading this MSDN entry I conclude that the vertical-align property doesn't apply on inline elements since they don't support the valign attribute.
My best idea by now is to reposition the text using some JavaScript, but as you may agree: That's no elegant solution.
So, do you know any neat trick to make this work in Internet Explorer?
IMPORTANT! The following CSS properties of the parent can't be changed:
#outer {
    display: inline;
    position: relative;
    float: none;
}

Comment: Thanks for your suggestions, guys! But I need a real inline element, no inline-block. Sorry, I should've been more precise on that! (Background: If I use any other display value, the images won't stick together on a resize. [Try out here!](http://jsfiddle.net/K9pEb/4/))
Answer: This should work: http://jsfiddle.net/gcG4D/
HTML

    Watch me align!

CSS
#outer {
    position: relative;
    display:inline-block;
    width:auto;
}

#inner {
    position: absolute;
    top: 0;
    left: 0;
    background-color: white;
    display:block;
}

img {
    display:inline-block;
}

Answer: you need to trigger layout to span with

float left or right or
display inline-block , table, inline-table, block ... but
inline or
position fixed or absolute or

http://jsfiddle.net/K9pEb/3/
Answer: Just add display: inline-block; to your #outer class. It should fix your issue in IE.


Prove that $v \in T_mSL(n) \iff \text{tr } v = 0$.

Question: Prove that $v \in T_mSL(n) \iff \text{tr } v = 0$.
I haven't idea how to prove that. I understand next steps:

$SL(n)$ - are the matrices $n\times n$ that have $\det = 1$

$T_mSL(n) = {W_m(SL(n))}/{\underset{m}{\sim}}$

Where $W_m(SL(n)) = \{\gamma \in C^{\infty}((\alpha,\beta), SL(n))\ |\ \gamma(0) = m, 0 \in (\alpha,\beta) \subset \mathbb{R}\}$
And $\gamma_1 \underset{m}{\sim} \gamma_2 \iff\exists$ coordinates $\xi$ that $(\xi \circ \gamma_1)'(0) = (\xi \circ \gamma_2)'(0)$
Next i can't understand how to do tasks like this
Comment: This is not correct unless $m$ is the identity matrix. The tangent space at $m\in SL(n)$ is $\{mv: \text{tr}(v) = 0\} = \{A\in\mathscr M_{n\times n}: \text{tr}(m^{-1}A) = 0\}$.
Comment: I have expend quite a bit my answer in order to provide some insight on the link between submersions and tangent spaces. It is a good exercise to check the unproved assumptions (well-definedness of maps) of my addendum.
Answer: Straight approach. Direct computation from the definition.
By definition, one has:
$$\textrm{SL}_n(\mathbb{R})={\det}^{-1}(\{1\}).$$
Furthermore, for all $X\in\textrm{SL}_n(\mathbb{R})$, $M\mapsto XM$ is a diffeomorphism of $\mathcal{M}_n(\mathbb{R})$, hence it suffices to show that $\textrm{SL}_n(\mathbb{R})$ is a manifold in a neighbourhood of $I_n$ and one will have:
$$T_X\textrm{SL}_n(\mathbb{R})=XT_{I_n}\textrm{SL}_n(\mathbb{R}).$$
Let us show that $\det\colon\mathcal{M}_n(\mathbb{R})\rightarrow\mathbb{R}$ is a submersion at $I_n$. It is a well-known result that:
$$\mathrm{d}_{I_n}\det\cdot H=\textrm{tr}(H)\tag{1}.$$
Hence, $\mathrm{d}_{I_n}\det$ is a submersion since it is a nonzero linear map with codomain of dimension $1$, $\textrm{tr}(I_n)=n$. Finally, $\mathrm{SL}_n(\mathbb{R})$ is a manifold of dimension $n^2-1$ and one has:
$$T_X\textrm{SL}_n(\mathbb{R})=X\ker(\mathrm{d}_{I_n}\det)=\{M\in\mathcal{M}_n(\mathbb{R})\textrm{ s.t. }\textrm{tr}(X^{-1}H)=0\}.$$
If you do not recall how to establish $(1)$ here is a sketch of a proof. For all $(i,j)\in\{1,\ldots,n\}^2$, let $E_{i,j}$ be the matrix with zero entries everywhere except the entry $(i,j)$ which is a $1$. Then, notice that:
$$\frac{\partial\det}{\partial E_{i,j}}(I_n):=\lim_{t\to 0}\frac{\det(I_n+tE_{i,j})-1}{t}=\delta_{i,j}.$$
Indeed, if $i\neq j$, then $\det(I_n+tE_{i,j})=1$ and $\det(I_n+tE_{i,i})=1+t$. Finally, one has:
$$\mathrm{d}_{I_n}\det\cdot H=\sum_{i=1}^n\sum_{j=1}^nh_{i,j}\frac{\partial\det}{\partial E_{i,j}}(I_n)=\sum_{i=1}^nh_{i,i}=\textrm{tr}(H).$$

Addendum. Submersions and tangent spaces.
I am going to expand a bit on the link between the tangent space and the kernel of the differential of a submersion, maybe it will shed some light.
Let $M$ be a manifold of dimension $n$, let $v$ be a point of $M$ and let $(U,\Phi)$ be a chart of $M$ centered at $v$. The map $\ell\colon T_vM\rightarrow\mathbb{R}^n$ defined by:
$$\ell([c])=(\Phi\circ c)'(0),$$
where $[c]$ denotes the tangency class of a curve $c\colon]-\varepsilon,\varepsilon[\rightarrow M$ going through $v$, is well-defined, namely the value $\ell([c])$ only depends of the tangency class of $c$ and is bijective. Indeed, it is injective by definition of the tangency relation and is surjective. If $x\in\mathbb{R}^n$, then $t\mapsto\Phi^{-1}(tx)$ is a curve of $M$ going through $v$ such that:
$$\ell([c])=x.$$
Therefore, one can endow $T_vM$ with a structure of a $n$-dimensional vector space.
Now, let $f\colon X\rightarrow Y$ be a submersion at $v$, with $M\subseteq X$ and $n=\dim(X)-\dim(Y)$ such that:
$$M=f^{-1}(\{y\})$$
Now, notice that if $c\colon]-\varepsilon,\varepsilon[\rightarrow M$ is a curve going through $v$, then:
$$f\circ c=y.$$
In particular, one has $\Phi\circ f\circ c=\Phi(y)$ and by differentiation, one gets:
$$\mathrm{d}_vf([c]):=(\Phi\circ f\circ c)'(0)=0.$$
namely $[c]\in\ker(\mathrm{d}_vf)$. Finally, we have establish that:
$$\ker(\mathrm{d}_vf)\subseteq T_vM.$$
Whence $T_vM=\ker(\mathrm{d}_vf)$, using the equality of dimension between the two vector spaces.

Another approach. The Cartan-Von Neumann theorem.
If you want to involve some machinery, you can always use the following:

Theorem. Let $G$ be a closed subgroup of $\textrm{GL}_n(\mathbb{R})$, then $G$ is a manifold whose tangent space at $I_n$ is:
  $$\mathfrak{g}:=\{X\in\mathcal{M}_n(\mathbb{R})\textrm{ s.t. }\forall t\in\mathbb{R},\exp(tX)\in G\}.$$

This is not a too hard result, the key point is observing that $\mathfrak{g}$ is a vector space which follows from $G$ being closed and the Lie-Trotter formula.
In our case, $\textrm{SL}_n(\mathbb{R})$ is indeed a closed subgroup of $\textrm{GL}_n(\mathbb{R})$, therefore:
$$T_{I_n}\textrm{SL}_n(\mathbb{R})=\{X\in\mathcal{M}_n(\mathbb{R})\textrm{ s.t. }\forall t\in\mathbb{R},\det(\exp(tX))=1\}.$$
Using trigonalization over $\mathbb{C}$, one has:
$$\det\circ\exp=\exp\circ\textrm{tr}.$$
Finally, one gets:
$$\begin{align}T_{I_n}\textrm{SL}_n(\mathbb{R})&=\{X\in\mathcal{M}_n(\mathbb{R})\textrm{ s.t. }\forall t\in\mathbb{R},\exp(t\textrm{tr}(X))=1\}\\&=\{X\in\mathcal{M}_n(\mathbb{R})\textrm{ s.t. }\textrm{tr}(X)=0\}.\end{align}$$
Comment: thank you for your answering. Can you please explain some moments (can't understand your english(I have some problems with this)).

What you mean then use this : $\mathcal{M}_n$ and "submersion"?
Comment: @EugeneKorotkov Sure, $\mathcal{M}_n(\mathbb{R})$ is a notation for matrices with real entries of size $n$ and a submersion is a smooth map between manifold whose differential is surjective at any point.


Convert base64 string to image in react native

Question: Problem
I created a social media app with expo's react native, and wanted to add the ability to upload images. Since expo won't let you convert a file to a blob to upload, I just uploaded the base64 image data as a string to the server database. How can I convert this data into the viewable image again after I download the data from off of the server?
Comment: Instead of trying to upload the image as a blob, create a form and attach the image as a file. You shouldn't store images in a database, you should store them as files that are referenced from the database. See this for an example: https://github.com/g6ling/React-Native-Tips/tree/master/How_to_upload_photo%2Cfile_in%20react-native
Comment: you can use [react-native-fetch-blob](https://github.com/wkh237/react-native-fetch-blob) to convert image to base64 and then again back to image from base64.
Answer: You can do this:
var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANS...';
<Image style={{width: 50, height: 50}} source={{uri: base64Icon}}/>

In the base64Icon variable you need to put your base64 data after data:image/png;base64,. Like this:
var base64Icon = 'data:image/png;base64,{PLACE_YOUR_BASE64_DATA_HERE}';

Comment: What to do if we want to download it ?
Comment: <Image source={{ uri: `data:image/png;base64,${item.appIcon}`}}   am getting base64 icon from api but in react native web not showing the app icon


how can i change the "Create new Account" to Custom registration

Question: Is there any ways to add more fields in "Create new Account" ?
By defaults it provides only username and emailid.
So how can i add more fields like gender, date of birth.
Answer: Fields module should be enabled with Field UI and other.
http://YOURSITE/admin/config/people/accounts/fields - add field, mark "Display on user registration form." on field editing form.


Find the absolute, relative, and percentage errors if x is rounded-off to three decimal digits. Given $x = 0.005998.$

Question: Recently, I am learning about numerical methods and I found this question in the textbook to find absolute, relative, and percentage errors if x is rounded-off to three decimal digits. Given $$x = 0.005998$$ In the solution they have rounded off x to 0.006 but this is rounding off to three decimal places.
Is decimal digit and decimal places equivalent in case of fractional numbers? Please correct where I am making the mistake. I am thinking to round off the number to three decimal digits as 0.00. Please tell am I correct to round off as 0.00 (this is round off to three decimal digits not three decimal places) or not?
Textbook solution:
Number rounded-off to three decimal digits =.006
Error = .005998 – .006 = – .000002
Absolute error $E_a$ = | error | = .000002
Relative error $E_r$ = .0033344
Percentage error $E_p$ = $E_r × 100 = .33344%$
Also, in the textbook, they haven't followed the rules for add/sub/multiplication/division of significant figures. Isn't it necessary to follow the significant rules in final answer to be calculated?
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [here](/help/notation), [here](//math.meta.stackexchange.com/q/5020), [here](//meta.stackexchange.com/a/70559) and [here](//math.meta.stackexchange.com/q/1773).
Comment: @DavidK is it necessary to follow rules of significant figures in numerical computations as I have seen many question in the textbook that clearly ignores the rules for add/sub/multiplication/division of significant figures? or we can take some liberties while calculating the numerical answer ignoring significant figures?
Comment: If the original number is not exact but is itself known only to four significant digits, the relative error should be $0.003$ (one significant digit, the same as for the absolute error) if we are keeping track of significant digits. It is mere coincidence that this is three decimal digits; the percent error is $0.3\%.$ Since I do not have the same textbook I do not know what its overall level of quality is.
Answer: For a given floating-point number (a simplified definition of this is a number with a decimal point included), the terms decimal places and decimal digits are used interchangeably.
This is because a decimal digit literally refers to ta digit following the decimal point. So, for the number you wanted to round off, $x = 0.005998$, the correct answer would be:
$$
x(round-off \ to \ 3 \ decimal \ places) = 0.006
$$
The key point is identifying that decimal places and decimal digits are the same. When asked to round off to a certain decimal place, you must have that many digits following the decimal point.
As for your query on the rules of mathematical operations based on the significant digits, it is important to understand that the final digit in a number is unknown. Meaning that the right-most digit always is uncertain and has the possibility of being different. It appears that the purpose of this exercise is to introduce you to how rounding off can create errors. In this case, you would consider the following:
$$
\begin{align}
x & = 0.005998 \\
x(rounded) & = 0.006000 \\
Error (absolute) & = 0.000002
\end{align}
$$
You need to fill in the decimal digits to the right of the rounded-off representation with zeros in order to perform some mathematical operation. You are absolutely correct in pointing out that the rules of significance are not followed and that the answers should have also been rounded off to the 3rd decimal place. However, it is assumed in most cases and not explicitly mentioned, which is what appears to have been assumed in this question.
Comment: So, let's take number as 8.00598, after rounding off it to three decimal digits, will it be 8.006?
Comment: I disagree strongly that the errors should also have been rounded to three places after the decimal. In the case of the absolute error, that would result in an answer of zero for every problem, making the term "absolute error" meaningless. While the other error measurements would not also go to zero, we are asked for measurements based on the original knowledge of the number to more than three decimal places, and we should use that knowledge.
Comment: @DavidK But that's the whole point of the error or meaning of uncertainty! The right-most digit is always uncertain with a varying probability of being incorrect. So in this case, while the intent is to have the user compute error to the 6th decimal place, OP is correct in assuming that it should be rounded off to 3 places. So, the absolute error of 0.000 indicates that the final digit is uncertain and may not necessarily be zero. I have pointed out here how the question seems to have assumed what you're trying to say, but the OP is actually correct in saying the rules haven't been followed.
Comment: @HarshitSingh That's correct, if you have to round off 8.00598 to 3 decimal places, it becomes 8.006. If you found this answer helpful, kindly upvote it so that I know it's been of use. Thanks!
Comment: We will just have to disagree then. I have never seen your interpretation from any reliable source.
Comment: @HarshitSingh If you have found an answer to be helpful, kindly consider upvoting it or marking it as correct, so that we know we've been working in the right direction. Have a great day!
Answer: X=0.005998 upto three decimal point=0.006

Absolute error=0.005998-0.006
Relatable error =(0.005998-0.006)/0.005998
Percentage error= {(0.005998-0.006)/0.005998}.100th%
Kindly calculate all those calculation by ownself


Realm AddChangeListner is not Working?

Question: I have two classes where one class adds the data in table another class where I have retrieved the data.I have added changeListener but it didn't execute after the table is changed. Below is the code
<code>  RealmResults<MessageContentTable> messageContentTables=
   realmObject.where(MessageContentTable.class).findAllAsync();
    messageContentTables.addChangeListener((collection, changeSet) ->
     {
        Log.e("Updating 123"+collection.size());

    });
</code>
Comment: Can you try shifting from async query to a sync query and then try it.
Answer: You need to store field variable (strong reference) to your RealmResults, otherwise it'll be consumed by the garbage collector and Realm won't be able to call the change listener anymore.
<code>RealmResults<MessageContentTable> messageContentTables;

public void something() {
    messageContentTables = realm.where(MessageContentTable.class).findAllAsync();
    messageContentTables.addChangeListener((collection, changeSet) -> {
        Log.e("Updating 123"+collection.size());
    });
</code>

Realm AddChangeListner is not Working?


SQL Server Trial Edition to Full Edition

Question: I installed SQL Server 2008 R2 for the 180 day trial. We tested the system and it's working fine, and I wanted to convert it to full version.
The problem is, I have a volume key licence to SQL Server, and the Microsoft support says that there is no key for SQL Server Standard editions (SQL Server (2008 or 2008 R2 ) ), and says that If I use the disc, the product will install automatically without requiring my keys.
My question is, how to convert the trial to the full version - I don't want to go through the hassle of setting up everything.
Thanks!
Comment: I would like to thank user67714 as this worked for me in Server 2012. I even called Microsoft and they said you have to uninstall the trial version and download the correct version from the Volume License portal which has the embedded license. Thank you so much!
Answer: What you want to do is treat it like an edition upgrade. Grab your VL copy of SQL Server, start the install, select the maintenance tab, and choose edition upgrade. See this blog posting on MSDN:
http://blogs.msdn.com/b/wesleyb/archive/2010/05/03/can-i-upgrade-my-sql-server-2008-r2-trial-to-a-full-version.aspx
Comment: I figured another way out. I inserted the VL copy and started the installation process, and in the screen where I am supposed to enter the Key, the Key was auto-populated. So I copied that key and used it to validate my trial version.
Answer: I know this is an old post but since it comes up on top in a Google search I thought I'd add my findings for SQL 2012 and Open Volume License which probably also applies to 2008
From the x64 directory of the SQL 2012 Standard Open Volume installation media there is a file named DefaultSetup.ini
That file contains the PID installation key required to do a version upgrade/downgrade.


xpages SSJS: cannot get rid of "com.ibm.xsp.acl.RedirectSignal" warnings in log

Question: I am building a multilingual application and I am storing the value of the latest language used in a cookie.
When the user opens up the application, the sessionScope variable is not set and the code will look for the cookie value and reload the page if not in the proper Locale.
I am getting the "com.ibm.xsp.acl.RedirectSignal" warning each time the page is reloaded in the proper locale, and I'd lilke to avoid it.
My code is located in the beforeRenderResponse event of the ApplicationLayout control I am using in the application, and looks like this:
if(!sessionScope.lang) {  //this only happens when the page is opened in browser for the first time
    var lang = context.getUrlParameter("lang").toLowerCase();
    if(!!lang) {
            sessionScope.lang = lang.toUpperCase();
            //set cookie for next time the site is opened by user
            setCookie("lang", lang.toUpperCase(), 30);
            context.setLocale(new Locale(lang.toLowerCase()));
    } else {
        //set language from cookie
        var lang = getLangFromCookie();
        if(!!lang) {
            sessionScope.lang = lang;
            context.setLocale(new Locale(lang.toLowerCase()));
        } else {
            sessionScope.lang = Appconfig.defaultLang;
            context.setLocale(new Locale(Appconfig.defaultLang.toLowerCase()));
        }
    }

    //need to trpa the redirect error thrown here, as it is just a warning - avoid filling log with this
    //importPackage(com.ibm.xsp.acl.RedirectSignal);
    importPackage(com.ibm.xsp.acl.RedirectSignal);

    try {
        //reload the page so Locale value kicks in
        context.reloadPage();
    } catch (RedirectSignal rs) {
        //just ignore
    }
}

Even though I added the importPackage line, I am still getting an error when saving the code (it is in a script Library):
Encountered " "rs"" at line...
How can I make this work?
Thanks :D
Answer: The catch is a Throwable, not a RedirectSignal. Here's the code I use in my handleException function
try {
    try {
        if (t instanceof RedirectSignal) {
            return;
        }
        if ("javax.faces.el.EvaluationException".equals(t.getClass().getName())) {
            if (t.getCause() instanceof RedirectSignal) {
                return;
            }
        }
    } catch (Throwable e) {
        // Error checking cause, skip
    }
    // Now log the error
} catch (Throwable e) {
    e.printStackTrace();
}

Comment: The code I gave was Java - sorry, I don't write much SSJS these days. Using it from SSJS is problematic. SSJS doesn't throw a Java Exception or Throwable. It's a variety of Java classes, as you'll see if you look at the processUncaughtException method in XPages OpenLog Logger's PhaseListener. The catch block won't need to specify Throwable, but I'm not sure if printStackTrace() and "instanceof" are available or relevant. getClass().getName() would work. Tommy's code will work for a specific call to context.reloadPage().
Comment: How can I do that in SSJS?  I can't seem to use the Throwable t as the catch parameter.
Comment: Alternatively, you may want to crerate a generic SSJS method where you pass the page to redirect to. If no page is passed, then call context.reloadPage(), otherwise context.redirectToPage(passedVal)
Answer: In SSJS you don't define the type/class of the exception in the catch block. Since you're not doing anything with the "exception", there's also no need to import the RedirectSignal class.
try {
    context.reloadPage();
} catch ( redirectSignal ) {
    // Ignore redirect signal "exception"
}

Comment: Works like a charm, I don't see the redirect messages in the log anymore.  Not sure why I got this message, but from what I have read, it seems it might be when a page redirects to itself.  If that's the case then this was an expected behavior as I am indeed reloading the same page, after changing the Locale, so the page reloads in the proper language.  Can't live with the browser's Locale only, I need the user (or a URL param or even a cookie) to have the choice of his Locale, independant of the browser.


How Could Python iterate the directoriy and detect the new files?

Question: How can I iterate all files and subdirs in  a Dir,
and can detect new file when put there?
Thank you for your help!
Comment: allfiles = list(os.walk(the_dir))
Comment: please follow the link : http://stackoverflow.com/questions/4582550/file-walking-in-python
Answer: Try os.walk. More specifically, try:
top="."
import os
for root, dirs, files in os.walk(top):
    for name in files:
        # do something with each file as 'name' (a)
        pass
    for name in dirs:
        # do something with each subdir as 'name' (b)
        pass
    # do something with root (dir path so far)
    # break at any point if necessary

To answer the question in your comment, at point (b) in the code, you can handle any subdirectory logic (also you can check to test that you have the right subdirectory to do certain custom logic on), via another function or directly/inline.
Comment: How does it can detect the new files at the Dir or subDir?


Is it a bad idea to install ADFS on the AD server itself?

Question: Working with a client to configure ADFS, just got this in an e-mail:
"We are using Server 2008 Enterprise with AD, GP, DNS and DHCP running on the same box."
And now he indicates he wants to also install ADFS on the same box as well. I am not even sure if ADFS and AD can be on the same server, but if it can be I also wonder if it is a good idea or not.
Answer: It should be fine to install on your Domain controllers.  As long as sane lookup caches (for DNS) and leases (for DHCP) are had, and you have a proper amount of DCs for your environment (the answer is never "one DC"), ADFS should not present a huge amount of load.
Comment: But you are installing IIS and exposing the box to the Internet, which I would not recommend doing on a DC for security purposes.
Comment: "ADFS's use of IIS was removed in Windows Server 2012 R2 and so it is now okay to run AD FS on a domain controller... In production, it would be recommended that the AD FS server was behind a Web Application Proxy." - [MSDN](https://msdn.microsoft.com/en-us/library/dn660966.aspx)
Answer: Yes its a supported configuration to have AD and ADFS on the same box so no problems there. But as the general preference is to have AD roles on dedicated servers, its not an encouraged configuration.
When you upgrade the AD in the future, you'd have to do in place upgrades of this server instead of demote/promote new DCs.
If you are also planning this server to be internet accessible, then its also not a good configuration from a security perspective unless you plan to have ADFS proxies too.
So if this is a very small environment where they have no other servers or means of even using virtualization to host roles on different OS guests, then yes you can do it.
Comment: As of 4/21/2015 it is actually recommended on TechNet to install ADFS on the DCs for less than 1000 users. ref: https://technet.microsoft.com/en-us/library/dn151324.aspx#BKMK_3
Comment: Although the point about upgrading in place versus demote/promote is definitely something to consider
Answer: I'm fairly certain you will need to specify LDAP ports other than default in this scenario.  Otherwise, it should function fine.
Comment: I believe you are thinking of AD LDS. In which case you would need to specify other ports for the LDS instance.


Linux DDOS Protection / Gateway without NAT

Question: I need help to configure a box for DDOS protection and provide external ip addresses to "internal" (which aren't really internal) servers.
I have 32 IP addresses from my ISP.
I want to configure a linux box with DDOS protection and put servers behind that box. Everything using those IP addresses.
Something like this:
ISP   <--->      Anti-DDOS / Gateway  <--->    serverA/serverB/serverC/etc...
xx.xx.xx.190         xx.xx.xx.189              xx.xx.xx.171 -> xx.xx.xx.188
To be precise, i still didn't started to configure the boxes and i already found a similar topic here but for ipv6.
Note: The servers need to have the public ips configured (No NAT or private IPs are to be used).
Note 2: No, my ISP doesn't provide me a DDOS protection.
What you recomend for software and configuration? My operating systems are Linux Debian only but can use others OS (no windows please!)
Regards
Answer: There are multiple ways to achieve this. For example by making a Linux Bridge (follow this tutorial for a bit). Another way is (for example) making a loadbalancer with IPVS (you can then bind the external IPs on the loopback interface on each client).
Comment: Hello Jeroen. Thanks for your reply and suggestion.
On that Linux Bridge can i have some kind of DDOS protection? What do you recomend? Actually i am using iptables with some sort of packet analysis with conn_track on another box. But i see it's not fully efficient.
Comment: We have a dedicated (hardware) DDoS appliance for that, because it has custom ASICs. The problem with a linux box is that it will be limited on interrupts / cpu processing. I would recommend using a really good quality NIC and run irqbalance (if not already). However, it will never be able to reach the performance that a specialized appliance has.

To block and detect attacks, you can either write something yourself with IPtables or use firewall packages (CSF). There are also commercial solutions like Clavister (software).
Comment: Thanks for your suggestion.
But after having invested in so many dedicated servers, there's no more budget this year for a dedicated DDoS appliance. I can manage to make the bridge but i don't see how can i integrate the CSF (or any other) on that.


Displaying current date with Javascript

Question: var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var n = weekday[d.getDay()];
document.write(n + getDate + getFullYear);

I'm having trouble displaying the current date. Any help would be helpful.
Comment: `getDate` and `getFullYear` need to be accessed through the _Date instance_, `d`, and they are _functions_ so they need to be _invoked_ with `()`, i.e. `d.getDate()`. Also, don't forget about _Array literals_ `['a', 'b', 'c']`, they will save you a lot of typing.
Comment: As it stands, the current code will most likely throw a _ReferenceError_. You can see any error messages in your browser's _Console_ (usually accessible by F12 or Ctrl+Shift+J). The message will give you some useful hints about what may be wrong and the line number (clicking the line number will take you to exactly where the error was thrown)
Answer: Looks like the problem is in your call to document.write. You need to call getDate and getFullYear on the date object you created (d). See below

var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var n = weekday[d.getDay()];
document.write(n + ', ' + d.getMonth() + '/' + d.getDate() + '/' + d.getFullYear());

Displaying current date with Javascript


PHP MYSQLi Array no select html

Question: Sou iniciante em php e estou desenvolvendo um pequeno sistema para minha empresa e que já serve como estudo, pois gosto muito desse área, a dúvida é simples, tenho o código abaixo:
<?php
include('conn/conexao.php');
$edt = $_GET['edital'];
$sql = "SELECT * FROM edt_cadastro WHERE id = $edt";
$res = $mysqli->query($sql);
$num = $res->num_rows;

for ($i = 0; $i < $num; $i++) {
  $dados = $res->fetch_array();
  $arrRefs[$dados['id']] = $dados['ref0'];
}
?>

Referências:
<select name="ref" id="ref">
  <?php foreach($arrRefs as $value => $nome){
    echo "<option value='{$value}'>{$nome}</option>";
  }
?>
</select>

com esse código ele identifica a opção de um select anterior para carregar esse select acima (com jQuery), até ai funciona certinho, só que o valor que vem do banco para esse select, vem como um array exemplo "1,2,3" eu gostaria que ele me mostrasse um lista com 1 depois o 2, o 3 e assim por diante, no banco está separado com virgula "," (1,2,3) eu já tentei usar a opção explode porém dai na lista só aparece o ultimo registo no meu exemplo o número 3. alguém poderia de ajudar? obrigado
Comment: Denis, se conseguiste resolver podes colocar a solucão como resposta (e não como comentário) ou então podes apagar a pergunta. Bom Ano Novo!
Comment: galera consegui, com o seguinte cod:
query($sql);
$i = 0;

?>

Referências:

fetch_array()) {
 $referencias = $row['ref0'];
 $quantidade_ref = explode(",",$referencias);
 $total=count($quantidade_ref);
 $n = 0;
 while($n < $total)
 {
 $i++;
    echo ''.$quantidade_ref[$n];
 $n++;
 }

}
?>
Answer: Consegui, com o seguinte cod:
<?php
include('conn/conexao.php');
$edt = $_GET['edital'];
$sql = "SELECT * FROM edt_cadastro WHERE id = $edt";
$res = $mysqli->query($sql);
$i = 0;
?>
Referências:
    <select name="ref" id="ref">
        <?php while ($row = $res->fetch_array()) {
            $referencias = $row['ref0'];
            $quantidade_ref = explode(",",$referencias);
            $total=count($quantidade_ref);
            $n = 0;
            while($n < $total) {
                $i++;
                echo '<option value="'.$i.'">'.$quantidade_ref[$n];
                $n++;
            }
        }?>
    </select>

Comment: Recomendo não utilizar a query como você está fazendo.
Leia sobre PreparedStatement.
Comment: Não seria melhor eliminar o `$n` e fazer simplesmente `echo ''.$quantidade_ref[++$i];` ? Ou melhor ainda, no lugar do `while($n<$total)` um `for($i=0; $i<$total;$i++)`...

PHP MYSQLi Array no select html


Cannot create Blob Container with Azure's REST API

Question: I'm trying to create a Blob Container using C# and the REST API (in Xamarin.Android).  I'm able to upload a blob to an existing container, but I can't seem to create a container via REST. The error is (403) Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.  Creating the Authorization Header works when uploading a blob, so it must be something with the way I'm constructing the container's string to be signed, but for the life of me I can't find the problem.  Here's the code:
    private async Task<bool> CreateContainer(string containerName)
    {
        String requestMethod = "PUT";
        String msVersion = "2009-09-19";
        string dt = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);

        String canonicalizedHeaders = String.Format("x-ms-date:{0}\nx-ms-version:{1}", dt, msVersion);
        String canonicalizedResource = String.Format("/{0}/{1}\nrestype:container", AzureStorageConstants.Account, containerName);
        String stringToSign = String.Format("{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canonicalizedHeaders, canonicalizedResource);

        string auth = SignThis(stringToSign);
        string urlPath = string.Format("https://{0}.blob.core.windows.net/{1}?restype=container", AzureStorageConstants.Account, containerName);
        Uri uri = new Uri(urlPath);

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("x-ms-date", dt);
        client.DefaultRequestHeaders.Add("x-ms-version", "2009-09-19");
        client.DefaultRequestHeaders.Add("Authorization", auth);

        HttpContent empty = null;
        HttpResponseMessage response = await client.PutAsync(uri, empty);

        return response.IsSuccessStatusCode;
    }

    private static String SignThis(String StringToSign)
    {
        String signature = string.Empty;
        byte[] unicodeKey = Convert.FromBase64String(AzureStorageConstants.Key);
        using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey))
        {
            Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(StringToSign);
            signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
        }

        String authorizationHeader = String.Format(
              CultureInfo.InvariantCulture,
              "{0} {1}:{2}",
              "SharedKey",
              AzureStorageConstants.Account,
              signature);

        return authorizationHeader;
    }

Answer: The reason your request is failing is because you're not including the content length in your stringToSign even though it is included in the request (HttpClient is including it and setting its value to 0). This is causing signature to mismatch. To fix this, include content length in your stringToSign:
String stringToSign = String.Format("{0}\n\n\n0\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canonicalizedHeaders, canonicalizedResource);


Form multiselect item and url encoding with GET method

Question: I have a form on a Drupal 7 site, which is submitted using the GET method to refresh the page's display using the query parameters.
One of the parameters uses the select box, with the multiple option.  This results in the query parameter using the format option%5B%5D=39&option%5B%5D=54
Is there a way to have the form submit and merge the query parameters into something like option=39+54
Answer: This is the solution that I have working at the moment, although I am not sure if this is the correct way to do this.
First is that instead of loading the form into my render array with drupal_get_form() I have now used drupal_build_form() which seems to allow GET method forms to use the validate and submit form hooks.
Then in the submit hook have $form_state['redirect'] to a custom formatted URL which is cleaner for end users.


Log4net creating (null) files

Question: I have Log4net configuration in app.config file with the file name set as a property as shown below. But On loading the application, files with name '(null)' are getting created.
I have removed [assembly: log4net.Config.XmlConfigurator(Watch = true)] from AssemblyInfo.cs file also. Still I am facing the issue.
<logger name="ReportLogger">
  <appender-ref ref="RollingFileAppender2" />
  <level value="ALL" />
</logger>
<appender name="RollingFileAppender2"
type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString"
 value="C:\MyApplicationLogs\%property{ReportName}.log" />
  <appendToFile value="true" />
  <rollingStyle value="Composite" />

  <maxSizeRollBackups value="10000" />
  <maximumFileSize value="1MB" />
  <countDirection value="1"/>
  <immediateFlush value="true" />
  <appendToFile value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%message%n" />
  </layout>
  </appender>

And my code is as follows:
    public void LogReport(object msg, string filename, string date)
    {
        ReportMsglogger = LogManager.GetLogger("ReportLogger");

        string AppLogFileName = GetTextReportFileName(filename, date);

        try
        {
            if (!String.IsNullOrEmpty(AppLogFileName))
            {
                log4net.Repository.ILoggerRepository loggerRepository2 = LogManager.CreateRepository(AppLogFileName + "Repository");
                ThreadContext.Properties["ReportName"] = AppLogFileName;
                log4net.Config.XmlConfigurator.Configure(loggerRepository2);
            }
        }
        catch (Exception ex) { }

        ReportMsglogger = LogManager.GetLogger(AppLogFileName + "Repository", "ReportLogger");

        ReportMsglogger.Info(msg);
    }

Can someone tell me what is wrong here.
Comment: Did you add this ? `private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);`
Answer: Make sure to assign a value to ThreadContext.Properties["ReportName"] before you make any Log4net related call.
The code in your question makes a call to ReportMsglogger = LogManager.GetLogger("ReportLogger"); before initializing ThreadContext.Properties["ReportName"].
Because of this, the name of the file will be (null).
Also ensure to initialize Log4net only once.
log4net.Config.XmlConfigurator.Configure(loggerRepository2); must not be called multiple times.
The code below shows the correct order about how to set the file name, initialize Log4net and log a message.
// Set log file name.
string AppLogFileName = "MyLogFile"; // Retrieve from GetTextReportFileName(...)
ThreadContext.Properties["ReportName"] = AppLogFileName;

// Set up Log4net.
ILoggerRepository repository = log4net.LogManager.GetRepository(Assembly.GetCallingAssembly());
XmlConfigurator.Configure(repository);

// Log a message.
var logger = LogManager.GetLogger("ReportLogger");
logger.Info("Hello world");

Answer: Your log4net config appears to be not well configured. Here is my config (web.config) :
<log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="\\Path\\To\\Your\\File.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>

    <root>
      <level value="ALL" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>

Then add this on your code files :
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Now, you'll have to call Log in your methods like this :
Log.Info(MethodBase.GetCurrentMethod().Name);

Try this and tell me if it works
Comment: Tried this. Its not working. Still null files are being created when application loads.
Comment: Also, My problem is when I dynamically create file using 'property' like in here -    this problem happens.  When the application loads, my reportname string is not assigned any value.
Comment: you can also refer to this : https://stackoverflow.com/questions/19116854/log4net-c4-0-null-in-output/19117013

Log4net creating (null) files