text:
Q: Buffer overflow attack, executing an uncalled function So, I'm trying to exploit this program that has a buffer overflow vulnerability to get/return a secret behind a locked .txt (read_secret()).
vulnerable.c //no edits here
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void read_secret() {
    FILE *fptr = fopen("/task2/secret.txt", "r");
    char secret[1024];
    fscanf(fptr, "%512s", secret);
    printf("Well done!\nThere you go, a wee reward: %s\n", secret);
    exit(0);
}

int fib(int n)
{
   if ( n == 0 )
      return 0;
   else if ( n == 1 )
      return 1;
   else
      return ( fib(n-1) + fib(n-2) );
}

void vuln(char *name)
{
    int n = 20;
    char buf[1024];
    int f[n];
    int i;
    for (i=0; i<n; i++) {
      f[i] = fib(i);
    }
    strcpy(buf, name);
    printf("Welcome %s!\n", buf);
    for (i=0; i<20; i++) {
      printf("By the way, the %dth Fibonacci number might be %d\n", i, f[i]);
    }
}

int main(int argc, char *argv[])
{
    if (argc < 2) {
        printf("Tell me your names, tricksy hobbitses!\n");
        return 0;
    }

    // printf("main function at %p\n", main);
    // printf("read_secret function at %p\n", read_secret);
    vuln(argv[1]);
    return 0;
}

attack.c //to be edited
#!/usr/bin/env bash
/task2/vuln "$(python -c "print 'a' * 1026")"

I know I can cause a segfault if I print large enough string, but that doesn't get me anywhere. I'm trying to get the program to execute read_secret by overwriting the return address on the stack, and returns to the read_secret function, instead of back to main.
But I'm pretty stuck here. I know I would have to use GDB to get the address of the read_secret function, but I'm kinda confused. I know that I would have to replace the main() address with the read_secret function's address, but I'm not sure how.
Thanks

A: If you want to execute a function through a buffer overflow vulnerability you have to first identify the offset at which you can get a segfault. In your case I assume its 1026. The whole game is to overwrite the eip(what tells the program what to do next) and then add your own instruction.
To add your own instruction you need to know the address of said instruction and then so in gdb open your program and then type in:
x function name

Then copy the address. You then have to convert it to big or little endian format. I do it with the struct module in python.
import struct
struct.pack("<I", address) # for little endian for big endian its different

Then you have to add it to your input to the binary so something like:
    python -c "print 'a' * 1026 + 'the_address'" | /task2/vuln
    #on bash shell, not in script
If all of this doesnt work then just add a few more characters to your offset. There might be something you didnt see coming.
python -c "print 'a' * 1034 + 'the_address'" | /task2/vuln

Hope that answers your question.


text:
Q: Erro Closure on a variable in loop of outer scope Estou desenvolvendo uma aplicação aonde recebo uma lista de empresas e suas localização (latitude e longitude), então eu tenho que plotar todas essas localizações no Google Maps, o meu problema e ao tentar adicionar um listner para capturar o click nesses markers e então abrir uma infoWindow.
Meu código:
empresaMark;
empresasMarkers = [];

    for (var i = 0; i < empresas.length; i++) {

            empresaMark = new google.maps.Marker({
                position: { lat: Number(empresas[i].Latitude), lng: Number(empresas[i].Longitude) },
                map: map,
                title: empresas[i].Nome,
                icon :'../Content/imagens/Icones/Markers/building-marker.png'
            });
             empresaMark.info = new google.maps.InfoWindow({
                    content: ''
                        + empresaMark.Nome
             });

        empresaMark.addListener('click', function() {
                empresaMark.info.open(map, empresaMark);
            });
            empresaMarkers.push(empresaMark);
        }

O erro ocorre na seguinte parte do código no objeto empresaMark:
empresaMark.addListener('click', function() {
                empresaMark.info.open(map, empresaMark);
            });

O erro é o seguinte :

Closure on a variable in loop of outer scope

Eu andei lendo sobre Closure e vi algumas perguntas no stackoverflow mas não consegui entender completamente, e muito menos aplicar ao meu código, caso alguém consiga me explicar o que preciso fazer para arrumar esse código e a utilidade das Closure eu ficaria grato.
Algumas perguntas que eu vi:
JavaScript closure inside loops – simple practical example
Javascript infamous Loop issue? [duplicate]
How to make object in loop in js with external value in javascript?

A: Aqui respondi uma pergunta parecida com a sua. Uma das soluções, inclusive, é a mesma.
O problema no seu código é que você sempre está acessando a variável empresaMarke do contexto em que seu click handler foi criado, esta variável, ao final da execução do loop, sempre apontará para o último marker criado no loop, e não aquele em que o handler foi criado.
Existem duas formas para resolver seu problema.
Uma é a seguinte(os detalhes estão no link que coloquei acima):
for (var i = 0; i < empresas.length; i++) {
  (function(empresa){
            var empresaMark = new google.maps.Marker({
            position: { lat: Number(empresa.Latitude), lng: Number(empresa.Longitude) },
            map: map,
            title: empresa.Nome,
            icon :'../Content/imagens/Icones/Markers/building-marker.png'
        });
         empresaMark.info = new google.maps.InfoWindow({
                content: ''
                    + empresaMark.Nome
         });

        empresaMark.addListener('click', function() {
            empresaMark.info.open(map, empresaMark);
        });
        empresaMarkers.push(empresaMark);
   }(empresas[i]))

}

A segunda seria fazer uma modificação nesse ponto do código:
 empresaMark.addListener('click', function() {
            empresaMark.info.open(map, empresaMark);
 });

para:
 empresaMark.addListener('click', function() {
      this.info.open(map, empresaMark);
 });

Levando em conta que o próprio marker é passado como contexto para o click handler.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maximum String Mismatches in Java I was recently going through a question in codehub and I was unable to solve this query. Can anyone help me how can this be solved?
You are given a string S of length N. You can select and reverse any substring of S of any length. You are allowed to perform this operation many number of times.
Determine maximum number of mismatches by performing operation.
Mismatch(S) is defined as number of corresponding positions were characters are different in S and reverse(S). For example : S = abab, reverse(S) = baba. Number of mismatches = 4. S= abca. Number of mismatches = 2.
Pseudo code :
static int solve( String S, int n)
{
//To do
}

Will be helpful if some one can explain once the code is done how this can be interpreted more easily and approached to solve.

A: I recently encountered the same question in one of the competency tests, I don't know about above solution, but my implementation below in python works for above problem
import itertools
def maximum_mismatches(s,n):
    if len(set(s)) == 1:
        return 0
    maxc = 0
    for str_c in set(itertools.permutations(s,n)):
        rev_str = str_c[::-1]
        counter = 0
        for i in range(n):
            if str_c[i] != rev_str[i]:
                counter += 1
        if maxc < counter:
            maxc = counter
    return maxc

I have tested for multiple test cases, it is working

A: Calculate the frequency of each character in the string and then take the difference of frequency of each character. See the code example in Java. It returns the max mismatch of characters of a string & it's reverse, given that a substring in the original string can be reversed any number of times.
Examples: 1. cantaaaa (answer = 6), 2. cbbaa (answer = 4), 3. aaaaabbbbccdd (answer = 12)
public static int maxMismatch(String str){
    if(str == null || str.length() <= 1) return 0;

    int freq[] = new int[26];

    for(int i = 0; i < str.length(); i++){
        freq[str.charAt(i) - 97]++;
    }

    int diff = 0;
    for(int i = 0; i < freq.length; i++){
        diff = Math.abs(freq[i] - diff);
    }

    return str.length() - diff;
}

A: import itertools as it
def mismatch(S,n):
    max =0
    for x in set(it.permutations(S[::-1],n)):
        cnt = 0
        for i in range(n):
            if x[i]!=S[i]:
                cnt+=1
        if cnt > max:
            max=cnt
    return max

A: #include <bits/stdc++.h>
using namespace std;
int max_mismatch(string s)
{
  unordered_map<char,int> fmap;
  for(auto &ch:s)
    fmap[ch]++;
  vector<int> tempV;
  for(auto &[_,f]:fmap)
     tempV.push_back(f);
  sort(tempV.begin(),tempV.end(),greater<int>());
  vector<int> freq(tempV.size());
  int diff=0,left=0,right=freq.size()-1;
  bool leftinsert=true;
  for(auto f:tempV)
  {
      if(leftinsert)
          freq[left++]=f;
      else
         freq[right--]=f;
      leftinsert^=1;
  }
  /*for(auto &val:freq)
     cout<<val<<" ";
  cout<<endl;  */
  left=0;right=freq.size()-1;
  for(int i=0;i<s.size()/2;i++)
  {
     if(left==right)
       break;
     if(!(--freq[left])) left++;
     if(!(--freq[right])) right--;
     diff+=2;
  }
  return diff;
}
int main()
{
    string s="aatacanaa";
    cout<<max_mismatch(s);
}

A: First a function to calculate the mismatch score, using this spec:

Mismatch(S) is defined as number of corresponding positions were characters are different in S and reverse(S). For example : S = abab, reverse(S) = baba. Number of mismatches = 4. S= abca. Number of mismatches = 2.

We don't need to actually reverse the string. Just compare the first character with the last, then the second with the second last, etc. I find it straightforward to use two index variables for something like this:
int mismatches(String s) {
    int result = 0;
    int i = 0;
    int j = s.length() - 1;
    while (j >= 0) {
        if (s.charAt(i) != s.charAt(j)) result++;
        i++;
        j--;
    }
    return result;
}

And here are some tests to increase our confidence:
@Test
public void test_mismatches() {
    assertEquals(0, mismatches(""));
    assertEquals(0, mismatches("a"));
    assertEquals(0, mismatches("aa"));
    assertEquals(2, mismatches("ab"));
    assertEquals(0, mismatches("aaa"));
    assertEquals(2, mismatches("aab"));
    assertEquals(2, mismatches("abc"));
    assertEquals(0, mismatches("aaaa"));
    assertEquals(2, mismatches("aaab"));
    assertEquals(2, mismatches("aaba"));
    assertEquals(4, mismatches("abcd"));
}

Now let's find the max mismatch. Here is the spec:

You are given a string S of length N. You can select and reverse any
substring of S of any length. You are allowed to perform this
operation many number of times.
Determine maximum number of mismatches by performing operation.

This is unclear and has typos. It is lazily written and if it was client work, I would be asking for a clarification. I've been burned in the past by working from unclear specs, and building something that the client didn't intend.
I think the use of the word "reverse" is a misnomer. I think it is to help hint at a solution for calculating the mismatch. The spec should be:

You are given a string. Determine maximum number of mismatches from any substring. For clarity, the original string is a valid substring of itself.

With this revised spec, we can just use a nested for loop to traverse the search space:
int maxMismatches(String s) {
    int result = 0;
    for (int i = 0; i < s.length(); i++)
        for (int j = s.length(); j > i; j--) {
            int mismatch = mismatches(s.substring(i, j));
            if (mismatch > result)
                result = mismatch;
        }
    return result;
}

And some tests:
@Test
public void test_max_mismatches() {
    assertEquals(0, maxMismatches(""));
    assertEquals(0, maxMismatches("a"));
    assertEquals(0, maxMismatches("aa"));
    assertEquals(2, maxMismatches("ab"));
    assertEquals(2, maxMismatches("aba"));
    assertEquals(4, maxMismatches("aabbaa"));
    assertEquals(6, maxMismatches("aaabcda"));
}

There is a gap in this set of tests. Some of the test strings require truncating the start to find the max. Some require truncating the end, but none require truncating both the start and end.
Both functions have obvious optimisations but they reduce clarity in a scenario where I don't think performance is important.

A: Here you could first reverse the giving string and then just iterate through the giving string and compare character at each index in both the giving string and reversed string and if there is a mismatch increase the counter.
Check the below code
public static void main(String args[])throws IOException {

    String s = "abab";
    System.out.println(solve(s,s.length()));
}

static int solve( String s, int n)
{
    //this can also be used to reverse string
    //String reversed = new StringBuilder(s).reverse().toString();

    String revStr = Stream.of(s)
            .map(word->new StringBuilder(word).reverse())
            .collect(Collectors.joining(" "));

    int counter = 0;
    for(int loop=0; loop < n; loop++){
        if(s.charAt(loop)!=revStr.charAt(loop)){
            ++counter;
        }
    }
    return counter;
}


text:
Q: MATLAB: Conditionally define get/set class methods I have created some MATLAB classes to do some error-checking when I use certain types of structures. This improve development time by preventing errors in the code, but significantly slow down execution time.
One way to get around this is to comment out the set methods inside the class. Is it possible to do this programmatically? For example, only define these methods if a parameter in the constructor is true.
classdef MWE
    %MWE     Minimum working example

    properties
        A
        B
        C
    end

    methods
        function obj = MWE(A, B, C)
            if nargin ~= 3
                error('A, B and C must all be provided.');
            end

            obj.A = A;
            obj.B = B;
            obj.C = C;
        end

%         function obj = set.A(obj, value)
%             validate(obj, value, 'A');
%             obj.A = value;
%         end
%
%         function obj = set.B(obj, value)
%             validate(obj, value, 'B');
%             obj.B = value;
%         end
%
%         function obj = set.C(obj, value)
%             validate(obj, value, 'C');
%             obj.C = value;
%         end

    end

    methods (Access = private)
        function validate(obj, value, name)
            % Code here
        end
    end
end

A:
Is it possible to do this programmatically? For example, only define these methods if a parameter in the constructor is true.

After some discussion, I see there are different ways of looking at your question.  And, indeed, it may be that you cannot do what you are asking as interpreted by some.  Here are two cases, however, that may suffice.

*

*Case 1

You have computationally intensive or otherwise time consuming methods, that you use to "do some error-checking", in a development setting, but want to turn off in a production environment.  And, these checks occur when the class is instantiated.

Place these methods in a wrapper function that is called from the constructor.
Here's an example
classdef classFoo
   properties(Access=private)
       fbar;
   end
   methods
       function this = classFoo(arg1, argN, debugMode)
           if(nargin>2 && debugMode)
               if(~this.verifyStuff(arg1, argN))
                   throw(MException('classFoo:ConstructFailure','Could not verify'));
               else
                    this.fbar = timeConsumingFunction();
               end
           else
               this.fbar = 42; % defaultValue;
           end
           % continue construction

       end
       function didVerify = verifyStuff(this, varargin)
           % complex code
           didVerify = randi(2)-1;  % 50/50
       end
   end
end

Then when creating objects you can choose to pass the debug mode flag as true like this:
a=classFoo(1,2,true)

or as false, like this:
a=classFoo(1,2,false)

or not at all, which is the same as the false case, like this:
a=classFoo(1,2)

*

*Case 2

You have two different versions of a get/set method that you are commenting out depending on your development environment.

Add a private member parameter (e.g. isDebugging) and set it at time of construction.  Now, instead of commenting out code in your get and set methods, you can handle the different cases with a simple if/else, predicated on your debug state like this:
classdef classFoo
   properties(Access=private)
       fbar;
       isDebugging;
   end
   methods
       function this = classFoo(debugMode)
           if(nargin<1 || ~islogical(debugMode))
               debugMode = false;
           end
           this.isDebugging = debugMode;
        end
        function setfbar(this, fIn)
             if(this.isDebugging)
                 this.fbar = timeConsumingFunction(fIn);
             else
               this.fbar = fIn; % defaultValue;
           end
        end
   end
end


text:
Q: Сортировка массива. Js Здравствуйте, столкнулся с вопросом.
Работаю с World of Tanks API, получаю Id всех танков игрока.
Тут же запрашиваю информацию по айди (Название танка, количество боев игрока на данном танке).
for (var i = 0; i < 20; i++) {
    tankName[i] = json.data[accId][i].name
    tankBattles[i] = json.data[accId][i].all.battles
}

В итоге получаются два массива, в которых tankName[1] соответствует tankBattles[1] и т.д.
Нужно показать пользователю список (Название, количество боев), но так, что бы танки сортировались от Большего количества боев, до Меньшего.
Извините за не очень ясную постановку вопроса, пишу впервые...

A: Делайте сразу правильно и пусть зависимые элементы будут в одном объекте:

let tanks   = [{tankName: 'Я танк 1', battles: ['Битвы танка 1'], score: 45}, {tankName: 'Танк 2', battles: ['Второго танка битвы'], score: 154}, {tankName: 'Третий танк', battles: ['Танка 3 битвы'], score: 12}];

let sortedTanks = tanks.sort((f, s) => f.score < s.score);
console.info(sortedTanks);


text:
Q: How do i force shut down on a computer without on off button I have a chromebook, I just installed Uberstudent(based on ubuntu 14.04) on it and when I tried to reboot it after installing, it doesn't shut down.
It just says

SQUASHFS error: Unable to read metadata cache entry [a6a58c76]
SQUASHFS error: Unable to read directory block [a6a58c76:196]

over and over and I can't write anything. I removed the USB while it was shutting down, so maybe thats something.
Anyway, I want to force shut down but acer 720p chromebook doesn't have a shut down key, it uses F12 as a shut down key which doesn't work since i installed linux.
So, how do i force shut down?

A: Im not sure if UberStudent has this feature since I never used this distro before but try the following in the command line to force a shutdown:
echo 1 > /proc/sys/kernel/sysrq
echo o > /proc/sysrq-trigger

This other command will force a reboot:
echo 1 > /proc/sys/kernel/sysrq
echo b > /proc/sysrq-trigger

A:
Anyway, I want to force shut down but acer 720p chromebook doesn't have a shut down key, it uses F12 as a shut down key which doesn't work since i installed linux.

*

*The power key is the power key. I just checked with my N22 booting Ubuntu 16.04 from a USB HDD. The N22 keyboard is not supported (USB keyboards work), but when I press the power button at the login screen I'm getting the shutdown or reboot options. If I would press the power button for 4 seconds or a bit longer it would power down via ACPI, I had to do that before, so I know that works despite of what function is mapped.

*Realize that there are different keyboard mappings. Just because you use a distro which is unaware of chromebook hardware doesn't mean that the power key becomes the F12 key or some other misguided interpretation of what this key is or isn't.


text:
Q: post link ID value from php to another php page when clicked I'm hoping you guys can help me out. So the question is, how to get that link id from page 1 and send it to page 2 when the link is clicked? So I can query based on clicked id to display its own content instead of displaying the whole content for each id. Page 2 is included in page 1. So connection to database is the same. Floors table and Rooms table is in the same database.
Here is my code.
Page 1 (sidebar menu. For example Ground Floor, 1st Floor)
<?php
    $result = $conn->query("select * from floors");
    while ($row = $result->fetch_assoc())
    {
        ?>
<a href="#floor" data-toggle="tab" id="<?php echo $row['floorid'];?>"><?php echo $row['floorname'];?>
<?php
    }
?>

Page 2 (sidebar menu content. For example Ground Floor content, 1st Floor content)
<?php
    $result = $conn->query("SELECT * FROM rooms WHERE floorid = '".$_GET['id']."'");
    while($row = $result->fetch_assoc())
    {
        ......
    }
    mysqli_close($conn);
?>

A: You can archive this in many ways but I'm going to show your 2 ways you can get this done.
First will be pure PHP,
1st page:
<?php
    $result = $conn->query("select * from floors");
    while ($row = $result->fetch_assoc())
    {
        ?>
<a class="links" href="page2.php?id=<?php echo $row['floorid'];?>" data-toggle="tab" id="<?php echo $row['floorid'];?>"><?php echo $row['floorname'];?>
<?php
    }
?>

Above code will directly send your data to the 2nd page where you want it to get your data from the data base. This will work but it will load your 2nd page on to the browser (if that what you want). But you have tagged 'javaScript' so I'm going to show you another way using jQuery and AJAX.
1st apge PHP:
<?php
    $result = $conn->query("select * from floors");
    while ($row = $result->fetch_assoc())
    {
        ?>
<a class="links" href="#" id="<?php echo $row['floorid'];?>"><?php echo $row['floorname'];?>
<?php
    }
?>

You can put this part in the same page as the above code or you can put it in separate JS file and link it to you PHP.
$(document).ready(function() {
    $(document).on('click', '.links', function(){
        var id = $(this).prop('id');

        $.ajax({
            url: 'page2.php',
            type: 'get',
            data: {'id': id}
        }).then(function (response) {
            if (response) {
                $('#floor').html(response);
            }
        });
    });
})

What the above code does is when the document is ready it listens or looks for click event's on the specified class which is '.links'. When the functions see there's a click event on any link under the '.link' class it takes the the click even and reads the 'id' property value.
Then using AJAX it sends the that captured data to your 2nd PHP graps the response from that PHP and populates the div under the id 'floor'.
Plus point is that your processing PHP won't be loaded it will be processed in the server and the main page will not get refreshed the div will be re-written with the in coming response text.
Hope this helps if it doesn't work just let me know.
NOTE: Please read up and switch to using prepared statements. If you're using mysqli then read this. If you're using PDO then read this.

A: Change
<a
    href="#floor"
    data-toggle="tab"
    id="<?php echo $row['floorid'];?>">
        <?php echo $row['floorname'];?>

To
<a
    href="?id=<?php echo $row['floorid'];?>#floor"
    data-toggle="tab"
    id="<?php echo $row['floorid'];?>">
    <?php echo $row['floorname'];?>

I added the id before the #floor so that you can use $_GET['id'] while redirecting to the element who have the id floor
To avoid the Undefined index error, use this:
<?php
    if(isset($_GET['id'])){
        $result = $conn->query("SELECT * FROM rooms WHERE floorid = '".$_GET['id']."'");
        while($row = $result->fetch_assoc())
        {
            ......
        }
        mysqli_close($conn);
    }
?>

A: You can use this code.
this is possible using two method one is $_GET and $_POST

*

*$_GET Method example :-

<a href="?id=<?php echo $row['floorid'];?>#floor" data-toggle="tab" id="<?php echo $row['floorid'];?>"><?php echo $row['floorname'];?>

Add the
href="?id=<?php echo $row['floorid'];?>#floor"
in anchor tag.
enter image description here


text:
Q: import html mysql table to excel with php. Big numbers converts to exponential in excel file I am fetch data from mysql table in html format and further it export to excel using php. Mysql table contains bigint stud_id like 201927341302805000 when I exported to excel it will display like 2.01927E+17. All stud_id of tables will converted to same number as 2.01927E+17.
Script used for export to excel:

I want send  bigint number as it is when I exported mysql file to excel.


text:
Q: Youtube HTML5 green screen and beep sound I am trying to get rid of Flash (using Flasblock) in my Firefox but I have a problem with YouTube.
After blocking it Firefox switched YT player to HTML5 but there is only 360p resolution available!
I searched in the internet to find a solution and I've tried changing few options in about:config to look like this:

*

*media.mediasource.enabled;  true

*media.mediasource.mp4.enabled;  true

*media.mediasource.webm.enabled;  true

*media.mediasource.whitelist;  true

*media.fragmented-mp4.enabled;  true

*media.fragmented-mp4.exposed;  true

*media.fragmented-mp4.ffmpeg.enabled;  false

*media.fragmented-mp4.gmp.enabled;  false

*media.fragmented-mp4.use-blank-decoder;  true
And when I go to https://www.youtube.com/html5 Everything is OK but when I try to play some video on YT I get a green screen and a beep sound.
But now I can choose the resolution.
Does anyone know how to fix this?
It works fine in Chrome

A: You have to set the option media.fragmented-mp4.use-blank-decoder to false, this is the cause of your problem.


text:
Q: I need help installing and using ubuntu I'm new here! I downloaded Ubuntu 13.10 32 bit version just now. It downloaded in .RAR (Winrar). When i open the file, i have many folders in it and at last, i have this "wubi.exe" file. i double-click it and it extracts. But after extraction, nothing rally happens. Sometimes i get the windows error sound but no pop-up box comes on the screen.
My second question, should i install it on my harddrive(with my windows) or a dvd, or a pendrive? What to do? Can someone give me a complete guide on ubuntu? Never used.
And also, i forgot my bios password, so i can't enter into bios. is that a problem? Can anyone help me on this too?
If there's anything i need to know, please tell me :)

A: Check your browser settings and check how it downloads .iso files. set it in such a way that it downloads the file directly as it is and stores it somewhere.
Once done this,mount the file on a cd/dvd/usb.
All you need to know next is here.
Also there is some possibility that you will boot into black screen.If so read this.
And lastly,for all the basic problems you will mostly probably fall into,the frequent questions page.
And not to forget,the bios password won't matter at all.should not until you wish to break your computer with wrong bios settings.

A: Dude, it is an iso file, and since you don't have any software to mount iso files, Winrar automatically shows the iso file types as winrar files. Don't worry.
Use a free iso mounter software like Daemon tools.
You can get the free version here.
http://www.daemon-tools.cc/products/dtLite#features
After installing it now see the file you have downloaded. The icon may be changed. If not no problem. Open Daemon tools from start menu and choose "Mount" option. Then browse for the file you have downloaded and select mount. Now you can see the files inside that iso file in "My Computer". Use WUBI installer to install. And for further assistance,
Follow the link aditya patil posted.

A: First thing, I suppose you would have to change your boot sequence in order to install Ubuntu through a USBstick, or pendrive like you said, but I'm not sure if you'll be able to do it without the BIOS password. So let's stick with another option.
You can use a DVD burning software to burn a DVD with the Ubuntu .iso file. After that, all you need to do is insert the disc and install.
But, since you're using Windows, I guess it would be much more simple if you just use a Windows Installer for Ubuntu instead of the .iso file.
You can get the installer in this page: http://www.ubuntu.com/download/desktop/windows-installer
And the installation instruction here: http://www.ubuntu.com/download/desktop/install-ubuntu-with-windows
Unfortunately it's not available for Windows 8 and Ubuntu 13.10.
If you still want to try a .iso file installation I recommend you to take a look at the others two articles (How to burn a DVD - How to create a bootable USB stick) you can find in that last page I posted here (right of the page).


text:
Q: Calculate area covered by pixels in several rasters I've a list of 96 categorical rasters (each with an associated variable i.e. rcp, period and month) with values ranging from 1-16 and I would like to calculate the area covered by each of those categories in each raster and return NA if the category doesn't exist in a raster.
This is the function I have created for now
a <- function(x){
rs <- x #categorical raster
b <- getValues(area(x, weights=FALSE))
b <- aggregate(b, by=list(getValues(x)), sum, na.rm=T)
b <- as.data.frame(b)
names(b) <- c("CLASS","AREA")
return(b)
}

The problem with this is that it returns a data frame with the existing raster values only and without the missing values. See below:
  CLASS       AREA
1     1 145084.052
2     5  39425.336
3     6  37912.591
4    10  10089.541
5    11   3150.571
6    15   1451.912
7    16   4289.296

How can I return a data frame with all the categories (1-16)? and combine all outputs into one? The column names should be rcp, period and month.
Here is my code for now:
mthLs <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
rcpLs <- c("rcp26", "rcp45", "rcp60", "rcp85")
periodLs <- c("2020_2049", "2040_2069")

for(rcp in rcpLs){
  rcpDir <- paste0(iDir, "/", rcp)
     for(period in periodLs){
         for (mth in 1:12) {
          rs <- raster(paste0(iDir, "/", rcp, "/", period, "/cng_", mth, ".tif", sep=""))
          b <- a(rs) #using function above
         }
       im <- cbind(RCP=rep(rcp,times=nrow(b)), PERIOD=rep(period,times=nrow(b)), MONTH=rep(mth,times=nrow(b)), b)

      }
  write.csv(im, paste(oDir, "/output.csv", sep=""), quote=T, row.names=F)
}

A: This could help
txt <-
"CLASS,REA
1,145084.052
5,39425.336
6,37912.591
10,10089.541
11,3150.571
15,1451.912
16,4289.296"

b <- read.csv(textConnection(txt),sep =  ",")

classes <- 1:16

merge(data.frame(CLASS = classes), b, by='CLASS', all.x=T)

result:
   CLASS        REA
1      1 145084.052
2      2         NA
3      3         NA
4      4         NA
5      5  39425.336
6      6  37912.591
7      7         NA
8      8         NA
9      9         NA
10    10  10089.541
11    11   3150.571
12    12         NA
13    13         NA
14    14         NA
15    15   1451.912
16    16   4289.296

A: Example data
library(raster)
r <- raster(nc=5, nr=5)
set.seed(20171214)
r1 <- setValues(r, sample(16, ncell(r), replace=TRUE))
r2 <- setValues(r, sample(16, ncell(r), replace=TRUE))
r3 <- setValues(r, sample(16, ncell(r), replace=TRUE))

If you can make a RasterStack (RasterLayers with same extent and resolution), you can do:
s <- stack(r1,r2,r3)
x <- freq(s)

m <- data.frame(value=1:16)
for (i in 1:length(x)) {
    y <- x[[i]]
    colnames(y)[2] <- paste0("v", i)
    m <- merge(m, y, all.x=TRUE)
}

m
#   value v1 v2 v3
#1      1  3  2  1
#2      2 NA  3 NA
#3      3  2  2  1
#4      4  1  3  2
#5      5  1 NA  2
#6      6  1  3  3
#7      7 NA  3  4
# ...

Or, without the RasterStack, create a list of RasterLayer objects e.g. with
# z <- lapply(filenames, raster)

But for this example we can do it more manually:
z <- list(r1, r2, r3)

m <- data.frame(value=1:16)
for (i in 1:length(z)) {
    y <- freq(z[[i]])
    colnames(y)[2] <- paste0("v", i)
    m <- merge(m, y, all.x=TRUE)
}

Or -- perhaps most straightforward --- with a vector with filenames ff
m <- data.frame(value=1:16)
for (i in 1:length(ff)) {
    y <- freq(raster(ff[i]))
    colnames(y)[2] <- paste0("v", i)
    m <- merge(m, y, all.x=TRUE)
}


text:
Q: Trying to get property 'nome' of non-object Laravel Eloquent Error ao puxar dados chave estrangeira Estou tentando usar relacionamentos para mostrar dados na tela mas eu recebo o seguinte erro:

Trying to get property 'nome' of non-object

Neste comando
$recebimento->planoconta()->get()->first()->nome

MODEL PLANO CONTA
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Planoconta extends Model
{
    //
    protected $table = 'plano_contas';

    protected $fillable = [
        'tipo', 'nome',
    ];

    public function pagamento():hasMany{
        return $this->hasMany('App\Pagamento', 'plano_contas_id');
    }

    public function recebimento():hasMany{
        return $this->hasMany('App\Recebimento', 'plano_contas_id');
    }

}

MODEL RECEBIMENTOS
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Cliente;
use Planoconta;

class Recebimento extends Model
{
    //
    protected $table = 'recebimentos';

    protected $fillable = [
        'data_emissao','data_venci','documento','parcela', 'valor', 'cliente_id','plano_contas_id', 'descricao',
    ];

    public function cliente():BelongsTo{
        return $this->BelongsTo('App\Cliente');

    }

    public function planoconta():BelongsTo{
        return $this->BelongsTo('App\Planoconta');

    }

}

HTML
@foreach($recebimentos as $recebimento)

id}}">
       {{$recebimento->id}}
       {{$recebimento->data_receb}}
       {{$recebimento->valor}}
       {{$recebimento->cliente()->get()->first()->nome}}
       {{$recebimento->planoconta()->get()->first()->nome}}
       <button class="btnOpenUpdateRecebimento btn btn-info" data-id="{{$recebimento->id}}" data-data_receb="{{$recebimento->data_receb}}" data-valor="{{$recebimento->valor}}" data-cliente_nome="{{$recebimento->cliente()->get()->first()->nome}}" data-cliente_id="{{$recebimento->cliente()->get()->first()->id}}" data-plano_contas="{{$recebimento->plano_contas}}" > </button>
                                    <button class="delete-recebimento btn btn-danger" data-id="{{$recebimento->id}}" data-data_receb="{{$recebimento->data_receb}}" data-valor="{{$recebimento->valor}}" data-cliente_nome="{{$recebimento->cliente()->get()->first()->nome}}" data-cliente_id="{{$recebimento->cliente()->get()->first()->id}}" ></button>

   @endforeach

MODEL CLIENTE QUE ESTA FUNCIONANDO E FIZ EXATAMENTE IGUAL
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\hasMany;
use Recebimento;

class Cliente extends Model
{
    ////
    protected $table = 'clientes';

    protected $fillable = [
        'nome', 'cpf', 'endereco', 'numero', 'cep', 'complemento', 'bairro', 'celular', 'telefone', 'cidade', 'estado', 'email',
    ];

    public function recebimento():hasMany{
        return $this->hasMany('App\Recebimento', 'cliente_id');
    }
}

A: public function recebimento():hasMany{
    return $this->hasMany('App\Recebimento', 'plano_contas_id', 'id');
}

public function planoconta():BelongsTo{
    return $this->BelongsTo('App\Planoconta', 'id', 'id');
}

Importante sempre informar os campos!


text:
Q: store image in database how to store image in database and retrive from database

A: It depends upon the circumstances. IF you are not having a large number of images then store them in you data base and their datatype should be blob. But if you are having a large number of images then store them in extra folder and save the path in your database


text:
Q: Regex Replace Match Found in String I am using a Regex to find a pattern within a string.  After I find a match I would then like to remove it from the existing string.
For example:
starting string ex: "Billed Hours (.5);"
converted string: "Billed Hours"

The regex pattern I am using is  @"([a-z.]+);$" - Not sure if this is correct, I want to check that only whole numbers or decimals are within the parentheses. If the pattern matches then remove parentheses, the value inside as well as the following semi-colon.
This is what I have so far:
string testString = "Billed Hours (.5);"
testString = Regex.Replace(testString, @"\([a-z.]+\);$", "");

This is in C#.
Any ideas?

A: Consider...
string testString= Regex.Replace(testString, @"\(\d*\.?\d*]*\);$", "");

A: Try the regex:
@"\s+\([^)]+\);$"

And replace by nothing.
The \s+ is to avoid having to trim spaces and [^)]+ matches any character except closing paren.


text:
Q: How do I show an image generated from scandir on php I am trying to show an image on a Wordpress post from a folder on the server. The images in the folder are put into an array using scandal and the . and … are ignored. The folder that the image comes from is selected using GET and is put into the url at the end of the address along with the image number. This is so the latest image (which is timestamped on the filename can be chosen using the array number.
Loading up the URL directly using "http://www.weburl.com/wp-content/.../getlatestimage.php?image=pap&num=1 will load up the image directly however if I try and put it in as img src or via an image block will not load the photo into the page. I believe that this is because the code echos an  in the php but I do not know how to load it into a constructed webpage any other way.
Here is the code I have written:
<?php
$imagepath = htmlspecialchars($_GET["image"]);
$imagenum = htmlspecialchars($_GET["num"]);

define('LOCALHOST', 'localhost' === $_SERVER['SERVER_NAME'] );

If(LOCALHOST){
    define('PATH_IMAGES', 'this_path');
}else{
    define('PATH_IMAGES', '../../../Images/');
}
?>

<?php
    $arrnum = $GLOBALS[imagenum] - 1;
    echo $arrnum;
    $dirname = PATH_IMAGES . $GLOBALS[imagepath]."/";
    $images = scandir($dirname);
    rsort($images);
    $ignore = Array(".", "..");
    foreach($images as $curimg){
        if(!in_array($curimg, $ignore)) {
            //echo "

";
            header('Content-type: image/jpeg');
            //echo file_get_contents($dirname$images[$arrnum]);
            echo "

Any and all help will be really appreciated.


text:
Q: Floating Objects and Weight The Situation:
A ball is placed in a beaker filled with water and floats. It is also attached to the bottom of the beaker via a string.
The Question:
The ball is attached to the beaker, thus making the ball and beaker (and string included) a system. However, it is floating. Does the ball add to the weight of the beaker?

A: Yes, it does. When an object floats, its mass is not affected. It only affect the force experienced by it, as the water exerts a "buoyant force" on the object:

Basically, there is a pressure difference between the top and bottom surfaces, and this corresponds to a force difference, leading to a net upwards force:

However, remember that the force exerted by the water on the object leads to an equal and opposite force exerted by the object on the water. Since at equilibrium, $m_{obj}g=\text{buoyant force}$, a force equal to the weight of the body is exerted on the water. When the beaker is weighed, this extra force is balanced by the normal force.
Here are some free body diagrams. BF is the buoyant force, T is the string tension. Note that N is the weight that the weighing platform measures.


text:
Q: error deleting from database I have a SQL Server Compact database created through VS 2010 (Local Database File option).
On form load (CategoryForm) I load the values from the database into the DataGridView1. I also add an extra ButtonColumn programmatically that I use for the Delete part.
The problem is this:

*

*On initial form load, the first time I press delete on any row, it works. If i press it again it does not work.

*The second time i click the button, the printed text I get on my Msgbox, is the Text of button! (delete) (screenshot included) p.s As mentionted below, when I comment-out the extra stuff, I get the correct values returned.

What I tried:

*

*Commented out everything SQL-related, left only the part where I get the RowIndex and the value at the specific cell at that index. I print them both on MsgBox. The values I get are correct. For example, 0 index and value test for first row with text test.

Below is my progress as well as screenshots:
CellContentClick method:
Private Sub DataGridView1_CellContectClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick

    Dim i As String

    'If e.ColumnIndex = 1 Then
    'If e.RowIndex >= 0 And e.RowIndex <= DataGridView1.Rows.Count - 1 Then

    i = DataGridView1.Rows(e.RowIndex).Cells(0).Value.ToString
    MsgBox(e.RowIndex)
    MsgBox(i)
    SQLStringDelete = "DELETE FROM Category WHERE categoryname = '" & i & "'"
    SQLConn.ConnectionString = ConnString 'Set the Connection String
    SQLConn.Open() 'Open the connection
    SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
    SQLCmd.CommandText = SQLStringDelete 'Sets the SQL String
    SQLCmd.ExecuteNonQuery() 'Executes SQL Command

    'Create Adapter
    Dim DataAdapter As SqlCeDataAdapter = New SqlCeDataAdapter("SELECT categoryname FROM Category", SQLConn)
    'Create DataSet
    Dim Dataset As New DataSet
    'fill the datset
    DataAdapter.Fill(Dataset)
    'attach dataset to the datagrid
    With DataGridView1
        .DataSource = Dataset.Tables(0)
        .Columns(0).HeaderText = ""
        .Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
    End With

    DataAdapter = Nothing
    Dataset = Nothing

    SQLConn.Close() 'Close the connection

End Sub

Form_Load method:
 Private Sub CategoryForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SQLConn.ConnectionString = ConnString 'Set the Connection String
        SQLConn.Open() 'Open the connection

        'Create Adapter
        Dim DataAdapter As SqlCeDataAdapter = New SqlCeDataAdapter("SELECT categoryname FROM Category", SQLConn)
        'Create DataSet
        Dim Dataset As New DataSet
        'fill the datset
        DataAdapter.Fill(Dataset)
        'attach dataset to the datagrid
        With DataGridView1
            .DataSource = Dataset.Tables(0)
            .Columns(0).HeaderText = ""
            .Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
        End With

        DataAdapter = Nothing
        Dataset = Nothing
        SQLConn.Close()

        With buttonColumn
            .Name = "DeleteButtonColumn"
            .HeaderText = ""
            .Text = "Delete"
            .UseColumnTextForButtonValue = True
            .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Width = 50
        End With

        If DataGridView1.Columns.Count = 1 Then
            DataGridView1.Columns.Add(buttonColumn)
        End If

    End Sub

Screenshots:

A: Turns out that the columns where autoregenerating causing column re-arrangement on each the second click. Just set DataGridView1.AutoGenerateColumns = false in both the form load and event and it works.


text:
Q: How to prove this question using Induction? I can't think of a way Assume $A_1$ to $A_m$ are all the subsets of $\{1,2,...,n\}$ which do not contain any consecutive values. Also for each subset $A,$ $P(A)$  is the product of every member of $A.$ ($P(\emptyset)=1.$)
So, for example, if $n=3,$ you get
$$A_1=\emptyset, A_2=\{1\},A_2=\{2\}, A_3=\{3\}, A_4=\{1,3\}$$
Now prove:
$$\sum_{i=1}^m P(A_i)^2 =(n+1)!$$
This is the original question In Farsi (Persian) :
enter image description here

A: Well, Base Case $n=1$ we have $A_1, A_2 = \emptyset, \{1\}$ and $\sum_{i=1}^mP(A_i)^2 = 1^2 + 1^2 = 2 = 2!=(1+1)!$.  Okay.
Just to cement this home let's try another $n=2$ then $A_1, A_2, A_3 = \emptyset, \{1\}, \{2\}$ and $\sum P(A_i)^2 = 1 + 1 + 4 = 6= 3!$.
For a somewhat more complex $n=3$ then $A_1, A_2, A_3, A_4, A_5$ are $\emptyset, \{1\}, \{2\}, \{3\},\{1,3\}$ and $\sum P(A_i)^2 = 1 + 1+4 + 9 + 9 = 24 = 4!$.
Okay.....
Indcution.  Suppose for $n$ we have the result.  Now for $n+1$.  First thing we have to ask ourselves is: what new sets do we have?  We ahve subsets of $\{1,2,3,....,n, (n+1)\}$ and we already would have had all the subsets that didn't include $n+1$ so the only new subsets will have $n+1$.
As there can be no consecutive numbers these new sets can not have $n$.  But every set we had when we calculated $n-1$ can just have $n+1$ added to them and be a new set.
So.... if $A_1, .... A_{m_{n-1}}$ are the subsets of $\{1,2,3,....,n-1\}$ with no consecutive numbers.  And $A_1, ....., A_m$ are the subsets of $\{1,2,3,.....,n\}$ with no consectutive numbers.  Then the new sets that include $n+1$ (but not $n$) are $A_{m+1} ,......., A_{m_{n+1}} = (A_1\cup \{n+1\}, A_2\cup \{n+1\}....., A_{m_{n-1}}\cup \{n+1\})$
And $\sum_{i=1}^{m_{n+1}} P(A_i)^2 = \sum_{i=1}^{m} P(A_i)^2 + \sum_{i=m+1}^{m_{n+1}} P(A_i)^2=$
$(n+1)! + \sum_{i=1}^{m_{n-1}} [P(A_i)\cdot(n+1)]^2=$
$(n+1)! + (n+1)^2\sum_{i=1}^{m_{n-1}}P(A_i)^2 =$
$(n+1)! + (n+1)^2(n-1 + 1)!=$
$(n+1)! + (n+1)^2n! = $
$n![(n+1) + (n+1)^2]=$
$n![(n+1)\{1 + (n+1)\}]=$
$n!(n+1)(n+2) = (n+2)!$.
I'm.... surprised!  But that was fun.
.....
Note as the induction step used assuming the statment is true for $n$ AND also assuming the statement is true for $n-1$ we must use strong induction (where we don't just assume the statement is true for $n$ but is true for all $k \le n$) and as or induction case uses two early stages, we must have two base cases.
Base case 1: $n =1$.
Base case 2: $n = 2$.
Inductions step:  Whenever the statement is true for $n$ and $n-1$ it will be true for $n+1$.
Therefore it is true for all natural $n$.


text:
Q: Tornado code deployment Is there a canonical code deployment strategy for tornado-based web application deployment. Our current configuration is 4 tornado processes running behind NginX? (Our specific use case is behind EC2.)
We've currently got a solution that works well enough, whereby we launch the four tornado processes and save the PIDs to a file in /tmp/. Upon deploying new code, we run the following sequence via fabric:

*

*Do a git pull from the prod branch.

*Remove the machine from the load balancer.

*Wait for all in flight connections to finish with a sleep.

*Kill all the tornadoes in the pid file and remove all *.pyc files.

*Restart the tornadoes.

*Attach the machine back to the load balancer.

We've taken some inspiration from this: http://agiletesting.blogspot.com/2009/12/deploying-tornado-in-production.html
Are there any other complete solutions out there?

A: We run Tornado+Nginx with supervisord as the supervisor.
Sample configuration (names changed)
[program:server]
process_name = server-%(process_num)s
command=/opt/current/vrun.sh /opt/current/app.py --port=%(process_num)s
stdout_logfile=/var/log/server/server.log
stderr_logfile=/var/log/server/server.err
numprocs = 6
numprocs_start = 7000

I've yet to find the "best" way to restart things, what I'll probably finally do is have Nginx have a "active" file which is updated letting HAProxy know that we're messing with configuration then wait a bit, swap things around, then re-enable everything.
We're using Capistrano (we've got a backlog task to move to Fabric), but instead of dealing with removing *.pyc files we symlink /opt/current to the release identifier.

A: I haven't deployed Tornado in production, but I've been playing with Gevent + Nginx and have been using Supervisord for process management - start/stop/restart, logging, monitoring - supervisorctl is very handy for this. Like I said, not a deployment solution, but maybe a tool worth using.


text:
Q: IOS Customkeyboard getting wrong size in Landscape mode I am working on custom keyboard. all works perfect but when i rotate the keyboard to landscape mode the keyboard load correctly but it takes the height of portrait mode keyboardview.

Here is my Try:
  @interface KeyboardViewController ()
{
CGFloat expandedHeight ;
BOOL isPortrait;
}
@property(strong,nonatomic)keyboardLayout *ObjKeyLayout;
 - (void)updateViewConstraints {
[super updateViewConstraints];
[self updateCustomHeight];
}
 -(void)updateCustomHeight
{

if (self.heightConstraint != nil) {
    [self.view removeConstraint:self.heightConstraint];
    [self.view layoutIfNeeded];
}
if(isPortrait)
{
    expandedHeight = 258;
}
else
{

    expandedHeight = 156;
}
self.heightConstraint = [NSLayoutConstraint constraintWithItem:self.view      attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant: expandedHeight];
[self.view addConstraint:self.heightConstraint];
[self.view layoutIfNeeded];
}
- (void)deviceOrientationDidChange:(NSNotification *)notification
{
NSLog(@"key");
if([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height){
    //Keyboard is in Portrait
    isPortrait=YES;
    isp=YES;
    [self LoadKeyboardview];
    [self updateCustomHeight];

}
else{

    isPortrait=NO;

    [self LoadKeyboardview];
    [self updateCustomHeight];

    //Keyboard is in Landscape
  }
  -(void)initiateOrientation
{
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
 if([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height){
    //Keyboard is in Portrait
    isPortrait=YES;
    [self LoadKeyboardview];
}
else{
     isPortrait=NO;
    [self LoadKeyboardview];
  //Keyboard is in Landscape
}
 - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
if([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height){
    //Keyboard is in Portrait
    isPortrait=YES;
    [self LoadKeyboardview];
    [self updateCustomHeight];
    }
else{
     isPortrait=NO;
    [self LoadKeyboardview];
    [self updateCustomHeight];
     //Keyboard is in Landscape
 }
}
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
if([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height){
    //Keyboard is in Portrait
    isPortrait=YES;
     [self LoadKeyboardview];
    [self updateCustomHeight];
    }
else{
    isPortrait=NO;
     [self LoadKeyboardview];
    [self updateCustomHeight];
    }
   }
  - (NSLayoutConstraint*)findViewHeightConstraint {
NSArray *constraints = self.view.superview.constraints;
for ( NSLayoutConstraint *constraint in constraints ) {
    if ( constraint.firstItem == self.view
        && constraint.firstAttribute == NSLayoutAttributeHeight )
        return constraint;
}
[self updateCustomHeight];
return nil;
 }
 - (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
// Update height when rotating
  [self updateCustomHeight];
   }

EDIT : Portrait Mode

EDIT:-
     @implementation KeyboardViewController
      - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Perform custom initialization work here
    self.portraitHeight = 256;
    self.landscapeHeight = 162;
  }
  return self;
    }

 - (void)viewDidLoad {
   [super viewDidLoad];

    // [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(deviceOrientationDidChange:) name: UIDeviceOrientationDidChangeNotification object: nil];

[self copyDatabaseIfNeeded];

NumKey=[[NSArray alloc]initWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"0", @"-", @"/", @":", @";", @"(", @")", @"$", @"&", @"@", @"\"", @".", @",", @"?", @"!",@"'",@"^", nil];

arrAlphabet=[[NSArray alloc]initWithObjects:@"q", @"w", @"e", @"r", @"t", @"y", @"u", @"i", @"o", @"p", @"a", @"s", @"d", @"f", @"g", @"h", @"j", @"k", @"l", @"z", @"x", @"c", @"v", @"b",@"n",@"m", nil];

arrKeyImages=[[NSArray alloc]initWithObjects:@"Q_key.png", @"W_key.png", @"E_key.png", @"R_key.png", @"T_key.png", @"Y_key.png", @"U_key.png", @"I_key.png", @"O_key.png", @"P_key.png", @"A_key.png", @"S_key.png", @"D_key.png", @"F_key.png", @"G_key.png", @"H_key.png", @"J_key.png", @"K_key.png", @"L_key.png", @"Z_key.png", @"X_key.png", @"C_key.png", @"V_key.png", @"B_key.png",@"N_key.png",@"M_key.png", nil];

keyIpad=[[NSArray alloc]initWithObjects:@"Q_Land_key.png", @"W_Land_key.png", @"E_Land_key.png", @"R_Land_key.png", @"T_Land_key.png", @"Y_Land_key.png", @"U_Land_key.png", @"I_Land_key.png", @"O_Land_key.png", @"P_Land_key.png", @"A_Land_key.png", @"S_Land_key.png", @"D_Land_key.png", @"F_Land_key.png", @"G_Land_key.png", @"H_Land_key.png", @"J_Land_key.png", @"K_Land_key.png", @"L_Land_key.png", @"Z_Land_key.png", @"X_Land_key.png", @"C_Land_key.png", @"V_Land_key.png", @"B_Land_key.png",@"N_Land_key.png",@"M_Land_key.png", nil];

  arrspecialImageKey=[[NSArray alloc]initWithObjects:@"1_key.png", @"2_key.png", @"3_key.png", @"4_key.png", @"5_key.png", @"6_key.png", @"7_key.png", @"8_key.png", @"9_key.png", @"0_key.png", @"desh_key.png", @"slash.png", @"shift_shemi.png", @"semi.png", @"left_brecket.png", @"right_breacket.png", @"doller_key.png", @"and_key.png", @"AtTherate.png", @"dobleComma.png", @"dot.png",@"singel_comma.png",@"question_mark.png", @"exemlaration.png", @"single_uppar_comma.png",@"upparArrow.png", nil];

  arrSpecialIpad=[[NSArray alloc]initWithObjects:@"1_Land_key.png", @"2_Land_key.png", @"3_Land_key.png", @"4_Land_key.png", @"5_Land_key.png", @"6_Land_key.png", @"7_Land_key.png", @"8_Land_key.png", @"9_Land_key.png", @"0_Land_key.png", @"Dash_Land_key.png", @"slash_Land_key.png", @"shif_semi_Land_key", @"semi_Land_key", @"left_brecket_Land_key.png", @"right_Land_key.png", @"doller_Land_key.png", @"and_Land_key.png", @"attherate_Land_key.png", @"dobblecomma_Land_key", @"dot_Land_key.png",@"comma.png",@"question.png", @"exemeleter.png", @"uppar_comma.png",@"upArrow.png", nil];

 self.nextKeyboardButton = [UIButton buttonWithType:UIButtonTypeSystem];

 [self.nextKeyboardButton setTitle:NSLocalizedString(@"Next Keyboard", @"Title for 'Next Keyboard' button") forState:UIControlStateNormal];
 [self.nextKeyboardButton sizeToFit];
 self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = NO;

 [self.nextKeyboardButton addTarget:self action:@selector(advanceToNextInputMode) forControlEvents:UIControlEventTouchUpInside];

 [self.view addSubview:self.nextKeyboardButton];
 self.nextKeyboardButton.hidden=YES;

   NSLayoutConstraint *nextKeyboardButtonLeftSideConstraint = [NSLayoutConstraint constraintWithItem:self.nextKeyboardButton attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0];
   NSLayoutConstraint *nextKeyboardButtonBottomConstraint = [NSLayoutConstraint constraintWithItem:self.nextKeyboardButton attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0];
   [self.view addConstraints:@[nextKeyboardButtonLeftSideConstraint, nextKeyboardButtonBottomConstraint]];

  self.heightConstraint = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:self.portraitHeight];

    // Perform custom UI setup here

    }
    - (void)deviceOrientationDidChange:(NSNotification *)notification
 {
self.heightConstraint.constant=expandedHeight;
   NSLog(@"key");
   if([UIScreen mainScreen].bounds.size.width < [UIScreen mainScreen].bounds.size.height){
    //Keyboard is in Portrait
    isPortrait=YES;
    isp=YES;
    [self LoadKeyboardview];
    [self updateCustomHeight];

}
else{

    isPortrait=NO;

    [self LoadKeyboardview];
    [self updateCustomHeight];
 }
  - (NSLayoutConstraint*)findViewHeightConstraint {
NSArray *constraints = self.view.superview.constraints;
for ( NSLayoutConstraint *constraint in constraints ) {
    if ( constraint.firstItem == self.view
        && constraint.firstAttribute == NSLayoutAttributeHeight )
        return constraint;
   }
 //  [self updateCustomHeight];
   return nil;
 }

A: If you use "auto layout" in designing of keyboard in xib then there is no need to add height constraint,it automatically adjust according to default keyboard size.I simply load the view and not add any height constraint and i works fine for me in all devices.
 override func viewDidLoad() {
        super.viewDidLoad()
        let nib = UINib(nibName: "VSPKeyboardViewController", bundle: nil)
        let objects = nib.instantiateWithOwner(self, options: nil)
        view = objects[0] as! UIView

}

override func updateViewConstraints() {
        super.updateViewConstraints()
}

A: You would be better to not keep removing and adding the height constraint. Instead add it the first time and then after that simply change its value and set the view as needing layout and then do the layout.
Also think your might be working out the orientation wrong by using bounds before the transition occurs.
Updated your methods as follows:
- (void)viewWillTransitionToSize:(CGSize)size
       withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
  if (size.width < size.height){
    //Keyboard is in Portrait
    isPortrait=YES;
    [self LoadKeyboardview];
    [self updateCustomHeight];
  }
  else{
    // New orientation is landscape
    isPortrait=NO;
    [self LoadKeyboardview];
    [self updateCustomHeight];
 }
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                               duration:(NSTimeInterval)duration{
  if (toInterfaceOrientation == UIInterfaceOrientationPortrait ||
      toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
    //Keyboard will be Portrait
    isPortrait=YES;
    [self LoadKeyboardview];
    [self updateCustomHeight];
  }
  else{
    //Keyboard will be Landscape
    isPortrait=NO;
     [self LoadKeyboardview];
    [self updateCustomHeight];
  }
}

-(void)updateCustomHeight
{
  if(isPortrait){
    expandedHeight = 258;
  }
  else{
    expandedHeight = 156;
  }

  // If no constraint add one, or if one exists update it only
  // if the height needs to change.
  if (self.heightConstraint == nil) {
    self.heightConstraint =
      [NSLayoutConstraint constraintWithItem:self.view
                                   attribute:NSLayoutAttributeHeight
                                   relatedBy:NSLayoutRelationEqual toItem:nil
                                   attribute:NSLayoutAttributeNotAnAttribute
                                  multiplier:0.0
                                    constant:expandedHeight];
    [self.view addConstraint:self.heightConstraint];
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
  }
  else if (self.heightConstraint.constant != expandedHeight){
    self.heightConstraint.constant = expandedHeight;
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
  }
}


text:
Q: Where should I unregister a broadcast receiver when your class extends Application and not Activity I know that when my class extends Activity, I can register a receiver in onCreate() or onStart() and de-register on onStop() or onDestroy().
But what if my class extends Application - where will I de-register my receiver?
Normally onTerminate() overridden method will never be called for a real device.

A: You shouldn't register broadcast receiver in your Application class. For that purposes you have to declare it via AndroidManifest


text:
Q: Parsed data display in JTable I am new to Java.  I have to display xml Parsed data parent nodes on JTabbedPane and child nodes in jtable into respective JTabbedPane. For parsing i have used sax parser and all the data was previously displayed in three JTextarea, I have created TabbedPane and displayed hardcoded string as title but i am not able to set Jtable into it with values.
public class JTableDisplay {
    public JTableDisplay() {
        JFrame frame = new JFrame("JTable Test Display");

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        JTable table = new JTable();

        JScrollPane tableContainer = new JScrollPane(table);

        panel.add(tableContainer, BorderLayout.CENTER);
        frame.getContentPane().add(panel);

        frame.pack();
        frame.setVisible(true);
    }

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

This is sample to create JTable after which i have to arrange the parsed data into in.

A: It is there. It is just not showing any data.
To make your table visible, try defining columns and rows for your table via the constructor :
 JTable table = new JTable(3,4);

Get it?
Now you just need to define the tablemodel and you are set.


text:
Q: Neatest way to access my data source (Serial port) from an NSTableViewDataSource in Swift (OSX)? I have an NSTableView in my simple app and a separate class SettingsTableSourceDelegate that inherits from NSTableViewDataSource and NSTableViewDelegate to handle populating and processing the table. Essentially the table is going to be populated from values received from a microcontroller, the specifics of aren't important, but what I want to know is a more general question of structure.
What is the best way, other than (if possible) singletons or storing my serial port instance in the app delegate, to access my serial port instance from my SettingsTableSourceDelegate class? Giving consideration to the fact that I don't want to be constantly closing and opening the port, and that the NSTableView isn't the only thing going to be using the port (though not at the same time).
I ideally would want the table to initially pull its values from the microcontroller over serial, then further manipulations done to the table are performed on a copy in memory, and only sent back when a Save button is clicked.
Many thanks for your time, I'm not very hot on design patterns and Swift/OSX programming is very new to me so any advice would be greatly appreciated!

A: You should start a separate thread for the serial port. Assuming you just display the data coming from the controller it's quite save to alter the table data source. If you are going to alter the count you need to be a bit more careful. Adding will just delay but deleting will eventually cause the table view to access already deleted entries.


text:
Q: How to calculate length of each Huffman code? The output for the code looks like this how can I calculate the length of the code lets say here I got Huffman lengths 1,10,11 now how can I calculate the length of each code so that I get {1,2,2}.
I tried to print some things but it was printing just the last one (11).
 Char | Huffman code
----------------------
 'P_0' |           1
 'P_1' |          10
 'P_2' |          11

The code was in this link https://www.section.io/engineering-education/huffman-coding-python/

A: Adding at the bottom of the file :
lengths = tuple(len(huffman_code[id]) for id in range(len(freq)))
print(lengths)

output :
Enter the string to compute Huffman Code: bar
 Char | Huffman code
----------------------
 'b'  |           1
 'a'  |          00
 'r'  |          01
Average length of the code: 1.650000
(1, 2, 2)

I get (1, 2, 2).


text:
Q: Cannot install GNOME extensions Currently having issues installing gnome extensions via their website. Usually there is a SLIDER bar that says ON/OFF , but I am unable to see it.
I am running Firefox 28.0 along with UBUNTU 12.04. I have disabled all addons and still nto able to see anything. I have GNOME 3.4.1 installed and GNOME Tweak Tool as well. I am able to install GNOME extensions from the terminal when i know the exact adress or command line.
Also, when I view the webiste it looks like the plugin list icons are sort of grayed out or transparent. When I compare this to screenshot below, they are much brighter and this makes me wonder if this indicates a problem.
Here is the normal image:

Here is what I see:

I have read How do I install and manage GNOME Shell extensions? with no luck
Thanks for reading.

A: Well, I have to credit Seth for this really, but I was not aware that I had to log out after installing gnome shell, so what I did was this:
.
after that I was able to see the slider on the extensions website.
Thank you Seth!


text:
Q: Bag of words training samples I have implemented Bag Of Words, everything is working smoothly. But, I'm confused about some steps and how to implement it.
I could create the bow descriptors as the last step in Bag of words to create the samples, as it shown here bowDE.compute(img, keypoints, bow_descriptor); .. The things is that i'm confused about the next steps.
I know that in BOW that I have to train and test a class (car) with non-class (cola), what I created in bow_descriptor vector  is only for the class car, so I have vector for samples that belong only to the car. here are the questions that I have for training my system and test it.
1- Shall I make the vector of bow_descriptor half of it for the class(cola) and the rest for non-class(cola) , or I have to create a new bow_descriptor for the non-class(cola) ?
2- I need to do multi-class classification, after finishing the first system for class (car), and I need to train a new class (Buses+trains and so on), shall I create a new training model for each of them, or
it is possible to do the training procedure with the previous training (i.e. training class BUS,train with the class car in the same system)?

A: It does not matter whether you create one object for all classes or one object for each class, as long as you use the same dictionary for all classes.
Creating only one object might be more economical. But the extracted image descriptors should be the same.
Regarding multiclass SVMs:
You used the SVM tag. So I assume you want to use SVM. There do exist ways to do multiclass classifications explicitly with SVMs it is more common to train several binary SVMs and combine them to get a multiclass results.
You can either use the 1-vs-1 setting, where you train one SVM per class pair. For testing you evaluate your test example on each SVM. The class which wins those duels the most often then becomes your final result.
The other popular approach is 1-vs-all SVMs. Here you train one SVM per class where samples from the current class are labeled positive and all other samples negative. During testing the class with the highest score wins.
So if you want to use the 1-vs-1 setting you might be able to reuse some binary SVMs when you add new classes. It is not possible for the 1-vs-All setting, as you need to add the new class to the negative samples for each SVM.


text:
Q: configuration of .htaccess for add_rewrite_rule to make sense I am trying this code from codex wordpress site
function custom_rewrite_basic() {
    add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');

How must by .htaccess file must be configured for above code to make sense? If I put the basic wordpress .htaccess configuration file then I get redirected to same page.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

A: after adding a new rule, you have to flush the rewrite-rules in order to use them
that can be done with the "flush_rewrite_rules" function
http://codex.wordpress.org/Function_Reference/flush_rewrite_rules
or it can be done in going in the Administration Screens -> Settings -> Permalink and just saving without changing something on this screen


text:
Q: How to mock a Python class to change just one argument I need to wrap a class in a mock like so:
Original code:
class _InnerImpl(object):

  def __init__(self, arg1, arg2, arg3):
    # do stuff

I would like to do something like this:
from unittest.mock import patch

def my_wrapper(*args, **kwargs):
  kwargs['arg1'] = gen_next_value()  # change one of the arguments
  return _InnerImpl(*args, **kwargs)  # call the real thing with modified args

def run(user_input):
  with patch(_InnerImpl, my_wrapper):
     some_method(user_input)

Unfortunately the way that patch works, I can't call the "real thing" because it is also called inside the with patch block. This results in infinite recursion loop.
I'm using this in an implementation outside of unit test. So this isn't for unit tests. I've tried various things such as saving __init__ reference, using wraps. Nothing works.

A: I suggest not using mocks for things that aren't unit tests. If I understand your example, it seems like what you need is a Factory method pattern https://en.wikipedia.org/wiki/Factory_method_pattern
If you can't modify the code you are patching, try using a different namespace. e.g., given target code a.py
class A(object):
    def __init__(self, v):
        print('A({})'.format(v))

def foo():
    y = A('a')

you could write b.py
from unittest.mock import patch
from a import A,foo
def my_wrapper(*args, **kwargs):
    return A('b')
def bar():
    with patch('a.A', my_wrapper):
        foo()


text:
Q: compareTo method explain 1, -1, 0 Can anyone explain how the 1, -1, and 0 are used in compareTo and other methods in java? I know how the methods work to a degree, but the three numbers confuse me.

A: By JavaDoc return from the method compareTo(obj) is:

a negative integer, zero, or a positive integer as this object is less
  than, equal to, or greater than the specified object.

This mean that if you invoke method on current object this.compareTo(obj) and by your own logic in method compareTo this object grater than obj that you passed to method, return would be a positive integer.
Your own logic mean that, for example in object that you compare to other, exist some integer field and if this field greater than other field in other object, by your logic, you consider that this object greater than other.


text:
Q: GSON serialize a list of polymorphic Composite classes I have a set of classes with following structure
public abstract class Rule { .... }
public class RuleType1 extends Rule { ... }
public class RuleType2 extends Rule { ... }
public class RuleType3 extends Rule { ... }
public class RuleType4 extends Rule { ... }

public class RuleSet extends Rule {
     ...
     private final Collection<Rule> rules;
}

I want to parse following json, which contains multiple nested Rule child classes. Since RuleSet contains Collection of Rule, it can have multiple RuleSet as well.
I have checked these answers already. I don't want to implement custom (de)serializer because that will make child classes less flexible. (Whoever will change classes will need to change serializer classes as well)
Deserializing an abstract class in Gson
Gson serialize a list of polymorphic objects
Here is the same json, I want to serialize/deserialize.
{
    "ruleType": "ruleSet",
    "rules": [
        {
            "ruleType": "ruleSet",
            "rules": [
                {
                    "ruleType": "RuleType1"
                },
                {
                    "ruleType": "ruleSet",
                    "rules": [
                        {
                            "ruleType": "RuleType2"
                        },
                        {
                            "ruleType": "RuleType3"
                        }
                    ]
                }
            ]
        },
        {
            "ruleType": "ruleSet",
            "rules": [
                {
                    "ruleType": "RuleType1"
                },
                {
                    "ruleType": "ruleSet",
                    "rules": [
                        {
                            "ruleType": "RuleType3"
                        },
                        {
                            "ruleType": "RuleType4"
                        }
                    ]
                }
            ]
        }
    ]
}

Edit after comments:

This is my class structure where RuleSet has Collection<IRule> rules
And this is my class
public class SampleClass {
    public IRule parameters;
    public double defaultConfidence;
    public String ruleType;
}

    static RuntimeTypeAdapterFactory<IRule> adaptor = RuntimeTypeAdapterFactory.of(IRule.class)
            .registerSubtype(RuleSet.class)
            .registerSubtype(Rule.class);

    static RuntimeTypeAdapterFactory<Rule> ruleAdaptor = RuntimeTypeAdapterFactory.of(Rule.class)
            .registerSubtype(DocumentTypesRule.class)
            .registerSubtype(DataAttributesRule.class)
            .registerSubtype(DictionariesRule.class)
            .registerSubtype(FileFormatsRule.class)
            .registerSubtype(FileLengthRule.class)
            .registerSubtype(FileNamePatternsRule.class)
            .registerSubtype(FixedRule.class)
            .registerSubtype(ImageTypesRule.class)
            .registerSubtype(KeywordsRule.class)
            .registerSubtype(RegexesRule.class)
            .registerSubtype(SimilaritiesRule.class)
            .registerSubtype(TopicsRule.class);

    private static final Gson GSON = new GsonBuilder()
            .registerTypeAdapterFactory(adaptor)
            .registerTypeAdapterFactory(ruleAdaptor)
            .create();

and facing following error while calling GSON.fromJson(response, SampleClass.class)
java.lang.RuntimeException: Unable to invoke no-args constructor for interface <classPath>.IRule. Registering an InstanceCreator with Gson for this type may fix this problem.


text:
Q: What is the advantage of setting a character column as VARCHAR(32) over VARCHAR(255) What is the advantage of setting a database column VARCHAR(32) over VARCHAR(255) even though the two of them consume 2-byte memory?

A: You are probably defaulted to CHARACTER SET utf8 (or utf8mb4), in which case (255) would need 2 bytes for the length.
But the real problem is with temp tables (pre-8.0):  If the SELECT is so complex that it needs to generate a temp table (eg, for sorting), it will try first to use a MEMORY table.  In doing so, it will turn VARCHARs into CHARs, thereby taking 765 bytes (if utf8).  If, in doing so, this (and other actions) take too much space, it will switch to the slower MyISAM for the temp table.  See the status value Created_tmp_disk_tables.
For SSN, country_code, zip, etc, explicitly say CHARACTER SET ascii (or latin1).  This will avoid extra bloat for the charset.
For fixed-length columns, use CHAR, not VARCHAR.  So, if this is a US SSN, shouldn't it be
SSN CHAR(11) CHARACTER SET ascii  COMMENT 'example: "123-45-6789"'

In spite of all that, the performance difference will be minor.
More important in the serious legal implications (in the US) if your computer is hacked into, and you lose sensitive info such as SSNs.  The cost of such a breach could bankrupt your fledgling business.  And no, simply encryption won't suffice -- think about how easy the hacker can find the encryption key.


text:
Q: Как привязать к одной кнопке сразу несколько форм? Всем привет, есть 4 формы на странице и одна кнопка, как привязать формы к этой кнопке?
Нашел атрибут form, прописал всем формам одинаковый id, но при клике на кнопку проверяется только самая верхняя форма.
В чем может быть проблема?


text:
Q: Why is worst case of is_permutation O(n^2)? The C++ docs say that the worst case time complexity for is_permutation is O(N^2):

At most O(N^2) applications of the predicate, or exactly N if the sequences are already equal, where N=std::distance(first1, last1).  However if ForwardIt1 and ForwardIt2 meet the requirements of LegacyRandomAccessIterator and std::distance(first1, last1) != std::distance(first2, last2) no applications of the predicate are made.

However, IMO it should be O(NlogN) in the worst case - can we not just sort both the sequences in O(NlogN) and then just compare them?  What am I missing?

A: is_permutation doesn't require the ranges to be sortable. It only uses the bool-valued comparison predicate.
Furthermore, the ranges are immutable, so even if they could be sorted, the sorting would imply creation of an index on one of the ranges. That would add O(N) memory cost to the O(NlogN) cost of index generation.


text:
Q: MariaDB Query slower after mysqldump I have a MariaDB server with several databases.
On my MariaDB server, some queries (with joins between tables of different databases) are slower after the daily mysqdump (one file sql by database).
After the daily mysqldump, the first run for one query will be 1.5 minutes  and the second run 3.2 secondes (this time is coherent with current run on the day).
I understand the second run is faster but why the first run after the daily mysqldump is slower ? And how improve it ?
An extrait of my server.cnf :

key_buffer_size = 384M
max_allowed_packet = 16M
table_open_cache = 2000
sort_buffer_size = 8M
join_buffer_size = 8M
read_buffer_size = 8M
read_rnd_buffer_size = 16M
myisam_sort_buffer_size = 64M
query_cache_limit= 128M
query_cache_size= 256M
query_cache_strip_comments=1
thread_concurrency = 8
tmp_table_size = 32M
max_heap_table_size = 32M
innodb_buffer_pool_size = 3G
innodb_buffer_pool_instances = 3
innodb_log_file_size = 448M
innodb_log_buffer_size = 64M
innodb_flush_log_at_trx_commit = 1
innodb_print_all_deadlocks = 1
innodb_lock_wait_timeout = 210

Thanks for you help.

A: First query could be slow as the innodb buffer has been filled up with the queries required for the mysqldump and all the data needs to be fetched from disk.
You could run SET GLOBAL innodb_buffer_pool_dump_now=1 before the dump and SET GLOBAL innodb_buffer_pool_load_now=1 after the dump to ensure the buffer pool is what it was prior.


text:
Q: Numbers in a Matrix I tried to solve the following problem with Python:

But I got stuck at generating a single valid table. I was expecting the program to display a valid matrix, but in order for the program to continue and not print None, I had to assign a 7 for a square that has no possibles. What should be fixed?
My code so far:
from pprint import pprint
import sys
import random

sys.setrecursionlimit(10000)

def getPossiblesForSquare(sqx,sqy,matrix):
    '''Gets the possible entries of matrix[sqy][sqx].
Assumes it equals 0.'''
    assert matrix[sqy][sqx]==0
    # get the row that it is on
    rowon=matrix[sqy]
    # columns are a little trickier
    colon=[matrix[row][sqx] for row in range(5)]

    # find the possibilities!
    possibles=list(range(1,7))

    for item in list(set(rowon+colon)): # remove duplicates
        if not (item == 0) and (item in possibles):
            del possibles[possibles.index(item)]

    random.shuffle(possibles)

    return possibles

def getPossiblesForMatrix(matrix):
    '''Gets all the possible squares for a matrix.'''
    possiblesdict={}
    for y in range(6):
        for x in range(6):
            if matrix[y][x]==0:
                possiblesdict[(y,x)]=getPossiblesForSquare(x,y,MATRIX)
    return possiblesdict

def flattenList(matrix):
    result=[]
    for i in matrix:
        if not isinstance(i,list):
            result+=[i]
        else:
            result+=flattenList(i)
    return result

def getPossibleMatrix(startMatrix, iteration=0, yon=1, prevZeroInd=None):
    if 0 not in flattenList(startMatrix):
        print('RESULT:\n\n')
        return startMatrix
    else:
        # find&fill in the first blank one
        ind=flattenList(startMatrix).index(0)
        y=ind//6
        x=ind%6
        if (x,y)==prevZeroInd:
            startMatrix[y][x]=7
        else:
            possibles=getPossiblesForSquare(x,y,startMatrix)
            if len(possibles)==0:
                startMatrix[y][x]=7
            else:
                startMatrix[y][x]=possibles[0]
            if iteration <= 6:
                return getPossibleMatrix(startMatrix, iteration+1, yon, (x,y)) # <<BUG
            else:
                if yon!=4:
                    return getPossibleMatrix(startMatrix, 0, yon+1, (x,y))

MATRIX=[[1,2,3,4,5,6],
        [2,0,0,0,0,5],
        [3,0,0,0,0,4],
        [4,0,0,0,0,3],
        [5,0,0,0,0,2],
        [6,5,4,3,2,1]]

result=getPossibleMatrix(MATRIX)
pprint(result)

A: Why your script hangs:

Essentially your script encounters problems here:
for item in list(set(rowon + colon)):  # remove duplicates
    if not (item == 0) and (item in possibles):
        del possibles[possibles.index(item)]

*

*At the third iteration, for the third cell your if condition is evaluated as true for all possible values [1 to 6] (if you output the matrix you will see that the set() you are creating contains all elements), so you always return zero, re-check the values, return zero ad infinitum.

If you're looking to brute-force a solution out of this, you might want to update the sqx and sqy to go to a different cell when possibles is empty.
Another additional small mistake I located was:
# you are checking values 1-5 and not 1-6!
possibles = list(range(1, 6)) # should be range(7) [exclusive range]

*

*Don't forget that range is exclusive, it doesn't include (excludes) the upper limit.

There exist of course, different ways to tackle this problem.

A possible -alternate- solution:

 Read this for the general, alternate view of how to solve this. If you do not want to see a possible solution, skip the 'code' part.

The solution matrix (one of the possible ones) has this form (unless I am making a horrible mistake):
MATRIX = [[1, 2, 3, 4, 5, 6],
          [2, 3, 6, 1, 4, 5],
          [3, 1, 5, 2, 6, 4],
          [4, 6, 2, 5, 1, 3],
          [5, 4, 1, 6, 3, 2],
          [6, 5, 4, 3, 2, 1]]

The Logic is as follows:
You must observe the symmetry present in the matrix. Specifically, every row and every column displays a 'flip and reverse' symmetry. For example, the first and last rows are connected by this equation :
row[0] = REV(flip(row[n]))

Similarly, all additional rows (or columns) have their corresponding counterpart:
row[1] = REV(flip(row[n-1]))

and so on.
So, for n=6 this essentially boils down to finding the (n / 2) -1 (because we already know the first and last row!) and afterwards flipping them (not the finger), reversing them and assigning them to their corresponding rows.
In order to find these values we can observe the matrix as a combination of smaller matrices:
These make the first two (unknown) rows of the matrix:
sub_matrix = [[1, 2, 3, 4, 5, 6],
              [2, 0, 0, 0, 0, 5],
              [3, 0, 0, 0, 0, 4],
              [6, 5, 4, 3, 2, 1]]

and the other two rows can be made by finding the correct values for these two.
Observe the restrictions in hand:
In column [1][1] and [1][m-1] we cannot:

*

*place a 2 or a 5
In columns [1][2] and [1][m-2] we cannot:

*

*place the previous values ([2, 5]) along with ([3, 4]) so, we cannot have a value in [2,3,4,5]
For the inner columns we're left with the set set(1-6) - set(2-5) = [1, 6]
and since we get a normal row and a single inverted and flipped row for this, we can arbitrarily select a value and add it as a column value.
By using another list we can keep track of the values used and fill out the rest of the cells.

Coding this: (Spoilers)

Note: I did not use numpy for this. You can and should though. (Also, Python 2.7)
Also, I did not use recursion for this (you can try to, by finding the same matrix for bigger values of n [I believe it's a good fit for a recursive function].
First, in order to not type this all the time, you can create a n x n matrix as follows: (This isn't much of a spoiler.)
# our matrix must be n x n with n even.
n = 6

# Create n x n matrix.
head = [i for i in xrange(1, n + 1)]   # contains values from 1 to n.
zeros = [0 for i in xrange(1, n-1)]    # zeros
tail = [i for i in xrange(n, 0, -1)]   # contains values from n to 1.

# Add head and zeros until tail.
MATRIX = [([j] + zeros + [(n+1)-j]) if j != 1 else head for j in xrange(1, n)]
# Add tail
MATRIX.append(tail)

Then, create the smaller (n/2 + 1) x n array:
# Split matrix and add last row.
sub_matrix = MATRIX[:(n / 2)] + [tail]

Afterwards, a small function called sub = fill_rows(sub_matrix) comes in and takes care of business:
def fill_rows(mtrx):

    # length of the sub array (= 4)
    sub_n = len(mtrx)

    # From 1 because 0 = head
    # Until sub_n -1 because the sub_n - 1 is = tail (remember, range is exclusive)
    for current_row in xrange(1, sub_n - 1):
        print "Current row: " + str(current_row)

        # -- it gets messy here --
        # get values of inner columns and filter out the zeros (matrix[row][n / 2] == 0 evaluates to False)
        col_vals_1 = [mtrx[row][n / 2] for row in xrange(0, sub_n) if mtrx[row][(n / 2)]]
        col_vals_2 = [mtrx[row][(n / 2) - 1] for row in xrange(0, sub_n) if mtrx[row][(n / 2) - 1]]

        col_vals = col_vals_1 + col_vals_2
        # print "Column Values = " + str(col_vals)

        row_vals = [mtrx[current_row][col] for col in xrange(0, n) if mtrx[current_row][col]]
        # print "Row Values = " + str(row_vals)

        # Find the possible values by getting the difference of the joined set of column + row values
        # with the range from (1 - 6).
        possible_values = list(set(xrange(1, n + 1)) - set(row_vals + col_vals))

        print "Possible acceptable values: " + str(possible_values)

        # Add values to matrix (pop to remove them)
        # After removing add to the list of row_values in order to check for the other columns.
        mtrx[current_row][(n-1)/2] = possible_values.pop()
        row_vals.append(mtrx[current_row][(n - 1) / 2])
        mtrx[current_row][(n-1)/2 + 1] = possible_values.pop()
        row_vals.append(mtrx[current_row][(n-1) / 2 + 1])

        # New possible values for remaining columns of the current row.
        possible_values = list(set(xrange(1, n + 1)) - set(row_vals))
        print "Possible acceptable values: " + str(possible_values)

        # Add values to the cells.
        mtrx[current_row][(n - 2)] = possible_values.pop()
        mtrx[current_row][1] = possible_values.pop()

    # return updated sub-matrix.
    return mtrx

The only thing left to do now is take those two rows, flip them, reverse them and add the head and tail to them:
print '=' * 30 + " Out " + "=" * 30

# Remove first and last rows.
del sub[0]
sub.pop()

# reverse values in lists
temp_sub = [l[::-1] for l in sub]
# reverse lists in matrix.
temp_sub.reverse()

# Add them and Print.
pprint([head] + sub + temp_sub + [tail])

This outputs what, I hope, is the right matrix:
============================== Out ==============================

[[1, 2, 3, 4, 5, 6],
 [2, 3, 6, 1, 4, 5],
 [3, 1, 5, 2, 6, 4],
 [4, 6, 2, 5, 1, 3],
 [5, 4, 1, 6, 3, 2],
 [6, 5, 4, 3, 2, 1]]

Additionally

By using this way of solving it the answer to the problem in hand becomes more easy. Viewing the matrix as a combination of these sub-matrices you can tell how many of these combinations might be possible.
As a closing note, it would be a good work-out to modify it a bit in order to allow it to find this array for an arbitrary (but even) number of n.

A: You have infinite recursion.  Your first three iterations are fine: your second row adds one possibility at a time, turning from 200005 into 214305.  At this point, you find that there are no possible choices.  You overwrite the existing 0 with a new 0, and then fail to backtrack.  Each of these is an error: 6 is a possible value, and you have no recovery code.
Here is the alteration I made to track the problem; additions are in double-star containers.  When you have a sick program, learn how to ask where it hurts.  The print function is an excellent instrument.
def getPossibleMatrix(startMatrix, **iter=0**):
    if 0 not in flattenList(startMatrix):
        return startMatrix
    else:
        # find&fill in the first blank one
        ind=flattenList(startMatrix).index(0)
        y=ind//6
        x=ind%6
        possibles=getPossiblesForSquare(x,y,startMatrix)
        if len(possibles)==0:
            startMatrix[y][x]=0
            **print ("No possibles; current location remains 0")**
        else:
            startMatrix[y][x]=possibles[0]
            ****print ("Added first possible")
        print (startMatrix)
        if iter <= 6:**
            return getPossibleMatrix(startMatrix, **iter+1**) # <<BUG


text:
Q: horizontally center element without fractional offset? margin: 0 auto will horizontally center an element. However, depending on the parent and child size, sometimes getBoundingClientRect returns a fractional left value (as does jQuery offset).  These fractions cause problems elsewhere in javascript code, so I would like to remove them (instead of compensate for them).
Is there a way to use css to horizontally center with an integer offset?  Or should I just use javascript?

There are lots of horizontal alignment questions, but none which seem to address this issue of subpixel perplexities.

var br = document.getElementById("kid").getBoundingClientRect();

document.getElementById("info").innerHTML = "left: " + br.left;
body {
  margin: 0;
}
#pop {
  position: absolute;
  width: 401px;
  height: 100%;
  background-color: pink;
}
#kid {
  width: 100px;
  height: 100px;
  background-color: orange;
  margin: 0 auto;
}

d

A: You can redefine Element.prototype.getBoundingClientRect so it returns rounded numbers.
This will also affect jQuery methods that rely on it, such as offset(), width(), and height():
Element.prototype.getBoundingClientRect= function() {
  var parent= this.parentNode instanceof HTMLElement ? this.parentNode : null,
      left  = Math.round(this.offsetLeft + (parent && parent.getBoundingClientRect().left)),
      top   = Math.round(this.offsetTop  + (parent && parent.getBoundingClientRect().top)),
      width = Math.round(this.offsetWidth),
      height= Math.round(this.offsetHeight);

  return {
    left:    left,
    top:     top,
    right:   left+width,
    bottom:  top+height,
    width:   width,
    height:  height
  }
} //getBoundingClientRect

In this Fiddle, you'll see the element's fractional dimensions using JavaScript and jQuery.  getBoundingClientRect is then redefined.
Click the button, and you'll see rounded dimensions based on the updated method.

A: Yes, you absolutely can use integers! However, you'll have location issues unless you use a system that is measured in integers as it's smallest unit of measurement.  Are there such units? Yes! They are called pixels, and are square units that can be represented with positive whole numbers (i.e. integers).  Simply make sure that you're referencing pixels in your CSS and NOT percentages or number of column spans and you'll have exactly what you're after...


text:
Q: Access - 2013, correct data format for variable uk phone numbers I am new to this, I have a number of data files that contain UK phone numbers with various issues, such as 0044, +44, missing the leading zero, etc.
Is there a way to remove if it is any of the cases above and replace it with only a zero
Many thanks
Remon

A: You can use the Replace function
UPDATE tbl
SET PhoneNo= REPLACE(PhoneNo, '+44', '0')
WHERE PhoneNo like '+44%'

This will only affect the records with +44. Similarly, you can use it for 0044

A: Use the Switch function.
Example, assuming your table is called tblUKTelNrs (adjust according to your specific requirements):
UPDATE tblUKTelNrs
SET telNr = Switch(telNr LIKE "0044*","044" & Mid(telNr,5),
telNr LIKE "+44*","044" & Mid(TelNr,4), telNr LIKE "44*","044" & Mid(TelNr,3))
WHERE telNr NOT LIKE "044*"


text:
Q: How to change SSIS variable values in C# I'm trying to set variables in code on an SSIS package I'm kicking off from C#.
Package pkg = app.LoadPackage(ConfigurationManager.AppSettings["SsisPkg"].ToString(), null);
pkg.Variables["User::FolderPath"].Value = Path.GetDirectoryName(e.FullPath);
pkg.Variables["User::FileName"].Value = Path.GetFileNameWithoutExtension(e.FullPath);

While debugging, I inspect the values directly after setting them, but nothing has changed.  I can drill into the value (hover, navigate to it, edit value) so it doesn't seem to be that they aren't editable.
Any ideas what I'm doing wrong here?
Update:  Thanks to billinkc, I'm comfortable what I'm doing should work so long as possibly other conditions are met.  I've found that direct assignments in code fail (no error, just don't "take") and I cannot edit the values in the watch window.  I can edit values when I'm inspecting them.
Could the actual issue be that there's a setting flagging these as read-only?
Answer Found:  Needed to make the variables writable before setting the value:
        pkg.Variables["User::FileName"].EvaluateAsExpression = false;

A: You're doing it right. I created a basic SSIS package. Has one Variable, FolderPath, type string. There is a single script task that fires an Information event and the contents of that expose the value of the FolderPath variable

I then created a basic C# console app like this
public class InformationListener : DefaultEvents
{
    public override void OnInformation(DtsObject source, int informationCode, string subComponent, string description, string helpFile, int helpContext, string idofInterfaceWithError, ref bool fireAgain)
    {
        //base.OnInformation(source, informationCode, subComponent, description, helpFile, helpContext, idofInterfaceWithError, ref fireAgain);
        Console.WriteLine(string.Format("{0} {1}", subComponent, description));
    }

}

class Program
{
    static void Main(string[] args)
    {
        string sourcePackage = string.Empty;
        string path = string.Empty;
        string variableName = string.Empty;
        string designValue = string.Empty;
        string newValue = string.Empty;
        InformationListener listener = null;

        sourcePackage = @"J:\Src\SO\SSIS\Package.dtsx";
        path = @"J:\runtime";
        variableName = "User::FolderPath";
        listener = new InformationListener();

        Application app = new Application();
        Package pkg = null;
        Variable ssisVariable = null;
        pkg = app.LoadPackage(sourcePackage, null);

        ssisVariable = pkg.Variables[variableName];
        designValue = ssisVariable.Value.ToString();

        Console.WriteLine(string.Format("Designtime value = {0}", designValue));

        ssisVariable.Value = path;

        newValue = ssisVariable.Value.ToString();
        Console.WriteLine(string.Format("new value = {0}", newValue));

        DTSExecResult results = DTSExecResult.Canceled;

        results = pkg.Execute(null, null, listener, null, null);

        Console.WriteLine("Press any key to continue");
        Console.ReadKey();

    }
}

As you can tell from the variable inspection

and from my print statements

the design-time value of C:\designTime goes to J: because I forgot to escape my string above but we can pretend it shows J:\runtime.
All this said, unless we serialize the package with a call to the SaveToXml method, the value of User::FolderPath resets to the design time value once the object goes out of scope. Permanently updating would look like
app.SaveToXml(sourcePackage, pkg, null);

OP EDIT this discussion and examples led me to the answer:
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/dad8e218-1fe0-49db-89da-5715fb6d4b21/sql-2008-r2-ssis-c-script-task-not-setting-variable


text:
Q: I want to check yyyy-mm-dd hh:mm (regular expression) I Want to form check text like : YYYY-MM-DD hh:mm (Date time)
And I found this ↓
                    "regex": /^((((19|[2-9]\d)\d{2})[\/\.-](0[13578]|1[02])[\/\.-](0[1-9]|[12]\d|3[01])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))|(((19|[2-9]\d)\d{2})[\/\.-](0[13456789]|1[012])[\/\.-](0[1-9]|[12]\d|30)\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))|(((19|[2-9]\d)\d{2})[\/\.-](02)[\/\.-](0[1-9]|1\d|2[0-8])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))[\/\.-](02)[\/\.-](29)\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])))$/,

It worked.
but this id checked : YYYY-MM-DD hh:mm:ss
And cut :ss part (I think)
"regex": /^((((19|[2-9]\d)\d{2})[\/\.-](0[13578]|1[02])[\/\.-](0[1-9]|[12]\d|3[01])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))|(((19|[2-9]\d)\d{2})[\/\.-](0[13456789]|1[012])[\/\.-](0[1-9]|[12]\d|30)\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))|(((19|[2-9]\d)\d{2})[\/\.-](02)[\/\.-](0[1-9]|1\d|2[0-8])\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))[\/\.-](02)[\/\.-](29)\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])))$/,

It doesn't worked.
how can i fix this?

A: If you want to check if a string is a valid time, a better approach is to use Date.parse().
Like so:
alert(Date.parse("2001-12-20 20:39"));  // returns 1008841140000
alert(Date.parse("2001-12-50 20:39"));  // returns NaN (sometimes?)

If you want to make extra certain the date matches that format, you can output it and check it against the original, like so:
Date.parse(y).strftime("%Y-%m-%d %H:%M") == y

A: If you have to use a regular expression, this should work:

/^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}/

It has no limit on range, so someone could put 14 as the month. It only checks that the format you want is exactly followed with any numbers.


text:
Q: Armadillo C++ Auto Type Bad Alloc Can someone explain why in Debug mode is working okay, but in release i see bad_allocation ?
#include <iostream>
#define ARMA_DONT_USE_WRAPPER
#include <armadillo>

int main()
{
    arma::cx_mat testMat;
    testMat.set_size(40, 19586);
    auto nPositions = static_cast<arma::sword>(floor(19586/2));
    arma::cx_rowvec a {19586, arma::fill::randu};
    for ( int i = 0 ; i < 40; ++i)
    {
            // testMat.row(i) = arma::shift(arma::fft(a), nPositions); // very slow
            auto result = (arma::shift(arma::fft(a), nPositions));
            result.print("result");
    }
    std::cout << " i am done \n";
}

( with arma::cx_rowvec is wokring okay, but bad perfomane )
gcc 11.2
armadillo armadillo-10.8.2

Thank you in advance.