text:
Q: how to make an Bootup Application I want to Make an device policy manager application
in which when i start the application it will have two button one for Guest user and one for Admin User and I will set the password for Admin as Well as Guest login, and after adding both the password when i boot up my device it should show me my main page asking for Admin Login and Guest Loging and when I click on Guest it will as for Guest Password and when I will click on Admin it will as for Admin Password and Unless i Provide any of the password my Device should not go to the home screen and once i have provided the right password it should go to the home screen as in my application i want to bind the use of some application from guest login and from admin login this should be enable.
as in my case i am not able to do so when ever i do so it does only goes to the activity after providing the pass word and once i press the home button it goes to home button

A: root the device and get super user permissions and you can create two users in adb shell command.
sice the os is based on linux its possible but difficult. May be you need to work with the kernel.

A: 1) First you should root the device using the suitable method. For example razorclaw.apk( or which ever suitable for your device).
2) Get the logic to hide status bar. Ex.
process = Runtime.getRuntime().exec(new String[]{"su","-c","service call activity 79 s16 com.android.systemui"});
process.waitFor();

3) Write a BroadcastReceiver
public class MyBootRecever extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    intent.setClass(context, UserLogin.class);
        context.startActivity(intent);
    }
}

4) Configure the BroadcastReceiver in AndroidManifest.xml
<receiver android:name="MyBootRecever">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>


text:
Q: Javascript - Issue with capturing value from API I'm learning web development and I'm trying to learn the basics. I have made my own project to find the current ETH price.
My JS code is below:
https://pastebin.com/6ecrTZCu

const button1 = document.querySelector('#eth');
const list = document.querySelector('#price');

const addPrice = async() => {
  const pricee = await checkPrice();
  console.log(pricee)
  const newLI = document.createElement('LI');
  newLI.append(pricee);
  list.append(newLI)
}

const checkPrice = async() => {
  axios.get('https://api.cryptonator.com/api/ticker/eth-aud')
    .then(res => {
      console.log(res.data.ticker.price)
      return res.data.ticker.price

    })
    .catch(err => {
      console.log('Sorry, error!')
      return 'Sorry, error!'
    })
}

button1.addEventListener('click', addPrice)

<button id="eth">Get ETH Price</button>

Can anyone explain why it is not capturing 'res.data.ticker.price' in line 6? This is really frustrating me!
Thanks for any assistance

A: The reason undefined is shown is because the checkPrice function returns immediately.
For this to function, checkPrice must return a Promise which can be awaited by the const pricee = await checkPrice(). Otherwise it returns immediately a undefined value.
Please check the corrected code.

const button1 = document.querySelector('#eth');
const list = document.querySelector('#price');

const addPrice = async() => {
  const pricee = await checkPrice();
  console.log(pricee)
  const newLI = document.createElement('LI');
  newLI.append(pricee);
  list.append(newLI)
}

const checkPrice = async() => {
  return await axios.get('https://api.cryptonator.com/api/ticker/eth-aud')
    .then(res => {
      console.log(res.data.ticker.price)
      return Promise.resolve(res.data.ticker.price);

    })
    .catch(err => {
      console.log('Sorry, error!')
      return 'Sorry, error!'
    })
}

button1.addEventListener('click', addPrice)

<button id="eth">Get ETH Price</button>

A: You need to return a promise from the checkPrice() method. Currently, You are returning nothing(void).
const checkPrice = async() => {
  return axios.get('https://api.cryptonator.com/api/ticker/eth-aud')
    .then(res => {
      console.log(res.data.ticker.price)
      return res.data.ticker.price

    })
    .catch(err => {
      console.log('Sorry, error!')
      return 'Sorry, error!'
    })
}

A: The problem in the first console.log is that console.log is not async function for this reason this execute before the async function. I resolve your problem only asyn await

const button1 = document.querySelector('#eth');
const list = document.querySelector('#price');

const addPrice = async() => {
  const pricee = await checkPrice();
  const newLI = document.createElement('LI');
  newLI.append(pricee);
  list.append(newLI)
}

const checkPrice = async() => {
  const result = await axios.get('https://api.cryptonator.com/api/ticker/eth-aud')
  return result.data.ticker.price
}

button1.addEventListener('click', addPrice)

<button id="eth">Get ETH Price</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to get rid of my timeout countdown thread upon completing my sequence of inputs? (Python) I am working on  a program where:
-we have a object detection loop
-it will be idle awaiting a user's input. Upon the first input, it will start a sequence of actions that need to be completed. If the user leaves and hasn't finished with the full sequence, I need to find a way to reset the sequence so that a new user can begin their own.
My current "solution" was to use a thread to start a timeout countdown by pointing the thread to the following function:
def timeout():
    count = 0
    t = 61
    while count <= 60:
        time.sleep(1)
        count += 1
        t -= 1
        to_queue.put(t)

This function will start counting down 60 seconds, and putting the values through my queue to_queue.
After implementing this i realized it's not an optimal solution, due to the fact that if my user(A) finishes their sequence and another one(B) starts right away, the previous 60 seconds will still be counting and end the sequence too early for the second user(B), thus creating a possibly endless loop of unfinished sequences.
My criteria for "restarting" the sequence is in two locations: once it has been completed reset all the values, and the other is if timeout == 0: reset sequence
I have been looking through the documentation for Queue and Multithreading but I can't seem to find the right solution. I know that threads cannot be "killed" but I have run out of options from examples on how to "kill threads" online.
I also saw that theres Timer() under the threading library but I'm not sure how to implement it as it requires a function as its argument, but my hypothetical restartSequence() function would require resetting values located inside my Sequence() function.  I am stuck here and feel like I'm missing something pretty obvious. any help is appreciated.
Thanks

A: You can use a while loop, that while a new user input comes the function will keep counting. The moment a new user input comes, the function will stop.

A: I found a way to fix my issue; I'm not sure how efficient this is but here goes:
I used an Event() object as a flag to run the "restart sequence" code:
from threading import Event
restartFlag = Event()

if restartFlag.set():
    restartSequence()

As for the countdown timer I gave up on using Queue(), and switched to using Timer(), which will execute a function when the set time runs out. timeFlag will run when the time reaches 0, restarting my sequence just like the queue used to. I realized that it was still running on the same timer upon starting a new sequence, so I created newTimer() to help me create a new Timer every time the sequence is started. It might not be the best option since I'm basically creating multiple threads for this, but they are supposed to die when finished, so there shouldn't be any problem AFAIK.
#Set resetFlag event in order to start Reset Sequence code
    def timeFlag():
        print("Reset Flag Set.")
        resetFlag.set()

    #Create new Timer() Object to avoid using the same every time
    def newTimer():
        print("Created new Reset Timer.")
        global resetTimer
        resetTimer = Timer(60.0, timeFlag)
    newTimer()

so then I do  resetTimer.start() when the sequence begins, and promptly use resetTimer.cancel() and newTimer() when the sequence is supposed to end.
Now we have a fully working sequence of steps


text:
Q: Is there anything in ~/.cache that is not really cache? My machine has lots of memory, so I moved ~/.cache/google-chrome into /tmp, which is a tmpfs RAM disk.
This makes the browser run faster and reduces SSD usage.
When I reboot, it all goes away, but it gets recreated again.
All is fine.
In theory, I could move all of ~/.cache there too.
But in practice, how likely is it that some packages (ab)use ~/.cache for something other than temporary reproducible data?
Update (2 days later):
I decided to try it out and did this:
$ mv ~/.cache ~/.cache.old
$ ln  -s  /tmp/home/ray/.cache  ~/.

and then added this to my ~/.profile:
mkdir  -p  /tmp/home/ray/.cache

and so far everything is working okay across reboots.  Removing .cache.old will free up about 2G of mostly ancient files.
If I ever do run into any packages that misuse .cache, I can teach .profile to add a symlink back to a real directory for that specific case.
Update (3 years later):
I've been running this for over 3 years now with no obvious problems.


text:
Q: What is the best way to avoid "system out of memory" in node.js? I am working on a project which need's to handle many ten's of thousands of active socket concurrent connections. Now been looking at the memory usage and the V8 engine, I am using Node.js v0.10.19 (Stable)
I can't afford for "system out of memory" event to happen. So currently working on running up to 15 node instances each limited to 1GB of RAM on a single server with plenty of RAM to operate with that & with quad core xeon processors and a load balancer to organise the load across all the instances.
So, is there a way to store socket connections outside the V8 Heap stack like in buffers or some other way so to reduce the Node.js memory usage?

A: Naturally since you're keeping many thousands or tens of thousands of connections open you will be incurring a memory cost by doing so.
Here's what I would ask:
Are you adding things to an array or an object that is filling up?
Are you instantiating heavy modules for each open connection?
Can you run a profiler to see what is doing what? (People do rave about that DTrace.)
Would it be possible to poll at an interval for what you want instead of keeping web sockets open?
Something else you can try if you can't run a profiler is logging the status of the app as it runs so you can analyze the problem. It's an oldschool technique but you can log each time a function is ending and see what the current memory usage is. That might also chew up some memory but if you find the problem that way, great.
Checking the memory usage is done via the Process module:
http://nodejs.org/api/process.html#process_process_memoryusage
Good luck and please let me know what you find out. I'm curious to see how you solve that very challenging problem.


text:
Q: MediaPlayer.seekTo() does not work for unbuffered position I use MediaPlayer for playing a single mp3 song from network. Data source is a HTTP URL.
Let's assume we have following playing state.
Song duration: 1:00
Current progress: 0:10
Current buffering progress 0:30
Let's say I want to skip some part of a song and seek forward. I do it with MediaPlayer.seekTo() method. If I seek to buffered position (0:20) it is performed correctly. But if I seek to a position which has not been buffered yet (0:40) the MediaPlayer behaves odd. It indicates immediately that it has seeked correctly without waiting for a buffer to fill. In fact it continues playing at the same position where it was before seeking. From now on MediaPlayer.getCurrentPosition() method returns wrong position. When playing reaches its end and OnCompletionListener.onCompletion callback is called the current media player position is much higher than entire song duration.
Any ideas for solving this?

A: I found a workaround for this problem:
First you create an OnBufferingUpdateListener:
MediaPlayer.OnBufferingUpdateListener bufferingListener = new MediaPlayer.OnBufferingUpdateListener() {
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        //code to increase your secondary seekbar
    }
};

Then in your seekbar event onProgressChanged do the following:
public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
    int secondaryPosition = seekBar.getSecondaryProgress();
    if (progress > secondaryPosition)
        seekBar.setProgress(secondaryPosition);
}

With this you guarantee the user can't drag the progress bar to an unbuffered position (and also you see what's buffered).

A: It has been fixed in Android 2.2 in some devices only as far as I know.
However Android 2.2 messes up with seeking to buffered posistion. Although a position is already buffered MediaPlayer sends a request to a server.

A: It's probably related to the bug that's (referring to one of the comments) eventually fixed in 2.2
http://code.google.com/p/android/issues/detail?id=4124


text:
Q: Android GPS location update I need to implement a system which requires user devices to continuously send me GPS updates.This can be really heavy on battery and data plans. Is there a model developed by android that takes care of such requirements?
Is it wise to switch on and off GPS while the app is running.
I am looking for a optimized model for this task.

A: This depends on the needed update interval. If the GPS is switched on, the time to get an exact fix depends on how much satelite it sees (eg. amount of visible free sky) and how long it was off.
So if you for example need one fix in ten minutes, it is ok to switch the GPS off and on. It would get a fix quite fast, but depending on the sky visibility, eg. may take a longer time (usually between some seconds and about a minute in worst case if a fix is possible) to get an accurate fix. On the other hand, if you need an update every minute, switching would not be useful in most cases (city driving for example) as the fix would already take an larger amount of the minute.
When switching the GPS, it is of great benefit of having a good sky visibility, eg. to instruct the users to not put the device deep inside the car or inside one's pocket but better mount it to the windscreen or hold it in front of the body for example. Then you can get fast fixing and shhort on-periods.


text:
Q: C - Returned array fills the array with the first value only My problem is that when I create a local array in the function and return it, all the values in the array become assigned to the array's first value. So for an example, an array of size 4 with the values 3, 5, 11, 13 is returned. The array now only has the values 3, 3, 3, 3. I'm fairly new to coding, so any help would be appreciated.
uint8_t* half( const uint8_t array[],
           unsigned int cols,
           unsigned int rows )
{

    int size = (cols / 2) * (rows / 2);

    uint8_t *newarray = malloc( size * sizeof(int) );

    float average;

    for (int i = 0; i < (rows / 2); i++) {

        for (int k = 0; k < (cols / 2); k++) {

            average = (array[ (2*k) + (2*i*cols) ] + array[ ((2*k) + 1) + (2*i*cols) ] + array[ ((2*k) + 1) + ((2*i*cols) + cols) ] + array[ (2*k) + ((2*i*cols) + cols) ]) / 4.0;

            newarray[k + (i * (cols / 2))] = (int)( round(average) );

        }
    }

    return newarray;

}

int main () {

    uint8_t *halfarray;

    halfarray = half(testarray, test_width, test_height);

    for (int i = 0; i < 4; i++) {

        printf("values in array %d\n", *halfarray);

    }

  return 0;
}

A: Try changing this line:
printf("values in array %d\n", *halfarray);

to this:
printf("values in array %d\n", *halfarray);
halfarray++

A: Use pointer arithmetic at each iteration to increment the position of the non-constant pointer, thusly:
   for (int i = 0; i < 4; i++, halfarray++) {

    printf("values in array %d\n", *halfarray);

}


text:
Q: Application crash while accessing data element of linked list when data is NULL I am using following code to traverse through linked list in objective c
   const MSList *calls = linphone_core_get_calls(LC);
            if (calls == NULL)
            {
                                [self dismissCtrl];
                //how to check current is which screen is on
                //                while ((currentView == CallView.compositeViewDescription) ||
                //                       (currentView == CallIncomingView.compositeViewDescription) ||
                //                       (currentView == CallOutgoingView.compositeViewDescription)) {
                //                    [self popCurrentView];
                //                }

            } else {
                linphone_call_resume((LinphoneCall *)calls->data);
                while (calls)
                {

                    if(calls->data != NULL && calls->data != nil && calls->data != (__bridge void *)((id)[NSNull null]))
                    {
                        //crash
                    if (linphone_call_get_state((LinphoneCall *)calls->data) == LinphoneCallIncomingReceived ||
                        linphone_call_get_state((LinphoneCall *)calls->data) == LinphoneCallIncomingEarlyMedia) {
                        [self displayIncomingCall:(LinphoneCall *)calls->data];
                        break;
                    }
                   }
                    calls = calls->next;

                }

Application is crashing when entire list is not null but its data,previous or next value is NULL. I have added code to check if data is NULL but if it(data) is NULL, then  i will not be able to access it and in condition itself application is crashing. How to prevent this ? I have attached screen-shot for where application is crashing and what is the value that list contains at that time.

A: if (calls == NULL) {
                [self dismissCtrl];
                //how to check current is which screen is on
                //                while ((currentView == CallView.compositeViewDescription) ||
                //                       (currentView == CallIncomingView.compositeViewDescription) ||
                //                       (currentView == CallOutgoingView.compositeViewDescription)) {
                //                    [self popCurrentView];
                //                }

            }
            else
            {

                size_t count = bctbx_list_size(calls);

                linphone_call_resume((LinphoneCall *)calls->data);

                int i = 0;

                while (calls )
                {

                    if(i < count)
{

                    if ( calls->data == (__bridge void *)((id)[NSNull null]) || calls->data == NULL || calls->data == nil )
                    {

                        return;
                    }

                    LinphoneCall *objCall =  (LinphoneCall *)calls->data;

                    LinphoneCallState state = (objCall != NULL) ? linphone_call_get_state(call) : 0;

                    if (state == LinphoneCallIncomingReceived ||
                        state == LinphoneCallIncomingEarlyMedia)
                    {
                        [self displayIncomingCall:(LinphoneCall *)calls->data];
                        break;
                    }

                    //calls ? calls->data : NULL
                   // calls =  calls ? calls->next : NULL;
                    calls = calls->next;
                        i = i+1;
                    }
                    else
                    {
                        break;
                    }
                }


text:
Q: Можно ли в express.js использовать несколько шаблонизаторов? Есть проект, состоящий из двух виртуальных частей - админская managment console и публичная. В одной я хочу использовать EJS, а в другой Jade. Это к примеру, для того, чтобы для публичной части можно было выбрать любой понравившийся клиенту (заказчику) шаблонизатор, а админка пусть уже будет на EJS.
Можно ли это реализовать? Хотя бы теоретический костыль какой-то существует?

A: Во-первых, обычно если настраивать шаблонизатор для некоторого расширения файла - то разным шаблонизаторам можно попросту указать разные расширения.
Во-вторых, админку можно выделить в отдельное подприложение:
var admin = express()
// ...

var main = express()
main.use('/admin', admin)

После такого выделения админку можно настраивать вообще независимо от основного приложения.


text:
Q: How do I add carriage return to the beginning of my tramp-shell-prompt-pattern? I am using a new server that when sshing into requires me the press "return" in order to see my shell prompt.  I believe this is causing my emacs tramp to get hung up.  When I tried to open a file through tramp on the new server I am repeatedly asked for the password.  I read that this could be due to tramp not recognizing the prompt.  The prompt is the same as on other servers that work, which makes me think it is this  that is causing issues.
I'm thinking the solution would be to add carriage return to the variable tramp-shell-prompt-pattern.  How would I do this?
maybe something like:
(setq tramp-shell-prompt-pattern "\r\(?:^\|\)[^]#$%> ]*#?[]#$%>] *\(\[[0-9;]*[a-zA-Z] *\)*")

adding \r to the front of the default?

Also, I don't know if it will be possible to remove this behavior on the server side.  I tried creating a .hushlogin file in my home directory, but it had no effect.

I came across this question which addresses the problem of the shell requiring user input.  The solution didn't work
(setq tramp-shell-prompt-pattern "^[^$>\n]*[#$%>] *\\(\[[0-9;]*[a-zA-Z] *\\)*")

Thanks for your help.  Clearly I'm a novice.


text:
Q: Могу ли я добавить тесты с методом main()? Имеется тула, написанная на Java. Могу ли я в папку с тестами добавить несколько перформанс-тестов, каждый с методом main()? Т.е. при запуске jar'ника, сгенеренного сборкой, не может ли запуститься один из этих тестов вместо стандартного метода main()?

A: Класс main метод которого будет выполнен, или задается в манифесте или укзывается в коммандной строке. Так что нет, ваши тестовые методы не запустятся, если вы только специально не запустите их.


text:
Q: Safe way to concatenate DOS variables to avoid unseen tab characters causing a double execution of a DEL command? I have a batch file:
C:\zzzztemp\zzzBUG_TEST.cmd
set backup_folder=.\BUG_TEST
echo %backup_folder%\*.*
del %backup_folder%\*.*
pause

...whose output is:
C:\zzzztemp>set backup_folder=.\BUG_TEST

C:\zzzztemp>echo .\BUG_TEST\*.*
.\BUG_TEST\*.*

C:\zzzztemp>del .\BUG_TEST\*.*
C:\zzzztemp\BUG_TEST\*.*, Are you sure (Y/N)? y

C:\zzzztemp>pause
Press any key to continue . . .

So far so good, just as expected.
But, if I accidentally have a tab at the end of specifying the folder variable
set backup_folder=.\BUG_TEST{accidentally had a tab here}

Results in:
C:\zzzztemp>set backup_folder=.\BUG_TEST

C:\zzzztemp>echo .\BUG_TEST     \*.*
.\BUG_TEST      \*.*

C:\zzzztemp>del .\BUG_TEST      \*.*
C:\zzzztemp\BUG_TEST\*, Are you sure (Y/N)? y
C:\*.*, Are you sure (Y/N)?

As you can see from the echo output, this is being interpreted as two arguments to the DEL command, and as a result the DEL operation is being performed twice, on two folders, one of which is c:\*.*
If one was to run this delete with the /Q (quiet, not requiring prompt to confirm delete), he could wipe out all the files in the root of c: !!!
So, I guess my question comes down to...
Is there a safe way to write:
del %backup_folder%\*.*

...Such that I would get a runtime error rather than an unintentional execution of delete with two arguments in the event that an unseen tab gets appended onto the variable assignment?

A: set "backup_folder=.\BUG_TEST" extra chars after last quote are ignored

Any characters after the last quote in the above assignment are ignored. No more accidental trailing tabs or spaces in your assignments :-)

A: EDIT:
if not "%backup_folder%"=="" if exist "%backup_folder%\*.*" del "%backup_folder%\*.*"

A: @ECHO OFF
SETLOCAL
ECHO test 1 - no stray TAB
set backup_folder=.\BUG_TEST
CALL :check %backup_folder%
IF NOT "%fcheck%"=="%backup_folder%" ECHO Suspect foldername +%backup_folder%+&GOTO :EOF
echo %backup_folder%\*.*
ECHO del %backup_folder%\*.*

ECHO test 2 - deliberate stray TAB

:: generate a TAB character
SET "TAB=   "

ECHO testing tab exists:%tab%:exists IF there's a gap between the colons
ECHO show it is a TAB%tab%:the
ECHO show it  is a TAB%tab%:colons
ECHO show it   is a TAB%tab%:should
ECHO show it    is a TAB%tab%:align

set backup_folder=.\BUG_TEST%tab%
CALL :check %backup_folder%
IF NOT "%fcheck%"=="%backup_folder%" ECHO Suspect foldername +%backup_folder%+&GOTO :EOF
echo %backup_folder%\*.*
ECHO del %backup_folder%\*.*
GOTO :eof

:check
SET fcheck=%1
GOTO :eof

Hmm - don't be alarmed by its size - most is commentary and there are two separate situations tested (with and without TAB)

*

*Not sure whether cut-and-paste will work successfully here - the tab actually must be a tab - but OP is good at those - perhaps overly so...

*Note the set "var=value" syntax - designed to stop um - stray invisible characters at the end of lines being included in the value assigned...
The :check routine uses the separators [space][tab][;][,][=] to assign a value - if the value assigned is identical to the original, then there were no separators.


text:
Q: Sort a list of products save in localstorage with JavaScript change event listener I have saved a list of products in localstorgae and I want all my products to be displayed in descending order when I click on one of the combobox items

const _UserData = [
    { id: 1, pic: "img/113677817.jpg", title: "کیسه بوکس", price: 159.000 },
    { id: 2, pic: "img/hand.jpg", title: "دستکش بوکس", price: 389.000 },
    { id: 3, pic: "img/hat.jpg", title: "کلاه تکواندو", price: 120.000 },
    { id: 4, pic: "img/tekvando.jpg", title: "لباس کاراته", price: 100.000 },
    { id: 5, pic: "img/nanchico.jpg", title: "نانچیکو", price: 230.500 },
    { id: 6, pic: "img/gel.jpg", title: "محافظ لثه", price: 42.000 },
    { id: 7, pic: "img/hogo.jpg", title: "هوگو تکواندو", price: 150.000 },
    { id: 8, pic: "img/ktg.jpg", title: "نقاب تکواندو", price: 160.000 },
    { id: 9, pic: "img/kongfu.jpg", title: "لباس کنگفو", price: 216.500 },
    { id: 10, pic: "img/band.jpg", title: "کمربند تکواندو", price: 27.000 },
    { id: 11, pic: "img/short.jpg", title: "شورت ووشو", price: 351.000 }
    ];

newFunction();
console.log(_UserData);

function newFunction() {
    _UserData.sort(function (a, b) {
        if (a.title.localeCompare(b.title)==-1) {
            return -1;
        }
        else {
            return 1;
        }

    });
}
<div class="select d-flex justify-content-start align-items-center m-5">
  <select name="format" id="sort">
    <option selected disabled>جستجو بر اساس</option>
    <option value="dec-price">قیمت-نزولی</option>
    <option value="inc-price">قیمت-صعودی</option>
    <option value="dec-title">عنوان-نزولی</option>
    <option value="inc-title">عنوان-صعودی</option>
  </select>
</div>

> Blockquote

A: For those looking for an answer,
I used the onchange event for the select tag and my problem was solved


text:
Q: Can't run the touchlist project I'd really like to implement in my app the touchlist widget, provided here:
https://github.com/commonsguy/cwac-touchlist
So I downloaded it and I imported the project folder in Eclipse; I  tried to run as an ant build but I got this error:
Buildfile: C:\commonsguy-cwac-touchlist-af26192\build.xml

BUILD FAILED
C:\commonsguy-cwac-touchlist-af26192\build.xml:49: taskdef class com.android.ant.SetupTask cannot be found
 using the classloader AntClassLoader[]

Total time: 328 milliseconds

What's wrong with what I've done so far? It is driving me crazy...

A: You have to right-click on your project and choose Properties.
On the dialog that opens choose Android from the left and in the Library section choose Add and add the cwac-touchlist project.
This is because cwac-touchlist was converted to an Android Library Project so you have to add it to your own project as a library.


text:
Q: Web Api HttpPost Method Not Allowed', I am writing web api method which retrieves list of countries. Name of the method is GetAllCountries. Methods accepts many parameters (like pageno, pagesize, sortorder,other filters etc.). Instead of creating method with many arguments I have created Dto which has properties mentioned above. Since Get method in web api can accept only primitive datatypes or simple dto's, I have chosen GetAllCountries as post method (it is decorated with HttpPost attribute) so that it can accept complex dto.When I am invoking GetAllCountries method from client, I am getting error "StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.1, Content: System.Net.Http.StreamContent, Headers".
I know my method name is against web api convention(meaning method name starts with Get but it is actually a post). I have checked everything (like url etc) but still I could not figure why error is coming.
Following is the Code
        [HttpPost]
    public GetCountryListResponse GetAllCountries(GetAllCountriesRequest request)
    {
        return DestinationBl.GetAllCountries(request);
    }

A: Sounds like you might have a problem with the method's input.
Try to add [FromBody] before the input parameter:
[HttpPost]
public Countries GetAllConuntries([FromBody]YorObject obj)
{}


text:
Q: What exactly is the difference between "Max" and "Super" setting in ECC BIOS setting of Asus M5A78L-M/USB3 motherboard? The manual says only:

ECC Configuration
ECC Mode [Disabled]
Enables or disables the DRAM ECC that allows the hardware to report and correct memory errors automatically.
Configuration options: [Disabled] [Basic] [Good] [Super] [Max] [User]"

Which says absolutely nothing about the particular difference between Super and Max.

A: Official answer from ASUS Customer Service:

It relates to Error checking - and the capacity it does it, max being max and super being a lot
It is typically a trade off in performance the more it checks for bit errors


text:
Q: How to add new items to recycler dynamically from request to API At the moment of opening my app it sends a request and it returns me 10 items, I want that once I'm at the bottom it makes another request and appends another 10 items to the initial 10 how can I do that?
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        new RequestBase(getActivity())
        {
            @Override
            public JsonObject onHttpOk(JsonObject response) throws JSONException
            {
                JsonObject objeto, pagination_details = null;
                final JsonArray data;

                if (getActivity() == null)
                    return response;

                if (response.get("pagination") == null)
                {
                    objeto = response;
                } else
                    {
                    objeto = response;
                    pagination_details = response.get("pagination").getAsJsonObject();
                    pagination = pagination_details.get("limit").getAsInt();
                    data = objeto.get("data").getAsJsonArray();
                    gson = new Gson();
                    arrayBusiness = new ArrayList<Business>();
                    arrayBusiness = gson.fromJson(data, BUSINESS_TYPE);

                        FeedsFragment.this.getActivity().runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run() {
                            recycler = (RecyclerView) FeedsFragment.this.getActivity().findViewById(R.id.recycler_main);
                            adapter = new MainAdapter(getActivity(), arrayBusiness, R.layout.main_row);

                            recycler.setNestedScrollingEnabled(false);
                            mLayoutManager = new GridLayoutManager(FeedsFragment.this.getActivity(), 2);
                            recycler.setLayoutManager(mLayoutManager);
                            recycler.setAdapter(adapter);
                            adapter.notifyItemInserted(arrayBusiness.size() - 1);

                            recycler.addOnScrollListener(new RecyclerView.OnScrollListener()
                            {
                                @Override
                                public void onScrolled(RecyclerView recyclerView, int dx, int dy)
                                {
                                    super.onScrolled(recyclerView, dx, dy);

                                    visibleItemCount = recycler.getChildCount();
                                    totalItemCount = mLayoutManager.getItemCount();
                                    firstVisiblePosition = mLayoutManager.findFirstVisibleItemPosition();

                                    if (loading)
                                    {
                                        if (totalItemCount > previousTotal)
                                        {
                                            loading = false;
                                            previousTotal = totalItemCount;
                                        }
                                    }
                                    if (!loading && (totalItemCount - visibleItemCount) <= (firstVisiblePosition + visibleThreshold))
                                    {
                                        Log.d("FINAL","LLEGASTE A FINAL DEL SCROLL");
                                        loadMore();
                                        loading = true;
                                    }

                                }
                            });

                            GifTextView loading = (GifTextView) FeedsFragment.this.getActivity().findViewById(R.id.loading);
                            TextView loadingText = (TextView) FeedsFragment.this.getActivity().findViewById(R.id.loadingText);
                            loading.setVisibility(View.GONE);
                            loadingText.setVisibility(View.GONE);
                        }
                    });
                }
                if (pagination_details.isJsonNull())
                {
                    Log.d("Paginacion", pagination_details.toString());
                }
                return objeto;
            }

            @Override
            public void onHttpCreate(JsonObject response) throws JSONException
            {

            }

            @Override
            public void onHttpUnprocessableEntity(JsonObject response) throws JSONException
            {
                this.cancel(true);
                final String error = response.get("errors").toString();
                getActivity().runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast.makeText(getActivity().getApplicationContext(), error, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }.execute("businesses/premiums", "GET");
        return android;
    }

I have the method loadMore
and what it does it sends the request to the API but with the results of the page 2 these are the ones that I'm trying to append to the initial 10, but what it does it's replacing them instead of appending
  public void loadMore()
    {
        new Thread(new Runnable()
        {
            public void run()
            {

                new RequestBase(getActivity()) {
                    @Override
                    public JsonObject onHttpOk(JsonObject response) throws JSONException {
                        JsonObject objeto, pagination_details = null;
                        final JsonArray data;

                        if (getActivity() == null)
                            return response;

                        if (response.get("pagination") == null) {
                            objeto = response;
                        } else {

                            objeto = response;
                            pagination_details = response.get("pagination").getAsJsonObject();
                            pagination = pagination_details.get("limit").getAsInt();
                            data = objeto.get("data").getAsJsonArray();
                            gson = new Gson();
                            arrayBusiness = new ArrayList<Business>();
                            arrayBusiness = gson.fromJson(data, BUSINESS_TYPE);

                            Log.d("size", String.valueOf(arrayBusiness.size()));

                            FeedsFragment.this.getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    recycler = (RecyclerView) FeedsFragment.this.getActivity().findViewById(R.id.recycler_main);
                                    adapter = new MainAdapter(getActivity(), arrayBusiness, R.layout.main_row);

                                    recycler.setNestedScrollingEnabled(false);
                                    mLayoutManager = new GridLayoutManager(FeedsFragment.this.getActivity(), 2);
                                    recycler.setLayoutManager(mLayoutManager);
                                    recycler.setAdapter(adapter);
                                }
                            });
                        }
                        if (pagination_details.isJsonNull())
                        {
                            Log.d("Paginacion", pagination_details.toString());
                        }
                        return objeto;
                    }
                }.execute("businesses/premiums?offset=2", "GET");
            }
        }).start();
    }

Thank you for your help


text:
Q: Jelly validateButton can't access Java method I'm trying to write a simple Jenkins plugin.
I'm facing problem with Jelly validateButton however; it can't access Java method.
Since I'm not quite familiar with Jelly and Java, I've been using this Wiki as a reference point - https://wiki.jenkins-ci.org/display/JENKINS/Jelly+form+controls
Here is what I get in Jenkins:
ERROR
HTTP ERROR 404

Problem accessing /tagBuild. Reason:

    Not Found

Powered by Jetty://

Here is my Jelly code:
<j:jelly xmlns:j="jelly:core" xmlns:l="/lib/layout" xmlns:st="jelly:stapler" xmlns:f="lib/form" xmlns:t="/lib/hudson">
    <l:layout norefresh="true">
        <st:include page="sidepanel.jelly" it="${it.build}"/>
        <l:main-panel>
            <f:form method="post">
                <f:entry title="${%Milestone Name}" help="Enter Milestone name to tag with...">
                    <f:textbox field="milestoneName" />
                </f:entry>
                <f:validateButton title="${%Tag Build}" progress="${%Tagging...}" method="tagBuild" with="milestoneName" />
            </f:form>
        </l:main-panel>
    </l:layout>
</j:jelly>

And here is the Java class:
import hudson.model.AbstractBuild;
import hudson.model.Action;
import hudson.util.FormValidation;
import org.kohsuke.stapler.QueryParameter;

public class MilestoneLabelingPlugin implements Action {
    AbstractBuild build;
    public AbstractBuild getBuild() { return this.build; }
    public MilestoneLabelingPlugin(AbstractBuild build) {
        super();
        this.build = build;
    }
    public String getUrlName() { return "MilestoneLabelingPlugin"; }
    public String getDisplayName() { return "Label Milestone Build"; }
    public String getIconFileName() { return "/plugin/milestone-labeling-plugin/icon/labelMilestoneBuild.png"; }

    public FormValidation doTagBuild(@QueryParameter("milestoneName") final String milestoneName) {
        return FormValidation.ok("Success!!" + milestoneName);
    }

}

The most interesting part is that I've tried to use Submit button, with  configured to run a method and it worked. Only problem was that I wasn't able to read value from input field :/
Is there anyone who had similar problem? Or someone who can tell me what am I doing wrong.
Thanks for all replies in advance.

A: I think the issue is as explained in the Wiki : "This method needs to be on the Descriptor class that owns this form fragment."  Looks like FormValidation method is only supported for Describable classes.


text:
Q: HudLayer doesn't show up in my iOS game greetings from a first time poster;
i found this site very useful a lot of times,but now there is a problem i cannot resolve,i recently made a iOS game with cocos2d,this game has scenes composed each of a game layer and a hudlayer,now,the hudlayer shows up in the xcode simulator with all the iphone models,but when i try on device it works only in the iphone 4. In an 5s for example it doesn't show up, while the game layer which contains the game works. So, when i open up the game i see only my character the level but not my joypad to move it,nor the scores ecc that should show up in the hudlayer,this is the way i implement it in a scene
header:
@interface GameScene : CCScene
{
}

@property(nonatomic,weak)GameLayer *gameLayer;
@property(nonatomic,weak)HudLayer *hudLayer;

@end

implementation in the .m:
@implementation GameScene

-(id)init {
    if ((self = [super init])) {
        _gameLayer = [GameLayer node];
        [self addChild:_gameLayer z:0];
        _hudLayer = [HudLayer node];
        [self addChild:_hudLayer z:1];
        _hudLayer.dPad.delegate=_gameLayer;
        _hudLayer.jPad.delegate=_gameLayer;
        _hudLayer.aPad.delegate=_gameLayer;
        _gameLayer.hud=_hudLayer;
    }
    return self;
}

@end

any advice?
thank you for the reply,this is the way i implemented the hud layer
header:
@interface HudLayer : CCLayer {

CCLabelTTF *_lifeLabel;
CCLabelTTF *_enemyLabel;

}
@property(nonatomic,weak)SimpleDPad *dPad;
@property(nonatomic, weak)SimpleJPad *jPad;
@property(nonatomic, weak)SimpleAPad *aPad;

-(void)setLifeString:(NSString *)string;
-(void)setEnemyString:(NSString *)estring;

@end

implementation .m:
@implementation HudLayer
-(id)init{
 if((self=[super init])){

    _dPad=[SimpleDPad dPadWithFile:@"pad.png" radius:50];
    _dPad.position=ccp(90, 60);
    _dPad.opacity=180;
    [self addChild:_dPad];
    _jPad=[SimpleJPad jPadWithFile:@"jumb.png" radius:30];
    _jPad.position=ccp(450, 60);
    _jPad.opacity=100;
    [self addChild:_jPad];
    _aPad=[SimpleAPad aPadWithFile:@"jumb.png" radius:30];
    _aPad.position=ccp(390, 60);
    _aPad.opacity=100;
    [self addChild:_aPad];

    //lifelabel

    _lifeLabel = [CCLabelTTF labelWithString:@"" fontName:@"Marker Felt" fontSize:25];

    _lifeLabel.position = ccp(90, 260);
    [self addChild:_lifeLabel];

    //enemy label
    _enemyLabel = [CCLabelTTF labelWithString:@"" fontName:@"Marker Felt" fontSize:25];

    _enemyLabel.position = ccp(380, 260);
    [self addChild:_enemyLabel];

}

return self;
}
-(void)setLifeString:(NSString *)string{

_lifeLabel.string=string;
}

-(void)setEnemyString:(NSString *)estring{
_enemyLabel.string=estring;
}

@end


text:
Q: .NET float representation in memory According to Jon Skeet's float article, setting the sign bit to 1 and everything else to 0 still gives the number 0. I'm not 100% sure if the sign bit is the very first bit (as told in the article) or the very last bit (as described in the docs). Regardless, I tried both:
byte[] buf = new byte[4];
buf[0] = 0b10000000;
buf[1] = 0b00000000;
buf[2] = 0b00000000;
buf[3] = 0b00000000;
float f = BitConverter.ToSingle(buf, 0); // 1,793662E-43

buf[0] = 0b00000000;
buf[1] = 0b00000000;
buf[2] = 0b00000000;
buf[3] = 0b00000001;
float g = BitConverter.ToSingle(buf, 0); // 2,350989E-38

And both do not result in 0. What am I doing wrong? The sanity check of setting all bits to 0 works.

A: Thanks to user EOF I realized that .NET bytes are not stored in the (for non-bit-hackers) intuitive endianess. buf[3] = 0b10000000; does the trick.


text:
Q: document.referrer does not work when the iframe is reloaded So I have a page which consist of an iframe.
Eg: Consider htp://example.com to be the page and htp://test.com as the iframe.
Now when I do $window.location.reload in the htp://test.com, while the iframe is loaded it takes the document.referrer as itself rather then htp://example.com.
It works fine for the first time when the main page is loaded.
But does not work when only the iframe is reloaded.


text:
Q: Python Connect 4 Turn WARNING: I am almost completely new to python, so the errors here may be obvious - I will apologise in advance. Also, please try and keep answers easy to understand for an idiot! Thanks :)
I am trying to create a Connect 4 game in python, and I have almost everything working except I can't get it to swap turns between Noughts and Crosses. My main code is below:
def main():
    global Xor0
    winCheck = True
    while winCheck == True:
        humanTile = enterHumanTile()
        print("The", Xor0, "player shall go first")
        mainBoard= getNewBoard()

        if Xor0 == "Crosses":
            drawBoard(mainBoard)
            move = getHumanMove(mainBoard)
            makeMove(mainBoard, humanTile, move)
            Xor0 = "Noughts"
            if isWinner(mainBoard, tile):
                drawBoard(mainBoard)
                print("Crosses win")
                winCheck = False
            Xor0 = "Noughts"
        else:
            drawBoard(mainBoard)
            move = getHumanMove(mainBoard)
            makeMove(mainBoard, humanTile, move)
            if isWinner(mainBoard, tile):
                drawBoard(mainBoard)
                print("Noughts win")
                winCheck=False
            Xor0 ="Crosses"

Xor0 is essentially turn, but I allocate it earlier using:
firstHTurn = random.randint(1,2)
if firstHTurn == 1:
    Xor0 = 'Crosses'
    tile = 'X'
else:
    Xor0 = 'Noughts'
    tile = '0'

which works fine, but I don't understand why the turn doesn't alternate at the end of each 'if' statement within main()
Full code:
import random
import sys
import copy
import time

def s():
    print("")

print("        _________                                     __    ___________                  ")
print("        \_   ___ \  ____   ____   ____   ____   _____/  |_  \_   _____/___  __ _________ ")
print("        /    \  \/ /  _ \ /    \ /    \_/ __ \_/ ___\   __\  |    __)/  _ \|  |  \_  __ \ ")
print("        \     \___(  <_> )   |  \   |  \  ___/\  \___|  |    |     \(  <_> )  |  /|  | \/")
print("         \______  /\____/|___|  /___|  /\___  >\___  >__|    \___  / \____/|____/ |__|   ")
print("                \/            \/     \/     \/     \/            \/                      ")

print("")
print("")

playerMethod = input("Would you like to player a computer or a friend (C for Computer, F for Friends)")

if playerMethod== "F":
    s()
    method = "pvp"
    print("Choose who will be Noughts and who will be Crosses")
    s()
    #time.sleep(3)
    #firstHTurn = random.randint(1,2)
    firstHTurn = 2
    if firstHTurn == 1:
        Xor0 = 'Crosses'
        tile = 'X'
    else:
        Xor0 = 'Noughts'
        tile = '0'
    print("The", Xor0, "will play first")
    s()
    print("-----------------------------")
    s()
elif playerMethod == "C":
    method = "pve"
    firstHTurn = random.randint(1,2)
    if firstHTurn == 1:
        print("The computer shall go first")
    else:
        print("You shall go first")
    print("-----------------------------")

a=0
board = []

while a==0:
    boardwidth = input("How wide should the board be?")
    try:
        float(boardwidth)
        break
    except ValueError:
        pass
        print("")
        print("======================")
        print("Please enter a number")
        print("======================")
        print("")
print("=== Board width set to", boardwidth, "===")

b=0
while b==0:
    boardheight = input("How tall should the board be?")
    try:
        float(boardheight)
        break
    except ValueError:
        pass
        print("")
        print("======================")
        print("Please enter a number")
        print("======================")
        print("")
print("=== Board height set to", boardheight, "===")
s()
if method == "pvp":
    print("=======================================")
    print(" ==The", Xor0, "player shall go first== ")
    print("=======================================")
if method == "pve" and firstHTurn == 1:
    print("=================================")
    print("== The Computer shall go first ==")
    print("=================================")

if method == "pve" and firstHTurn == 2:
    print("==============================")
    print("===== You Shall go first =====")
    print("==============================")

BHeight = int(boardheight)
BWidth = int(boardwidth)

def getNewBoard():
    board = []
    for x in range(BWidth):
        board.append([' '] * BHeight)
    return board

def drawBoard(board):
    print()
    print(' ', end='')
    for x in range(1, BWidth + 1):
        print(' %s  ' % x, end='')
    print()

    print('+---+' + ('---+' * (BWidth - 1)))

    for y in range(BHeight):
        print('|   |' + ('   |' * (BWidth - 1)))

        print('|', end='')
        for x in range(BWidth):
            print(' %s |' % board[x][y], end='')
        print()

        print('|   |' + ('   |' * (BWidth - 1)))

        print('+---+' + ('---+' * (BWidth - 1)))

def enterHumanTile():
    if tile == 'X':
        return ['X', '0']
    else:
        return ['0', 'X']

def isValidMove(board, move):
    if move < 0 or move >= (BWidth):
        return False

    if board[move][0] != ' ':
        return False

    return True

def getHumanMove(board):
    while True:
        print("Which column do you want to move on? (1-%s, or 'quit' to quit the game)" % (BWidth))
        move = input()
        if move.lower().startswith('q'):
            sys.exit()
        if not move.isdigit():
            continue
        move = int(move) - 1
        if isValidMove (board, move):
            return move

def makeMove(board, player, column):
    for y in range(BHeight-1, -1, -1):
        if board[column][y] ==' ':
            board[column][y] =tile
            return

def playAgain():
    # This function returns True if the player wants to play again, otherwise it returns False.
    print('Do you want to play again? (yes or no)')
    return input().lower().startswith('y')

def isWinner(board, tile):
    # check horizontal spaces
    for y in range(BHeight):
        for x in range(BWidth - 3):
            if board[x][y] == tile and board[x+1][y] == tile and board[x+2][y] == tile and board[x+3][y] == tile:
                return True

    # check vertical spaces
    for x in range(BWidth):
        for y in range(BHeight - 3):
            if board[x][y] == tile and board[x][y+1] == tile and board[x][y+2] == tile and board[x][y+3] == tile:
                return True

    # check / diagonal spaces
    for x in range(BWidth - 3):
        for y in range(3, BHeight):
            if board[x][y] == tile and board[x+1][y-1] == tile and board[x+2][y-2] == tile and board[x+3][y-3] == tile:
                return True

    # check \ diagonal spaces
    for x in range(BWidth - 3):
        for y in range(BHeight - 3):
            if board[x][y] == tile and board[x+1][y+1] == tile and board[x+2][y+2] == tile and board[x+3][y+3] == tile:
                return True

    return False

def main():
    global Xor0
    winCheck = True
    while winCheck == True:
        humanTile = enterHumanTile()
        print("The", Xor0, "player shall go first")
        mainBoard= getNewBoard()

        while winCheck == True:
            if Xor0 == "Crosses":
                drawBoard(mainBoard)
                move = getHumanMove(mainBoard)
                makeMove(mainBoard, humanTile, move)
                Xor0 = "Noughts"
                if isWinner(mainBoard, tile):
                    drawBoard(mainBoard)
                    print("YOU WIN")
                    winCheck = False
                Xor0 = "Noughts"
            else:
                drawBoard(mainBoard)
                move = getHumanMove(mainBoard)
                makeMove(mainBoard, humanTile, move)
                if isWinner(mainBoard, tile):
                    drawBoard(mainBoard)
                    print("Noughts win")
                    winCheck=False
                Xor0 ="Crosses"

main()


text:
Q: Python JSON Google Translator parsing with Simplejson problem I am trying to parse the Google Translation result using simplejson in Python. But I am getting the following Exception.
Traceback (most recent call last):
  File "Translator.py", line 45, in <module>
    main()
  File "Translator.py", line 41, in main
    parse_json(trans_text)
  File "Translator.py", line 29, in parse_json
    json = simplejson.loads(str(trans_text))
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 418, in raw_decode
    obj, end = self.scan_once(s, idx)
simplejson.decoder.JSONDecodeError: Expecting property name: line 1 column 1 (char 1)

This is my json object looks like
{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}

could anyone tell me what is the problem here?

A: The issue is that simplejson supports json with double quote encoded strings and not single quote encoded strings, so a naive solution might be
json.loads(jsonstring.replace("'", '"'))

A: You are doing simplejson.loads(str(trans_text))
trans_text is NOT a string (str or unicode) or buffer object. This is witnessed by the simplejson error message, and your report of repr(trans_text):

This is my repr of trans text
  {'translations': [{'translatedText':
  'hola'}]}

trans_text is a dictionary.
If you want to convert that into a JSON string, you need to use simplejson.dumps(), not simplejson.loads().
If you want to use the result for something else, you just need to dig the data out e.g.
# Your other example
trans_text = {'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
for x in trans_text['translations']:
    print "chunk of translated text:", x['translatedText']

A: JSON syntax doesn't support full syntax of JavaScript. Unlike JavaScript, JSON strings and attribute names have to be double-quoted.

string ::= "" | " chars "


text:
Q: Finite groups whose Sylow 2-subroups are Klein groups I am reading part VIII of Burnside's "Notes on the Theory of Groups of Finite Order". It was published in 1895 (Proc. London Math. Soc., vol. 26, p. 325-338, 1895, Collected Papers, vol. I, p. 590-596).
Burnside first proves something that I understand (in today's language) as follows :
$\mathbf{Statement \ 1}.$ Let $G$ be a finite group whose Sylow 2-subgroups are Klein groups. Then one (and only one) of the two following cases holds :
(i) for every Sylow 2-subgroup $V$ of $G$, the three elements of order 2 of $V$ form a conjugacy class in $N_{G}(V)$, $\vert N_{G}(V) \vert$ (and thus also $\vert G \vert$) is divisible by 12 and all elements of order 2 in $G$ are conjugate in $G$;
(ii) for every Sylow 2-subgroup $V$ of $G$, the three elements of order 2 of $V$ are pairwise non-conjugate in $G$ and $N_{G}(V) = C_{G}(V)$.
I have no problem with that.
Thereafter, Burnside's goal seems to be to prove that if $G$ is simple, it is the case (i) of Statement 1 that takes place. Today, it is an easy consequence of Burnside's transfer theorem : in case (ii), we have $N_{G}(V) = C_{G}(V)$ for every Sylow 2-subgroup $V$ of $G$, thus, by Burnside's transfer theorem, $G$ cannot be simple. But Burnside doesn't use his transfer theorem here. (I presume that he had not yet stated this theorem in 1895. By the way, when and where did he publish it for the first time ? I don't find the answer on Internet.)
I must confess that I don't understand this part of Burnside's paper. He considers a group, let us say $G$, of order $N = 4m$, with $m$ odd, he assumes that the Sylow 2-subgroups of $G$ are Klein groups and, if I understand it correctly, he notes $4m_{1}$ the order of the normalizer in $G$ of a Sylow 2-subgroup of $G$. Then he says (p. 590-591 in the Collected Papers, vol. I) :
"Suppose now that this is not the case [I understand : Suppose that we are not in case (i) of Statement 1, in other words suppose that we are in case (ii) of Statement 1.], so that the group contains 3 different conjugate sets of operations of order 2 [OK]. Every operation [Burnside says "operation" where we say "element"] of order 2 is certainly self-conjugate [For an element of a group, Burnside says "self-conjugate" where we say "central"; for a subgroup, he says "self-conjugate" where we say "normal".] in a sub-group of order $2^{2}m_{1}$ [Indeed, every element $v$ of order 2 of $G$ is contained in a Sylow 2-subgroup $V$ of $G$ and, since we are in case (ii) of Statement 1, $N_{G}(V)$ centralizes $V$ and thus centralizes $v$. Recall that $2^{2}m_{1}$ is the order of $N_{G}(V)$ for every Sylow 2-subgroup $V$ of $G$.], and may be self-conjugate in a more extensive sub-group. [In other words : $N_{G}(V)$ is contained in $C_{G}(v)$ and it is possible that $C_{G}(v)$ is greater than $N_{G}(V)$.] Let, then, $S$, an operation of order 2 be self-conjugate within a group of order $2^{2}m_{1} \mu $. [I understand : let $S$ be an element of order 2 of $G$ and let $2^{2}m_{1} \mu $ be the order of $C_{G}(S)$.] An operation of this sub-group whose order is odd, and which is not contained in the sub-group of order $2^{2}m_{1}$, is permutable with $S$, and with no operation of order 2 which is not conjugate to $S$."
What is exactly the meaning of this last sentence ? Burnside says "THE sub-group of order $2^{2}m_{1}$". But $S$ can belong to several Sylow 2-subgroups of $G$. If $S$ is in a Sylow 2-subgroup $V$ of $G$ and also in another Sylow 2-subgroup $W$ of $G$, what is "THE sub-group of order $2^{2}m_{1}$" ? $N_{G}(V)$ or $N_{G}(W)$ ?
In any case, I think that the following statement is wrong :
$\mathbf{Statement \ 2}.$ (not from Burnside, and wrong). Let $G$ be a finite group whose Sylow 2-subgroups are Klein groups. Assume that case (ii) of Statement 1 holds, so that, for every Sylow 2-subgroup $V$ of $G$, the three elements of order 2 of $V$ are pairwise non-conjugate in $G$ and $N_{G}(V) = C_{G}(V)$. Let $v$ be an element of order 2 of $G$, let $V$ be a Sylow 2-subgroup of $G$ containing $v$, let $t$ be an element of odd order in $C_{G}(v)$ and assume that $t$ is not in $N_{G}(V) = C_{G}(V)$. Then all elements of order 2 in $C_{G}(t)$ are conjugate in $G$.
Here is a counterexample. Let $H$ be a nonabelian group of order 21. Then $H$ is a semidirect product $\langle x_{7} \rangle \rtimes  \langle y_{3} \rangle $, where $x_{7}$ is an element of order 7,  $y_{3}$ an element of order 3 and $y_{3} x_{7} {y_{3}}^{-1} = {x_{7}}^{2}$.
By von Dyck's theorem, or whatever, there exists one and only one automorphism $\sigma$ of H such that $\sigma (x_{7}) = {x_{7}}^{-1}$ and $\sigma (y_{3}) = y_{3}$. Clearly, $\sigma$ is of order 2 in $Aut(H)$.
Choose a Klein group $V = \{1, a, b, c\}$. Let $\tau : v \mapsto \tau_{v}$ be the homomorphism from $V$ to $Aut(H)$ such that $\tau_{1} = \tau_{a} = id_{H}, \tau_{b} = \tau_{c} =\sigma$. Put $G = H \rtimes _{\tau}V$. Clearly the Sylow 2-subgroups of $G = H \rtimes _{\tau}V$ are Klein groups. It is easy to check that
(1) $\qquad (1, a)$ is a central element of order 2 in $G = H \rtimes _{\tau}V$;
(2) $\qquad (1, b)$ is an element of order 2 in $G = H \rtimes _{\tau}V$ and it commutes with $(y_{3}, 1)$, which is an element of order 3 in $G = H \rtimes _{\tau}V$;
(3)  $\qquad (x_{7}, b)$ is an element of order 2 in $G = H \rtimes _{\tau}V$ and it doesn't commute with $(y_{3}, 1)$.
From (1), it results that $(1, a)$ is conjugate to no element of $G = H \rtimes _{\tau}V$ other than $(1, a)$ itself. Since (for example by (2) ), $G = H \rtimes _{\tau}V$ has at least one other element of order 2 than $(1, a)$, it is not true that all the elements of order 2 in $G = H \rtimes _{\tau}V$ are conjugate in $G = H \rtimes _{\tau}V$. Thus we are not in case (i) of Statement 1, thus
(4) $\qquad$ it is case (ii) of Statement 1 which holds,
Put $W = \langle (1, a), (x_{7}, b)\rangle$. In view of (1) and (3), $W$ is a Sylow 2-subgroup $W$ of $G = H \rtimes _{\tau}V$, $(y_{3}, 1)$ commutes with $(1, a)$, $(y_{3}, 1)$ is not in $C_{G}(W)$. Thus, if Statement 2 was true, all the elements of order 2 of $G = H \rtimes _{\tau}V$ commuting with $(y_{3}, 1)$ should be conjugate to eachother in $G$. It is false, since, by (1) and (2), both $(1, a)$ and $(1, b)$ are elements of order 2 commuting with $(y_{3}, 1)$, but they are not conjugate in $G$ (since $(1, a)$ is central in $G$). Thus Statement 2 is wrong.
So my question is : do you think that Burnside's proof is correct and, if it is the case, could you make it clearer ?
I will now copy the whole proof of Burnside. Maybe it can help you understand his ideas.
"Suppose now that this is not the case, so that the group contains 3 different conjugate sets of operations of order 2. Every operation of order 2 is certainly self-conjugate in a sub-group of order $2^{2}m_{1}$, and may be self-conjugate in a more extensive sub-group. Let, then, $S$, an operation of order 2 be self-conjugate within a group of order $2^{2}m_{1} \mu $. An operation of this sub-group whose order is odd, and which is not contained in the sub-group of order $2^{2}m_{1}$, is permutable with $S$, and with no operation of order 2 which is not conjugate to $S$. Hence it must form one of a set of $2r$ conjugate operations , where $r$ is odd. If now the group be represented as a permutation group, consisting of the permutations of these $2r$ operations among themselves which arise by transforming them by all the operations of the group, any operation of order 2 which is not conjugate to $S$ will give a substitution in the permutation-group, consisting in $r$ transpositions, i.e. an odd substitution, and, therefore, the group cannot be simple. Hence, the group is certainly not simple unless the maximum sub-group, which contains an operation of order 2 self-conjugately, is of order $2^{2}m_{1}$; and when this condition is satisfied every operation of order 2 is permutable with just 2 other operations of order 2, and with no more.
But, now, if $A$, $B$ are two operations of order 2 belonging to different conjugate sets, and if $(AB)^{n} = 1$, $A$, $B$ generate a dihedral group of order $2n$. If $n$ were odd, $A$ and $B$ would be conjugate, which is not the case. Hence, $n$ must be even, and then $(AB)^{\frac{1}{2}n}$ is an operation of order 2 which is permutable with $n$ distinct pairs [?] of operations of order 2. But this is in direct contradiction to what has just been proved, so that this case cannot occur. It follows that, if a group whose order is $2^{2}m$ ($m$ odd) contains 3 different conjugate sets of operations of order 2, it cannot be simple."
$\mathbf{Edit}$ (May 22, 2021). I still feel that Burnside's proof is not absolutely correct, but I think it can be fixed (without use of transfer theory), by use of Burnside's ideas.
Let $G$ be a finite simple group whose Sylow 2-subgroups are Klein groups and let us prove that all the elements of order 2 in $G$ are conjugate.
$\mathbf{Lemma \ 1.}$ Let $G$ a finite simple group, let $t$ be an element of $G$ such that the number of conjugates of $t$ in $G$ is of the form $2r$, with $r$ odd. Then, for every element $s$ of order 2 in $G$, there exists at least one G-conjugate of $t$ which commutes with $s$.
Proof. Let $Conj(t)$ denote the set of conjugates of $t$ in $G$. From the hypotheses, $Conj(t)$ has more than an element, thus the simple group $G$ is nonabelian and acts nontrivially on $Conj(t)$ by conjugation, thus the permutation $u \mapsto sus^{-1}$ is even. If $s$ commuted with no conjugate of $t$, this permutation should be the product of $r$ transpositions (with disjoint supports) and should thus be odd, contradiction.
$\mathbf{Lemma \ 2.}$ Let $G$ be a group, let $a, b$ two elements of order 2 in $G$, not conjugate with each other in $G$. Assume that $ab$ has finite order $n$. Then $\langle a, b \rangle$ is a dihedral group of order $2n$ and $n$ is even.
Proof. The fact that $\langle a, b \rangle$ is a dihedral group of order $2n$ is classical (Rotman 1999, theor. 3.32, p. 68). Assume (absurdly) that $n$ is odd. Then the order of $\langle a, b \rangle$ is even and not divisible by 4, thus the Sylow 2-subgroups of $\langle a, b \rangle$ are its subgroups of order 2, thus (Sylow) all the subgroups of order 2 of $\langle a, b \rangle$ are conjugate in $\langle a, b \rangle$, thus all the elements of order 2 of $\langle a, b \rangle$ are conjugate in $\langle a, b \rangle$, thus $a$ and $b$ are conjugate in $\langle a, b \rangle$ and thus in $G$, contradiction.
Here is another proof that $n$ is even. If $n$ was odd, say $n = 2k + 1$, we would have $(ab)^{2k+1} = 1$, $(ab)^{k} a (ab)^{-k} = b$ thus $a$ and $b$ would be conjugate, contradiction.
$\mathbf{Theorem.}$ Let $G$ a finite simple group whose Sylow 2-subgroups are Klein groups. Then all the elements of order 2 of $G$ are conjugate.
Proof. Assume first that
(hyp. 1)$\qquad $ there exists an element $t$ of $G$ such that the number of conjugates of $t$ is of the form $2r$, with $r$ odd.
Then, by Lemma 1, every element of order 2 of $G$ commutes with (at least) one conjugate of $t$. In other words,
(2)$\qquad$ every element of order 2 of $G$ is conjugate in $G$ with an element (of order 2) of $C_{G}(t)$.
On the other hand, since the order of $G$ is divisible by 4 and not by 8, it results from (1) that $\vert C_{G}(t) \vert$ is divisible by 2 and not by 4. Thus the Sylow 2-subgroups of $C_{G}(t)$ are its subgroups of order 2, thus (Sylow) the subgroups of order 2 of $C_{G}(t)$ are conjugate in $C_{G}(t)$, which amounts to say that the elements of order 2 of $C_{G}(t)$ are conjugate in $C_{G}(t)$. With (2), this proves that all the elements of order 2 of $G$ are conjugate in $G$. Thus the theorem is true in our hypothesis (1), thus we can assume that this hypothesis is not satisfied, i.e.
(3)$\qquad$ for every element $t$ of $G$, the number of conjugates of $t$ in $G$ is odd or divisible by 4.
Assume that (absurdly),
(hyp.4)$\qquad$ there exist two elements $a$ and $b$ of order 2 of $G$ which are not conjugate in $G$.
Let $n$ denote the order of $ab$. By Lemma 2, $n$ is even and $\langle a, b \rangle$ is a dihedral group of order $2n$ (and thus of order divisible by 4).
Assume that (absurdly)
(hyp. 5)$\qquad n$ is not equal to 2.
Then, since $n$ is even and $G$ has no element of order 4, $n$ is not a power of 2, thus the dihedral group $\langle a, b \rangle$ has at least one element $t$ of odd prime order $p$, In a dihedral group, every element of odd order is conjugate to its inverse, thus $t$ and $t^{-1}$ are conjugate in $\langle a, b \rangle$. A fortiori,
(6)$\qquad t$ and $t^{-1}$ are conjugate in $G$.
Let $t'$ be a conjugate of $t$ in $G$. Then $t'$ is of order $p$. Since $p$ is odd and $\neq 1$, $t'$ and $t'^{-1}$ are distinct. Moreover, in view of (6), $t'$ and $t'^{-1}$ are conjugate in $G$. Thus the conjugates of $t$ in $G$ are in even number, thus, in view of (3), the number of conjugates of $t$ in $G$ is divisible by 4. Since the order of $G$ is divisible by 4 and not by 8, this implies that
(7)$\qquad \vert C_{G}(t) \vert$ is odd.
But $t$, being of order different from 2, is in the unique cyclic subgroup $C$ of index 2 of the dihedral group $\langle a, b \rangle$. Since $C$ is abelian, $C$ centralizes $t$, thus $C_{G}(t)$ contains $C$. But the order of $C$ is $n$ and is thus even, thus $C_{G}(t) \vert$ is even, which contradicts (7). Thus our hypothesis (5) is false, thus (always in our hypothesis 4), $n = 2$, in other words the order of $ab$ is 2, which implies that $a$ and $b$ commute. Thus we have proved that
(8)$\qquad$ for all elements $a, b$ of order 2 of $G$ which are not conjugate in $G$, $a$ and $b$ commute.
If $a$ and $b$ are two such elements, then, every conjugate $b'$ of $b$ in $G$ is an element of order 2 which is not conjugate to $a$, thus the hypotheses on $a$ and $b$ in (8) are satisfied by $a$ and $b'$, thus every conjugate of $b$ commutes with $a$, thus
(9)$\qquad$ the subgroup of $G$ generated by the conjugates of $b$ is contained in $C_{G}(a)$.
But the subgroup of $G$ generated by the conjugates of $b$ is a nontrivial normal subgroup of $G$, thus, since $G$ is assumed to be simple, the subgroup of $G$ generated by the conjugates of $b$ is the whole $G$, thus (9) means that $C_{G}(a) = G$, thus $a$ is central in $G$, which is impossible, since $G$ is a nonabelian simple group. Thus our hypothesis (4) is absurd, which proves the theorem.
We can conclude from this theorem that (if $G$ is a simple group whose Sylow 2-subgroups are Klein groups), then, for every Sylow 2-subgroup $V$ of $G$, the three elements of order 2 of $V$ are conjugate in $N_{G}(V)$. (Rotman 1999, Lemma 7.49, p. 196.) So, we have proved, without transfer theory, that if $G$ is a simple group whose Sylow 2-subgroups are Klein groups, then case (i) of the Statement 1 above holds.
Do you think my formulation of the proof is better than Burnside's, or do I see difficulties wherd there is none?


text:
Q: Trying to connect my board and winCombos array in javascript for tic-tac-toe I am trying to connect my winCombos array with my data-indexes on my board so that they reference eachother. I am trying to start the first steps of my check win function but cannot wrap my head around this. Any help would be appreciated. Thank you.
HTML:

Javascript:
    const winCombos = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ]

function which(event) {
    console.log(`Index ${event.target.dataset.index} got clicked!`);

    if (count % 2 == 1 && event.target.classList.contains('unselected')) {
        count++
        event.target.innerHTML = '';
        turn.innerHTML = "O Player's Turn";
        event.target.classList.remove('unselected');
        event.target.classList.remove('selectedX');
        event.target.classList.add('selectedO');
    }
    if (count % 2 == 0 && event.target.classList.contains('unselected')) {
        count++
        event.target.innerHTML = '';
        turn.innerHTML = "X Player's Turn";
        event.target.classList.remove('unselected');
        event.target.classList.remove('selectedO');
        event.target.classList.add('selectedX');
    }

}

function checkWin() {
    if (winCombos[0].classList.contains(selectedX)) {
        console.log('win')
    }
}
checkWin();

A: Here's something for you to play with.
Basically, if the squares found at all 3 positions in one of the sub-arrays are both the same and belong to a player, that player wins.
What I do is grab the text from the first square mentioned in one of the items in the winCombos array. I then check to make sure it holds something, exiting if not. I then check that both the 2nd and 3rd elements match the first.
Hope you find it useful.

"use strict";
window.addEventListener('load', onLoaded, false);
function onLoaded(evt)
{
    document.querySelector('div').addEventListener('click', onBoardClicked, false);
}

const winCombos = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];

function onBoardClicked(evt)
{
    let elem = evt.target;

    if (elem.classList.contains('box') == false)
        return;

    if (elem.classList.contains('unselected'))
    {
        elem.classList.remove('unselected');
        elem.classList.add('selected')
        elem.textContent = 'X';
        checkWin();
    }
}

function checkWin()
{
    let squares = document.querySelectorAll('div.box');

    for (var comboIndex=0,n=winCombos.length; comboIndex<n; comboIndex++)
    {
        let curCombo = winCombos[comboIndex];
        let value = squares[curCombo[0]].textContent;
        if (value !== '')
        {
            if (squares[curCombo[1]].textContent == value && squares[curCombo[2]].textContent == value)
            {
                alert(`Winner, winner - player ${value}`);
            }
        }
    }
}
.box
{
    display: inline-block;
    width: 48px;
    height: 48px;
    background: #bbb;
    line-height: 16px;
    vertical-align: middle;
}
.board
{
    width: 160px;
    height: 160px;
    display: block;
}


text:
Q: django form with select fields I have the following models
class Group(models.Model):
    name = models.CharField(max_length=32, unique=True)

class Subgroup(models.Model):
    name = models.CharField(max_length=32, unique=True)
    group = models.ForeignKey(Group)

class Keywords(models.Model):
    name = models.CharField(max_length=32, unique=True)
    subgroup = models.ForeignKey(Subgroup)

For each Subgroup I need to manage a list of keywords.
I'm trying to use django forms to automatically display a list (select box) where if I add or remove values to that list and then issue a form.save that it automatically updates the models and data.
How exactly can I do this? Are my models designed properly to allow this?

A: I think you can create form with MultipleChoiceField:
class MyForm(forms.Form):
    to_select = forms.MultipleChoiceField(widget=forms.CheckboxInput, choices=[])

In this case you have to override form`s save method.
Did you try to create model form for subgroup class?
class MyForm(forms.ModelForm):
    class Meta():
        model=Subgroup


text:
Q: Should I use Get or Load - nhibernate? I am wondering which one I should use in this situation. I have a dropdown list that send a value back to the server. The server currently uses load and make the object. It then grabs a value out of and tries to convert it to an enum.
After doing some reading it seems that I should just use Get as I am need to access something out of the object other than the PK.

A: In general, use Get if you need access to properties other than the Id itself; this makes the intention of your code much clearer and is likely more efficient in the long run. Load is great if you need to setup FK relationships when creating or updating entities without making unnecessary round-trips to the database.
For further reading, check out Ayende's article that describes this in greater detail.

A: Get and Load are different if lazy loading is enabled.
If you use the method Load, NHibernate does not retrieve the entity from the database, but rather creates a proxy object and the only populated property is the ID.
If you access to an other property, NHibernate will load the entity from the DB.
So in your case the best use should be Get.


text:
Q: Can ubuntu run on one machine while being installed on another? I have a desktop computer on which the hard disk gave out. It is also connected by network to a brand new i5 desktop computer running Windows.
Is there a way in which I can install Ubuntu on a shared drive in the i5 computer and use it to run Ubuntu on the old computer?

A: That's a good question. I can only guide you in the right direction here, as even I don't know the correct way to go about it. It sounds like you might want to do something like PXE booting (booting over a network). One caveat that I am aware of: it has to be a wired connection. Beyond that, I haven't really done much research on it as I've never had the need to do such a thing.
You have to set up the host computer really specifically as well. I believe it has to have a TFTP server installed to work at a bare minimum.
I do know that you can use PXE boot to boot the Ubuntu installer, so I don't see why you couldn't use it to boot the whole OS. However, the installer runs totally in RAM, so you'd probably have to make some heavy modifications to Ubuntu to get it to run the full-fledged OS from a remote disk. Frankly, I don't even know that it's possible, but one thing I've learned in all my Linux years is that if you give it enough effort, anything's possible ;)
I was going to suggest a VNC server, but more than likely you're going to be running Windows on the main machine and not Ubuntu, so that wouldn't work out very well. However, you could install it in a virtual machine and set it as if it's just another computer on the physical network. Then you can, say, boot an Ubuntu LiveCD/USB from the dead computer and connect to the virtual machine hosting a VNC server, effectively making your HDD-less computer a thin client.


text:
Q: How can I quickly quickly see a readable mysql uptime? I'd like to quickly get uptime for mysql in a useful way, not just dump the seconds from GLOBAL STATUS and then do some math. Is there a way to accomplish this on Linux?

A: This little script dumps uptime in the format: "1 day 4 hours 35 minutes". It only lists seconds when that is the only current value over 0 and days when uptime is over 1 day.
#/bin/sh

# Prints the uptime of mysql
# Optional: Takes one argument for the servername, default is localhost

# Set $host
if [ $1 ]; then
  host=$1
else
  host="localhost"
fi

#Get Uptime in seconds from mysql server
s=`mysql -h $host --skip-column-names -e "select VARIABLE_VALUE from information_schema.GLOBAL_STATUS where VARIABLE_NAME='Uptime';"`

#Takes seconds, outputs human readable time
#Function Source: http://unix.stackexchange.com/a/170299/17808
converts()
{
    local t=$1

    local d=$((t/60/60/24))
    local h=$((t/60/60%24))
    local m=$((t/60%60))
    local s=$((t%60))

    if [[ $d > 0 ]]; then
            [[ $d = 1 ]] && echo -n "$d day " || echo -n "$d days "
    fi
    if [[ $h > 0 ]]; then
            [[ $h = 1 ]] && echo -n "$h hour " || echo -n "$h hours "
    fi
    if [[ $m > 0 ]]; then
            [[ $m = 1 ]] && echo -n "$m minute " || echo -n "$m minutes "
    fi
    if [[ $d = 0 && $h = 0 && $m = 0 ]]; then
            [[ $s = 1 ]] && echo -n "$s second" || echo -n "$s seconds"
    fi
    echo
}

#Convert seconds to readable time
converts $s


text:
Q: ChannelRead not invoked I have an existing application which uses java sockets to connect to a C++ server and send request and read response , I am trying to change java sockets to net based connection ..
I have a netty client and I am sending the same request through Netty client , I can see the request is being sent and my channel read is not invoked for me to read the response from the server
I see FLUSH , READ COMPLETE , FLUSH , INACTIVE and UNREGISTERED in the netty logs .
I need help on why the clients channel read method is not invoked ..
I am using Netty 4.1.10.Final and below is the client and the client handler code
public ChannelFuture connectLoop() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap clientBootstrap = new Bootstrap();

        clientBootstrap.group(group);
        clientBootstrap.channel(NioSocketChannel.class);
        clientBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        clientBootstrap.option(ChannelOption.TCP_NODELAY, true);
        clientBootstrap.remoteAddress(new InetSocketAddress("127.0.0.1", 8888));
        clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                //socketChannel.pipeline().addLast( new StringDecoder() ,new StringEncoder()  , new LineBasedFrameDecoder(1024), new ChannelHandlerAdapter(){
                socketChannel.pipeline().addLast("framer", new LengthFieldBasedFrameDecoder(1000000,0,4,0,4));//16KB

                socketChannel.pipeline().addLast("logger", loggingHandler);
               socketChannel.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
               socketChannel.pipeline().addLast("bytesDecoder", new ByteArrayDecoder());

                // Encoder
                socketChannel.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
                socketChannel.pipeline().addLast("bytesEncoder", new ByteArrayEncoder());
                socketChannel.pipeline().addLast(new NettyClientHandler());

            }
        });
        ChannelFuture channelFuture = clientBootstrap.connect().sync();

        this.channel = channelFuture.channel();
        //channelFuture.channel().closeFuture().sync();
        return channelFuture;

    } finally {

    }

}

    public void shutdown() {
        workGroup.shutdownGracefully();
    }

}

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

   @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Invoked -------------- > channel read complete");
        ctx.flush();
    }

    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {
        System.out.println("Invoked -------------- > Channel Active");

        super.channelActive(channelHandlerContext);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause){
        cause.printStackTrace();
        channelHandlerContext.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        System.out.println("Invoked -------------- > channel read");
        System.out.println("Client received:" + msg.toString());
        channelHandlerContext.close();
    }

}

This is how i am sending the message where msg is byte array
NettyClient nettyClient = new NettyClient(10500);
        ChannelFuture channelFuture = nettyClient.connectLoop();
        channelFuture.channel().writeAndFlush((msg)).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);


text:
Q: Why does setting the "disabled" property to false also remove the "disabled" attribute? I have a button which is initially disabled:
<button disabled="disabled">Lorem ipsum</button>

For this button, button.getAttribute('disabled') returns "disabled". However, when I enable this button with JavaScript:
button.disabled = false;

then button.getAttribute('disabled') starts returning null.
Live demo: http://jsfiddle.net/Rhj3c/1/
Why is that? Shouldn't .getAttribute() return the value from the original HTML source code? How do I then determine if the button was disabled in the original HTML source code?

A:
Shouldn't .getAttribute() return the value from the original HTML source code?

No, as per the specification (emphasis mine):

If a reflecting IDL attribute is a boolean attribute, then on getting the IDL attribute must return true if the content attribute is set, and false if it is absent. On setting, the content attribute must be removed if the IDL attribute is set to false, and must be set to the empty string if the IDL attribute is set to true. (This corresponds to the rules for boolean content attributes.)

How do I then determine if the button was disabled in the original HTML source code?

Check it before it changes. If the problem really is limited to "the original HTML source code" and not "what the element started out as" (for example, if it was created in JavaScript), that could be just a:
var originallyDisabled = Array.prototype.slice.call(
    document.querySelectorAll('[disabled]')
);
⋮
if (originallyDisabled.indexOf(button) !== -1) {
    …
}

A: The disabled attribute is a Boolean attribute and when present, it specifies that the  element should be disabled if not present then it's enabled and it could be used as:
<!-- Disabled -->
<button disabled>Lorem ipsum</button>

It could be used as a property (Example):
var button = document.querySelector('button');
console.log(button.disabled); // true if present, false if not

// Or this
console.log(button.hasAttribute('disabled')); // true if present false if not

Update (Example):
var input = document.querySelector('input');
input.value = 'Dynamic value';
console.log(input.getAttribute('value')); // "Initial value" attribute is in source
console.log(input.value); // "Dynamic value" property is in ram, rendered on the screen

Using input.value you set property in ram not in source, you need to use setAttribute to change thesource, is that you asked for ?


text:
Q: Is there certain functionality JDBC driver from MYSQL does not have? I am trying to find the type of data that a column is through the JDBC driver from MYSQL.
The query I am trying to execute is SHOW FIELDS FROM PARAMETERS WHERE FIELD='COLUMN_NAME' through Java and and the exception thrown is a java.sql.SQLException with the following error: Before Start of Result set. I am positive I am executing the same query as the one I am doing through SQL. Is there any other way of retrieving the column type with just the column name


text:
Q: JS - Motion Detect EventTrigger Constantly Triggering Function i'm working on a project in which i have a while() loop acting as an event listener. OnEvent i need to reset .currentTime in an html video.
the problem is, the event is triggered by a motion sensor, which whenever activated is supposed to set the video at a current playtime. Because the motion sensor is always listening and always alerting when it detects motion, my video is also stuck in this loop, constantly being reset when the event listener is triggered instead of playing its full section. i can't seem to figure out a way around this.
since my code is quite long at this point, i'm simply going to include the event-listener and trigger function.
appreciate any help!
       function processWV() {
           var startTime = +new Date(),
               changed = false,
               f;

           context.drawImage(video, 0, 0, canvas.width, canvas.height);
           f = detectf();

           if (experimentType === MASK_EXPERIMENT) {
               drawMasks(f);
           } else {
               highlightf(f);

           }

            //console.log(+new Date() - startTime);

           setTimeout(processWV, 25);
       }

   function listening(f) {

       if (f == false) {
           section = 2;
           updateVideo();
           return false;
       } else {
           section = 1;
       }

       for (var i = 0; i < f.length; i++) {
           var f = f[i];
           context.fillRect(f.x, f.y, f.width, f.height);
       }

   }

   function updateVideo(){
                console.log('update');
               $("#video")[0].currentTime = 14;
   }

A: you need to give the trigger function additional params to ensure that it exits the beginning of section 2.
if it's looping, it's probably just being called to to that same spot over and over again. what you should do is say something like:
if(section==2 && video.currentTime < whatever_section_1_end_time_is){
set to section 2;
}

hope that makes sense.


text:
Q: How to concatenate jsx in styled components I have trouble adding padding to a component.
This is the current code (it works fine)
padding: ${props =>
  props.isMobile && props.variant === "a"
    ? Spacing.Large
    : Spacing.Small};

However I want the padding to only be top and bottom and the side to be 0, so I want to do something like this: (notice the 0's)
padding: ${props =>
  props.isMobile && props.variant === "a"
    ? 0 Spacing.Large
    : 0 Spacing.Small};

But it will give me a syntax error, what is the correct way to handle this?

A: padding takes a string value, so when you do the ternary statement, you need to make sure it's a string.
padding: ${props =>
  props.isMobile && props.variant === "a"
    ? `0 ${Spacing.Large}`
    : `0 ${Spacing.Small}`};

This will make sure the ternary is properly executed.


text:
Q: How to get mongodb to start at boot time in Ubuntu I have a stock install of Ubuntu 14, installed a few weeks ago. I installed mongodb with apt-get. When I run
sudo service mongodb start

then the service runs correctly and I can access all the mongodb goodness. However, whenever I reboot it will not start automatically. I have tried running update.rc or whatever it is called, and it claims to run successfully however still no luck.
Is this a known issue? How can I diagnose it? And I guess, most importantly, how can I make it start at reboot?

A: For adding any service to startup try:
sudo update-rc.d <service_name> defaults

If that doesn't work you can add your start command in /etc/rc.local before the line exit 0


text:
Q: Android flash restart. OnDestroy called before/while OnResume I have numerous crashreports that only can occur under the condition, that OnDestroy is called before or while OnResume is executed.
In this case I initialize the class with the context. I have crashreport with null reference exception in getDefaultSharedPreferences which can only occur when this.context is null. this.context is null only when CalledByOnDestroy was executed.
How can this be?
   public public class ImageProcessor {

        private Context context;

        // called by OnCreate
        public ImageProcessor(Context context) {
             this.context = context;
        }

        public void OnDestroyHandler() {
            this.context = null;
        }

        @Override
        public void OnResumeHandler() {
            this.frameId = 0;
            SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.context);
        }
    }

A: In OnResumeHandler you can check if this.context == null , if is not then get the defaultSharedPreferences


text:
Q: Does defining initialize for a singleton class make sense in Ruby? I anticipate that I am not trying to do anything practical here, just trying to understand some deeper Ruby concepts.
Supppose I have the following code
class Bookshelf
  @book_qty = 100 # class instance var

  class << self
    attr_accessor :books_qty
  end

  def initialize
    @book = "This book is in every object as an object instance variable"
  end

  # so far so good, but what happens with...

  def self.initialize   # what would be this called on ?
    puts " and at what step would this be printed, if ever?"
    # I thought it would be printed when the class code is parsed first time,
    # but no
  end

  # or also

  class << self
    def initialize
      puts "same here"
    end
  end

end

I know it might not make sense or might be too intricately related on how Ruby internals work, but, if by chance anyone has been puzzled too by this and knows the answer... please share it :)

A: There is no purpose to defining initialize for the singleton class (whether you use def self. or class << self). initialize is only called by Class#new and...
Bookshelf.singleton_class.new
# TypeError: can't create instance of singleton class

that's not allowed.
If you want code to be executed the first time a class is parsed, just put it in the class
class Bookshelf
  puts "class defined!"
end

A: In some cases, it does make sense to define a custom constructor, but I wouldn't call the method initialize, since the instance method you override to customise initialisation is also called initialize. That would be a little confusing.

def self.initialize   # what would be this called on ?

If you define a method like this, you can invoke it by sending the method directly to the class:
Bookshelf.initialize

Same thing applies for methods defined inside class << self.
As mentioned, it does make sense to define custom constructors for a class. Sometimes just for readability's sake:
class Bookshelf
  attr_accessor :book_qty

  def self.with_quantity(quantity)
    new(quantity)
  end

  def initialize(quantity)
    self.book_qty = quantity
  end
end

Now you could instantiate a Bookshelf like this:
bs = Bookshelf.with_quantity 100
bs.quantity # => 100

You actually call .new on the singleton class of Bookshelf. And #initialize is basically just a hook for the instance to tweak its initialisation.
How you could access class instance variables
class Bookshelf
  @book_qty = 1000
  class << self
    attr_accessor :book_qty
  end
end

Bookshelf.book_qty # => 1000
Bookshelf.book_qty = 2000
Bookshelf.book_qty # => 2000


text:
Q: PL/SQL: statement ignored when inserting I'm trying to create a stored procedure that can only be executed in the month of march based on system date. Here is a snippot of such code:
CREATE PROCEDURE sp_time_window (
    p_sales_ID    in sales.sales_ID%TYPE,
    p_product     in sales.product%TYPE,
    p_unitCost    in sales.unitcost%TYPE,
    p_quantity    in sales.quantity%TYPE)

    IS BEGIN
    DECLAR v_date varchar(3)

    BEGIN

    SELECT TO_CHAR(sysdate,'MM') into v_date from duaL

    IF (v_date in ('MAR')) THEN
       INSERT INTO sales (sales_ID, product, unitcost, quantity) values
       (p_sales_ID, p_  product, p_unitCost, p_quantity);
   ENDIF;
   END;
   END;
    /

ORACLE gives me this error:
LINE/COL      ERROR
--------     ---------------------------------------------------
14/2          PL/SQL: SQL Statement ignored
16/5          PL/SQL: ORA-00933: SQL command not properly ended

please help

A: You have a redundant layer of BEGIN/END, and various typos, some of which I think you've just introduced creating the question, like DECLAR instead of DECLARE. But the first thing that might get that error is the missing semicolon after dual.
SELECT TO_CHAR(sysdate,'MM') into v_date from duaL;

You can assign the month value directly to the variable without the select from dual anyway:
v_date := TO_CHAR(sysdate,'MM');

... but as you have that defined as varchar2(3) and later look for MAR, that format mask should be MON not MM. However, using numbers is safer anyway, otherwise you need to be sure your session is in English. Your variable should be the appropriate type.
You also have a spaces in p_  product, and ENDIF instead of END IF, but again those might not be in your real code.
You can reduce what you have to:
CREATE OR REPLACE PROCEDURE sp_time_window (
    p_sales_ID    in sales.sales_ID%TYPE,
    p_product     in sales.product%TYPE,
    p_unitCost    in sales.unitcost%TYPE,
    p_quantity    in sales.quantity%TYPE)
AS
BEGIN
    IF extract(month from sysdate) = 3 THEN
       INSERT INTO sales (sales_ID, product, unitcost, quantity)
       VALUES (p_sales_ID, p_product, p_unitCost, p_quantity);
   END IF;
END;
/

The extract(month from sysdate) gets the month number from the date, so you can check if that is 3, as a number not a string. You also don't need the local v_date variable if you do that extraction in the IF clause.
Silently ignoring the insert seems odd, as the caller will no have no idea if that happens. And this won't stop inserts outside the procedure. In this case it might be appropriate to use a trigger that raises an exception if the month number is not 3.


text:
Q: Python Socket Request Handler I have a problem with the actual handling of a client/ server System.
For a project I have a control unit, to which sensor data is sent.
After that, I want the Control Unit to send the data to a server, where the data is captured.
So now I have a client (HoloLens2), which connects to the server over a TCP-connection and requests data.
The Problem now, is that i don't know exactly how I should handle those different requests.
I've already coded the following lines for the server.
With this I am able to successfully open the TCP-Connection:
import socket
import threading

HEADER = 64 # Length of HEADER-message
HOST = socket.gethostbyname(socket.gethostname())
PORT = 28500  # Port to listen on (non-privileged ports are > 1023)
ADDR = (HOST, PORT)
FORMAT = 'utf-8'
DISCIONNECT_MESSAGE = "!DISCONNECT"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

#Setup for listening. This function runs for each client
def handle_client(connection, cl_addr):
    print(f"[NEW CONNECTION] {cl_addr} connected.")

    connected = True
    while connected:
        #Wait on this line until we receive a message with 64 bytes
        msg_length = connection.recv(HEADER).decode(FORMAT)

        #Read out the information about the followed message in the HEADER-Message
        msg_length = int(msg_length)
        #Receive the actual message
        msg = connection.recv(msg_length).decode(FORMAT)

        if(msg == DISCIONNECT_MESSAGE):
            connected = False

        print(f"[{cl_addr}] {msg}")
    connection.close()

#start socket server
def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {HOST}")
    while True:
        #Wait on this line until new connection established
        conn, addr = server.accept()

        #when connection successfull, start new thread
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1} ")

print("[STARTING] server is starting . . .")
start()

If I now want to send different data for different requests, for example when the message is "!SENSOR1",
I want to send all the data captured of the sensor.
Do I have to implement the whole thing simply with if-else query like this:
if(msg == "!SENSOR1"):
            connection.send("This is the data from sensor 1: ")

Or is there a much more efficient way to handle this problem?