text:
Q: Bind bxslider after ajax call in WP Please help me with binding bxSlider on Ajax response, tried on. , tries function after but no help (think problem with lack of JS syntax knowledge).
Here's JS:
    $('.catalog-menu-links a').click(function(event) {
    event.preventDefault();

    // Set class to newly selected language button
    $('.catalog-menu-links li.current-menu-item').removeClass('current-menu-item');
    $(this).parent().addClass('current-menu-item');

    // Get new language data URL
    var href = $(this).attr("href");

        $.get(href, function(data) {

        var ajaxCatalogSliderContent = $(data).find('.catalog-slider').html();
        $('.catalog-slider').fadeOut('slow', function(){
            $('.catalog-slider').html(ajaxCatalogSliderContent);
            }).fadeIn();
        //alert($('.catalog-slider').html());
        $('body .bxslider-catalog').bxSlider({pager: true,controls: true,mode: 'fade'});
    });
});

I tried this:
    function startCatalogSlider() {
    $('.bxslider-catalog').bxSlider({pager: true,controls: true,mode: 'fade'});}
startCatalogSlider();

    $('.catalog-menu-links a').click(function(event) {
    event.preventDefault();

    // Set class to newly selected language button
    $('.catalog-menu-links li.current-menu-item').removeClass('current-menu-item');
    $(this).parent().addClass('current-menu-item');

    // Get new language data URL
    var href = $(this).attr("href");

        $.get(href, function(data) {

        var ajaxCatalogSliderContent = $(data).find('.catalog-slider').html();
        $('.catalog-slider').fadeOut('slow', function(){
            $('.catalog-slider').html(ajaxCatalogSliderContent);
            }).fadeIn();
        //alert($('.catalog-slider').html());
        startCatalogSlider();
    });
});

But with no successful result


text:
Q: How to install pymedia without compiling prereq's from source? I'm trying to install pymedia: http://pymedia.org/ on ubuntu.  I'm fine with building pymedia itself from source, as that seems my only option, but I'd rather not have source built versions of its prerequisites lying around if I can avoid it.
I installed most of the prereq's with the following:
sudo apt-get install python-dev libogg-dev libvorbis-dev libfaad-dev libasound2-dev libmp3lame-dev
Then I downloaded the pymedia source tarball and ran:
python setup.py build
With that I get:
OGG          : found
VORBIS       : found
FAAD         : found
MP3LAME      : found
VORBISENC    : found
ALSA         : found
Continue building pymedia ? [Y,n]:

Which looks good.  I hit yes.. and it errors out with:
#...
g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions build/temp.linux-x86_64-2.6/sound/sound.o build/temp.linux-x86_64-2.6/sound/resample.o build/temp.linux-x86_64-2.6/sound/fft.o -logg -lvorbis -lfaad -lmp3lame -lvorbisenc -lasound -o build/lib.linux-x86_64-2.6/pymedia/audio/sound.so
/usr/bin/ld: build/temp.linux-x86_64-2.6/sound/sound.o: relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
build/temp.linux-x86_64-2.6/sound/sound.o: could not read symbols: Bad value
collect2: ld returned 1 exit status
error: command 'g++' failed with exit status 1

What gives?

A: This error is not related to the prereqs, it's likely a bad build script.
If I understand this correct (my C-foo is weak) 64bits shared libraries must be compiled with the -fPIC flag and sound.cpp isn't in this case.
In the setup.py of pymedia there is a function called *disable_fPIC* that forces gcc to compile all it's libraries without it. You can try to disable that function (just replace all the code with a pass statement) and try to compile it again. It shoul read something like this:
def disable_fPIC():
    pass

I can't test it as my machine is 32bits, so I can just hope that it helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Algorithm to test file equivalence I'm writing a program that needs to test if a file is equivalent to one or more other files. To accomplish this, every time we see a new file we stat the file and get the size.
We use the size as a key and if we've never seen the size before than we know that's a new file.
If we have seen that size before we were planning to md5 the first 4k and last 4k of the target file and check to see if that hash has been seen in list associated with the size key.
I don't want to hash the whole file since these files can be rather large (largest I've seen so far is 90G).
The goal is to avoid spending a lot of time on redundant file comparisons. Will this algorithm work, and can it be improved?
More details on my particular problem: I'm attempting to deduplicate a decently sized set of data ( 2Pb ) that contains a large amount of time stamped files (about 40%) created from syslog on FreeBSD machines. Before I start chewing through that many files line by line I wanted to make sure that the file I was looking at hadn't been seen before.

A: It sounds like you are trying to optimize the file comparison because that can be a potentially expensive operation:

*

*If two files have different sizes, they must be different files.

*If the first and last 4K of two files hash to different values, they must be different files. The first portion will check stuff like a file identifier commonly included in the first few bytes, while the last would help catch cases where a file is being appended to (e.g. a log file), similar to what tail checks.

Next you would have to compare the entire file just to be sure. At this point it might makes sense to store multiple hash values (MD5 if security is not a concern, SHA2, etc). You should be able to find a way to read in the file once and feed it to multiple hash algorithms. Then you store a data structure with all of the hashes, which you can very quickly compare with other data structures for other files.
If all of those tests pass (files likely but not necessarily equal) then you might need to perform a full file comparison.
I think your algorithm sounds reasonable, and I think my minor additions will help.
Based on the clarifications in the question, I think your approach will work. The odds that log files are the same size and the first and last portions hash the same is extremely low. If you use a strong hash algorithm with a large output size (compared to MD5), the chance is even lower: with SHA-512, the internal state and output range are ginormous. Given we are talking about log files that are very likely to have date/time stamps at the start of each line, the input should have enough entropy to make this a non-issue.

A: Your approach is good... if the files have completely random data. Here are some things to consider:

*

*How bad is it if there are collisions? If you need a mission critical guarantee (e.g. those astronauts on the ISS will die if a collision occurs), your algorithm may not be good enough, even though there are 10^38 possible MD5 hashes. People do win the lottery occasionally, after all, though for random data this is probably safe.

*This is the more important one: if the files are all generated in the same way, have similar formatting, records, have header/footer information, etc. then it's actually possible that these files begin and end exactly the same way - and would thus have the same hash - even though they are not the same.

So, you're barking up the right tree, but definitely pay attention to the actual details of your use case to ensure you're not overlooking something obvious.

A: Data deduplication is also often called "record linkage", so you may want to also use that as a search term when researching this.
There is an article on the Eventbrite engineering blog that explains how you could greatly reduce the number of file comparisons by using Multi Index Locality Sensitive Hashing. In short, you create a special kind of hash value whereby similar documents will have hash values that are close by. You can then compare potentially similar documents byte for byte because the number of documents you have to compare to is a much smaller set.

A: Elaborating a bit on Snowman's answer, I think I would go for a hierarchy of hash values over (exponentially) increasing subsets of the file, computed on-demand whenever collisions occur, and memorized in a suitable data structure (hash table, but even a simple prefix tree would do) for quick future access. This should ensure quick failure in case of 'almost identity', and retain the worst-case complexity (up to a log factor) and achieve good average-case complexity.
It would go as follows in pseudo-Python, taking as input a file f, a set of files D and a dictionary H (again, one could do better here, but it should not matter too much) acting as a cache for previously computed hash values:
collisions = [fc for fc in D if size(fc)==size(f)]
size_hash = 4*1024
while (len(collisions) > 0) and (size_hash<=size(f)):
  H[(f,size_hash)] = md5(f,size_hash)
  for fc in collisions:
    if (fc,size_hash) not in H:
      H[(fc,size_hash)] = md5(fc,size_hash)
  collisions = [fc for fc in collisions if H[(fc,size_hash)]==H[(f,size_hash)]]
  size_hash *= 2
for fc in collisions:
  # Painstakingly read and compare content to that of f...

Worst-case complexities: In the worst case, all of the files have equal length n, and have different yet MD5 identical (unlucky!) contents, so one ends up computing MD5 hashes for chunks of size 4k, 8k, 16k... n in each of the files, only to read them in full afterward.
In term of time, the first 4k of each file are read to compute the first hash, then the first 8k for the second, 16k for the third ... then the full size n. Computing an MD5 can be done in linear time, so the total time-consumption is (up to a constant) 4k+8k+16k+...+n < 2n operations, i.e. it remains in the order of magnitude of the final (unavoidable) comparison of the files.
In term of memory, log(n) MD5 hash values (one for 4k, one for 8k...), each of constant size will be stored, so the overhead should be reasonable.
Average-case complexities: I won't detail the analysis (maths are not permitted by the markdown system here anyway :) ), but even assuming a large number of files having equal size, the expected number of computed hash values should be constant on average, so this algorithm will neither read significant chunks of the files, nor clotter the memory.

A: Without some knowledge of the nature of the files you cannot be sure without hashing the entire file. Checking the file size and hashing only a portion of the file contents is sufficient only if you can guarantee that the contents will be unique in the hashed portions.


text:
Q: MySQL 5.6.21 on Debian 7.7 -- nice is automatically set to 19 several seconds after starting it up; can't figure out why I'm running MySQL 5.6.21 on an OpenVZ VPS with Debian 7.7. MySQL is installed from the DotDeb repository (full version number is 5.6.21-1~dotdeb.1).
Whenever the MySQL server is started or restarted, at first its niceness is 0. However, approximately 20 seconds later, it gets automatically reniced to 19 (lowest priority), and I can't figure out why.
I searched through all the configuration files, I verified that there are no cron jobs set to do this, and I looked through the startup script (/etc/init.d/mysql). There is nothing there that would be causing this.
If I manually renice it back to 0, sometimes it stays at 0, and sometimes it eventually gets reniced to 19 again.
It's not causing any performance issues for the websites hosted on this VPS (I have some very efficient caching in place which limits the need to even touch the database), but this little mystery is starting to get on my nerves. I'm a MySQL DBA by profession and have a MySQL 5.6 Database Administrator certification from Oracle, but I can't figure out this quirk...and it is very frustrating for me.
Sure, I could just set up an hourly cron job checking the niceness of the MySQL server process, and if it has changed, renice it back to 0, but I want to know why it is happening, not just slap a band-aid over it.
Any thoughts or assistance would be greatly appreciated. Thank you!
/etc/mysql/my.cnf
[client]
socket  = /var/run/mysqld/mysqld.sock

[mysqld_safe]
nice      = 0
socket    = /var/run/mysqld/mysqld.sock
log_error = /var/log/mysql/mysql-error.log

[mysqld]
basedir                         = /usr
bind_address                    = 127.0.0.1
connect_timeout                 = 30
datadir                         = /var/lib/mysql
innodb_buffer_pool_size         = 224M
innodb_file_per_table           = 1
innodb_flush_log_at_trx_commit  = 2
innodb_log_buffer_size          = 4M
innodb_log_file_size            = 8M
innodb_open_files               = 2048
innodb_thread_concurrency       = 8
interactive_timeout             = 60
join_buffer_size                = 2M
key_buffer_size                 = 128K
log-queries-not-using-indexes   = 1
long_query_time                 = 2
max_allowed_packet              = 16M
max_connections                 = 125
max_connect_errors              = 100
max_heap_table_size             = 1M
pid_file                        = /var/run/mysqld/mysqld.pid
query_cache_limit               = 8M
query_cache_min_res_unit        = 1K
query_cache_size                = 48M
query_cache_type                = 1
read_rnd_buffer_size            = 1M
skip_external_locking           = 1
slow_query_log                  = 1
slow_query_log_file             = /var/log/mysql/mysql-slow.log
socket                          = /var/run/mysqld/mysqld.sock
sort_buffer_size                = 1M
table_definition_cache          = 2048
table_open_cache                = 2048
table_open_cache_instances      = 4
thread_cache_size               = 16
tmp_table_size                  = 1M
user                            = mysql
wait_timeout                    = 60

[mysqldump]
max_allowed_packet = 16M
quick
quote_names

[isamchk]
key_buffer = 128K

!includedir /etc/mysql/conf.d/

contents of config files in /etc/mysql/conf.d
#
# The MySQL 5.6 database server configuration file.
#
# This custom MySQL 5.6 specific configuration file
# adds on top of the existing default my.cnf file at
# - /etc/mysql/my.cnf.
#
# Please add any extra MySQL 5.6 options in this file
# for sake of clarity.
#
# You may uncomment any existing option to enable it
#
# sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

[mysqld_safe]
syslog

/etc/init.d/mysql
#!/bin/bash
#
### BEGIN INIT INFO
# Provides:          mysql
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Should-Start:      $network $time
# Should-Stop:       $network $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop the mysql database server daemon
# Description:       Controls the main MySQL database server daemon "mysqld"
#                    and its wrapper script "mysqld_safe".
### END INIT INFO
#
set -e
set -u
${DEBIAN_SCRIPT_DEBUG:+ set -v -x}

test -x /usr/bin/mysqld_safe || exit 0

. /lib/lsb/init-functions

SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
CONF=/etc/mysql/my.cnf
MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"

# priority can be overriden and "-s" adds output to stderr
ERR_LOGGER="logger -p daemon.err -t /etc/init.d/mysql -i"

# Safeguard (relative paths, core dumps..)
cd /
umask 077

# mysqladmin likes to read /root/.my.cnf. This is usually not what I want
# as many admins e.g. only store a password without a username there and
# so break my scripts.
export HOME=/etc/mysql/

## Fetch a particular option from mysql's invocation.
#
# Usage: void mysqld_get_param option
mysqld_get_param() {
    /usr/sbin/mysqld --print-defaults \
        | tr " " "\n" \
        | grep -- "--$1" \
        | tail -n 1 \
        | cut -d= -f2
}

## Do some sanity checks before even trying to start mysqld.
sanity_checks() {
  # check for config file
  if [ ! -r /etc/mysql/my.cnf ]; then
    log_warning_msg "$0: WARNING: /etc/mysql/my.cnf cannot be read. See README.Debian.gz"
    echo                "WARNING: /etc/mysql/my.cnf cannot be read. See README.Debian.gz" | $ERR_LOGGER
  fi

  # check for diskspace shortage
  datadir=`mysqld_get_param datadir`
  if LC_ALL=C BLOCKSIZE= df --portability $datadir/. | tail -n 1 | awk '{ exit ($4>4096) }'; then
    log_failure_msg "$0: ERROR: The partition with $datadir is too full!"
    echo                "ERROR: The partition with $datadir is too full!" | $ERR_LOGGER
    exit 1
  fi
}

## Checks if there is a server running and if so if it is accessible.
#
# check_alive insists on a pingable server
# check_dead also fails if there is a lost mysqld in the process list
#
# Usage: boolean mysqld_status [check_alive|check_dead] [warn|nowarn]
mysqld_status () {
    ping_output=`$MYADMIN ping 2>&1`; ping_alive=$(( ! $? ))

    ps_alive=0
    pidfile=`mysqld_get_param pid-file`
    if [ -f "$pidfile" ] && ps `cat $pidfile` >/dev/null 2>&1; then ps_alive=1; fi

    if [ "$1" = "check_alive"  -a  $ping_alive = 1 ] ||
       [ "$1" = "check_dead"   -a  $ping_alive = 0  -a  $ps_alive = 0 ]; then
    return 0 # EXIT_SUCCESS
    else
    if [ "$2" = "warn" ]; then
        echo -e "$ps_alive processes alive and '$MYADMIN ping' resulted in\n$ping_output\n" | $ERR_LOGGER -p daemon.debug
    fi
    return 1 # EXIT_FAILURE
    fi
}

#
# main()
#

case "${1:-''}" in
  'start')
    sanity_checks;
    # Start daemon
    log_daemon_msg "Starting MySQL database server" "mysqld"
    if mysqld_status check_alive nowarn; then
       log_progress_msg "already running"
       log_end_msg 0
    else
        # Could be removed during boot
        test -e /var/run/mysqld || install -m 755 -o mysql -g root -d /var/run/mysqld

        # Start MySQL!
        su - mysql -s /bin/sh -c "/usr/bin/mysqld_safe > /dev/null 2>&1 &"

        # 6s was reported in #352070 to be too few when using ndbcluster
        # 14s was reported in #736452 to be too few with large installs
        for i in $(seq 1 30); do
                sleep 1
            if mysqld_status check_alive nowarn ; then break; fi
        log_progress_msg "."
        done
        if mysqld_status check_alive warn; then
                log_end_msg 0
            # Now start mysqlcheck or whatever the admin wants.
            output=$(/etc/mysql/debian-start)
        [ -n "$output" ] && log_action_msg "$output"
        else
            log_end_msg 1
        log_failure_msg "Please take a look at the syslog"
        fi
    fi
    ;;

  'stop')
    # * As a passwordless mysqladmin (e.g. via ~/.my.cnf) must be possible
    # at least for cron, we can rely on it here, too. (although we have
    # to specify it explicit as e.g. sudo environments points to the normal
    # users home and not /root)
    log_daemon_msg "Stopping MySQL database server" "mysqld"
    if ! mysqld_status check_dead nowarn; then
      set +e
      shutdown_out=`$MYADMIN shutdown 2>&1`; r=$?
      set -e
      if [ "$r" -ne 0 ]; then
        log_end_msg 1
        [ "$VERBOSE" != "no" ] && log_failure_msg "Error: $shutdown_out"
        log_daemon_msg "Killing MySQL database server by signal" "mysqld"
        killall -15 mysqld
            server_down=
        for i in 1 2 3 4 5 6 7 8 9 10; do
              sleep 1
              if mysqld_status check_dead nowarn; then server_down=1; break; fi
            done
          if test -z "$server_down"; then killall -9 mysqld; fi
      fi
        fi

        if ! mysqld_status check_dead warn; then
      log_end_msg 1
      log_failure_msg "Please stop MySQL manually and read /usr/share/doc/mysql-server-5.6/README.Debian.gz!"
      exit -1
    else
      log_end_msg 0
        fi
    ;;

  'restart')
    set +e; $SELF stop; set -e
    $SELF start
    ;;

  'reload'|'force-reload')
    log_daemon_msg "Reloading MySQL database server" "mysqld"
    $MYADMIN reload
    log_end_msg 0
    ;;

  'status')
    if mysqld_status check_alive nowarn; then
      log_action_msg "$($MYADMIN version)"
    else
      log_action_msg "MySQL is stopped."
      exit 3
    fi
    ;;

  *)
    echo "Usage: $SELF start|stop|restart|reload|force-reload|status"
    exit 1
    ;;
esac

A: Sounds like it may be set in mysqld_safe. There was once an ancient bug about this.
Recall the mysqld_safe calls mysqld from within an indefinite loop.
Goto the OS and run the following:
grep -n nice `which mysqld_safe`

This will show you all places where nice is set, defaulted and used
I just ran this on a CentOS VM that's running MySQL 5.5.20
[~]# cat /etc/redhat-release
CentOS release 5.7 (Final)
[~]# mysql --version
mysql  Ver 14.14 Distrib 5.5.20, for Linux (x86_64) using readline 5.1
[~]# grep -n nice `which mysqld_safe`
17:niceness=0
56:  --nice=NICE                Set the scheduling priority of mysqld
200:      --nice=*) niceness="$val" ;;
629:if test $niceness -eq 0
633:  NOHUP_NICENESS="nohup nice -$niceness"
636:# Using nice with no args to get the niceness level is GNU-specific.
638:# BSD could use "nohup sh -c 'ps -o nice -p $$' | tail -1").
641:if nohup nice > /dev/null 2>&1
643:    normal_niceness=`nice`
644:    nohup_niceness=`nohup nice 2>/dev/null`
646:    numeric_nice_values=1
647:    for val in $normal_niceness $nohup_niceness
654:                numeric_nice_values=0 ;;
658:    if test $numeric_nice_values -eq 1
660:        nice_value_diff=`expr $nohup_niceness - $normal_niceness`
661:        if test $? -eq 0 && test $nice_value_diff -gt 0 && \
662:            nice --$nice_value_diff echo testing > /dev/null 2>&1
667:            niceness=`expr $niceness - $nice_value_diff`
668:            NOHUP_NICENESS="nice -$niceness nohup"

See if the first occurrence of nice (in this case niceness) is set to 19.
You could also just grep for the number 19 in the mysqld_safe script.
I have never heard of random setting of niceness before. Nevertheless, I would start with mysqld_safe
Keep in mind that mysqld may have been launched as a nohup with niceness.
According to Wikipedia on nice

nice is a program found on Unix and Unix-like operating systems such as Linux. It directly maps to a kernel call of the same name. nice is used to invoke a utility or shell script with a particular priority, thus giving the process more or less CPU time than other processes. A niceness of −20 is the highest priority and 19 or 20 is the lowest priority. The default niceness for processes is inherited from its parent process and is usually 0.

Note the last sentence

The default niceness for processes is inherited from its parent process and is usually 0.

This sounds disturbing because mysqld could possibly be re-inheriting its original nice value. Who is the parent of mysqld? Like I said in the beginning: it's mysqld_safe.
You should also make sure your OS is not running with 19 for nice. Simply run nice to find out.
Also, note the usage message for nice
[~]# nice --help
Usage: nice [OPTION] [COMMAND [ARG]...]
Run COMMAND with an adjusted niceness, which affects process scheduling.
With no COMMAND, print the current niceness.  Nicenesses range from
-20 (most favorable scheduling) to 19 (least favorable).

  -n, --adjustment=N   add integer N to the niceness (default 10)
      --help     display this help and exit
      --version  output version information and exit

NOTE: your shell may have its own version of nice, which usually supersedes
the version described here.  Please refer to your shell's documentation
for details about the options it supports.**

Report bugs to <bug-coreutils@gnu.org>.

Based on the aforementioned NOTE:, your shell's nice may have an issue. If mysqld_safe inherits its niceness from above, mysqld will be grandfathered with the grandparent's niceness.


text:
Q: JNDI LDAP How to decode SSHA password I used apacheds(as LDAP server) and inserted entries into it using apache directory studio. For the userPassword atribute I selected plain text only. but, apache directory studio is encrypting it. i don't know why is that. Now, my java program to retrieve that entry is giving me a ssha encrypted password. can anyone out there help me in how to decode it ?
    import java.util.Hashtable;
    import javax.naming.Context;
    import javax.naming.NamingEnumeration;
    import javax.naming.NamingException;
    import javax.naming.directory.Attribute;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;

    class GetAttrs {
    public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY,
      "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:10389/o=mojo");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    try {
    // Create initial context
    DirContext ctx = new InitialDirContext(env);

    // Specify the ids of the attributes to return
    String[] attrIDs = { "cn", "sn", "uid", "userPassword" };

    // Get the attributes requested
    Attributes answer = ctx
      .getAttributes("cn=Harish Koppala, ou=Users", attrIDs);

    // Print the answer
    printAttrs(answer);

    // Close the context when we're done
    ctx.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    static void printAttrs(Attributes attrs) throws Exception{
    if (attrs == null) {
    System.out.println("No attributes");
    } else {
    /* Print each attribute */
    try {
    for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
      Attribute attr = (Attribute) ae.next();
      System.out.print(attr.getID()+" : ");
      /* print each value */
      if("userpassword".equalsIgnoreCase(attr.getID())){
          for (
                  NamingEnumeration e = attr.getAll();
                  e.hasMore();
                  System.out.println(new String((byte[])e.next()))
               );
      }else{
      for (
              NamingEnumeration e = attr.getAll();
              e.hasMore();
              System.out.println(e.next())
          );
      }
      }
     } catch (NamingException e) {
     e.printStackTrace();
     }
     }
     }

     }

output:
userPassword : {SSHA}SKA8QY7BBX0tgdZlzL+3sEDFnIBsJwd8VHjexw==
uid : hwilliams
sn : Williams
cn : Hugo Williams

A: It isn't encrypting it. It is securely hashing it. You can't decrypt or decode it.


text:
Q: How to show that $e^{-x/2} x^{y-1} \leq 1$ for $x$ large enough and $y\geq 1$ I am wondering how to show that $e^{-x/2} x^{y-1} \leq 1$ for $x$ large enough and $y\geq 1$
I thought I could try to solve for an $x$ s.t. $e^{\frac{x}{2}} > x^{y-1}$, but if I try to take logs to get rid of the $e$, I end up with a log of $x$.

A: You cannot directly apply your idea of L'Hospital because it would not give you a constant in the end if $y$ is not an integer. So you would need to use a squeeze as well.
Another method: note that $$e^{-x/2} x^{y-1}=e^{-x/2+(y-1)\ln x}$$
So all you have to do is prove that for $a,b\geq0$, $$\lim_{x\to \infty}(a\ln x-bx)=-\infty$$
Factor by $x$ and apply L'Hopital to see that $\ln x\over x$ tends to $0$ at infinity.


text:
Q: Using device name instead of ID in OpenCV method VideoCapture.open() I have a lot of video devices in my /dev folder (e.g. video1, video2, ..., video9) and one /dev/video which is always pointing to the valid device (which, of course, can change).
I want to open the /dev/video device with OpenCV using cv::Videocapture and realized that there are only two ways to open it:
VideoCapture::VideoCapture(const string& filename)
VideoCapture::VideoCapture(int device)

The first one opens a file and the second one opens /dev/video[device].
Is there any way to do something like cap = cv::VideoCapture("/dev/video");?

A: with current OpenCV 3.2.0 you can create a new capture like this:
cv::VideoCapture cap("/dev/video20", cv::CAP_V4L);

its one of the additional constructors:

VideoCapture (const String &filename, int apiPreference)
  Open video file or a capturing device or a IP video stream for video capturing with API Preference.

this is also possible with the open function:
cap.open("/dev/video20", cv::CAP_V4L);

i have tested this successfully under Kubuntu 16.10 with self compiled openCV from current git master.

A: By looking at the source code of OpenCV 2.4.11 (cap.cpp) you can see that the overload using const string& filename is calling 'cvCreateFileCapture' which uses other plugins as FFMPEG or GStreamer to load files so the answer is no.
bool VideoCapture::open(const string& filename)
{
   if (isOpened()) release();
   cap = cvCreateFileCapture(filename.c_str());
   return isOpened();
}

A: The best thing is to parse the ID of the device.
#include <regex>
#include <boost/filesystem.hpp>

...

boost::filesystem::path path( "/dev/video3" );
auto target = boost::filesystem::canonical(path).string();
std::regex exp( ".*video(\\d+)" );
std::smatch match;
std::regex_search( target, match, exp );
auto id = strtod( match[1] );
auto cap = cv::VideoCapture( id );

Note the use of canonical() to make the path absolute and resolve any symbolic links. This way it works even if you give it v4l device paths from /dev/v4l/by-id or /dev/v4l/by-path like for example:
"/dev/v4l/by-id/usb-046d_0990_1188AD49-video-index0"
"/dev/v4l/by-path/pci-0000:00:13.2-usb-0:4.4.4:1.0-video-index0"


text:
Q: StackOverFlowException inside a recursive function I have a table in database as follows:
MenuItem
-------------
MenuItemId    1 --------+
MenuItemName            |
ParentId      * --------+

Now I have written a recursive function to get all the Parent MenuItems with their children.
private ICollection<MenuItem> GetAllChildrenOfSpecificMenuItemRecursively(MenuItem menuItem, IEnumerable<MenuItem> menuItems)
{
    ICollection<MenuItem>  Children = null;
    foreach (MenuItem mi in menuItems)
    {
        if (mi.ParentMenuItemId != null)
        {
            if (mi.ParentMenuItemId == menuItem.MenuItemId)
            {
                Children.Add(mi);
            }
            else
            {
                return GetAllChildrenOfSpecificMenuItemRecursively(mi, menuItems);
            }
        }
    }

    return Children;
}

Now, I am calling it from another function as follows:
public IEnumerable<MenuItem> GetAllParentMenuItemsWithChildren()
{
    List<MenuItem> MenuItems = new List<MenuItem>();
    IEnumerable<MenuItem> AllMenuItems = null;

    using (MaxContext entityContext = new MaxContext())
    {
        AllMenuItems = (from e in entityContext.MenuItemSet select e).ToList();

        foreach (MenuItem menuItem in entityContext.MenuItemSet)
        {
            if (menuItem.ParentMenuItemId == null)
            {
                menuItem.Children = GetAllChildrenOfSpecificMenuItemRecursively(menuItem, AllMenuItems);
                MenuItems.Add(menuItem);
            }
        }
    }

    return MenuItems;
}

But it gives me stackoverflowException inside the recursive function. I am sure that I am making a minor mistake in that function. Can anybody point out that mistake?

A: Your GetAllChildrenOfSpecificMenuItemRecursively() always recurses with mi. It should recurse with mi.ParentMenuItemId instead.

A: Why are you always passing the same menuItems colleciton into recursive function?
your code should be something along the lines of:
private IEnumerable<MenuItem> GetAllChildrenOfSpecificMenuItemRecursively(MenuItem menuItem)
{
    var children = new List<MenuItem>();
    foreach (MenuItem mi in menuItem.Children)
    {
        // Why are you checking this?
        if (mi.ParentMenuItemId != null)
        {
            // Why are you checking this?
            if (mi.ParentMenuItemId == menuItem.MenuItemId)
            {
                children.Add(mi);
            }
            else
            {

                children.AddRange(GetAllChildrenOfSpecificMenuItemRecursively(mi))
            }
        }
    }

    return Children;
}

From method name, this is all that it should be doing:
private IEnumerable<MenuItem> GetAllChildrenOfSpecificMenuItemRecursively(MenuItem menuItem)
{
    var children = new List<MenuItem>();
    if (menuItem.Children == null) return children;

    foreach (MenuItem mi in menuItem.Children)
    {
       children.Add(mi);
       children.AddRange(GetAllChildrenOfSpecificMenuItemRecursively(mi));
    }

    return Children;
}

Edit:
public class MenuItem
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }

    public virtual MenuItem Parent { get; set; }

    [InverseProperty("Parent")]
    public virtual ICollection<MenuItem> Children { get; set; }
}

A: I think there is a simpler (and maybe faster) way of doing this without using recursion. Something like this:
    public ICollection<MenuItem> GetMenuItemsAsTreeList()
    {
        AllMenuItems = entityContext.MenuItemSet.ToList();

        Dictionary<int, MenuItem> dic = AllMenuItems.ToDictionary(n => n.Id, n => n);

        List<MenuItem> rootMenuItems = new List<MenuItem>();

        foreach (MenuItem menuItem in AllMenuItems)
        {
            if (menuItem.ParentMenuItemId.HasValue)
            {
                MenuItem parent = dic[menuItem.ParentMenuItemId.Value];
                menuItem.ParentMenuItem = parent;
                parent.SubMenuItems.Add(menuItem);
            }
            else
            {
                rootMenuItems.Add(menuItem);
            }
        }

        return rootMenuItems;
    }


text:
Q: PayPal Sandbox - Service Temporarily Unavailable I'm using PayPal Express Checkout for Digital Goods. I've tested it in PayPal Sandbox and it used to work fine.
Now, When i click in Pay With PayPal button. It gives me 503 error and tell me this
"Service Temporarily Unavailable. The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later."
Is it true that PayPal system have a maintenance? Because, I've tested for two days and the result is still the same. I've check in PayPal notify website, but it doesn't give any information about Sandbox maintenance.
Does anyone here also have the same issue with me?
Thank you


text:
Q: How can I make a fixed menu with scrolling in IE Please help me to fix menu on the top of the body and that should be scrolled horizontally.
I used position:fixed for the particular <div> tag with top:0;left:0 values. But when I resize the window to 50%, the fixed menu appearing only 50% remaining part was got inside the border (not appearing).
Please make me to fix this problem to view the menu with scrolling when we decrease the window size..

A: You can use bootstrap this will help you to fix the nav bar and this will not disturb the page on resizing the content. You can see the example Here.


text:
Q: Is there a way to make the flash[:notice] appear above, or before, the flash[:error]? So, I'd like to be able to display both a flash[:notice] and a flash[:error] on the same action, but I'd like for the :notice to always be displayed above (or before) the error.  Is there a way to do this?
In my controller, I thought I could just code the flash[:error] before the flash[:notice], so that rails will display it correctly, and it does a vast majority of the time.  But every now and then they are randomly switched, and I can't seem to figure out why.  So, how can I ensure that a flash[:notice] is always displayed above an :error ?
Edit: Thanks to Ben's and Ryan's advice, I've now just set up conditionals in my layout/application file.
    <% if flash[:notice] %>

<%= flash[:notice] %>

    <% end %>

    <% if flash[:error] %>

<%= flash[:error] %>

    <% end %>

I'm pretty satisfied with this, but maybe there's an even better way?
Edit #2:  Yes, there is.  Ben added it to his answer below.  Thanks again Mr. Ben.

A: The order of display simply depends on your view code. If you do this in your controller:
flash[:notice] = "Notice me"
flash[:error] = "BAAAAADDDD"

And this in your view:

<%= flash[:notice] %>

<%= flash[:error] %>

the :notice will always appear first.
Try this for a more elegant approach. The order you define in the array is the order they'll appear in:
<% [:error, :notice].each do |condition| %>
  <%= "
#{flash[condition]}
" if flash.has_key?(condition) %>
<% end %>

A: Always nil your notice and error object.

<% if flash[:notice] %>
<%= flash[:notice] %><% flash[:notice]=nil %>
<% end %>
<% if flash[:error] %>
<%= flash[:error] %><% flash[:error] =nil %>
<% end %>

A: I would make this a comment but it doesn't do multi-lined code snippets very well. They're probably "randomly switched" because you're using it like this:
  <% flash.each do |k, v| %>
    <div id='flash_<%= k %>'><%= v %>

  <% end %>

In 1.8 hash keys are unordered and because flash is a Hash, you'll get these output in whatever order Ruby feels like at the time. As Ben suggested, putting them in the "correct" order manually would help.


text:
Q: What is the expression for "Current Geodatabase" to be used in ModelBuilder? I have features in different geodatabases. When I process the features inside these geodatabases from Model Builder,and provide output names for them, I want them to be something like "CurrentGeodabaseName_%name%".
I want to know what is the expression for including Current Geodatabase Name in the output file.

A: This page is pretty helpful explaining the various inline model substitution variables: Examples of inline model variable substitution
 %Data Workspace%

should resolve to the geodatabase name.


text:
Q: How to get YouTube channel name and URL after authenticating Once I have authenticated a user - such as in the code below - how can I find out their channel name and URL of channel?
I'm using the YouTube data api v3 with .NET library:
UserCredential credential;
  using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
  {
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        new[] { YouTubeService.Scope.YoutubeReadonly },
        "user",
        CancellationToken.None,
        new FileDataStore(this.GetType().ToString())
    );
  }

  var youtubeService = new YouTubeService(new BaseClientService.Initializer()
  {
    HttpClientInitializer = credential,
    ApplicationName = this.GetType().ToString()
  });

A: Finally worked out how to do it.  Once you get the token back from the authentication do this:
var channelsListRequest = _youTubeService.Channels.List("id,snippet");

channelsListRequest.Mine = true;

var channelsListResponse = channelsListRequest.Execute();

if (    (null != channelsListResponse)          &&
        (null != channelsListResponse.Items)    &&
        (channelsListResponse.Items.Count > 0)  )
{
    Channel userChannel = channelsListResponse.Items[0];

    string youtubeUserID = userChannel.Id;
    string ytChannelURL = "https://www.youtube.com/channel/" + userChannel.Id;
    string name = userChannel.Snippet.Title;
}

Phew!


text:
Q: Estimating the curvature tensor of spacetime using a rotating body In curved space, you can define the Riemann curvature tensor at a point. In Riemann normal coordinates with that point as origin, the Riemann curvature tensor can be expressed as depending only on the derivatives of christofell symbols at the points (since the christofell symbols themselves vanish at origin, assuming no torsion). I think the derivatives of christoffel symbols at origin indicate the variation in gravitational forces at origin. If so, could you measure the Riemann curvature tensor by placing a small rotating body at the origin. The tidal forces developed in the rotating body should instantaneously slow down the rotation and simultaneously generate some heat. Could you use information about the change in angular velocity and/or rate of heat generation to estimate the Riemann curvature tensor? I used space and space-time interchangeably. Please let me know if one or other is more appropriate here. Please note that I'm just studying this stuff. So, I won't be able to understand extremely complicated answers.

A: The Riemann curvature tensor can be broken down into a tidal part, which is due to distant matter, and a non-tidal part, which is due to matter that is present at that point. If you're willing to trust the Einstein field equations, then it may not be that exciting to measure the non-tidal part, since it's probably much easier if you just examine what matter is present.
The tidal part can be measured by a tensor called the Weyl tensor, and I think the answer is that by orienting your rotating body along the three coordinate axes, you could measure three numbers, which would tell you something about the Weyl tensor. However, the Weyl tensor has 10 degrees of freedom, not just 3, so this method of measurement isn't going to tell you everything about the Weyl tensor.


text:
Q: Number of fields in a structure I'm new in abap development .
Actually, I'm looking for the Number of fields of a table or structure
any suggestion please

A: For counting the components of a structure, better use RTTS as we don't want to access the database for result we already have in our environment.
DATA(lwa_struct) = VALUE kna1( ). " your structure e.g. kna1

DATA(lo_descr) = CAST cl_abap_structdescr( cl_abap_datadescr=>describe_by_data( lwa_struct ) ).

DATA(lw_all_fields) = LINES( lo_descr->components ). " => 184

A: @lausek answered correctly. But for release 730 or lower, you'll need to adapt to something like this:
data ls_mara type mara.
data lo_structdescr type ref to cl_abap_structdescr.
data lv_count type i.

lo_structdescr ?= cl_abap_datadescr=>describe_by_data( ls_mara ).
lv_count = lines( lo_structdescr->components ).
write lv_count.

A: Another solution from my side.
select count(*) into @data(lv_count) from dd03l
    where tabname = 'YOUR STRUCTURE NAME' and AS4LOCAL = 'A'.


text:
Q: Saving text labels on top of images I'm building an app which takes Strings from the user and saves them using NSUserDefaults. Then I recover them and paste them on top of an image (a form or questionnaire)  I'm currently saving the image with .write to file but when I check the image I've saved, I discovered that it doesn't save the full image and as a consequence the positions for the fields aren't right. I need to be able to send this image and later on print on a sheet of A4 paper.
The simulator :
http://postimg.org/image/5szujdgw3/
The saved image:
http://postimg.org/image/uq6mea6vb/
Why isn't it saving the full image?
Here's my code :
import UIKit

class StartMorgagesSave: UIViewController {
  let rectangle = UIBezierPath(rect: CGRectMake(80, 166, 80, 05)) //x , y , width , height 240, 165
  let shapeLayer = CAShapeLayer()
  //let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    shapeLayer.path = rectangle.CGPath
    shapeLayer.strokeColor = UIColor.blueColor().CGColor
    shapeLayer.fillColor = UIColor.whiteColor().CGColor
    view.layer.addSublayer(shapeLayer)
    view.pdfData.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent("test53.pdf"), atomically: true) // what it is saved as
    view.pdfData.writeToFile("fdfdlo", atomically: false)
    print(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.path!)
  }
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
}

extension UIView {
  var pdfData: NSData {
    let result = NSMutableData()
    UIGraphicsBeginPDFContextToData(result, frame, nil)
    guard let context = UIGraphicsGetCurrentContext() else { return result }
    UIGraphicsBeginPDFPage()
    layer.renderInContext(context)
    UIGraphicsEndPDFContext()
    return result
  }
}

Niall


text:
Q: Как передать свойства в Modal? - react-native const Modals=({ title, img, author })=>(
<View style={styles.container1}>
<ImageBackground source={require('./img/el4.png')}  style={styles.img} >
  <Text style={styles.text}>Книга</Text>
  <View style={{flex:1, top:140, left:50}}>
      <TouchableOpacity onPress={()=>onPressNoItem(Item)}>
          <Image source={require('./img/strel.png')}/>
      </TouchableOpacity>
  </View>
</ImageBackground>
    <Text style={styles.textModal}>{title}</Text>
    <Text style={styles.author}>{author}</Text></View>)

return (
 <SafeAreaView style={styles.container}>
 <FlatList data={post}
renderItem={renderItem}
keyExtractor={keyExtractor}
extraData={isRender} />
 <Modal data={post}
 renderItem={renderItem}
 keyExtractor={keyExtractor}
 extraData={isRender}
 animationType="fade"
 visible={isModalVisible}
onRequestClose={()=>setisModalVisible(false)} >
  <Modals />
</Modal>
 </SafeAreaView> );


text:
Q: Yii2: db access from widget Widgets should be designed to be self-contained and they should not access a database directly. But recently I've come across the code that uses a direct access to the database to retrieve widget settings, and also caches retrieved values.
Here's the part of the widget:
class DbCarousel extends Carousel
{
    // ...
    public function init()
    {
        $cacheKey = [
            WidgetCarousel::className(),
            $this->key
        ];
        $items = Yii::$app->cache->get($cacheKey);
        if ($items === false) {
            $items = [];
            $query = WidgetCarouselItem::find()
                ->joinWith('carousel')
                ->where([
                    '{{%widget_carousel_item}}.status' => 1,
                    '{{%widget_carousel}}.status' => WidgetCarousel::STATUS_ACTIVE,
                    '{{%widget_carousel}}.key' => $this->key,
                ])
                ->orderBy(['order' => SORT_ASC]);
            foreach ($query->all() as $k => $item) {
                /** @var $item \common\models\WidgetCarouselItem */
                if ($item->path) {
                    $items[$k]['content'] = Html::img($item->getImageUrl());
                }
                if ($item->caption) {
                    $items[$k]['caption'] = $item->caption;
                }
            }
            Yii::$app->cache->set($cacheKey, $items, 60*60*24*365);
        }
        $this->items = $items;
        parent::init();
    }
    // ...
}

Question is: can widget under any circumstances access a database, or it's a sign that refactoring is needed?

A: Technically querying data and representing it are two different tasks, so such widget breaks single responsibility principle. However Yii has already a abstraction for retrieving data from database (ActiveRecord and/or ActiveQuery), so it is not that simple. You don't need to create separate data provider class for calling News::find()->newestFirst()->limit(5)->all() - usually it is easier and more pragmatic to call this query directly in LatestNewsWidget.
In general you have three situations with widgets:

*

*Widget may display different sets of data in the same way (like GridView).

*The same data may be displayed in different ways by different widgets, like widget for displaying menu - there is one menu stored in database, but depending on layout different widget should be used.

*Both, way of displaying and data, is unique - for example you have only one menu and only one layout (so there is only one widget for displaying menu).

As far as two first cases clearly indicates that data source and widget should be separated, it is not that clear in third case. Personally I'm often using widgets which are responsible for retrieving all necessary data and dependencies, so I can use them simply by MyWidget::widget(). I never had any problems with this, but I'm trying to avoid too complicated DB queries - complicity usually should be hidden behind ActiveQuery abstraction. Also you always need to be prepared for refactoring and extracting querying data to separate component - at some point your unique widget with unique set of data may become not unique and separating widget and data provider may be the only sane way to keep your code DRY.


text:
Q: What's the underlying grammatical structure of this sentence with three instances of "it" and two of "being"? I just encountered the following sentence in The Oxford Guide to Style (p. 161) and could not figure out its structure:

Since it⁽¹⁾ is being presented as a direct quotation it⁽²⁾ is treated as one, it⁽³⁾ being immaterial that the words are not in English.

Why can the the final instance of the pronoun it, the one labelled with a superscripted '(3)', be inserted at the end?
The first two instances of it, those labelled (1) and (2), are clearly coreferential to the same earlier antecedent (whatever is being presented as a direct quotation), but what is the third instance of it referring to?
What is the grammatical structure of this sentence?
Can that third it be omitted and the sentence remain grammatical and unchanged in meaning?

A: The parenthetical participle clause

*

*it being immaterial that the words are not in English

is the result of  Extraposition (with dummy it inserted) on the parenthetical participle clause

*

*that the words are not in English being immaterial
Extraposition is very common in English when the subject of a short verb phrase (like being immaterial) is long and syntactically complex (like that the words are not in English). It moves the heavy material to the end, where it's easier to parse in a right-branching language like English, and leaves a harmless little one syllable marker that leads right into the auxiliary verb, which is what English prefers.
If you exaggerate these dimensions, you see how useful it is. Contrast

*

*That I had to stand in line for over an hour yesterday is too bad.
versus the extraposed version

*

*It's too bad that I had to stand in line for over an hour yesterday.
Oh, and as for the two beings, the first is simply the progressive construction operating on the passive be presented, producing is being presented, a tensed main verb chain. The second one is a non-finite equivalent of a tensed subordinate clause. In this case, something like

*

*since it is immaterial that the words are not in English
with the same extraposed clause. Unlike the first, this being is not tensed, since it's a participle.

A: Your highlighted text is what is called a nominative absolute, which is used to describe the subject of the main clause, the "direct quotation," but is essentially a separate clause in its own right, and has almost no bearing on the first clause - in other words, it is completely parenthetical. If reworded, it could stand as a separate sentence, as "It is immaterial that the words [of the direct quotation] are not in English."
The "it" you're questioning is the subject of this absolute, so no, it cannot be deleted and maintain the integrity of the sentence.


text:
Q: 'System.NullReferenceException' occurred in databaseService.dll in wcf service I made a WCF service and hosted in windows forms application and made a client win from application to consume that I service retrieves data from database and shows to the client by entering ID.
How can I solve it?
I have seen many null references questions in stack overflow but thy are not related to WCF.
Image of error in my code:

Connection string in my web.config file:

A: Your connection string must be null.
Go to your Webconfig file which is in xml format. Check whether  tag has the proper connection string or it is missing.
If it is missing you can add it by using this:
<connectionString>
<add name="connection_name" providerName = "provider_name" connectionString="connectionString"/>
</connectionString>

Try this it will work.

A: You must verify that the executable that is actually running the service also has the connection string defined in app.config or web.config. Probably, when you test it you have it defined correctly, but when you run it outside the tester, the application that is actually running does not have it defined.


text:
Q: php Xcart Setup using smarty template i want to run a existing product store site on my localhost wamp server i changed all the Config variables in config file
as follow
$sql_host ='localhost';
$sql_user ='root';
$sql_db ='beauty';
$sql_password ='';
$xcart_http_host ="http://localhost/beautyuniverse/";
$xcart_https_host ="http://localhost/beautyuniverse/";
$xcart_web_dir ="";

but there is nothing showing on running my application only pure blank page is showing
All are most Welcome to solve my problem . thanks in Advance

A: The reason you are seeing a blank page is because the PHP generated an error (maybe due to incorrect validation) and execution is halted.
To see the error, you can try to either change the configuration in php.ini to display errors or try to change the error reporting settings in PHP by adding the following lines at the very beginning of the file:
<?php
error_reporting(E_ALL); // report all errors
ini_set('display_errors', 1); // display errors to browser

You can find in the manual more information about error reporting:
http://www.php.net/manual/en/function.error-reporting.php
Once you identify the error, you can try to fix it.

A: I had a similar problem (blank page) after moving the cart to a different server.  I had to turn on DEVELOPMENT MODE inside X-Cart and crank up the debug mode to 3 (log & write errors to screen).
Inside config.php, look for debug_mode flag and set it to 3.
$debug_mode = 3
And uncomment this line:
define('DEVELOPMENT_MODE', true);

A: Another reason for getting blank page in x-cart, besides PHP error, could be the existence of a 3rd-party module in the store, which works either based on a domain-related licence (licenced to work only on the client's domain), or requires IonCube software, in case it's code is encrypted. You can install IonCube in your local server as well and thus run the site, but you won't be able to trace it's code via a debugger.


text:
Q: Large Woocommerce Site (83,000 items), What Can I Do? So I have a really large woocommerce site (partsboss.co) that has around 83,000 items.  It's on VPS hosting with digitalocean, and things were running super fast until around 50,000 items.  Now the site is just draaaaaaaaaging.
It's set up on Ubuntu with nginx, APC and Varnish caching.  I'm not really sure where the bottle neck is or how to fix it, but as far as I can tell it's basically taking forever to query the mysql database and return results.
So my question is, do I need to just optimize mysql more (if so, how? Not really a mysql expert) or do I need to split the database with something like Hyperdb? Again, if that's the case, I read the readme for Hyperdb and it wasn't too explicit... if you know of any good tutorials, throw them my way :)  Any help would be much appreciated, thanks!

A: Did either of you solve your issues with Woocommerce being slow?
After some profiling, I determined it was PHP being slow, not SQL.
Total query time: 0.05915s for 89 queries.
Page generated in 22.00653s (99.73% PHP, 0.27% MySQL)

With that info, nothing you change in the front end is going to solve anything.


text:
Q: pg_bulkload from S3 bucket Can pg_bulkload read file from S3 bucket? Please share the scripts. Could you please tell me how do we deploy the script into production?

A: pg_bulkload cannot read data from an Amazon S3 bucket.
You could 'cheat' by using a utility that mounts an Amazon S3 as a disk (eg s3fs, Mountain Duck, Cloudberry Drive). This way, pg_bulkload can simply reference a 'local' disk without knowing that it is backed by Amazon S3.
Alternatively, simply download the data from S3 to your local disk and then use pg_bulkload.


text:
Q: Weird Issue Quaternion Rotation in XNA Space Simulator I have spent 8 hours trying to find a solution.
So here is my problem.  My ship is rotating like it's rotating around something, like a string.  When I go farther and farther from the starting position, I start rotating more weirder and weirder.  Like I am attached to a string.
Here is the code for Rotation and Movement.
public void MoveShip(List<InputAction> InputActionList, GameTime gameTime)
    {
        float second = (float)gameTime.ElapsedGameTime.TotalSeconds;
        float currentTurningSpeed = second * TurningSpeed;
        float leftRightRotation = 0;
        float upDownRotation = 0;
        float linearLeftRightRotation = 0;
        foreach(InputAction action in InputActionList)
        {
            switch(action)
            {
                case InputAction.Left:
                    leftRightRotation -= currentTurningSpeed;
                    break;
                case InputAction.Right:
                    leftRightRotation += currentTurningSpeed;
                    break;
                case InputAction.Up:
                    upDownRotation += currentTurningSpeed;
                    break;
                case InputAction.Down:
                    upDownRotation -= currentTurningSpeed;
                    break;
                case InputAction.IncreaseSpeed:
                    if (ShipSpeed < MaxShipSpeed)
                        ShipSpeed += Acceleration;
                    break;
                case InputAction.DecreaseSpeed:
                    if (ShipSpeed > MinShipSpeed)
                        ShipSpeed -= Acceleration;
                    break;
                case InputAction.LinearLeft:
                    linearLeftRightRotation += currentTurningSpeed;
                    break;
                case InputAction.LinearRight:
                    linearLeftRightRotation -= currentTurningSpeed;
                    break;
                case InputAction.Fire1:
                    WeaponSystem2D.RequestFire(ShipPosition, ShipRotation);
                    break;
            }

        }

        Quaternion currentRotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), leftRightRotation) *
            Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), upDownRotation) *
            Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), linearLeftRightRotation);

        currentRotation.Normalize();
        ShipRotation *= currentRotation;

        ShipPosition *= Vector3.Transform(new Vector3(0, 0, 1), ShipRotation) * (ShipSpeed * second);

        ShipWorld = Matrix.CreateFromQuaternion(ShipRotation) * Matrix.CreateTranslation(ShipPosition);

    }

What is the problem? Why is it doing this? I want the ship to rotate on a dime, since it is space.
EDIT:
-The model is not an issue.
EDIT 2: Nevermind, the rotation was actually working, it was my skybox that was broken!

A: This code is actually perfect, my skybox made it look like it was broken.


text:
Q: Is there a replacement for Arrays with enums as indexes? I used to use enums as indexes in C. (each enum something like an alias for an int value)
Example:
typedef enum {DOG, CAT, MOUSE} ANIMALS;
int[3] age;
...
age[DOG] = 4;
age[CAT] = 3;
age[MOUSE] = 10;

With enums as indexes, I can always be sure that I am updating the right cell. Furthermore, I need the simplicity of arrays as well.
I would like to do the same in Java. But, I cant seem to find a simple replacement.
Does anyone know a replacement that can be used the same way as Array+enum combo did in C?

A: Yes there is a fairly simple one. Use HashMaps.
Map<CustomEnum, Object> hashMap = new HashMap<>();

//Basic usage
hashMap.put(CustomEnumID, ObjectValue);
ObjectValue obj = hashMap.get(CustumEnumID); //Returns the value from the above line
hashMap.containsValue(CustomEnumID); //Return true or false

A: Enum is pretty much object in Java. So basically you go for HashMap is you would like to introduce Object-Object relations in your code.

A: As was already said in other answers, using Map<YourEnum, V> is a good way to do what you want to do. However, Java, actually, has a EnumMap (it does implement regular Map interface) which is designed especially for use with enum type keys, and, as said in the documentation, it is likely to be faster than using HashMap.

A: In my opinion, there are two solutions:
1) You can simulate 'C enum type' by class in Java:
class Animals {
    public static int DOG = 0;
    public static int CAT = 1;
    public static int MOUSE = 2;
}

In this case you manually set values to enum - in C it is automatically done by compiler.
Usage of enum looks like this
public class Test {
  public static void main(String[] args) {

    int[] age = new int[3];

    age[Animals.DOG] = 4;
    age[Animals.CAT] = 3;
    age[Animals.MOUSE] = 10;

    for (int i = 0; i < age.length; i++) {
        System.out.print(age[i] + " ");
    }
  }
}

I think this is bad solution because this break OOP principle of encapsulation (in class Animals).
2) You can use Java enum
enum Animals {
    DOG(0), CAT(1), MOUSE(2);
    int value;

    private Animals(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

And example of usage
public class Test {
    public static void main(String[] args) {

        int[] age = new int[3];

        age[Animals.DOG.getValue()] = 4;
        age[Animals.CAT.getValue()] = 3;
        age[Animals.MOUSE.getValue()] = 10;

        for (int i = 0; i < age.length; i++) {
            System.out.print(age[i] + " ");
        }
    }
}

In Java enum is kind of class. For more details read this.
There is no default values for enum and you have to set by yourself. In this example it is done with construcructor Animal(int value). Also, we cannot use Animals.DOG like integer values but we have to use method getValue().


text:
Q: Plupload HTML4 Add Files dialog not triggering in IE I'm using Plupload (jQuery version) with HTML4 for IE, and for some reason it's not opening the File Dialog when I press the Add Files button.
The Plupload container is placed in a dialog, and I call .pluploadQueue() just before I show the dialog, each time.
It works fine on FF and Chrome.

A: The Cause

I call .pluploadQueue() just before I show the dialog, each time.

The Solution
Apparently, Plupload doesent seem to fire the dialog if the Plupload container is hidden (display:none) while evaluating .pluploadQueue()
I had to do a display:block before calling .pluploadQueue() - since I didnt want to fade in my dialog till after the Plupload stuff was done, I simply set the containers opacity:0
Long story short: Make sure your Plupload container is not hidden when you call .pluploadQueue()

A: After showing or moving the button, call uploader.refresh() to have the runtime shim update its position.


text:
Q: sending variable to a javascript file in RoR I am using ajax to call a RoR rails function and am new to this.
The function is
def destroy
   @fav_company = FavouriteCompany.find(params[:id])

    respond_to do |format|
     format.js { render :layout=>false }
    end
end

In my destroy.js.erb I have
 $('#profile_alerts').show();
 $('#Fav#{@fav_company.id}').hide();

The first line is working but not the second line. I am suspecting it is unable to access @fav_company.
What should I do? thanks
=====
Some additional information, the call I am making to this function is a link_to with remote => 'true' as such:
<%=link_to "destroy",{:controller=>"favourite_companies",:action=>"destroy", :id=>"#{fav.id}"}, {:remote => true } %>

A: This:
$('#Fav#{@fav_company.id}').hide();

Should be:
 $('#Fav #{@fav_company.id}').hide();

Assuming @fav_company.id presents a variable in the DOM

A: Since your javascript code is in an ERB file I think you should be using $('#Fav<%=@fav_company.id%>').hide();.

A: Try to use:
$('#Fav#{escape_javascript({@fav_company.id}).html_safe}').hide();

==================================================================================
Ok, my code, but I does another task:
albums/show.html.haml
= link_to t('write.comment'),  new_album_comment_path(@album, :format => :js, :id => @album.id), :remote => true

comments/new.js.haml
$("#comment_form").html("#{escape_javascript(render :partial => "comments/form").html_safe}");

also all code here https://github.com/barthezslavik/mebel - if you found something useful, I'll be happy


text:
Q: Wildfly does not log into a different file using logging profile I tried to custom my logging using logging-profile, this is my standalone.xml logging-profile configuration:
<logging-profiles>
    <logging-profile name="PRUEBA">
        <console-handler name="CONSOLA">
            <level name="INFO"/>
            <formatter>
                <named-formatter name="COLOR-PATTERN"/>
            </formatter>
        </console-handler>
        <file-handler name="ARCHIVO">
            <level name="INFO"/>
            <file relative-to="jboss.server.log.dir" path="app.log"/>
        </file-handler>
        <logger category="py.com.myapp.controllers">
            <level name="INFO"/>
            <handlers>
                <handler name="ARCHIVO"/>
                <handler name="CONSOLA"/>
            </handlers>
        </logger>
        <formatter name="COLOR-PATTERN">
            <pattern-formatter pattern="%K{level}%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
        </formatter>
    </logging-profile>
 </logging-profiles>

This is the manifest.MF
Manifest-Version: 1.0
Class-Path:
Logging-Profile: PRUEBA
This is the prueba.java file
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private Logger appLogger;

protected Logger getLogger() {
    if (appLogger == null) {
        appLogger = LoggerFactory.getLogger(Prueba.class);
    }
    return appLogger;
}

@RequestMapping(value = "/prueba")
public String prueba(ModelMap model{
    getLogger().error("****************PRUEBA***************");
}

But it does not log into the file app.log, it still logging in the server.log
 Someone can help me?

A: It should be working. Are you sure you are editing the correct file (standalone.xml, standalone-full.xml etc). Do any other changes on the logging profile work?
You could also try adding <file-handler name="ARCHIVO" autoflush="true"> which is used in the standard configuration of wildfly

A: " tag level name="INFO"/> should be changed to level name="DEBUG"/>
this is for log level


text:
Q: Magento 2 event observer custom config save given error I have a custom section tab in configuration my section url is:
http://dev.test/admin/admin/system_config/edit/section/vendor_module/key/?????????
exception(s):
Exception #0 (Magento\Framework\Exception\LocalizedException): Invalid XML in file .../app/code/Vendor/Module/etc/adminhtml/events.xml:
Element 'event', attribute 'name': [facet 'pattern'] The value 'admin_system_config_changed_section_vendor_module' is not accepted by the pattern '[a-zA-Z_]+'.
Line: 3

Element 'event', attribute 'name': 'admin_system_config_changed_section_vendor_module' is not a valid value of the atomic type 'eventName'.
Line: 3

Element 'event', attribute 'name': Warning: No precomputed value
available, the value was either invalid or something strange happend.
Line: 3
...

events.xml:
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="admin_system_config_changed_section_vendor_module">
    <observer name="custom_admin_system_config_change_vendor_module" instance="Vendor\Module\Observer\ConfigObserver"/>
</event>
</config>

It works with general and other sections. Any ideas?

A: I think is related with bug and your vendor or module have number in name.
Like 'b2b' or something.
Solution is to change names with this numbers or upgrade to Magento  2.3
Ref.
https://github.com/magento/magento2/issues/5035enter link description here

A: I cant see any issue with that XML
Compare it with this
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="custom_admin_system_config_change_vendor_module">
        <observer instance="Xigen\Config\Observer\Backend\Custom\AdminSystemConfigChangeVendorModule" name="xigen_config_observer_backend_custom_adminsystemconfigchangevendormodule_custom_admin_system_config_change_vendor_module"/>
    </event>
</config>

AdminSystemConfigChangeVendorModule.php
namespace Xigen\Config\Observer\Backend\Custom;

class AdminSystemConfigChangeVendorModule implements \Magento\Framework\Event\ObserverInterface
{
    /**
     * Execute observer
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(
        \Magento\Framework\Event\Observer $observer
    ) {
        //Your observer code
    }
}


text: Q: What's "grails package" actually do? I'd like to debug packing my grails project into war file by 'grails war' (because of an error described here: Can not build war from grails project) so I'm looking for differences in (ant?) commands which are executed step by step by 'grails package' (which my project does successfully) and 'grails war' in it's packaging section (which ends up with error: Error WAR packaging error: startup failed ).


text:
Q: How to test model with HABTM associations? I need to test a model with HABTM association. My factory looks like:
FactoryGirl.define do
  factory :article do |f|
    body "Some awesome text"
    after(:build) {|article| article.users = [create(:user)]}
  end
end

How to test article creation without users association later in such way:
it "is not a valid article without users" do
  article = build(:article, users: []) #doesn't work
  expect(article.valid?).to eq(false)
end

A: You may be better off creating a sub-factory:
FactoryGirl.define do
  factory :article do |f|
    body "Some awesome text"

    factory :article_with_users do
      after(:build) {|article| article.users = [create(:user)]}
    end
  end
end

Then test by:
it "don't create article without users associations" do
  article = build(:article) #doesn't work
  expect(article.valid?).to eq(false)
end

it "do create article with users associations" do
  article = build(:article_with_users)
  expect(article.valid?).to eq(true)
end

This, however, depends on your validation setup in your models as well.
it don't, it do :)


text:
Q: Is there a layer in Caffe that can get an arbitrary sub block in a blob? Is there a layer in Caffe that can get an arbitrary sub block in a blob?

A: AFAIK there is not a completely general slicing layer in caffe.
If you want to extract sub-blocks that are specific channels of a blob, you can use "Slice" layer.
Depending on your requirements, you might find "Crop" layer sufficient for your needs.
If you need more flexible access to sub-blocks, you might want to consider using a "Python" layer.

An example using "Crop" layer
As you pointed out "Crop" layer expects two "bottom"s but since the second one is only used for reference shape, you can produce it using "DummyData" layer.
Suppose you want to select x[:,:,3:20,5:40], this is a 17x35 crop
layer {
  name: "ref_shape_17x35"
  type: "DummyData"
  top: "ref_shape_17x35"
  dummy_data_param { shape { dim: 1 dim: 1 dim: 17 dim: 35 } }
}
layer {
   name: "crop_x"
   type: "Crop"
   bottom: "x"
   bottom: "ref_shape_17x35"
   top: "crop_x"
   crop_param {
     axis: 2  # do not crop the first two dimensions
     offset: 3
     offset: 5
   }
 }

I did not try it myself, but it should work (let me know if it doesn't).


text:
Q: In Ruby on Rails, what's the difference between installing something as a gem or as a plugin? On http://github.com/collectiveidea/delayed_job
it says:

To install as a gem, add the following to config/environment.rb:
config.gem 'delayed_job'
  Run rake gems:install

versus

To install as a plugin:
script/plugin install git://github.com/collectiveidea/delayed_job.git

What is the difference between installing it as a gem or as a plugin?
Also, the first method just install gem 2.0.3 which might be the tobi's version? (rake gems:install installs the version by gem list -r delayed_job) Is it http://github.com/tobi/delayed_job  ?
The "plugin" method specifically says it is the collectiveidea version?  Doesn't it matter which one you install?

A: Both the Gem and the vendored plugin refers to the collectiveidea's fork. In fact, collectiveidea is the current maintainer for the delayed_job Gem on RubyGems.
That said, generally speaking installing a plugins as a Gem has many advantages.

*

*You can install it once and use it in many different projects

*You can take advantage of dependency resolution

*You can upgrade just changing version number

*You don't need to store the entire plugin code in your SCM

So, why you can install a plugin "as a plugin"?
There are many different answers.
At the very beginning, Rails plugins came as simple libraries. Time passes and developers started to notice the advantage of packaging plugins as Gem.
Also, before Rails 3, some plugin features were only reserved to plugins and not to Gems. For instance, before Rails 3, plugins could bundle rake tasks while there wasn't a way to inject new rake tasks or new routes into the main application.
In the last two years, the most part of Rails plugins offers the ability to be installed as a plugin or as a Gem. With Rails 3 and the arrival of Bundler, I'm sure plugins are going to be deprecated in favor of Gems.

A: That are 2 different repositorys,
maybe you shoult try
config.gem 'delayed_job', :source => http://github.com/collectiveidea/delayed_job.git

Look at: http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies
Btw. maybe you want to look at a maybe better solution: resque - see http://ruby-toolbox.com/categories/queueing.html for a comparison of used queing gems

A: When you install a gem it will be available for all apps, in case you use a plugin - just for an app it's installed into.

A: The basic difference is a gem is something that gets installed on the system running your Rails application, whereas a plugin is installed along with your application, plugin does not get installed on the system level.
suppose you are using rvm and let us take this example.
we have two applications app1 and app2
both are running on a common rvm gemset named gemset1
when you add a gem in the gemfile of app1 and run bundle install and then being in the same rvm gemset which is gemset1, if you run the second app app2 the gem will be available in the second application as well
Whereas with the plugin it will not be the case because plugins get installed on application level and not at the system level


text:
Q: How to check if an array that has objects in react components state has duplicate values before sending a form? So I have a state:
 const [persons, setPersons] = useState([{ id: 1, name: "Arto Hellas" }]);
 const [newName, setNewName] = useState("");

A simple form:
 <form onSubmit={addName}>

      name: <input value={newName} onChange={handleNameChange} />

      <button type="submit">add</button>

  </form>

And the handlers for the form. I can add new names and render them but
Im trying to check if the name typed in the input has allready been added and if so just a simple alert that its not possible. I have banged my head in the wall for hours trying everything I could but with my knowledge it just isnt going anywhere. (Starter exercises for open uni at my country)

A: All you need to do is find the element in persons, If it is present then alert, console.log, or tell the user that it is not possible else add into the state.
demo
I've used console.log, You can use alert or anything to tell the user.
function addName(e) {
    e.preventDefault();
    const isPresent = persons.find((p) => p.name === newName);
    if (!isPresent) {
      setPersons((state) => {
        return [...state, { id: state.length + 1, name: newName }];
      });
      setNewName("");    // Clear the input
    } else {
      console.log("Not possible");
    }
  }


text:
Q: Nodejs fetch works in localhost but not in production I have a problem with my code.. It works fine in localhost but in production it stopped working for some strange reason.. It does not console log Fetch not sucessfull, it just tries until I get a status code 500.
/app.js
app.use('/onlineplayers', (req, res) => {
    const Gamedig = require('gamedig')
    Gamedig.query({
        type: 'rust',
        host: process.env.GAME_HOST,
        port: process.env.GAME_PORT,
        requestRules: true,
        maxAttempts: 100,
        socketTimeout: 100
    }).then((state) => {
        const numplayers = state.raw.numplayers
        const wipeTime = state.raw.tags[8].substring(4)
        const mapType = state.map
        res.status(200)
        res.send([numplayers, wipeTime, mapType])
        return
    }).catch((error) => {
        console.log(error)
    })
})

/public/js/onlineplayers.js
fetch('/onlineplayers')
    .then(res => {
        if (res.ok) {
            console.log("Fetch request successfull")
        }
        else { console.log("Fetch not sucessfull") }
        return res
    })
    .then(res => res.json())
    .then((res => {
        const getP = document.getElementById("online")
        getP.innerHTML = res[0]
        const utcSeconds = res[1]
        const d = new Date(0)
        d.setUTCSeconds(utcSeconds)
        const getPp = document.getElementById("wipe-info")
        const getDiv = document.getElementById("loading")
        getPp.title = "Last wiped: " + d
        const progressBar = document.getElementById("progressbar").style.width = getP.innerText + "%"
        const mapType = document.getElementById("maptype").innerHTML = res[2]
        getDiv.classList.add("visually-hidden")
    }))
    .catch(error => console.log(error))


text:
Q: How to navigate to a div in another component in Angular 2? I have routeConfig as follows and I am using HashLocationStrategy.
@RouteConfig([
    {path: '/', name: 'Home', component: HomeComponent, useAsDefault: true},
    {path: '/me', name: 'Profile', component: ProfileComponent}
])

How can I navigate to a div(or section) in the profile view (profile#skills) from the Home view using angular2 routing
I would do a href on /profile.html#skills if it was plain html. I am not sure how to do this in angular2.  May be it is something simple.Appreciate any pointers.
TIA

A: This is currently a bug or missing feature in Angular2. See also https://github.com/angular/angular/issues/6595


text:
Q: RaceOnRCWCleanup when running console app for speech recognition I don't know either we can create a console app or not for speech recognition(searched for the same but didn't find any answer)and tried this code.
I have this code working in winforms app
but  when trying to create this app in console visual studio is giving a very strange error mscorelib.pdb not found.And transferring to a page mscorelib.pdb
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Speech;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Threading;

namespace ConsoleApplication2
{
    public  class Program
    {

        public static void Main(string[] args)
        {
            tester tst = new tester();
            tst.DoWorks();

        }

    }
    public class tester
    {
        SpeechSynthesizer ss = new SpeechSynthesizer();
        SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
        PromptBuilder pb = new PromptBuilder();
        Choices clist = new Choices();

        public void DoWorks()
        {
            clist.Add(new string[] { "how are you", "what is the current time", "open chrome", "hello" });

            Grammar gr = new Grammar(new GrammarBuilder(clist));

            sre.RequestRecognizerUpdate();
            sre.LoadGrammar(gr);
            sre.SetInputToDefaultAudioDevice();
            sre.SpeechRecognized += sre_recognised;
            sre.RecognizeAsync(RecognizeMode.Multiple);
        }

        public void sre_recognised(object sender, SpeechRecognizedEventArgs e)
        {
            switch (e.Result.Text.ToString())
            {
                case "hello":ss.SpeakAsync("Hello shekar");
                    break;
                case "how are you": ss.SpeakAsync("I am fine and what about you");
                    break;
                case "what is the time":ss.SpeakAsync("current time is: " + DateTime.Now.ToString());
                    break;
                case "open chrome":System.Diagnostics.Process.Start("chrome", "wwe.google.com");
                    break;
                default:  ss.SpeakAsync("thank you");
                    break;
            }
            Console.WriteLine(e.Result.Text.ToString());
        }
    }
}

here is the snapshot of the error page

I also loaded the given option "Microsoft.symbol.Server", but it is still giving the same output.
EDIT
HERE is the output window

Outputs are of big lengths ,so not being able to show all the outputs ,captured some relevant parts (regret).

A: You're seeing the debugger issuing a RaceOnRCWCleanup. The reason may be that you are instantiating but not properly cleaning up COM objects created under the hood by SpeechSynthesizer and/or SpeechRecognitionEngine.
At the same time, a Console application is not automatically 'kept alive'. You need to specifically add code to prevent it from exiting immediately.
You need to do 2 things:

*

*Ensure your application stays alive long enough (for example, by adding a Console.ReadLine() statement in the Main method

*Make sure that resources are properly cleaned up. Both SpeechRecognitionEngine and SpeechSynthesizer implement IDisposable, so they should be disposed when no longer needed. To do this properly, implement IDisposable in your tester class:

Example:
 public class Tester
 {
    SpeechSynthesizer ss = new SpeechSynthesizer();
    SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
    public void Dispose()
    {
         ss.Dispose();
         sre.Dispose();
    }
 }


text:
Q: Прошивка Atmega32U4 скетчем arduino IDE Как прошить Atmega32U4 скетчем arduino с внутренним кварцем. В качестве программатора могу использовать arduino uno или USBASP. Знаю как прошить Atmega 8. Заранее спасибо

A: *

*Нужно добавить описание микроконтроллера в файл boards.txt (директорий hardware/arduino/avr). Это нужно из-за нестандартной частоты тактирования - 8 МГц. Можно скопировать описание платы Leonardo, изменив частоту.

*Скомпилировать загрузчик Caterina под частоту 8 МГц.

*Подключить программатор к микроконтроллеру по ICSP.

*Запрограммировать FUSE-биты (hfuse 0xD8, lfuse 0xF2, efuse 0xCB) с помощью программы avrdude.

*Выбрать в IDE программатор и описанный микроконтроллер.

*В IDE прошить загрузчик.

Далее:

*

*Либо загрузить скетч по USB.

*Либо скомпилировать скетч, найти его в директории /tmp (в Linux), и прошить hex-файл, используя программу avrdude.


text:
Q: Try except finally - Is EMPTY try except finally valid in python? Is it okay to have empty try except finally block in python, something like this,
try:
    #nothing here,
except:
    #nothing here as well,
finally:
    #nothing here too.

A: Sure, you can use pass to pass a block:
try:
    pass
except:
    pass
finally:
    pass

More examples:
def a():
    pass

while True:
    pass

for i in range(10):
    pass
...


text:
Q: VBScript .focus function doesn't execute on Windows Server 2003 The .focus function won't execute on Windows Server 2003 when I run my VBScript, however it works fine up to that point. Does anyone know why this could be?
Here's my script:
WScript.Sleep 1000 .getElementByID("quickSearchMsisdn").value = "085729916"
WScript.Sleep 1000 .getElementByID("quickSearchMsisdn").value = "0857299167"
WScript.Sleep 1000 .getElementByID("quickSearchMsisdn").value = "0857299167"
                   .getElementByID("quickSearchMsisdn").Focus
WScript.Sleep 10000 .getElementByID("doSendSMS").click

A: There is not Focus Function in vbscript that I am aware of, Maybe you are describing the focus method of some class? Some code would be very helpful.


text:
Q: VBScript FTP Delete file if exists I'm having trouble deleting a file from an FTP server if it exists, below is a really cut down version of my code but usually the inFile is a varible. The code below in theory should delete the file test.txt from the FTP server as it does exist but nothing seems to happens. If I create a local directory with a test.txt file in it and point the inFile at that directory the file deletes fine so I'm assuming it has something to do with remote connections. Any ideas?
inFile = "ftp://username:password@xxx.xxx.xxx.xxx/test.txt"

File_Delete(inFile)

Sub File_Delete (inFile)

            dim strProc, objFSO

            Set objFSO = CreateObject("Scripting.FileSystemObject")

            If objFSO.FileExists(inFile) Then
                            objFSO.DeleteFile infile
            end if

            set objFSO = nothing

end sub


text:
Q: MagicalRecord and how to handle database change on application update? I am using Magical Record in my app and it is working just fine. First version is already on app store. Now I have made some updates, database model has changed (some new entities + relationships), and i would like to update my app on app store.
But i fear these modifications will break my app, because model for database has changed. In app delegate i call;
[MagicalRecord setupCoreDataStackWithStoreNamed:[DataManager defaultStoreFileName]];

This line sets up the database, but I am not really sure how it does. Does it every time delete the previous database and sets up new with same path? If it does that my problem is solved, but it doesn't seem to work that way.
The other solution I am considering is to delete database if version of app has changed. And then call this line of code.
To make it clear how do i handle from database perspective app update?


text:
Q: Spanish version of a Francophile I know the word Francophile is someone who likes France and the French. I also know of Anglophiles that is a similar word for the British. Is there such a word for the Spanish though?

A: The closest you can come is "Hispanophile," but this might restrict your love to Spain or it might mean any Spanish-speaking place, of which there are numerous outside the Iberian peninsula.

A: Iberophile seems to be commonly used to refer to a love of all things Spanish.
This book even uses "Francophile" and "Iberophile" in the same sentence.

A: Both the Spanish Monarchy and subsequent government of Francisco Franco were generally disliked because of their extreme greed, avarice and authoritarianism. A word for "Love of Spain" therefore never came into common use. Iberophile denotes a love for Iberian culture that includes both Spain and Portugal without any political connotations.


text:
Q: For while loop C++ basic interest calculator For your 21st birthday, your grandmother opens a savings account for you and deposits $1000 into the account.  The savings account pays a 3% interest on the account balance.  If you don't deposit any more money into the account, and you don't withdraw any money from the account, how much will your savings account be worth at the end of 1 through 5 years?
Create a program that gives you the answers.  You can calculate the answers using the following formula: b = p * (1 + r)n .  In the formula, p is the principal (the amount of the deposit), r is the annual interest rate (3%), n is the number of years (1 through 5), and b is the balance in the savings account at the end of the nth year.
Use a for loop.
Any help will be greatly appreciated
This is what I have so far and all I get is an infinite loop
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

void main()
{
// Inputs //

double princ = 0.0;
double rate = 0.0;
int years = 0;
int year = 1;
double total = 0.0;

// Ask User For INFO //

cout << "What is the principle? ";
cin >> princ;
cout << "What is the rate in decimal? ";
cin >> rate;
cout << "how many years? ";
cin >> years;

for (double total; total = princ*(1+rate)*year;)
{
cout << "The balance after year " << year << " is "<< total << endl << endl;
year += 1;
}

while((years + 1)!= year);

system("pause");
}

A: You have misunderstood how the for loop works. It is used to do something a certain number of times, in your example it would be appropriate to loop over a certain number of years. Something like this:
double interest = 1.0 * rate:
double accumulated = 1.0 * interest;

for (auto i=1; i < years; ++i) {
    accumulated *= interest;
    cout << "The balance after year " << i << " is " << (princ * accumulated) << std::endl;
}

A: Your problem is that you somehow mixed up your for and while loop.
Instead of
for (double total; total = princ*(1+rate)*year;)
{
cout << "The balance after year " << year << " is "<< total << endl << endl;
year += 1;
}

while((years + 1)!= year);

You'd probably want something like this:
for (double total; (years +1) != year; total = princ*(1+rate)*year)
{
cout << "The balance after year " << year << " is "<< total << endl << endl;
year += 1;
}

Also your main function shouldn't return void as already noted in the comments and should instead be int main()


text:
Q: Htaccess help, $1 being used before its set??? what? I have this snippet
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond $1 !^(index\.php|images|img|css|js|robots\.txt)
RewriteRule (.*) index.php?/$1 [L]

It won't allow me to access a file at website.com/js/main.php
but it will let me access index.php
According to my webhost, $1 is being called before it is set. Any solutions?
I'll accept answers when i get back tomorrow. Thank you!

A: I'm assuming you want the rewrite to ignore the things which your condition currently specifies. In that case...
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond !^(index\.php|images|img|css|js|robots\.txt)
RewriteRule (.*) index.php?/$1 [L,QSA]

...should work fine. You'll probably want the QSA on there so that if there's a query string, it's properly handled.

A: Your web host is wrong. The order of ruleset processing is:

*

*pattern in RewriteRule is tested (that will populate the $N references with values)

*associated RewriteCond conditions are tested (if present)

Only if the pattern matches the current URL path and the associated condition is fulfilled, the pattern is applied.
So in your case the pattern (.*) is tested on the current URL path js/main.php (without local prefix /). It matches ($0=js/main.php, $1=js/main.php) so the three associated conditions are tested in the order they appear:

*

*RewriteCond %{REQUEST_FILENAME} !-f

*RewriteCond %{REQUEST_FILENAME} !-d

*RewriteCond $1 !^(index\.php|images|img|css|js|robots\.txt)
Assuming that the requested URL path /js/main.php does not refer to an existing file or directory, the first conditions are both true. But the third one will evaluate to false as $1=js/main.php and the pattern ^(index\.php|images|img|css|js|robots\.txt) matches (^js branch) js/main.php. So the condition is not fulfilled and the rule is not applied.


text:
Q: parse error: Invalid numeric literal at line 1, column 16 when I pass the below in shell script I am getting an error parse error: Invalid numeric literal at line 1, column 16
sgRuleDetail=`echo $sGroupsMyIp | jq --arg sGroupId "$sGroupId" 'select(.sgId | contains($sGroupId))'`


text:
Q: search serialised meta_value for date value? i've saved and array of 'open days' as a serialised array in a meta value.
I was hoping i could then just search this field for the selected dates but i can't seem to create a match.
serialised = a:2:{i:0;s:10:"2011-09-16";i:1;s:10:"2011-09-17";} ; // two open dates
and was trying this and some variation without luck ;
$values_serialized = serialize(array('2011-09-16')); // need to serialise???

$args =  array ('meta_query' => array(
    array( 'key'=>'v-openDays', 'value'=>$values_serialized,'compare'=>'IN' )
  )
)
// IN or LIKE?

will also be searching for multiple days but need to get one working first! Help appreciated, Dc

A: Don't serialize the search value, just use 'value' => '2011-09-16' 'compare' => 'LIKE'.
Otherwise you're essentially looking for;
a:1:{i:0;s:10:"2011-09-16"}

Which of course doesn't actually match anywhere in;
a:2:{i:0;s:10:"2011-09-16";i:1;s:10:"2011-09-17";}


text:
Q: Grab all of the pages of a PDF using textsharp
I am getting a pfd using the older version of itextsharp with this code
string Oldfile = @"C:/test.pdf"; // Gets the Template
    (new FileInfo("C:/C:/test.pdf")).Directory.Create(); // Go create this folder if it's not there
    string NewFile = "C:/test.pdf";
    PdfReader reader = new PdfReader(Oldfile);
    iTextSharp.text.Rectangle Size = reader.GetPageSizeWithRotation(1);
    Document document = new Document(Size);
 //   MemoryStream memory_stream = new MemoryStream();
   FileStream fs = new FileStream(NewFile, FileMode.Create, FileAccess.Write);
    PdfWriter weiter = PdfWriter.GetInstance(document, fs);
    document.Open();
    PdfContentByte cb = weiter.DirectContent;
    PdfImportedPage page = weiter.GetImportedPage(reader, 1);
    //PdfImportedPage page2 = weiter.GetImportedPage(reader, 2);
    cb.AddTemplate(page, 0, 0);

The problem I am having is when it gets that file it has 2 pages in that pdf but it only gets the 1st page and adds lines and saves the only 1st page of the pdf I want to be able to grab both of them or is there a way to merge them after wards

A: I bet you need to iterate all pages.
using System;
using System.IO;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace TestAnything
{
    class Program
    {

        static void Main(string[] args)
        {
            List<string> filesToMerge = new List<string> { @"c:\temp\1.pdf", @"c:\temp\2.pdf" };
            FileInfo destinationFile = new FileInfo(@"c:\temp\merge.pdf");
            if (File.Exists(destinationFile.FullName))
                File.Delete(destinationFile.FullName);
            MergeFiles(filesToMerge, destinationFile);
        }

        public static void MergeFiles(List<string> sourceFiles, FileInfo destinationFile)
        {
            if (sourceFiles == null || sourceFiles.Count == 0)
                throw new ArgumentNullException("blahhh.");

            PdfReader reader = new PdfReader(sourceFiles[0]);
            Document document = new Document(reader.GetPageSizeWithRotation(1));
            PdfCopy writer = new PdfCopy(document, new FileStream(destinationFile.FullName, FileMode.Create));
            document.Open();
            try
            {
                foreach (string sourceFile in sourceFiles)
                {
                    reader = new PdfReader(sourceFile);
                    reader.ConsolidateNamedDestinations();

                    for (int x = 1; x <= reader.NumberOfPages; x++)
                        writer.AddPage(writer.GetImportedPage(reader, x));

                    PRAcroForm form = reader.AcroForm;
                    if (form != null)
                        writer.CopyAcroForm(reader);
                }
            }
            finally
            {
                if (document.IsOpen())
                    document.Close();
            }
        }
    }
}


text:
Q: Initialize multiple constant class members using one function call C++ If I have two different constant members variables, which both need to be initialized based on the same function call, is there a way to do this without calling the function twice?
For example, a fraction class where numerator and denominator are constant.
int gcd(int a, int b); // Greatest Common Divisor
class Fraction {
public:
    // Lets say we want to initialize to a reduced fraction
    Fraction(int a, int b) : numerator(a/gcd(a,b)), denominator(b/gcd(a,b))
    {

    }
private:
    const int numerator, denominator;
};

This results in wasted time, as the GCD function is called twice. You could also define a new class member, gcd_a_b, and first assign the output of gcd to that in the initializer list, but then this would lead to wasted memory.
In general, is there a way to do this without wasted function calls or memory? Can you perhaps create temporary variables in an initializer list?

A:
In general, is there a way to do this without wasted function calls or memory?

Yes.  This can be done with a delegating constructor, introduced in C++11.
A delegating constructor is a very efficient way to acquire temporary values needed for construction before any member variables are initialized.
int gcd(int a, int b); // Greatest Common Divisor

class Fraction {
public:
    // Call gcd ONCE, and forward the result to another constructor.
    Fraction(int a, int b) : Fraction(a,b,gcd(a,b))
    {
    }
private:
    // This constructor is private, as it is an
    // implementation detail and not part of the public interface.
    Fraction(int a, int b, int g_c_d) : numerator(a/g_c_d), denominator(b/g_c_d)
    {
    }
    const int numerator, denominator;
};

A: The member vars are initialized by the order they are declared in the class declaration, hence you can do the following (mathematically)
#include <iostream>
int gcd(int a, int b){return 2;}; // Greatest Common Divisor of (4, 6) just to test
class Fraction {
public:
    // Lets say we want to initialize to a reduced fraction
    Fraction(int a, int b) : numerator{a/gcd(a,b)}, denominator(b/(a/numerator))
    {
    }
//private:
    const int numerator, denominator;//make sure that they are in this order
};
//Test
int main(){
    Fraction f{4,6};
    std::cout << f.numerator << " / " << f.denominator;
}

No need for calling another constructors or even making them.

A: @Drew Dormann gave a solution similar to what I had in mind. Since OP never mentions not being able to modify the ctor, this can be called with Fraction f {a, b, gcd(a, b)}:
Fraction(int a, int b, int tmp): numerator {a/tmp}, denominator {b/tmp}
{
}

Only this way there is no second call to a function, constructor or otherwise, so it's no wasted time. And it's no wasted memory since a temporary would have to be created anyway, so you may as well make good use of it. It also avoids an extra division.