text:
Q: CMD Batch file trouble with nested IF statements and variables I am writing a cmd batch file which queries windows registry and then reports back to a file with the output. The keys I am looking to query are around SSL for SCHANNEL.
I want the output to read correct and not necessarily the specific reg value, so turning the value into a variable if that variable matches xyz either set another variable to 'disabled' or echo 'SSLv2 is disabled' so rather an interpretation of what the reg value is, for example if 0x1 is the value i want the output to echo 'SSLv2 is disabled' not 'SSLv2 is 0x1'.
I'm having difficult nesting the if statements also if there is no registry key present at all, ie Empty or null to just display 'SSLv2 is enabled'.
Below is just one example for SSLv2 for client side.
For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set mydate=%%a-%%b-%%c)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
FOR /F "tokens=* USEBACKQ" %%F IN (`hostname`) DO SET hostname=%%F
set hostnamefolder=%~dp0\%hostname%
mkdir %hostnamefolder%\logs
mkdir %hostnamefolder%\logs\files
mkdir %hostnamefolder%\logs\sceenshots
set workingdir=%~dp0

set Logfile=%hostnamefolder%\%hostname%_BRSIS.txt
set curdir=%~dp0
If Exist %Logfile% Del %Logfile%
@echo On
setlocal ENABLEEXTENSIONS

REM ======================================
REM SSLv2 configuration for Client:
REM ======================================

FOR /F "usebackq skip=2 tokens=1,3" %%A IN (`reg query "HKLM\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server" /v DisabledByDefault 2^>nul`) DO (
    set ValueName=%%A
    set ValueValue=%%B
)

echo %valueName%
echo %ValueValue%

if defined ValueName (
        if %ValueValue% EQU 0x1 (
            echo SSLv2 protocol for client connections is disabled >> %Logfile%
        ) else (
        if %valueValue% EQU 0x0 (
            echo SSLv2 protocol for client connections is enabled >> %Logfile%
        )) else (
            echo SSLv2 protocol for client connections are enabled >> %Logfile%
        )

I'm not a programmer so please forgive my coding, however, I'm keen to learn.

A: if defined ValueName (
   if defined Valuevalue (
     if "%ValueValue%" EQU "0x1" (
        echo SSLv2 protocol for client connections is disabled >> %Logfile%
     ) else (
        if "%valueValue%" EQU "0x0" (
          echo SSLv2 protocol for client connections is enabled >> %Logfile%
        ) else (
          echo SSLv2 protocol for client connections are enabled >> %Logfile%
        )
     )
  ) else (
   echo valuevalue is not defined
  )
) else (
 echo valuename is not defined
)

The key is to match indent levels. Your code is missing the terminal ) to close the outermost if. Your )) closes the two inner if statements, consequently the else is not paired to an if.

(I'm an ailurophile...)
set "message=SSLv2 protocol for client connections are enabled"
if defined valuename if defined valuevalue (
   if "%valueValue%" EQU "0x1" set "message=SSLv2 protocol for client connections is enabled"
   if "%valueValue%" EQU "0x0" set "message=SSLv2 protocol for client connections is enabled"
)
echo %message%>>%logfile%

Simple. Or as complex as you need.
Better to clearly say what your desired output is under which circumstances.

A: Here's an example which may help:
@Echo Off
Set "LogFile=Output.log"
Set "RK=HKLM\System\CurrentControlSet\Control\SecurityProviders"
Set "RK=%RK%\SCHANNEL\Protocols\SSL 2.0\Server"
Set "RV=DisabledByDefault"
Set "SO=SSLv2 protocol for client connections "
Set "DV=does not exist"
For /F "EOL=H Tokens=2*" %%A In ('Reg Query "%RK%" /V "%RV%" 2^>Nul'
) Do If "%%B"=="0x1" (Set "DV=is enabled") Else Set "DV=is disabled"
(Echo %SO%%DV%)>"%Logfile%"

Here's your code redone with indents and Remarks to help with your learning:
@Echo Off
Rem Ensure this script is in the current direcotry
CD /D "%~dp0"
Rem Setting local variables for use in this script
    Rem Date and time stamps
        Rem Undefine any existing variable named DS
        Set "DS="
    For /F "Tokens=1-5 Delims=/: " %%A In ('RoboCopy/NJH /L "\|" Null'
    ) Do If Not Defined DS (Set "DS=%%A-%%B-%%C" & Set "TS=%%D%%E")
    Rem Hostname
    For /F "Delims=" %%A In ('HostName') Do Set "HN=%%A"
    Rem Host folder
    Set "HF=%CD%\%HN%"
    Rem Log file
    Set "LF=%HF%\%HN%_BRSIS.txt"
    Rem SSLv2 registry key
    Set "RK=HKLM\System\CurrentControlSet\Control\SecurityProviders"
    Set "RK=%RK%\SCHANNEL\Protocols\SSL 2.0\Server"
    Rem SSLv2 target value
    Set "RV=DisabledByDefault"
    Rem Common SSLv2 output string
    Set "SO=SSLv2 protocol for client connections "
    Rem default SSLv2 output string ending [for missing value]
    Set "DV=does not exist"
Rem Creating necessary directories if missing
If Not Exist "%HF%\logs\files\" MD "%HF%\logs\files"
If Not Exist "%HF%\logs\sceenshots\" MD "%HFr%\logs\sceenshots"
Rem SSLv2 configuration for Client:
    Rem Check registry for SSLv2 key value
    For /F "EOL=H Tokens=2*" %%A In ('Reg Query "%RK%" /V "%RV%" 2^>Nul'
    ) Do If "%%B"=="0x1" (
        Rem define variable for SSLv2 output string ending [for enabled value]
        Set "DV=is enabled") Else (
        Rem define variable for SSLv2 output string ending [for disabled value]
        Set "DV=is disabled")
    Rem Output resulting string to log file
    (Echo %SO%%DV%)>"%LF%"
Rem Rest of code goes here


text:
Q: How to increment variable under DOS? I've spent the past 3hrs trying to work this out but just couldn't find a solution. Here's my batch script:
if NOT Exist Counter.txt GOTO START
Type c:\counter.txt
if %COUNTER% EQU %Cycles% goto Pass
if NOT %COUNTER% EQU %Cycles% goto Cycle

:START
Set COUNTER=0
set CYCLES=250

:Cycle
set /A COUNTER=%COUNTER%+1     <----------- PROBLEM
echo Iteration %COUNTER% of %CYCLES%
echo Delay 3 seconds to reboot
choice /cy /n /t:y,3
warmboot.com

:Pass
pause

What it's doing is it runs the file "warmboot.com" (which reboots my PC) and runs for 250 cycles. Once the cycles have run 250 times (i.e when counter equals cycles) then it stops.
Under Windows, this works. However, this doesn't work under DOS environment. I've tried versions from v4 all the way up to v6.22 and even v7 and they all fail when it reaches the "PROBLEM" line.
If I do this:
set /A COUNTER=%COUNTER%+1
echo %Counter%

OR this:
set /A COUNTER+=1
echo %Counter%

both will return a blank line, i.e it shows nothing as the output.
If I type:
set /?

then it shows this:

Displays, sets, or removes cmd.exe environment variables.
SET [variable=[string]]
variable  Specifies the environment-variable name.
    string   Specifies a series of characters to assign to the variable.

but typing the same command under CMD in Windows shows a lot more stuff. I'm thinking that the SET function under DOS doesn't support arithmetic functions, but for work purposes I have to run my scripts in DOS only.
Any ideas?

A: I realize you've found another answer - but the fact is that your original code was nearly correct but for a syntax error.
Your code contained the line
set /A COUNTER=%COUNTER%+1

and the syntax that would work is simply...
set /A COUNTER=COUNTER+1

See http://ss64.com/nt/set.html for all the details on the SET command. I just thought I'd add this clarification for anyone else who doesn't have the option of using FreeDOS.

A: Indeed, set in that old DOS (rather than Windows' cmd) has no option to allow for arithmetic. (cmd does have the way you described.) You could do a giant lookup table, though:
if %COUNTER%==249 set COUNTER=250
...
if %COUNTER%==3 set COUNTER=4
if %COUNTER%==2 set COUNTER=3
if %COUNTER%==1 set COUNTER=2
if %COUNTER%==0 set COUNTER=1

A: A little bit late for the party, but it's an interessting question.
You can write your own inc.bat for incrementing a number.
It can increment numbers from 0 to 9998.
@echo off
if "%1"==":inc" goto :increment

call %0 :inc %counter0%
set counter0=%_cnt%
if %_overflow%==0 goto :exit

call %0 :inc %counter1%
set counter1=%_cnt%
if %_overflow%==0 goto :exit

call %0 :inc %counter2%
set counter2=%_cnt%
if %_overflow%==0 goto :exit

call %0 :inc %counter3%
set counter3=%_cnt%
goto :exit

:increment
set _overflow=0
set _cnt=%2

if "%_cnt%"=="" set _cnt=0

if %_cnt%==9 goto :overflow
if %_cnt%==8 set _cnt=9
if %_cnt%==7 set _cnt=8
if %_cnt%==6 set _cnt=7
if %_cnt%==5 set _cnt=6
if %_cnt%==4 set _cnt=5
if %_cnt%==3 set _cnt=4
if %_cnt%==2 set _cnt=3
if %_cnt%==1 set _cnt=2
if %_cnt%==0 set _cnt=1
goto :exit

:overflow
set _cnt=0
set _overflow=1
goto :exit

:exit
set count=%counter3%%counter2%%counter1%%counter0%

A sample for using it is here
@echo off
set counter0=0
set counter1=
set counter2=
set counter3=

:loop
call inc.bat
echo %count%
if not %count%==250 goto :loop

A: I've found my own solution.
Download FreeDOS from here:
http://chtaube.eu/computers/freedos/bootable-usb/
Then using my Counter.exe file (which basically generates a Counter.txt file and increments the number inside every time it's being called), I can assign the value of the number to a variable using:
Set /P Variable =< Counter.txt

Then, I can check if it has run 250 cycles by doing:
if %variable%==250 echo PASS

BTW, I still can't use Set /A since FreeDOS doesn't support this command, but at least it supports the Set /P command.

A: I didn't use DOS for - puh - feels like decades, but based on an old answer and my memories, the following should work (although I got no feedback, the answer was accepted, so it seems to work):
@echo off
  REM init.txt should already exist
  REM to create it:
  REM   COPY CON INIT.TXT
  REM   SET VARIABLE=^Z
  REM ( press Ctrl-Z to generate ^Z )
  REM
  REM also the file "temp.txt" should exist.
REM add another "x" to a file:
echo x>>count.txt
REM count the lines in the file and put it in a tempfile:
type count.txt|find /v /c "" >temp.txt

REM join init.txt and temp.txt to varset.bat:
copy init.txt+temp.txt varset.bat
REM execute it to set %variable%:
call varset.bat

for %%i in (%variable%) do set numb=%%i
echo Count is: %numb%
   REM just because I'm curious, does the following work? :
   set numb2=%variable%
   echo numb2 is now %var2%
if %numb%==250 goto :finished
echo another boot...
warmboot.exe
:finished
echo that was the last one.

In DOS, neither set /a nor set /p exist, so we have to work around that.
I think both for %%i in (%variable%) do set numb=%%i and set numb2=%variable% will work, but I can't verify.
WARNING: as there is no ">" or "<" comparison in DOS, you should delete the batchfile at the :finished label (because it continues to increment and 251 is not equal 250 anymore)
(PS: the basic idea is from here. Thanks foxidrive. I knew, I knew it from StackOverflow but had a hard time to find it again)

A: Coming to the party very very late, but from my old memory of DOS batch files, you can keep adding a character to the string each loop then look for a string of that many of that character.  for 250 iterations, you either have a very long "cycles" string, or you have one loop inside using one set of variables counting to 10, then another loop outside that uses another set of variable counting to 25.
Here is the basic loop to 30:
@echo off
rem put how many dots you want to loop
set cycles=..............................
set cntr=
:LOOP
set cntr=%cntr%.
echo around we go again
if "%cycles%"=="%cntr%" goto done
goto loop
:DONE
echo around we went

A: I built my answer thanks to previous contributors.
Not having time for a custom counter.exe, I downloaded sed for FREEDOS.
And then the batch code could be, emulating "wc -l" with the utility sed, something like this according to your loop (I just use it to increment through executions starting from "1" to n+1):
Just remember to manually create a file "test.txt" with written on the first row

0

sed -n '$=' test.txt > counter.txt
set /P Var=< counter.txt
echo 0 >> test.txt

A: Directly from the command line:
 for /L %n in (1,1,100) do @echo %n

Using a batch file:
 @echo off
 for /L %%n in (1,1,100) do echo %%n

Displays:
 1
 2
 3
 ...
 100

A: None of these seemed to work for me:
@ECHO OFF

REM 1. Initialize our counter
SET /A "c=0"

REM Iterate through a dummy list.
REM Notice how the counter is used: "CALL ECHO %%c%%"
FOR /L %%i in (10,1,20) DO (

  REM 2. Increment counter
  SET /A "c+=1"

  REM 3. Print our counter "%c%" and some dummy data "%%i"
  CALL ECHO Line %%c%%: - Data: %%i
)

The answer was extracted from: https://www.tutorialspoint.com/batch_script/batch_script_arrays.htm (Section: Length of an Array)
Result:
Line 1: - Data: 10
Line 2: - Data: 11
Line 3: - Data: 12
Line 4: - Data: 13
Line 5: - Data: 14
Line 6: - Data: 15
Line 7: - Data: 16
Line 8: - Data: 17
Line 9: - Data: 18
Line 10: - Data: 19
Line 11: - Data: 20

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to highlight the rows in google spreadsheet if the first column value is date? I am very new to google spreadsheet and trying to use conditional Formatting to highlight the rows only if the first column value is Date.

*

*shared public google spreadsheet:  https://docs.google.com/spreadsheets/d/10NzbtJhQj4hQBnZXcmwise3bLBIAWrE0qwSus_bz7a0/edit#gid=1405439211
My attempt
=not (isblank($A4))

// This is not working.
// But A4 is not fixed, on a new day if I insert some rows, $A4 might be $A5 and it may not work.

Example google sheet

*

*this sheet has two columns Date and Contents.

*I want to highlight rows only when first value is date as shown below

Date     Contents

Dec 22   hello  --> highlight this row, since it has date on column Date
         hi      ---> don't hightlight this

Dec 21  This is another data and needs to be highlighted
        dont highlight me
        dont highlight me

Dec 20  highlight me

And so on.

A: Try this formula
=$A1<>""


text:
Q: How to use substring with replace in one query? Hi How can I add REPLACE to the following query?
SELECT SUBSTRING(title,1,1) AS titlealpha,
COUNT(title)
FROM serien
WHERE not_seen =''
GROUP BY titlealpha;

From an alphabetical list, with titlealpha I try to replace extraordinary letters, like öäüéàè, into normal abc... letters.
REPLACE(titlealpha, 'ä', 'a')
REPLACE(titlealpha, 'ö', 'o')

Is there also a short, clean way?

A: a easy way is to replace the this in all rows. MySQL only write the Record if it change
like
UPDATE serien set title = replace(title, 'ä' , 'a');

or you can put multi replaces in one Statement
UPDATE serien set title = REPLACE( REPLACE(title, 'ä' , 'a'), 'Ä', 'A');

ans so on

A: try
SELECT REPLACE(REPLACE(SUBSTRING(title,1,1), 'ä', 'a'), 'ö', 'o')
AS titlealpha,
COUNT(title)
FROM serien
WHERE not_seen =''
GROUP BY titlealpha;


text:
Q: Facebook graph api, get gender of friends I'm trying to breakup my list of friends by gender but I don't know how to get the the friends gender from their id and list the friends by gender. Currently I have their id and profile pic listed. Essentially all I need is how to get their gender and sort the friends.
     for friend in friends
  .col-xs-3.col-md-2
    p #{friend.id}
    a.thumbnail(href='http://facebook.com/#{friend.id}')
      img(src='https://graph.facebook.com/#{friend.id}/picture?width=150&height=150')

 exports.getFacebook = function(req, res, next) {
 var token = _.find(req.user.tokens, { kind: 'facebook' });
 graph.setAccessToken(token.accessToken);
 async.parallel({
getMe: function(done) {
  graph.get(req.user.facebook, function(err, me) {
    done(err, me);
  });
},
getMyFriends: function(done) {
  graph.get(req.user.facebook + '/friends', function(err, friends) {
    done(err, friends.data);
  });
}
 },
 function(err, results) {
if (err) return next(err);
res.render('api/facebook', {
  title: 'Facebook API',
  me: results.getMe,
  friends: results.getMyFriends
});
});
};

A: Within your getMyFriends function make an API call to graph.facebook.com/me/friends?fields=name,gender
Each item in the response will look something like
{
      "name": "phwd",
      "gender": "male",
      "id": "113702895386410"
}

From there you can break it up.
You can also do /FRIEND_ID?fields=name,gender
These calls will of course have to be appended with an access token or be returned via an SDK call.


text:
Q: Establishing Entity Framework Entity addition & ADO.Net stored procedure INSERTS together inside a single Transaction I have an application where I am using Entity Framework or handle data from database tables. There is a main table, CUSTOMER which is is linked to 3 other tables through foreign keys. The linked tables are
RENTAL
PAYMENTS
VEHICLES

I am able to  add / edit / delete entities on all these 4 tables using EF.
I would like to change the current scenario (where EF is used to handle all DB transaction) to something like this.

After I create a new entity and when try to save the entities (5 new
  entities/records) back to the database, I would like to use a stored
  procedure to add the new entity to VEHICLES model and use EF to save
  entities to all other models - and still gat all this down under one
  single transaction.
Also, I have to wait till the EF call is completed, since I need the
  new  CUSTOMER_ID created as part of EF save to be passed on as an
  input parameter to the stored procedure to save VEHICLES entity.

I don't want to call the stored procedure from outside the transaction, thus if the Stored Procedure call fails, the changes made to the database through EF also are rolled back.
Anyone have any idea how to get this accomplished?
PS : Not looking for any code samples; a high level illustration will help.
I am using Entity Framework 5, .Net v4.5, VS 2013, Oracle 11g, ODP.Net

A: Map stored procs to Entity
1) Create the stored procedure(s)
2) Update your data model to include the stored procedure(s)
- "Update Model From Database" menu via EF 6.x
3) Then find the Entity (or create a new Entity) in the Entity Data Model and hook up Stored Procs to Insert, Update, and Delete Functions
 - right click the Entity and select "Stored Procedure Mapping" menu
4) Use LinqToEntity to add/modify the entities with Database.BeginTransaction()
then call SaveChanges() on context, then Commit or Rollback.
Note: Starting with EF6 Database.ExecuteSqlCommand() by default will wrap the command in a transaction if one was not already present. There are overloads of this method that allow you to override this behavior if you wish. Also in EF6 execution of stored procedures included in the model through APIs such as ObjectContext.ExecuteFunction() does the same (except that the default behavior cannot at the moment be overridden). In either case, the isolation level of the transaction is whatever isolation level the database provider considers its default setting. By default, for instance, on SQL Server this is READ COMMITTED.
https://msdn.microsoft.com/en-us/data/dn456843.aspx


text:
Q: ndk-build NDK_TOOLCHAIN_VERSION 4.8 vs clang Some time ago I developed a jni wrapper for the C libspeex audio codec.
Recently I had some problem in compiling and running this with the ndk r10e, since the audio encode function crashed in runtime.
Finally I found that when I compile with
NDK_TOOLCHAIN_VERSION:=4.8

the native code runs while with
NDK_TOOLCHAIN_VERSION:=clang

it crashes. I wonder about the difference between the two toolchains.
The logcat of the crash:
11-02 14:26:33.642 1908-1908/com.ermes.intau D/dalvikvm: GC_FOR_ALLOC freed 1248K, 20% free 34140K/42456K, paused 102ms, total 102ms
11-02 14:26:33.642 1908-2514/com.ermes.intau A/libc: Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 2514 (Thread-103909)
11-02 14:26:33.742 1908-1908/com.ermes.intau D/dalvikvm: GC_FOR_ALLOC freed 6K, 18% free 34883K/42456K, paused 89ms, total 89ms

A: gcc and clang are completely different C compilers. They have no common code.
Of course they aren't developed in a vacuum. The developers of both compilers do compete with each other to generate the best / fastest machine code. While the optimisations they both perform may be based on the same ideas, they both have different edge cases that will be compiled differently.
With clang being the newest compiler to be developed, they do try to compile other open source projects that have a history of being compiled by gcc. With either clang or the open source project being changed whenever bugs are found.
The C language standard also leaves a lot of behaviour undefined. Things like dividing by zero, dereferencing a NULL pointer, signed integer overflows, alignment of stack allocations... Both compilers will exploit these edge cases to generate faster code. If a block of code "might" do something weird, the compiler can assume that the developer knows what they are doing and have handled these cases elsewhere.
http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html


text:
Q: Mysql - Como eliminar registros que superaron un tiempo determinado desde su momento de creacion? Tengo un formulario de inicio de sesion juntamente con una opcion para reestablecer su contraseña, cuando el usuario solicita reestablecer su contraseña el sistema automaticamente le envia un codigo de seguridad a su correo electronico que posteriormente el usuario lo tiene que introducir para autorizar el cambio de contraseña. Este codigo se almacena en una tabla de mi base de datos y lo que trato de hacer es de que todos aquellos codigos que hayan superado los 60 minutos desde su fecha de creacion sean eliminados ya que el codigo solo tendra una vigencia de 1 hora (60 min). Tengo el siguiente script en php pero no funciona.
private function actualizarCodigos(){
        /**
         * EN ESTA FUNCION LO QUE SE HACE ES ELIMINAR LOS CODIGOS QUE EXPIRARON LOS 60MIN(1 HORA).
         */
        try {
            $this->clase_dbconexion = new dbconexion();
            $conexion = $this->clase_dbconexion->conectar();
            $consulta = $conexion->prepare("DELETE FROM aclcose WHERE cacofeccre > DATE_ADD(NOW(), INTERVAL 60 MINUTE)");
            $consulta->execute();
            $conexion = $this->clase_dbconexion->desconectar($conexion);
            return true;

        } catch (PDOException $exception) {
            //echo('Se produjo un error al registrar en la tabla Cliente: ' . $exception->getMessage());
            return false;
        }
    }

*

*cacocorele = Correo electronico.

*cacofeccre = Fecha de Creacion.

*cacocodseg = Codigo de Seguridad.

A: Analicemos la condicion que usas
cacofeccre > DATE_ADD(NOW(), INTERVAL 60 MINUTE)

O sea, estamos buscando que cacofeccre (ni voy a preguntar por el nombre del campo) sea mayor que este momento mas 60 minutos.
Y no, eso nunca va a pasar.. si cacofeccre es un momento en el pasado, nunca va a ser mayor a un momento que es ahora (que es el futuro) mas 60 minutos (que es mas futuro que ese futuro de antes)
lo que vos querias, realmente, es que cacofeccre + 60 minutos fuera menor a este momento... o sea, haya pasado mas de una hora...
prueba asi:
DATE_ADD(cacofeccre, INTERVAL 60 MINUTE) < NOW()


text:
Q: .Net equivalent of Swift map and reduce I got this operation:
let lines = (0..<linesCount).map({ _ in "\n" }).reduce("", +)

lineCount is an integer.
How can I convert this code to C#?
I have written something with Enumerable.Range(1, linesCount) and .Select(...) linked to .Aggregate(...) but I don't know what to put in (...) to get the exact same result as the Swift line.

A: Please try this code:
var linesCount = 4;
var lines = Enumerable
    .Range(1, linesCount)
    .Select(i => "\n")
    .Aggregate((c, n) => $"{c}{n}");

However if you only need to create a string of single char that repeated several times you can use string constructor:
var lines = new string('\n', linesCount);

A: MapReduce in C#
Map in C#
static void Main(string[] args)
{
   var testList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   var mapList = Map<int, int>(x => x + 2, testList);

   mapList.ToList<int>().ForEach(i => Console.Write(i + " "));
   Console.WriteLine();
   Console.ReadKey();
}

static IEnumerable<TResult> Map<T, TResult>(Func<T,TResult> func,
IEnumerable<T> list)
{
    foreach (var i in list)
       yield return func(i);
}

Reduce in C#
static void Main(string[] args)
{
   var testList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   Console.WriteLine(Reduce<int, int>((x, y) => x + y, testList, 0));
   Console.ReadKey();
}

static T Reduce<T, U>(Func<U, T, T> func, IEnumerable<U> list, T acc)
{
   foreach (var i in list)
       acc = func(i, acc);

   return acc;
}


text:
Q: Find the number of vertices in the graph Let $n\ge 1$ and $V_n = (\left\{ 1,2,...n \right\}\rightarrow\left\{ 0,1,2 \right\})$.
Let us define $G_n = \left<V_n, E_n \right>$. $f,g$, are two vertices. They are connected iff:
$$\left|\{ i \in \left\{ 1,...n\right\} | f(i)+g(i)=1 \right\}| = 1$$
Prove that the number of edges is: $$\sum\nolimits_{k = 0}^n {k\left( {\matrix{
   n  \cr
   k  \cr
 } } \right)} {4^{k - 1}} \cdot {3^{n - k}}$$
My approach was "creating" a $2\times 2n$ table where the columns $(0,1), (1,0)$ are allowed to appear only once (and only one of them). I couldn't figure out how to connect this approach to the desired formula. I'll be glad for help!

A: If $f\in V_n$, let's define its paramater $k$ as $|\{i: f(i)\leq 1\}|$. Let's call $I_f=\{i: f(i)\leq 1\}$.
Let $f$ be a function of parameter $k$, and let's count its neighbours.
We build a generic neighbour $g$.
First, we have to choose the index $i$ for which $g(i)+f(i)=1$. This is only possible if $i\in I_f$, so we have $k$ choices for $i$. Then, we have to avoid $1$ on the other indices of $I_f$, so we have $2^{k-1}$ choices for $g$'s values on the rest of $I_f$. Finally, we can choose anything for the $n-k$ other values, so we have $3^{n-k}$choices.
In total, $f$ has $k2^{k-1}3^{n-k}$ neighbours.
Now, we just need to count the number of $f$ with parameter $k$. We have $n \choose k$ choices for the set $I_f$. Then, we have $2^k$ choices for the values of $I_f$, and none outside (it has to be $2$).
So the number of $f$ with parameter $k$ is $2^k {n\choose k}$.
Finally, we sum all these neighbours for all $f$, and we get the formula $$2|E_n|=\sum_{k=0}^n2^k{n\choose k}\cdot k 2^{k-1}  3^{n-k}$$
Remember that the sum of degrees is twice the number of edges, because each edge is counted twice. Simplifying gives us the wanted formula.


text:
Q: "Fancy Button" Click Event not firing I am working on a fancy design for a ASPX page, but I am having problems firing the buttons to run code. Here's what I have:
This is the ASPX code:
<button runat="server" id="btnLogin" onserverclick="LoginClick_Click"></button>

And the codebehind:
protected void LoginClick_Click(object sender, EventArgs e)
    {
        notice.Visible = true;

   //     Response.Redirect("");

    }

I am clicking the button to see if anything shows up (even to a Blank broken page [yes I uncommented it]) but no go. I believe this is something simple but I've been struggling here for nearly an hour and no go. Joys of coding I guess.
Edit:
 <button runat="server" id="btnLogin" OnServerClick="btnLogin_Click" ></button>

That worked. Capitalization it seems.

A: You need to be more careful with your syntax.
<asp:Button runat="server" id="btnLogin" OnClick="btnLogin_Click" />

Code behind
protected void btnLogin_Click(object sender, EventArgs e)
    {
        notice.Visible = true;
    }

A: If you're really interested in using a different button from an ASP control, you might want to just poke a hidden ASP button with the desired functionality using some inline javascript and jquery...
<asp:Button ID="btnLogin" runat="server" Visible="False" />
<button type="button" id="btnFancy" onclick="serverClick();">TextHere</button>

--
<script type="text/javascript">
function serverClick() {
    $('#<%=btnLogin.ClientID%>').click();
    }
</script>

I wouldn't suggest this, but it should work for you.


text:
Q: Using "as" instead of "that" (I don't know as this is valid) When answering the ELL question "I can't say as ever I was lost" quoted Daniel Boone, I said that having as instead of that in the cited context was a "dialectal, folksy" usage. Then I came up with these two examples...

1: Wealthy man that he is, John cannot buy happiness.
   2: Wealthy as he is, John cannot buy happiness.

...which both seem syntactically valid to my ear. I don't think I could say the same if the two highlighted words were swapped, but I'm less sure about that.
Can anyone explain what's going on here? And either support or refute my perception that #1 and #2 above are valid as presented, but not if the usages were reversed?

A: Your two examples become less liable to questions of interchangeability when they are both properly parsed as absolute constructions with ellipsis. When an absolute in sentence-initial position merely describes a state, such as being wealthy or a wealthy man, the participle is often omitted:

19.10.2017.  The astute politician that he is, Mr Odinga has been using allegory and riddles to tell his supporters how the electoral commission denied him of victory. — "Raila Odinga - the man Kenyans either love or loathe," BBC News.

In other contexts, the participle is usually expressed:

In a skewed way, Kathy's actions had forced Cory to make a better life for himself, but being the man he was, he would have done it anyway. — Gail Sattler, Dating the Best Man, 2015, 171.

and especially when the participle is not used absolutely:

Robbed of control by virtue of being a woman and the particular woman that she is, the anorexic, like the self-mutilating woman, has seized control over the one area that women are encouraged to control, and she is holding on to it desperately.— Bonnie Burstow, Radical Feminist Therapy: Working in the Context of Violence, 1992.

Your second example omits both the initial participle and the first conjunction in an adjectival as (adj.) as construction, which may or may not be expressed:

As intelligent as he is, he misjudges the evil of the others, believing they can be spoken with rationally and never realizes the seriousness of the situation and the potential for a deathly response. — Harold Bloom, William Golding's Lord of the Flies, Bloom's Guides, 2004, 14.

Though still current after say, the non-standard, highly colloquial as introducing a relative clause in the Daniel Boone citation was far more frequent and occurred in more contexts in earlier centuries than today:

'Why, I can't say as I know any real harm of her,' said her mother, 'unless it's as she's a Catholic.'
  'Totty Nancarrow a Catholic!' exclaimed Ackroyd. 'Why, I never knew that.'
  'Her mother was Irish, you see, an' I don't suppose as her father thought much about religion. I dessay there's some good people Catholics, but I can't say as I take much to them I know.' — George Gissing, Thyrza, 1887.
Dealing with the blues, but can't say as I'm suffering. Joseph M. Monks, filmmaker, born Queens NYC, Blog post, 8 Feb. 2017.

A: Someone named se16teddy posted about this at forum.wordreference.com:

The OED has this usage as No. 26 of as, adverb and conjunction.

*Introducing a noun clause, after say, know, think, etc.; = that conjunction 1a.

It marks this usage: Now England regional (southern) and U.S.
regional.
The OED's examples include the following:
1484 Caxton tr. G. de la Tour-Landry Bk. Knight of Tower (1971)
lxiiii. 94, I saye not as ye shalle be pryuely and allone one by
other.
1856 H. B. Stowe Dred xi. 100, I don't know as you'll like the
appearance of our place.
1997 F. Chappell Farewell I'm bound to leave
You 11, I don't know as I believe that talk.

It sounds quaint and folksy to my ear but not uncontemporary (is there a better word for that?).

A: Using either "that" or "as" there is valid.  HOWEVER, in your second example, you omit the word "man" after "as," which materially changes it from the first example.
In order to have the second example parallel the first example, you must include the word "man" beforehand like you do in the first.  While the second example is grammatical, by omitting "man," you change its meaning and structure to something different than the first example's.  That's because by eliminating the noun "man" after the adjective "wealthy," you are changing what is a left dislocation into an absolute phrase.
Examples:

*

*"I can't say as I'm surprised."

Source 1
Source 2
Source 3

*

*"I can't say that I'm surprised."

Source 4
Source 5
Source 6
Both of the above examples mean the exact same thing.
Do you see that "I can't say as ever I was lost" and "I can't say that ever I was lost" mean the same thing, but "I can't say as ever was lost" doesn't mean the same thing and is wrong?  Well, that's what you do when you eliminate the word "man" in your second example.  It's just that, unlike in your Daniel Boone quote, you've provided a construction where omitting the noun after "as," while changing the meaning and the construction, doesn't create a syntactical error like it does in the Daniel Boone quote.


text:
Q: Runtime exception in Initializing SQLiteOpenHelper constructor I have used a constructor for SQLiteOpenHelper as given below:
(I have already implemented onCreate() and onUpgrade() methods)
public class DB_todos extends SQLiteOpenHelper{

     DB_todos(Context context){
          super(context, DB_NAME, null, DB_VERSION);
  }
     ..........
}

The Runtime exception is:
Exception Ljava/lang/NullPointerException; thrown while initializing Lapp/quicklook/DB_todos;
I am confused if the way i have used the constructor is legitimate. Please give your inputs to resolve this.

A: Did you properly open the db  before accessing it ? You should open the db [ds.open() at the start of OnCreate() and ds.close() at the end og OnCreate()]


text:
Q: Why does Math::BigInt has wrong output? I need to get the nearest number $new to $orig divisible by $divisor. The $new should be greater than $orig. So I have come with the following formula (hopefully, there is no error in it):
$new = $orig + ($divisor - $orig % $divisor)

Now, the $orig number is an integer and has up to 30 digits. I want to implement this into a Perl function using Math::BigInt, but the output is quite wrong.
use Math::BigInt;

Math::BigInt->accuracy(60);
Math::BigInt->precision(60);

my $orig = Math::BigInt->new('5967920747812842369477355441');  # A
my $divisor = Math::BigInt->new('719');                        # B
my $modulo = $orig->bmod($divisor);  # A % B = M
my $diff = $divisor->bsub($modulo);  # B - M = D
my $new = $orig->badd($diff);        # A + D = N
my $test = $new->bdiv($divisor);     # N / B = 0

print("orig : $orig\n");      # 10; should be: 5967920747812842369477355441
print("modulo : $modulo\n");  # 10; should be: 648
print("diff : $diff\n");      # 71; should be: 71
print("new : $new\n");        # 10; should be: 5967920747812842369477355512
print("test : $test\n");      # 10; should be: 0

A: https://metacpan.org/pod/Math::BigInt#Arithmetic-methods : "These methods modify the invocand object and returns it."  In other words, bmod, bsub, and badd are like %=, -=, and +=, not like %, -, and +.
So everywhere where you call one of the arithmetic methods, you should copy first, so the object you are currently calling the method on isn't changed:
use Math::BigInt;

Math::BigInt->accuracy(60);
Math::BigInt->precision(60);

my $orig = Math::BigInt->new('5967920747812842369477355441');  # A
my $divisor = Math::BigInt->new('719');                        # B
my $modulo = $orig->copy->bmod($divisor);  # A % B = M
my $diff = $divisor->copy->bsub($modulo);  # B - M = D
my $new = $orig->copy->badd($diff);        # A + D = N
my $test = $new->copy->bmod($divisor);     # N % B = 0

print("orig : $orig\n");      # 10; should be: 5967920747812842369477355441
print("modulo : $modulo\n");  # 10; should be: 648
print("diff : $diff\n");      # 71; should be: 71
print("new : $new\n");        # 10; should be: 5967920747812842369477355512
print("test : $test\n");      # 10; should be: 0

(Also changed your test to do modulus, not division.)


text:
Q: visual studio не компилирует проект angular 2 Пытаюсь запустить "quickstart angular 2" посредством visual studio и получаю кучу ошибок типа:
Cannot find name 'Map'.
Cannot find name 'Promise
при этом если делать просто с помощью npm start, все нормально работает.
Буду благодарен за помощь.

A: Это дело не в студии ,а в том что у вас не установлены typings.
npm typings intall


text:
Q: In source insight, how to directly jump to project window text box? In source insight, to access source file, I use project window very often.
I type few letters or word contained in the name of the file I look for in project window text box to find the target file quickly.
However, to do that, I need to click the project window text box using mouse and it's a little bit annoying.
The question is "is there any keyboard shortcut to directly get to project window text box?"

A: I got how to do it.
In [Option] - [Key Assignments], assign your customized key to "Navigation: Activate Project Window". That's it!


text:
Q: reverse date javascript from yyyy/mm/dd to dd/mm/yyyy I making an asp project and the date is displayed as yyyy/mm/dd but when the user press on the edit button for the form i need to replace the date format with dd/mm/yyyy
this the asp code remember i need the user to show the date as yyyy/mm/dd in the table but when he pressing on a button i need the date to be reversed to dd/mm/yyyy
 @EnnotaBAL.ArabicEncoding.GetArabicNumbers(transaction.PostDate.ToString("yyyy/MM/dd"))

and this the javascript code for the date element:
// Transaction Date
var TransDate = oCells.item(4).innerHTML;
document.getElementById('Date').value = convertDigitIn(TransDate);

A: function convertDigitIn(str){
   return str.split('/').reverse().join('/');
}


text:
Q: Substract values in a column based on the values of 2 other columns I have the dataframe below
vol<-structure(list(activity = c("RAAMELK", "RAAMELK", "Separering",
"Separering", "Sweetmilk Pasteurizer 8331", "Sweetmilk Pasteurizer 8331",
"9004 - T42 kartong 70x70", "9004 - T42 kartong 70x70", "9006 - T61 BIB",
"9006 - T61 BIB", "9004 - T41 kartong 70x70", "9004 - T41 kartong 70x70"
), qty = c(0, 31, 31, 9, 31, 31, 6, 6, 3, 3, 28, 28), in_out = c("in",
"out", "in", "out", "in", "out", "in", "out", "in", "out", "in",
"out"), qty_scrap = c(0, 0, 0, 0, 0, -270.64, 0, 524, 0, 260,
0, 0)),
row.names = c(NA, -12L), case_id = "case_id", activity_id = "activity",
activity_instance_id = "action", lifecycle_id = "registration_type",
resource_id = "resource", timestamp = "timestamp",
class = c("eventlog", "log", "tbl_df", "tbl", "data.frame"))

And I want to subtract the values on column qty based on if they have the same value in column activity and with the logic in-out from the in_out column. The result will be saved in the qty_scrap column.
The result dataframe will then have 4 columns. The activity column with the unique name of the activity, the in column with the in value of the qty, the out column with the out value of the qty and the qty_scrap column with their difference.

A: You can reshape your data to a wider format, and then mutate your scrape column by subtracting the in and out columns.
library(dplyr)
library(tidyr)

vol %>%
  pivot_wider(id_cols = "activity", names_from = "in_out", values_from = "qty") %>%
  mutate(qty_scrap = `in` - out)

#> # A tibble: 6 x 4
#>   activity                    `in`   out qty_scrap
#>   <chr>                      <dbl> <dbl>     <dbl>
#> 1 RAAMELK                        0    31       -31
#> 2 Separering                    31     9        22
#> 3 Sweetmilk Pasteurizer 8331    31    31         0
#> 4 9004 - T42 kartong 70x70       6     6         0
#> 5 9006 - T61 BIB                 3     3         0
#> 6 9004 - T41 kartong 70x70      28    28         0

Created on 2023-01-24 by the reprex package (v2.0.1)

A: You could try this:
vol %>%
  group_by(activity) %>%
  mutate(qty_scrap = head(qty, 1) - tail(qty, 1)) %>%
  tidyr::pivot_wider(names_from = in_out, values_from = qty) %>%
  select(activity, `in`, out, qty_scrap)

Output
#   activity                    `in`   out qty_scrap
#   <chr>                      <dbl> <dbl>     <dbl>
# 1 RAAMELK                        0    31       -31
# 2 Separering                    31     9        22
# 3 Sweetmilk Pasteurizer 8331    31    31         0
# 4 9004 - T42 kartong 70x70       6     6         0
# 5 9006 - T61 BIB                 3     3         0
# 6 9004 - T41 kartong 70x70      28    28         0


text:
Q: How can i make my iframe app visible for everyone? I'm new to Facebook app development and I ran into a stupid issue:
I made a simple app consisting of a flash player embedded in an iframe stored on my server and then I added it (as a tab) to a Facebook Event page I also created.
My problem is that the iframe will only load the page's content if the user's role is mapped in the app settings; it works fine for me since I'm the administrator and I believe my test users can also see it quite well, but for everyone else the iframe is blank.
Any ideas on how to make it visible for everyone?
Thanks in advance
Edit:

*

*Content page is here:
http://livextend.com/facebook/nosajthing_musicbox/

*Tab is here:
http://www.facebook.com/pages/Nosaj-Thing-no-Musicbox/174470872628888?sk=app_214393448619749

A: Sounds like your app is in Sandbox Mode. If it is, you're right - only Admin, Devs, and Testers will be able to use / see the app. If you want everyone to see it, disable Sandbox Mode:

*

*Go to https://developers.facebook.com/apps/

*Select your app and then Edit Settings

*Settings > Advanced

*In Authentication section, set Sandbox Mode to Disabled


text: Q: Good introduction to many-body Green's function via path integral formulation? Can anyone kindly provide any information on valuable references or books on this topic? It appears to be prevalent in 90s papers on High-$T_c$ superconductivity or quantum Hall effect, especially in a form of fermions interacting with $U(1)$ gauge field.


text:
Q: Create TextView from template XML file I have a template of simple TextView in a file simple_txt.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="30dp"
    android:textSize="18sp" >
</TextView>

In some code I need to create a TextView from this template, something like:
TextView txt = new TextView(this);
txt.setLayout(R.layout.simple_txt);//???

then do something with it (setText etc.). How can I create a TextView like this?

A: TextView txt = (TextView) View.inflate(this, R.layout.simple_txt, null);


text:
Q: Array.includes returning false in Chrome Extension While trying to check if an item is in the array in a chrome extension, its returning false with array.includes() method.
Here is the code for checking
chrome.storage.sync.get({
        blockedUrl: []
    }, items => {
        let list = items.blockedUrl;
        let n = list.includes("example.com");
        document.getElementById('test').innerHTML = n;
    });

console.log(list) returns full array with all items (including example.com).
Any suggestion is much appreciated.


text:
Q: How to encode and decode SecretKey in JAVA? KeyStore ks = KeyStore.getInstance("JCEKS");
ks.load(null, null);
SecretKey skInput = new SecretKeySpec("input".getBytes(), "DESede");
SecretKeyEntry skeInput = new KeyStore.SecretKeyEntry(skInput);
ks.setEntry("input_key", skeInput, new KeyStore.PasswordProtection("banana".toCharArray()));
FileOutputStream fos = new FileOutputStream("my.keystore");
pambks.store(fos, "password".toCharArray());
fos.flush();
fos.close();

The code shown above is trying to encode the input into a SecretKey and store into keystore. The code shown below is how I retrieve the key from keystore. But I do not know how to decode it back to original value?
FileInputStream fin = new FileInputStream("my.keystore");
KeyStore ks = KeyStore.getInstance("JCEKS");
ks.load(fin, "password".toCharArray());
SecretKeyEntry ske = (SecretKeyEntry) readks.getEntry("input_key", new KeyStore.PasswordProtection("banana".toCharArray()));
SecretKey sk = ske.getSecretKey();

I wasn't sure whether this is the correct way of doing encryption and decryption to SecretKey, please correct me if I'm wrong.

A: Reading back this Q/A I think I've misread the question.
You can get the byte representation of the key back by calling the getEncoded method on you key. After that it is possible to use one of the String constructors to revert it back to text. As said, you should not use a string as key. Note that DES keys are contain parity in the last bit, so this may change the result. To use strings for keys it is more advisable to use hexadecimals. Note that keys should have enough entropy, and a string is not likely to provide that.

There are several things not entirely correct in the code above:

*

*You should not (ever) use "input".getBytes(). First of all, getBytes() uses a platform specific default character encoding. If you want to use a DES key as a String, decode it with a decoder of hexadecimals (e.g. in Apache Commons codec or Bouncy Castle).

*You should use 24 bytes for DESede keys. "input".getBytes() does not return enough bytes.

*For DES keys it pays to put the key specification through a KeyFactory if only to make sure that the parity bits are set. They you will be sure that the key is valid.
To get a good amount of key data, use PBKDF2 for passwords or use randomly generated keys.
If an encrypted key store is good enough storage for an encrypted key depends on the use case and the other security measures.


text:
Q: sftp - "protocol error: mtime.sec not present" when using /usr/sbin/nologin I am trying to use sftp to pull a file from a remote server.
Both client and server-side users are created with adduser --system and their shell is /usr/sbin/nologin. The users are called legit-backup.
Public-key authorisation has been configured for the client user to have SSH access to the server as a user of the same name. When I try to pull down the file /home/legit-backup/test a file using the command sudo -u legit-backup scp legit-backup@<remote-server>:~/test, I receive the error protocol error: mtime.sec not present, no files copy down.
If I change the remote user's shell to /bin/bash then sftp works as normal.
I wan to use /usr/sbin/nologin for security reasons, the user should not be able to have SSH access other than sftp, is it possible?


text:
Q: Regular Expression for First Name and Last Name in a single field I have a scenario where user has to enter its first Name and last name in a single field, so there must be a space between 2 names, and after space there must be atleast  a character. I tried to using contains(""), but this method returns true if user just enter a space and does not enter anything after that space.
Kindly guide me a way to achieve this. I have also tried to search Regular Expression but failed to find any.

A: You can use code like this:
public static void main(String[] args) throws IOException {
    String input = "first last";
    if (input.matches("[a-zA-Z]*[\\s]{1}[a-zA-Z].*")) {
        String[] name = input.split(" ");
        System.out.println(Arrays.toString(name));
    } else {
        System.out.println("Please input the valid name.");
    }
}

It will put first name and last name to array if:

*

*[a-zA-Z]* - input begins with characters;

*[\\s]{1} - contains only one space;

*[a-zA-Z].* - ends with at least one character.

A: Here is the regex and a test:
@Test
public void test_firstAndLastName_success() {
  Pattern ptrn = Pattern.compile("(\\w+)\\s+(\\w+)");
  Matcher matcher = ptrn.matcher("FirstName  LastName");
  if (matcher.find()) {
    Assert.assertEquals("FirstName", matcher.group(1));
    Assert.assertEquals("LastName", matcher.group(2));
  } else {
    Assert.fail();
  }
}

The validation is the matcher returning false on find.
If you do not want to permit multiple spaces (\s+) then either remove + (which will still permit for a single tab) or replace it with a space.

A: A simple split using " " will do after trimming the string.
Please check the below code for more understanding :
String[] splitter = null;

String s = "abbsd sdsdf"; // string with 2 words and space

    splitter = s.trim().split(" ");

    if(splitter.length!=2){
        System.out.println("Please enter first or last name");
    }
    else{
        System.out.println("First Name : "+splitter[0]);
        System.out.println("Last Name : "+splitter[1]);
    }

    s = "abc"; //string without space

    splitter = s.trim().split(" ");

    if(splitter.length!=2){
        System.out.println("Please enter first or last name");
    }
    else{
        System.out.println("First Name : "+splitter[0]);
        System.out.println("Last Name : "+splitter[1]);
    }

Please check with other scenarios with and without space. This should be helpful.


text:
Q: Binary matrix multiplication I am following an academic lecture on coding theory. The following matrix multiplication is done at the lecture. I paste a clear screenshot of the frame below.

As stated on the figure, I do not understand how such a simplification (indicated by the red arrow)  can be done. I would so much appreciate an elaborative answer which explains how this simplification. (the YouTube link opens the exact time he mentions this)
I truly appreciate for your valuable time.

A: Assuming the coefficients are mod 2,

\begin{align*}
&v_0 = u_0 + u_2 + u_3\\[4pt]
\implies\;&v_0 - u_0 - u_2 - u_3 = 0\\[4pt]
\implies\;&v_0 + u_0 + u_2 + u_3 = 0\qquad\text{[since $-1 \equiv 1 \pmod 2$]}\\[4pt]
\end{align*}

A: we know that
v0 = u0+u2+u3

*

*so, v0+u0+u2+u3 = 2 x v0

*in binary, 2 x 'anything' = 'anything' shifted left with '0' shifted in from right

*so the least significant bit is '0'


text:
Q: write client side api that uses libraries I've written the server side of an api, that serves html via json using REST via codeigniter.
I'm investigating how to write a client side api with javascript, to get the data from the server via the api, present it in the dom and bind events to it.
One of the things I need at the client side is jquery. Now I'm wondering what happens if the client already is using another version of jquery, that conflicts the version I need?

A: It's possible to use multiple versions of jquery simultaneously by assigning jQuery.noConflict() to a variable right after the jquery version is loaded. Then just use that variable as your reference to the version you need.


text:
Q: Speeding up realtime Gui updates from a thread This is a technique I've used for years to receive network data and use it in my GUI (dialog, form etc).
    public delegate void mydelegate(Byte[] message);

    public ReceiveEngineCS(String LocalIpIn, String ReceiveFromIp, mydelegate d)
    {
         this.m_LocalIpIn = LocalIpIn;
         this.m_ReceiveFromIp = ReceiveFromIp;
         m_MainCallback = d;
         SetupReceive();
         m_Running = true;
         //Create the Track receive thread and pass the parent (this)
         m_RtdirReceiveThread = new Thread(new ParameterizedThreadStart(MessageRecieveThread));
         m_RtdirReceiveThread.Start(this);
    }

    private void MessageRecieveThread(System.Object obj)
    {
         ReceiveEngineCS parent = (ReceiveEngineCS)obj;

         while(parent.m_Running)
         {
              Byte[] receiveBytes = new Byte[1500];
              try
              {
                   receiveBytes = parent.m_ClientReceiver.Receive(ref parent.ipEndPoint);
                   parent.ThreadOutput(receiveBytes);
              }
              catch ( Exception e )
              {
                  parent.StatusUpdate(e.ToString());
              }
         }
    }

    public void ThreadOutput(Byte[] message)
    {
         m_MainCallback(message);
    }

public partial class SystemMain : Form
{
    //Local Class Variables
    Network.ReceiveEngineCS SystemMessageReceiver;
    private void Form1_Load(object sender, EventArgs e)
    {
        //Load up the message receiver
        SystemMessageReceiver = new Network.ReceiveEngineCS(localAddy, fromAddy, new mydelegate(LocalDelegate));
    }

    public void LocalDelegate(Byte[] message)
    {
        if (Form.ListView.InvokeRequired)
        {
            //External call: invoke delegate
            Form.ListView.Invoke(new mydelegate(this.LocalDelegate), message);
        }
        else
        {
            //Get the Packet Header
            Formats.PacketHeaderObject ph = new Formats.PacketHeaderObject(message);
            //Update or Add item to Specific ListView
            ... update views
        }
    }
 }

The Receiver takes in anywhere between 10 and 100 real-time messages a second and often more.
I've been doing research lately into .Net 4.0 and C# and noticed many other similar ways to do this data processing
,such as Worker Threads, and other ways of using the Delegate and Invoke.
My question... Is there a more efficient way in the newer .Net Libraries (3.5, 4.0 etc) to do this data receive / GUI updating?
I think this method isn't working as well with C#.
Any help would be appreciated.

A: One of the best ways of posting updates to a GUI is to have the worker thread package up the data included in the update and place it in a queue. The UI thread will then poll the queue periodically. Having the worker thread use Control.Invoke to update the UI is way overused in my opinion. In contrast, having the UI thread poll for the updates has several advantages.

*

*It breaks the tight coupling between the UI and worker threads that Control.Invoke imposes.

*It puts the responsibility of updating the UI thread on the UI thread where it should belong anyway.

*The UI thread gets to dictate when and how often the update should take place.

*There is no risk of the UI message pump being overrun as would be the case with the marshaling techniques initiated by the worker thread.

*The worker thread does not have to wait for an acknowledgement that the update was performed before proceeding with its next steps (ie. you get more throughput on both the UI and worker threads).

You did not mention how ThreadOutput was implemented, but you might consider the approach I mentioned above if it is not already done that way. Experience has taught me that this is usually the best approach. Letting the UI thread throttle its update cycle is big a advantage.

A: Take a look into Thread Pooling instead of spinning new thread each time.


text:
Q: sorl-thumbnail unit tests fail by 1 pixel (!) I'm using sorl-thumbnail in a Django 1.2 (currently 1.2 RC) project and getting a surprising failure of four of sorl's built-in unit tests. Essentially, the resized images are all 1px shorter than the unit tests expect them to be. See below for details
I'm developing on OSX 10.5.8 (not Snow Leopard) with Python 2.5.1 (r251:54863, Feb  6 2009, 19:02:12) and PIL 1.1.6.
Any thoughts what might be up?
Cheers
Steve
======================================================================
FAIL: test_extension (sorl.thumbnail.tests.fields.FieldTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/fields.py", line 66, in test_extension
    self.verify_thumbnail((50, 37), thumb, expected_filename)
  File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/base.py", line 92, in verify_thumbnail
    self.assertEqual(image.size, expected_size)
AssertionError: (50, 38) != (50, 37)

======================================================================
FAIL: test_thumbnail (sorl.thumbnail.tests.fields.ImageWithThumbnailsFieldTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/fields.py", line 111, in test_thumbnail
    self.verify_thumbnail((50, 37), thumb, expected_filename)
  File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/base.py", line 92, in verify_thumbnail
    self.assertEqual(image.size, expected_size)
AssertionError: (50, 38) != (50, 37)

======================================================================
FAIL: testTag (sorl.thumbnail.tests.templatetags.ThumbnailTagTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/templatetags.py", line 118, in testTag
    self.verify_thumbnail((90, 67), expected_filename=expected_fn)
  File "/usr/local/django/myprojectnamehere/lib/sorl/thumbnail/tests/base.py", line 92, in verify_thumbnail
    self.assertEqual(image.size, expected_size)
AssertionError: (90, 68) != (90, 67)

A: Here's the hack that I used to work around this. I put the following in tests.py in my own app:
def monkeypatch_sorl_tests():
    from sorl.thumbnail.tests.base import BaseTest
    from sorl.thumbnail.tests.fields import FieldTest, ThumbnailFieldTest, ImageWithThumbnailsFieldTest
    def always_pass(*args, **kwargs):
        pass
    BaseTest.verify_thumbnail = always_pass
    FieldTest.test_extension = always_pass
    ImageWithThumbnailsFieldTest.test_thumbnail = always_pass
    ThumbnailFieldTest.test_thumbnail = always_pass

monkeypatch_sorl_tests()

Of course, this prevents some of the tests from running. But, assuming that the library has been tested on other systems, this shouldn't be too much of a problem.


text:
Q: Hermitian of the Dyson series If I have some time-dependent interaction Hamiltonian $H_I(\tau)$, with the interaction beginning in the asymptotic past ($\tau$$\rightarrow$$-\infty$) and ending in the asymptotic future ($\tau$$\rightarrow$$\infty$), then the first two terms in the Dyson series will read:
\begin{equation}
U=U^{(1)}+U^{(2)}+\cdots
\end{equation}
where
\begin{equation}
U^{(1)}=-i\int_{-\infty}^{\infty}d\tau H_I(\tau)
\end{equation}
\begin{equation}
U^{(2)}=-\int_{-\infty}^{\infty}d\tau\int_{-\infty}^{\infty}d\tau'\Theta(\tau-\tau')H_I(\tau)H_I(\tau').
\end{equation}
The interaction Hamiltonian is Hermitian $H_I^{\dagger}(\tau)=H_I(\tau)$. I want to calculate the first two terms of the series expansion of $U^{\dagger}$. I know that
\begin{equation}
U^{(1)\dagger}=i\int_{-\infty}^{\infty}d\tau H_I(\tau).
\end{equation}
My question is, when I write down $U^{(2)\dagger}$, do I reverse the time ordering (i.e, replace $\Theta(\tau-\tau')$ with $\Theta(\tau'-\tau)$), and write down
\begin{equation}
U^{(2)\dagger}=-\int_{-\infty}^{\infty}d\tau\int_{-\infty}^{\infty}d\tau'\Theta(\tau'-\tau)H_I(\tau)H_I(\tau'),
\end{equation}
or do I simply keep the term the same (since there is no factor of $i$. and the Hamiltonians are already Hermitian)?

A: Technically, when computing the hermitian conjugate of your $U^{(2)}$, you should leave the integration variables unchanged and only swap the Hamiltonians since $$(A B)^\dagger = B^\dagger A^\dagger,$$
and $H$ is assumed to be hermitian.
You could then relabel $\tau_1 \leftrightarrow \tau_2$ to explicitly see that this is not equivalent to simply exchanging $\tau_1$ with $\tau_2$:
$$\left(\int_0^\infty d\tau_1 \int_0^{\tau_1} d \tau_2 H(\tau_1) H(\tau_2) \right)^\dagger = \int_0^\infty d\tau_1 \int_0^{\tau_1} d \tau_2 H(\tau_2) H(\tau_1) =  \int_0^\infty d\tau_2 \int_0^{\tau_2} d \tau_1 H(\tau_1) H(\tau_2).$$
A highly recommended exercise is to use your series expansion to second order to explicitly show that $U^\dagger U = 1$, where it will be helpful to think about the limits of integration as the triangular areas obtained when dividing the first quadrant of the coordinate space $(\tau_1,\tau_2)$ by the line $\tau_1 = \tau_2$.


text:
Q: working with figures in python notebook in os x I am trying to work out the best way to work with figures in ipython notebook. This is a problem on os x but not in windows.
I have worked out how to put figures inline and in separate windows. What I'd like to do is put a figure in a separate window, leave it open and keep working on the notebook. But it seems I have to close the figure window to continue working on the notebook. How can I continue working on the notebook without closing the figure window?

A: The documentation was hard to parse, but I stumbled on the solution, which wasn't obvious to me.
On OS X, using ipython notebook, the magic command
%matplotlib osx
causes any external graphics windows to be interactive. That is, I don't have to type
show()
and I don't have to close the graphics window to continue working in the notebook.


text:
Q: Почему в посимвольном отображении string в php возникают кракозябры Файл в кодировке utf-8. В английских символах все в порядке. Например, "Hello"
символы отображаются корректно. Отображение проверяется в Chrome
   <?php
      $var = "Привет";
      echo $var;
      $i = mb_strlen($var);
      $it = 0;
      while($i != 0){
         echo $var{$it};
         $it++;
         $i--;
         echo "<br>";
      }


text:
Q: Change keyboard layout from C# code with .NET 4.5.2 I am coding away on my plugin for SDL Trados Studio.
The last part of the plugin requires some automation that is not exposed by the APIs at all, so all I have (hold on to something) is to automate the default keyboard shortcuts.
I have the code working perfectly for the English keyboard layout (and Hungarian, too!), but it of course does not work for Greek, Russian and so forth.
I have been searching for the solution but I was not able to find it until now, not on the web nor on SO, such as this post: Change keyboard layouts through code c#
I need to change the keyboard layout to English so it can take the correct shortcuts (and other character strings). Then I need to switch it back to what it was before. I am working with a very limited API, so I only have SendKeys at my disposal.
Here is the working code:
//Save the document
SendKeys.SendWait("^s");
//Open files view
SendKeys.SendWait("%v");

SendKeys.SendWait("i");
SendKeys.SendWait("1");
Application.DoEvents();

//get url and credentials from a custom input form
string[] psw = UploadData.GetPassword(
    Settings.GetValue("Upload", "Uri", ""),
    Vars.wsUsername == null ? Settings.GetValue("Upload", "User", "") : Vars.wsUsername,
    Vars.wsPassword == null ? "" : Vars.wsPassword
    );
Application.DoEvents();

if (psw != null)
{
    try
    {
        //start upload
        SendKeys.SendWait("%h");
        SendKeys.Send("r");

        //select all files
        SendKeys.Send("%a");
        SendKeys.Send("%n");
        //enter login url
        SendKeys.Send("%l");
        SendKeys.Send("{TAB}");
        SendKeys.Send(psw[0]);
        SendKeys.Send("{TAB}");
        SendKeys.Send("{ENTER}");

        //enter username
        SendKeys.Send("%l");
        SendKeys.Send("+{END}");
        SendKeys.Send(psw[1]);
        //enter credentials
        SendKeys.Send("%p");
        SendKeys.Send(SendEscape(psw[2]));
        SendKeys.Send("{ENTER}");
        //start upload
        SendKeys.SendWait("%f");
    }
    catch (Exception)
    {
        MessageBox.Show("Cannot do automatic upload, please use the default method of Trados Studio.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
    finally
    {
        //switch back to editor view
        SendKeys.SendWait("%vd");
    }
}

So the questions I have:

*

*Can somebody help me with a code to actually store the current keyboard layout and switch to English, then switch it back at the end?

*Is there a simpler solution? I tried to look at the native methods but it is too high for me, so I would really appreciate any help to convert my code into native if that is the way to go instead of switching the keyboard layout. Any suggestions?

A: Switching the keyboard layout requires some P/Invoke; you´ll need at least the following Windows functions to get it working: LoadKeyboardLayout, GetKeyboardLayout and ActivateKeyboardLayout. The following import declarations worked for me...
[DllImport("user32.dll",
    CallingConvention = CallingConvention.StdCall,
    CharSet = CharSet.Unicode,
    EntryPoint = "LoadKeyboardLayout",
    SetLastError = true,
    ThrowOnUnmappableChar = false)]
static extern uint LoadKeyboardLayout(
    StringBuilder pwszKLID,
    uint flags);

[DllImport("user32.dll",
    CallingConvention = CallingConvention.StdCall,
    CharSet = CharSet.Unicode,
    EntryPoint = "GetKeyboardLayout",
    SetLastError = true,
    ThrowOnUnmappableChar = false)]
static extern uint GetKeyboardLayout(
    uint idThread);

[DllImport("user32.dll",
    CallingConvention = CallingConvention.StdCall,
    CharSet = CharSet.Unicode,
    EntryPoint = "ActivateKeyboardLayout",
    SetLastError = true,
    ThrowOnUnmappableChar = false)]
static extern uint ActivateKeyboardLayout(
    uint hkl,
    uint Flags);

static class KeyboardLayoutFlags
{
    public const uint KLF_ACTIVATE = 0x00000001;
    public const uint KLF_SETFORPROCESS = 0x00000100;
}

Whenever I have to use native API methods I try to encapsulate them in a class that hides their declaration from the rest of the project´s codebase. So, I came up with a class called KeyboardLayout; that class can load and activate a layout by a given CultureInfo, which comes in handy...
internal sealed class KeyboardLayout
{
    ...

    private readonly uint hkl;

    private KeyboardLayout(CultureInfo cultureInfo)
    {
        string layoutName = cultureInfo.LCID.ToString("x8");

        var pwszKlid = new StringBuilder(layoutName);
        this.hkl = LoadKeyboardLayout(pwszKlid, KeyboardLayoutFlags.KLF_ACTIVATE);
    }

    private KeyboardLayout(uint hkl)
    {
        this.hkl = hkl;
    }

    public uint Handle
    {
        get
        {
            return this.hkl;
        }
    }

    public static KeyboardLayout GetCurrent()
    {
        uint hkl = GetKeyboardLayout((uint)Thread.CurrentThread.ManagedThreadId);
        return new KeyboardLayout(hkl);
    }

    public static KeyboardLayout Load(CultureInfo culture)
    {
        return new KeyboardLayout(culture);
    }

    public void Activate()
    {
        ActivateKeyboardLayout(this.hkl, KeyboardLayoutFlags.KLF_SETFORPROCESS);
    }
}

If you only need to have the layout be active for a short while - and you want make sure to properly restore the layout when done, you could write some kind of a scope type using the IDiposable interface. For instance...
class KeyboardLayoutScope : IDiposable
{
    private readonly KeyboardLayout currentLayout;

    public KeyboardLayoutScope(CultureInfo culture)
    {
        this.currentLayout = KeyboardLayout.GetCurrent();
        var layout = KeyboardLayout.Load(culture);
        layout.Activate();
    }

    public void Dispose()
    {
        this.currentLayout.Activate();
    }
}

Than you can use it like this...
const int English = 1033;
using (new KeyboardLayoutScope(CultureInfo.GetCultureInfo(English))
{
    // the layout will be valid within this using-block
}

You should know that in newer versions of Windows (beginning in Windows 8) the keyboard layout cannot be set for a certain process anymore, instead it is set globally for the entire system - and the layout can also be changed by other applications, or by the user (using the Win + Spacebar shortcut).
I would also recommend to not use SendKeys (or its native counterpart SendInput)  since it simulates keyboard input which will be routed to the active/focused window. Using the SendMessage function instead is suitable, but you might want combine that with functionality that can properly determine the target window; but to explain such technique would go beyond the scope of the this question and answer. This answer here illustrates a possible solution: How to send keystrokes to a window?

A: Change keyboard layouts through c# code:
using System;
using System.Linq;
using System.Globalization;
using System.Windows.Forms;
...
public static void Switch_keyboard(string lang)
{
    CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(lang);
    InputLanguage inputLanguage = InputLanguage.FromCulture(cultureInfo);
    InputLanguage.CurrentInputLanguage = inputLanguage;
}

private void button1_Click(object sender, EventArgs e)
{
    var list = InputLanguage.InstalledInputLanguages.Cast<InputLanguage>().Select(c => c.Culture.Name).ToList();
    Switch_keyboard(list[0]); // "ru-RU" or "ru-BY" ...
}

A: Change class @Matze,
internal class KeyboardLayoutScope : IDisposable, IKeyboardLayoutScope
    {
        private readonly KeyboardLayout currentLayout;

        public KeyboardLayoutScope() { }

        public KeyboardLayoutScope(CultureInfo culture)
        {
            currentLayout = KeyboardLayout.GetCurrent();
            KeyboardLayout.Load(culture).Activate();
        }

        public KeyboardLayoutScope(KeyboardLayout currentLayout) => this.currentLayout = currentLayout;

        public void Dispose() => currentLayout.Activate();
    }
    internal interface IKeyboardLayoutScope
    {
        void Dispose();
    }

Other Class
internal sealed class KeyboardLayout
    {
        private readonly uint hkl;

        private KeyboardLayout(CultureInfo cultureInfo) => hkl = NativeMethods.LoadKeyboardLayout(new StringBuilder(cultureInfo.LCID.ToString("x8")), KeyboardLayoutFlags.KLF_ACTIVATE);

        private KeyboardLayout(uint hkl) => this.hkl = hkl;

        public uint Handle => hkl;

        public static KeyboardLayout GetCurrent() => new KeyboardLayout(NativeMethods.GetKeyboardLayout((uint)Thread.CurrentThread.ManagedThreadId));

        public static KeyboardLayout Load(CultureInfo culture) => new KeyboardLayout(culture);

        public void Activate() => NativeMethods.ActivateKeyboardLayout(hkl, KeyboardLayoutFlags.KLF_SETFORPROCESS);
    }

A: Try thisone:
        public void switch_keyboard(string lang)
    {
        string keyboard_lang = InputLanguage.CurrentInputLanguage.Culture.TwoLetterISOLanguageName;
        if (keyboard_lang != lang)
        {
            int en_index = -1;
            for (int i = 0; i < System.Windows.Forms.InputLanguage.InstalledInputLanguages.Count - 1; i++)
            {
                try
                {
                    if (System.Windows.Forms.InputLanguage.InstalledInputLanguages[i].Culture.TwoLetterISOLanguageName == lang)
                    { en_index = i;  break; }
                }
                catch { break; }
            }
            if (en_index != -1)
            { InputLanguage.CurrentInputLanguage = System.Windows.Forms.InputLanguage.InstalledInputLanguages[en_index]; }
        }
    }

A: In 4.6.1 all methods posted here isn't working properly>
I got my solution:
// set keyboard layout
LoadKeyboardLayout("en-EN", 0x00000100);
// methods
[DllImport("user32.dll")] public static extern IntPtr GetKeyboardLayout(uint thread);
        [DllImport("user32.dll")]
        public static extern long LoadKeyboardLayout(
            string pwszKLID,  // input locale identifier
            uint Flags         // input locale identifier options
        );
    public static CultureInfo GetCurrentKeyboardLayout()
        {
            try
            {
                int keyboardLayout = GetKeyboardLayout(0).ToInt32() & 0xFFFF;
                return new CultureInfo(keyboardLayout);
            }
            catch
            {
                return new CultureInfo(1033); // Assume English if something went wrong.
            }
        }


text:
Q: Finding The Laurent Series for $\sin(\frac{z}{1+z})$ at $z = -1.$ I'm trying to find the Laurent Series for $\sin\left(\frac{z}{1+z}\right)$ centered around $z = -1.$ It seems to me that I should be considering the typical power series expansion of $\sin$, i.e.
$$\sin(w) = \sum_{k = 0}^{\infty} (-1)^k \frac{w^{2k+1}}{(2k+1)!}.$$
However, when I perform this with our current function, I see that
$$\sin\left(\frac{z}{1+z}\right) = \sum_{k = 0}^{\infty} (-1)^k
\frac{z^{2k+1}}{(1+z)^{2k+1}(2k+1)!}.$$
I am not entirely sure what to do with $z^{k+1}.$ Are there some other things that I should be doing with this series to account for the singularity of $\frac{z}{1+z}$ at $z = -1$?

A: $$
\begin{align}
\sin\left(1-\frac1{1+z}\right)
&=\sin(1)\cos\left(\frac1{z+1}\right)-\cos(1)\sin\left(\frac1{z+1}\right)\\
&=\sin(1)\sum_{k=0}^\infty\frac{(-1)^k}{(2k)!}\left(\frac1{z+1}\right)^{2k}-\cos(1)\sum_{k=0}^\infty\frac{(-1)^k}{(2k+1)!}\left(\frac1{z+1}\right)^{2k+1}
\end{align}
$$

A: HINT:
$$\sin\left(\frac{z}{z+1}\right)=\sin\left(1-\frac{1}{z+1}\right)=\sin(1)\cos\left(\frac{1}{z+1}\right)-\cos(1)\sin\left(\frac{1}{z+1}\right)$$


text:
Q: Leaflet with Customs Tiles seems to not be working I am trying to use Leaflet in Combination with Custom Tiles to make a fictional Map, but it seems to not be working even when I set the Error Tile URL to a completely different image, it doesn't even show that.
My JS Code looks like this:
axios.get("https://crugg.de/udumap/map1/tiles/tiles.json").then((result) => {
    let tilesData = JSON.parse(result.data.replace(/(\/\/)[A-Z a-z,:'()\/.#0-9]*/gm, ""));
    console.log(tilesData.center);
    let map = L.map('map', {
        center: [tilesData.center[0], tilesData.center[1]],
        zoom: tilesData.center[2]
    }).setView([tilesData.center[0], tilesData.center[1]], tilesData.center[2]);
    L.tileLayer('https://crugg.de/udumap/map1/tiles/{z}/{x}/{y}.png', {
        attribution: 'Map data © UD:RP Map contributors',
        minZoom: tilesData.minzoom,
        maxZoom: tilesData.maxzoom,
        zoomOffset: -1,
        bounds: L.latLngBounds(L.latLng(tilesData.bounds[0], tilesData.bounds[1]), L.latLng(tilesData.bounds[2], tilesData.bounds[3])),
        errorTileUrl: "https://crugg.de/udumap/map1/tiles/17/107729/82841.png"
    }).addTo(map);
});

JSFiddle: https://jsfiddle.net/5xprc6n3/1/
This is my first time using Leaflet and I have no Idea why this isn't working.

A: You have to remove the bounds property.
L.tileLayer('https://crugg.de/udumap/map1/tiles/{z}/{x}/{y}.png', {
        attribution: 'Map data © UD:RP Map contributors',
        minZoom: tilesData.minzoom,
        maxZoom: tilesData.maxzoom,
        zoomOffset: -1,
        errorTileUrl: "https://crugg.de/udumap/map1/tiles/17/107729/82841.png"
    }).addTo(map);


text:
Q: Sparse and homogeneous solutions I'm been having a problem in descovering what is the answer to the following question related to Numerical methods (so using matrices): I have a set of 4 equations to solve with variables x1, x2, x3, x4, x5. The first question is to find it's free variables... This one is easy, just put the matrix into Reduced Row Echelon Form and work with the pivots. However, there are two more questions: Find a sparse solution, and Find a homogeneous solution...
Question itself:
Let
http://i.imgur.com/UmP9x94.png
Find:

*

*Free Variables (This one I know how to solve)

*Sparse solution

*Homogeneous solution
My question is, what solutions should I calculate, how can I calculate a sparse solution and an homogeneous solution? I've been looking on internet for hours but can't find any explanation what so ever.
Please, help!
Thank you


text:
Q: Adding different types of marker on the map with using Leaflet.draw I am using Leafletjs with Leaflet.draw to create an interactive map on my web.
But I need to enable different types of "marker". And then when creating them I need to identify them. I tried adding a title to each marker, but then I can't get it.
attempt 1:
https://jsfiddle.net/k9w2jf05/2/

L.DrawToolbar.include({
    getModeHandlers: function (map) {
        return [
            {
                enabled: true,
                handler: new L.Draw.Marker(map, { icon: new L.Icon.Default() }),
                title: 'Place restaurant marker'
            },
            {
                enabled: true,
                handler: new L.Draw.Marker(map, { icon: new L.Icon.Default() }),
                title: 'Place gas station marker',
                innerHTML: "sdadadds"
            },
            {
                enabled: true,
                handler: new L.Draw.Marker(map, { icon: new L.Icon.Default() }),
                title: 'Place hospital marker'
            }
        ];
    }
});

attempt 2:
https://jsfiddle.net/k9w2jf05/1/
var drawPluginOptions = {
  position: 'topright',
  draw: {
    polyline: false,
    polygon: false,
    circle: false, // Turns off this drawing tool
    rectangle: false,
    circlemarker: false,
    marker: {
    title: "soyel1",
      icon: new MyCustomMarker()
    }
  },
  edit: {
    featureGroup: editableLayers, //REQUIRED!!
    remove: false
  }
};

map.on('draw:created', function(e) {
  var type = e.layerType,
    layer = e.layer;

    /*if(layer.title == "Place hospital marker"){
        do this...
    }*/

  editableLayers.addLayer(layer);
});

I simply need different markers to appear on the bar, with different icons and detect when one or the other is clicked, and when one or the other is deleted. To have 1 of each on the map always.
How can I do that?

A: There might be other, more 'official' ways, but the only way I could find to get some parameter from marker creation button to marker creation event, is through marker icon properties when marker is created through handler, defined with getModeHandlers option.
Before marker is created with handler new L.Draw.Marker(map, { icon: new L.Icon.Default() }), we create icon as separate object and then any custom property can be added to it. This property can be retrieved inside the marker creation event handler with e.layer.options.icon.myType, where myType can be any name, as long it does conflict with standard icon properties.
In the code below, property named myType is used to bind appropriate tooltip to the marker at the time of marker creation.
To create marker with different icon for each button, it's easy, just create marker with the desired icon.
To change draw icon to custom icon, I tried to find official way, but got lost, so I just used some standard JS HTML CSS trickery to assign the same icons that are used for marker icons to the draw icons.
var iconTitle = [
  'Place restaurant marker',
  'Place gas station marker',
  'Place hospital marker'
];

var iconUrl = [
  'img/restaurant.png',
  'img/gas-station.png',
  'img/hospital.png'
];

function createDrawnMarker(id, type) {
  var icon = L.icon({
    iconUrl: iconUrl[id],
    iconSize: [38, 38],
    iconAnchor: [19, 37],
    tooltipAnchor: [19, -19]
  });
  icon.myType = type;
  var marker = new L.Draw.Marker(map, {icon: icon});
  return(marker);
}

L.DrawToolbar.include({
  getModeHandlers: function (map) {
    return [
      {
        enabled: true,
        handler: createDrawnMarker(0, 'Restaurant'),
        title: iconTitle[0],
      },
      {
        enabled: true,
        handler: createDrawnMarker(1, 'Gas station'),
        title: iconTitle[1],
        innerHTML: "sdadadds"
      },
      {
        enabled: true,
        handler: createDrawnMarker(2, 'Hospital'),
        title: iconTitle[2]
      }
    ];
  }
});

var drawControl = new L.Control.Draw(drawPluginOptions);
map.addControl(drawControl);

var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);

map.on('draw:created', function(e) {
  var type = e.layerType,
  layer = e.layer;
  layer.bindTooltip(layer.options.icon.myType);
  editableLayers.addLayer(layer);
});

var drawButtons = document.getElementsByClassName('leaflet-draw-draw-marker');
for (var i = 0; i < drawButtons.length; i++) {
  var j = iconTitle.indexOf(drawButtons[i].title);
  drawButtons[i].style.backgroundImage ='url(' + iconUrl[j] + ')';
  drawButtons[i].style.backgroundSize = '25px 25px';
  drawButtons[i].style.backgroundPositionX = '2px';
  drawButtons[i].style.backgroundPositionY = '2px';
}

A: I don't know a solution for Leaflet-Draw but for Leaflet-Geoman a more modern draw tool.

var MyCustomMarker = L.icon({
  shadowUrl: null,
  iconAnchor: new L.Point(12, 12),
  iconSize: new L.Point(24, 24),
  iconUrl: 'https://upload.wikimedia.org/wikipedia/commons/6/6b/Information_icon4_orange.svg'
})

var HospitalIcon = L.icon({
  shadowUrl: null,
  iconAnchor: new L.Point(12, 12),
  iconSize: new L.Point(24, 24),
  iconUrl: 'https://upload.wikimedia.org/wikipedia/commons/4/49/Estaci%C3%B3n_Hospitales.png'
})

var hospitalMarker = map.pm.Toolbar.copyDrawControl('drawMarker',{name: "hospitalMarker"})
hospitalMarker.drawInstance.setOptions({markerStyle: {icon : HospitalIcon}});

var infoMarker = map.pm.Toolbar.copyDrawControl('drawMarker',{name: "infoMarker"})
infoMarker.drawInstance.setOptions({markerStyle: {icon : MyCustomMarker}});

https://jsfiddle.net/falkedesign/e8prm0qu/


text:
Q: Given the sets $A, B, C, S$ It is easy to solve for x
in $A,B,C$, but I don't understand $S=\{x∈R\mid x∈A↔x∈B−C\}$

Find the set S in terms of the interval. Give as an answer the sum of the finite extremes of each of the intervals that make it up.
$A=\{x∈ R / \dfrac{x}{3} ∈[−1;4]\}$
$B=\{x∈ R / (x+3) ∈[4;7]\}$
$C=\{x∈ R / \dfrac{1−2x}{2} ∈[−1;2]\}$
$S=\{x∈R / x∈A↔x∈B−C\}$

source: Lumbreras Editors

A: Simplifying the expressions leads to,
$A=[-3,12]$
$B=[1,4]$
$C=[-1.5,1.5]$
Now, $B\setminus C=(1.5,4]$(everything in $B$ that is not in $C$).
We can evaluate the condition $x\in A\iff x\in B\setminus C$ by thinking along the lines: for what values of $x$ is it true that if it belongs to $A$ then it must belong to $B\setminus C$ and vice-versa?
You can try to attempt before looking at the solution below.

 We can see that if $x\in A\cap(B\setminus C)$ then the above condition holds.
 Hence $S=A\cap(B\setminus C)=(1.5,4].$


text:
Q: Angular move array items between arrays on click - Plunkr included I'm looking to create a list of tags, when you click the blue tag it gets added to a new array and is displayed above, it should be unselectable in the old array but its place is marked by css however the user should be able to click it in the new array and it will go back to its original place in the old array and be removed from the new array. I've made a plunker with what I have done so far.
So far the issue is that when clicked it gets added to the new array but it is still clickable in the old array, so clicking it multiple times ends up adding duplicate values to the new array, I also need functionality where if the user clicks it in the new array it goes back to its original spot in the old array.
and here is the typescript code for anyone who wants to view it here
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
    selector: 'my-app',
    template: `

Hello {{name}}

        Current behaviour: user clicks the blue tag and it goes into the array displayed above.
        user clicks already selected blue tag and it duplicated in array. wanted behaviour is that once selected
        it goes into the new array and it is then unclickable in the blue tags part, but you can click it from the above part and
        it will be visible and selectable in the blue part again

        TLDR: click blue tag and goes into another array, click tag in new array and it goes back to the blue array

                  {{ m }}

                  {{ c }}

      `,
    })
    export class App {
      name:string;

    seed: Array<any> = [
        "ice",
        "hockey",
        "rubbish",
        "traitor",
        "mneumonic",
        "chronical",
        "stuff",
        "entity",
        "poo",
        "junk",
        "mcDonalds",
        "Fruit",
        "going",
        "sweet"
      ]

        cloneSeedArray: Array<any> = [];
        cloneSeedArrayForSelection: Array<any> = [];

        selectedIdx = 0;
        stateOfButton: boolean[];

        matchArray: Array<any> = [];

      constructor() {
        this.name = `Angular! v${VERSION.full}`
      }

      changeState(index, seedWord) {

        // a) click item to add / remove a class
        // b) add item to a new array
        // c) compare both arrays to ensure they match
        // d) if both arrays dont match show warning and allow to recreate
        // this.selectedIdx = index;
        console.log("index " + index)
        this.matchArray.push(seedWord)
        this.stateOfButton[index] = !this.stateOfButton[index];
        console.log("seedWord " + seedWord)
      }

    ngAfterViewInit() {
      this.cloneSeedArray = this.seed.slice();
      this.cloneSeedArrayForSelection = this.shuffleArray( this.cloneSeedArray  )
      this.stateOfButton = Array(this.cloneSeedArrayForSelection.length).fill(false);
      this.cd.detectChanges();
    }

    shuffleArray(d) {
        for ( let  c = d.length - 1; c > 0; c--) {
            let b = Math.floor(Math.random() * (c + 1));
            let a = d[c];
            d[c] = d[b];
            d[b] = a;
        }
        return d
    };
}

@NgModule({
    imports: [ BrowserModule ],
    declarations: [ App ],
    bootstrap: [ App ]
})
export class AppModule {}

A: I would map your array to array of objects with selected property.
This way way we can easily determine which element should be displayed in new array and which should remain in old array
ts
export class AppComponent {
  seed = [
    "ice",
    ...
  ];

  items: Item[];
  selectedItems: Item[] = [];

  ngOnInit() {
    this.items = this.shuffleArray(this.seed)
      .map(x => ({ name: x, selected: false }));
  }

  select(item: Item) {
    if (item.selected) {
      return;
    }

    this.selectedItems.push(item);
    item.selected = true;
  }

  unSelect(item: Item, idx: number) {
    item.selected = false;
    this.selectedItems.splice(idx, 1);
  }

 ...
}

interface Item {
  name: string;
  selected: boolean;
}

html

     {{ item.name }}

      {{ item.name }}

Ng-run Example
Note: I also removed pointer-events: none; rule from .c-seedContainer.u-displayOnly selector in your css

A: You can add the following code lines to the "changeState" method to know if the word is already in the array
changeState(index, seedWord) {

// a) click item to add / remove a class
// b) add item to a new array
// c) compare both arrays to ensure they match
// d) if both arrays dont match show warning and allow to recreate
// this.selectedIdx = index;
for(let word of this.matchArray){
  if(word == seedWord){
    return;
  }
}
console.log("index " + index)
this.matchArray.push(seedWord)
this.stateOfButton[index] = !this.stateOfButton[index];
console.log("seedWord " + seedWord)}


text:
Q: member count.. Array output numbers? I am currently stuck..
When trying to fetch member count it returns as an array, which is not that easy to output when It's a number.. here is the code
Member.php
public function __construct() {
        $this->_pdo = DB::connect();
    }
public function count() {
    $this->_query = $this->_pdo->query("SELECT COUNT(*) FROM members");
    if(!$this->_query->error()) {
        print_r($this->_query);
    }
    return false;
}

DB.php
    private function __construct() {
    try {
        $this->pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/dbname'), Config::get('mysql/username'), Config::get('mysql/password'));
    } catch(PDOException $e) {
        die($e->getMessage());
    }
}

public static function connect() {
    if(!isset(self::$_connect)) {
        self::$_connect = new DB();
    }
    return self::$_connect;
}

public function query($sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }

        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }
    return $this;
}

How can I output this in the correct way?

A: You need to fetch the data.
$this->_query->fetchColumn();


text:
Q: Stop iframe from flashing white when changing its source via javascript I have an iframe:
<iframe id="main_frame" src="first_url.html" style="visibility:hidden;" onload="this.style.visibility = 'visible';"></iframe>

As you can see it has been set to not be visible while loading. This ensures that no 'white flash' occurs while the frame loads. However, if I change the source of the iframe by clicking this button:
<button onclick="change_view('new_url.html')">change view</button>

..where the javascript function to change the source is:
 function change_view(url) {
          var site = url
          document.getElementById('main_frame').src = site
            }

then I get the white flash while the source changes.  Is there is a way to change the source of the iframe without getting this white flash?

A: You could try this
<iframe style="visibility:hidden;" onload="this.style.visibility = 'visible';" src="../examples/inlineframes1.html" > </iframe>

It hides iframe until fully loaded.
https://css-tricks.com/snippets/html/get-rid-of-white-flash-when-iframe-loads/


text:
Q: Working with Transaction Types in EJB I have the following example:
public class MyEJBService implements javax.ejb.SessionBean {
      public void modifyAllItems() {
           doSomething...
           for(...)
           {
                modifyItem(item);
           }
      }

     public void modifyItem(Item item) {
          doSomething...
     }
}

Method 1 = modifyAllItems
Method 2 = modifyItem
Method1 calls method2 several times. I want to disable the transaction at method1 but enable the transaction at method2. Each call of method2 should be at a different transaction (if an error occurs while modifying an item, some items could have been modified while others remains unchanged). I've defined an EJB transaction type for method1() - NEVER and another for method2() - REQUIRES NEW. The problem is that it seems that when I'm calling method2(), the EJB is not creating any transaction because when an error occurs inside method2() it is not rolling back (if something is changed at the database inside method2 but it throws an exception before method2 completition the database is not returning to the previous state - rollback). Is this behavior expected? I'm a little bit confused. Thank you very much.

A: Yes it's the expected behavior as transaction are implemented using a proxy and so applied only when the call to the EJB method is done from a third party object. If you want method2() transaction to be applied when called from method1() you have to move it to a second EJB object.

A: Another idea is Bean Managed Transaction,belowing are the steps

*

*ejb-jar.xml
<transaction-type>Bean</transaction-type>

*the code
public class MyEJBService implements javax.ejb.SessionBean {
SessionContext context;
public void modifyAllItems()
{
    doSomething();
     for(...)
     {
         UserTransaction  trans=context.getUserTransaction();;
         try
         {
          trans.begin();
          modifyItem(item);
          trans.commit();
         }catch(Exception  e)
         {
             trans.rollback();//if need propagation then:trans.setRollbackOnly();
         }
     }
}

public void modifyItem(Item item) {
    doSomething();
}

@Override
public void setSessionContext(SessionContext context) throws EJBException,
        RemoteException {
    this.context = context;
}


text:
Q: Why when I click on the images does nothing happen? I am new to jQuery so hopefully this isn't two dumb of a question but I have looked around.
I have a simple todo list shown here:   I am curious as to why when I click the images shown (after adding an item) the functions do nothing.
The following are the two methods of concern...I'm pretty sure they are not being called. I'm unsure why:
$('.delete').on('click', function(event) {
    event.preventDefault();
    var reply = confirm("Are you sure you want to delete this todo item?");
    if(reply === true) {
        $(this).closest('.item').remove();
    }
});

$('.edit').on('click', function(event) {
    $(this).closest('.item').slideDown('fast');
});

A: You could use event delegation as follows:
$('#list').on('click', '.delete', function(event) {
    event.preventDefault();
    var reply = confirm("Are you sure you want to delete this todo item?");
    if(reply === true) {
        $(this).closest('.item').remove();
    }
});

$('#list').on('click', '.edit', function(event) {
    $(this).closest('.item').slideDown('fast');
});

Another, and more efficient, option would be to define your click handlers and then assign them to the elements after creating them:
var onDeleteButtonClicked = function(event) {
    //delete code from above.
};

var onEditButtonClicked = function(event) {
    //edit code from above.
};

function addTo(event) {
    event.preventDefault();

    var toAdd = $('#addition').val();

    if(toAdd.length > 0) {
        var listItem = $('
' + toAdd + '
');
        var img = $('')
            .click(onDeleteButtonClicked); //Assign your delete click handler here.
        var img1 = $('')
            .click(onEditButtonClicked); //Assign your edit click handler here.
        listItem.append(img);
        listItem.append(img1);
        $('#list').append(listItem);
        $('#addition').val("")
    } else {
        alert("Cannot add empty list item!");
    }
}

A: Try this:
$('#container').on('click','.delete' ,function(event){

    event.preventDefault();
    var reply = confirm("Are you sure you want to delete this todo item?");
    if(reply === true) {
        $(this).closest('.item').remove();
    }

});


text:
Q: Want to parse a file and reformat it to create a pairRDD in Spark through Scala I have dataset in a file in the form:
1: 1664968

2: 3 747213 1664968 1691047 4095634 5535664

3: 9 77935 79583 84707 564578 594898 681805 681886 835470 880698

4: 145

5: 8 57544 58089 60048 65880 284186 313376

6: 8

I need to transform this to something like below using Spark and Scala as a part of preprocessing of data:
1 1664968

2 3

2 747213

2 1664968

2 4095634

2 5535664

3 9

3 77935

3 79583

3 84707

And so on....
Can anyone provide input on how this can be done.
The length of the original rows in the file varies as shown in the dataset example above.
I am not sure, how to go about doing this transformation.
I tried soemthing like below which gives me a pair of the key and the first element after the semi-colon.
But I am not sure how to iterate over the entire data and generate the pairs as needed.
def main(args: Array[String]): Unit = {
  val sc = new SparkContext(new SparkConf().setAppName("Graphx").setMaster("local"))
  val rawLinks = sc.textFile("src/main/resources/links-simple-sorted-top100.txt")

  rawLinks.take(5).foreach(println)

  val formattedLinks = rawLinks.map{ rows =>
    val fields = rows.split(":")
    val fromVertex = fields(0)
    val toVerticesArray = fields(1).split(" ")
    (fromVertex, toVerticesArray(1))
  }

  val topFive = formattedLinks.take(5)
  topFive.foreach(println)
}

A: val rdd = sc.parallelize(List("1: 1664968","2: 3 747213 1664968 1691047 4095634 5535664"))
val keyValues = rdd.flatMap(line => {
  val Array(key, values) = line.split(":",2)
  for(value <- values.trim.split("""\s+"""))
    yield (key, value.trim)
})
keyValues.collect

A: split row in 2 parts and map on variable number of columns.
def transform(s: String): Array[String] = {
  val Array(head, tail) = s.split(":", 2)
  tail.trim.split("""\s+""").map(x => s"$head $x")
}

> transform("2: 3 747213 1664968 1691047 4095634 5535664")
// Array(2 3, 2 747213, 2 1664968, 2 1691047, 2 4095634, 2 5535664)


text:
Q: Having problems compiling Mathematica Cuda code Ok I am trying to follow the examples of Cuda Code in the docummentation
Run the CUDAQ[] and get back a True
and run some of the first examples of Cuda code in the documentation and they also work
but when I try
doubleFun = CUDAFunctionLoad["
  __global__ void doubleVec(mint * in,  mint length) {
      mint index = threadIdx.x + blockIdx.x * blockDim.x;
        if (index < length)
          in[index] = 2*in[index];
    }", "doubleVec", {{_Integer}, _Integer}, 256]

This example is to multiply a vector by 2
I get the following error code
CUDAFunctionLoad::noxcomp: A C compiler was not found in specified directory `1`.
Set"XCompilerInstallation" to the directory containing a supported C compiler.
Supported C compilers are detailed in the NVCCCompiler documentation page. >>

It looks like mathematica does not know where my C compiler is at and needs to be define
I look in the documentation and I do not see how to do that.
I am using OS X for Mac and from the above error message they are asking me to set
XCompilerInstallation to the directory containing the C compiler, I also have installed XCode. What should I do next?


text:
Q: How to determine the type of a mobile application I am trying to automate an application on an Android device but I am having a problem. When the application is launched and running on my device, I can see it properly, using the UIAutomatorViewer but it looks like the elements in the application haven't been detected properly by it. So if I want to interact with an element, the only option for me now is to manually determine its physical location and use tap there. This is obviously not the best approach.
After doing some reading online I learned that UIAutomatorViewer only supposed to work with Native applications while I am not 100% sure what type of application is the one that I am working with. I have tried to inspect it via Chrome chrome://inspect/#devices and the application is definitely displayed there with all the elements I need. I am not sure however that this is an indication of being a web app or hybrid app?
I have also tried to view the context handlers:
Set<String> contextNames = driver.getContextHandles();
for (String contextName : contextNames) {
    System.out.println(contextNames);
}

But it only prints out NATIVE_APP context which doesn't sum up with my theory that this might be a web or hybrid app and that's the reason why I can't use UIAutomatorViewer properly.

A: Hybrid app - embeded HTML5 apps inside a thin native container. Then, if some menu/views of your native application contains WebView - app is hybrid. So, to say that is not hybrid app on all menu/views should be only one context. You can try to search by class (e.g. android - "android.webkit.WebView") or to check contexts on each application view. And if app is hybrid you can switch between contexts and find elements for example in web context by css selectors.