Q:

Reverse sign of number stored as string

This is a trivial operation but it has revealed some tricky points.
I have a string in PHP, say '234.00'. I want to convert that to a negative number, and preferably get a string in the end. So the test cases should be
'234.00'  ==> '-234.00'
'-234.00' ==> '234.00'
'0.00'    ==> '0.00'

The original code was
$signReversed = $stringNumber * -1.0

but that has problems because I really need a string for consistency with other code. So I tried
$signReversed = strval($stringNumber * -1.0)

but this fails on the last test case, because I get '-0' -- negative zero as a string.
Suggestions on the best way to do this?

A:

What about this
should work for small numbers, large numbers and strings can contain NULL bytes
function flipSign($stringNummer) {
   if ((string)$stringNummer !== $stringNummer) // fast !is_string check
      throw new Exception('input should be a string');
   return number_format($stringNummer * -1, 2, '.', '');
}

/**
 * NULL byte test
 */
var_dump(flipSign("00\0.10"));   // string(5) "-0.10"
var_dump(flipSign("-00\0.10"));  // string(4) "0.10"

var_dump(flipSign("00.10"));   // string(5) "-0.10"
var_dump(flipSign("-00.10"));  // string(4) "0.10"

var_dump(flipSign("234.00"));   // string(7) "-234.00
var_dump(flipSign("-234.00"));  // string(6) "234.00"

var_dump(flipSign("234.20"));   // string(7) "-234.20"
var_dump(flipSign("-234.20"));  // string(6) "234.20"

var_dump(flipSign("100000.20"));   // string(10) "-100000.20"
var_dump(flipSign("-100000.20"));  // string(9)  "100000.20"


Q:

Copy rows automatically to new sheet with Google Apps Script

I have a spreadsheet with some information on, and I want it to copy across to a second sheet automatically. I also want it to copy across automatically when I insert new rows within the rows copied across. I found the code below but I don't completely understand what I would have to do to it for it to do what I want, or if I would need to add anything. I have basic coding knowledge but not much, so if someone could explain this it would be much appreciated.
function myFunction() {
var source = SpreadsheetApp.openById('xxxxxx');
var sourcesheet = source.getSheetByName('sheet1');
var target = SpreadsheetApp.openById('xxxxx')
var targetsheet = target.getSheetByName('sheet1');
var rangeValues = sourcesheet.getRange(2, 1, sourcesheet.getLastRow(), sourcesheet.getLastColumn()).getValues();
targetSheet.appendRow(rangeValues);
}

A:

You can do it much more simply by using the =IMPORTRANGE() function, e.g. =IMPORTRANGE("https://docs.google.com/spreadsheets/d/10X7KGGFd4U8IwQO4QgunmLMphtwwEF9bGwfu3Vrm3AM/","Sheet1!A:Z")
Put this formula in the second spreadsheet, replace the URL with the URL of the first spreadsheet (I just put an example one) and tweak the "sheet_name!range" with what you need. The 2nd spreadsheet will then automatically update whenever the inputted range of the 1st spreadsheet changes :)
Hope this helps!


Q:

Upload and fetch MySQL polygons to Python

I have to store some polygons in a MySQL database.
I insert a polygon into the database using a query from the MySQL manual
SET @g = 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))';
INSERT INTO geom VALUES (111, ST_GeomFromText(@g));

The columns of the table are id and polygon, the type of the latter column is POLYGON, but I have the same issue if it is set to GEOMETRY.
Then I fetch the polygon from the database (using sqlalchemy) and the result will be bytes.
So I try to convert it into Shapely
from shapely import wkb
from sqlalchemy import create_engine
import pandas as pd

my_engine = ... # sqlalchemy engine connecting to the database
df = pd.readsql('SELECT polygon FROM geom WHERE id = 111;', my_engine)
p = df.polygon[0]
wkb.loads(p)
>>> <shapely.geometry.point.Point at 0x7f1896b01b38>

I get a point not a polygon. What could be the issue?

A:

Without using any of the geometry format conversion functions you're selecting the internal geometry format used by MySQL. The reason why you get a Point is that this internal format for your polygon begins with:
b'\x00\x00\x00\x00\x01\x03\x00\x00\x00\x02\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00...'

Interpreted as WKB it is:

00: Big endian
00 00 00 01: POINT (2D)
03 00 00 00 02 00 00 00: X-coordinate
05 00 00 00 00 00 00 00: Y-coordinate

The solution is to use a suitable conversion function in your query:
df = pd.read_sql("""
    SELECT ST_AsWKB(polygon) AS polygon
    FROM geom
    WHERE id = 111;""", my_engine)


Q:

using asp.net mvc3 with jquery.validate.unobtrusive.js to validate form and changebutton

I am working with mvc3 and use model validation like this:
    public class ColumnVM {
    [Required(ErrorMessage = "Required")]
    public string Name { get; set; }}

I want to do clientside validation with model validation.
My html is :
@using(Html.BeginForm("AddColumn","Column",FormMethod.Post))
@html.TextBoxFor(model=>model.Name)
@Html.ValidationMessageFor(model=>model.Name)
<input type="submit" value="submit" style="background-color:blue">

I want to do the client validation before submit.If the submit is valid,the submitbutton change its color and disbled itself calling:function changeBtnColor(obj) {
    obj.css("background-color", "#A9A9A9");
    obj.attr("disabled", "disabled");
}
If not,do not change its color and do not disable,and show validation error message.
When  jquery.validate.unobtrusive.js is in,I cannot use $("form").validate() any more. How can I do this task?

A:

Include this script after the jquery, jquery validate and jquery validate unobtrusive scripts
<script>
    $(function () {
        $("form").validate().settings.submitHandler = function (form) {
            alert('valid form');
            // do your stuff here
            form.submit();
        }
    });
</script>


Q:

Como fazer com que o R repita uma requisição?

Estou tentando extrair dados do Vagalume pelo R, para isso, utilizei o pacote "vagalumeR", e tirei um exemplo de código daqui: https://brunaw.github.io/vagalume/vagalumeR.html
O problema: ao tentar extrair as letras das música de determinados artista eu recebo um erro, quase sempre, mas nem sempre, o que me faz presumir que o erro seja fruto de uma instabilidade da API. sendo assim, gostaria de saber como fazer com que o R repita a solicitação até que a letra seja de fato extraida.
library(vagalumeR)
library(plyr)
library(tidyverse)
artist <- "portela"
song <- songNames(artist)
let <- ldply(map(song$song.id[1:62], lyrics, type = "id",
                 key = key), data.frame)

Error in if (cont$mus[[1]]$lang > 1) { : argument is of length zero

A:

Tentar até conseguir
A seguinte solução não é nem eficiente nem elegante, mas faz o que você pediu.
lyrics2 <- function(x, type, key) {
  # Tenta pegar dados
  res <- try(lyrics(x, type = type, key = key))
  if (inherits(res, 'try-error')) { # verifica se houve erro
    cat('Um erro ocorreu com a música de id:', as.character(x), '\n')
    Sys.sleep(abs(rnorm(1, 2)))
    return(lyrics2(x, type, key)) # faz chamada recursiva
  }
  res # retorna resultado caso não haja erro
}

A ideia da lyrics2 é basicamente tentar chamar a função e, se um erro ocorrer, chamar esta função  que verifica o erro (lyrics2) recursivamente. Desta maneira ela só vai parar de se chamar quando não houver mais erro na requisição.
A função try() tenta executar o código dentro dela mas não para caso um erro ocorra. Neste caso ela devolve um objeto com a classe 'try-error' e com a mensagem do erro.
Se um erro tiver ocorrido, a função Sys.sleep() põe o sistema para "dormir". O argumento passado para ela é o valor absoluto de um número aleatório, que na média será 2. A ideia de fazer isso é ser "gentil" com o servidor.
Ocorre que o código fica rodando infinitamente (ou pelo menos durante muito tempo) porque há algum problema com a API em alguns IDs (como o '3ade68b8g2009b0b3').
let2 <- map(song$song.id, lyrics2, type = "id", key = key)

Eliminar falhas
Por este motivo, outra opções pode ser tentar executar o código uma vez e eliminar as falhas.
df_erro <- data.frame(
  id = 'erro', name = 'erro', song.id = 'erro',
  song = 'erro', language = NA_integer_, text = 'erro'
)
safe_lyrics <- safely(lyrics, otherwise = df_erro, FALSE)

O código acima usa alguns dos conceitos do pacote purrr (já carregado no tidyverse).
O primeiro deles é a ideia de uma função segura. A função safely() retorna a mesma função passada como primeiro argumento, mas com uma modificação: ela agora passará a retornar um resultado com duas listas. A primeira lista se chama result e contém o resultado caso tudo ocorra bem e a segunda se chama error e conterá a mensagem do erro. O segundo argumento passado é o resultado que deve retorna nos casos de erro. Ele é útil para permitir juntar os resultados posteriormente
O segundo é usar a função map_df('result') para mapear todas as listas que retorna do primeiro map para extrair o elemento 'result' delas e uni-las em um data.frame.
let3 <- map(song$song.id, safe_lyrics, type = "id", key = key) %>%
  map_df('result')

O resultado acima retorna um data.frame  com 62 observações, uma para cada música da Portela. Os erros voltam com o conteúdo de df_erro e podem ser verificado com which(let3$id == 'erro')


Q:

Multiple custom directives on 1 page with callbacks

I have created a custom directive (with some help from SO). It's a full page date picker which uses ngModel to set the date when the user selects a date. At the same time it calls a callback function which is set when the directive is added to the page. The problem is that if I put 2 date pickers on the page then it always tries to call the callback from the second one.
Here is the HTML...
<fp-date-picker ng-model="dateOne" on-select="dateSelectedOne()"></fp-date-picker>

<fp-date-picker ng-model="dateTwo" on-select="dateSelectedTwo()"></fp-date-picker>

Here is my directive with most of it removed for brevity
angular.module('directives').directive('fpDatePicker', ['$parse', function ($parse) {

    return {

        restrict: 'EA',
        require: 'ngModel',
        templateUrl: '/templates/fpDatePicker.tpl.html',

        link: function($scope, $element, $attrs, ngModel){

            // A callback executed when a date is selected
            var onSelectCallback = $parse($attrs.onSelect);

            // Set current month
            $scope.selectedDate = moment();

            // Set date when one is clicked
            $scope.selectDate = function(day){

                var selectedDay = day.number;
                var selectedMonth = $scope.currentMonth.format('MM');
                var selectedYear = $scope.currentMonth.format('YYYY');

                $scope.selectedDate = moment(selectedYear + '-' + selectedMonth + '-' + selectedDay, 'YYYY-MM-DD');

                // Update the model
                ngModel.$setViewValue($scope.selectedDate);

                // Call the on-select callback
                onSelectCallback($scope);

            };

        }

    };

}]);

And just in case it's needed, here is my directive template....

    <
    >

        {{day.number}}

I thought that the problem of it always using the callback from the last instance of the directive on the page might be something to do with variables in the link function being global to all instances of that directive, or $attrs not being the attrs of the current instance of the directive, but I used console.log() to show the $attrs and it was different in each case.
I also wondered if it had anything to do with making the scope isolated, but although the callback functions sit on the scope, the expression in the attributes is not part of the scope, it's an attribute being passed in.
Very confused, any help would really be appreciated.
UPDATE: Created a Plunkr
http://plnkr.co/edit/nU27Wjpu3UYCR9q6DnLw?p=preview

A:

Your problem comes from the fact that your directive does not rely on isolated scope. Both directive instances thus share the same scope. When the second directive  is created, it overrides all scope variables.
You can read more about isolated scope in the doc: https://docs.angularjs.org/guide/directive.
Here is a plunkr showing how to use isolated scopes:
http://plnkr.co/edit/U64sbukqfFW0NQmvIC1a
I have updated your markup to make it compatible with the controller as syntax:

    {{main.dateOne}}
    <fp-date-picker ng-model="main.dateOne" on-select="main.dateSelectedOne()"></fp-date-picker>

    {{main.dateTwo}}
    <fp-date-picker ng-model="main.dateTwo" on-select="main.dateSelectedTwo()"></fp-date-picker>

The main change in your directive definition, is the use of the scope attribute in the directive definition object to have an isolated scope:
.directive('fpDatePicker', function() {

    return {
      scope: {
        select: '&onSelect'
      },

      restrict: 'EA',
      require: 'ngModel',
      templateUrl: 'datepicker.html',

      link: function($scope, $element, $attrs, ngModel) { ... }
     };
  })

Please note your code still has issues with date selection. Clicking on a day will select the date of the previous day. I did not fix that. Let me knopw if you need help


Q:

How do use a custom data type with ngModel in Angular Dart

I'm building an app in AngularDart, and so far it's going well. I particularly love how easy it makes forms. However, I'm running into a little snag in that regard.
Basically what I want to do is have the ngModel of a given form element work with a different data type, converting back and forth between the two as needed. For example, I am using an <input type='number'/> element in my HTML, but on the dart business logic side of things I'd like to deal with that value as a Dart Decimal class (from here: https://pub.dartlang.org/packages/decimal) because I need to avoid floating point issues.
I make pretty extensive use of 2-way data binding and ngModel in my app because it's awesome and works well for this application. However, ngModel doesn't work in this particular case. Obviously I can work around it, but I'm hoping for a little more elegance. I'd like to be able to specify some class or function that would allow me to do type conversion with ngModel.
I've looked around on Google and in the documentation and suspect my solution has something to do with using a Form Control, although I'm a little confused on how exactly this would work. I'm having a hard time finding much relevant example code or documentation to what I'm trying to do. Maybe I'm barking up the wrong tree there.
Here's a super simplified example of what I'd like to be able to accomplish if I can figure out what I need to do:
@Component(
  selector: 'my-component',
  template: '...<input type="number" [(ngModel)]="thing.attr"/>...'
)
class MyComponent{

  DataObject thing = new DataObject();
}

class DataObject{
  Decimal attr;
}

I imagine this is something that I'm likely to run into a lot is the need to do type conversion, not just specifically in this case with the Decimal class, so any help or advice anyone has would be much appreciated.

Update
I was able to make some good progress based on Ted Sander's answer below, but it's still not quite working for me and I'm not sure why.
This is the code I ended up with:
import 'package:angular/angular.dart';
import 'dart:html';
import 'package:angular_forms/angular_forms.dart';

import 'package:decimal/decimal.dart';

@Directive(
  selector: 'input[type=decimal][ngControl],'
      'input[type=decimal][ngFormControl],'
      'input[type=decimal][ngModel]',
)
class DecimalValueAccessor implements ControlValueAccessor {
  final InputElement _element;

  DecimalValueAccessor(HtmlElement element) : _element = element as InputElement;

  @HostListener('change', ['\$event.target.value'])
  @HostListener('input', ['\$event.target.value'])
  void handleChange(String value) {
    print('About to parse decimal');
    Decimal dec;
    try{
      dec = new Decimal.parse(value);
    }
    catch (e){
      //TODO: mark feild as invalid
      return;
    }
    print('Got $dec with type ${dec.runtimeType}');
    onChange((value == '' ? null : dec), rawValue: value);
  }

  void writeValue(value) {
    _element.value = '$value';
  }

  void onDisabledChanged(bool isDisabled) {
    _element.disabled = isDisabled;
  }

  TouchFunction onTouched = () {};

  @HostListener('blur')
  void touchHandler() {
    onTouched();
  }

  /// Set the function to be called when the control receives a touch event.
  void registerOnTouched(TouchFunction fn) {
    onTouched = fn;
  }

  ChangeFunction<Decimal> onChange = (Decimal _, {String rawValue}) {};

  /// Set the function to be called when the control receives a change event.
  void registerOnChange(ChangeFunction<Decimal> fn) {
     onChange = fn;
  }
}

It seems to work okay going one way: if I change the value programatically it seems to pick it up and work fine. However, if I change it via the input, it throws an exception Type 'String' is not a subtype of expected type 'Decimal'.
I added some print statement as you can see, just to make sure the type conversion code is actually running. It prints out "About to parse decimal" and "Got 1.55 with type Decimal" as I would expect. However, I notice this shows up not before but after the exception is thrown in the console, which is really confusing me. Does anyone have any ideas on why this could be happening?

A:

Excellent question. The thing that you are looking for is the ControlValueAccessor. It is responsible for reading/writing/converting values from a DOM Element, or Component.
You can see the angular_forms number version here.
A more complicated angular_component version is here.
You'll want to create one of these that basically does what the angular_forms version does, but doesn't use double.parse. The directive that you create I would suggest giving it a selector of input[type=decimal] so that it doesn't conflict with the one provided by forms, and add that directive to your directives list in the components where you want to use it.
Glad you are liking AngularDart so far!


Q:

Is it possible to practice freestyle breathing with a kick board?

I have been trying to achieve "one goggle in the water" side breathing, but even using flippers and three kick boards to keep my body as high as humanly possible, basic face anatomy dictates that if my eye is underwater, half of my mouth is underwater. Now I read that "Your arms create pockets of air near your armpits as you reach ahead and stroke. Swimming coaches teach students to turn their heads to one side and draw a breath from the pocket." Does this mean that the kick board approach is impossible and the only way to practice side breathing is while you are doing strokes? I had thought it was the wake from your head that created the air pocket, which is why I was using flippers to move forward as fast as possible while holding the kick board.

A:

There are various breathing exercises for beginners with the kickboard:
If you are right handed and prefer breathing from the right,  then keep your left hand outstretched to the front of the board and the right hand bent and on the bottom side, then breathe from the right with normal kicking patterns by twisting your head to the right. The key here is to try to not tilt the heard upwards, only twist it to the right,  at that time, half of your face will be outside the water and you can then slowly breathe. If you're left handed,  then just switch sides.

A:

What the coaches mean, is that when you turn your head to the side, water forms kind of a "bow wave" coming off of your head/forehead, which causes a small trough (area of lower water) to form near your nose/chin, and it's in this pocket that you breathe. Yes, your eye will be underwater, but the bow wave moves the water away from the rest of your face.
Speed does help, but once you get used to it, you can have your mouth half full of water and still be able to breathe. As you get faster and faster, the bow wave effect is easier to do and clears your nose/mouth much better.
Use one kick board, and when you want to breathe, drop your hand off the board on that side, pull, then breathe during the arm recovery. This will help to develop your timing and encourage the body roll. You don't want to just turn your head only.


Q:

Matrix representation of the linear operator $A = \frac{d}{dx} + x \frac{d}{dx}$

$A = \frac{d}{dx} + x \frac{d}{dx}$ is an operator that acts on the vector space $P^n$ of all real valued polynomials of degree $\le n$. with respect to the standard basis $\{x_n\}_{n\in \mathbb{N}_0}$.
To find the linear operator I checked the "effect" of the operator on the basis:
$$\frac{d}{dx}(x^0) + x \frac{d}{dx} (x^0) = 0  \\
\frac{d}{dx}(x^1) + x \frac{d}{dx} (x^1) = 1 + x \\
\frac{d}{dx}(x^2) + x \frac{d}{dx} (x^2) = 0 + 2x + 2x^2 \\
\frac{d}{dx}(x^3) + x \frac{d}{dx} (x^3) = 0 + 0 + 3x^2 + 3x^3 $$
From here I concluded that in 4-dimension the operator would be represented by the matrix:
$$\left[ \begin {array}{cccc} 0&1&0&0\\ 0&1&2&0
\\ 0&0&2&3\\ {}0&0&0&3\end {array}
 \right] $$
but the correct seems to "exclude" the first column of zeros and instead the four dimension matrix is "a shift" to the left with the fourth column being: $[0,0,0,4]$.
Where did I go wrong?

A:

What you did looks fine to me, if you are using the basis $\{1,x,x^2,x^3\}$ for what you call $P^3$. (Are you certain that is the basis the book expects?)
Anywayno matter what the basis is supposed to be, the "shifted" answer you describe cannot be correct. It is nonsingular, but this operator annihilates nonzero constant functions.


Q:

AS3 sound sound specific timeline playing

I want to play a sound's specific time, i tried using position , but not gonna help , help me
please help me , i need to play a file from specific time to a specific time , i tried using current position , but how do i make it stop , i dont wanna use stop or close functions
        protected function application1_applicationCompleteHandler(event:FlexEvent):void
        {
            snd.load(ul);
            trace(snd.bytesTotal);
            trace(snd.bytesLoaded);
            trace(snd.isBuffering);
            snd.addEventListener(Event.COMPLETE,nad);
            snd.addEventListener(IOErrorEvent.IO_ERROR,rightu);

        }
        protected function rightu(event:IOErrorEvent):void
        {
            Alert.show("error");
        }
        public function nad(event:Event):void
        {

            trace(snd.bytesTotal);
            trace(snd.bytesLoaded);
            trace(snd.isBuffering);

            p1.enabled=true;
        }

        protected function p1_clickHandler(event:MouseEvent):void
        {
            if(p1.label=="PLAY")
            {
                sc=snd.play(pause);
                sc.soundTransform=st;
                p1.label="PAUSE";

            }
            else
            {
                pause= sc.position;
                sc.stop();
                p1.label="PLAY";

            }

        }

        protected function i1_clickHandler(event:MouseEvent):void
        {
            st.volume += .1;
            if(st.volume > 1)
            {
                st.volume = 1;
            }
            sc.soundTransform=st;
        }

        protected function d1_clickHandler(event:MouseEvent):void
        {
            st.volume -= .1;
            if(st.volume <0)
            {
                st.volume=0;
            }
            sc.soundTransform=st;
        }

        protected function pa1_clickHandler(event:MouseEvent):void
        {

            sc.stop();
            p1.label="PLAY";
            pause=0;

        }

        protected function test_clickHandler(event:MouseEvent):void
        {
            trace(sc.position);
        }

    ]]>
</fx:Script>
<s:HGroup horizontalAlign="center" verticalAlign="middle">

<s:VGroup verticalAlign="middle" horizontalAlign="center">
    <mx:ProgressBar id="q"/>
    <s:Button id="p1" label="PLAY" enabled="false" click="p1_clickHandler(event)" />
    <s:Button id="pa1" label="STOP" click="pa1_clickHandler(event)"/>
    <s:Button id="i1" label="INCREASE" click="i1_clickHandler(event)"/>
    <s:Button id="d1" label="DECREASE" click="d1_clickHandler(event)"/>
    <s:Button id="test" click="test_clickHandler(event)"/>
</s:VGroup>
</s:HGroup>

A:

If you want to play seconds 21-40 of a 60 second sound(which is what I think you are trying to do), then when you play the sound sound.play(21) then try adding an ENTER_FRAME event listener and checking the position of the channel to stop it at 40...
    private var stopPosition:int = 40000;
    private var pause:int = 21000; // set to 21 secs for example in code

    protected function p1_clickHandler(event:MouseEvent):void{
        if(p1.label=="PLAY"){
            sc=snd.play(pause);
            sc.soundTransform=st;
            p1.label="PAUSE";
            addEventListener(Event.ENTER_FRAME, checkPosition);
        } else {
            pause= sc.position;
            stopTheSound();
        }
    }

    private function checkPosition(event:Event):void{
         if(sc.position >= stopPosition){
              stopTheSound();
         }
    }

    private function stopTheSound():void{
         sc.stop();
         p1.label="PLAY";
         removeEventListener(Event.ENTER_FRAME, checkPosition);
    }


Q:

how can select a file from my file folder in android

how can browse a file (any type) from file manager. i am trying to using this code
Intent pickFileIntent = new Intent();
pickFileIntent.setAction(Intent.ACTION_GET_CONTENT);
pickFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickFileIntent.setType("*/*");
Intent chooserIntent = Intent.createChooser(pickFileIntent,
                           getText(R.string.choosefile_title));
startActivityForResult(chooserIntent, PICK_FILE_REQUEST);

this code is open the gallery and select the picture but  file not browse.
my LogCat error is
 02-19 16:46:19.846: E/ActivityThread(512): Failed to find provider info for com.navjagpal.filesharer.FileProvider

i am beginner in android.please help me with a sample code .
thanks in advance.......

A:

Specify full path in Authorities tag in manifest file ( SearchableDictionary sample code in SDK).
<provider android:name=".DictionaryProvider"
       android:authorities="com.example.android.searchabledict.DictionaryProvider"


Q:

Specify a TTL in the messages using WCF

I would create a WCF service with some methods: one of these methods would have a TTL (Time To Live) argument of byte type in order to set the maximum radius of forwarding to other nodes.
Since IP packets have a TTL field, is it possible to set this field using WCF in order to reach the same target?
Thanks a lot!

A:

for usual Socket communication you could do it with this:
Socket.Ttl Property
for WCF I'm not sure you can control it in the same way, for MSMQ bindings there ius a TimeToLive property of the binding as TimeSpan but is not the same thing as changing the TTL at the IP level, see here: WCF / MSMQ "time-to-be-received has elapsed" dead letter queue issue
I'm not sure if you could write your own WCF binding and be able to push to your value to the underlying socket as in the first link I mentioned above...


Q:

Count number of events before certain events until another event is encountered in the same group in Big query?

I want to count some certain values until a specific event occurred in SQL. This is very similar question to this question:
Count number of events before and after a event “A” till another event “A” is encountered in Big query?
The answer to this question didn't solve my problem which I am confused with RANGE BETWEEN 1 PRECEDING AND 1 PRECEDING too. Differently from that question I don't look for strings but I want to count other events.
My table would be like
   User       Event   Day
    1          C     2019-01-10
    1          B     2019-01-11
    1          D     2019-01-12
    1          A     2019-01-13
    2          D     2019-01-10
    2          B     2019-01-11
    2          C     2019-01-12
    2          D     2019-01-13
    2          A     2019-01-14
    2          E     2019-01-15

I would like to count C or D until event A or B occured.
I try
COUNTIF(Event = 'C' OR Event = 'D') OVER(PARTITION BY User ORDER BY Day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS count_events
But this doesn't stop counting until event A or B. It counts all C or D events in partition.
My result table would look like this and the counting would stop if one of the event is occurred and restart counting again when the expected event occurs.
   User       Event   Day           count_events
    1          C     2019-01-10           0
    1          B     2019-01-11           1
    1          D     2019-01-12           0
    1          A     2019-01-13           1
    2          D     2019-01-10           0
    2          B     2019-01-11           1
    2          C     2019-01-12           0
    2          D     2019-01-13           1
    2          A     2019-01-14           2
    2          E     2019-01-15           0

A:

Below is for BigQuery Standard SQL
#standardSQL
SELECT * EXCEPT(grp),
  COUNTIF(event IN ('C', 'D'))
  OVER(PARTITION BY user, grp ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) count_events
FROM (
  SELECT *,
    COUNTIF(event IN ('A', 'B'))
      OVER(PARTITION BY user ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING ) grp
  FROM `project.dataset.table`
)

if to apply to sample data in your question - result is
Row user    event   day         count_events
1   1       C       2019-01-10  0
2   1       B       2019-01-11  1
3   1       D       2019-01-12  0
4   1       A       2019-01-13  1
5   2       D       2019-01-10  0
6   2       B       2019-01-11  1
7   2       C       2019-01-12  0
8   2       D       2019-01-13  1
9   2       A       2019-01-14  2
10  2       E       2019-01-15  0

You can test, play with above using below
#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 user, 'C' event, DATE '2019-01-10' day UNION ALL
  SELECT 1, 'B', '2019-01-11' UNION ALL
  SELECT 1, 'D', '2019-01-12' UNION ALL
  SELECT 1, 'A', '2019-01-13' UNION ALL
  SELECT 2, 'D', '2019-01-10' UNION ALL
  SELECT 2, 'B', '2019-01-11' UNION ALL
  SELECT 2, 'C', '2019-01-12' UNION ALL
  SELECT 2, 'D', '2019-01-13' UNION ALL
  SELECT 2, 'A', '2019-01-14' UNION ALL
  SELECT 2, 'E', '2019-01-15'
)
SELECT * EXCEPT(grp),
  COUNTIF(event IN ('C', 'D'))
  OVER(PARTITION BY user, grp ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) count_events
FROM (
  SELECT *,
    COUNTIF(event IN ('A', 'B'))
      OVER(PARTITION BY user ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING ) grp
  FROM `project.dataset.table`
)
-- ORDER BY user, day

I don't want to count last event C because it didn't occur before event A but after event A

Below is quick "fix"
#standardSQL
SELECT * EXCEPT(grp),
  COUNTIF(event IN ('A', 'B')) OVER(PARTITION BY user, grp) *
  COUNTIF(event IN ('C', 'D'))
    OVER(PARTITION BY user, grp ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) count_events
FROM (
  SELECT *,
    COUNTIF(event IN ('A', 'B'))
      OVER(PARTITION BY user ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING ) grp
  FROM `project.dataset.table`
)
-- ORDER BY user, day

If to apply to recent example you used - result is
Row user    event   day         count_events
1   1       C       2019-01-10  0
2   1       B       2019-01-11  1
3   1       D       2019-01-12  0
4   1       A       2019-01-13  1
5   2       D       2019-01-10  0
6   2       B       2019-01-11  1
7   2       C       2019-01-12  0
8   2       D       2019-01-13  1
9   2       A       2019-01-14  2
10  2       C       2019-01-15  0
11  2       E       2019-01-16  0


Q:

How can I pass data from parent to child view?

I have a container view, which uses a storyboard embed segue to load an embedded static table view. The segue ID is 'CONTAINER'.
When I run the following code, the prepareForSegue never actually gets called so no data is passed from the parent to the child.
 - (void)viewDidLoad {
[super viewDidLoad];

if ([sGender isEqualToString:@"MALE"]) {
    containerGender = @"MALE";

    if ([containerGender isEqualToString:@"MALE"]){
        NSLog(@"MALE");
    }else{
        NSLog(@"BROKEN");
    }
}
else if ([sGender isEqualToString:@"FEMALE"]) {
    containerGender = @"FEMALE";
}
}

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"CONTAINER"]) {
    if([containerGender isEqualToString:@"MALE"]) {

        if ([containerGender isEqualToString:@"MALE"]){
            NSLog(@"MALE");
        }else{
            NSLog(@"BROKEN");
        }

        SportTableViewController *tableView = segue.destinationViewController;
        tableView.sportGender = @"MALE";
    }
    else if ([containerGender isEqualToString:@"FEMALE"]){
        SportTableViewController *tableView = segue.destinationViewController;
        tableView.sportGender = @"FEMALE";
    }
}
}

My question is:
a)Why is prepareForSegue not called? Does the Storyboard Embed Segue behave differently to a standard seque?
b)Is there a better way of passing data from the container view to the embedded table?
Also please ignore the messy implementation/various log tests, just my attempts to work out whats going wrong.

A:

My question actually stems from a misunderstanding of how container views load their embedded views. Apparently, it all happens before viewDidLoad. That means my conversion of sGender into containerGender took place too late.
I fixed it by passing sGender to the embedded view directly. I had thought I'd already tried this, but yesterday was obviously a slow day ;).


Q:

How to get mouse press and release positions using bash

I want to get the mouses position when it clicks down, and then when its released in bash as 2 variables.
some thing like
press=( X Y )
release= ( X Y )

or
pressX
pressY
releaseX
releaseY

How can I do this?
I've already tried doing
xinput list | grep -Po 'id=\K\d+(?=.*slave\s*pointer)' | xargs -P0 -n1 xinput test | awk '{print $2}'

but I don't know how to process the output correctly…

A:

thank you @gst for the answer!
heres my edited version for other ppl in the future
MOUSE_ID=$(xinput --list | grep -i -m 1 'mouse' | grep -o 'id=[0-9]\+' | grep -o '[0-9]\+')
STATE1=$(xinput --query-state $MOUSE_ID | grep 'button\[' | sort)
while true; do
    sleep 0.2
    STATE2=$(xinput --query-state $MOUSE_ID | grep 'button\[' | sort)
    button=$(comm -13 <(echo "$STATE1") <(echo "$STATE2") | grep -Po "(?<=\=).*$")
    STATE1=$STATE2

    # if the mouse is clicked down - save the x and y coordinates into downX and downY
    if [ "$button" = "down" ]; then eval $(xdotool getmouselocation --shell); downX=$X;downY=$Y; fi
    # when the mouse is unclicked - save the x and y coordinates into upX and upY
    # then exit the while loop
    if [ "$button" = "up" ]; then eval $(xdotool getmouselocation --shell); upX=$X;upY=$Y; break; fi
done

EDIT:
I scrapped all this and used
slop=$(slop --padding=-1 --bordersize=2 -f "%x %y %w %h %g %i") || exit 1
read -r X Y W H G ID < <(echo $slop)

instead, since slop makes it so that your cursor cant select text etc while the mouse is down!


Q:

bugzilla template why does my string == return true for 2 different strings

My if(str == seltext) is returning true, all the time.
heres my code:-
[% FOREACH cll = classifications %]
    var str = "[% cll.object.name FILTER js %]";
    var seltext = classSel.options[classInd].text;
    alert(str+" "+seltext);
    if(str == seltext)
    {
        alert("classfound=[% cll %]");     /// THIS ALWAYS GETS FIRED
    }
[% END %]

I cannot understand why this is happening, I think it might be because the [% only gets saved the the variable str once, but they my alert wouldn't change.

A:

The way i fixed this was by revering the if statement so it goes like this
if(classSel.options[classInd].text == "[% cll.object.name FILTER js %]")

then it works


Q:

How to declare protocol for HKT in swift?

In Haskell, when using typeclass, it is easy to declare constraint of its' instances' type kind.
class Functor (f :: * -> *) where
  ...

* -> * represents HKT (Higher-Kinded Types), this means any type conforming to Functor must be a HKT.
How can I achieve this with Swift's protocol ?

A:

Swift does not support HKT as a type form natively, but you can simulate the constraint with a trick of associatedtype:
public protocol Functor {
    /// (* -> *)
    associatedtype FA: Functor = Self
    /// *
    associatedtype A
    /// fmap
    func fmap<B>(_ f: ((A) -> B)) -> FA where FA.A == B
}

And conformance example:
enum Maybe<A> {
    case just(A)
    case nothing
}

extension Maybe: Functor {
    func fmap<B>(_ transform: ((A) -> B)) -> Maybe<B> {
        switch self {
        case .nothing:
            return .nothing
        case .just(let v):
            return .just(transform(v))
        }
    }
}


Q:

Can't get numpy to import with python3.2

I have Ubuntu 12.04, and three different python builds on the machine (python2.7, python3, python3.2). I can only get packages to import in python 2.7. Whenever I try to import them in Python 3.2.3, I get:
Python 3.2.3 (default, Jan 14 2014, 13:11:14)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named numpy
>>>

I have seen various questions around Stack with similar issues, but none of them have fixed my issue.
For example, I have ran this code:
sudo apt-get install python3-numpy python3-scipy

With this result:
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-numpy is already the newest version.
python3-scipy is already the newest version.

So, it seems that I do have the packages installed for python3, but can't get them to load into the python3.2.3 environment.
    >>> sys.path
    ['', '/usr/local/lib/python32.zip', '/usr/local/lib/python3.2',
 '/usr/local/lib/python3.2/plat-linux2', '/usr/local/lib/python3.2/lib-dynload',
'/home/bre-dev-2/.local/lib/python3.2/site-packages', '/usr/local/lib/python3.2/site-packages']

All of the site-packages are empty, while numpy and scipy exists in the folder usr/lib/python3/dist-packages (notice there is no "local" in the path name).
And finally, when I change sys.path to contain the directory with numpy and scipy:
>>> sys.path[6]='/usr/lib/python3/dist-packages'
>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/numpy/__init__.py", line 137, in <module>
    from . import add_newdocs
  File "/usr/lib/python3/dist-packages/numpy/add_newdocs.py", line 9, in <module>
    from numpy.lib import add_newdoc
  File "/usr/lib/python3/dist-packages/numpy/lib/__init__.py", line 4, in <module>
    from .type_check import *
  File "/usr/lib/python3/dist-packages/numpy/lib/type_check.py", line 8, in <module>
    import numpy.core.numeric as _nx
  File "/usr/lib/python3/dist-packages/numpy/core/__init__.py", line 5, in <module>
    from . import multiarray
ImportError: cannot import name multiarray

Any suggestions? Starting to lose my mind....

A:

After the dectective work, as suspected :P, there was some other Python environment at work. Now, why is that there? :-D
If you want to use the system Python, force it with /usr/bin/python3. That would let you work with the Numpy you installed.
If you want to get the one under /usr/local/bin out of the way, just rename it so that it doesn't "shadow" the other Pythons in the system. Remember that /usr/local/bin takes precedence over /usr/bin in the path.


Q:

Show only (Low Search) shortcuts from logged in user

I am new to Low search, and happy I got shortcuts working.
My site is a member site, with memberdata in  a channel (Profile-edit) I want to show only shortcuts to the user that creates them (when they were logged in). Is there a way to filter shortcuts so that users only see their own shortcuts?
(And my apologies if I missed this in the docs)
(edit: I mean shortcuts created in the frontend, not collections)

A:

Thanks a lot Low, for you reaction.
In the meantime I found a 'dirty' solution:
I created a channel (called shortcut), and a form on the result page. URL as hidden field, the title of the entree in the channel 'shortcut'.
Now I can call these entrees made by AUTHOR and link them to the result page.
For the ones interested, this my (simple) code.
On result page:

{exp:channel:form channel="shortcut" return="zoek/opdrachten" entry_id="{segment_5}"}
    {if segment_4 == ""}

    <input type="hidden" name="url_title" id="url_title" value="{url_title}">
    <input type="hidden" name="entry_date" id="entry_date" value="{entry_date}">
    <input type="hidden" name="title" id="title" value="{segment_3}" onkeyup="liveUrlTitle();">

        <fieldset>
            <legend>CV</legend>
            Bewaar deze selectieGeef een beschrijving van deze zoekopdracht

                {field:shortcut_beschrijving}

            <input type="submit" value="Voeg toe">

        </fieldset>

    {/if}
{/exp:channel:form}

On the shortcut list page
{exp:channel:entries channel="shortcut"
    author_id="CURRENT_USER"
    disable="categories|category-fields|member-data"
    dynamic="no"
}

    {if no_results}Je hebt geen zoekopdrachten opgeslagen{/if}

    {count}
    {shortcut_beschrijving}

{/exp:channel:entries}


Q:

Adding QGraphicsView and QGraphicsScene to a label in Qt

I have a stacked widget on which I have a QLabel. I display an image on this label. I want to zoom and pan this image and I am trying to use the QGraphicsView technique. However a new window opens.
This is what I am doing.
 scene = new QGraphicsScene(this);
 view = new QGraphicsView(this);
 QPixmap pix("/root/Image);
 label->setPixmap(pix);
 scene->addWidget(label);
 view->setScene(scene);
 view->setDragMode(QGraphicsView::scrollHandDrag);
 view->show();

Can someone please suggest me what I should do. I want the label to act like the QGraphicsView.
Thank You :)

A:

You create a scene and view and add the label to the scene, then tell the view to show itself with: -
view->show()

If, as you state, you want the QGraphicsView on the label, don't add the label to the scene, but add the QGraphicsView to the label: -
QLabel* pLabel = new QLabel(mainWindow); // setting mainWindow as the parent
QGraphicsView* pView = new QGraphicsView(pLabel) // set the label as the parent of the view.

You do not need to call show, as the label will handle that for you, assuming the label is on a Widget that is already displayed.
Now, instead of setting the pixmap on the label, create a pixmap in the scene with: -
pScene->addPixmap(pixmap);


Q:

HBase java.lang.OutOfMemoryError

I'm having the following issue with Hbase.
I have a script which starts the HBase shell and inserts many rows into a table with a single column. I have tried inserting 10,000 rows but after about 1,700 I get the dreaded "java.lang.OutOfMemoryError: unable to create new native thread" error. I have tried changing the Java heap size from 1000mb default to 1800mb, but this doesn't allow me to insert any more than the 1700 or so rows.
However, I've noticed that I can insert 1000 rows, exit the shell, restart the shell, insert 1000 more into the same table, exit again, and so on and so forth. I don't really understand enough about the JVM to figure out why it's allowing me to do this in several sessions, but not allowing me to batch insert in the same session.
Can someone please explain to me what is going on here, and what I might do about it?
EDIT:
I am now using 64-bit machine, red hat linux 5, with Java 1.6. I'm giving HBase a heapsize of 20gb (I have ~32 gigs memory total).
For stack size, I'm giving 8mb. The default on 64-bit is 2mb I believe; with 2mb I got this same error, and increasing it to 8mb did not help at all (I was only able to insert the same amount of rows regardless of stack size, ~1700).
I have read that decreasing the heap size could make this error go away but that did not help either. Below are the jvm options that I'm setting (everything is default except for stack size).
HBASE_OPTS="$HBASE_OPTS -ea -Xss8M -XX:+HeapDumpOnOutOfMemoryError -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode"

A:

I encountered this error yesterday. What was happening in my case is that I was creating a lot of instances of HTable which created way too many threads when I was using the put on a record. (I was using a mapper and creating it inside the map function)
I'd check to see if your connection to HBase is being created a lot (inside a loop or a map function. If that is happening, then moving it to instantiate fewer connections to HBase (I used HTable) may solve the problem.
It solved mine.
HTH


Q:

Migration from solrj to spring-data-solr

Can't find full tutorial for spring-data-solr.
Have a question about migrating to spring-data-solr.
For example I have the following query on solarj:
SolrQuery query = new SolrQuery();
query.setQuery("*:*");
query.setParam("df", region);
query.setParam("fq", addType(param));
query.setParam("fl", region);
query.setRows(10000);
query.addSort(region, SolrQuery.ORDER.asc);

query.set(GroupParams.GROUP, true);
query.set(GroupParams.GROUP_FIELD, groupField);
query.set(GroupParams.GROUP_MAIN, true);
query.set(GroupParams.GROUP_FORMAT, "simple");
SolrTemplate server = /*initialization*/
server.execute(client -> client.query(SOLR_COLLECTION_NAME, query));

So how can I migrate this code to spring-data-solr Query class? Or even to SolrRepository if possible? You might wanna ask me what I have tried so far: now I tried to create solar query as:
Query query = new SimpleQuery("*:*");
query.setRows(10000);
query.addSort(new Sort(Direction.ASC, SCHOOL_REGION));

But how can I set params like "df", "fl", etc. and all of the group params? I don't see setters for it.
And the second question is can I use SolrCrudRepository for complicated query like this?

A:

This answer may help somebody, so:
spring-data-solr (v4.0.10.RELEASE) does not support DisMax Parameters, so you're not able to use these params by default, the solution was to create custom SolrQuery:
@Data
@EqualsAndHashCode(callSuper = true)
public class ExtendedQuery extends SimpleQuery {
    private List<String> queryFields;
    private String defaultField;
}

Then we can set these params like:
query.setDefaultField(SCHOOL_CITY);
query.setQueryFields(Arrays.asList("school_name^150.0", "school_city^30.0"));

One more thing you'll need is to create custom QueryParser:
public class ExtendedQueryParser extends QueryParserBase<AbstractQueryDecorator> {

    private final DefaultQueryParser defaultQueryParser;

    public ExtendedQueryParser(MappingContext mappingContext) {
        super(mappingContext);
        defaultQueryParser = new DefaultQueryParser(mappingContext);
    }

    @Override
    public final SolrQuery doConstructSolrQuery(
            AbstractQueryDecorator query, Class<?> domainType) {
        ExtendedQuery decoratedQuery = (ExtendedQuery) query.getDecoratedQuery();

        SolrQuery solrQuery =
            defaultQueryParser.constructSolrQuery(decoratedQuery, domainType);

        Optional.ofNullable(decoratedQuery.getDefaultField())
            .ifPresent(defaultField ->
                solrQuery.setParam(CommonParams.DF, defaultField));
        if (!CollectionUtils.isEmpty(decoratedQuery.getQueryFields())) {
            solrQuery.setParam(DisMaxParams.QF,
                String.join(SPACE, decoratedQuery.getQueryFields()));
        }

        return solrQuery;
    }
}

The last step is to register this parser:
@Bean
public ExtendedQueryParser extendedQueryParser(SolrTemplate solrTemplate) {
    ExtendedQueryParser extendedQueryParser = new ExtendedQueryParser(null);
    solrTemplate.registerQueryParser(ExtendedQuery.class, extendedQueryParser);
    return extendedQueryParser;
}


Q:

Getting an error trying to Route a page (Rails Server)

I'm attempting to try Routing for the first time. I'm following along with a book from Learn-rails.com. Author says to delete what is in config/routes.rb and replace it with: `
LearnRails::Aplication.routes.draw do
  root to: redirect('/about.html')
end

After I saved the file, and then refresh localhost:3000 I get this NameError page: http://imgur.com/6pCPAoP
It says:

Tip: add gem "binding_of_caller" to your Gemfile to enable the REPL
  and local/instance variable inspection.

Which I did add, and did "bundle install". Then I tried to restart rails server in a new window, and now that won't work. If I remove what the Author said to add to the routes.rb file. Everything is fine. Does anyone have any ideas on what is going on? Thanks!

A:

The screenshot clearly specifies, missing 'p' in LearnRails::Aplication is creating the issue. Just replace and it should work


Q:

Batch file - get variable as a string from Windows environment

In Windows system variable I have the following variable
x = 123
Data_123 = ddd:
How do I get this variable as a string from batch filet
So at the end I want to get the variable like
"Data"_%x%   and I will get the value ddd
How can I do that

A:

you need delayed expansion:
@echo off
setlocal enabledelayedexpansion
set x=123
set data_123=hello
echo !data_%x%!

(there is another method without delayed expansion:
call echo %%data_%x%%%


Q:

Flash Packager for IOS: Is the performance for the compiled app too poor to use?

I am looking to develop a ipad app that relies on a lot of animation - mainly cutout animation and was looking at using flash CS 5 to publish a flash app to ios.
I see a few articles on poor performance for flash apps on ios. Anyone have any experience in using flash to publish for ios?

A:

I was doing some testing with it and the frame rate was horrible.  It ended up being easier to start learning Objective-c than to use the Packager for iOS.  That being said I saw this link the other day (http://forums.adobe.com/thread/826112) talking about Air 2.6 for iOS.  Worth reading.  I haven't messed with it yet but I did do a quick test with an Air app running on the Motorola Xoom with Android and it worked great so maybe there's some hope.


Q:

Google Maps v3: large size for markers

I need to display markers on my map and it's working well. The only problem is that they appear to be too small. How can I make sure that the markers used are large in size and can be visible from almost any zoom state?

A:

For making the icons bigger I would definitely recommend to make your icon images larger. To for example fix pixely icons on high-dpi mobile device using downscaled hi-res icons use following code:
var marker = new google.maps.Marker({
    position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
    map: map,
    icon: {
        url: "img/img.png",
        scaledSize: new google.maps.Size(32, 32) // pixels
    }
});
Tested with Google Maps API JavaScript v3.13

A:

If your using version 3 of the api-
When you create the marker, in the marker options you can specify the icon like this:
icon: new google.maps.MarkerImage(
         url:string, size?:Size,
         origin?:Point, anchor?:Point, scaledSize?:Size
      )

Set size to the actual size of your icon image.
Set scaledSize to whatever size you want to stretch the image to.
It is better of cause to make an icon image the size you want instead of scaling it.


Q:

Privacy issue with email verification

I'm currently working on a small website and my customer is very concerned with privacy issues.
I'm implementing a user registration with common email verification, i.e. when a user wants to register he needs to provide an email address and an email containing a verification link is sent to this address.
In the registration form, I'm doing the usual form validation. If the username - which can be chosen freely - is already in use, a message is displayed saying so. My first thought was to do the same for the email address, because this one also should be unique across the system.
But under some circumstances, even the information if some person is registered at the site might be private. But now, if someone would like to know if some other person is registered and if he would know that other person's email, he could simply try to register a new user with this known address and the error message would tell him that this other person is already registered.
I have one idea how to solve this (I will post it as self-answer) but I would like to know, if 1) this solution has any other flaws and 2) if there are other possible solutions for this situation.
Thanks.

A:

So this is the solution I've thought of. Please comment if you detect any problems with it :)
If a new user uses an existing email address, I will simply display the "normal" success message saying that a email with the link has been sent to the given address.
Then an email would be sent to this address saying, that someone tried to register a new user with this address, that this address is already in use and can only be used once (basically, the validation error message will only be sent to the email address and not to the web browser).

A:

Have you considered choosing to not deal with it at all?
There are a number of ID providers about; and using a similar method to the Stack Exchange family of sites might be more appropriate for your case.
Relegating ID management to an external provider is quite easy, and is easily more secure than having to deal with passwords, emails, user uniqueness, etc. yourself.
Additionally, most ID providers will allow you to access the registered user's email address, so that's not likely to be a concern.


Q:

how do I perform segue after log in with google account?

I've been working on sign in with Google account.
I basically followed the guide from Friebase (https://firebase.google.com/docs/auth/ios/google-signin)
It worked, but I have trouble performing segue to my main page from sign in page
here's the code in my signin View controller :
class SignInController: UIViewController,  GIDSignInUIDelegate{

@IBOutlet weak var signInButton: GIDSignInButton!

override func viewDidLoad() {
    super.viewDidLoad()
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().signInSilently()

    }

func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
    if let err = error {
        print(error)
    }
    else {
        performSegue(withIdentifier: "GoToMain", sender: self)
    }
}

it should work if i put performSegue in the signIn function but it didn't
after log in with google successfully, it goes back to protected (sign in) page
I've been working and trying to shoot this problem for almost 6 hours, still can't figure it out !!!
self learning is a lot of pain.
any help is appreciated!!!
Thanks!!
Ian.
update
so now my code is like the following :
class SignInController: UIViewController,  GIDSignInUIDelegate, GIDSignInDelegate {

@IBOutlet weak var signInButton: GIDSignInButton!

override func viewDidLoad() {
    super.viewDidLoad()
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().signInSilently()
    GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID

    }

public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {

    if let authentication = user.authentication
    {
        let credential = FIRGoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)

        FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) -> Void in
            if error != nil
            {
                print("Problem at signing in with google with error : \(error)")

            }
            else if error == nil{
                print("user successfully signed in through GOOGLE! uid:\(FIRAuth.auth()!.currentUser!.uid)")

            }
        })
    }
}

func signIn(signIn: GIDSignIn!, didDisconnectWithUser user: GIDGoogleUser!, withError error: NSError!) {

}

I added GIDsignDeligate protocol otherwise there will be an error at line
 "GIDSignIn.sharedInstance().delegate = self"
When I run it, it crashed with "unexpectedly found nil while unwrapping an Optional value error" (seem to happen at "if let authentication = user.authentication"
)
Am i missing anything?
I feel I'm almost there!

A:

Just add GIDSignIn.sharedInstance().delegate = self to your viewDidLoad function:-
 override func viewDidLoad() {
  super.viewDidLoad()
   GIDSignIn.sharedInstance().uiDelegate = self
   GIDSignIn.sharedInstance().signInSilently()
   GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()!.options.clientID
   GIDSignIn.sharedInstance().delegate = self
}

And change your sign in user function to:-
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {

    if let authentication = user.authentication
    {
        let credential = FIRGoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)

        FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) -> Void in
        if error != nil
        {
            print("Problem at signing in with google with error : \(error)")

            }
        else if error == nil{
            print("user successfully signed in through GOOGLE! uid:\(FIRAuth.auth()!.currentUser!.uid)")

                            }
                    })
            }
}

PS:- This is swift3 version, so don't just copy paste it. Try writing it and autoComplete will help.


Q:

Java Server not able to encrypt/decrypt data with Blackberry's AESkey

I am developing a BlackBerry application where the server is in Java. Whenever AES encrypted data is sent to server along with PKCS5 Formatting,The server gets bad padding exception while decrypting it.

A:

Is that the Blackberry or the server code? Have you tried using the standard JCE classes? something like this:

Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec key = new SecretKeySpec(yourKeyBytes, "AES");
aes.init(Cipher.DECRYPT_MODE, key);
byte[] cleartext = aes.update(ciphertext, 0, ciphertext.length);


Q:

selecting multiple counts when tables not directly co-relate

users table:

user_id (distinct for each user)
source_id (users may have the same source)

rule tables:

white_rules
black_rules
general_rules

these tables all look the same, and have:

victim_id (co-relates to user_id from users table).
rule_id (co-relates to a different table which is not important here)

What i need is to extract the amount of total rules per-type (white,black,general) per-source_id.
example:

source_id: 5 ---> total 70 white rules, total 32 black rules, total 21 general rules
source_id: 7 ---> total 2 white rules, total 0 black rules, total 4 general rules

and so on... for all distinct sources that are listed on users table.
what i tried is:
SELECT source_id,
count(w.victim_id) as total_white,
count(b.victim_id) as total_black,
count(g.victim_id) as total_general
from users
LEFT JOIN white_rules as w ON (user_id=w.victim_id)
LEFT JOIN black_rules as b ON (user_id=b.victim_id)
LEFT JOIN general_rules as g ON (user_id=g.victim_id)
where deleted='f' and source is not null
group by source;

but the result table I get has wrong (higher) numbers than what I expect to get,
so I must be doing something wrong :)
would appreciate any hinge in the right direction.

A:

You need to do your counts in subqueries, or count distinct, as your multiple 1 to many relationships are causing cross joining. I don't know your data but imagine this scenario:
Users:
User_ID |   Source_ID
--------+--------------
  1     |      1

White_Rules
Victim_ID | Rule_ID
----------+-------------
   1      |    1
   1      |    2

Black_Rules
Victim_ID | Rule_ID
----------+-------------
   1      |    3
   1      |    4

If you run
SELECT  Users.User_ID,
        Users.Source_ID,
        White_Rules.Rule_ID AS WhiteRuleID,
        Black_Rules.Rule_ID AS BlackRuleID
FROM    Users
        LEFT JOIN White_Rules
            ON White_Rules.Victim_ID = Users.User_ID
        LEFT JOIN Black_Rules
            ON Black_Rules.Victim_ID = Users.User_ID

You will get all combinations of White_Rules.Rule_ID and Black_Rules.Rule_ID:
User_ID | Source_ID | WhiteRuleID | BlackRuleID
--------+-----------+-------------+-------------
  1     |    1      |      1      |      3
  1     |    1      |      2      |      4
  1     |    1      |      1      |      3
  1     |    1      |      2      |      4

So counting the results will return 4 white rules and 4 black rules, even though there are only 2 of each.
You should get the required results if you change your query to this:
SELECT  Users.Source_ID,
        SUM(COALESCE(w.TotalWhite, 0)) AS TotalWhite,
        SUM(COALESCE(b.TotalBlack, 0)) AS TotalBlack,
        SUM(COALESCE(g.TotalGeneral, 0)) AS TotalGeneral
FROM    Users
        LEFT JOIN
        (   SELECT  Victim_ID, COUNT(*) AS TotalWhite
            FROM    White_Rules
            GROUP BY Victim_ID
        ) w
            ON w.Victim_ID = Users.User_ID
        LEFT JOIN
        (   SELECT  Victim_ID, COUNT(*) AS TotalBlack
            FROM    Black_Rules
            GROUP BY Victim_ID
        ) b
            ON b.Victim_ID = Users.User_ID
        LEFT JOIN
        (   SELECT  Victim_ID, COUNT(*) AS TotalGeneral
            FROM    General_Rules
            GROUP BY Victim_ID
        ) g
            ON g.Victim_ID = Users.User_ID
WHERE   Deleted = 'f'
AND     Source IS NOT NULL
GROUP BY Users.Source_ID

Example on SQL Fiddle
An alternative would be:
SELECT  Users.Source_ID,
        COUNT(Rules.TotalWhite) AS TotalWhite,
        COUNT(Rules.TotalBlack) AS TotalBlack,
        COUNT(Rules.TotalGeneral) AS TotalGeneral
FROM    Users
        LEFT JOIN
        (   SELECT  Victim_ID, 1 AS TotalWhite, NULL AS TotalBlack, NULL AS TotalGeneral
            FROM    White_Rules
            UNION ALL
            SELECT  Victim_ID, NULL AS TotalWhite, 1 AS TotalBlack, NULL AS TotalGeneral
            FROM    Black_Rules
            UNION ALL
            SELECT  Victim_ID, NULL AS TotalWhite, NULL AS TotalBlack, 1 AS TotalGeneral
            FROM    General_Rules
        ) Rules
            ON Rules.Victim_ID = Users.User_ID
WHERE   Deleted = 'f'
AND     Source IS NOT NULL
GROUP BY Users.Source_ID

Example on SQL Fiddle


Q:

QSort returns wrong (scrambled?) numbers in cmp function

I want to use QSort in my program to sort elements in the pointer to pointers to struct. The first element is ok but then it is messed up. The function seems to read some elements but in wrong order / position.
Here is my code
...

typedef struct Date {
    int day;
    int month;
    int year;
} Date;

...

// Sorts the date date_num - the number of entered dates, dates - pointer to pointers to structs of dates
void sort_dates(int* date_num, Date** dates){

    // Normalize the year
    int d; // The date
    for(d=0;d<*date_num;d++){
        if(dates[d]->year >= 90 && dates[d]->year <= 99){
            dates[d]->year = (dates[d]->year)+1900;
        } else{
            dates[d]->year = (dates[d]->year)+2000;
        }
    }

    qsort(dates[0], *date_num, sizeof(Date), compare);

}

int compare(const void* a, const void* b){

    Date* date1 = (Date*)a;
    Date* date2 = (Date*)b;

    // Concatenate year, month and day
    long num1 = date1->year;
    long num2 = date2->year;

    // Concatenate month
    num1 = num1*100+(date1->month);
    num2 = num2*100+(date2->month);

    // Concatenate day
    num1 = num1*100+(date1->day);
    num2 = num2*100+(date2->day);

    printf("num1 = %d %d %d, num2 = %d %d %d\n", date1->year, date1->month, date1->day, date2->year, date2->month, date2->day);

    //return (num2 - num1);
    return 0; // Sorting Temporarily disabled

}

After input:
January 1 01
January 1 00
February 28 99
July 17 12
September 10 12
July 1 00
June 30 90
August 25 06
May 27 08
October 1 03

The program converts month names to numbers and stores dates in Date** dates . After executing this I expect something like this in format
num1 = year month day, num2=year month day :
num1 = 2001 1 1, num2 = 2012 9 10
num1 = 2012 9 10, num2 = 2000 7 1
...

But it actually returns something like that:
num1 = 2001 1 1, num2 = 0 0 0
num1 = 0 2000 1, num2 = 33 0 0
num1 = 1 0 33, num2 = 0 2000 1
num1 = 2001 1 1, num2 = 1 0 33
num1 = 0 0 0, num2 = 1 0 33
num1 = 2 28 0, num2 = 0 0 1999
num1 = 2012 7 17, num2 = 0 0 0
num1 = 0 33 0, num2 = 2012 7 17
num1 = 2 28 0, num2 = 0 33 0
num1 = 0 0 1999, num2 = 0 33 0
num1 = 2001 1 1, num2 = 2 28 0
num1 = 0 0 0, num2 = 2 28 0
num1 = 1 0 33, num2 = 2 28 0
num1 = 0 2000 1, num2 = 2 28 0
num1 = 33 0 0, num2 = 2 28 0

I suspect that there could be a problem with the size of each block to be sorted as ex. year is in some elements at wrong position (different than first) but logically it seems to be right.

A:

This:
qsort(dates[0], *date_num, sizeof(Date), compare);

is wrong, if you want to sort dates then pass dates to qsort(), not its first element. Also the size you want to sort is the size of a pointer, i.e. sizeof (Date *), or ever better sizeof *dates.
Further, your comparison function fails to take into account that it will be passed pointers to elements of dates, i.e. pointers to pointers to Date. This means it should start:
static int compare(const void* a, const void* b){
    const Date * const date1 = *(const Date**) a;
    const Date * const date2 = *(const Date**) b;

Again, this change is needed since the comparison function to qsort() is passed two pointers to elements in the array that is getting sorted. That's a reasonable thing to pass, it can't pass the elements themselves (it doesn't know their types), but a const void * can point at any kind of data. Since your array elements are of type Date * (pointer to Date), that means the actual values sent to compare() are pointers to pointers to Date (i.e. Date **).
Finally, there's no point in dropping const inside it, so don't do that.


Q:

How to get a list of all projections that are currently available in QGIS via the PyQGIS-API

i'm building a QGIS-Plugin and i want the user to choose a CRS out of a combobox in which the coordinates he would enter into some textfields are represented, so these can be converted into another projection.
Is it possible to get a list of all the currently available projections via the PyQGIS-API?
I'm searching the QGIS-API right now, but no luck so far.

A:

The projections available in Qgis are stored in a sqlite database called srs.db, found in apps/qgins/resources. The data is stored in the tbl_srs table.
For a python approach, you can look into the transformation tools plugin.
selectCrsDlg.py should have the data you want.


Q:

What does 'ignore reason: pending' in cucumber tests means?

I am using wdio v4.12.0 and wdio-cucumber-framework which is using cucumber v1.3.3 One of tests is ignored and only information in cmd output is that ignore reason: pending. All previous and later steps are executed without error.

[field with default name is visible] Test ignored: field with default name is visible, ignore reason: pending

Feature file:
Scenario: User is able to add field
  Given user is on fields page
  When user creates new field with default name
  Then field with default name is visible

What can be cause of skipping this step? What does pending means (is it just unresolved promise or what)?

A:

I believe scenarios are marked as pending when Cucumber cannot find the underlying definition for one or more steps. In this case, it probably cannot find the step definition for "Then field with default name is visible" so check if you have implemented this definition.


Q:

In discord.py how to send a message on a just created channel?

I am making a ticket bot, it creates a channel every time someone reacts a message in the "ticket" category, how to get the channel obj so the bot can send a message there?
I have this:
@client.event
async def on_raw_reaction_add(payload):
    r_msg_id = payload.message_id
    print(r_msg_id)
    channel_id = payload.channel_id
    user_id = payload.user_id
    channel = client.get_channel(channel_id)
    category_id = int("719621258106372219")
    category = client.get_channel(category_id)
    client.get_channel(r_msg_id)
    msg_obj = await channel.fetch_message(r_msg_id)
    guild_id = payload.guild_id
    guild = client.get_guild(guild_id)
    member = payload.member
    f = open("ticket_nums.txt", "w+")
    #ticket_num = f.read()
    #f.write(int(ticket_num) + 1)
    #f.close()
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        payload.member: discord.PermissionOverwrite(read_messages=True)
    }
    if True: #r_msg_id == "720708414107287724": commented out because it doesn't work idk why
        if not user_id == "718528256365559829":
            await msg_obj.remove_reaction("\U0001f4e8", discord.Object(id=user_id))
            await category.create_text_channel(r"ticket#" , overwrites=overwrites) #mette i permessi alla persona che apre il ticket

also while opening the ticket_nums file, which should contain the ticket count, it keeps me giving me this error: (It's giving it every time I try to open a file)
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
  File "C:\Users\giaco\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\giaco\Desktop\Bot\Discord Bot\bot_discord.py", line 216, in on_raw_reaction_add
    f = open("ticket_nums.txt", "w+")
PermissionError: [Errno 13] Permission denied: 'ticket_nums.txt'

A:

When creating a channel, it returns the channel object back. Thanks to this, you can put it into a variable and then send() it:
channel = await category.create_text_channel(...)
await channel.send("Hey! I just created this channel!")

As for your Permission denied error, I suspect you need elevated permissions on your account. To let the program have the necessary permissions, you can run whatever IDE you're using as administrator:
Right-click > Run as administrator > Allow > Run your script

References:

create_text_channel() - Specifically, Return type:

abc.Messageable
Messageable.send()


Q:

Ubuntu's garbage collection cron job for PHP sessions takes 25 minutes to run, why?

Ubuntu has a cron job set up which looks for and deletes old PHP sessions:
# Look for and purge old sessions every 30 minutes
09,39 *     * * *     root   [ -x /usr/lib/php5/maxlifetime ] \
   && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 \
   -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) ! -execdir \
   fuser -s {} 2> /dev/null \; -delete

My problem is that this process is taking a very long time to run, with lots of disk IO. Here's my CPU usage graph:

The cleanup running is represented by the teal spikes. At the beginning of the period, PHP's cleanup jobs were scheduled at the default 09 and 39 minutes times. At 15:00 I removed the 39 minute time from cron, so a cleanup job twice the size runs half as often (you can see the peaks get twice as wide and half as frequent).
Here are the corresponding graphs for IO time:

And disk operations:

At the peak where there were about 14,000 sessions active, the cleanup can be seen to run for a full 25 minutes, apparently using 100% of one core of the CPU and what seems to be 100% of the disk IO for the entire period. Why is it so resource intensive? An ls of the session directory /var/lib/php5 takes just a fraction of a second. So why does it take a full 25 minutes to trim old sessions? Is there anything I can do to speed this up?
The filesystem for this device is currently ext4, running on Ubuntu Precise 12.04 64-bit.
EDIT: I suspect that the load is due to the unusual process "fuser" (since I expect a simple rm to be a damn sight faster than the performance I'm seeing). I'm going to remove the use of fuser and see what happens.

A:

Congratulations on having a popular web site and managing to keep it running on a virtual machine for all this time.
If you're really pulling in two million pageviews per day, then you're going to stack up a LOT of PHP sessions in the filesystem, and they're going to take a long time to delete no matter whether you use fuser or rm or a vacuum cleaner.
At this point I'd recommend you look into alternate ways to store your sessions:

One option is to store sessions in memcached. This is lightning fast, but if the server crashes or restarts, all your sessions are lost and everyone is logged out.
You can also store sessions in a database. This would be a bit slower than memcached, but the database would be persistent, and you could clear old sessions with a simple SQL query. To implement this, though, you have to write a custom session handler.

A:

Removing of fuser should help. This job runs a fuser command (check if a file is currently opened) for every session file found, which can easily take several minutes on a busy system with 14k sessions. This was a Debian bug (Ubuntu is based on Debian).
Instead of memcached you can also try to use tmpfs (a filesystem in memory) for session files. Like memcached this would invalidate sessions on reboot (this can be worked around by backing up this directory somewhere in shutdown script and restoring in startup script), but will be much easier to setup. But it will not help with fuser problem.

A:

So, the Memcached and database session storage options suggested by users here are both good choices to increase performance, each with their own benefits and drawbacks.
But by performance testing, I found that the huge performance cost of this session maintenance is almost entirely down to the call to fuser in the cron job. Here's the performance graphs after reverting to the Natty / Oneiric cron job which uses rm instead of fuser to trim old sessions, the switchover happens at 2:30.

You can see that the periodic performance degradation caused by Ubuntu's PHP session cleaning is almost entirely removed. The spikes shown in the Disk Operations graph are now much smaller in magnitude, and about as skinny as this graph can possibly measure, showing a small, short disruption where previously server performance was significantly degraded for 25 minutes. Extra CPU usage is entirely eliminated, this is now an IO-bound job.
(an unrelated IO job runs at 05:00 and CPU job runs at 7:40 which both cause their own spikes on these graphs)
The modified cron job I'm now running is:
09 *     * * *     root   [ -x /usr/lib/php5/maxlifetime ] && \
   [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 \
   -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 \
   | xargs -n 200 -r -0 rm


Q:

How can I insert a value to a table thats inside a table

I am just testing out my knowledge and I want to know how I can insert a string value like a name into a nested table.
I have tried table.insert() but I cant seem to insert into the nested table
whitelist = {
    owners = {"Owner","AnotherOwner","John"},
    users = {"Jack","Jill","username"}
}

table.insert(whitelist,2,"Q") --What I want to do
--[[for index,table in pairs(whitelist) do
    print(index)
    for key,value in pairs(table) do
        print('\t',value)
    end
end
(I want to use this later after inserting to see if it works)
]]--

I expected it to print out both tables with an added value of "Q"into users but I get an error:

Position out of bounds

A:

You want to insert in the users list, so use table.insert(whitelist.users,"Q").


Q:

Tee command unix

How can I tee all these services into a log file:
stop service 1
stop service 2
stop service 3

I want all these services logs go to a file
should I use :
stop service 1 | tee log1.log
stop service 2 | tee log1.log
stop service 3 | tee log1.log

Or:
stop service 1
stop service 2
stop service 3 | tee log1.log

I haven't found a question like this
Thank you!

A:

tee accepts the -a flag to append to a file. So you should be able to redirect the output from all three commands to a single file by executing:
stop service 1 | tee log1.log
stop service 2 | tee -a log1.log
stop service 3 | tee -a log1.log

(The first command will truncate any existing file)

A:

Another way not using tee is to simply use a bash command group with a single redirection of stdout to a log file:
{ stop service 1; stop service 2; stop service 3 } > log1.log

Use the >> operator to append to the log file, or use the &>> operator to append both stdout and stderr. It's also possible to use a bash subshell instead:
( stop service 1; stop service 2; stop service 3 ) > log1.log


Q:

How fast does my connection need be to play World of Warcraft?

I've got a bad connection and I would like to know if I can play WoW without experiencing major problems.
This is my connection:
Ping: 30 ms
Download: 3.21 Mbps
Upload: 1.51 Mbps

A:

The product specs for WoW say that it works with 56K modems, so your bandwidth should be fine.
In my firsthand experience, if I'm experiencing lag it's related to packet loss. I won't detail how to fix that since it's a long IT troubleshooting process, but if you go to pingtest.net and your "Jitter" is fairly low you should be okay.


Q:

adding a parameter to a url that has a mod_rewrite value

I have a rewirte rule that rewrites my portfolio urls from
portfolio.php?cat=cat-name&project=project-slug
to
/portfolio/cat/slug/
That all works fine and dandy, I'm wondering if It's possible to add a parameter to the end of the rewritten slug. For example
/portfolio/cat/slug&preview=true
I'm trying to make it so I can preview hidden projects by appending the preview=true to the end. It works if I go to
portfolio.php?cat=cat-name&project=project-name&preview=true
I'm just hoping I don't have to create a rule that has /true I've tied various ways to get the value or preview but thought someone here may have a simple solution
Edit Adding .htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^.*$
#portfolio
RewriteRule ^portfolio/?$ portfolio.php [L,NC]
RewriteRule ^portfolio/([a-z0-9_-]+)/([a-z0-9_-]+)/?$ portfolio.php?cat=$1&project=$2 [L,NC]
RewriteRule ^portfolio/([a-z0-9_-]+)/?$ portfolio.php?cat=$1 [L,NC]
RewriteRule ^portfolio/([a-z0-9_-]+)/page=([0-9]+)/? portfolio.php?cat=$1&page=$2&

A:

Add QSA as an option to the back of the RewriteRule (in the [] brackets). E.g.
RewriteRule ^portfolio/([a-z0-9_-]+)/([a-z0-9_-]+)/?$ portfolio.php?cat=$1&project=$2 [L,NC,QSA]


Q:

Fingerprinting the webpage content

I'm moderating a closed section of a forum - think 'covered by NDA' (not actually, but it's a good equivalent of the situation), with restricted access.
Sometimes we find screenshots from that forum posted by some rogue user anonymously in places where they definitely shouldn't appear. And the screenshots being anonymous, with no discernable features, don't let us find the rogue and draw consequences.
I'd like to learn of some way to affect page appearance so that a screenshot of it could be traced to the author of the screenshot - maybe some kind of steganography that can survive lightweight compression, or other inconspicious elements that would allow to identify, whose account these screenshots were made from? Specifically, possible to appear broadly enough that even a relatively small part of the screen (say, one post) is sufficient to identify the culprit?
I tried "cooking my own" embedding something akin to low-contrast barcode in borders around posts, but it was neither inconspicious enough nor durable enough to survive 85% quality JPEG compression.

A:

This looks like a classical Canary Trap. Basicly I would suggest to hide encrypted information about the user in different ways:

obvious QR-Code  (as suggested by slugster)
different colors (as suggested by Nick Wilde)
page viewed as username - footer on each page
replacing certain words with synonyms
code information in spaces and interpunction within the text

If the user compresses/reduces the size of the screenshot, you can still guess / measure the different interpunction of the text - combined with another measurement the user might "forget" to remove all of them.
Regardless of the stenographical method I would suggest to encrypt the data with an public/private-key meachnism to ensure that if someone reads out or assumes that there is data and tries to read it out, the person isn't able to find it easily.


Q:

Custom numbering of listings

I have a number of listings in my document, numbered 1, 2, 3 and so on.
I need a table with three listings (say, three different variants of the same algorithm), that will be numbered as 2a, 2b, 2c. The very next listing would be numbered as 3.

A:

you can also save the current counter value to make it independent from the current counter setting.
\documentclass{article}
\usepackage{listings}
\begin{document}

\begin{lstlisting}[caption=foo]
 foo
\end{lstlisting}

\setcounter{lstlisting}{0}
\renewcommand\thelstlisting{2.\alph{lstlisting}}
\begin{lstlisting}[caption=foo]
 foo
\end{lstlisting}
\begin{lstlisting}[caption=foo]
 foo
\end{lstlisting}
\begin{lstlisting}[caption=foo]
 foo
\end{lstlisting}

\renewcommand\thelstlisting{\arabic{lstlisting}}
\setcounter{lstlisting}{2}
\begin{lstlisting}[caption=foo]
 foo
\end{lstlisting}

\end{document}


Q:

Android multi time button press problem?

i have very annoying scenario
on button click i show toast or start thread.
what problem i am facing right now is
user presses same button many times and there are lots of toasts and threads starts one by one
i have seen some mobile apps after pressing button they disable touch screen
or any one guide me how to handle this situation in android? or how android developers deals with this problem?
any help would be appreciated.

A:

For threads use the AsncTask and use getStatus to see if you need to fire the thread off again. For dialog boxes use isShowing(). For other tasks that expire on their own use a long to hold the time of the last start and only allow it start again if enough time has passed.


Q:

What is the Catholic understanding of 'age' in Scripture and in its Tradition?

New Testament scriptural passages with 'age':

Matthew 12:31-33
  (RSVCE)
  31 Therefore I tell you, every sin and blasphemy will be forgiven men,
  but the blasphemy against the Spirit will not be forgiven. 32 And
  whoever says a word against the Son of man will be forgiven; but
  whoever speaks against the Holy Spirit will not be forgiven, either in
  this age or in the age to come.
Mark 10:29-31
  (RSVCE)
  29 Jesus said, “Truly, I say to you, there is no one who has left
  house or brothers or sisters or mother or father or children or lands,
  for my sake and for the gospel, 30 who will not receive a hundredfold
  now in this time, houses and brothers and sisters and mothers and
  children and lands, with persecutions, and in the age to come
  eternal life. 31 But many that are first will be last, and the last
  first.”
Similarly, Luke 18:29-31
  (RSVCE).
1 Corinthians 10:10-12
  (RSVCE)
  10 nor grumble, as some of them did and were destroyed by the
  Destroyer. 11 Now these things happened to them as a warning, but they
  were written down for our instruction, upon whom the end of the ages
  has come. 12 Therefore let any one who thinks that he stands take
  heed lest he fall.
Ephesians 1:20-22
  (RSVCE)
  20 which he accomplished in Christ when he raised him from the dead
  and made him sit at his right hand in the heavenly places, 21 far
  above all rule and authority and power and dominion, and above every
  name that is named, not only in this age but also in that which is
  to come; 22 and he has put all things under his feet and has made
  him the head over all things for the church,
Hebrews 6:4-6
  (RSVCE)
  4 For it is impossible to restore again to repentance those who have
  once been enlightened, who have tasted the heavenly gift, and have
  become partakers of the Holy Spirit, 5 and have tasted the goodness of
  the word of God and the powers of the age to come, 6 if they then
  commit apostasy, since they crucify the Son of God on their own
  account and hold him up to contempt.

In the Nicene Creed recited at Mass in the US there is born of the Father before all ages vs. eternally begotten of the Father cf. Catechism of the Catholic Church - Credo Chart. Does this mean that there was eternity, the Beginning, and then there is a succession of ages?
In the Liturgy of the Eucharist, a line in Eucharistic Prayer III is now you never cease to gather a people to yourself while previously it was from age to age you gather a people to yourself perhaps suggesting that the latter conveyed a meaning that it wasn't meant to convey.
And finally, here is a mention of age by Venerable Bartholomew Holzhauser in this context:

He also wrote a remarkable work on the last book of the New Testament,
  the Revelation or the Apocalypse, which today is still held in high
  regard by Roman Catholics. He interpreted the book of the Apocalypse
  as follows: The seven stars and the seven candlesticks seen by St John
  signify seven periods of the history of the Church, from its foundation to its consummation at the final judgment. To these periods
  correspond the seven churches of Asia Minor, the seven days of the
  Mosaic record of creation, the seven ages before Christ, and the
  seven gifts of the Holy Ghost. Since, he claimed, all life is
  developed in seven stages, so God has fixed seven periods for
  regeneration.

Lactantius
"Therefore let the philosophers, who enumerate thousands of ages from the beginning of the world, know that the six-thousandth year is not yet complete. . . . Therefore, since all the works of God were completed in six days, the world must continue in its present state through six ages, that is, six thousand years. For the great day of God is limited by a circle of a thousand years, as the prophet shows, who says, ‘In thy sight, O Lord, a thousand years are as one day [Ps. 90:4]’" (Divine Institutes 7:14 [A.D. 307]).

What is the Catholic understanding of 'age' in Scripture and in its Tradition?

A:

The word "saeculum" is the Latin word used for "age" in many Catholic writings, and in the Scripture passages that you mention in your question. This word is defined as "a generation; the spirit of the age , the times; a hundred years, a century, an age" by  this Latin dictionary.
According to etymonline.com (and others), the English word "secular" derives from the Latin word "saeculum" by an interesting path. "Saecularis" is a Latin adjective that means "pretaining to an age." This contrast was used by medieval writers to refer to the present age, or to the general doings of the world, and from this distinction arises the modern sense of "secular" meaning "non-religious." (Also, the "secular priesthood," is the body priests who live in the world, as opposed to in monasteries, that is, to diocesan rather than order priests.) The sense of "age" (= "saeculum") referring to the present world, or the present created order (that is, the world before the Last Day), is contrasted with the "age to come" (Latin "venturum saeculum") as in the Latin Nicene creed, "vitam venturi saeculi," which means, "the life of the world to come" or "life of the age to come."
The quotation from Matthew 12 and from Mark 10 use "age" in this sense, to contrast the present order of creation with that which will exist after Christ comes again.
The quotation from 1 Corinthians shows us a slightly different sense. In ancient culture, there was a sense of repetition or succession of ages ("saecula", plural). Paul is alluding to the fact that the ages will no longer succeed one after another, but rather once Christ has returned all things will be completed, and the transient succession of "saecula" will end. (In some cases, a "saeculum" is the duration of a particular political arrangement, and in some cases it is a period of 100 years. The Romans celebrated "Ludi saeculares" roughly every 100 years, though Augustus Caesar caused them to be celebrated so that they might mark his inauguration of a new period of Roman government and show a continuation of an ancient tradition.)
The quotation from Ephesians shows that the name of Jesus is supreme, both in the current, transient created order and in the "age to come," that is, in the perfected order that will arise after Christ returns. This sense, the contrast of "now" against "after Second Coming," is the same sense as found in your quotations from the Evangelists.
As an aside, I would also note that although it is not reflected in the English translation, "Glory to the Father, to the Son, and to the Holy Spirit, as it was in the beginning, is now, and will be forever, world without end," the use of "saeculum" occurs in the Latin version of this prayer, where we see "et in saecula saeculorum," literally, "into the ages of ages," rather than "world without end." A similar expression of "into the age of an age" or "into the ages of ages" is found in the doxology in many Psalms, and in the hymn of Daniel and his companions in the furnace.
Regarding the Nicene Creed, the phrase "born of the Father before all ages," (Latin: "ex Patre natum ante omnia saecula") indicates that Christ's existence precedes the existence of every successive period of creation, including this present age (Latin "hoc saeculum"). This is the same sense of "saecula" (plural) found in 1 Corinthians as discussed above.
In summary, there are two related senses of "age" in this tradition. "This age" or "the present age" (usually singular, Latin "hoc saeculum") contrasted with the "age to come," (Latin "saeculum venturum"), and meaning simply the current order of creation before Christ returns. The second sense, "ages," usually plural, refers to successive periods of creation, usually looking at times past before the author wrote, as when Paul speaks of the "end of the ages" meaning roughly "the cessation of the quasi-cyclical rise and fall of nations, passage of seasons, etc., and their replacement with whatever God has prepared in the age to come."
I don't know enough to comment on the numerical interpretation of Revelation. I hesitate to point to any literal correspondence between the Revelation of St. John and real world events, historical or predicted, but that is only my opinion, and is really a caution born of ignorance.
You may be right that the change from "from age to age" to "you never cease" is meant to avoid accidentally using this sense of age. Another goal of the recent translation was to follow the Latin more closely, and the Latin in this case reads simply "et populum tibi congregare non desinis" literally "you do not cease to gather a people for yourself."
I hope I've answered your question adequately. I answer from the perspective of what the word "age" in Latin means, and, as a Latin teacher, I am much more confident of the Latin than of any theological implications I may accidentally have made.


Q:

Why do you need excess LAH to reduce esters?

I am little confused on this question. On one hand, I remember my teacher saying that $\ce{LiAlH4}$ is like $\ce{BH3}$ of hydroboration oxidation of alkene, where you one mole of $\ce{BH3}$ can oxidize 3 mole of alkene molecule. but on the other hand my textbook keeps on mentioning excess LAH when reducing ester? Can't one mole of LAH reduce four mole of ester molecules as well? Thanks.

A:

Lithium aluminium hydride or LAH is the more everyday form of $\ce{LiAlH4}$. When originally produced, most of it is indeed $\ce{LiAlH4}$ but that quickly partially hydrolyses giving the grey powder you may or may not know from the lab. As such, $\ce{LiAlH4}$ is practically never entered into reactions in pure form. Since it is impure, excess reagent is added to make sure the reduction job is performed as desired.
Also, remember to consider the reaction meachnism:
$$\ce{R-COOR' ->[LAH][- HOR'] R-CHO ->[LAH] R-CH2OH}\tag{1}$$
Note that the second step, the reduction of an aldehyde, is more rapid than the first as aldehydes are more reactive towards nucleophiles than esters. Thus, if you attempted to bargain, hoping to arrive at the aldehyde selectively, you would end up with under half of your reactant reduced to the alcohol and half of it still as an ester. Another reason to always add excess just to be sure.


Q:

How to uninstall mod_wsgi when installed with make?

I have installed mod_wsgi on Ubuntu 14.04 as described in their documentation. While I don't get any errors from Apache or anything my Django setup does not work (no idea why exactly) so I would like to start over and use libapache2-mod-wsgi.
However, I don't know how to uninstall mod_wsgi. This answer to a more general question on the subject advises trying make uninstall which does not work in this case.
make -n install gives me the following output:
/usr/bin/apxs2 -c -I/usr/include/python2.7 -DNDEBUG -D_FORTIFY_SOURCE=2  -Wc,-g -Wc,-O2  src/server/mod_wsgi.c src/server/wsgi_*.c -L/usr/lib -L/usr/lib/python2.7/config  -lpython2.7 -lpthread -ldl  -lutil -lm
/usr/bin/apxs2 -i -S LIBEXECDIR=/usr/lib/apache2/modules -n 'mod_wsgi' src/server/mod_wsgi.la

What exactly do I have to do to uninstall this?
Thanks!
Edit: I'm using mod_wsgi-4.5.3.

A:

Remove any configuration you added to Apache configuration files and also run:
sudo rm /usr/lib/apache2/modules/mod_wsgi.so

I would strongly recommend against using the system provided mod_wsgi package as it is generally out of date by many many versions and is also thus not supported. You are better off using the latest from source code and trying to work out what the problem is, exact details of which you haven't posted.


Q:

Rails: validation between columns

Assume, we have a model, let's call it Articles. There, we have two columns, min and max. The rule is: min can't be greater or equal to max. How do you resolve this custom type of validation? Any ideas?
Going further, let's assume that we have columns character and made_of. Task is to create a validation which is gonna help to avoid a situation, when "character = human" and "made_of = steel".
Is there are standard routines to manage "metaphysical" conflicts between columns?

A:

You could use validate to define your own validations. For instance:
class Article < ActiveRecord::Base
  validate :min_greater_than_max, :humans_aint_made_of_steel

  def min_greater_than_max
    errors.add(:min, "can't be greater than max") if min > max
  end

  def humans_aint_made_of_steel
    errors.add(:human, "can't be made of steel") if character == 'human' && made_of == 'steel'
  end

end


Q:

Updating state of component from returned server data

I am injecting the props into the initial state of component. I want to change the if I click on some button inside the component I want to update the state and the data should be reflected immediately.
eventData is an object which contains two attributes one is key(another object) and other is array of object
Data Structure looks like :

eventData--->
    {
    key:{}
    events: [{},{},...]
    }

    this.state = {
    events:this.props.eventData.events,
    }

    static getDerivedStateFromProps(nextProps, prevState){
        if(nextProps.eventData.events!==prevState.events){
          return { events: nextProps.eventData.events};
       }
       else return null;
     }

     componentDidUpdate(prevProps, prevState) {

       const {eventData} = this.props;
       if(prevProps.eventData.events!==this.props.eventData.events){
         //Perform some operation here
         this.setState({events: eventData.events});
         this.classMethod();
       }
     }

 handleClickButton = (event, action) => {

      const {eventData} = this.props;

      axios.post(configs.Data.sendEvent, {events: event, key:eventData.key, action:action})//event here is a single event
      .then(res=>{
           this.setState({events:res.data.singleResult.dataEvent});
      });

      };

Since I updated the state but the result is not reflected. Can I use componentDidUpdate to update state from upcoming updated state?

A:

You can try to keep incoming data on parent component where props come from without touching componentDidUpdate(). Then pass a function from that component to make changes on state of that component. Then render child component again.
If you want to change both Parent component and Child components data,  you can try something like below. It's not a good method but it should work.
class Parent extends Component
{
  ....
  this.state = {dataFromSever:""}
  ...

  changeData = (data) =>
     {
     this.setState({dataFromServer:data});
     }
  ...

   render()
   {
       ...
        /*
        * ReactDOM.unmountComponentAtNode is goint to unmount react component from
        * 'container' component.
        * For now, just consider 'container' where you put react components.
        */
        ReactDOM.unmountComponentAtNode(document.getElementById('container'));
        ReactDOM.render(<ChildComponent changeData={this.changeData}
        currentData={this.state.dataFromServer}>
        </ChildComponent>,document.getElementById('container'));
        ...
   }

}

and
class ChildComponent extends Component
{
  ....
  ...

  handleClickButton = (event, action) => {

      const {eventData} = this.props;

      axios.post(configs.Data.sendEvent, {events: event,
      flightTaskKey:eventData.flightKey, action:action})
      .then(res=>{
           this.props.changeData(res.data.singleResult.dataEvent);
      });

      };
  ...

   render()
   {
    ... <...> this.props.currentData </...>
   }

}


Q:

Castle Dynamic Proxy how to merge data in CreateClassProxyWithTarget

It is possible to add proxy capabilities to an already generated and not empty object using Castle Dynamic Proxy?
I've tried this:
Dog _myDog=new Dog();
_myDog.Name="Fuffy";

var _proxyDog = generator.CreateClassProxyWithTarget<Dog>(_myDog, ProxyGenerationOptions.Default, new DogInterceptor());

_proxyDog results as a new object.
Now this is only an example, in real world application my object has 30+ properties and I want to know if I can avoid to copy those props one by one!

A:

Yes it is. The only problem: ProxyGenerator needs to instantiate an object of that type anyway. This code is actually working correctly in my project:
public static class MongoExtensions
{
    static readonly ProxyGenerator pg = new ProxyGenerator();
    public static MongoCollection GetRetryCollection(this MongoDatabase db, string collectionName, int retryCount = 5, int pauseBetweenRetries = 2000)
    {
        var coll = db.GetCollection(collectionName);
        return (MongoCollection)pg.CreateClassProxyWithTarget(typeof(MongoCollection), coll, new object[] { db, collectionName, coll.Settings }, new RetryingInterceptor { RetryCount = retryCount, PauseBetweenCalls = pauseBetweenRetries });
    }
}

Paramerts of CreateClassProxyWithTarget are:

type of the proxied object,
proxied instance
array of constructor paramers for the proxied type.
interceptor for this proxy.

I can't really explain, why it need constructor parameters for the object, but this code work correctly for me.