问:
Where is my mistake - Date calculator for selectbox in Javascript/jQuery?
```<code>$(.dateselboxes) .change( function(){

var y; y=$("#year").val();
var m; m=$("#month").val();
var d;
</code>```

// check leap year

```<code>var leapYear;
if(y%4==0)
{
    if(y%100==0)
    {
        if(y%400==0) {leapYear=true;}
        else {leapYear=false;}
    }
    else {leapYear=true;}
}
else {leapYear=false;}
</code>```

// calculate the number of days

```<code>var dz;
if(m==1 || m=3 || m=5 || m=7 || m=8 || m=10 || m=12) {dz=31;}
else if(m==2)
    {
        if(leapYear==true) {dz=29;}
        else {dz=28;}
    }
else {dz=30;}
</code>```

// remove last option a couple of times

```<code>switch(dz)
    {
        case 28:
            for(i=0;i<3;i++)
            {$("#day option:last").remove();}
            break;
        case 29:
            for(i=0;i<2;i++)
            {$("#day option:last").remove();}
            break;
        case 30:
            $("#day option:last").remove();
            break;
        default:
            var axaxax=0;
            break;
    }
</code>```

});

答:
Here you go, this code works (in Chrome, at least):

```<code>var opts = $('#day option').get();

$('#month, #year').change(function() {
    var y = +$('#year').val(),
        m = +$('#month').val(),
        leap = y % 400 === 0 || y % 100 !== 0 && y % 4 === 0 ? true : false,
        days = 30;

    switch ( m ) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            days = 31; break;
        case 2:
            days = leap ? 29 : 28; break;
    }

    $('#day').empty().append( opts.slice(0, days) );

});
</code>```

Live demo: http://jsfiddle.net/83yUF/

Body:
$(.dateselboxes) .change( function(){

var y; y=$("#year").val();
var m; m=$("#month").val();
var d;

// check leap year

var leapYear;
if(y%4==0)
{
    if(y%100==0)
    {
        if(y%400==0) {leapYear=true;}
        else {leapYear=false;}
    }
    else {leapYear=true;}
}
else {leapYear=false;}

// calculate the number of days

var dz;
if(m==1 || m=3 || m=5 || m=7 || m=8 || m=10 || m=12) {dz=31;}
else if(m==2)
    {
        if(leapYear==true) {dz=29;}
        else {dz=28;}
    }
else {dz=30;}

// remove last option a couple of times

switch(dz)
    {
        case 28:
            for(i=0;i<3;i++)
            {$("#day option:last").remove();}
            break;
        case 29:
            for(i=0;i<2;i++)
            {$("#day option:last").remove();}
            break;
        case 30:
            $("#day option:last").remove();
            break;
        default:
            var axaxax=0;
            break;
    }

});

Body:
Here you go, this code works (in Chrome, at least):

var opts = $('#day option').get();

$('#month, #year').change(function() {
    var y = +$('#year').val(),
        m = +$('#month').val(),
        leap = y % 400 === 0 || y % 100 !== 0 && y % 4 === 0 ? true : false,
        days = 30;

    switch ( m ) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            days = 31; break;
        case 2:
            days = leap ? 29 : 28; break;
    }

    $('#day').empty().append( opts.slice(0, days) );

});

Live demo: http://jsfiddle.net/83yUF/


来源: stackexchange

问:
Why does IE 11 use Windows-1252 instead of UTF-8 when it's decoding?
I set <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> in the head.

But when IE 11 sends API request, it will perform Windows-1252 instead of UTF-8.

For example, if the URL contains ü, it should be %C3%BC in UTF-8, but IE 11 will break it into %C3 and %BC, and sends as Ã¼ according to Windows-1252.

So is there any way to solve this issue?

I tested in IE 11. This issue doesn't exist on Edge.

答:
Take a look to IE encoding settings, probably it’s set not to automatic (should use encoding defined by meta tag), but set to windows-1252

Please take a look here for additional details and causes:
https://support.microsoft.com/en-us/help/928847/internet-explorer-uses-the-wrong-character-set-when-it-renders-an-html

ContentLicense: CC BY-SA 3.0


问:
Python read numbers in text file to list to calculate mean
I have a file with a lot of numbers and I want to try to read it in python into a list of a list. Then calculate its mean or sum or whatever.

Here is my text file:

```<code>   1,2,5349,2398,19,3450
   10,95,201,5943,234,2319482,12
</code>```

then here is my code:

```<code>def ReadList(fileName):
    with open(fileName, 'r') as numbers:
        datalist = []
        for line in numbers:
            datalist.append(line.strip().split(' '))
    return datalist
</code>```

but my results turn up as datalist = ['1,2,5349....3450'],['10,95...,12'] they have the apostraphe at the beinning and the end, and I can't calculate the mean with it. I have tried to use:
                     datalist.appent(int(line.strip().split(' ')))already and it doesn't make the data into numbers but adds some other errors.

EDIT: The data seem okay now that I changed it to datalist.append([int(x) for x in line.strip().split(',')]).

But I can't calculate the mean when my method is

```<code>numbers = ReadList('data.txt')

total = 0.0
for num in numbers:
     total = total + num
return total/len(nums)
</code>```

the same errors still appear:"TypeError: unsupported operand type(s) for +: 'float' and 'list'"

My goal is to have it as a few separate list of a list and calculate each separate list's means and then display it in a column for example:

```<code>List# Mean
1     (Mean value of the first list( 1,2,5349,2398,19,3450))
2     (Mean value of the second list(10,95,201,5943,234,2319482,12))
</code>```

答:
You have to do two operations here, first one you have to split the list with ',' and after that you have to transform the string to int.

you can do that using:

```<code>datalist.append([ int(x) for x in line.strip().split(',') ])
</code>```

this code will split the string, transform the string to int, and after that append to the datalist variable.

EDIT:
you have update your question, so here is the rest of my answer:
There are two errors in the block that you calculate the mean, the first one is that you are iterating in a list of lists, so you have to go through both of the itens, the second is that you are using the wrong value. You are calculating the len of num, you should get the len of numbers. this is what will be your final code:

```<code>numbers = ReadList('data.txt')
    means = []
    for line in numbers:
         total = 0.0
         for num in line:
              total = total + num
          means.append(total/len(numbers))
    return means
</code>```

Body:
I have a file with a lot of numbers and I want to try to read it in python into a list of a list. Then calculate its mean or sum or whatever.

Here is my text file:

   1,2,5349,2398,19,3450
   10,95,201,5943,234,2319482,12

then here is my code:

def ReadList(fileName):
    with open(fileName, 'r') as numbers:
        datalist = []
        for line in numbers:
            datalist.append(line.strip().split(' '))
    return datalist

but my results turn up as datalist = ['1,2,5349....3450'],['10,95...,12'] they have the apostraphe at the beinning and the end, and I can't calculate the mean with it. I have tried to use:
                     datalist.appent(int(line.strip().split(' ')))already and it doesn't make the data into numbers but adds some other errors.

EDIT: The data seem okay now that I changed it to datalist.append([int(x) for x in line.strip().split(',')]).

But I can't calculate the mean when my method is

numbers = ReadList('data.txt')

total = 0.0
for num in numbers:
     total = total + num
return total/len(nums)

the same errors still appear:"TypeError: unsupported operand type(s) for +: 'float' and 'list'"

My goal is to have it as a few separate list of a list and calculate each separate list's means and then display it in a column for example:

List# Mean
1     (Mean value of the first list( 1,2,5349,2398,19,3450))
2     (Mean value of the second list(10,95,201,5943,234,2319482,12))

Body:
You have to do two operations here, first one you have to split the list with ',' and after that you have to transform the string to int.

you can do that using:

datalist.append([ int(x) for x in line.strip().split(',') ])

this code will split the string, transform the string to int, and after that append to the datalist variable.

EDIT:
you have update your question, so here is the rest of my answer:
There are two errors in the block that you calculate the mean, the first one is that you are iterating in a list of lists, so you have to go through both of the itens, the second is that you are using the wrong value. You are calculating the len of num, you should get the len of numbers. this is what will be your final code:

numbers = ReadList('data.txt')
    means = []
    for line in numbers:
         total = 0.0
         for num in line:
              total = total + num
          means.append(total/len(numbers))
    return means


问:
How to change font size of species labels in vegan's biplot() function
I am trying to create a series of publishable biplots of a PCA on insect abundance in different strata (tree canopy and understory) of forests. I am doing this using the rda() function. To create the plot, I am using vegan's biplot() function and do a couple of modifications to it:

```<code>Family=read.table("Family2.txt", header=T)
strata=read.table("Strata.txt", header=T)

family.pca=rda(Family)

with(strata, levels(Strata))

biplot(family.pca, type=c("text", "none"), col=c("black", "black"), xlab="",
ylab="")
title(xlab="PC1 (86.8%)", ylab="PC2 (9.7%)", mgp=c(2.2, 2.2, 0))
points=c(16, 1)
colour=c("black", "black")
with(strata, points(family.pca, display = "sites", col = colour, pch =
points))
with(strata, legend("topright", legend = levels(Strata), bty = "n", col =
colour, pch = points, pt.bg = points))
</code>```

The result is quite nice:

But because I will join several biplots to a bigger graph, the labels for the families (usually called 'species labels') are too small. I tried to change them using cex=1.5 in biplot(), but it seems to get overwritten by the defaults of the function. When I create an empty biplot frame by setting type=c("none", "none"), I can add bigger species labels using the text() function, e.g.

```<code>text(family.pca, display = "species", cex = 1.0, col = "black")
</code>```

but then I don't know how to add the arrows to the plot (I would really like to have the arrows in there...).

Does anybody know of a solution for this case? Answers are greatly appreciated.

答: I recommend going to ?biplot   you should see an explanation for the argument cex in the documentation. That should help you as it related to the labels of the plot and the size of these labels.

Body:
I am trying to create a series of publishable biplots of a PCA on insect abundance in different strata (tree canopy and understory) of forests. I am doing this using the rda() function. To create the plot, I am using vegan's biplot() function and do a couple of modifications to it:

Family=read.table("Family2.txt", header=T)
strata=read.table("Strata.txt", header=T)

family.pca=rda(Family)

with(strata, levels(Strata))

biplot(family.pca, type=c("text", "none"), col=c("black", "black"), xlab="",
ylab="")
title(xlab="PC1 (86.8%)", ylab="PC2 (9.7%)", mgp=c(2.2, 2.2, 0))
points=c(16, 1)
colour=c("black", "black")
with(strata, points(family.pca, display = "sites", col = colour, pch =
points))
with(strata, legend("topright", legend = levels(Strata), bty = "n", col =
colour, pch = points, pt.bg = points))

The result is quite nice:

But because I will join several biplots to a bigger graph, the labels for the families (usually called 'species labels') are too small. I tried to change them using cex=1.5 in biplot(), but it seems to get overwritten by the defaults of the function. When I create an empty biplot frame by setting type=c("none", "none"), I can add bigger species labels using the text() function, e.g.

text(family.pca, display = "species", cex = 1.0, col = "black")

but then I don't know how to add the arrows to the plot (I would really like to have the arrows in there...).

Does anybody know of a solution for this case? Answers are greatly appreciated.


问:
How can I change the position of an object through the ccp function in cocos2d?
I am new to the cocos2d framework, so I took the sample application from this location and tried to modify it.  By using the line

```<code>target.position = ccp(winSize.width , (target.contentSize.width/2)+actualY);
</code>```

the object is shown in landscape.  When the app runs it will show me the output in landscape mode, and the targets are shown from the starting the landscape mode of one side to another side.  I want to show it from the the end of the landscape mode to the start.  How can I do this?

Also, I want to show in portrait mode. How can I do this as well?

答: What version of cocos2d u using? You can change orientation of app in the app delegate.. From landscape to portrait..</p>

ContentLicense: CC BY-SA 2.5

Body:
I am new to the cocos2d framework, so I took the sample application from this location and tried to modify it.  By using the line

target.position = ccp(winSize.width , (target.contentSize.width/2)+actualY);

the object is shown in landscape.  When the app runs it will show me the output in landscape mode, and the targets are shown from the starting the landscape mode of one side to another side.  I want to show it from the the end of the landscape mode to the start.  How can I do this?

Also, I want to show in portrait mode. How can I do this as well?


问:
Visual Studio syntax highlighting / autocomplete not working correctly
My Visual Studio does not highlight or autocomplete any Unity3D commands any more. I created a new script when noticing that. I restarted VS, reinstalled VS, also reverted all script changes I made today in my project but the result is still the same. Also I now get errors when trying to open my project file. It says it needs a migration and isn't compatible with the current Visual Studio version installed.

The actual error reads "The application that is based on this project type was not found." [translated from German].

I found similar posts on the web where reinstalling VS resolved the issue. Unfortunately, it did not for me. This is how it looks:

Anybody knows how I can fix this?

答:
Ok, I was able to resolve this issue using this trick:

"Do me a favor... if this is Visual Studio 2017... hit your start menu and find Visual Studio Installer... Run it... select "Modify" and select individual components... find Visual Studio Tools for Unity... if it's installed, untick it and uninstall it, then run the installer again and reinstall it. Otherwise, just tick it and install it."


问:
How to make a dynamic gradient effect in a dynamically generated view?
I have to make a gradient color effect in the view that generated dynamically according to the scenario and also the view would be of any shape (diagonal or square)

As shown in image, gradient effect could be in any shape.
Also, if I create custom view for every possible case and play with Visibility, then how I will manage these views to fit perfectly on every device screen size?
Just need a small help to start.
Thanks in advance.

答:
I have solved the issue using this approach.

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new CustomView(this));
}
</code>```

}

and now create a CustomView class

```<code>public class CustomView extends View {
Rect rect;

private Rect rectangle;
private Paint paint;

public CustomView(Context context) {
    super(context);
    int x = 50;
    int y = 50;
    int sideLength = 200;
    int sideLength1 = 100;
    rectangle = new Rect(x, y, sideLength, sideLength1);
    paint = new Paint();
    paint.setColor(Color.GRAY);
}

 @Override
protected void onDraw(Canvas canvas) {

    int width = this.getMeasuredWidth();
    int height = this.getMeasuredHeight();

    BitmapShader shader;
    //shader = new BitmapShader(header, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

    //paint.setShader(shader);

    Path path = new Path();

    path.moveTo(40,40);
    path.lineTo(5,height/2);
    path.lineTo(width/2,height/4);
    path.lineTo(width/2,0);

    canvas.drawPath(path,paint);

}
</code>```

Body:
I have solved the issue using this approach.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new CustomView(this));
}

}

and now create a CustomView class

public class CustomView extends View {
Rect rect;

private Rect rectangle;
private Paint paint;

public CustomView(Context context) {
    super(context);
    int x = 50;
    int y = 50;
    int sideLength = 200;
    int sideLength1 = 100;
    rectangle = new Rect(x, y, sideLength, sideLength1);
    paint = new Paint();
    paint.setColor(Color.GRAY);
}

 @Override
protected void onDraw(Canvas canvas) {

    int width = this.getMeasuredWidth();
    int height = this.getMeasuredHeight();

    BitmapShader shader;
    //shader = new BitmapShader(header, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

    //paint.setShader(shader);

    Path path = new Path();

    path.moveTo(40,40);
    path.lineTo(5,height/2);
    path.lineTo(width/2,height/4);
    path.lineTo(width/2,0);

    canvas.drawPath(path,paint);

}


问:
Adding wav in exe
Is there any way to add music to exe(c++)file without additional wave file?

For example, If I use "PlaySound" to play wav file, the wave file should be located under same folder where the exe file be. But I want to run it without wav file so that when someone receives the exe file, they can listen to the music without receiving the wav file..

I want it as a code...

And here's my current code.

```<code>#include <iostream>
#include <stdio.h>
#include <windows.h>
using namespace std;

/* ========================================================================== */
enum {
    BLACK,
    DARK_BLUE,
    DARK_GREEN,
    DARK_SKY_BLUE,
    DARK_RED,
    DARK_VOILET,
    DARK_YELLOW,
    GRAY,
    DARK_GRAY,
    BLUE,
    GREEN,
    SKY_BLUE,
    RED,
    VIOLET,
    YELLOW,
    WHITE,
};

enum { HIDDEN, SHOW };

void CursorView(char show)
{
    HANDLE hConsole;
    CONSOLE_CURSOR_INFO ConsoleCursor;

    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    ConsoleCursor.bVisible = show;
    ConsoleCursor.dwSize = 1;

    SetConsoleCursorInfo(hConsole, &ConsoleCursor);
}

void gotoxy(int x, int y)
{
    COORD XY = { x, y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), XY);
}
void SetColor(int color)
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}

void gamedraw(void)
{
        PlaySound(TEXT("10.wav"), NULL, SND_FILENAME | SND_LOOP | SND_ASYNC);

        printf("You are listening to my song.");

  getchar();
}
void MainInit(void)
{
   system("mode con: cols=100 lines=45");
   system("cls");
}

/* ========================================================================== */

int main(void)
{
   CursorView(HIDDEN);
   MainInit();

   gamedraw();

   for (;;) {

      if (GetAsyncKeyState(VK_ESCAPE) < 0)  break;
   }

   CursorView(SHOW);

   return 0;
}
</code>```

答: You can add the .wav as a resource but then playing it becomes quite a lot more difficult (either you'll have to extract the resource to some path on disk or use one of the audio APIs to submit the wav data).</p>

Title: Adding wav in exe

Body:
Is there any way to add music to exe(c++)file without additional wave file?

For example, If I use "PlaySound" to play wav file, the wave file should be located under same folder where the exe file be. But I want to run it without wav file so that when someone receives the exe file, they can listen to the music without receiving the wav file..

I want it as a code...

And here's my current code.

#include <iostream>
#include <stdio.h>
#include <windows.h>
using namespace std;

/* ========================================================================== */
enum {
    BLACK,
    DARK_BLUE,
    DARK_GREEN,
    DARK_SKY_BLUE,
    DARK_RED,
    DARK_VOILET,
    DARK_YELLOW,
    GRAY,
    DARK_GRAY,
    BLUE,
    GREEN,
    SKY_BLUE,
    RED,
    VIOLET,
    YELLOW,
    WHITE,
};

enum { HIDDEN, SHOW };

void CursorView(char show)
{
    HANDLE hConsole;
    CONSOLE_CURSOR_INFO ConsoleCursor;

    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    ConsoleCursor.bVisible = show;
    ConsoleCursor.dwSize = 1;

    SetConsoleCursorInfo(hConsole, &ConsoleCursor);
}

void gotoxy(int x, int y)
{
    COORD XY = { x, y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), XY);
}
void SetColor(int color)
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}

void gamedraw(void)
{
        PlaySound(TEXT("10.wav"), NULL, SND_FILENAME | SND_LOOP | SND_ASYNC);

        printf("You are listening to my song.");

  getchar();
}
void MainInit(void)
{
   system("mode con: cols=100 lines=45");
   system("cls");
}

/* ========================================================================== */

int main(void)
{
   CursorView(HIDDEN);
   MainInit();

   gamedraw();

   for (;;) {

      if (GetAsyncKeyState(VK_ESCAPE) < 0)  break;
   }

   CursorView(SHOW);

   return 0;
}


问:
Java singltone exception Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
i have Server side i tried to make it Singeltone in order to accses server metodtds from another classes, but when i run server main and then i do Server.getInstance() from another class it throws this expection:

Exception in thread "main"
  java.net.BindException: Address already in use: JVM_Bind

i tried a lot of things but its not working

```<code> private static Server serverinstance = null;
        private static Object obj=new Object();

        public Server() throws IOException {
            server = new ServerSocket(222);
            hash = new HashMap<String, SocketData>();
        }

        public static Server getInstance() throws IOException {
            synchronized (obj) {
                if (serverinstance == null) {
                    serverinstance = new Server();
                    serverinstance.listenServer();
                }
                return serverinstance;
            }
        }

        private void listenServer() throws IOException {
            while (flag) {
                ans = server.accept();
                if (serverinstance != null)
                    new EchoThread(serverinstance, ans);
            }
        }

    public static void main(String args[]) throws IOException {
            Server.getInstance();
        }

    Class A()
    {
    public A()
    {
    Server.getInstance();
    }
    }
</code>```

答: Try restarting your computer. That is because another program is already using port 222, so your program is unable to listen on it. If that doesn't work, try switching 222 to something different, like maybe 8000 or 9999, basically any number from 1000-65535 (0-65535 if you are on Windows)</p>

Body:
i have Server side i tried to make it Singeltone in order to accses server metodtds from another classes, but when i run server main and then i do Server.getInstance() from another class it throws this expection:

Exception in thread "main"
  java.net.BindException: Address already in use: JVM_Bind

i tried a lot of things but its not working

 private static Server serverinstance = null;
        private static Object obj=new Object();

        public Server() throws IOException {
            server = new ServerSocket(222);
            hash = new HashMap<String, SocketData>();
        }

        public static Server getInstance() throws IOException {
            synchronized (obj) {
                if (serverinstance == null) {
                    serverinstance = new Server();
                    serverinstance.listenServer();
                }
                return serverinstance;
            }
        }

        private void listenServer() throws IOException {
            while (flag) {
                ans = server.accept();
                if (serverinstance != null)
                    new EchoThread(serverinstance, ans);
            }
        }

    public static void main(String args[]) throws IOException {
            Server.getInstance();
        }

    Class A()
    {
    public A()
    {
    Server.getInstance();
    }
    }


问:
makefile not updating .o file with respectively with .h file
I have following make file :-

```<code>VER = Debug
CC = gcc
objectfiles = Getstr.o ui.o ustreqsol.o main.o
pkg = `pkg-config --cflags --libs gtk+-3.0`

obj = $(addprefix objs/,$(objectfiles))

../$(VER)/Calculator: $(obj)
    $(CC) -o $@ $(obj) $(pkg)

./objs/ui.o:ui.c
    $(CC) -c -o $@ $< $(pkg)

./objs/main.o:main.c
    $(CC) -c -o $@ $< $(pkg)

./objs/%.o: %.c %.h
    $(CC) -c -o $@ $<

clean:
    -rm ../$(VER)/Calculator
    -rm /objs/*
</code>```

and follwing files in my src dir:-

```<code>$ ls
Getstr.c  main.c  Makefile  objs  ui.c  ui.h  ustreqsol.c  ustreqsol.h
</code>```

objs is directory. Whenver I change ustreqsol.h file it compiles ustreqsol.c file but not in case for ui.h file

```<code>$ touch ustreqsol.h
$ make
gcc -c -o objs/ustreqsol.o ustreqsol.c
gcc -o ../Debug/Calculator objs/Getstr.o objs/ui.o objs/ustreqsol.o objs/main.o `pkg-config --cflags --libs gtk+-3.0`
$ make
make: '../Debug/Calculator' is up to date.
$ touch ui.h
$ make
make: '../Debug/Calculator' is up to date.
</code>```

As a noob in makefiles i have no idea why is this happening

答:
The reason ui.c is not being rebuilt is because you explictly said ui.h is not a dependency:

```<code>./objs/ui.o:ui.c
    $(CC) -c -o $@ $< $(pkg)
</code>```

For the general dependency you have set up:

```<code>./objs/%.o: %.c %.h
    $(CC) -c -o $@ $<
</code>```

The dependency list only takes effect for files that you didn't explicitly set them for, such as ustreqsol.c.

You need to add targets for each object file specifying the dependencies for each one.  The targets can be blank, as the %.o target will fill in what to do.

For example:

```<code>./objs/ustreqsol.o: ustreqsol.c ustreqsol.h ui.h

./objs/ui.o: ui.c ui.h

./objs/main.o: main.c ui.h ustreqsol.h

./objs/Getstr.o: Getstr.c

./objs/%.o: %.c %.h
    $(CC) -c -o $@ $<
</code>```

Body:
I have following make file :-

VER = Debug
CC = gcc
objectfiles = Getstr.o ui.o ustreqsol.o main.o
pkg = `pkg-config --cflags --libs gtk+-3.0`

obj = $(addprefix objs/,$(objectfiles))

../$(VER)/Calculator: $(obj)
    $(CC) -o $@ $(obj) $(pkg)

./objs/ui.o:ui.c
    $(CC) -c -o $@ $< $(pkg)

./objs/main.o:main.c
    $(CC) -c -o $@ $< $(pkg)

./objs/%.o: %.c %.h
    $(CC) -c -o $@ $<

clean:
    -rm ../$(VER)/Calculator
    -rm /objs/*

and follwing files in my src dir:-

$ ls
Getstr.c  main.c  Makefile  objs  ui.c  ui.h  ustreqsol.c  ustreqsol.h

objs is directory. Whenver I change ustreqsol.h file it compiles ustreqsol.c file but not in case for ui.h file

$ touch ustreqsol.h
$ make
gcc -c -o objs/ustreqsol.o ustreqsol.c
gcc -o ../Debug/Calculator objs/Getstr.o objs/ui.o objs/ustreqsol.o objs/main.o `pkg-config --cflags --libs gtk+-3.0`
$ make
make: '../Debug/Calculator' is up to date.
$ touch ui.h
$ make
make: '../Debug/Calculator' is up to date.

As a noob in makefiles i have no idea why is this happening

Body:
The reason ui.c is not being rebuilt is because you explictly said ui.h is not a dependency:

./objs/ui.o:ui.c
    $(CC) -c -o $@ $< $(pkg)

For the general dependency you have set up:

./objs/%.o: %.c %.h
    $(CC) -c -o $@ $<

The dependency list only takes effect for files that you didn't explicitly set them for, such as ustreqsol.c.

You need to add targets for each object file specifying the dependencies for each one.  The targets can be blank, as the %.o target will fill in what to do.

For example:

./objs/ustreqsol.o: ustreqsol.c ustreqsol.h ui.h

./objs/ui.o: ui.c ui.h

./objs/main.o: main.c ui.h ustreqsol.h

./objs/Getstr.o: Getstr.c

./objs/%.o: %.c %.h
    $(CC) -c -o $@ $<


问:
I published my private SSH key in a repository
This may be the most stupid question in this forum. But I just created a private repository and somehow my public and private ssh key were written into files inside the local repo.

When I published my repo to bitbucket the files with both of my SSH Keys got published, too. So now they are openly accessable on my repo. And even when I delete them you find them in the log files. How can I safely return from that mistake?

答:
Your private key is compromised. You must replace it everywhere you used it before, immediately.

Generate a new private and public key pair, right now.

Remove the public key from the list of allowed keys everywhere you used it.
Replace it with the new public key.

Remove the old private key from the history of the repository.
You can follow GitHub's guide.

Remove the old private key, you don't need it anymore.

You'll need to figure out how the key ended up in the repo.
To avoid further mistakes,
and your new key showing up again in that repo,
I suggest to remove the repo from the internet while you investigate.
You can easily push it back later when you're done.


问:
javaFX- how to place a textarea in the bottom of the screen
i am a beginner in javafx, so i am working on a chat app UI.
i want to place a textarea in the bottom of the screen, and must stay in this position whatever the size of the screen.

this is my FXML file:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXTextArea?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>

<GridPane fx:id="gridParent" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="550.0" prefWidth="750.0" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.bmi.client.AccueilController">
  <columnConstraints>
    <ColumnConstraints hgrow="SOMETIMES" maxWidth="228.0" minWidth="10.0" prefWidth="100.0" />
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  </columnConstraints>
  <rowConstraints>
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  </rowConstraints>
   <children>
      <AnchorPane fx:id="listePane" prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: #1D232A;" />
      <AnchorPane fx:id="convPane" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
         <children>
            <Pane fx:id="namePane" prefHeight="47.0" prefWidth="375.0" style="-fx-background-color: #b0b0b0;">
               <children>
                  <Label fx:id="nameLabel" layoutX="14.0" layoutY="15.0" />
               </children>
            </Pane>
            <JFXTextArea fx:id="messageArea" layoutY="482.0" prefHeight="68.0" prefWidth="375.0" promptText="Ecrire un message..." style="-fx-background-color: white; -fx-border-radius: 10px;"  />
         </children>
      </AnchorPane>
   </children>
</GridPane>
</code>```

and this is a screenshot of the FXML File
image

and when i resize the screen i get something like that:
image2

答:
Here is one way using an HBox as the root.

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXTextArea?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.VBox?>

<HBox prefHeight="550.0" prefWidth="750.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <AnchorPane fx:id="listePane" prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: #1D232A;" />
      <VBox prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS">
         <children>
            <Pane fx:id="namePane" prefHeight="47.0" prefWidth="375.0" style="-fx-background-color: #b0b0b0;" VBox.vgrow="ALWAYS">
               <children>
                  <Label fx:id="nameLabel" layoutX="14.0" layoutY="15.0" />
               </children>
            </Pane>
            <JFXTextArea fx:id="messageArea" prefHeight="68.0" prefWidth="375.0" promptText="Ecrire un message..." style="-fx-background-color: white; -fx-border-radius: 10px;" />
         </children>
      </VBox>
   </children>
</HBox>
</code>```

Body:
i am a beginner in javafx, so i am working on a chat app UI.
i want to place a textarea in the bottom of the screen, and must stay in this position whatever the size of the screen.

this is my FXML file:

<?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXTextArea?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>

<GridPane fx:id="gridParent" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="550.0" prefWidth="750.0" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.bmi.client.AccueilController">
  <columnConstraints>
    <ColumnConstraints hgrow="SOMETIMES" maxWidth="228.0" minWidth="10.0" prefWidth="100.0" />
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  </columnConstraints>
  <rowConstraints>
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  </rowConstraints>
   <children>
      <AnchorPane fx:id="listePane" prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: #1D232A;" />
      <AnchorPane fx:id="convPane" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1">
         <children>
            <Pane fx:id="namePane" prefHeight="47.0" prefWidth="375.0" style="-fx-background-color: #b0b0b0;">
               <children>

               </children>
            </Pane>
            <JFXTextArea fx:id="messageArea" layoutY="482.0" prefHeight="68.0" prefWidth="375.0" promptText="Ecrire un message..." style="-fx-background-color: white; -fx-border-radius: 10px;"  />
         </children>
      </AnchorPane>
   </children>
</GridPane>

and this is a screenshot of the FXML File
image

and when i resize the screen i get something like that:
image2

Body:
Here is one way using an HBox as the root.

<?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXTextArea?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.VBox?>

<HBox prefHeight="550.0" prefWidth="750.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <AnchorPane fx:id="listePane" prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: #1D232A;" />
      <VBox prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS">
         <children>
            <Pane fx:id="namePane" prefHeight="47.0" prefWidth="375.0" style="-fx-background-color: #b0b0b0;" VBox.vgrow="ALWAYS">
               <children>
                  <Label fx:id="nameLabel" layoutX="14.0" layoutY="15.0" />
               </children>
            </Pane>
            <JFXTextArea fx:id="messageArea" prefHeight="68.0" prefWidth="375.0" promptText="Ecrire un message..." style="-fx-background-color: white; -fx-border-radius: 10px;" />
         </children>
      </VBox>
   </children>
</HBox>


问:
How to compute the git hash-object of a directory?
Does anyone have an example of using git hash-object on a directory?  It works easily enough on a file* but doesn't work as I'd expect for a directory**

```<code>*:  git hash-object c:\somefile.txt
**: git hash-object -t tree c:\somedirectory
</code>```

When I try to use hash-object with the directory, it complains "fatal: Cannot open 'C:\someDirectory': Permission denied"

答:
Depending why you wish to do this, the following git command might be useful:

```<code>git ls-files -s somedirectory | git hash-object --stdin
</code>```

This give a single hash which takes into account the filenames and contents.

It works like this. The git ls-files -s .... outputs a list of files and their hashes as text to stdout, then git hash-object generates a hash for the data it receives from stdin.

My use case for this is the following - I want to know whether the (git managed) files in a directory in one branch exactly(*) match those in another branch. The specific use is to compare the "directory hashes" decide whether I need to re-generate derived files which are cached.

By default git ls-files will list files in sub-directories too. If you don't want that, try looking at answers to "how to git ls-file for just one directory level. There are also various other options to git ls-files, including the ability to specify a list of files to include.

(*) excluding hash-collisions

Body:
Does anyone have an example of using git hash-object on a directory?  It works easily enough on a file* but doesn't work as I'd expect for a directory**

*:  git hash-object c:\somefile.txt
**: git hash-object -t tree c:\somedirectory

When I try to use hash-object with the directory, it complains "fatal: Cannot open 'C:\someDirectory': Permission denied"

Body:
Depending why you wish to do this, the following git command might be useful:

git ls-files -s somedirectory | git hash-object --stdin

This give a single hash which takes into account the filenames and contents.

It works like this. The git ls-files -s .... outputs a list of files and their hashes as text to stdout, then git hash-object generates a hash for the data it receives from stdin.

My use case for this is the following - I want to know whether the (git managed) files in a directory in one branch exactly(*) match those in another branch. The specific use is to compare the "directory hashes" decide whether I need to re-generate derived files which are cached.

By default git ls-files will list files in sub-directories too. If you don't want that, try looking at answers to "how to git ls-file for just one directory level. There are also various other options to git ls-files, including the ability to specify a list of files to include.

(*) excluding hash-collisions


问:
Mongoose populate a field without ObjectId?
I have a schema:

```<code>var Schema = mongoose.Schema;

var TicketSchema = new Schema({
externalId: String,
name: String,
items: [{
    externalId: String,
    price: Number,
    quantity: {
        type: Number,
        default: 1
    },
    comment: {
        type: String,
        default: '',
        trim: true
    },
    entity: {
        type: String,
        ref: 'Entity'
    }
}],
tableId: String
});

mongoose.model('Ticket', TicketSchema);
</code>```

And I want to populate entity field with an unique field other than ObjectId.
How can I achieve that?

答:
Though late answer. Please check Populate Virtuals for Mongoose 4.5.0

Click the link below

http://mongoosejs.com/docs/populate.html

And scroll down or search for Populate Virtuals you will see it does exactly what you want.

Body:
I have a schema:

var Schema = mongoose.Schema;

var TicketSchema = new Schema({
externalId: String,
name: String,
items: [{
    externalId: String,
    price: Number,
    quantity: {
        type: Number,
        default: 1
    },
    comment: {
        type: String,
        default: '',
        trim: true
    },
    entity: {
        type: String,
        ref: 'Entity'
    }
}],
tableId: String
});

mongoose.model('Ticket', TicketSchema);

And I want to populate entity field with an unique field other than ObjectId.
How can I achieve that?


问:
location of Firefox extensions in Mac OS?
In Mac OS X, where are installed extensions for Firefox located?</p>

OwnerDisplayName: Geuis

Body: ~/Library/Application Support/Firefox/Profiles/[profile name]/extensions


问:
Compile error with EasyBMP library
I'm trying to write a program that can rotate a given BMP file 180 degrees and create a new BMP file with the rotated image. I'm using the EasyBMP library. However, every time I try to compile, I get these warnings:

```<code>EasyBMP Warning: Attempted to access non-existent pixel (359, 236);
                 Truncating request to fit in the range [0,358] x [0,269].
</code>```

And I get hundreds of these! (The image in question is 359x270) The weird thing is that my code actually works 100%. When I run the program, it does create a rotated image and looks perfect.

答:
If should be

```<code>for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        color = in(x, y);
        *(out(width - x - 1, height - y - 1)) = *color;
    }
}
</code>```

(Note < instead of <= and - 1 added).

Title: Compile error with EasyBMP library

Body:
I'm trying to write a program that can rotate a given BMP file 180 degrees and create a new BMP file with the rotated image. I'm using the EasyBMP library. However, every time I try to compile, I get these warnings:

EasyBMP Warning: Attempted to access non-existent pixel (359, 236);
                 Truncating request to fit in the range [0,358] x [0,269].

And I get hundreds of these! (The image in question is 359x270) The weird thing is that my code actually works 100%. When I run the program, it does create a rotated image and looks perfect.

Body:
If should be

for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        color = in(x, y);
        *(out(width - x - 1, height - y - 1)) = *color;
    }
}

(Note < instead of <= and - 1 added).


问:
Developing shiny web app,getting an "ui not found" error message
Currently developing my first web app with the Shiny package, but unfortunately, after running  the code on Rstudio  am encountering the following error message:

server <- function(input, output){}
  shinyApp(ui ,server)
  Error in force(ui) : object 'ui' not found

What could be the issue?

答:
Every shiny page has a ui and server element. The problem is that you only have the server defined, and not the ui. See below for an example of a very basic shiny webpage.

```<code>library(shiny)

# setwd(dirname(rstudioapi::getActiveDocumentContext()$path))  # set your working directory

# Set the ui section.
ui <- fluidPage(
  h1("Title"),
  selectInput("test.input", "Select a letter", choices = c("a", "b", "c")),
  textOutput("test.output")
)

# Set the server section.
server <- function(input, output, session) {
  output$test.output <- renderText(
    paste0("You have selected ", input$test.input)
  )
}

shinyApp(ui = ui, server = server)
</code>```

This shiny app has a basic header, dropdown menu and HTML output, which is all defined in the ui variable. Your page should look like this:

See this page for more about the basic layout of a shiny app.

Body:
Every shiny page has a ui and server element. The problem is that you only have the server defined, and not the ui. See below for an example of a very basic shiny webpage.

library(shiny)

# setwd(dirname(rstudioapi::getActiveDocumentContext()$path))  # set your working directory

# Set the ui section.
ui <- fluidPage(
  h1("Title"),
  selectInput("test.input", "Select a letter", choices = c("a", "b", "c")),
  textOutput("test.output")
)

# Set the server section.
server <- function(input, output, session) {
  output$test.output <- renderText(
    paste0("You have selected ", input$test.input)
  )
}

shinyApp(ui = ui, server = server)

This shiny app has a basic header, dropdown menu and HTML output, which is all defined in the ui variable. Your page should look like this:

See this page for more about the basic layout of a shiny app.


问:
Byteman - trace all classes and methods in a given package
When using Byteman, we have to specify the class and the method in the rule syntax. What if I want to trace program execution using Byteman?

Example: I do not know which methods are being executed when executing a feature of the program. I want to identify the called methods during the feature execution.

Does this mean that I've to add a rule for each method of each class in a given package? Or is there any other way to achieve this?

答: It looks like Byteman is not the right tool for what you want. Better results would be provided by: Understand or JProfiler. Especially in multi-threading environment.</p>


问:
Numpy array creation using a sequence
I have seen this, but it doesn't quite answer my question.

I have an array:

```<code>x = np.array([0, 1, 2])
</code>```

I want this:

```<code>y = np.array([[0,1], [0,2], [1,0], [1,2], [2,0], [2,1]])
</code>```

That is, I want to take each value (let's call it i) of the array x and create x.shape[0]-1 new arrays with all of the other values of x, excluding i.

Essentially y contains the indices of a 3x3 matrix without any diagonal elements.

I have a feeling there's an easy, pythonic way of doing this that's just not coming to me.

答:
This is a case where, unless you really need to speed, etc, of numpy, pure Python gives a cleaner solution:</p>

```<code>import itertools

y = itertools.permutations([0, 1, 2], 2)

# [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
</code>```

Title: Numpy array creation using a sequence

Body:
I have seen this, but it doesn't quite answer my question.

I have an array:

x = np.array([0, 1, 2])

I want this:

y = np.array([[0,1], [0,2], [1,0], [1,2], [2,0], [2,1]])

That is, I want to take each value (let's call it i) of the array x and create x.shape[0]-1 new arrays with all of the other values of x, excluding i.

Essentially y contains the indices of a 3x3 matrix without any diagonal elements.

I have a feeling there's an easy, pythonic way of doing this that's just not coming to me.

Body:
This is a case where, unless you really need to speed, etc, of numpy, pure Python gives a cleaner solution:

import itertools

y = itertools.permutations([0, 1, 2], 2)

# [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]


问:
Trying to insert a column with a formula for Excel VBA
I am trying to insert a column into my data table and insert a formula into the cells. This code has worked for me on this project except for this formula:

```<code>     With Data

            .Columns("M:M").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
            .Range("M1").FormulaR1C1 = "PROD-DESC"
            .Range("M2").FormulaR1C1 = "=CONCATENATE(K2," - ",L2)"
            .Range("M2:M" & .Cells(Rows.Count, "M").End(xlUp).Row).FillDown

 End With
</code>```

When I run the code. I get a mismatch error and it highlights the line with the concatenate formula.

Any help would be greatly appreciated. I am really struggling to figure out why this is not working.

Thanks,

G

答:
The following will work (you need to double the double quotes as you're inside another string - you also need to remove R1C1):

```<code>.Range("M2").Formula = "=CONCATENATE(K2,"" - "",L2)"
</code>```

Body:
I am trying to insert a column into my data table and insert a formula into the cells. This code has worked for me on this project except for this formula:

     With Data

            .Columns("M:M").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
            .Range("M1").FormulaR1C1 = "PROD-DESC"
            .Range("M2").FormulaR1C1 = "=CONCATENATE(K2," - ",L2)"
            .Range("M2:M" & .Cells(Rows.Count, "M").End(xlUp).Row).FillDown

 End With

When I run the code. I get a mismatch error and it highlights the line with the concatenate formula.

Any help would be greatly appreciated. I am really struggling to figure out why this is not working.

Thanks,

G

Body:
The following will work (you need to double the double quotes as you're inside another string - you also need to remove R1C1):

.Range("M2").Formula = "=CONCATENATE(K2,"" - "",L2)"


问:
getting DOM element coordinates without showing a view in pyqt5
I am trying to get the coordinates of the bounding box for all DOM elements. I am currently using pyqt5 and could do it successfully with the following codes:

```<code>class Browser(QWebEngineView):
    def __init__(self):
        super(Browser, self).__init__()
        self.loadFinished.connect(self._load_finished)

    def _result(self, x):
        for tagname, top, right, bottom, left in x:
            print "%8s %3d %3d %3d %3d"%(tagname, top, right, bottom, left)

    def _load_finished(self):
        js_script = """
                function get_coordinates() {
                    var res = [];
                    var all = document.getElementsByTagName("*");
                    for (var i=0, max=all.length; i < max; i++) {
                        var rect = all[i].getBoundingClientRect()
                        res.push([all[i].tagName, rect.top, rect.right, rect.bottom, rect.left]);
                    }
                    return res;
                }
                get_coordinates();
                """
        self.page().runJavaScript(js_script, self._result)

app = QApplication(sys.argv)
br = Browser()
url = QUrl(url_address)
br.load(url)
br.show()
app.exec_()
</code>```

One disadvantage of this codes is that it opens a browser to show the webpage (because of br.show()), and I am wondering if there is any way of preventing this. I simply commented br.show() and ran the codes. But, the coordinate results for some DOM elements are different than the original ones.

thanks,

答:
If you want to not show a window you use QWebEnginePage:

```<code>class Browser(QWebEnginePage):
    def __init__(self):
        super(Browser, self).__init__()
        self.loadFinished.connect(self._load_finished)

    def _result(self, x):
        for tagname, top, right, bottom, left in x:
            print("%8s %3d %3d %3d %3d"%(tagname, top, right, bottom, left))

    def _load_finished(self):
        js_script = """
                function get_coordinates() {
                    var res = [];
                    var all = document.getElementsByTagName("*");
                    for (var i=0, max=all.length; i < max; i++) {
                        var rect = all[i].getBoundingClientRect()
                        res.push([all[i].tagName, rect.top, rect.right, rect.bottom, rect.left]);
                    }
                    return res;
                }
                get_coordinates();
                """
        self.runJavaScript(js_script, self._result)

app = QApplication(sys.argv)
br = Browser()
url = QUrl(url_address)
br.load(url)
app.exec_()
</code>```

Body:
I am trying to get the coordinates of the bounding box for all DOM elements. I am currently using pyqt5 and could do it successfully with the following codes:

class Browser(QWebEngineView):
    def __init__(self):
        super(Browser, self).__init__()
        self.loadFinished.connect(self._load_finished)

    def _result(self, x):
        for tagname, top, right, bottom, left in x:
            print "%8s %3d %3d %3d %3d"%(tagname, top, right, bottom, left)

    def _load_finished(self):
        js_script = """
                function get_coordinates() {
                    var res = [];
                    var all = document.getElementsByTagName("*");
                    for (var i=0, max=all.length; i < max; i++) {
                        var rect = all[i].getBoundingClientRect()
                        res.push([all[i].tagName, rect.top, rect.right, rect.bottom, rect.left]);
                    }
                    return res;
                }
                get_coordinates();
                """
        self.page().runJavaScript(js_script, self._result)

app = QApplication(sys.argv)
br = Browser()
url = QUrl(url_address)
br.load(url)
br.show()
app.exec_()

One disadvantage of this codes is that it opens a browser to show the webpage (because of br.show()), and I am wondering if there is any way of preventing this. I simply commented br.show() and ran the codes. But, the coordinate results for some DOM elements are different than the original ones.

thanks,

Body:
If you want to not show a window you use QWebEnginePage:

class Browser(QWebEnginePage):
    def __init__(self):
        super(Browser, self).__init__()
        self.loadFinished.connect(self._load_finished)

    def _result(self, x):
        for tagname, top, right, bottom, left in x:
            print("%8s %3d %3d %3d %3d"%(tagname, top, right, bottom, left))

    def _load_finished(self):
        js_script = """
                function get_coordinates() {
                    var res = [];
                    var all = document.getElementsByTagName("*");
                    for (var i=0, max=all.length; i < max; i++) {
                        var rect = all[i].getBoundingClientRect()
                        res.push([all[i].tagName, rect.top, rect.right, rect.bottom, rect.left]);
                    }
                    return res;
                }
                get_coordinates();
                """
        self.runJavaScript(js_script, self._result)

app = QApplication(sys.argv)
br = Browser()
url = QUrl(url_address)
br.load(url)
app.exec_()


问:
React Native Post Request via Fetch throws Network Request Failed
I've came across the following error.
At the moment I developing an Android App with React Native therefore I'm planning to use fetch for doing a post request for me.

```<code>fetch("https://XXreachable-domainXX.de/api/test", {
    method: "post",

    body: JSON.stringify({
      param: 'param',
      param1: 'param',

    })
  })
  .then((response) = > response.json())
  .then((responseData) = > {
    ToastAndroid.show(
      "Response Body -> " + JSON.stringify(responseData.message), ToastAndroid.SHORT
    )
  })
  .catch((error) = > {
    console.warn(error);
  });
</code>```

The app now throws an error:

TypeError: Network request failed

When I change the code to a GET-Request it's working fine, in the browser with a window.alert() as a return it's cool and also the Chrome extension Postman returns data correctly.

答:
I had this problem on Android due to an expired certificate. The error message I had was com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: Certificate expired at Fri Sep 29 16:33:39 EDT 2017 (compared to Fri Dec 08 14:10:58 EST 2017).

I was able to confirm this using digicert.com.

Unfortunately I did have to dig rather deep into the React Native code and debug the XHR code in the bundle (index.android.bundle) in order to find the error message and the URL in question, because it was in some of my logging code, which I obviously didn't log to the console as well. :)

I was helped by this GitHub issue comment.

ContentLicense: CC BY-SA 4.0

Body:
I've came across the following error.
At the moment I developing an Android App with React Native therefore I'm planning to use fetch for doing a post request for me.

fetch("https://XXreachable-domainXX.de/api/test", {
    method: "post",

    body: JSON.stringify({
      param: 'param',
      param1: 'param',

    })
  })
  .then((response) = > response.json())
  .then((responseData) = > {
    ToastAndroid.show(
      "Response Body -> " + JSON.stringify(responseData.message), ToastAndroid.SHORT
    )
  })
  .catch((error) = > {
    console.warn(error);
  });

The app now throws an error:

TypeError: Network request failed

When I change the code to a GET-Request it's working fine, in the browser with a window.alert() as a return it's cool and also the Chrome extension Postman returns data correctly.


问:
Add element to sublist of a list
I have the following code:

```<code>let numbers = [[1],[2],[3],[4]]
</code>```

I want to append "3" to the sublist at index 2 of the list ([3]), like this:

```<code>(numbers !! 2) ++ [3]
</code>```

to get this:

```<code>numbers = [[1],[2],[3,3],[4]]
</code>```

But Im very confused :P Any idea?

答:
If writing the recursive update function is difficult for you, you can convert your list structure to a synthetic indexed array with zip

```<code>zip [0..] [[1],[2],[3],[4]]
</code>```

and write your concat version based on the index as you do in other languages with indexed arrays

```<code>appendAt n a = map (\(i,x) -> if i==n then x++[a] else x) . zip [0..]
</code>```

then,

```<code>appendAt 2 3 numbers
</code>```

wll give you the desired result.

Title: Add element to sublist of a list

Body:
I have the following code:

let numbers = [[1],[2],[3],[4]]

I want to append "3" to the sublist at index 2 of the list ([3]), like this:

(numbers !! 2) ++ [3]

to get this:

numbers = [[1],[2],[3,3],[4]]

But Im very confused :P Any idea?

Body:
If writing the recursive update function is difficult for you, you can convert your list structure to a synthetic indexed array with zip

zip [0..] [[1],[2],[3],[4]]

and write your concat version based on the index as you do in other languages with indexed arrays

appendAt n a = map (\(i,x) -> if i==n then x++[a] else x) . zip [0..]

then,

appendAt 2 3 numbers

wll give you the desired result.


Title: Trim Decimal Places from Numbers in a Text Editor

Body:
I have a set of SVG definition exported from Inkspace and as anyone who has done this themselves will know the resulting definition often contains far more accuracy that is actually justified. For example for a 32 x32 icon definition shown below, Inkspace has generated 6 (or more!) decimal places of accuracy per pixel. Now I know that means it will scale but in my case I would rather save space in my app which requires input of hundreds of such icon definitions.

<svg width="32" height="32"><path d="M 14.576172 5.453125 L 13.78125 8.8222656 L 12.464844 9.3691406 L 9.5625 7.5898438 L 7.5898438 9.5351562 L 9.3691406 12.576172 L 8.8222656 13.78125 L 5.4785156 14.630859 L 5.4785156 17.369141 L 8.8496094 18.246094 L 9.3691406 19.507812 L 7.5625 22.464844 L 9.5351562 24.410156 L 12.548828 22.658203 L 13.808594 23.177734 L 14.603516 26.494141 L 17.396484 26.521484 L 18.191406 23.177734 L 19.505859 22.658203 L 22.410156 24.410156 L 24.355469 22.410156 L 22.658203 19.451172 L 23.150391 18.191406 L 26.492188 17.369141 L 26.492188 14.630859 L 23.123047 13.726562 L 22.630859 12.521484 L 24.410156 9.5351562 L 22.410156 7.5898438 L 19.451172 9.3417969 L 18.246094 8.8222656 L 17.396484 5.453125 L 14.576172 5.453125 z M 15.984375 12.082031 A 3.9078221 3.9078221 0 0 1 19.892578 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 19.896484 A 3.9078221 3.9078221 0 0 1 12.078125 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 12.082031 Z" fill="#f9f9f9" /></svg>

So my question is how can I trim the definitions using a text editor to say 2 decimal places.

I have found that by using TextWrangler with the following grep search and replace string

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9][0-9])
\1

that I can search for all 6 decimal places strings and replace them with 2 decimal places. Then I can change the search and replace to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9])
\1

and then to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9])
\1

and finally to

(\.[0-9][0-9])([0-9][0-9][0-9])
\1

and this works.

However if someone with slightly (or a lot) more brain pixels than me, could show me how to do all of the above with just one search and replace operation, I would be very happy.

Body:
To remove the unwanted precision from the (bash or shell) command line, try:

sed -E 's/([[:digit:]]\.[[:digit:]]{2})[[:digit:]]+/\1/g' file.svg

To change the file in place (Linux),

sed -i.bak -E 's/([[:digit:]]\.[[:digit:]]{2})[[:digit:]]+/\1/g' file.svg

Or OSX:

sed -i .bak -E 's/([[:digit:]]\.[[:digit:]]{2})[[:digit:]]+/\1/g' file.svg

How it works

This looks for any place where there is a digit, followed by a period, followed by two digits, followed by some number of more digits:

([[:digit:]]\.[[:digit:]]{2})[[:digit:]]+

The first digit, period, and two following digits are in parens.  This saves them to group 1 which we use as the replacement text.

Example

Your input file:

$ cat >file.svg
<svg width="32" height="32"><path d="M 14.576172 5.453125 L 13.78125 8.8222656 L 12.464844 9.3691406 L 9.5625 7.5898438 L 7.5898438 9.5351562 L 9.3691406 12.576172 L 8.8222656 13.78125 L 5.4785156 14.630859 L 5.4785156 17.369141 L 8.8496094 18.246094 L 9.3691406 19.507812 L 7.5625 22.464844 L 9.5351562 24.410156 L 12.548828 22.658203 L 13.808594 23.177734 L 14.603516 26.494141 L 17.396484 26.521484 L 18.191406 23.177734 L 19.505859 22.658203 L 22.410156 24.410156 L 24.355469 22.410156 L 22.658203 19.451172 L 23.150391 18.191406 L 26.492188 17.369141 L 26.492188 14.630859 L 23.123047 13.726562 L 22.630859 12.521484 L 24.410156 9.5351562 L 22.410156 7.5898438 L 19.451172 9.3417969 L 18.246094 8.8222656 L 17.396484 5.453125 L 14.576172 5.453125 z M 15.984375 12.082031 A 3.9078221 3.9078221 0 0 1 19.892578 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 19.896484 A 3.9078221 3.9078221 0 0 1 12.078125 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 12.082031 Z" fill="#f9f9f9" /></svg>

Our command:

$ sed -E 's/([[:digit:]]\.[[:digit:]]{2})[[:digit:]]+/\1/g' file.svg
<svg width="32" height="32"><path d="M 14.57 5.45 L 13.78 8.82 L 12.46 9.36 L 9.56 7.58 L 7.58 9.53 L 9.36 12.57 L 8.82 13.78 L 5.47 14.63 L 5.47 17.36 L 8.84 18.24 L 9.36 19.50 L 7.56 22.46 L 9.53 24.41 L 12.54 22.65 L 13.80 23.17 L 14.60 26.49 L 17.39 26.52 L 18.19 23.17 L 19.50 22.65 L 22.41 24.41 L 24.35 22.41 L 22.65 19.45 L 23.15 18.19 L 26.49 17.36 L 26.49 14.63 L 23.12 13.72 L 22.63 12.52 L 24.41 9.53 L 22.41 7.58 L 19.45 9.34 L 18.24 8.82 L 17.39 5.45 L 14.57 5.45 z M 15.98 12.08 A 3.90 3.90 0 0 1 19.89 15.98 A 3.90 3.90 0 0 1 15.98 19.89 A 3.90 3.90 0 0 1 12.07 15.98 A 3.90 3.90 0 0 1 15.98 12.08 Z" fill="#f9f9f9" /></svg>


问:
Laravel group user entities by categories
I have three tables: users, rooms and room categories. So I want to get specific user rooms grouped by their categories but only for those categories which user rooms have. Here are my models and migrations:

Room Model

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    protected $fillable = ['type_id', 'name', 'rooms_count', 'smoking'];

    // public $with = ['type'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function type()
    {
        return $this->belongsTo('App\RoomType', 'type_id', 'id');
    }
}
</code>```

Room Types Model

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class RoomType extends Model
{
    protected $fillable = ['title'];

    public $with = ['rooms'];

    public function rooms()
    {
        return $this->hasMany('App\Room', 'type_id');
    }
}
</code>```

User Model

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function rooms()
    {
        return $this->hasMany('App\Room');
    }
}
</code>```

User table migration

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
</code>```

Rooms table migration

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoomsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('rooms', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('type_id');
            $table->string('name');
            $table->integer('rooms_count');
            $table->boolean('smoking');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('rooms');
    }
}
</code>```

Room types migration

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoomTypesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('room_types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('room_types');
    }
}
</code>```

So I want to get the result like this

```<code>[
  {
    "id": 1,
    "title": "Eum laboriosam.",
    "created_at": "2017-12-06 18:19:59",
    "updated_at": "2017-12-06 18:19:59",
    "rooms": [
      {
        "id": 1,
        "user_id": 1,
        "type_id": 1,
        "name": "room1",
        "rooms_count": 1,
        "smoking": 1,
        "created_at": "2017-12-06 18:53:39",
        "updated_at": "2017-12-06 18:53:39"
      }
    ]
  },
  {
    "id": 2,
    "title": "Atque officiis.",
    "created_at": "2017-12-06 18:19:59",
    "updated_at": "2017-12-06 18:19:59",
    "rooms": [
      {
        "id": 2,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      },
      {
        "id": 3,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      },
      {
        "id": 4,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      },
      {
        "id": 5,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      }
    ]
  }
]
</code>```

I have used for that this code:

```<code>return $roomsByCategories = RoomType::with('rooms')->get();
</code>```

But I'm getting all categories which I don't need because a user has rooms only for 2 categories.

答:
You should use where condition and can join room_types and group results like this:

```<code>    return $roomsByCategories = User::with('rooms')
     ->join('room_types', 'room_types.id', '=', 'rooms.type_id')
     ->where('rooms.user_id', $user_id)
     ->groupBy('room_types.id')
     ->get();
</code>```

Or you can use:

```<code>return $roomsByCategories = Rooms::with('type')
         ->where('rooms.user_id', $user_id)
         ->groupBy('room_types.id')
         ->get();
</code>```

Body:
I have three tables: users, rooms and room categories. So I want to get specific user rooms grouped by their categories but only for those categories which user rooms have. Here are my models and migrations:

Room Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    protected $fillable = ['type_id', 'name', 'rooms_count', 'smoking'];

    // public $with = ['type'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function type()
    {
        return $this->belongsTo('App\RoomType', 'type_id', 'id');
    }
}

Room Types Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class RoomType extends Model
{
    protected $fillable = ['title'];

    public $with = ['rooms'];

    public function rooms()
    {
        return $this->hasMany('App\Room', 'type_id');
    }
}

User Model

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function rooms()
    {
        return $this->hasMany('App\Room');
    }
}

User table migration

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Rooms table migration

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoomsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('rooms', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('type_id');
            $table->string('name');
            $table->integer('rooms_count');
            $table->boolean('smoking');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('rooms');
    }
}

Room types migration

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoomTypesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('room_types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('room_types');
    }
}

So I want to get the result like this

[
  {
    "id": 1,
    "title": "Eum laboriosam.",
    "created_at": "2017-12-06 18:19:59",
    "updated_at": "2017-12-06 18:19:59",
    "rooms": [
      {
        "id": 1,
        "user_id": 1,
        "type_id": 1,
        "name": "room1",
        "rooms_count": 1,
        "smoking": 1,
        "created_at": "2017-12-06 18:53:39",
        "updated_at": "2017-12-06 18:53:39"
      }
    ]
  },
  {
    "id": 2,
    "title": "Atque officiis.",
    "created_at": "2017-12-06 18:19:59",
    "updated_at": "2017-12-06 18:19:59",
    "rooms": [
      {
        "id": 2,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      },
      {
        "id": 3,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      },
      {
        "id": 4,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      },
      {
        "id": 5,
        "user_id": 1,
        "type_id": 2,
        "name": "standart Delux",
        "rooms_count": 4,
        "smoking": 1,
        "created_at": "2017-12-06 19:15:49",
        "updated_at": "2017-12-06 19:15:49"
      }
    ]
  }
]

I have used for that this code:

return $roomsByCategories = RoomType::with('rooms')->get();

But I'm getting all categories which I don't need because a user has rooms only for 2 categories.

Body:
You should use where condition and can join room_types and group results like this:

    return $roomsByCategories = User::with('rooms')
     ->join('room_types', 'room_types.id', '=', 'rooms.type_id')
     ->where('rooms.user_id', $user_id)
     ->groupBy('room_types.id')
     ->get();

Or you can use:

return $roomsByCategories = Rooms::with('type')
         ->where('rooms.user_id', $user_id)
         ->groupBy('room_types.id')
         ->get();


问:
Random URL for update action in a State Machine like Rails app
I'm developing an app that is much similar to a State Machine.

After create a "person", there are attributes left null, that have to be filled yet through "update" actions.

I defined a "unique_token" function in my model, so when creating and updating the person, a new unique string is assigned.

Later, I defined "/:unique_token" in my routes for the "edit" and "update" actions.

Later, In my controller, for "edit" and "udpate", I defined:

@person = Person.find_by_unique_token(params[:unique_token])

BUT!

I get an error because the update action still tries to find an ID.

How should I override that?

There's a better approach for this?

Thanks.

答:
wow, easy as:

```<code>class PeopleController < ApplicationController

  before_filter :authenticate_unique_token, :only => [:edit]

  def authenticate_unique_token
    person = Person.find_by_unique_token(params[:unique_token])
    if person.blank? || person.id != params[:id].to_i
      raise "whatever"
    end
  end
</code>```

i hope this could help anyone!

Body:
wow, easy as:

class PeopleController < ApplicationController

  before_filter :authenticate_unique_token, :only => [:edit]

  def authenticate_unique_token
    person = Person.find_by_unique_token(params[:unique_token])
    if person.blank? || person.id != params[:id].to_i
      raise "whatever"
    end
  end

i hope this could help anyone!


问:
Currying merge_with in python toolz
I would like to be able to curry merge_with:

merge_with works as I expect

```<code>>>> from cytoolz import curry, merge_with
>>> d1 = {"a" : 1, "b" : 2}
>>> d2 = {"a" : 2, "b" : 3}
>>> merge_with(sum, d1, d2)
{'a': 3, 'b': 5}
</code>```

On a simple function, curry works as I expect:

```<code>>>> def f(a, b):
...     return a * b
...
>>> curry(f)(2)(3)
6
</code>```

But I'm not able to "manually" make a curried version of merge_with:

```<code>>>> curry(merge_with)(sum)(d1, d2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
>>> curry(merge_with)(sum)(d1)(d2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
</code>```

The pre-curried version works:

```<code>>>> from cytoolz.curried import merge_with as cmerge
>>> cmerge(sum)(d1, d2)
{'a': 3, 'b': 5}
</code>```

Where is my mistake?

答:
It is because merge_with takes dicts as positional arguments:

```<code>merge_with(func, *dicts, **kwargs)
</code>```

so f is the only obligatory argument, and for empty *args you get an empty dictionary:

```<code>>>> curry(merge_with)(sum)  # same as merge_with(sum)
{}
</code>```

so:

```<code>curry(f)(2)(3)
</code>```

is equivalent to

```<code>>>> {}(2)(3)
Traceback (most recent call last):
...
TypeError: 'dict' object is not callable
</code>```

You'll have to explicit and define helper

```<code>def merge_with_(f):
    def _(*dicts, **kwargs):
        return merge_with(f, *dicts, **kwargs)
    return _
</code>```

which can be used as you want:

```<code>>>> merge_with_(sum)(d1, d2)
{'a': 3, 'b': 5}
</code>```

or:

```<code>def merge_with_(f, d1, d2, *args, **kwargs):
    return merge_with(f, d1, d2, *args, **kwargs)
</code>```

which can both

```<code>>>> curry(merge_with_)(sum)(d1, d2)
{'a': 3, 'b': 5}
</code>```

and:

```<code>>>> curry(merge_with_)(sum)(d1)(d2)
{'a': 3, 'b': 5}
</code>```

Title: Currying merge_with in python toolz

Body:
I would like to be able to curry merge_with:

merge_with works as I expect

>>> from cytoolz import curry, merge_with
>>> d1 = {"a" : 1, "b" : 2}
>>> d2 = {"a" : 2, "b" : 3}
>>> merge_with(sum, d1, d2)
{'a': 3, 'b': 5}

On a simple function, curry works as I expect:

>>> def f(a, b):
...     return a * b
...
>>> curry(f)(2)(3)
6

But I'm not able to "manually" make a curried version of merge_with:

>>> curry(merge_with)(sum)(d1, d2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
>>> curry(merge_with)(sum)(d1)(d2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable

The pre-curried version works:

>>> from cytoolz.curried import merge_with as cmerge
>>> cmerge(sum)(d1, d2)
{'a': 3, 'b': 5}

Where is my mistake?

Body:
It is because merge_with takes dicts as positional arguments:

merge_with(func, *dicts, **kwargs)

so f is the only obligatory argument, and for empty *args you get an empty dictionary:

>>> curry(merge_with)(sum)  # same as merge_with(sum)
{}

so:

curry(f)(2)(3)

is equivalent to

>>> {}(2)(3)
Traceback (most recent call last):
...
TypeError: 'dict' object is not callable

You'll have to explicit and define helper

def merge_with_(f):
    def _(*dicts, **kwargs):
        return merge_with(f, *dicts, **kwargs)
    return _

which can be used as you want:

>>> merge_with_(sum)(d1, d2)
{'a': 3, 'b': 5}

or:

def merge_with_(f, d1, d2, *args, **kwargs):
    return merge_with(f, d1, d2, *args, **kwargs)

which can both

>>> curry(merge_with_)(sum)(d1, d2)
{'a': 3, 'b': 5}

and:

>>> curry(merge_with_)(sum)(d1)(d2)
{'a': 3, 'b': 5}


问:
Access process.env in environment.ts file created from the angular-cli
I have an angular-cli application (angular version 4.0.0). I want to be able to access my environment variables in the environment.ts file created from the cli.

Example:

```<code>export SOME_VARIABLE=exampleValue
</code>```

When I build my angular app I want "exampleValue" to be populated in the SOME_VARIABLE field.

```<code>// environment.ts

export const environment = {
    production: false,
    SOME_VARIABLE: process.env.SOME_VARIABLE
};
</code>```

Unfortunately, process.env isn't available in this file. How can I gain access to it?

答:
One way to solve this is to create a node script, which replaces a place holder.

This can be done with replace-in-file from npm.

A solution can look like this:

npm install replace-in-file --save-dev

Create a place holder

```<code>export const environment = {
  production: true,
  version: '{BUILD_VERSION}'
}
</code>```

Create node script to replace the place holder (replace.build.js in root folder)

```<code>var replace = require('replace-in-file');
var buildVersion = process.env.BUILD_NUMBER;
const options = {
  files: 'environments/environment.ts',
  from: /{BUILD_VERSION}/g,
  to: buildVersion,
  allowEmptyPaths: false,
};

try {
  let changedFiles = replace.sync(options);
  console.log('Build version set: ' + buildVersion);
}
catch (error) {
  console.error('Error occurred:', error);
}
</code>```

Execute this node script in your build process f.e. in gulp

```<code>gulp.task('updateVersion', function (done) {
  exec('node ./replace.build.js', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    done();
  });
});
</code>```

Now you can use environment.version in your app.

Body:
I have an angular-cli application (angular version 4.0.0). I want to be able to access my environment variables in the environment.ts file created from the cli.

Example:

export SOME_VARIABLE=exampleValue

When I build my angular app I want "exampleValue" to be populated in the SOME_VARIABLE field.

// environment.ts

export const environment = {
    production: false,
    SOME_VARIABLE: process.env.SOME_VARIABLE
};

Unfortunately, process.env isn't available in this file. How can I gain access to it?

Body:
One way to solve this is to create a node script, which replaces a place holder.

This can be done with replace-in-file from npm.

A solution can look like this:

npm install replace-in-file --save-dev

Create a place holder

export const environment = {
  production: true,
  version: '{BUILD_VERSION}'
}

Create node script to replace the place holder (replace.build.js in root folder)

var replace = require('replace-in-file');
var buildVersion = process.env.BUILD_NUMBER;
const options = {
  files: 'environments/environment.ts',
  from: /{BUILD_VERSION}/g,
  to: buildVersion,
  allowEmptyPaths: false,
};

try {
  let changedFiles = replace.sync(options);
  console.log('Build version set: ' + buildVersion);
}
catch (error) {
  console.error('Error occurred:', error);
}

Execute this node script in your build process f.e. in gulp

gulp.task('updateVersion', function (done) {
  exec('node ./replace.build.js', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    done();
  });
});

Now you can use environment.version in your app.


问:
Deshuffle text with C
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

```<code>1  X
4  T
3  Z
2  L
</code>```

And I wanted to deshuffle it and output another file as so:

```<code>1  X
2  L
3  Z
4  T
</code>```

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit

答: I'd just use sort -n instead of writing a program.

Title: Deshuffle text with C

Body:
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

1  X
4  T
3  Z
2  L

And I wanted to deshuffle it and output another file as so:

1  X
2  L
3  Z
4  T

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit


问:
What does np.empty((0,shape)) in python mean?
How can the tuple with shape (0,2) be passed?

```<code>a = np.empty((0,2))
a
>>> array([], shape=(0, 2), dtype=float64)
</code>```

Also what is the difference between tuple and list while passing the shape as a parameter in np.empty()?

```<code>arr = np.empty((2,2))
arr
>>> array([[ 0.,  0.],
           [ 0.,  0.]])
arr1 = np.empty([2,2])
arr1
>>> array([[ 0.,  0.],
           [ 0.,  0.]])
</code>```

How both tuple and list gives same output?

答:
Passing a tuple with 0, such as (0, 2) as shape parameter is allowed, but the resulting array is empty since it contains 0*2 = 0  elements.  Written out in words, it's "zero rows with 2 elements in each row" where "2 elements in each row" is not of much consequence since there are no rows.

Such arrays arise when slicing goes wrong: for example,

```<code>b = np.ones((2, 2))
a = b[2:, :]
</code>```

makes a an array of shape (0, 2) as there are no values of the first index that fall in the given slice.  There is no reason to create such arrays intentionally.

There is no difference between np.empty([2, 2]) and np.empty((2, 2)), the array creation method, as many other NumPy methods, accepts a list instead of a tuple. It's still recommended to use tuples for shape parameters, because arr.shape is always a tuple.

Body:
How can the tuple with shape (0,2) be passed?

a = np.empty((0,2))
a
>>> array([], shape=(0, 2), dtype=float64)

Also what is the difference between tuple and list while passing the shape as a parameter in np.empty()?

arr = np.empty((2,2))
arr
>>> array([[ 0.,  0.],
           [ 0.,  0.]])
arr1 = np.empty([2,2])
arr1
>>> array([[ 0.,  0.],
           [ 0.,  0.]])

How both tuple and list gives same output?

Body:
Passing a tuple with 0, such as (0, 2) as shape parameter is allowed, but the resulting array is empty since it contains 0*2 = 0  elements.  Written out in words, it's "zero rows with 2 elements in each row" where "2 elements in each row" is not of much consequence since there are no rows.

Such arrays arise when slicing goes wrong: for example,

b = np.ones((2, 2))
a = b[2:, :]

makes a an array of shape (0, 2) as there are no values of the first index that fall in the given slice.  There is no reason to create such arrays intentionally.

There is no difference between np.empty([2, 2]) and np.empty((2, 2)), the array creation method, as many other NumPy methods, accepts a list instead of a tuple. It's still recommended to use tuples for shape parameters, because arr.shape is always a tuple.


问:
Sql - Have a big query which need to be filter out duplicates
I have a massive query which joins about 70 tables and returns over 200 columns:

```<code>SELECT TABLEA.ID, TABLEB.ID, TABLEC.ID  ...
FROM TABLEA LEFT JOIN TABLEB ON TABLEA.ID = TABLE.FID LEFT JOIN TABLEC ON TABLEB.ID = TABLEC.FID ...
WHERE [some conditions]
</code>```

This result has one unique primary column it should return which is TABLEA.ID. All the values in the column should be unique, but due to bad data collection there are some duplicates. So I have some ID which are duplicates and they have other columns with different values. From these duplicates I know which specific rows I need to grab and which duplicates I can discard (ex. grab the row where TABLEA.ID = 9999 and TABLEZ.SOMECOLUMN = 'JOHN DOE').

So the final resultset looks something like this:

```<code>TABLEA.ID | TABLEB.ID | TABLEZ.SOMECOLUMN .....
     1         fjash       BOB
     2         dfd         BOB
     3         34g         JOHN
     3         vfg         KIM
     3         vsd         OBI-WAN
     4         vgsdfg      NICK
     4         fg          HA
     5         hggh        HAHA
</code>```

From this I know which duplicated I need to filter out to get something like this:

```<code>TABLEA.ID | TABLEB.ID | TABLEZ.SOMECOLUMN .....
     1         fjash       BOB
     2         dfd         BOB
     3         34g         JOHN
     4         vgsdfg      NICK
     5         hggh        HAHA
</code>```

I thought this would be easy as I would simple filter them out in the where clause but it has turned out to be more complicated than I thought.

```<code> SELECT TABLEA.ID, TABLEB.ID, TABLEC.ID  ...
    FROM TABLEA LEFT JOIN TABLEB ON TABLEA.ID = TABLE.FID LEFT JOIN TABLEC ON TABLEB.ID = TABLEC.FID ...
    WHERE [some conditions]
    AND (TABLEA.ID = 9999 AND TABLEZ.SOMECOLUMN = 'JOHN DOE')
</code>```

But this only returns one row instead. I tried another combination by trying to negate it:

```<code>AND (TABLEA.ID = 9999 AND TABLEZ.SOMECOLUMN <> 'OTHER VALUE OTHER THAN JOE DOE')
</code>```

But this also does not work.

答:
Okay, I am trying to help with the pseudo code in the same language. Please try to relate.

Try using row_number over partition by id (to be unique) and filter row_number 1 values:
Try avoiding preferred value for ID because you want this column as unique in your output dataset.

Try:

```<code>SELECT TABLEA.ID, TABLEB.ID, TABLEC.ID  ...
FROM
    (SELECT TABLEA.ID, TABLEB.ID, TABLEC.ID  ...
       ,ROW_NUMBER() OVER(PARTITION BY TABLEA.ID
                     ORDER BY CASE WHEN TABLEX.SOMECOLUMN = 'Some preferred value' THEN 0 ELSE 1 END,
                              CASE WHEN TABLEZ.SOMEOTHERCOL='Some other preferred value' THEN 0 ELSE 1 END,
                              ROWNUM) RN
        FROM TABLEA LEFT JOIN TABLEB ON TABLEA.ID = TABLE.FID LEFT JOIN TABLEC
        ON TABLEB.ID = TABLEC.FID ...
        WHERE [some conditions])
WHERE RN=1;
</code>```

Body:
I have a massive query which joins about 70 tables and returns over 200 columns:

SELECT TABLEA.ID, TABLEB.ID, TABLEC.ID  ...
FROM TABLEA LEFT JOIN TABLEB ON TABLEA.ID = TABLE.FID LEFT JOIN TABLEC ON TABLEB.ID = TABLEC.FID ...
WHERE [some conditions]

This result has one unique primary column it should return which is TABLEA.ID. All the values in the column should be unique, but due to bad data collection there are some duplicates. So I have some ID which are duplicates and they have other columns with different values. From these duplicates I know which specific rows I need to grab and which duplicates I can discard (ex. grab the row where TABLEA.ID = 9999 and TABLEZ.SOMECOLUMN = 'JOHN DOE').

So the final resultset looks something like this:

TABLEA.ID | TABLEB.ID | TABLEZ.SOMECOLUMN .....
     1         fjash       BOB
     2         dfd         BOB
     3         34g         JOHN
     3         vfg         KIM
     3         vsd         OBI-WAN
     4         vgsdfg      NICK
     4         fg          HA
     5         hggh        HAHA

From this I know which duplicated I need to filter out to get something like this:

TABLEA.ID | TABLEB.ID | TABLEZ.SOMECOLUMN .....
     1         fjash       BOB
     2         dfd         BOB
     3         34g         JOHN
     4         vgsdfg      NICK
     5         hggh        HAHA

I thought this would be easy as I would simple filter them out in the where clause but it has turned out to be more complicated than I thought.

 SELECT TABLEA.ID, TABLEB.ID, TABLEC.ID  ...
    FROM TABLEA LEFT JOIN TABLEB ON TABLEA.ID = TABLE.FID LEFT JOIN TABLEC ON TABLEB.ID = TABLEC.FID ...
    WHERE [some conditions]
    AND (TABLEA.ID = 9999 AND TABLEZ.SOMECOLUMN = 'JOHN DOE')

But this only returns one row instead. I tried another combination by trying to negate it:

AND (TABLEA.ID = 9999 AND TABLEZ.SOMECOLUMN <> 'OTHER VALUE OTHER THAN JOE DOE')

But this also does not work.

Body:
Okay, I am trying to help with the pseudo code in the same language. Please try to relate.

Try using row_number over partition by id (to be unique) and filter row_number 1 values:
Try avoiding preferred value for ID because you want this column as unique in your output dataset.

Try:

SELECT TABLEA.ID, TABLEB.ID, TABLEC.ID  ...
FROM
    (SELECT TABLEA.ID, TABLEB.ID, TABLEC.ID  ...
       ,ROW_NUMBER() OVER(PARTITION BY TABLEA.ID
                     ORDER BY CASE WHEN TABLEX.SOMECOLUMN = 'Some preferred value' THEN 0 ELSE 1 END,
                              CASE WHEN TABLEZ.SOMEOTHERCOL='Some other preferred value' THEN 0 ELSE 1 END,
                              ROWNUM) RN
        FROM TABLEA LEFT JOIN TABLEB ON TABLEA.ID = TABLE.FID LEFT JOIN TABLEC
        ON TABLEB.ID = TABLEC.FID ...
        WHERE [some conditions])
WHERE RN=1;


问:
Write some "if-statement"
I want to write one script in "if-statement"

There are a lot of .html files in the ./simulations/ folder, and write end balance in the html files like this:

'end balance: 1000.00000000 (0.00%)'

'end balance: 19.21977440 (-98.08%)'

'end balance: 1135.80974233 (13.58%)'

I just want to find 'end balance: ....... (...%)'

if the end balance is 1000 or lower echo 'end balance 100 0r lwss', if it is higher, 'echo end balance bigger than 1000'.

like this:

if [ "$(egrep -n 'end balance: [0-9.]' ./simulations/*.html)" -gt 1000 ]; then
echo ' end balance bigger than 1000 '
else
echo ' end balance less than 1000 '
fi

答:
Your condition fails because the output of the command substitution is not an integer. It also isn't being applied on a per-file basis.

In meta-code, what you're looking for is probably more along the lines of:

```<code>for every HTML file, loop
  Check the balance at the end of the file.
    If it's greater than 1000, do one thing,
    Otherwise, do something else.
end loop
</code>```

In bash with grep, this might look something like:

```<code>for f in simulations/*.html; do
    if egrep -q 'end balance: (1000|[0-9]{3})\>' "$f"; then
        echo "$f: end balance > 1000"
    else
        echo "$f: end balance <= 1000 or missing"
    fi
done
</code>```

If you wanted to pull the number out of the file for numeric comparison instead of using a regex, then this might work:

```<code>for f in simulations/*.html; do
    n="$(egrep -o 'end balance: [0-9]+' "$f" | grep -o '[0-9]*')"
    if [[ -z "$n" ]]; then
        echo "$f: no balance found"
    elif [[ $n -gt 1000 ]]; then
        echo "$f: end balance > 1000"
    else
        echo "$f: end balance <= 1000"
    fi
done
</code>```

In both cases, you'll get a line of output for each HTML file that is processed.

Title: Write some "if-statement"

Body:
Your condition fails because the output of the command substitution is not an integer. It also isn't being applied on a per-file basis.

In meta-code, what you're looking for is probably more along the lines of:

for every HTML file, loop
  Check the balance at the end of the file.
    If it's greater than 1000, do one thing,
    Otherwise, do something else.
end loop

In bash with grep, this might look something like:

for f in simulations/*.html; do
    if egrep -q 'end balance: (1000|[0-9]{3})\>' "$f"; then
        echo "$f: end balance > 1000"
    else
        echo "$f: end balance <= 1000 or missing"
    fi
done

If you wanted to pull the number out of the file for numeric comparison instead of using a regex, then this might work:

for f in simulations/*.html; do
    n="$(egrep -o 'end balance: [0-9]+' "$f" | grep -o '[0-9]*')"
    if [[ -z "$n" ]]; then
        echo "$f: no balance found"
    elif [[ $n -gt 1000 ]]; then
        echo "$f: end balance > 1000"
    else
        echo "$f: end balance <= 1000"
    fi
done

In both cases, you'll get a line of output for each HTML file that is processed.