text:
Q: Splitting a list of number into N even subsections I have a list of numbers, and I want to split them up into N evenly spaced numbers,  while the first and last number must be in the resulting list, all numbers should be an integer, so I'm ok with the space between the last two being off by a little.
For example I have a range of 1-100 and the I want the resulting list in three numbers, so it would be [1, 50, 100]. Is there a python way to split them? Or what could be an equation to get the increment? Getting the increment by (last-first)/N will not work because it will results in more numbers.
I couldn't come up with a working equation to get the increment, the best I have is (last-first-2)/N-2, but that fails to give an even split on some combinations.

A: You can do this with numpy.linspace():
import numpy as np
np.linspace(1, 100, 3, dtype=int)

Output:
array([  1,  50, 100])

Or if you already had an list of integers, and you wanted to sample from it using this method:
nums = range(1,200,2)  # odd numbers
[nums[i-1] for i in np.linspace(1, 100, 3, dtype=int)]

Output:
[1, 99, 199]


text:
Q: How do I remove the entire left nav bar in admin for certain level users? I know how to remove items from the left nav bar (hook into admin_menu and do global $menu; unset( $menu[ __( "Posts" ) ] ); for example). But it still shows a left nav bar (with nothing on it). I want the entire left nav bar gone.
I have tried this and it doesn't work:
//This doesn't work (in any hook, or plugin constructor)
show_admin_bar(false);

//This also doesn't work
add_filter('show_admin_bar', '__return_false');

What is the hook/function to do this?

A: You could creatively use output caching to capture the adminbar and then discard it like so:
<?php
// this filter runs in menu-header.php L37 right before the admin menu is rendered
add_filter( 'parent_file', function( $parent_file ){
    ob_start();
    return $parent_file;
} );
// runs after the output
add_action( 'in_admin_header', function(){
    ob_clean(); // discard output
    echo '<div id="wpcontent">';
} );

Please do not actually consider using this in any production environment. It does not provide any security and it might break various things (for example the admin toolbar). I consider this an educational answer to the problem "how to use PHP output caching and WP filters to move remove stuff?". You are probably better off just using CSS.

A: If you look at the bottom of the menu-header.php file in the wp-admin folder, you will see that the admin menu is hard coded. There are no hooks that would allow you to disable it.
Another issue is that the #wpcontent div has a left margin (depending on the screen size), so even if you did strip out the admin menu code, the space it normally occupies would still be there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create custom Vary group in litespeed WordPress plugin? I am trying to create custom Vary group (ESI) based on user capability instead of role in my wordpress website. Please help if anyone have solution to customize it.

A: you need to use other plugin , like role editor , to create different roles first , and then set them to different varies in ESI


text:
Q: How to iterate this structure Map>> and pass its values into a method? I would like to iterate through this structure Map<String, Map<String, Set<String>>> and pass its values into a method using Java Stream API.
Let's say I have a function

doSomething(String a, String b, Set  c)

and I need to call it for the values of the structure above.
Map<String, Map<String, Set<String>>> myMap = new HashMap<>();
    Set<String> mySet1 = Set.of("A", "B");
    Set<String> mySet2 = Set.of("C", "D");
    Map<String, Set<String>> helperSet = new HashMap<>();
    helperSet.put("1557491", mySet1);
    helperSet.put("1557492", mySet2);
    myMap.put("1165624", helperSet);

    List<MyObject> details = myMap.entrySet().stream()
            .map(e -> doSomething(
                    e.getValue().entrySet().stream()
                            .map(d -> d.getKey()).iterator().next(),
                    e.getKey(),
                    e.getValue().entrySet().stream()
                            .map(f -> f.getValue().iterator().next())
            ).collect(Collectors.toList());

This is what I have written so far, unfortunately it doesn't work, it only manages to pass the values of the first set (mySet1).
I am quite new to Java 8. Any help will be highly appreciated!

A: You can do it with a stream within a stream:
myMap.entrySet().stream()
    .map(e1 -> e1.getValue().entrySet().stream()
            .map(e2 -> doSomething(e1.getKey(), e2.getKey(), e2.getValue()))
            .collect(toList())
    ).flatMap(List::stream)
    .collect(toList());


text:
Q: Zip the contents of every sub-folder in a folder in Mac automatically I have this folder/file structure
parent folder
--subfolder1
  -sub-subfolder
  -file1
  -file2
--subfolder2
  -sub-subfolder
  -file1
  -file2
...

I want to:

*

*create zip files from the contents of the subfolders. which means,
file1, file2, and sub-subfolder will be zipped, but not the enclosing subfolder.

*name each zip file with the name of the folder, like subfolder1.zip,
subfolder2.zip...
I'd prefer that the zip files remain in the related subfolder so it will be:
parent folder
--subfolder1
  -sub-subfolder
  -file1
  -file2
  -subfolder1.zip
--subfolder2
  -sub-subfolder
  -file1
  -file2
  -subfolder2.zip
...

I am hoping that it would be possible with Automator but had no success till now.
My searches resulted in solutions that zip every folder individually with the folder itself, which in this case is not useful for me. I need the contents of the folders to be zipped.
Any ideas?

A: Not sure about Automator, but you can easily accomplish this in Terminal.
find "parent folder" -type d -depth 1 -execdir sh -c 'cd "$1" && zip -r "$1" .' _ '{}' \;

*

*find "parent folder" -type d -depth 1 lists all subdirectories of "parent folder" (just run it to see the result)

*-execdir executes the part up to the \; for each subdirectory found

*sh -c 'cd "$1" && zip -r "$1" .' _ '{}' starts a subshell to change into the directory to pack and then zip the content there. The {} contains the name of the subdirectory and is the value $1 will be set to within the subshell, _ is syntactically required but the actual content is ignored.


text:
Q: Boolean checkbox status update in ManagedBean I have two Boolean type check box in my jsf page from which second check box is made disabled depending upon the first check box status and for first time page loading both the check box are unchecked. I am updating the second check box disable status through script when first check box is checked.Then i am selecting second check box.
       But the problem is when i am submitting my page only first check box status is getting updated. This is my Managed Bean
@ManagedBean(name = "checkBoxTest")
@SessionScoped
public class CheckBoxTest {
    private boolean check1;
    private boolean check2;
    public boolean isCheck1() {
        return check1;
    }
    public void setCheck1(boolean check1) {
        this.check1 = check1;
    }
    public boolean isCheck2() {
        return check2;
    }
    public void setCheck2(boolean check2) {
        this.check2 = check2;
    }
    public String update(){
        boolean status = this.isCheck1();
        boolean status2 = this.isCheck2();
        return "checkboxExample.xhtml";
    }
}

This is my jsf page
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

   <h:head>
      <title>JSF tutorial</title>
      <link href="css/styles.css" rel="stylesheet" type="text/css" />

   </h:head>
   <h:body>

CheckBox Example

      <h:form id="form">
        <h:outputLabel value="First Check"/>
        <h:selectBooleanCheckbox name="check1" id="check1" value="# {checkBoxTest.check1}" onclick="changeCheckBox2Status()">  </h:selectBooleanCheckbox>
        <h:outputLabel value="Second Check"/>
        <h:selectBooleanCheckbox name="check2" id="check2" value="#{checkBoxTest.check2}" disabled="#{checkBoxTest.check1?false:true}">   </h:selectBooleanCheckbox>
        <h:commandButton action="#{checkBoxTest.update()}" value="Submit2">
        </h:commandButton>
      </h:form>
   </h:body>

My script is given below
function changeCheckBox2Status(){
        var checkBox1Status = document.getElementById("form:check1");
        if(checkBox1Status.checked){
            document.getElementById("form:check2").disabled=false;
        }
    }

A: Did you try something like:
public void setCheck1(boolean check1) {
    this.check1 = check1;
    this.check2 = !this.check2;
}

and similarly for the other.


text:
Q: Some of the aliases you requested do not exist: events.create i am trying to create new event using graph api.i set create_event permission for testing user. now i execute graph api but it gives me error like :
{
   "error": {
      "message": "(#803) Some of the aliases you requested do not exist: events.create",
      "type": "OAuthException"
   }
}
can anyone tell me why this happening.

A: You are using an old method for creating events.  The event.create has been deprecated. As you can see from the documentation :

We are in the process of deprecating the REST API. If you are building
  a new Facebook application, please use the Graph API. While there is
  still functionality that we have not ported over yet, the Graph API is
  the center of Facebook Platform moving forward and where all new
  features will be found.

Please read the new documentation on events to learn about the new methods of dealing with them.

We as facebook developers are solely responsible for keeping up-to-date with the changes that 3rd party API's, on which we base our development, make to their systems.
A great place to keep updated on changes and new features would be the Facebook Developers Blog and the Facebook Developers Roadmap.

A: What is your Post URL ?
You need to Post to /events and supply at least the name and start_time parameters.
Note the start_time is strict about format, if the format is off, you will get a event id but the event is never created.
You can test this directly in Graph API explorer.


text:
Q: Best Practice for storing DateTime values in Xpages I'm trying to implement Managed Beans that represent objects with some date-time values (It's a Training session, with a day, a start time and an end-time).
I am not sure what is the best practice for actually storing the information within my Java code - a Vector, a Java Time object, a lotus.domino.notesdatetime.
I've been badly burnt before and I was wondering what is the best practice?

A: Store each date-time-value in a java.util.Date object.
You can get the Date value from NotesDateTime value with .toJavaDate()

A: Use the OpenNTF Domino API and then you can basically ignore the lotus.domino.DateTime class and work strictly with the Java objects.
Side note: You should never use a Vector for anything, really. They are a concrete holdover in the lotus.domino API from Java 1.1.


text:
Q: Root, Home sizes I'm about to install a linux distro. Wondering about which size to allocated to home and root.
I know the home partition will generally contain the user's files and stuffs. I want to know: when installing a package, does it store on the root partition, or the home? That would help me to determine which size to allocate to root and home.
Update:
Currently running Windows 8.1 Pro and Ubuntu on it.
Windows 2 partitions: 200GB, 146GB.
Ubuntu: 50GB, Swap 4GB.
New linux distro (Kali 2.0) to be installed on 50GB of unformatted space

A: Usually packages are installed in /usr/lib (part of root) or /opt directory.
Most of the app will use space allocated to root.
Some exceptional cases installs modules only available to single user goes in local directory.


text:
Q: Como somar a diagonal de uma matriz em C? Me ajudem no seguinte exercício:
Faça um programa que defina uma matriz de inteiros de tamanho 5x5. Em seguida,
inicialize essa matriz com números aleatórios entre 5 e 9. Finalmente, seu programa deve calcular a soma dos elementos da diagonal dessa matriz. O programa deve imprimir a matriz gerada e a soma de sua diagonal. Segue um exemplo de saída.
Matriz gerada:
5 6 7 8 9
9 5 6 7 8
8 9 5 6 7
7 8 9 5 6
6 7 8 9 5

A soma da diagonal da matriz é: 25.
O código que fiz, não faz a soma corretamente:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char**argv){

    int matriz[5][5];
    int i, x, j, p;
    int soma=0;

    srand(time(NULL));

    printf("Matriz gerada: ");

    for(i=0; i<5; i++){
        printf("\n");
            for(j=0; j<5; j++){
                x=5+(rand()%5);
                printf("%3d", x);
                matriz[i][j];
                if(i==j){
                    for(p=0; p<5; p++){
                        soma+=matriz[i][j];
                    }
                }
            }
    }
    printf("\n");
    printf("Soma da diagonal principal: %d", soma);
    return 0;
}

A: Seu código tinha basicamente dois problemas. Como o @Luiz Vieira mencionou, você não estava guardando o valor de x na matriz. Além disso, como você mesmo notou, tinha um loop desnecessário fazendo a soma.
Para facilitar a leitura, foram removidas todas as variáveis redundantes e dada uma leve enxugada no código, já resolvendo os dois problemas mencionados:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char**argv){
    int matriz[5][5];
    int i, j;
    int soma=0;

    srand( time( NULL ) );

    printf( "Matriz:\n" );
    for( i = 0; i < 5; i++ ){
        for( j = 0; j < 5; j++ ){
            matriz[i][j] = 5 + rand() % 5;
            printf( "%3d", matriz[i][j] );
            if( i==j ){
                soma += matriz[i][j];
            }
        }
        printf( "\n" );
    }
    printf( "Soma da diagonal principal: %d", soma );
    return 0;
}

Veja funcionando no IDEONE.
Agora, imaginando que você tivesse que somar a diagonal de uma matriz pré-existente, veja como ficaria o loop da soma, se fosse independente do resto:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char**argv) {
    int matriz[5][5];
    int i, j;
    int soma = 0;

    srand( time( NULL ) );

    /* gerando a matriz */
    printf( "Matriz:\n" );
    for( i = 0; i < 5; i++ ) {
        for( j = 0; j < 5; j++ ) {
            matriz[i][j] = 5 + rand() % 5;
            printf( "%3d", matriz[i][j] );
        }
        printf( "\n" );
    }

    /* fazendo a soma */
    for( i = 0; i < 5; i++ ) {
        soma += matriz[i][i];
    }
    printf("Soma da diagonal principal: %d", soma);

    return 0;
}

Veja funcionando no IDEONE.

A: Fiz de um jeito que nao precisa nem de if, no C, sou novo na programação mas se isso for ajudar em alguma coisa, tá aqui:
   #include<stdio.h>
     main()
    {
         int D[5][5], i=0, j=0, soma1=0,soma2=0 ,x=5;
          printf("--------------------------\ninforme os valores da matriz\n____________________________\n");
for(i=0;i<5;i++){
    x--;
    for(j=0;j<5;j++){
        printf("%d - %d = ",i+1,j+1);
        scanf("%d",&D[i][j]);
    }
    soma1=soma1+D[i][i];
    soma2=soma2+D[i][x];
}
printf("\n-----------\nsoma diagonal 1:\t%d",soma1);
printf("\n-----------\nsoma diagonal 2:\t%d",soma2);

}


text:
Q: How to calculate CRC of a 64Bit DLL in Delphi? I am using following code to calculate CRC32 of 32Bit DLLs.
//Code to Check CRC of DLL files
procedure CalcCRC32(FileName: String; var CRC32: dword);
const Table: Array[0..255] of DWord =
     ($00000000, $77073096, $EE0E612C, $990951BA,
      $076DC419, $706AF48F, $E963A535, $9E6495A3,
      $0EDB8832, $79DCB8A4, $E0D5E91E, $97D2D988,
      $09B64C2B, $7EB17CBD, $E7B82D07, $90BF1D91,
      $1DB71064, $6AB020F2, $F3B97148, $84BE41DE,
      $1ADAD47D, $6DDDE4EB, $F4D4B551, $83D385C7,
      $136C9856, $646BA8C0, $FD62F97A, $8A65C9EC,
      $14015C4F, $63066CD9, $FA0F3D63, $8D080DF5,
      $3B6E20C8, $4C69105E, $D56041E4, $A2677172,
      $3C03E4D1, $4B04D447, $D20D85FD, $A50AB56B,
      $35B5A8FA, $42B2986C, $DBBBC9D6, $ACBCF940,
      $32D86CE3, $45DF5C75, $DCD60DCF, $ABD13D59,
      $26D930AC, $51DE003A, $C8D75180, $BFD06116,
      $21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F,
      $2802B89E, $5F058808, $C60CD9B2, $B10BE924,
      $2F6F7C87, $58684C11, $C1611DAB, $B6662D3D,
      $76DC4190, $01DB7106, $98D220BC, $EFD5102A,
      $71B18589, $06B6B51F, $9FBFE4A5, $E8B8D433,
      $7807C9A2, $0F00F934, $9609A88E, $E10E9818,
      $7F6A0DBB, $086D3D2D, $91646C97, $E6635C01,
      $6B6B51F4, $1C6C6162, $856530D8, $F262004E,
      $6C0695ED, $1B01A57B, $8208F4C1, $F50FC457,
      $65B0D9C6, $12B7E950, $8BBEB8EA, $FCB9887C,
      $62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65,
      $4DB26158, $3AB551CE, $A3BC0074, $D4BB30E2,
      $4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB,
      $4369E96A, $346ED9FC, $AD678846, $DA60B8D0,
      $44042D73, $33031DE5, $AA0A4C5F, $DD0D7CC9,
      $5005713C, $270241AA, $BE0B1010, $C90C2086,
      $5768B525, $206F85B3, $B966D409, $CE61E49F,
      $5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4,
      $59B33D17, $2EB40D81, $B7BD5C3B, $C0BA6CAD,
      $EDB88320, $9ABFB3B6, $03B6E20C, $74B1D29A,
      $EAD54739, $9DD277AF, $04DB2615, $73DC1683,
      $E3630B12, $94643B84, $0D6D6A3E, $7A6A5AA8,
      $E40ECF0B, $9309FF9D, $0A00AE27, $7D079EB1,
      $F00F9344, $8708A3D2, $1E01F268, $6906C2FE,
      $F762575D, $806567CB, $196C3671, $6E6B06E7,
      $FED41B76, $89D32BE0, $10DA7A5A, $67DD4ACC,
      $F9B9DF6F, $8EBEEFF9, $17B7BE43, $60B08ED5,
      $D6D6A3E8, $A1D1937E, $38D8C2C4, $4FDFF252,
      $D1BB67F1, $A6BC5767, $3FB506DD, $48B2364B,
      $D80D2BDA, $AF0A1B4C, $36034AF6, $41047A60,
      $DF60EFC3, $A867DF55, $316E8EEF, $4669BE79,
      $CB61B38C, $BC66831A, $256FD2A0, $5268E236,
      $CC0C7795, $BB0B4703, $220216B9, $5505262F,
      $C5BA3BBE, $B2BD0B28, $2BB45A92, $5CB36A04,
      $C2D7FFA7, $B5D0CF31, $2CD99E8B, $5BDEAE1D,
      $9B64C2B0, $EC63F226, $756AA39C, $026D930A,
      $9C0906A9, $EB0E363F, $72076785, $05005713,
      $95BF4A82, $E2B87A14, $7BB12BAE, $0CB61B38,
      $92D28E9B, $E5D5BE0D, $7CDCEFB7, $0BDBDF21,
      $86D3D2D4, $F1D4E242, $68DDB3F8, $1FDA836E,
      $81BE16CD, $F6B9265B, $6FB077E1, $18B74777,
      $88085AE6, $FF0F6A70, $66063BCA, $11010B5C,
      $8F659EFF, $F862AE69, $616BFFD3, $166CCF45,
      $A00AE278, $D70DD2EE, $4E048354, $3903B3C2,
      $A7672661, $D06016F7, $4969474D, $3E6E77DB,
      $AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0,
      $A9BCAE53, $DEBB9EC5, $47B2CF7F, $30B5FFE9,
      $BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6,
      $BAD03605, $CDD70693, $54DE5729, $23D967BF,
      $B3667A2E, $C4614AB8, $5D681B02, $2A6F2B94,
      $B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D);

var F: file;
    BytesRead: dword;
    Buffer: Array[1..65521] of byte;
    i: Word;
begin
    FileMode := 0;
    CRC32 := $ffffffff;
    {$I-}
    AssignFile(F, FileName);
    Reset(F, 1);
    if IOResult = 0 then
    begin
      repeat
        BlockRead(F, Buffer, SizeOf(Buffer), BytesRead);
        for i := 1 to BytesRead do CRC32 := (CRC32 shr 8) xor Table[Buffer[i] xor (CRC32 and $000000FF)];
      until BytesRead = 0;
    end;
    CloseFile(F);
    {$I+}
    CRC32 := not CRC32;
end;

Now I want to do the same for 64Bit DLLs in my 64Bit application.
But above code always returning 0.
I am not able to convert this code. Can someone please guide me here.
TIA
Yogi Yang

A: There is absolutely no reason for CRC of a 32-bit DLL to behave differently to CRC of a 64-bit DLL. CRC simply works on a file as is.

SIDE NOTE: The 32 in CRC32 has nothing to do with whether the app/dll or whatever is 32-bit. (You can run a CRC on a text file if you choose.) The 32 refers to the size of the check value i.e. 32-bits.

Your code is deliberately hiding IO errors: First with {$I-} and then by quietly doing nothing if IOResult <> 0. Hiding errors is a terrible thing to do, and leads to misdiagnosis of problems as you have here.
If you fix the CRC code to stop hiding errors, you can at least find out what the real problem is. I.e. Add code to report the error as below.
Reset(F, 1);
if IOResult = 0 then
begin
  ...
end
else
begin
  RaiseLastOSError; //Defined in SysUtils
end;

UPDATE
Once you've learnt the real problem and why hiding errors is such a bad thing to do, I suggest you modernise your CRC code as explained below.
NOTE This code very deliberately does not make any attempt to hide errors.

*

*If you hide errors and something goes wrong, you're left puzzling why it's not working.

*If you don't hide errors and something goes wrong, you get an exception/error telling you what went wrong; and therefore half the work fixing the problem is done already!

Write an overload of CalcCRC32 using TStream.
function CalcCRC32(AStream: TStream): Cardinal;
const CRCTable: array[0..255] of DWord =
     //Put your large const array here;
var
  LBytesRead: Integer;
  LBuffer: array[1..65521] of byte;
  LLoopI: Word;
begin
  Result := $ffffffff;

  repeat
    LBytesRead := AStream.Read(LBuffer, SizeOf(LBuffer));
    for LLoopI := 1 to LBytesRead do
    begin
      Result := (Result shr 8) xor CRCTable[LBuffer[LLoopI] xor (Result and $000000FF)];
    end;
  until LBytesRead = 0;

  Result := not Result;
end;

Then you can modify your existing routine as follows to keep calling code working as before.
procedure CalcCRC32(AFileName: String; var CRC32: DWORD);
var
  LStream: TStream;
begin
  LStream := TFileStream.Create(AFileName, fmOpenRead, fmShareDenyNone);
  try
    CRC32 := CalcCRC32(LStream);
  finally
    LStream.Free;
  end;
end;

A: That function operates the same in 32 bit as 64 bit. There is nothing to change.
If the file cannot be opened the function returns 0, because not $ffffffff = $00000000.
Thus I conclude that nothing more is happening here than your file not being found.
One problem with your code is that it doesn't give very identifiable error signals. When a file cannot be found, or is locked, or just happens to have a CRC value of 0, the outcome is the same. Which is really the root of your confusion. Some error handling should be added to make the failure modes distinguishable.
The code is also limited to operating on files. A stream based implementation would make it more flexible, and probably go a long way to making error handling easy to add.

A: It should be: fmOpenRead or fmShareDenyNone, but for CRC32 calculation I would suggest to use fmShareDenyWrite
LStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);


text:
Q: Thread.Abort and App crash all
I found something wierd with my program
using System;
using System.Data.SqlTypes;
using System.Threading;
namespace TestCrash
{
  class Program
  {
    static void Main(string[] args)
    {
      /*Console.WriteLine(typeof(SqlInt32));*/
      var h = new Holder();
      h.Test();
      Console.WriteLine("TestHolder");
      Console.ReadLine();
    }
  }
  public class Holder
  {
      private Thread t;
      private void Work()
      {
          Thread.Sleep(Timeout.Infinite);
      }
      ~Holder()
      {
          t.Abort();
      }
      public void Test()
      {
          t = new Thread(new ThreadStart(Work));
          t.IsBackground = true;
          t.Start();
      }
  }

This program terminates normally, however, if I uncomment the fisrt code line in Main which prints type of 'System.Data.SqlTypes.SqlInt32', the program will crash when exit, and the windows event tells me that 'Access Violation' (0xc0000005)
Faulting application name: TestCrash.exe, version: 1.0.0.0, time stamp: 0x52b0189a
Faulting module name: ntdll.dll, version: 6.1.7600.16385, time stamp: 0x4a5be02b
Exception code: 0xc0000005
Fault offset: 0x00000000000159ad
Faulting process id: 0x1f20
Faulting application start time: 0x01cefb129f0bf5e8
Faulting application path: C:\yuanf\Flx\Source\TestCrash\bin\Debug\TestCrash.exe
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: ddf78d96-6705-11e3-bafd-005056b80090

I found it has something to do with the thread abort, but can anyone explain why abort the 'Work' thread in the finalizer will cause the crash, while in other threads this will work well?
After some experiments, I found instead of printing 'System.Data.SqlTypes.SqlInt32', any code that can introduce loading of the System.Data.dll will make this program terminate abnormally. How does it matter?
To be noted, according to my tests, the crash happens only with .NET 4.0 on windows 2008R2, or win 7. With other version of .NET like 3.5 or 4.5, or OS like Windows XP, it terminates normally.
Thank you in advance!


text:
Q: INSERT INTO SQL Server : Linked Server without specifying database in semi-fully qualified name I have a server called DEV, a database called Nus12345, a linked server called SnapshotDev, a schema called Snapshot, and a table called SnapshotPersonEmployee.
On the DEV server, there are many other databases. On the linked server, there are the same databases as on DEV.
Right now I have a stored procedure that inserts into the table with
INSERT INTO Snapshot.SnapshotPersonEmployee

We are instead conceptually wanting to change to inserting into a table on a linked server by using
INSERT INTO [SnapshotDev].[Nus12345].[Snapshot].[SnapshotPersonEmployee]

My question is, can I insert into the table on the linked server without changing the stored procedure? Is there a way (like making a synonym) that will reference the table on the linked server with just
INSERT INTO Snapshot.SnapshotPersonEmployee

EDIT
I should add that this stored procedure appears once on every database, and that is why I want to try to do this without change the stored procedure. By not naming the database it allows us to keep one version of the stored procedure--one SP on each database, but they are all the same.
We are thinking of removing the SnapshotPersonEmployee table in the current (DEV) server from all of the databases. Would this help/hinder any possible solutions?

A: Yes you can. Use SQL synonyms https://msdn.microsoft.com/en-us/library/ms187552(v=sql.105).aspx
By doing that you'll have a full control behind the curtains, but please fully document it and be consistent. It is a nightmare to troubleshoot databases with synonyms.
As an alternative you can use dynamic SQL, it might be more transparent.

A: If you are willing to drop/rename the original table, then you can create a view with the same name instead, but pointing at the linked server.
So your view would be in the snapshot database (but please list your columns):
CREATE VIEW [Snapshot].[SnapshotPersonEmployee] AS

SELECT * FROM [SnapshotDev].[Nus12345].[Snapshot].[SnapshotPersonEmployee]

Then you can insert into it as you would any other table.  This also lets you avoid synonyms which as Slava Murygin pointed out can be problematic to troubleshoot.


text:
Q: Java client-socket:Cannot receive messages from server to client So there this problem that has been giving me headaches for days now.I am making a multi-user chat application.My design is as follows:
1.There is a login window.
2.As soon as the details are entered, the client-side chat window opens.
3.Now the user starts typing.
4.As soon as he hits enter or clicks on the send button,the message is sent to the server.
5.The server sends it to all clients, including the one that send it the original message.
The problem:I am unable to receive any messages from the server to the client.
Here is my server class:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server implements Runnable {
static InetAddress address;
static ArrayList<Integer> clients=new ArrayList<Integer>();
static ArrayList<Socket> socs=new ArrayList<>();
static String message="";
static DataOutputStream toClient;
static  ServerSocket socket;
static Socket socketNew;
static boolean running=false;
public static void main(String[] args) throws IOException
{
    socket=new ServerSocket(8000);
    System.out.println("Server started on port 8000");
    running=true;

    while(true)
    {
        socketNew=socket.accept();
        socs.add(socketNew);
        address=socketNew.getInetAddress();

        System.out.println("connected to client at address: "+address);

        Server server=new Server();
        new Thread(server).start();

    }
}

public void run() {
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(socketNew.getInputStream()));
        String message;
        PrintWriter out;

        while ((message = br.readLine()) != null) {
            System.out.println(message);
            for (Socket s : socs) // sending the above msg. to all clients
            {
                out = new PrintWriter(s.getOutputStream(), true);
                out.write(message);
                out.flush();

            }

        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

And here is the receive_message function in the client class.Note that this method,I've run on a separate thread that starts as soon as the user logs-in.
public void receive_data()
{while(true)
{
try {
    BufferedReader in;
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    while(in.readLine()!=null)
    {
        System.out.println(in.readLine());
       console(in.readLine());
       }
   }
 catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }

  }
 }

}

Any suggestions?Thanks for your time. :-)

A: You are writing messages without a line ending, while your client is waiting for a line ending character in the readLine loop. By placing out.write('\n') in your server send loop, it will also send a newline character.
Example:
for (Socket s : socs)  {
     out = new PrintWriter(s.getOutputStream(), true);
     out.write(message);
     out.write('\n'); // added this line
     out.flush();
}


text:
Q: Parsing json response into dict using yaml I am trying to parse a string into a dictionary using python's yaml module. I am getting exception when the value has ":" in it. Here is my sample code
import yaml

input = '''{"method":"Send", "buf":{"html":"

Sample message

Parse it

","text":"\t* Sample message\n\t* Parse it\n"}} '''
yaml.load(input)

I get the following exception
Traceback (most recent call last):
  File "webmailparser.py", line 9, in ?
    yaml.load(input)
  File "/usr/lib/python2.4/site-packages/yaml/__init__.py", line 58, in load
    return loader.get_single_data()
  File "/usr/lib/python2.4/site-packages/yaml/constructor.py", line 42, in get_single_data
    node = self.get_single_node()
  File "/usr/lib/python2.4/site-packages/yaml/composer.py", line 35, in get_single_node
    if not self.check_event(StreamEndEvent):
  File "/usr/lib/python2.4/site-packages/yaml/parser.py", line 93, in check_event
    self.current_event = self.state()
  File "/usr/lib/python2.4/site-packages/yaml/parser.py", line 138, in parse_implicit_document_start
    StreamEndToken):
  File "/usr/lib/python2.4/site-packages/yaml/scanner.py", line 116, in check_token
    self.fetch_more_tokens()
  File "/usr/lib/python2.4/site-packages/yaml/scanner.py", line 252, in fetch_more_tokens
    return self.fetch_plain()
  File "/usr/lib/python2.4/site-packages/yaml/scanner.py", line 679, in fetch_plain
    self.tokens.append(self.scan_plain())
  File "/usr/lib/python2.4/site-packages/yaml/scanner.py", line 1308, in scan_plain
    "Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.")
yaml.scanner.ScannerError: while scanning a plain scalar
  in "<string>", line 1, column 58:
     ... "html":"<div style="color:#000; background-color:#ff ...
                                         ^
found unexpected ':'
  in "<string>", line 1, column 63:
     ... ":"<div style="color:#000; background-color:#fff; fo ...
                                         ^
Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.

Is there any workaround for this?
This worked
import yaml

input = r'{"method":"Send", "buf":{"html":"

Sample message

Parse it

","text":"\t* Sample message\n\t* Parse it\n"}} '
print yaml.load(input)


text:
Q: function for intersection of 2 lines design I have class Line, which represent 2 dimensional line. It has function for checking if 2d point lie on this line.
class Line
{
    private:
       float a,b,c: //line coefficients
    public:
    bool checkPointOnLine();
    .....
}

now I have to check find point of intersectionof 2 lines. I'm wondering if it is better to put new member function in class Line  like
class Line
{
    private:
       float a,b,c: //line coefficients
    public:
    bool checkPointOnLine();
    Point getIntersectionPoint(const  Line& line);
    .....
}

or to use non member function
Point getIntersectionPoint(const Line& l1,const Line& l2);

A: Although to a large measure this is a matter of preference, a static or non-member function approach is slightly more preferable because of symmetry.
When two calls
a.someFunction(b)

and
b.someFunction(a)

always return the same result, a symmetric function
someFunction(a, b)

is more intuitive.
Note that since an intersection may not exist (for parallel lines) or have an infinite number of points (for two identical lines) returning a Point is not ideal. You would be better off returning a pair of Point and some indicator of its validity, for example
enum LineIntersectionKind {
    Valid
,   Empty
,   Infinite
};

pair<Point,LineIntersectionKind> getIntersectionPoint(const Line& l1,const Line& l2);


text:
Q: TensorFlow Object detection API only in specified region of frame (defining ROI in input frame) I am using TensorFlow Object Detection API (https://github.com/tensorflow/models) for custom object detection.
I have trained my model on custom object detection, and the result is good.
Now I want to define a region in my input frame, i,e only in this defined region my object detection should be working. The object detected outside the region of interest should be ignored.
import cv2
cap = cv2.VideoCapture('video.mp4')

def run_inference(model, cap):
    while cap.isOpened():
        ret, image_np = cap.read()
        # Actual detection.
        output_dict = run_inference_for_single_image(model, image_np)
        # Visualization of the results of detection.
        vis_util.visualize_boxes_and_labels_on_image_array(
            image_np,
            output_dict['detection_boxes'],
            output_dict['detection_classes'],
            output_dict['detection_scores'],
            category_index,
            instance_masks=output_dict.get('detection_masks_reframed', None),
            use_normalized_coordinates=True,
            line_thickness=8)
        cv2.imshow('object_detection', cv2.resize(image_np, (800, 600)))
        if cv2.waitKey(1) & 0xFF == ord('q'):
            cap.release()
            cv2.destroyAllWindows()
            break

run_inference(detection_model, cap)

I have tried using  cv2 function polylines to define lines on my input frames.
cv2.polylines(image, [pts], isClosed, color, thickness)

but couldn't activate object detection API to work only in the specified region
Expected Final Output: In the video frame I should a polygon box representing as Region of Interest(ROI) and whenever objected is detected inside the ROI it should give me bounding boxes (outside this ROI, it can neglect)

A: cv2.polylines() is just for drawing lines on the image, it's merely a visual thing.
You can crop the numpy image image_np by the region you want, and pass that cropped img to tf.
image_cropped = image_np[y_start:y_end, x_start:x_end]

What is a bit unintuitive is that when a image is represented with numpy, the first index is 'y axis', and second index is 'x axis'.


text:
Q: Is there a Java annotation to generate parameter documentation? Projects like hadoop have a ton of parameters, but all that documentation is manually generated from xml, rather than coming from the code.
Is there a way of doing something with an annotation that can generate this documentation?
  public static final String MAP_SORT_SPILL_PERCENT = "mapreduce.map.sort.spill.percent";

  <name>mapreduce.map.sort.spill.percent</name>
  <value>0.80</value>
  <description>The soft limit in the serialization buffer. Once reached, a
  thread will begin to spill the contents to disk in the background. Note that
  collection will not block if this threshold is exceeded while a spill is
  already in progress, so spills may be larger than this threshold when it is
  set to less than .5</description>

A: You can use @param javadoc tag to generate parameter information in the code, such as this example from the wikipedia page:
/**
 * Short one line description.
 *
 * @param  variable Description text text text.
 * @return Description text text text.
 */
public int methodName (...) {
    // method body with a return statement
}

That's how Oracle generates the official doc for Java (example)


text:
Q: Game development: "Play Now" via website vs. download & install I've spent some time looking over the various threads here on stackoverflow and while I saw a lot of posts and threads regarding various engines that could be used in game development, I haven't seen very much discussion regarding the various platforms that they can be used on.
In particular, I'm talking about browser games vs. desktop games.
I want to develop a simple 3D networked multiplayer game - roughly on the graphics level of Paper Mario and gameplay with roughly the same level of interaction as a hack & slash action/adventure game - and I'm having a hard time deciding what platform I want to target with it. I have some experience with using C++/Ogre3D and Python/Panda3D, but I'm wondering if it's worth it to spend the extra time to learn another language and another engine/toolkit just so that the game can be played in a browser window (I'm looking at jMonkeyEngine right now).
For simple & short games the newgrounds approach (go to the site, click "play now", instant gratification) seems to work well. What about for more complex games? Is there a point where the complexity of a game is enough for people to say "ok, I'm going to download and play that"? Is it worth it to go with engines that are less-mature, have less documentation, have fewer features, and smaller communities* just so that a (possibly?) larger audience can be reached? Does anyone have any experiences with decisions like this?
Thanks!
(* With the exception of flash-based engines it seems like most of the other approaches have these downsides when compared to what is available for desktop-based environments. I'd go with flash, but I'm worried that flash's 3D capabilities aren't mature enough right now to do what I want easily).

A: Download and install is a harder sell.  People are more reluctant to do it, and once they have done it, you own the problem of platform compatibility, and you have installed code to update or avoid as your game evolves.
Java applets eliminate all that mess.   Presumably also flash or html5.


text:
Q: Drawing smooth lines with canvas So far none of the threads here on smooth lines are correct.
how to draw smooth curve through N points using javascript HTML5 canvas?
Smooth user drawn lines in canvas
Both result in jagged lines. By smooth I mean using the x,y points as control points to make the line smooth.  The line does NOT need to go through the points.  It simply has to draw a smooth line given n points.
Basically I'm recording each line segment, then when the user mouses up, it wil smooth the line.
I've tried my own method using bezierCurveTo but that only smooths every other point, and then the connecting points are harsh still.  The internet seems to think what I'm looking for is called B-Spline curves. I tried applying a linear algebra matrix to the problem, but I failed at that lol.
Here is the best curve I can get, (image). The line in red is the "smoothed" line, as you can see it smooths every other point, but not continuous.  This is using the code from
how to draw smooth curve through N points using javascript HTML5 canvas?
My code does the same thing
http://www.square-bracket.com/images/smoothlines.png
Thanks for your help!

A: You need to keep the same tangent in the points bellowing in the line. Check http://jsfiddle.net/FHKuf/4/.
Edit:
Sorry, just noticed your comment today. Just happened to be testing something related and remembered your question. It happens that in the past I did wrote some code to interpolate some lines. It is called Catmull-Rom(just a ref. that I googleed) it passes by the middle control points. I did changed the code to my test and thought that you may have some use to it. See at http://jsfiddle.net/FHKuf/6/.

A: I was exploring all techniques but did not get any proper solution for smooth free drawing on canvas. Then I simply used quadraticCurveTo with different logic without using original mouse points.
I first calculated control point(mid-point) and replace old mouse move point with the control point. I did this 2 times and finally applied quadraticCurveTo to the final array and I got super smooth drawing.
It was amazing. I did it without using this heavy paper.js and other smoothing libraries.
Here is my code:
currentCanvas.beginPath();
        currentCanvas.lineCap = 'round';
        currentCanvas.strokeStyle = "black";
        currentCanvas.lineWidth = "2";
        currentCanvas.moveTo(queue[0].x, queue[0].y);

        //queue is an array of original points which were stored while onmousemove event callback

        var tempQueue1 = [queue[0]];
        for (var i = 1; i < queue.length - 1;  i = i+1) {
            //if((Math.abs(queue[i].x - queue[i-1].x) >3 || Math.abs(queue[i].x - queue[i-1].x)<1) &&  (Math.abs(queue[i].y - queue[i-1].y) >3 || Math.abs(queue[i].y - queue[i-1].y)<1)){
                var c = (queue[i].x + queue[i + 1].x) / 2;
                var d = (queue[i].y + queue[i + 1].y) / 2;
                //tempQueue.push(queue[i]);
                tempQueue1.push({x:c, y:d});
                //currentCanvas.quadraticCurveTo(queue[i].x, queue[i].y, c, d);
            //}
        }

        var tempQueue2 = [tempQueue1[0]];
        for (var i = 1; i < tempQueue1.length - 1;  i = i+1) {
            //if((Math.abs(queue[i].x - queue[i-1].x) >3 || Math.abs(queue[i].x - queue[i-1].x)<1) &&  (Math.abs(queue[i].y - queue[i-1].y) >3 || Math.abs(queue[i].y - queue[i-1].y)<1)){
                var c = (tempQueue1[i].x + tempQueue1[i + 1].x) / 2;
                var d = (tempQueue1[i].y + tempQueue1[i + 1].y) / 2;
                //tempQueue.push(queue[i]);
                tempQueue2.push({x:c, y:d});
                //currentCanvas.quadraticCurveTo(queue[i].x, queue[i].y, c, d);
            //}
        }

        var tempQueue = [tempQueue2[0]];
        for (var i = 1; i < tempQueue2.length - 1;  i = i+1) {
            //if((Math.abs(queue[i].x - queue[i-1].x) >3 || Math.abs(queue[i].x - queue[i-1].x)<1) &&  (Math.abs(queue[i].y - queue[i-1].y) >3 || Math.abs(queue[i].y - queue[i-1].y)<1)){
                var c = (tempQueue2[i].x + tempQueue2[i + 1].x) / 2;
                var d = (tempQueue2[i].y + tempQueue2[i + 1].y) / 2;
                //tempQueue.push(queue[i]);
                tempQueue.push({x:c, y:d});
                //currentCanvas.quadraticCurveTo(queue[i].x, queue[i].y, c, d);
            //}
        }

        for (var i = 1; i < tempQueue.length - 2;  i = i+1) {
            //if((Math.abs(queue[i].x - queue[i-1].x) >3 || Math.abs(queue[i].x - queue[i-1].x)<1) &&  (Math.abs(queue[i].y - queue[i-1].y) >3 || Math.abs(queue[i].y - queue[i-1].y)<1)){
                var c = (tempQueue[i].x + tempQueue[i + 1].x) / 2;
                var d = (tempQueue[i].y + tempQueue[i + 1].y) / 2;
                currentCanvas.quadraticCurveTo(tempQueue[i].x, tempQueue[i].y, c, d);
            //}
        }

        // For the last 2 points
        currentCanvas.quadraticCurveTo(
        tempQueue[i].x,
        tempQueue[i].y,
        tempQueue[i+1].x,
        tempQueue[i+1].y
        );
        currentCanvas.stroke();
        queue = [];


text:
Q: Guest User permission problem on update operation I am using the AppExchange Unsubscribe Link package (from Salesforce Labs) (version installed 3.10.0) and I get the following error when I try to unsubscribe a Lead or Contact:

FIELD_CUSTOM_VALIDATION_EXCEPTION: Insufficient permissions: secure query included inaccessible field

I think that this is related to the security policies incorporated on Summer '20 for guest users for not allow update and delete records, only create and read.
As the unsubscribe link needs a guest user (unauthenticated user) for the requeriment makes sense and it must update the field HasOptedOutOfEmail from Contact or Lead, I don't how to by pass the error.
I tried the following:

*

*I check that the error ocurrs when the packages attempt an update on Contact or Lead. That happen on update flow component.

*I check the permissions and adding the guest user to "Unsubscribe Link" permission set.

*I check that all the Flows of the packages runs as System mode without colaboration (see all data).

*I create manual sharing rules for guest user to the Contact and Lead objects in order that that user can see all data.

*I removed the update flow component that causes the error and replaced it by a trigger that is mounted on the Unsubscribe Link custom object.This record is created before that the Contact or Lead update. Same error.

*I moved the apex logic from the trigger to a class with without sharing keyword on the definition of the class and creating a static method with the update logic. Same error.

*I make the static method as @future. Same error.

*I change the static method in an instance method. Same error.

*I make an @InvocableMethod that is invoked from the same flow. Same error.
What can I do for bypass this error and Salesforce allow me to update the Lead or Contact record with the guest user?
Thanks!


text:
Q: Click on DIV to show image path in an alternate DIV I have a div placed outside the image div

Click

javascript/jquery code below to get the image path.
$('.TextShow').click(function() {
var ImageShowed = $('#2').attr('src');
alert(ImageShowed);
});

When I click on .TextShow the ImageShowed is NULL.
My question is, why am I not getting the image path.

A: You are missing a { and have added an extra [ which as nothing to do here.
Here's your corrected code:
jQuery(function ($) {
    $('.TextShow').click(function () { // << this was missing
        var ImageShowed = $('#2').attr('src'); // << removed the extra [
        alert(ImageShowed);
    });
});

Also, think of wrapping your code inside jQuery(function($) { ... }); to be sure your jQuery code is executed after the DOM is loaded.
Working JSFiddle

A: You have some syntax problems:

*

*first line missing '{' at the end

*Second line contains extra '[' that should be removed

your code should look like this:
$('.TextShow').click(function() {
var ImageShowed = $('#2').attr('src');
alert(ImageShowed);
});

here is a working sample: http://jsbin.com/wejozopeci/1/edit?html,js,output


text:
Q: Why Icinga2 telegram notification fails in specific services? I have created custom telegram notification very similar to email notifications. The problem is that it works for hosts and most of the services but not for all of them.
I do not post the *.sh files in scripts folder as it works!
In constants.conf I have added the bot token:
const TelegramBotToken = "MyTelegramToken"

I wanted to manage telegram channels or chat ids in users file, so I have users/user-my-username.conf as below:
object User "my-username" {
    import "generic-user"

    display_name = "My Username"
    groups = ["faxadmins"]

    email = "my-username@domain.com"
    vars.telegram_chat_id = "@my_channel"
}

In templates/templates.conf I have added the below code:
template Host "generic-host-domain" {
    import "generic-host"
    vars.notification.mail.groups = ["domainadmins"]
    vars.notification["telegram"] = {
        users = [ "my-username" ]
    }
}

template Service "generic-service-fax" {
  import "generic-service"
  vars.notification["telegram"] = {
        users = [ "my-username" ]
  }
}

And in notifications I have:
template Notification "telegram-host-notification" {
  command = "telegram-host-notification"
  period = "24x7"
}

template Notification "telegram-service-notification" {
  command = "telegram-service-notification"
  period = "24x7"
}

apply Notification "telegram-notification" to Host {
  import "telegram-host-notification"

  user_groups = host.vars.notification.telegram.groups
  users = host.vars.notification.telegram.users

  assign where host.vars.notification.telegram
}
apply Notification "telegram-notification" to Service {
  import "telegram-service-notification"

  user_groups = host.vars.notification.telegram.groups
  users = host.vars.notification.telegram.users

  assign where host.vars.notification.telegram
}

This is all I have. As I have said before it works for some services and does not work for other services. I do not have any configuration in service or host files for telegram notification.
To test I use Icinga web2. Going to a specific service in a host and send custom notification. When I send a custom notification I check the log file to see if there is any error and it says completed:
[2017-01-01 11:48:38 +0000] information/Notification: Sending reminder 'Problem' notification 'host-***!serviceName!telegram-notification for user 'my-username'
[2017-01-01 11:48:38 +0000] information/Notification: Completed sending 'Problem' notification 'host-***!serviceName!telegram-notification' for checkable 'host-***!serviceName' and user 'my-username'.

I should note that email is sent as expected. There is just a problem in telegram notifications for 2 services out of 12.
Any idea what would be the culprit? What is the problem here? Does return of scripts (commands) affect this behaviour?
There is no Telegram config in any service whatsoever.

A: Some telegram commands may fail due to markdown parser.
I've encountered this problem:
If service name has one underscore ('_'), then parser will complain about not closed markdown tag and message will not be sent


text:
Q: Facing a problem when re-projecting a file? I am trying to re-project from Equi-rectangular. The file is provided as HDF5.
I wonder why half of the map is not projected correctly.
gdal_translate -of "ENVI" -gcp 0 0 0 90 -gcp 1440 0 360 90 -gcp 0 720 0 -90 -
gcp 1440 7 20 360 -90 -a_srs "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"

here how the results look like:
![enter image description here][1]
For info:

A: I have added a few intermediate steps to change longitudes from 0/360 to -180/180:
gdal_translate HDF5:"GW1AM2_20141231_01D_EQOD_L3SGTPWLA1100100.nc"://Time_Information ti.tif
gdal_translate -a_ullr 0 90 360 -90 -a_srs epsg:4326 ti.tif deg.tif
gdalwarp -t_srs epsg:4326 -wo SOURCE_EXTRA=1000 --config CENTER_LONG 0 deg.tif degree.tif
gdalwarp -of "ENVI" -s_srs "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" -t_srs "+proj=cea +lon_0=0 +lat_ts=30 +x_0=0 +y_0=0 +a=6371228 +b=6371228 +units=m +no_defs" -ts 1383 586 degree.tif gcp_wgs_ease.img

and it looks like expected:


text:
Q: webview.postUrl(String url, byte[] postData) not working for Android 11 and above? I am trying to load data in my webview and with the method:
webview.postUrl(url, byteData)

I am able to get correctly filled form data in webview but for Android OS 11 and above it is loading plain form with no data filled.


text:
Q: Using ternary operator in lambda where condition This is how I retrieve my data using linq lambda expression.
var data = await _repo.GetAll().where(x => x.isDeleted = false).CountAsync();

And I also want to filter my data with _date.
bool filterWithDate = false;
var _date = DateTime.Now.AddDays(-7);

filterWithDate will be pass by method parameter and it's dynamic.
If it's true , I want to filter by _date , if false , I will get all data.
I can check with if(filterWithDate) here , but I just want to filter in linq where condition with ternary operator to simplify my code.
var data = await _repo.GetAll().
where(x => x.isDeleted = false
&& (filterWithDate) ? x.date >= _date : ??? ).CountAsync();

A: As stated in the comment,
You could use two lines instead and still use ternary operator
var data = filterWithDate ?
               await _repo.GetAll().Where(x => x.isDeleted = false && x.date >= _date).CountAsync() :
               await _repo.GetAll().Where(x => x.isDeleted = false).CountAsync();

Or You go full if statement
if(filterWithDate)
    await _repo.GetAll().Where(x => x.isDeleted = false && x.date >= _date).CountAsync();
else
    await _repo.GetAll().Where(x => x.isDeleted = false).CountAsync();

This will save you a lot of thinking

A: While I agree with the comments on the question and also the answer from @Bosco, If you still would like to go with a sinlge-line change, you can try this...
var data = await _repo.GetAll().
    Where(x => !x.isDeleted && (!filterWithDate || x.date >= _date)).CountAsync();


text:
Q: I tried to add proxies to a get request but it didn't work in this code below I just read the proxies from a txt file then I choose a random proxy to connect
but It keep to connect with my original IP please help
while True:
 proxy = set()
 with open("proxies.txt", "r") as f:
     file_lines1 = f.readlines()
     for line1 in file_lines1:
         proxy.add(line1.strip())

 session = req.session()
 proxies = {
     'http': 'http://' + random.choice(list(proxy))
 }
 print(proxies)
 ip = session.get('https://api.ipify.org', proxies=proxies).text
 print(ip)


text:
Q: Get data from MongoDb and insert in a file I built the next files:

var express = require('express');
var app = express();
app.set("view engine", "ejs");

app.use("/", function(request, response){
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("Test");
    dbo.collection("users").findOne({},function(err, result) {
    if (err) throw err;
    console.log(result);
    var name = result.name;
    response.render('index',{ name});
    db.close();
  });
});
});
app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

<%=name %>

I get the first name of users from my database:MongoDb, and i insert it
<%=name %>
. How to get all names from database? Now i get only the first.

A: So, As far as I could understand the question it is You want to get the first name of all the users in the collection users .
If that is what you are looking to achieve. May be we should understand first as to why we are only getting one User. It could very well be because of the method.

dbo.collection("users").findOne({},function(err, result) {});

As the name suggest findOne will only return one object that matches the criteria given as the first argument to the methdo findOne which in Our case is simply {}. So, In Our case it would return the very first User in User collection. To get the list of all the Users simply change findOne to simply find. Which In Our case would then be :

dbo.collection("users").find({},function(err, result) {});


text:
Q: Php code inside html or html inside php? I am writing code in php, but I am confused in the following coding styles:

    <?php echo 'Hello World'; ?>

This is another

    <?php echo 'hello again'; ?>

OR
<?php
  echo '

    Hello World

This is another

    hello again

 ';
?>

And, Which is better in complex programming?

A: The first one is better in all cases. Why? Simply because there is no need to escape any characters, and there is syntax highlighting in editors. It also makes your code more readable (especially if you use indenting in the HTML as well)
Besides, the ability to interleave HTML and PHP is a core feature of PHP. It's meant to be used like this. You can even do stuff like:
The programmer says
<?php if(isGoodbye()){ ?>
goodbye
<?php }else{ ?>
hello
<?php }?>
world

It makes life easy for you, so why not use it?

A: First one for sure.
Look, your HTML is

*

*natural,

*can be highlighted,

*indented

*checked for syntax errors automatically by the editor.

This is called "PHP template" and being most useful way of separating business logic from presentation logic (save for the special template languages)


text:
Q: Which of the following is (are) correct? Let $F$ be a finite field.If $f:F\rightarrow F$,given by $f(x)=x^3$ is a ring homomorphism,then
$(A)$$F=\mathbb Z/3\mathbb Z$.
$(B)$$F=\mathbb Z/2\mathbb Z$ or $Characteristic$ of $F=3$.
$(C)$$F=\mathbb Z/2\mathbb Z$ or $\mathbb Z/3\mathbb Z$.
$(D)$$Characteristic$ of $F$ is $3$.
Solution:
If  $F=\mathbb Z/3\mathbb Z=${$0,1,2$} or $F=\mathbb Z/2\mathbb Z=${$0,1$},then elements of $F$  are  satisfying the operation preserving properties.This leads me (PLEASE CHECK!!) to the  selection of options$(A)$,$(B)$ and $(C)$.
I'm not getting how to accept or discard option $(D)$.
Please give some suggestions  about my attempt......

A: I guess you are to make the following observations (you justify the unclear conclusions):

*

*If $f$ is a homomorphism of fields, then
$$2=1+1=f(1)+f(1)=f(1+1)=f(2)=2^3.$$ This implies that $F$ has characteristic either two or three.

*$f$ is the identity mapping of $\Bbb{Z}/2\Bbb{Z}$.

*If $F$ has characteristic three, then for all $z_1,z_2\in F$ we have
$$F(z_1+z_2)=(z_1+z_2)^3=z_1^3+3z_1^2z_2+3z_1z_2^2+z_2^3=z_1^3+z_2^3.$$ This implies that $f$ is a homomorphism of rings.

*If $F$ has characteristic two, and there exists an element $z\in F$, $z\neq0,1$, then we can conclude that $z+z^2\neq0.$

*If $F$ and $z$ are as in step 4, then
$$f(1+z)=(1+z)^3=1+3z+3z^2+z^3=1+z+z^2+z^3=f(1)+f(z)+(z+z^2),$$
so $f$ is not a homomorphism of rings.

*Putting all this together we see that (B) is correct and the rest of the claims are false. For full credit it is important that you understand the logic of this conclusion. I gathered that this may be a difficult step.


text:
Q: UITextInput not announced correctly by VoiceOver I have a problem with how VoiceOver announces my custom UITextInput while it has the keyboard focus: When the accessibility focus is moved to the UITextInput view by swiping left/right the UITextInput is correctly announced by VoiceOver and I am hearing something like Text field, is editing, <content of text input>, character mode, insertion point at end.
However, if I move the accessibility focus to the UITextInput by tapping on it, VoiceOver says empty line, which is not correct.
I would expect VoiceOver to make the exact same announcement regardless of how the UITextInput got the accessibility focus.
Any ideas what might be the cause of this strange behavior?

A: To mark up a text field you need to take advantage of a few different properties. First, the "Text field" part you can only get by having your custom control extend the UITextFIeld class. That's the only way you can get that announcement at the beginning without effecting the read out of other things. You could append this to the label. Here are the properties I would recommend for your custom text editor.
Preferred Markup

ClassType: Subclass of UITextField (Probably the most important piece)
AccessibilityLabel: The thing the entered text represents (Ex: Password, Username, etc).
AccessibilityValue: The entered text.
AccessibilityHint: "Some non critical information, that shares some details about what the entered information will be used for."
AccessibilityTraits: (NOT Static Text Trait)

Note that the hint isn't crucial information. Hints are frequently ignored, and just contain useful clarifying information.
Aleternate markup (NOT RECOMMENDED)

ClassType: Subclass of ????
AccessibilityLabel: Text field, $EditingState, $EnteredText, $InsertionPoint
AccessibilityValue: nil
AccessibilityHint: nil
AccessibilityTraits: StaticText (Weird, but if you're including role information yourself, we want the trait of static text on an editable text field, to avoid VoiceOver being smart, including it, and duplicating role information in the announcement... is this starting to feel like a hack yet???)

This is honestly a terrible idea, you really should just have your TextField inherit from the system UITextField and get all of that stuff for free, but if you must, this is how you wold achieve... similar behavior without doing so. I say similar because there are a few things you CANNOT replicate in a custom control.

*

*keyboard type ("character mode") is more painful for you to grab than the system, and I recommend omitting in the custom case. The keyboard doesn't have to respect your requests for mode changes (custom keyboards and such), you can get into trouble and confuse users attempting to share this based on your application's settings. The system is the only thing that can get this right in all scenarios.

*Inflection. By doing this the custom way you will lose the style and inflection from VoiceOver. The pauses between the Label and the Entered Text. The lower voice that is read when the placeholder text is read out, etc. You can add commas to your AccessibilityLabel to somewhat replicate some of this, but ultimately, your custom control will always sound a little "off" to a VoiceOver user... unless your custom view extends UITextField...


text:
Q: How to download zip file from url in unity? I am using unity 2019.2.14f1 and visual studio 2019.I also tried with ICSharpCode.SharpZipLib but can't find any solution.I am trying with the code from the code which is available in the following url:
Unzip a memorystream (Contains the zip file) and get the files
  Thanks in advance.

A: You can download files in Unity using UnityWebRequest.Get. Note that using it like in the example shown on that page, you're going to want to make sure you know how to use Unity's Coroutines.
Also, instead of downloadHandler.text you're going to want to use downloadHandler.data to get the downloaded data as bytes you can put into a stream.
Once you've got those you can use the appropriate libraries or standard library calls to unzip your files.

A: To download a file from a URL you can use system.net
WebClient client = new WebClient();
client.DownloadFile("http://whateverlinkyouhave.zip", @"C:\whateverlinkyouhave.zip")

A: Everyone's answer is correct, especially using UnityWebRequest. One of things you must do is to turn the byte[] data to zip file. And then use some Unzip library.
Example implementation
using System;
using UnityEngine.Networking;

private IEnumerator DownloadZipFile(string url)
{
    using (UnityWebRequest www = UnityWebRequest.Get(url))
    {
        yield return www.Send();
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            string savePath =  string savePath = string.Format("{0}/{1}.zip", Application.persistentDataPath, "zip_file_name");
            System.IO.File.WriteAllBytes(savePath, www.downloadHandler.data);
        }
    }
}

Hope it helps.


text:
Q: Using XSLT 2.0 tags in Crystal Reports 2008 As part of a task at work I'm looking at exporting a simple list of details from a Crystal Report into separate xml files, one for each row.
The list is basic employee info i.e. First name, Surname etc.
Using Crystal Reports 2008 and quickly reading up on XSLT, I've managed to write a transformation that places each employee in it's own element with child-elements detailing its information.
However, i'm trying to use the xsl:result-document command, but Crystal Reports doesn't seem to like it. My XSLT file works fine in SAXON and splits the xml into separate files, but Crystal ignores everything inside the tag completely and just displays the header info.
Has anybody else had a similar problem?
I'm aware that the result-document tag was made available in XSLT 2.0, so would I be right in guessing the processor in Crystal Reports 2008 only works with XSLT 1.0? If so is there a way I can force it to work with XSLT 2.0?
Thanks for your time,
Ben
Below is my XSLT file:
<?xml version='1.0' ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:b="urn:crystal-reports:schemas:report-detail">

  <xsl:template match="/b:CrystalReport">
    <Report>
      <xsl:for-each select="b:Details">
        <xsl:variable name="empnumber" select="b:Section/b:Field[@Name='EmployeeNumber1']/b:Value"/>
        <xsl:result-document href="{$empnumber}.xml">
          <Employee>
            <xsl:attribute name="ID">
              <xsl:value-of select="b:Section/b:Field[@Name='EmployeeNumber1']/b:Value"/>
            </xsl:attribute>
            <FirstName>
              <xsl:value-of select="b:Section/b:Field[@Name='FirstName1']/b:Value"/>
            </FirstName>

            <Surname>
              <xsl:value-of select="b:Section/b:Field[@Name='Surname1']/b:Value"/>
            </Surname>

            <Test>
              <xsl:value-of select="$empnumber" />
            </Test>

          </Employee>
        </xsl:result-document>
      </xsl:for-each>
    </Report>
  </xsl:template>
</xsl:stylesheet>

A:
so would I be right in guessing the
  processor in Crystal Reports 2008 only
  works with XSLT 1.0? If so is there a
  way I can force it to work with XSLT
  2.0?

The short answer: no. However, some products allow to connect to a third party processor. I'm not aware of this option for Crystal Reports though. Also, result-document is a sufficiently complex instruction which is not easy to allow through extension functions.
Thinking about this more: aren't you simply using .NET to do the transformation? Out of the box, .NET only supports XSLT 1.0 (despite past promises otherwise). Because what you can do is to export the XML from Crystal Reports and transform that with an XSLT 2.0 processor. Saxon has been ported to .NET using IKVM.


text:
Q: SQL : Fetching new data by date from mysql without iterating in program I have a table called student with the structure below. the table represents student visitors to a library.

Id Name   Date          StudentId
1  John   2010-01-09      3
2  Matt   2010-01-10      5
3  Jane   2010-02-10      8
4  John   2010-02-10      3
5  Matt   2010-02-11      5
6  Jane   2010-02-11      8
7  Bob    2010-02-12      9
8  Tom    2010-02-12      10
9  Sam    2010-02-12      11
10 Jane   2010-02-12      8

I am running a query to fetch New visitors everyday. New visitors are visitors who have never visited the library before that date.The query I am using is as below.
SELECT count(*) FROM student
  WHERE DATE(Date) = :date
  AND Name NOT IN
     (SELECT DISTINCT Name FROM student WHERE DATE(Date) < :date);

I am currently iterating over each date in the table in my program and then using the query above to fetch me New visitors everyday. This works fine but was wondering if it is possible to fetch all values in a single query without iterating in the program? what is more optimal?
the output I am expecting is as below:

Date         Count of New Visitors
2010-01-09       1
2010-01-10       2
2010-01-11       0
2010-01-12       3

please note that the below query that I have tried will not fetch the correct result
SELECT Date, Count(*) FROM student
  WHERE DATE(Date) BETWEEN :startdate AND :enddate
  AND Name NOT IN
     (SELECT DISTINCT Name FROM student WHERE DATE(Date) < :startdate)  GROUP BY Date;

The result(which is incorrect and what I am not looking for ) I will get from the above query for startdate = 2010-01-09 and enddate = 2010-01-12 is below:

Date         Count of New Visitors
2010-01-09       1
2010-01-10       3
2010-01-11       2
2010-01-12       4

A: You have error in your test output. I think this is what you are looking for:
select u1.date,
(select count(*)
 from users u2
 where u2.date = u1.date
 and u2.studentid not in(select studentid from users u3 where u3.date < u2.date)) c
from users u1
group by u1.date


text:
Q: SQL Log shipping - Very Slow restore I have SQL Server 2012 SP4, ten databases and log shipping.
One database 2.7TB

*

*Ten data files and two log files

Log shipping configuration:

*

*Transaction log backup job : 3 Min

*Copy job : 1 Min

*Restore job : 1 Min

*Standby Mode, clicked Disconnect users...

A 50MB trn file take at 2 hours restored. The database is being 100% restored and remains. How do i solve this?

A: I added sql service account to Perform volume maintenance tasks and disk slowness problem appeared on the server. The storage team replaced the disks with faster disks. Problem is solved.


text:
Q: Lost ActiveWorksheet after 'for each worksheet' loop Routine using for each worksheet loop to unprotect all worksheets in workbook, change active worksheet at least instead to keep the actual one.
This behaviour recognized by Office2016 only, and routine start by command button. If you start by Makro, by Event or Immediate window it works fine and ActiveWorksheet keep as it is.
If you put debug stop mark into the routine it will work also fine started by command button.
This behaviour is recognized only by unprotect function. Protect function, print worksheet names or what ever works fine using for each worksheet loop.
It is important to keep ActiveWorksheet.
The function works fine for several years by Office2010.
The issue comes up by change to Office2016. And now we have one sheet the function is called by command button, not by event, and we recognized the issue first time.
To change the function is not so easy because it is used within a validated environment
For Each ws In ActiveWorkbook.Worksheets
    If ws.ProtectContents = True Then
        ws.Unprotect Password:=GetPassword()
    End If
Next ws

this code will keep ActiveWorksheet for example:
(called by command button)
For Each ws In ActiveWorkbook.Worksheets
    If ws.ProtectContents = False Then
        ws.Protect Password:=GetPassword()
    End If
Next ws

What do I have to do to keep ActiveWorksheet?
'code to reproduce the issue

'declaration zone
Public Const GLB_PW = "Password"

'Module 1
Sub Protection_On()  'called by command button
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
    If Not ws.ProtectContents Then
        'ws.Protect GLB_PW  '
        ws.Protect Password:=""
        End If
    Next ws
Debug.Print "Aktive Worksheet: " & ActiveSheet.Name
End Sub
Sub Protection_Off()  'called by command button
'code generating the issue
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
    If ws.ProtectContents Then
        'ws.Unprotect GLB_PW
        ws.Unprotect Password:=""
        End If
    Next ws
Debug.Print "Aktive Worksheet: " & ActiveSheet.Name
'ActiveSheet moved from Sheet1 to Sheet3
End Sub

A: Actually the code should not change the active worksheet at all. But what you can do is remember the ActiveSheet in a variable, run the code and then re-activate the sheet again.
Dim OriginalActiveSheet As Worksheet
Set OriginalActiveSheet = ActiveSheet

For Each ws In ActiveWorkbook.Worksheets
    If ws.ProtectContents = False Then
        ws.Protect Password:=GetPassword()
    End If
Next ws

OriginalActiveSheet.Activate


text:
Q: Good sites/blogs for FPGA development projects I'm looking for interesting online resources on FPGA development - sites, blogs, that sort of thing. What I'm after is examples of fun (and hopefully not too expensive) projects that one can try out and learn from.

A: have you tried fpga4fun.com or fpga-forum.com?
Also mikrocontroller.net (altough in german) has a linklist.

A: John Kent's site is a good starting point.

A: Try opencores.org - it hosts open source projects.

A: Great site with interesting projects and articles
http://www.fpga4fun.com/

A: I've compiled a list of FPGA Online Resources. Check link
fpga-blog.tumblr.com/links


text:
Q: Next.js cumulative layout shift issue with SSG site I have an CLS issue with this landing site. The landing site is statically generated in Next.js(SSG) as seen on this photo /.

I must be missing something regarding Next.js SSG. When I open the generated index.html file, not all HTML content is present. When page loads it looks like Next.js is injecting these missing sections on the page load... Shouldn't the entire HTML be statically generated and available in the index.html site? What am I missing or not understanding here?
Here is the data fetching for the page:
import Head from "next/head"
import {
  Box,
  Center,
  Container,
  Heading,
  Tag,
} from "@chakra-ui/react";
import { request } from "/lib/datocms";
import {
  MAIN_MENU_QUERY,
  BLOG_POSTS_QUERY,
  BLOG_CATEGORIES_QUERY,
  HOME_PAGE_QUERY,
} from "/lib/queries";
import BlockRender from "/components/blocks/BlockRender";
import ChakraNextLink from "/components/atoms/ChakraNextLink";
import BlogGrid from "/components/blog/BlogGrid"
import { renderMetaTags } from "react-datocms";

...

export const getStaticProps = async ({ preview }) => {
  const graphqlRequest = {
    query: MAIN_MENU_QUERY,
    preview
  }
  const data = await request(graphqlRequest);

  const homePageGraphqlRequest = {
    query: HOME_PAGE_QUERY,
    preview
  }
  const homePage = await request(homePageGraphqlRequest);
  const pageData = homePage?.homePage;

  const blogPostsGraphqlRequest = {
    query: BLOG_POSTS_QUERY,
    preview,
    variables: {
      count: homePage.homePage.blogPostCount ?? 0
    }
  }
  const blogPosts = await request(blogPostsGraphqlRequest);

  const blogCategoriesGraphqlRequest = {
    query: BLOG_CATEGORIES_QUERY,
    preview
  }
  const blogCategories = await request(blogCategoriesGraphqlRequest);

  return {
    props: {
      data,
      pageData,
      blogPosts,
      blogCategories
    },
  };
};

Here is the code of my index page:
export default function Home({ data, pageData, blogPosts, blogCategories }) {
  const metaTags = pageData.seo.concat(data.site.favicon);

  return (
    <>
      <Head>
        {renderMetaTags(metaTags)}
      </Head>

      # all this content is not in the generated Index.html file and causes CLS issue
      {pageData.content &&
        pageData.content.map((block, key) => <BlockRender key={key} block={block} />)
      }

      # this is in the generated index.html file
      <Box w="full" py="12">
        {pageData.showBlogSection && (
          <BlogSection posts={blogPosts} categories={blogCategories}>
        )}
      </Box>
    </>
  )
}

A: The problem was in the  component that dynamically loads components for data from my backend headless CMS. I changed this:
import dynamic from "next/dynamic";

export default function BlockRender({block}) {
  switch(block.__typename) {
    case "ContactSectionRecord":
      const ContactSection = dynamic(() => import("../page/ContactSection"));
      return <ContactSection block={block} />;
    case "StructuredTextSectionRecord":
      const StructuredTextSection = dynamic(() => import("../page/StructuredTextSection"));
      return <StructuredTextSection block={block} />;
    case "VirtualShowroomSectionRecord":
      const VirtualShowroomSection = dynamic(() => import("../page/VirtualShowroomSection"));
      return <VirtualShowroomSection block={block} />;
    case "HeroSectionOneRecord":
      const HeroOneSection = dynamic(() => import("../page/HeroOneSection"));
      return <HeroOneSection block={block} />;
    case "HeroSectionTwoRecord":
      const HeroTwoSection = dynamic(() => import("../page/HeroTwoSection"));
      return <HeroTwoSection block={block} />;
    case "PanogaSectionRecord":
      const PanogaSection = dynamic(() => import("../page/PanogaSection"));
      return <PanogaSection block={block} />;
    case "VirtualShowroomLandingSectionRecord":
      const VirtualShowroomLandingSection = dynamic(() => import("../page/VirtualShowroomLandingSection"));
      return <VirtualShowroomLandingSection block={block} />;
    case "AktualnaPonudbaSectionRecord":
      const AktualnaPonudbaSection = dynamic(() => import("../page/AktualnaPonudbaSection"));
      return <AktualnaPonudbaSection block={block} />;
    case "ParalaxSectionRecord":
      const ParalaxSection = dynamic(() => import("../page/ParalaxSection"));
      return <ParalaxSection block={block} />;
    case "ColumnBlockRecord":
      const ColumnBlockSection = dynamic(() => import("../page/ColumnBlockSection"));
      return <ColumnBlockSection block={block} />;
    default:
      return <></>
  }
}

into this:
import dynamic from "next/dynamic";

const ContactSection = dynamic(() => import("../page/ContactSection"));
const StructuredTextSection = dynamic(() => import("../page/StructuredTextSection"));
const VirtualShowroomSection = dynamic(() => import("../page/VirtualShowroomSection"));
const HeroOneSection = dynamic(() => import("../page/HeroOneSection"));
const HeroTwoSection = dynamic(() => import("../page/HeroTwoSection"));
const PanogaSection = dynamic(() => import("../page/PanogaSection"));
const VirtualShowroomLandingSection = dynamic(() => import("../page/VirtualShowroomLandingSection"));
const AktualnaPonudbaSection = dynamic(() => import("../page/AktualnaPonudbaSection"));
const ParalaxSection = dynamic(() => import("../page/ParalaxSection"));
const ColumnBlockSection = dynamic(() => import("../page/ColumnBlockSection"));

export default function BlockRender({block}) {
  switch(block.__typename) {
    case "ContactSectionRecord":
      return <ContactSection block={block} />;
    case "StructuredTextSectionRecord":
      return <StructuredTextSection block={block} />;
    case "VirtualShowroomSectionRecord":
      return <VirtualShowroomSection block={block} />;
    case "HeroSectionOneRecord":
      return <HeroOneSection block={block} />;
    case "HeroSectionTwoRecord":
      return <HeroTwoSection block={block} />;
    case "PanogaSectionRecord":
      return <PanogaSection block={block} />;
    case "VirtualShowroomLandingSectionRecord":
      return <VirtualShowroomLandingSection block={block} />;
    case "AktualnaPonudbaSectionRecord":
      return <AktualnaPonudbaSection block={block} />;
    case "ParalaxSectionRecord":
      return <ParalaxSection block={block} />;
    case "ColumnBlockRecord":
      return <ColumnBlockSection block={block} />;
    default:
      return <></>
  }
}

The CLS droped from 0.85 to 0.1.
I hope this answers helps someone with similar issue.


text:
Q: Killing a process created with Python's subprocess.Popen() Here is my thought:
First of all, I created a process by using subprocess.Popen
Second, after certain amount of time, I tried to kill it by Popen.kill()
import subprocess
import os, signal
import time

proc1 = subprocess.Popen("kvm -hda /path/xp.img", shell = True)
time.sleep(2.0)
print 'proc1 = ', proc1.pid
subprocess.Popen.kill(proc1)

However, "proc1" still exists after Popen.kill().
Could any experts tell me how to solve this issue?
I appreciate your considerations.
Thanks to the comments from all experts, I did all you recommended, but result still remains the same.
proc1.kill() #it sill cannot kill the proc1
os.kill(proc1.pid, signal.SIGKILL) # either cannot kill the proc1

Thank you all the same.
And I am still waiting for your precious experience on solving this delicate issue.

A: In your code it should be
proc1.kill()

Both kill or terminate are methods of the Popen object. On macOS and Linux, kill sends the signal signal.SIGKILL to the process and terminate sends signal.SIGTERM. On Windows they both call Windows' TerminateProcess() function.

A: process.terminate() doesn't work when using shell=True. This answer will help you.

A: Only use Popen kill method
process = subprocess.Popen(
    task.getExecutable(),
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True
)
process.kill()

A: How about using os.kill?  See the docs here: http://docs.python.org/library/os.html#os.kill


text:
Q: Extract only alphabetic characters from VARCHAR column I have a column of type VARCHAR2 which has text like '12-MAR-2014,,1234,DATA,VALUE,12/03/14,,124,End'. And I need the output to be, '%DATA%VALUE%End%'. i.e. the text to be delimited by comma ','. Only alphabets need to be selected leaving out the date or numeric or special characters. Something like,
select some_function('12-MAR-2014,,1234,DATA,VALUE,12/03/14,,124,End') as output from dual;

OUTPUT
---------
%DATA%VALUE%End%

EDIT:
Another added requirement where alphanumeric values need to be retained:
select some_function('12-MAR-2014,,1234,DATA65,VALUE,12/03/14,,124,End') as output from dual;

OUTPUT
---------
%DATA65%VALUE%End%

A: You can use regexp_replace().  I think the expression is something like this:
select regexp_replace(col, '([^a-zA-Z]+)', '%')

Unfortunately, I cannot test this right now (and SQL Fiddle is down).

A: Something like this may help you:
select regexp_replace('12-MAR-2014,,1234,DATA,VALUE,12/03/14,,124,End','[[0-9]{2}-(JAN|FEB|MAR|APR|JUN|JUL|AUG|SEP|OCT|NOV|DEC)-[0-9]{4}]*|[^a-zA-Z]+|$','%') from dual


text:
Q: Good tolerance for double comparison I am trying to come up with a good tolerance when comparing doubles in unit tests.
If I allow a fixed tolerance as I've seen mentioned on this site (eg return abs(actual-expected) < 0.00001;), this will frequently fail when numbers are very big due to the nature of floating point representation.
If I use a relative tolerance in terms of % error allowed (eg return abs(actual-expected) < abs(actual * 0.001); this fails too often for small numbers (and for very small numbers, the computation itself can introduce rounding error).  Additionally, it allows too much tolerance in certain ranges (eg comparing 2000 and 2001 would pass).
I'm wondering if there's any standard algorithm for allowing tolerance that will work for both small and large numbers.  Should I try for some kind of base 2 logarithmic tolerance to mirror floating point storage?  Should I do a hybrid approach based on the size of the inputs?
Since this is in unit test code, performance is not a big factor.

A: The specification of tolerance is a business function.  There aren't standards that say "all tolerance must be within +/- .001%".  So you have to go to your requirements and figure out what's going to work for you.
Look at your application.  Let's say it's for some kind of cutting machine.  Are they metal machining tolerances?  .005 inches is common.  Are they wood cabinet sawing tolerances?  1/32" is sloppy, 1/64" is better.  Are they house framing tolerances?  Don't expect a carpenter to come closer than 1/4".  Hand cutting with a welding torch?  Hope for about an inch.  The point is simply that every application depends on something different, even when they're doing equivalent things.
If you're just talking "doubles" in general, they're usually good to no better than 15 digits of precision.  Floats are good to 7 digits.  I round those down by one when I'm thinking about the problem (I don't rely on a double being accurate to more than 14 digits and I stop with floats at six digits); however, if I'm worried about more than the 12th digit of precision I'm generally working with large dollar amounts that have to balance precisely, and I'd be a fool to use non-integer math for them.  Business people want their stuff to balance to the penny, and wouldn't approve of rounding off addition operations!
If you're looking at math library operations such as the trig functions, read the library's documentation on each function.


text:
Q: How to play ogg file with NSpeex? I'm working on a c# project with particular needs of playing ogg file with NSpeex Library.
How to make NSpeex to read ogg file from file path? and how to make it play and seek?
I think NAudio is needed, but I still can't figure out how...
Forgive me, I'm new to audio development, I hope someone could show me some code samples here.


text:
Q: How can I predict customer lifetime value in 12 months? I was trying to predict 'customer lifetime value' but only for the first 12 months of him/her in the platform I work for. However, most models, such as Pareto/NBD, are good in order to assess the real lifetime value, not only for this short period.
First, I thought about using lifetimes package in Python, but only filtering the twelve first payments of each customer. But when I try to use the predict function, I can't make this sort of control (limit to 12 months after the subscription).
Is there any way of doing this? Any package in which this is possible?


text:
Q: Converting ordered dictionaries with different values I have an ordered dictionary of ordered dictionaries, now if the value of the key if its a list I need to create a list of dictionaries with using all the values inside the list like this,
dee= OrderedDict([('b', [1,9]), ('a', ['{}','{}'])])
eee=[OrderedDict([('b', 1),('a',{})]),OrderedDict([('b', 9),('a',{})])]

Now how do i recursively go inside the dictionary like ab and create a list with dictionaries with same keys and different values.
ab=OrderedDict([('part', ['8888822701B', '8889012006B', '8889012013B', '8889012014B', '8889012016C', '8889012019B', '8889012020C', '8889012021D', '8889012022B']), ('file', ['0', '1', '2', '3', '4', '5', '6', '7', '8']), ('estimatedtime', ['100', ' 100', ' 100', ' 100', ' 100', ' 100', ' 100', ' 100', ' 100']), ('signature', ['{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}']), ('otherpartsignature', ['{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}'])])

A: You can iterate over all keys and create new Ordered dicts on the first key processed, the later keys add to the earlier created dicts.
For each key you iterate over all values and put them into single Ordered dicts that you add to a list (this works as long as your input value-lists all have the same amount of data):
from collections import OrderedDict

ab = OrderedDict([
    ('part', ['8888822701B', '8889012006B', '8889012013B', '8889012014B', '8889012016C',
              '8889012019B', '8889012020C', '8889012021D', '8889012022B']),
    ('file', ['0', '1', '2', '3', '4', '5', '6', '7', '8']),
    ('estimatedtime', ['100', ' 100', ' 100', ' 100', ' 100', ' 100', ' 100', ' 100', ' 100']),
    ('signature', ['{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}']),
    ('otherpartsignature', ['{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}'])])

listOfDicts = []
for key,values in ab.items():
    if not dicts: # create all new OrderedDicts when processing the values of first key
        for v in values:
            listOfDicts.append(OrderedDict({key:v}))
    else:
        for idx,v in enumerate(values): # use the earlier created Ordered dicts and add to them
            d = listOfDicts[idx]
            d[key]=v

print(listOfDicts)

Output:
[OrderedDict([('part', '8888822701B'), ('file', '0'), ('estimatedtime', '100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
 OrderedDict([('part', '8889012006B'), ('file', '1'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
 OrderedDict([('part', '8889012013B'), ('file', '2'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
 OrderedDict([('part', '8889012014B'), ('file', '3'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
 OrderedDict([('part', '8889012016C'), ('file', '4'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
 OrderedDict([('part', '8889012019B'), ('file', '5'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
 OrderedDict([('part', '8889012020C'), ('file', '6'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
 OrderedDict([('part', '8889012021D'), ('file', '7'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
 OrderedDict([('part', '8889012022B'), ('file', '8'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')])]


text:
Q: jQueryUI Sortable + Draggable and fixed position with overflow auto - can't drag items into sortable I'm trying to design page where are two panels and one center content.
Like this:

...

...

...

jQuery('#left li').draggable({
    connectToSortable: ".EditingFormCategoryFields",
    helper: "clone",
});
jQuery('#center').sortable();

Left panel is source of items. Center panel is target for items.
There is problem with overflow. I need overflow: auto, because it could contain long content.
If you try this http://jsfiddle.net/NfQuk/3/ you will see that you couldn't drag items from left panel to center.

A: The problem is not the overflow, but the fact that the draggable items are taking the 'left' div as container and thus cannot be dragged outside of it. Try setting the containment property to your section element.


text:
Q: R summing up total for each class for each id Say I have a dataset like this:
df <- data.frame(id = c(1, 1, 1, 2, 2),
      classname = c("Welding", "Welding", "Auto", "HVAC", "Plumbing"),
      hours = c(3, 2, 4, 1, 2))

I.e.,
   id  classname  hours
1   1   Welding     3
2   1   Welding     2
3   1   Auto        4
4   2   HVAC        1
5   2   Plumbing    2

I'm trying to figure out how to summarize the data in a way that gives me, for each id, a list of the classes they took as well as how many hours of each class. I would want these to be in a list so I can keep it one row per id. So, I would want it to return:
   id     class.list     class.hours
1   1    Welding, Auto       5,4
2   2    HVAC, Plumbing      1,2

I was able to figure out how to get it to return the class.list.
library(dplyr)
classes <- df %>%
group_by(id) %>%
summarise(class.list = list(unique(as.character(classname))))

This gives me:
   id     class.list
1   1    Welding, Auto
2   2    HVAC, Plumbing

But I'm not sure how I could get it to sum the number of hours for each of those classes (class.hours).
Thanks for your help!

A: In base R, this can be accomplished with two calls to aggregate. The inner call sums the hours and the outer call "concatenates" the hours and the class names. In the outer call of aggregate, cbind is used to include both the hours and the class names in the output, and also to provide the desired variable names.
# convert class name to character variable
df$classname <- as.character(df$classname)
# aggregate
aggregate(cbind("class.hours"=hours, "class.list"=classname)~id,
          data=aggregate(hours~id+classname, data=df, FUN=sum), toString)
  id class.hours     class.list
1  1        4, 5  Auto, Welding
2  2        1, 2 HVAC, Plumbing

In data.table, roughly the same output is produced with a chained statement.
setDT(df)[, .(hours=sum(hours)), by=.(id, classname)][, lapply(.SD, toString), by=id]
   id      classname hours
1:  1  Welding, Auto  5, 4
2:  2 HVAC, Plumbing  1, 2

The variable names could then be set using the data.table setnames function.

A: This is how you could do it using dplyr:
classes <- df %>%
  group_by(id, classname) %>%
  summarise(hours = sum(hours)) %>%
  summarise(class.list = list(unique(as.character(classname))),
            class.hours = list(hours))

The first summarise peels of the latest group by (classname). It is not necessary to use unique() anymore, but I kept it in there to match the part you already had.


text:
Q: Angular 2 sorting with lodash Component:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as _ from 'lodash';

@Component({
  selector: 'app-ore-table',
  templateUrl: './ore-table.component.html',
  styleUrls: ['./ore-table.component.less']
})
export class OreTableComponent implements OnInit {
  ores = '../assets/json/ores.json';
  prices = 'https://esi.tech.ccp.is/latest/markets/prices/?datasource=tranquility';

  oreArray: any;
  pricesArray: any;
  joinedArray: Array<any> = [];
  completeArray: Array<any> = [];

  seconds: number;
  turrets: any;
  turretYield: any;
  duration: any;

  constructor(private http: HttpClient) {
    this.seconds = 3600;
    this.turrets = 2;
    this.turretYield = 1593;
    this.duration = 106.9;
  }

  getOres() {
    this.http.get(this.ores).subscribe(data => {
      this.oreArray = data;
      this.getPrices();
    });
  }

  getPrices() {
    this.http.get(this.prices).subscribe(data => {
      this.pricesArray = data;
      this.joinPrices();
    });
  }

  joinPrices() {
    const cycles = this.seconds / this.duration;
    const totalYield = this.turretYield * this.turrets;

    this.oreArray.forEach((data) => {
      const matchingPrice = this.getMatchingPrice(data);

      const oreMined = totalYield * (1 / data.volume) * cycles;
      const hourIncome = matchingPrice.average_price.toFixed(2) * oreMined;
      const hourIncomeFormat = Number(hourIncome).toFixed();
      const isk = String(hourIncomeFormat).replace(/(.)(?=(\d{3})+$)/g, '$1,');

      if (matchingPrice !== false) {
          this.joinedArray.push({
              id: data.id,
              name: data.name,
              type: data.type,
              volume: data.volume.toFixed(2),
              average_price: matchingPrice.average_price.toFixed(2),
              max_income: isk,
              image: data.image
          });
      }
    });
    console.log(this.joinedArray);
    this.completeArray = _.sortBy(this.joinedArray, ['max_income']).reverse();
  }

  updatePrices(newTurrets, newTurretYield, newDuration) {
    console.log(newTurrets);
    this.joinedArray = [];

    const cycles = this.seconds / newDuration;
    const totalYield = newTurretYield * newTurrets;

    this.oreArray.forEach((data) => {
      const matchingPrice = this.getMatchingPrice(data);

      const oreMined = totalYield * (1 / data.volume) * cycles;
      const hourIncome = matchingPrice.average_price.toFixed(2) * oreMined;
      const hourIncomeFormat = Number(hourIncome).toFixed();
      const isk = String(hourIncomeFormat).replace(/(.)(?=(\d{3})+$)/g, '$1,');

      if (matchingPrice !== false) {
          this.joinedArray.push({
              id: data.id,
              name: data.name,
              type: data.type,
              volume: data.volume.toFixed(2),
              average_price: matchingPrice.average_price.toFixed(2),
              max_income: isk,
              image: data.image
          });
      }
    });
  }

  getMatchingPrice(data) {
    for (let i = 0; i < this.pricesArray.length; i++) {
      if (this.pricesArray[i].type_id === data.id) {
            return this.pricesArray[i];
        }
    }
    return false;
  }

  ngOnInit() {
    this.getOres();
  }
}

HTML:

        {{ ore.name }}
        {{ ore.volume }} m³
        {{ ore.average_price }} ISK
        {{ ore.max_income }}

Screenshot:

I'm using lodash to sort my array by the 'max_income' field and then applying .reverse() to sort it in descending order:
this.completeArray = _.sortBy(this.joinedArray, ['max_income']).reverse();

As seen in the screenshot above, it works perfectly other than the first row.  Because it starts with an 8, it's appearing first and this is completely wrong.  What adjustment can I make to force the numbers to sort properly?  Here as what an object looks like:
{
    "id": 17870,
    "name": "Vitreous Mercoxit",
    "type": "Mercoxit",
    "volume": "40.00",
    "average_price": "19000.04",
    "max_income": "50,964,186",
    "image": "../assets/images/Mercoxit.png"
  }

A: I suspect the problem is it is compared as a string.
Try this:
    this.completeArray = _.sortBy(this.joinedArray,
                  (item) => {
                     return +item.max_income;
                  }).reverse();

or:
this.completeArray = _.sortBy(this.joinedArray,
                      (item) => {
                         return +(item.max_income.replace(',', ''));
                      }).reverse();

A: There's no need to use loadash here. It's better to write your own comparison function and use the native Array.sort() function.

var numberCompare = (a, b) => a - b;

var arr = ['1', '20', '31', '400,000', '5', '600', '70'];
var res = arr.map(x => +x.replace(',', '')).sort(numberCompare);

console.log(res);

If you want a reverse sort, do b - a in the above function.

A: The max_income is a string that can contain comma separators. Change the function that is passed to sortBy to convert the string to a number:
_.sortBy(this.joinedArray, item => +item.max_income.replace(',', ''))