问:
box-shadow glitch when interacting
I have a vignette on my stock image created with box-shadow. It looks good, but sometimes when I press button that is on top of that vignette or when I select text then it dissapears only in the region of that selection which looks bad.

```<code><div>
    <div class="stock-image flex-container">
      <div class="column">
        <div class="row column">
          <div>
            <h1 class="welcome">Connect with people</h1>
          </div>
         </div>
        </div>
     </div>
</div>
</code>```

Css:

```<code>.stock-image {
    width: 100%;
    height: 32em;
    background: linear-gradient(90deg, rgba(22, 156, 202,0.65), rgba(22, 156, 202,0.45)),#00A7E1 url(../../assets/img/home/stock-image.jpg) no-repeat center center;
    background-size: cover;
    box-shadow: inset 0 0 30em 0.7em #000;
}
</code>```

Sometimes when I select Connect with people it removes shadow inside the selected area and after deselecting it, the shadow is still missing.

Also I cannot just create vignette in photoshop, because the image is visible depending on device's screen size that user uses, so often only part of the image is visible.

EDIT:
As a workaround I used two linear-gradients:

```<code>linear-gradient(to right, rgba(0,0,0,0.75) 0%, rgba(0,0,0,0.15) 15%, rgba(0,0,0,0.0) 35%, rgba(0,0,0,0.0) 65%, rgba(0,0,0,0.15) 85%, rgba(0,0,0,0.75) 100%)
linear-gradient(to bottom, rgba(0,0,0,0.75) 0%, rgba(0,0,0,0.15) 15%, rgba(0,0,0,0.0) 35%, rgba(0,0,0,0.0) 65%, rgba(0,0,0,0.15) 85%, rgba(0,0,0,0.75) 100%)
</code>```

It doesn't look as good as I would want, but I guess it's just a matter of tweeking parameters.

答:
I don't have a solution for your problem but it seems to be linked with a known issue of chrome : https://code.google.com/p/chromium/issues/detail?id=442335

Also quoted in this post :

 border-radius with box-shadow inset pixelized / rugged

So the design your using is considered as a rendering bug.

Here you can compare the render of your code with different browser:

chrome : http://imgur.com/Bu9b0hB

firefox : http://imgur.com/ChJclHz

The firefox one is considered 'normal'.

Also your issue with the shadow and selections doesn't seems to appear on firefox.

To get an extendible image you might want to use 9-patch images, which is a technology used notably on android. I don't really know much about it...

Title: box-shadow glitch when interacting

Body:
I have a vignette on my stock image created with box-shadow. It looks good, but sometimes when I press button that is on top of that vignette or when I select text then it dissapears only in the region of that selection which looks bad.

Connect with people

Css:

.stock-image {
    width: 100%;
    height: 32em;
    background: linear-gradient(90deg, rgba(22, 156, 202,0.65), rgba(22, 156, 202,0.45)),#00A7E1 url(../../assets/img/home/stock-image.jpg) no-repeat center center;
    background-size: cover;
    box-shadow: inset 0 0 30em 0.7em #000;
}

Sometimes when I select Connect with people it removes shadow inside the selected area and after deselecting it, the shadow is still missing.

Also I cannot just create vignette in photoshop, because the image is visible depending on device's screen size that user uses, so often only part of the image is visible.

EDIT:
As a workaround I used two linear-gradients:

linear-gradient(to right, rgba(0,0,0,0.75) 0%, rgba(0,0,0,0.15) 15%, rgba(0,0,0,0.0) 35%, rgba(0,0,0,0.0) 65%, rgba(0,0,0,0.15) 85%, rgba(0,0,0,0.75) 100%)
linear-gradient(to bottom, rgba(0,0,0,0.75) 0%, rgba(0,0,0,0.15) 15%, rgba(0,0,0,0.0) 35%, rgba(0,0,0,0.0) 65%, rgba(0,0,0,0.15) 85%, rgba(0,0,0,0.75) 100%)

It doesn't look as good as I would want, but I guess it's just a matter of tweeking parameters.


来源: stackexchange

问:
Google analytics, adwords, facebook data on my server
I've got client who has several different websites, each website having Google analytics account.
Our marketing department is also running Google Adwords/Facebook/Instagram ads for each of those websites.

I want data/leads from Google and Facebook on my local server. I also want real-time data that should automatically update from Google & Facebook with fixed time interval.

I've been Googling and experimenting with the Analytics API docs, but no luck.

Any one please help me to find better solution.

#This question is not for this website but I didn't find any other option.

Thank you.

答:
There are several services that your are looking for. Use this info like a getting started. Every service has his own simplicities and complexities.

Adwords

Use Campaign Performance Report to download your campaign's metrics. See examples in PHP, Java, Python, etc.

Analytics

Use RealTime API to get real time data. See examples

Use Core Reporting API to get general data. See examples

There is a very useful tool: Query Explorer to see Analytics API working

Facebook / Instagram

Use Ads Insights API to download your campaigns's metrics. See examples

ContentLicense: CC BY-SA 3.0


问:
Displaying text from a sf::Text object from another Class. SFML
I am trying to create a class that will create a black box with some white text in it. It would eventually be able to scale the size of the box depending on the string that is sent to the class. But, to begin with, I do not know why the text does not display. I appreciate the help.

Here is the TextBox.h

```<code>class TextBox{

public:

sf::RectangleShape rect;
sf::Text text;
sf::Font font;

TextBox(std::string str, sf::Font f);
sf::Text getText();
</code>```

This is the TextBox Constructor that is found in the TextBox.cpp. The sf::Font I am sending to the constructor is the font that was set by SFML.

```<code>#include "TextBox.h"
#include "string"

TextBox::TextBox(std::string str, sf::Font font){

rect.setFillColor(sf::Color::Black);
rect.setPosition(20, 20);
rect.setSize(sf::Vector2f(120,120));

text.setFont(font);
text.setString(str);
text.setCharacterSize(24);
text.setFillColor(sf::Color::White);

text.setPosition(rect.getPosition());

}
</code>```

This is the code in the main.cpp that should be displaying both the Rect and the Text

```<code>sf::Font font;
if (!font.loadFromFile(resourcePath() + "sansation.ttf")) {
    return EXIT_FAILURE;
}

TextBox textBox("This Box", font);
textBox.text.setStyle(sf::Text::Bold);
// Start the game loop
while (window.isOpen())
{
    // Process events
    sf::Event event;
    while (window.pollEvent(event))
    {
        // Close window: exit
        if (event.type == sf::Event::Closed) {
            window.close();
        }

        // Escape pressed: exit
        if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
            window.close();
        }
    }

    // Clear screen
    window.clear();

    window.draw(textBox.rect);
    window.draw(textBox.text);

    // Update the window
    window.display();
</code>```

I have tried using a public getText() method that returns a sf::Text object, but it does not solve the issue.
Also, the modifications I do for the rect do work and the rect is displayed. The text isn't.

Thank you and Cheers

答:
From sf::Text::setFont() method:

The font argument refers to a font that must exist as long as the text uses it. Indeed, the text doesn't store its own copy of the font, but rather keeps a pointer to the one that you passed to this function. If the font is destroyed and the text tries to use it, the behavior is undefined.

.

In your TextBox constructor, you pass font as a copy f, after initialize textBox, the font copy f will be destroyed, hence your textBox.text is not displayed.

Fixing it is simple: pass font as it is by using pass by (constant) reference:
TextBox(std::string str, const sf::Font& f);

(You might want to pass std::string as const reference, too)

Body:
I am trying to create a class that will create a black box with some white text in it. It would eventually be able to scale the size of the box depending on the string that is sent to the class. But, to begin with, I do not know why the text does not display. I appreciate the help.

Here is the TextBox.h

class TextBox{

public:

sf::RectangleShape rect;
sf::Text text;
sf::Font font;

TextBox(std::string str, sf::Font f);
sf::Text getText();

This is the TextBox Constructor that is found in the TextBox.cpp. The sf::Font I am sending to the constructor is the font that was set by SFML.

#include "TextBox.h"
#include "string"

TextBox::TextBox(std::string str, sf::Font font){

rect.setFillColor(sf::Color::Black);
rect.setPosition(20, 20);
rect.setSize(sf::Vector2f(120,120));

text.setFont(font);
text.setString(str);
text.setCharacterSize(24);
text.setFillColor(sf::Color::White);

text.setPosition(rect.getPosition());

}

This is the code in the main.cpp that should be displaying both the Rect and the Text

sf::Font font;
if (!font.loadFromFile(resourcePath() + "sansation.ttf")) {
    return EXIT_FAILURE;
}

TextBox textBox("This Box", font);
textBox.text.setStyle(sf::Text::Bold);
// Start the game loop
while (window.isOpen())
{
    // Process events
    sf::Event event;
    while (window.pollEvent(event))
    {
        // Close window: exit
        if (event.type == sf::Event::Closed) {
            window.close();
        }

        // Escape pressed: exit
        if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
            window.close();
        }
    }

    // Clear screen
    window.clear();

    window.draw(textBox.rect);
    window.draw(textBox.text);

    // Update the window
    window.display();

I have tried using a public getText() method that returns a sf::Text object, but it does not solve the issue.
Also, the modifications I do for the rect do work and the rect is displayed. The text isn't.

Thank you and Cheers


问:
lsb_release of the host OS in a Docker
I want to get the Operating System that I'm running on inside a Docker.

This is what my docker-compose looks like and I'm inheriting from the python:2.7 image

```<code> version: '2'
 services:
   robot-configuration-interface:
     build: '.'
     restart: always
     network_mode: 'host'
     ports:
       - 8000:80
     environment:
       - REDIS_HOST=localhost
       - DEBUG=true
     volumes:
       - ~/logs/fetchcore-server:/var/log/supervisor
       - /var/run/docker.sock:/var/run/docker.sock
       - /opt/ros/indigo:/opt/ros/indigo
       - /etc/environment:/etc/environment
       - /etc/NetworkManager/system-connections/:/etc/NetworkManager/system-connections/
       - /lib:/lib
       - /usr/lib/:/usr/lib
       - /usr/bin/:/usr/bin/
       - /var/run/:/var/run/
     privileged: true
     user: root
</code>```

The lsb_release -d command returns Debian GNU/Linux 8.7 (n/a) instead of
Ubuntu 14.04.5 LTS even though i'm mounting /usr/bin

答: The answer is mounting /etc/lsb-release to the volumes

Title: lsb_release of the host OS in a Docker

Body:
I want to get the Operating System that I'm running on inside a Docker.

This is what my docker-compose looks like and I'm inheriting from the python:2.7 image

 version: '2'
 services:
   robot-configuration-interface:
     build: '.'
     restart: always
     network_mode: 'host'
     ports:
       - 8000:80
     environment:
       - REDIS_HOST=localhost
       - DEBUG=true
     volumes:
       - ~/logs/fetchcore-server:/var/log/supervisor
       - /var/run/docker.sock:/var/run/docker.sock
       - /opt/ros/indigo:/opt/ros/indigo
       - /etc/environment:/etc/environment
       - /etc/NetworkManager/system-connections/:/etc/NetworkManager/system-connections/
       - /lib:/lib
       - /usr/lib/:/usr/lib
       - /usr/bin/:/usr/bin/
       - /var/run/:/var/run/
     privileged: true
     user: root

The lsb_release -d command returns Debian GNU/Linux 8.7 (n/a) instead of
Ubuntu 14.04.5 LTS even though i'm mounting /usr/bin


问:
Using rawpy to convert multiple raw .NEF Images to TIFF
I have been searching through this forum but cannot find a relevant answer to my problem. I have only found solutions for single file conversions.

I want to convert a directory of Nikon RAW images (.NEF) into TIFF (.tiff).
This can be achieved with the rawpy plugin apparently. I am not well versed in python and have done my best. You will probably find my script laughable :)

I'd like to ideally be able to paste the directory path into the command line and have it convert everything for me, into 16-bit tiffs.

```<code>import rawpy
import imageio

paths = 'C:\Users\Jake\Desktop\Exposuretests\Darks'

for i in paths:
    with rawpy.imread(paths) as raw:
        rgb = raw.postprocess()
imageio.imsave(paths + '.tiff', rgb)
</code>```

Thanks all in advance for any help. I am sure this is quite simple for those versed in python!

答:
You can do it very simply without having to write any Python or loops if you use ImageMagick which is installed on most Linux distros and is available for macOS and Windows.

In Terminal, simply type:

```<code>magick mogrify -format tif *NEF
</code>```

Body:
I have been searching through this forum but cannot find a relevant answer to my problem. I have only found solutions for single file conversions.

I want to convert a directory of Nikon RAW images (.NEF) into TIFF (.tiff).
This can be achieved with the rawpy plugin apparently. I am not well versed in python and have done my best. You will probably find my script laughable :)

I'd like to ideally be able to paste the directory path into the command line and have it convert everything for me, into 16-bit tiffs.

import rawpy
import imageio

paths = 'C:\Users\Jake\Desktop\Exposuretests\Darks'

for i in paths:
    with rawpy.imread(paths) as raw:
        rgb = raw.postprocess()
imageio.imsave(paths + '.tiff', rgb)

Thanks all in advance for any help. I am sure this is quite simple for those versed in python!

Body:
You can do it very simply without having to write any Python or loops if you use ImageMagick which is installed on most Linux distros and is available for macOS and Windows.

In Terminal, simply type:

magick mogrify -format tif *NEF


问:
Explain this AVR macro for linked list of strings
Hi I'm taking a microprocessor class and trying to create a recursive function that returns the length of some strings that are in a linked-list structure.

I've been given this macro to work with and was hoping somebody could help me to understand it. Particularly I'd like to know how exactly using this macro creates a linked-list.

```<code>.set NEXT_STRING = 0x0000
.macro defstring
    .set T = PC
    .dw NEXT_STRING << 1
    .set NEXT_STRING = T
    .if strlen(@0) & 1
    .db @0, 0
    .else
    .db @0, 0, 0
    .endif
.endmacro
</code>```

The ways it's used is as follows:

defstring "somestring"

defstring "another"

Then supposedly, a linked-list is created with these strings held as data on each node.

Any help appreciated, Thanks!

答:
The line below declares an assembler constant called NEXT_STRING with a value of 0.  Wherever NEXT_STRING appears in the program, it will be replaced by 0.

```<code>.set NEXT_STRING = 0x0000
</code>```

I think the name NEXT_STRING could be confusing.  It's actually a pointer to the last string you declared in your assembly file.

This line sets T to equal the current program counter (PC).  So that is the current location in flash that the assembler is writing to.

```<code>.set T = PC
</code>```

The .dw directive below writes a 16-bit word to flash, with the specified value.  This word will store a pointer to the next node in the list, so we set it equal to NEXT_STRING.  The bit shift part is probably due to the fact that the PC counts in words, but AVR pointers count in bytes, so you have to multiply by 2 when turning a PC value into a pointer.  This is the first part of code that actually wrote anything to flash.

```<code>.dw NEXT_STRING << 1
</code>```

The first pointer you generate will be a null pointer because NEXT_STRING is 0.  But then we set NEXT_STRING equal to T, so that when you call the macro the next time, the pointer will point to the place in flash where the last pointer is stored.

```<code>.set NEXT_STRING = T
</code>```

At this point, I think you can see that a linked list is being formed.  The first time you call defstring, a null pointer is stored in flash, which will some day be the end of the linked list.  Then you call it again, and it makes a second pointer that points to the first.  Then you call it again, and it makes a third pointer that points to the second.

Linked lists are only useful if there is some data in them, so the next thing the macro does is add the string data using the code below.  Whoever wrote this decided that they wanted to always end the string with a null byte (which is standard for C-language strings) and they also decided to add an extra padding byte if the length of the string is odd, ensuring the space taken by a node in the linked list is always even.  This is called 2-alignment and it might make it easier for the AVR to load the 2-byte pointer.  I am not convinced that this alignment is necessary, but if it is, I would prefer to use the .align 2 directive at the beginning and/or end of the macro instead of doing this hack.

```<code>.if strlen(@0) & 1
.db @0, 0
.else
.db @0, 0, 0
.endif
</code>```

Aside:  This is not the only way to store a list of strings in an AVR.  A more standard approach that you see in C programs would be to have all the strings in one place and then have an array of pointers in another place.  The length of the array would either be a constant or the array could be terminated by a null pointer.  Another option, used by REG_MULTI_SZ data in the Windows Registry, is to just store the strings one after another in memory, with no pointers, separated by null bytes, and ended by two null bytes.  Each method gives you different space/performance tradeoffs and the last one cannot store an empty string.

Body:
Hi I'm taking a microprocessor class and trying to create a recursive function that returns the length of some strings that are in a linked-list structure.

I've been given this macro to work with and was hoping somebody could help me to understand it. Particularly I'd like to know how exactly using this macro creates a linked-list.

.set NEXT_STRING = 0x0000
.macro defstring
    .set T = PC
    .dw NEXT_STRING << 1
    .set NEXT_STRING = T
    .if strlen(@0) & 1
    .db @0, 0
    .else
    .db @0, 0, 0
    .endif
.endmacro

The ways it's used is as follows:

defstring "somestring"

defstring "another"

Then supposedly, a linked-list is created with these strings held as data on each node.

Any help appreciated, Thanks!

Body:
The line below declares an assembler constant called NEXT_STRING with a value of 0.  Wherever NEXT_STRING appears in the program, it will be replaced by 0.

.set NEXT_STRING = 0x0000

I think the name NEXT_STRING could be confusing.  It's actually a pointer to the last string you declared in your assembly file.

This line sets T to equal the current program counter (PC).  So that is the current location in flash that the assembler is writing to.

.set T = PC

The .dw directive below writes a 16-bit word to flash, with the specified value.  This word will store a pointer to the next node in the list, so we set it equal to NEXT_STRING.  The bit shift part is probably due to the fact that the PC counts in words, but AVR pointers count in bytes, so you have to multiply by 2 when turning a PC value into a pointer.  This is the first part of code that actually wrote anything to flash.

.dw NEXT_STRING << 1

The first pointer you generate will be a null pointer because NEXT_STRING is 0.  But then we set NEXT_STRING equal to T, so that when you call the macro the next time, the pointer will point to the place in flash where the last pointer is stored.

.set NEXT_STRING = T

At this point, I think you can see that a linked list is being formed.  The first time you call defstring, a null pointer is stored in flash, which will some day be the end of the linked list.  Then you call it again, and it makes a second pointer that points to the first.  Then you call it again, and it makes a third pointer that points to the second.

Linked lists are only useful if there is some data in them, so the next thing the macro does is add the string data using the code below.  Whoever wrote this decided that they wanted to always end the string with a null byte (which is standard for C-language strings) and they also decided to add an extra padding byte if the length of the string is odd, ensuring the space taken by a node in the linked list is always even.  This is called 2-alignment and it might make it easier for the AVR to load the 2-byte pointer.  I am not convinced that this alignment is necessary, but if it is, I would prefer to use the .align 2 directive at the beginning and/or end of the macro instead of doing this hack.

.if strlen(@0) & 1
.db @0, 0
.else
.db @0, 0, 0
.endif

Aside:  This is not the only way to store a list of strings in an AVR.  A more standard approach that you see in C programs would be to have all the strings in one place and then have an array of pointers in another place.  The length of the array would either be a constant or the array could be terminated by a null pointer.  Another option, used by REG_MULTI_SZ data in the Windows Registry, is to just store the strings one after another in memory, with no pointers, separated by null bytes, and ended by two null bytes.  Each method gives you different space/performance tradeoffs and the last one cannot store an empty string.


问:
win32 resource file help
on this website, under the "Edit Control" title, there are a couple of lines of code like this..

```<code>case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;
</code>```

I know that this method of creating buttons and such are done on the fly, But I was wondering how you would do it without doing it like this, instead using a resource file?.
In the Forgers Win32 tutorial it shows how to make a menu using a resource file, and how to describe a dialog box etc, But I cant seem to put any controls on the main(parent) window using a resource file??.

for example I have the following .rc file

```<code>#include "resource.h"
ID_MENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit", ID_FILE_EXIT
    END
    POPUP "&About"
    BEGIN
        MENUITEM "&Information", ID_ABOUT_INFO
    END
END

ID_ABOUT_INFO DIALOG DISCARDABLE  0,0,250,250
CAPTION "Information"
BEGIN
    CTEXT "some text",ID_BLA,15,15,144,33
END

//this is all fine but how do I decribe the main window?, instead of the menu and dialog boxes?.
</code>```

How do I describe the main window instead of creating things on the fly?. Is there some kind of keyword?

答:
TheForger has added all his example code in a zip file, you can download them and check it out.

You still need to create the window, TheForger does this as well, but then he includes the icons and menus in the WNDCLASSEX struct which is passed to the window that is to be created. This is then collected from the resource file (.rc file) via the resouce.h file.

MSDN has a section about resource files as well, and as you can see

Resources can be composed of a wide
  range of elements, including interface
  elements that provide information to
  the user (for example a bitmap, icon,
  or cursor); custom resources that
  contain data an application needs;
  version resources that are used by
  setup APIs; and menu and dialog box
  resources.

The main window(s) are not mentioned.

ContentLicense: CC BY-SA 2.5

Title: win32 resource file help

Body:
on this website, under the "Edit Control" title, there are a couple of lines of code like this..

case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;

I know that this method of creating buttons and such are done on the fly, But I was wondering how you would do it without doing it like this, instead using a resource file?.
In the Forgers Win32 tutorial it shows how to make a menu using a resource file, and how to describe a dialog box etc, But I cant seem to put any controls on the main(parent) window using a resource file??.

for example I have the following .rc file

#include "resource.h"
ID_MENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit", ID_FILE_EXIT
    END
    POPUP "&About"
    BEGIN
        MENUITEM "&Information", ID_ABOUT_INFO
    END
END

ID_ABOUT_INFO DIALOG DISCARDABLE  0,0,250,250
CAPTION "Information"
BEGIN
    CTEXT "some text",ID_BLA,15,15,144,33
END

//this is all fine but how do I decribe the main window?, instead of the menu and dialog boxes?.

How do I describe the main window instead of creating things on the fly?. Is there some kind of keyword?


问:
Allocating memory to structure within structure
I'm trying to allocate memory for the code,of which i've only included excerpts from the actual program, that follows below, the problem I am having is that i don't know how to allocate memory to the type Key that lies within BStree_node this leads to the issue of segmentation errors when i try to assign values to variables within Key.</p>

```<code>typedef int Data_Item;
typedef char* Sub_Key;
typedef struct {Sub_Key key1; Sub_Key key2;} Key;

struct BStree_node{
    Key key;
    Data_Item data;
    struct BStree_node *left, *right;
}
typedef struct BStree_node BStree_node;
typedef BStree_node** BStree;

BStree bs_tree_ini(void){
    BStree tempTreePointer;
    tempTreePointer = malloc(sizeof(BStree_node*));

    BStree_node *tempNode;
    tempNode = malloc(sizeof(BStree_node));
    tempNode = NULL;

    tempTreePointer = &tempNode;

    return tempTreePointer;

}
</code>```

答:
You could initialize your node like this, using calloc to zero the memory to initialize all the fields properly:

```<code>BStree_node *init_node()
{
   BStree_node *rval = calloc(1,sizeof(BStree_node)); // so all data & pointers are zeroed
   return rval;
}
</code>```

use it like this: init main, and only left. right stays zeroed: no right node for that main node.

```<code>int main()
{
    BStree_node *head = init_node();
    head->left = init_node();
    ...

    return 0;
}
</code>```

Body:
I'm trying to allocate memory for the code,of which i've only included excerpts from the actual program, that follows below, the problem I am having is that i don't know how to allocate memory to the type Key that lies within BStree_node this leads to the issue of segmentation errors when i try to assign values to variables within Key.

typedef int Data_Item;
typedef char* Sub_Key;
typedef struct {Sub_Key key1; Sub_Key key2;} Key;

struct BStree_node{
    Key key;
    Data_Item data;
    struct BStree_node *left, *right;
}
typedef struct BStree_node BStree_node;
typedef BStree_node** BStree;

BStree bs_tree_ini(void){
    BStree tempTreePointer;
    tempTreePointer = malloc(sizeof(BStree_node*));

    BStree_node *tempNode;
    tempNode = malloc(sizeof(BStree_node));
    tempNode = NULL;

    tempTreePointer = &tempNode;

    return tempTreePointer;

}

Body:
You could initialize your node like this, using calloc to zero the memory to initialize all the fields properly:

BStree_node *init_node()
{
   BStree_node *rval = calloc(1,sizeof(BStree_node)); // so all data & pointers are zeroed
   return rval;
}

use it like this: init main, and only left. right stays zeroed: no right node for that main node.

int main()
{
    BStree_node *head = init_node();
    head->left = init_node();
    ...

    return 0;
}


问:
Switch Python Version for Vim & Syntastic
Is it possible to change the python version used by syntastic for syntax checking?

As the Issue  https://github.com/scrooloose/syntastic/issues/385 indicates I could use virtual-env. But is it also possible just with syntastic or vim commands?

答:
In spite of all the answers here, I still find the recommendation from the FAQ to be the best. I have added this to my .vimrc so that I can easily switch between python versions.

```<code>function Py2()
  let g:syntastic_python_python_exec = '/usr/local/bin/python2.7'
endfunction

function Py3()
  let g:syntastic_python_python_exec = '/usr/local/bin/python3.6'
endfunction

call Py3()   " default to Py3 because I try to use it when possible
</code>```

With those functions installed, it's easy to switch python version right within vim with :call Py2() or :call Py3() depending on what I need at the moment. No need to exit vim and activate a different virtualenv as the popular answer would have you do.

Body:
In spite of all the answers here, I still find the recommendation from the FAQ to be the best. I have added this to my .vimrc so that I can easily switch between python versions.

function Py2()
  let g:syntastic_python_python_exec = '/usr/local/bin/python2.7'
endfunction

function Py3()
  let g:syntastic_python_python_exec = '/usr/local/bin/python3.6'
endfunction

call Py3()   " default to Py3 because I try to use it when possible

With those functions installed, it's easy to switch python version right within vim with :call Py2() or :call Py3() depending on what I need at the moment. No need to exit vim and activate a different virtualenv as the popular answer would have you do.


问:
get source of selected file in ionicframwork
I am building a mobile app using ionic. One of the usecase is to let the user browse a file and upload it to the backend server (which exposes a rest service).
On the UI, I am using the html file tag.

<input type="file" ng-select="uploadFile($files)" multiple>```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>.controller('UploadDocCtrl', function ($scope, $cordovaFileTransfer) {

  $scope.uploadFile = function(files) {
   console.log("selected file "+files);
   // hard coded file path "/android_asset/www/img/ionic.pdf" to be replaced with the user selected file
   $cordovaFileTransfer.upload(restServiceEndpoint, "/android_asset/www/img/ionic.pdf", properties).then(function(result) {
   console.log("SUCCESS: " + JSON.stringify(result.response));
  }, function(err) {
        console.log("ERROR: " + JSON.stringify(err));
   }, function (progress) {
// constant progress updates
  });
});</code>```

The problem is that I am not able to get a reference to the selected file. Can someone please help with the steps to achieve this. Thanks!

答:
Keep file in www folder which has index.html file.

then just give path like "ionic.pdf"

```<code>.controller('UploadDocCtrl', function ($scope, $cordovaFileTransfer) {

  $scope.uploadFile = function(files) {
   console.log("selected file "+files);
   // hard coded file path "/android_asset/www/img/ionic.pdf" to be replaced with the user selected file
   $cordovaFileTransfer.upload(restServiceEndpoint, "ionic.pdf", properties).then(function(result) {
   console.log("SUCCESS: " + JSON.stringify(result.response));
  }, function(err) {
        console.log("ERROR: " + JSON.stringify(err));
   }, function (progress) {
// constant progress updates
  });
});
</code>```

Body:
I am building a mobile app using ionic. One of the usecase is to let the user browse a file and upload it to the backend server (which exposes a rest service).
On the UI, I am using the html file tag.

<input type="file" ng-select="uploadFile($files)" multiple>

.controller('UploadDocCtrl', function ($scope, $cordovaFileTransfer) {

  $scope.uploadFile = function(files) {
   console.log("selected file "+files);
   // hard coded file path "/android_asset/www/img/ionic.pdf" to be replaced with the user selected file
   $cordovaFileTransfer.upload(restServiceEndpoint, "/android_asset/www/img/ionic.pdf", properties).then(function(result) {
   console.log("SUCCESS: " + JSON.stringify(result.response));
  }, function(err) {
        console.log("ERROR: " + JSON.stringify(err));
   }, function (progress) {
// constant progress updates
  });
});

The problem is that I am not able to get a reference to the selected file. Can someone please help with the steps to achieve this. Thanks!

Body:
Keep file in www folder which has index.html file.

then just give path like "ionic.pdf"

.controller('UploadDocCtrl', function ($scope, $cordovaFileTransfer) {

  $scope.uploadFile = function(files) {
   console.log("selected file "+files);
   // hard coded file path "/android_asset/www/img/ionic.pdf" to be replaced with the user selected file
   $cordovaFileTransfer.upload(restServiceEndpoint, "ionic.pdf", properties).then(function(result) {
   console.log("SUCCESS: " + JSON.stringify(result.response));
  }, function(err) {
        console.log("ERROR: " + JSON.stringify(err));
   }, function (progress) {
// constant progress updates
  });
});


问:
ImportError: No module named six
I'm trying to build OpenERP project, done with dependencies. It's giving this error now

```<code>Traceback (most recent call last):
  File "openerp-client.py", line 105, in <module>
  File "modules\__init__.pyo", line 23, in <module>
  File "modules\gui\__init__.pyo", line 22, in <module>
  File "modules\gui\main.pyo", line 33, in <module>
  File "rpc.pyo", line 29, in <module>
  File "common\__init__.pyo", line 22, in <module>
  File "common\common.pyo", line 26, in <module>
  File "tools\__init__.pyo", line 28, in <module>
  File "dateutil\relativedelta.pyo", line 12, in <module>
ImportError: No module named six
</code>```

Could someone guide what's wrong and how it can be fixed???

答:
If pip "says" six is installed but you're still getting:

ImportError: No module named six.moves

try re-installing six (worked for me):

```<code>pip uninstall six
pip install six
</code>```

Title: ImportError: No module named six

Body:
I'm trying to build OpenERP project, done with dependencies. It's giving this error now

Traceback (most recent call last):
  File "openerp-client.py", line 105, in <module>
  File "modules\__init__.pyo", line 23, in <module>
  File "modules\gui\__init__.pyo", line 22, in <module>
  File "modules\gui\main.pyo", line 33, in <module>
  File "rpc.pyo", line 29, in <module>
  File "common\__init__.pyo", line 22, in <module>
  File "common\common.pyo", line 26, in <module>
  File "tools\__init__.pyo", line 28, in <module>
  File "dateutil\relativedelta.pyo", line 12, in <module>
ImportError: No module named six

Could someone guide what's wrong and how it can be fixed???

Body:
If pip "says" six is installed but you're still getting:

ImportError: No module named six.moves

try re-installing six (worked for me):

pip uninstall six
pip install six


问:
How can I draw a arrow for showing incoming/ outgoing calls
I'm creating an app that shows Call Log.

In most of the contacts app we see arrows representing incoming/outgoing/missed calls.

where can I get them or can I create them using drawables or something?

答: If you are talking about icons, you can try Google Material Icons. It is the standard library of icons recommended by Google.</p>


问:
Is `/tmp` the right place for UNIX-domain socket files?
When using UNIX sockets for IPC communication, a file must be created in the file system. Many examples out there on the Internet suggest /tmp as a good place to place sockets in. Some suggest to use /tmp/specific_folder with 700 permissions to keep /tmp clean and the sockets safe from other users access.

However, is that reliable? Can't the OS remove any file in there at any moment? Let us suppose those files are to persist in there for days or months and some might not be used for communication during long periods (i.e.: days).

Also, storing those files in a local user folder (for example, in ./.hidden_sockets/) has the disadvantage of not cleaning those files in case, for example, the system crashes. Not even after system reboot.

Where would you put those files? Is there a standard/preferred way?

答:
When sticky bit is set on a folder then only the owner of the file and root can remove the file from that directory and by default /tmp directory is protected with sticky bit.
That is why it is suggested to put the socket file in /tmp folder so that only the owner and root have the permission to remove it but everyone can access it.

```<code>drwxrwxrwt. 25 root root 720 Mar 30 23:36 /tmp/
---------^--
this t indicate sticky bit ###this 1 in "chmod 1777 dir" used to set sticky bit
</code>```

For complete story check the below step by step commands -
Consider we have 3 users root, a and b.

```<code>[root@localhost ~]# mkdir /test
[root@localhost ~]# chmod 777 /test/
[root@localhost ~]# su - a
[a@localhost ~]$ cd /test/
[a@localhost test]$ touch a.txt
[a@localhost test]$ ls -ltr a.txt
-rw-rw-r--. 1 a a 0 Mar 30 17:25 a.txt
[a@localhost test]$ su - b
[b@localhost ~]$ cd /test/
[b@localhost test]$ touch b.txt
[b@localhost test]$ rm a.txt
rm: remove write-protected regular empty file 'a.txt'? y
[b@localhost test]$ su - a
[a@localhost ~]$ cd /test/
[a@localhost test]$ ll
-rw-rw-r--. 1 b b 0 Mar 30 17:25 b.txt
[a@localhost test]$ rm b.txt
rm: remove write-protected regular empty file 'b.txt'? y
[a@localhost test]$ su - root
[root@localhost ~]# chmod 1777 /test/ ####setting sticky bit
[root@localhost ~]# cd /test/
[root@localhost test]# su a
[a@localhost test]$ pwd
/test
[a@localhost test]$ touch a.txt
[a@localhost test]$ ll
-rw-rw-r--. 1 a a 0 Mar 30 17:27 a.txt
[root@localhost test]# su b
[b@localhost test]$ touch b.txt
[b@localhost test]$ ll
-rw-rw-r--. 1 a a 0 Mar 30 17:27 a.txt
-rw-rw-r--. 1 b b 0 Mar 30 17:27 b.txt
[b@localhost test]$ rm a.txt
rm: remove write-protected regular empty file 'a.txt'? y
rm: cannot remove 'a.txt': Operation not permitted
</code>```

(b user is not able to remove the file because we have set the sticky
  bit on the directory test)

Body:
When sticky bit is set on a folder then only the owner of the file and root can remove the file from that directory and by default /tmp directory is protected with sticky bit.
That is why it is suggested to put the socket file in /tmp folder so that only the owner and root have the permission to remove it but everyone can access it.

drwxrwxrwt. 25 root root 720 Mar 30 23:36 /tmp/
---------^--
this t indicate sticky bit ###this 1 in "chmod 1777 dir" used to set sticky bit

For complete story check the below step by step commands -
Consider we have 3 users root, a and b.

[root@localhost ~]# mkdir /test
[root@localhost ~]# chmod 777 /test/
[root@localhost ~]# su - a
[a@localhost ~]$ cd /test/
[a@localhost test]$ touch a.txt
[a@localhost test]$ ls -ltr a.txt
-rw-rw-r--. 1 a a 0 Mar 30 17:25 a.txt
[a@localhost test]$ su - b
[b@localhost ~]$ cd /test/
[b@localhost test]$ touch b.txt
[b@localhost test]$ rm a.txt
rm: remove write-protected regular empty file 'a.txt'? y
[b@localhost test]$ su - a
[a@localhost ~]$ cd /test/
[a@localhost test]$ ll
-rw-rw-r--. 1 b b 0 Mar 30 17:25 b.txt
[a@localhost test]$ rm b.txt
rm: remove write-protected regular empty file 'b.txt'? y
[a@localhost test]$ su - root
[root@localhost ~]# chmod 1777 /test/ ####setting sticky bit
[root@localhost ~]# cd /test/
[root@localhost test]# su a
[a@localhost test]$ pwd
/test
[a@localhost test]$ touch a.txt
[a@localhost test]$ ll
-rw-rw-r--. 1 a a 0 Mar 30 17:27 a.txt
[root@localhost test]# su b
[b@localhost test]$ touch b.txt
[b@localhost test]$ ll
-rw-rw-r--. 1 a a 0 Mar 30 17:27 a.txt
-rw-rw-r--. 1 b b 0 Mar 30 17:27 b.txt
[b@localhost test]$ rm a.txt
rm: remove write-protected regular empty file 'a.txt'? y
rm: cannot remove 'a.txt': Operation not permitted

(b user is not able to remove the file because we have set the sticky
  bit on the directory test)


问:
Is this string Base64? How can I tell what is the encoding used?
This is a puzzle to me and I am really annoyed that I cannot solve it! So, if anyone has some free time I would like to here some suggestions on how to solve it!

I use a software that stores the password in an oracle database. The password field is of type Varchar2(100 char). It seems to me that the software encodes the passwords and stores the encoded string in the database.

My password is '1234' and the encoded string is 'cRDtpNCeBiql5KOQsKVyrA0sAiA='. All the passwords in the database are 28 characters long.

The puzzle that I have assigned to myself is to find the encoding and/or encryption of the string. My first check was on Base64

So here is my first test in python (idle):

```<code>>>> import base64
>>> encoded = 'cRDtpNCeBiql5KOQsKVyrA0sAiA='
>>> decoded = base64.b64decode(encoded)
>>> decoded
'q\x10\xed\xa4\xd0\x9e\x06*\xa5\xe4\xa3\x90\xb0\xa5r\xac\r,\x02 '
>>> print decoded
qíﾤО*ﾥ䣐ﾰﾥrﾬ
</code>```

,

Here is my second test:

```<code>>>> myString = '1234'
>>> encoded = base64.b64encode(myString)
>>> encoded
'MTIzNA=='
>>> decoded = base64.b64decode('MTIzNA==')
>>> decoded
'1234'
</code>```

So, my first thought is that this is not Base64 encoded. After I checked wikipedia (https://en.wikipedia.org/wiki/Base64) it seems that Base64 encoded strings are not of fixed size. My second thought is that the string was encrypted and then encoded into Base64 and that is why I get the weird-looking decoded string.

Any ideas?

答:
It is actually Base64 encoded. However, it is not the password itself that is encoded, but its SHA-1 hash.

```<code>from sha import sha
print 'cRDtpNCeBiql5KOQsKVyrA0sAiA='.decode('base64').encode('hex')
print sha('1234').hexdigest()
</code>```

or for newer versions of Python:

```<code>from hashlib import sha1
print 'cRDtpNCeBiql5KOQsKVyrA0sAiA='.decode('base64').encode('hex')
print sha1('1234').hexdigest()
</code>```

Base64 encodes 3 bytes as 4 characters. As you have 27 characters with one padding, you can see that there are 20 encoded bytes (27*3/4). When something security related is 20 bytes (or 160 bits) long, it's usually a SHA-1. When it's 16 bytes (128 bits), it's usually MD5.

BTW, it's always a good idea to add random salt to the mix so two identical passwords wouldn't stick out in the database. On Linux, the crypt module helps you with that and throws in a few more security measures.

Edit: to answer another comment - it's very easy to get the original from the "encrypted" password. There's a technique that got famous a few years back called Rainbow Tables. There are even online versions of it. Just type in your hash in hex (7110eda4d09e062aa5e4a390b0a572ac0d2c0220) and it'll give you 1234 in a second.

Body:
This is a puzzle to me and I am really annoyed that I cannot solve it! So, if anyone has some free time I would like to here some suggestions on how to solve it!

I use a software that stores the password in an oracle database. The password field is of type Varchar2(100 char). It seems to me that the software encodes the passwords and stores the encoded string in the database.

My password is '1234' and the encoded string is 'cRDtpNCeBiql5KOQsKVyrA0sAiA='. All the passwords in the database are 28 characters long.

The puzzle that I have assigned to myself is to find the encoding and/or encryption of the string. My first check was on Base64

So here is my first test in python (idle):

>>> import base64
>>> encoded = 'cRDtpNCeBiql5KOQsKVyrA0sAiA='
>>> decoded = base64.b64decode(encoded)
>>> decoded
'q\x10\xed\xa4\xd0\x9e\x06*\xa5\xe4\xa3\x90\xb0\xa5r\xac\r,\x02 '
>>> print decoded
qíﾤО*ﾥ䣐ﾰﾥrﾬ

,

Here is my second test:

>>> myString = '1234'
>>> encoded = base64.b64encode(myString)
>>> encoded
'MTIzNA=='
>>> decoded = base64.b64decode('MTIzNA==')
>>> decoded
'1234'

So, my first thought is that this is not Base64 encoded. After I checked wikipedia (https://en.wikipedia.org/wiki/Base64) it seems that Base64 encoded strings are not of fixed size. My second thought is that the string was encrypted and then encoded into Base64 and that is why I get the weird-looking decoded string.

Any ideas?

Body:
It is actually Base64 encoded. However, it is not the password itself that is encoded, but its SHA-1 hash.

from sha import sha
print 'cRDtpNCeBiql5KOQsKVyrA0sAiA='.decode('base64').encode('hex')
print sha('1234').hexdigest()

or for newer versions of Python:

from hashlib import sha1
print 'cRDtpNCeBiql5KOQsKVyrA0sAiA='.decode('base64').encode('hex')
print sha1('1234').hexdigest()

Base64 encodes 3 bytes as 4 characters. As you have 27 characters with one padding, you can see that there are 20 encoded bytes (27*3/4). When something security related is 20 bytes (or 160 bits) long, it's usually a SHA-1. When it's 16 bytes (128 bits), it's usually MD5.

BTW, it's always a good idea to add random salt to the mix so two identical passwords wouldn't stick out in the database. On Linux, the crypt module helps you with that and throws in a few more security measures.

Edit: to answer another comment - it's very easy to get the original from the "encrypted" password. There's a technique that got famous a few years back called Rainbow Tables. There are even online versions of it. Just type in your hash in hex (7110eda4d09e062aa5e4a390b0a572ac0d2c0220) and it'll give you 1234 in a second.


问:
How to disable Context Menu in JavaFX?
So still kind of figuring out JavaFX, I was able to disable entering text in the textbox but I am not sure how to prevent the context menu from coming up when right clicked. Is anybody aware of how to prevent the default context menu from popping up when right clicked? `</p>

```<code>//CombatFeedback is scrollable textbox to update user on what's     happening.
TextArea CombatFeedback= new TextArea("Text.");
CombatFeedback.setPrefColumnCount(20);
CombatFeedback.setPrefRowCount(5);
CombatFeedback.setWrapText(true);
CombatFeedback.setStyle("-fx-font: 20 arial");
CombatFeedback.setEditable(false);
ScrollPane scrollerCombat = new ScrollPane(CombatFeedback);`
</code>```

答:
You can consume the event that signifies a request has been made for a context menu:</p>

```<code>CombatFeedback.addEventFilter(ContextMenuEvent.CONTEXT_MENU_REQUESTED, Event::consume);
</code>```

Title: How to disable Context Menu in JavaFX?

Body:
So still kind of figuring out JavaFX, I was able to disable entering text in the textbox but I am not sure how to prevent the context menu from coming up when right clicked. Is anybody aware of how to prevent the default context menu from popping up when right clicked? `

//CombatFeedback is scrollable textbox to update user on what's     happening.
TextArea CombatFeedback= new TextArea("Text.");
CombatFeedback.setPrefColumnCount(20);
CombatFeedback.setPrefRowCount(5);
CombatFeedback.setWrapText(true);
CombatFeedback.setStyle("-fx-font: 20 arial");
CombatFeedback.setEditable(false);
ScrollPane scrollerCombat = new ScrollPane(CombatFeedback);`

Body:
You can consume the event that signifies a request has been made for a context menu:

CombatFeedback.addEventFilter(ContextMenuEvent.CONTEXT_MENU_REQUESTED, Event::consume);


问:
How defensive should a Bash script be?
I recently stumbled over a very basic code snippet and began to wonder how defensive a Bash script needs to be.

[[ -f $file ]] && rm -- "$file" || echo "File does not exist."

What is the purpose of checking if the file exists when you could also simply pass the file to rm and let rm do the check itself? If the reason is that you can control what is shown as an error message yourself, why isn't it then necessary to also check if the file is writable in order to delete it? This leads me to believe that if you once start to test for possible conditions before you call a command -- in order to be consistent -- you'd need to check for every eventuality or you'd end up with error messages printed by yourself and those of external commands (rmin this case).

Another slightly more complex example I have wondered about would be

ffmpeg -n -i "./$file" -codec:a flac "./${file%.*}.flac"

This takes a file and transcodes it with the FLAC codec. Would it be sensible to first check the existence of the input file, whether that file is readable and also whether the location is writable for the output file? (Checking if the output file already exists is already done by providing the option -n to ffmpeg which means not to overwrite existing files.)

All of these would be checked by ffmpeg itself if I wouldn't add these checks.

答:
How defensive your script should be depends on how granular a control you want over execution of your script.

If you are happy with how a command handles failure and the rest of your script can execute without any problem whether it fails or succeeds, you can execute it totally blindly, ignoring its output and return value...

```<code>command_to_be_ignored >/dev/null 2>&1 ||:
</code>```

Maybe you are satisfied just knowing whether it succeeds or fails?

```<code>command_to_be_ignored >/dev/null 2>&1 || result=$?
</code>```

If you run a mission-critical script and you want to react to many potential failure modes, then you will need to capture and test the output of the command, or test preconditions and do something different if they are not met.

By the way, checking preconditions to the execution of a command does not make error handling unnecessary, because the command may still fail due to things happening in parallel, or simply you not fully understanding (or being able to test) all potential failure modes.  Checking pre-conditions is used to change what your program does in specific cases, not to avoid handling errors.

To sum it up, it is a matter of engineering : understanding the underlying mechanisms, knowing what you need to do, and making appropriate tradeoffs.

Title: How defensive should a Bash script be?

Body:
How defensive your script should be depends on how granular a control you want over execution of your script.

If you are happy with how a command handles failure and the rest of your script can execute without any problem whether it fails or succeeds, you can execute it totally blindly, ignoring its output and return value...

command_to_be_ignored >/dev/null 2>&1 ||:

Maybe you are satisfied just knowing whether it succeeds or fails?

command_to_be_ignored >/dev/null 2>&1 || result=$?

If you run a mission-critical script and you want to react to many potential failure modes, then you will need to capture and test the output of the command, or test preconditions and do something different if they are not met.

By the way, checking preconditions to the execution of a command does not make error handling unnecessary, because the command may still fail due to things happening in parallel, or simply you not fully understanding (or being able to test) all potential failure modes.  Checking pre-conditions is used to change what your program does in specific cases, not to avoid handling errors.

To sum it up, it is a matter of engineering : understanding the underlying mechanisms, knowing what you need to do, and making appropriate tradeoffs.


问:
Overlay everything outside of Div
I found what I was looking for the other day but cannot find it again.

I have a Div with position:aboslute and I'm looking to have a CSS overlay of everything besides that Div.

And if you click that overlay that goes away.

Please help!

答:
```<code><body>
<div id="overlay"></div>
<div id="modal"></div>

body {position:relative;}
#overlay  {position:fixed; top:0; left:0; width:100%;
height:100%; z-index:1000; background:#000; }
#modal {z-index:1001; position:absolute;}

$(document).on('click', '#overlay', function(){
$('#overlay').hide();
});
</code>```

Title: Overlay everything outside of Div


问:
has_many and belongs_to with join table
I have Users and Trucks. I want the ability to say @truck.drivers << @users and @user.truck = @truck.

The solution is simple until I want the relationship to be stored in a join table.

```<code># tables
:users
  :id

:truck_drivers
  :user_id
  :truck_id

:truck
  :id
</code>```

I've gotten it to where I can say @truck.drivers << @user and @user.trucks << @truck, but I would like to limit a user to occupy one truck at a time, for my sanity.

Is it possible? A has_many/belongs_to with a join table? Or should I try a different approach? I'm not using a third model for the join table. It's just a table. Here's what I have so far.

```<code>class User < ApplicationRecord
  has_and_belongs_to_many :trucks,
    join_table: :truck_drivers, # points to the table
    class_name: :Truck # looks for the truck model in the table
end

class Truck < ApplicationRecord
  belongs_to :company
  has_and_belongs_to_many :drivers,
    join_table: :truck_drivers,
    class_name: :User
end
</code>```

The reason I need a join table in the first place is because each User can have many Roles: Admin, Manager, Driver, Customer Service, etc. I thought it didn't make sense to add a truck_id to all the users if all the users are not going to be using trucks.

答:
Yes this is a standard strategy with rails using the  :through keyword.

rails documentation: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Make a model called TruckUser with truck_id and user_id

then edit your classes:

```<code>class User < ApplicationRecord
  has_many :truck_users
  has_many :trucks, through: :truck_users
end

class Truck < ApplicationRecord
  belongs_to :company
  has_many :truck_users
  has_many :drivers, through: :truck_users
end

class TruckUser < ApplicationRecord
  belongs_to :truck
  belongs_to :user
end
</code>```

Title: has_many and belongs_to with join table

Body:
I have Users and Trucks. I want the ability to say @truck.drivers << @users and @user.truck = @truck.

The solution is simple until I want the relationship to be stored in a join table.

# tables
:users
  :id

:truck_drivers
  :user_id
  :truck_id

:truck
  :id

I've gotten it to where I can say @truck.drivers << @user and @user.trucks << @truck, but I would like to limit a user to occupy one truck at a time, for my sanity.

Is it possible? A has_many/belongs_to with a join table? Or should I try a different approach? I'm not using a third model for the join table. It's just a table. Here's what I have so far.

class User < ApplicationRecord
  has_and_belongs_to_many :trucks,
    join_table: :truck_drivers, # points to the table
    class_name: :Truck # looks for the truck model in the table
end

class Truck < ApplicationRecord
  belongs_to :company
  has_and_belongs_to_many :drivers,
    join_table: :truck_drivers,
    class_name: :User
end

The reason I need a join table in the first place is because each User can have many Roles: Admin, Manager, Driver, Customer Service, etc. I thought it didn't make sense to add a truck_id to all the users if all the users are not going to be using trucks.

Body:
Yes this is a standard strategy with rails using the  :through keyword.

rails documentation: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Make a model called TruckUser with truck_id and user_id

then edit your classes:

class User < ApplicationRecord
  has_many :truck_users
  has_many :trucks, through: :truck_users
end

class Truck < ApplicationRecord
  belongs_to :company
  has_many :truck_users
  has_many :drivers, through: :truck_users
end

class TruckUser < ApplicationRecord
  belongs_to :truck
  belongs_to :user
end


问:
Linking to a tab or panel of a shiny app
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?

Update

The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).

However, I'd be interested to also know about more generic ways of linking parts of a shiny app.

Example

I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.

The value #tab-4527-2 came from investigating the HTML output of ui, but I just saw that those values change each time I restart the app.

```<code>library(shiny)

# UI ---------------------------------------------------------------------

ui <- fluidPage(
  tabsetPanel(
    tabPanel(
      "A",
      p(),
      actionLink("link_to_tabpanel_b", "Link to panel B")
    ),
    tabPanel(
      "B",
      h3("Some information"),
      tags$li("Item 1"),
      tags$li("Item 2")
    )
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {
  observeEvent(input$link_to_tabpanel_b, {
    tags$a(href = "#tab-4527-2")
  })
}

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

答:
You can give your tabsetPanel an id and use updateTabsetPanel with your observeEvent

```<code>library(shiny)

# UI ---------------------------------------------------------------------

ui <- fluidPage(
  tabsetPanel(id = "demo",
    tabPanel(
      "A",
      p(),
      actionLink("link_to_tabpanel_b", "Link to panel B")
    ),
    tabPanel(
      "B",
      h3("Some information"),
      tags$li("Item 1"),
      tags$li("Item 2")
    )
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {
  observeEvent(input$link_to_tabpanel_b, {
    updateTabsetPanel(session, "demo", "B")
  })
}

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

Body:
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?

Update

The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).

However, I'd be interested to also know about more generic ways of linking parts of a shiny app.

Example

I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.

The value #tab-4527-2 came from investigating the HTML output of ui, but I just saw that those values change each time I restart the app.

library(shiny)

# UI ---------------------------------------------------------------------

ui <- fluidPage(
  tabsetPanel(
    tabPanel(
      "A",
      p(),
      actionLink("link_to_tabpanel_b", "Link to panel B")
    ),
    tabPanel(
      "B",
      h3("Some information"),
      tags$li("Item 1"),
      tags$li("Item 2")
    )
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {
  observeEvent(input$link_to_tabpanel_b, {
    tags$a(href = "#tab-4527-2")
  })
}

shinyApp(ui, server)

Body:
You can give your tabsetPanel an id and use updateTabsetPanel with your observeEvent

library(shiny)

# UI ---------------------------------------------------------------------

ui <- fluidPage(
  tabsetPanel(id = "demo",
    tabPanel(
      "A",
      p(),
      actionLink("link_to_tabpanel_b", "Link to panel B")
    ),
    tabPanel(
      "B",
      h3("Some information"),
      tags$li("Item 1"),
      tags$li("Item 2")
    )
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {
  observeEvent(input$link_to_tabpanel_b, {
    updateTabsetPanel(session, "demo", "B")
  })
}

shinyApp(ui, server)


问:
Override a CSS variable and assign it to another variable doesn't take effect (var chain)
Sorry if the title is a little bit confusing but i didn't know how to describe it more understandable in english.

Does someone know why the first div does not have a red border. I would assume that the --secondary variable becomes overriden by child and would take effect on every other variable that assigns this variable?!

```<code>codepen.io/anon/pen/wJQVRO
</code>```

EDIT

Dont ask me why plunker and codepen dont support @apply but thats nearly the use case i need

http://codepen.io/anon/pen/wJQVRO/

```<code>  body {
    --primarycolor: {
      border: 2px solid var(--secondary);
    };

    --secondary: blue;
    border:2px solid var(--secondary);
    padding:5px;
  }

  div {
    --secondary: red;
    @apply(--primarycolor);
    padding:5px;
  }

  p {
    --secondary: black;
    @apply(--primarycolor);
    padding:5px;
  }
</code>```

In my polymer environment the @apply works, but thats not the problem, sorry for that..couldn't determine why codepen and plunker don't support it?! Anyway the problem i'm trying to explain is that the div and p element will both have a blue border and not like expected a red and a black border. Assume that the --primarycolor set is a great set of properties, it then would be a big effort to me if that work like expected.

答:
you're assigning the --secondary color to red, but assigning the div border color a value of --primarycolor which is blue stated in the body

```<code>div {
    --secondary: red; // change this to --primarycolor: red;
    color: var(--primarycolor);
    border:2px solid var(--primarycolor); // or change this to var(--secondary)
    padding:5px;
  }
</code>```

so either change the border assignment to var(--secondary) or change to --primarycolor: red instead of the --secondary: red

Body:
Sorry if the title is a little bit confusing but i didn't know how to describe it more understandable in english.

Does someone know why the first div does not have a red border. I would assume that the --secondary variable becomes overriden by child and would take effect on every other variable that assigns this variable?!

codepen.io/anon/pen/wJQVRO

EDIT

Dont ask me why plunker and codepen dont support @apply but thats nearly the use case i need

http://codepen.io/anon/pen/wJQVRO/

  body {
    --primarycolor: {
      border: 2px solid var(--secondary);
    };

    --secondary: blue;
    border:2px solid var(--secondary);
    padding:5px;
  }

  div {
    --secondary: red;
    @apply(--primarycolor);
    padding:5px;
  }

  p {
    --secondary: black;
    @apply(--primarycolor);
    padding:5px;
  }

In my polymer environment the @apply works, but thats not the problem, sorry for that..couldn't determine why codepen and plunker don't support it?! Anyway the problem i'm trying to explain is that the div and p element will both have a blue border and not like expected a red and a black border. Assume that the --primarycolor set is a great set of properties, it then would be a big effort to me if that work like expected.

Body:
you're assigning the --secondary color to red, but assigning the div border color a value of --primarycolor which is blue stated in the body

div {
    --secondary: red; // change this to --primarycolor: red;
    color: var(--primarycolor);
    border:2px solid var(--primarycolor); // or change this to var(--secondary)
    padding:5px;
  }

so either change the border assignment to var(--secondary) or change to --primarycolor: red instead of the --secondary: red


问:
Pjsip on iPhone using 3G incoming call has no audio when in UDP
After downloading, compiling, and installing pjsip version 2.0 (from pjsip.org) into my iPhone project, I am having the following issue:

The problem is when I am using UDP, while on 3G.

While the iPhone device is on 3G - On incoming calls, I cann't hear the other party, however the other party can hear me.  On outgoing calls on 3G, however, everything works just fine.

While the phone is on Wi-Fi, everything works great, incoming, outgoing, both parties hear fine.

Also, TCP works well for all scenarios, both 3G and Wi-Fi.

Tried implementing the solutions found here: http://trac.pjsip.org/repos/wiki/audio-problem-local-no-audio

But to no avail, been scratching my head for a while on this one ...

答:
You should try this. Add UDP transport inside startPjsipAndRegisterOnServer method.</p>

```<code>{
        // Init transport config structure
        pjsua_transport_config cfg;
        pjsua_transport_config_default(&cfg);
        cfg.port = 5080;
        status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, &cfg, NULL);
        if (status != PJ_SUCCESS) error_exit("Error creating transport", status);
    }
</code>```

Body:
You should try this. Add UDP transport inside startPjsipAndRegisterOnServer method.

{
        // Init transport config structure
        pjsua_transport_config cfg;
        pjsua_transport_config_default(&cfg);
        cfg.port = 5080;
        status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, &cfg, NULL);
        if (status != PJ_SUCCESS) error_exit("Error creating transport", status);
    }


问:
Is there an open source SQL Server DB compare tool?
I'm working on an open source project that uses SQL Server 2005 as the data store. We need a DB compare tool to generate diff scripts to be able to upgrade a DB from one version to another.

Is there an open source or free SQL Server DB diff tool out there that generates a convert script?

答:
While it's not exactly what you want, I found this for postgres:

http://mbk.projects.postgresql.org/

It doesn't generate a diff to apply, but rather allows you to merge a full dump of the new version of the table with the previous version.

OwnerDisplayName: Guy


问:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='eError']"}
I am trying to validate a login section with all valid and invalid inputs.

here is the code i have tried:

```<code>
    public void login_Valid_Invalid_Combinations() throws BiffException, IOException, InterruptedException
    {
      String FilePath = "D://credentials.xls";
      FileInputStream FIS = new FileInputStream(FilePath);
      Workbook WB = Workbook.getWorkbook(FIS);
      Sheet SH = WB.getSheet(0);
      for(int row =0; row<= SH.getRows()-1; row++)
      {
          String userNAME = SH.getCell(0, row).getContents();
          String passWORD = SH.getCell(1, row).getContents();
          System.out.println("USERMANE : "+userNAME + "  PASSWORD : "+passWORD);
          driver.get("LOGIN PAGE URL");
          driver.findElement(By.id("Email")).sendKeys(userNAME);
          driver.findElement(By.id("Password")).sendKeys(passWORD);
          driver.findElement(By.id("btnlogin")).click();
          System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());
          Thread.sleep(2000);
          String URL = driver.getCurrentUrl();
          System.out.println(URL);
          if (URL.equals("URL AFTER SUCCESFULL LOGIN"))
          {
              System.out.println("Login Successfull");
          }
          else
          {
              System.out.println("Login Failed");
          }
      }
      driver.close();
    }
```

I want to show the error message each time login failed, which is working fine. But when login is successful with valid inputs, it's showing:

"org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='eError']"}"

as the error message is not coming for successful login.

Can you please help me how to handle this.

答:
In case of success you will not get error message, in this case below line will throw NoSuchElement Exception

```<code>System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());
</code>```

We need to put above piece of code in try block then it will handles the exception.below is the updated code.

```<code>String userNAME = SH.getCell(0, row).getContents();
String passWORD = SH.getCell(1, row).getContents();
System.out.println("USERMANE : "+userNAME + "  PASSWORD : "+passWORD);
driver.get("LOGIN PAGE URL");
driver.findElement(By.id("Email")).sendKeys(userNAME);
driver.findElement(By.id("Password")).sendKeys(passWORD);
driver.findElement(By.id("btnlogin")).click();
Thread.sleep(2000);
String URL = driver.getCurrentUrl();
if (URL.equals("URL AFTER SUCCESFULL LOGIN"))
  {
    System.out.println("Login Successfull");
  }
else
  {
   System.out.println("Login Failed");
try{
   System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());
   }
catch(Exception e){
    }
    }
</code>```

Let me know if it helps you.

Body:
I am trying to validate a login section with all valid and invalid inputs.

here is the code i have tried:

    public void login_Valid_Invalid_Combinations() throws BiffException, IOException, InterruptedException
    {
      String FilePath = "D://credentials.xls";
      FileInputStream FIS = new FileInputStream(FilePath);
      Workbook WB = Workbook.getWorkbook(FIS);
      Sheet SH = WB.getSheet(0);
      for(int row =0; row<= SH.getRows()-1; row++)
      {
          String userNAME = SH.getCell(0, row).getContents();
          String passWORD = SH.getCell(1, row).getContents();
          System.out.println("USERMANE : "+userNAME + "  PASSWORD : "+passWORD);
          driver.get("LOGIN PAGE URL");
          driver.findElement(By.id("Email")).sendKeys(userNAME);
          driver.findElement(By.id("Password")).sendKeys(passWORD);
          driver.findElement(By.id("btnlogin")).click();
          System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());
          Thread.sleep(2000);
          String URL = driver.getCurrentUrl();
          System.out.println(URL);
          if (URL.equals("URL AFTER SUCCESFULL LOGIN"))
          {
              System.out.println("Login Successfull");
          }
          else
          {
              System.out.println("Login Failed");
          }
      }
      driver.close();
    }

I want to show the error message each time login failed, which is working fine. But when login is successful with valid inputs, it's showing:

"org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='eError']"}"

as the error message is not coming for successful login.

Can you please help me how to handle this.

Body:
In case of success you will not get error message, in this case below line will throw NoSuchElement Exception

System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());

We need to put above piece of code in try block then it will handles the exception.below is the updated code.

String userNAME = SH.getCell(0, row).getContents();
String passWORD = SH.getCell(1, row).getContents();
System.out.println("USERMANE : "+userNAME + "  PASSWORD : "+passWORD);
driver.get("LOGIN PAGE URL");
driver.findElement(By.id("Email")).sendKeys(userNAME);
driver.findElement(By.id("Password")).sendKeys(passWORD);
driver.findElement(By.id("btnlogin")).click();
Thread.sleep(2000);
String URL = driver.getCurrentUrl();
if (URL.equals("URL AFTER SUCCESFULL LOGIN"))
  {
    System.out.println("Login Successfull");
  }
else
  {
   System.out.println("Login Failed");
try{
   System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());
   }
catch(Exception e){
    }
    }

Let me know if it helps you.


问:
Addition game with timer
A count down timer will display 20-s and a "start" button will be visible.

When the start button is pushed:

the "start" will change to "submit"
the timer will count down to 0 over 20 seconds.
the page will display random addition problems (single digit, plus single digit)
a text box will be available to type answers into and when you hit the "submit" button a new random problem will appear
This will repeat until the timer runs out at which time:

The page will display the number of attempted problems, the number of correct problems, and the percentage of correct problems.
The "submit" button will turn back into "start" and the page will be able to run again if you hit start again.

答:
Actually have a project I did for my wife/kids for their home schooling to drill their math facts. It doesn't have a count-down but it does time the assessments.

Feel free to check it out here: http://mathfactory.azurewebsites.net/#/

All the front-end code for it is here: http://mathfactory.azurewebsites.net/Client/Bundles/app-bundle.js

Title: Addition game with timer


问:
Differences between apktool and baksmali
As far as I know, both apktool and baksmali are able to produce smali code out of .apk (.dex) files, and apktool makes use of the dexlib2. They are both APK packing/unpacking tools

But still I am not clear what are the main differences between apktool and smali/baksmali. in temrs of functionality with .dex files and extended features?

PS:
One of the difference that I just found out is that apktool is able to work with multiple dex files inside an apk while baksmali cannot (at least for the time being)

I did try to read the source code but due to the lack of experience, I could not really understand the working flow of both tools. I would really appreciate If anyone could suggest some readings or flow charts, etc.

Thank you!

答:
smali/baksmali are an assembler/disassembler pair for the dex format. Baksmali takes a dex file and produces human readable assembly, and smali takes the human readable assembly and produces a dex file.

Apktool is a more general took for unpacking and repacking an apk. It actually uses smali/baksmali under the hood in order to assemble/disassemble the dex file. It also unpacks the binary resources and binary xml files back into the standard textual format, etc.


问:
WebView will not function with loadUrl but works with loadData
I'm using standard addresses like google and facebook, but loadUrl does nothing, it just sits there at a white screen, but if i pipe html into it using loadData, it works fine. Any ideas or tips? I've got it enabling javascript, and I have this call:

```<code>mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            TextView t;
            t = (TextView)findViewById(R.id.pageTitle);
            t.setText(view.getTitle());
        }
    });
</code>```

Do i need to override anything else?

答:
The discussed above are cool and pretty good but I've noticed this thing in newer versions of android studio the method loadUrl() does not work direct through. so we should identify the settings first then set true for JS as like this

wb.getSettings().setJavaScriptEnabled(true);
 wb.getSettings().setLoadWithOverviewMode(true);

Body:
I'm using standard addresses like google and facebook, but loadUrl does nothing, it just sits there at a white screen, but if i pipe html into it using loadData, it works fine. Any ideas or tips? I've got it enabling javascript, and I have this call:

mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            TextView t;
            t = (TextView)findViewById(R.id.pageTitle);
            t.setText(view.getTitle());
        }
    });

Do i need to override anything else?


问:
How to programmatically add/remove an image to navigation bar title in Swift 3/Xcode
So I currently have a menu bar open and close on the left side of the app, and I want a certain image to appear on the navigation bar title when I open the menu. Below is my function for opening and closing the menu.

```<code>@IBAction func openMenu(_ sender: Any) {

    if (menuShowing) {
        self.navigationController?.navigationBar.barTintColor = UIColor(red:0.00, green:0.20, blue:0.63, alpha:1.0)
        navigationItem.leftBarButtonItem?.tintColor = UIColor.white
        navigationItem.titleView = ""
        leadingConstraint.constant = -240
        shadowLeadingConstraint.constant = -250
        UIView.animate(withDuration: 0.6, animations: {
            self.view.layoutIfNeeded()
        })

    }
    else {
        self.navigationController?.navigationBar.barTintColor = UIColor.white
        navigationItem.leftBarButtonItem?.tintColor = UIColor(red:0.00, green:0.20, blue:0.63, alpha:1.0)

        let image = UIImage(named: "MenuBarTransparent")
        navigationItem.titleView = UIImageView(image: image)
        navigationItem.titleView?.frame=CGRect(x:10, y:0, width:30, height:360)

        leadingConstraint.constant = 0
        shadowLeadingConstraint.constant = 0
        UIView.animate(withDuration: 0.3, animations: {
            self.view.layoutIfNeeded()
        })
    }
    menuShowing = !menuShowing
}
</code>```

This portion of code in the above function makes the image appear when I want it to, but manipulating the x and y-coordinate has no effect whatsoever so I can't center the image correctly:

```<code>let image = UIImage(named: "MenuBarTransparent")
        navigationItem.titleView = UIImageView(image: image)
        navigationItem.titleView?.frame=CGRect(x:10, y:0, width:30,  height:360)
</code>```

Also, this portion of code from above does not let me delete the image from the nav bar title whenever I close the menu again, it says "Cannot assign value of type 'String' to type 'UIView?':

```<code>navigationItem.titleView = ""
</code>```

Thanks in advance for any help.

答:
Here's how you would set the object with it's init.

navigationItem.titleView = UIImageView.init(image: UIImage(named:"image"))

Body:
So I currently have a menu bar open and close on the left side of the app, and I want a certain image to appear on the navigation bar title when I open the menu. Below is my function for opening and closing the menu.

@IBAction func openMenu(_ sender: Any) {

    if (menuShowing) {
        self.navigationController?.navigationBar.barTintColor = UIColor(red:0.00, green:0.20, blue:0.63, alpha:1.0)
        navigationItem.leftBarButtonItem?.tintColor = UIColor.white
        navigationItem.titleView = ""
        leadingConstraint.constant = -240
        shadowLeadingConstraint.constant = -250
        UIView.animate(withDuration: 0.6, animations: {
            self.view.layoutIfNeeded()
        })

    }
    else {
        self.navigationController?.navigationBar.barTintColor = UIColor.white
        navigationItem.leftBarButtonItem?.tintColor = UIColor(red:0.00, green:0.20, blue:0.63, alpha:1.0)

        let image = UIImage(named: "MenuBarTransparent")
        navigationItem.titleView = UIImageView(image: image)
        navigationItem.titleView?.frame=CGRect(x:10, y:0, width:30, height:360)

        leadingConstraint.constant = 0
        shadowLeadingConstraint.constant = 0
        UIView.animate(withDuration: 0.3, animations: {
            self.view.layoutIfNeeded()
        })
    }
    menuShowing = !menuShowing
}

This portion of code in the above function makes the image appear when I want it to, but manipulating the x and y-coordinate has no effect whatsoever so I can't center the image correctly:

let image = UIImage(named: "MenuBarTransparent")
        navigationItem.titleView = UIImageView(image: image)
        navigationItem.titleView?.frame=CGRect(x:10, y:0, width:30,  height:360)

Also, this portion of code from above does not let me delete the image from the nav bar title whenever I close the menu again, it says "Cannot assign value of type 'String' to type 'UIView?':

navigationItem.titleView = ""

Thanks in advance for any help.


问:
Javascript method always returns same value
I have two methods in my class. One method randomizes values, another one returns those values in a string that represents CSS color. Yet after randomization it still returns same string all the time, even though values in created object are changed. Can you please explain why?

Here's jsfiddle: https://jsfiddle.net/wpem1j9e/

```<code>function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
    this.randomize = function(){
        this.r = Math.floor(Math.random() * 100);
        this.g = Math.floor(Math.random() * 100);
        this.b = Math.floor(Math.random() * 100);
        return this;
    }
    this.toString = function(){
        var cssColor = "rgb(" + r + "%," + g + "%," + b + "%)";
        return cssColor;
    }
}
var color1 = new Color (1, 1, 1);
color1.randomize().toString(); // still returns "rgb(1%,1%,1%)";
</code>```

答: Because in your toString function you are using r, g and b instead of this.r, this.g and this.b. The former are you constructor parameters.

Body:
I have two methods in my class. One method randomizes values, another one returns those values in a string that represents CSS color. Yet after randomization it still returns same string all the time, even though values in created object are changed. Can you please explain why?

Here's jsfiddle: https://jsfiddle.net/wpem1j9e/

function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
    this.randomize = function(){
        this.r = Math.floor(Math.random() * 100);
        this.g = Math.floor(Math.random() * 100);
        this.b = Math.floor(Math.random() * 100);
        return this;
    }
    this.toString = function(){
        var cssColor = "rgb(" + r + "%," + g + "%," + b + "%)";
        return cssColor;
    }
}
var color1 = new Color (1, 1, 1);
color1.randomize().toString(); // still returns "rgb(1%,1%,1%)";


问:
DSE Graph Loader mapping edges
I have to map data from JSON files to DSE.
Everything is working just fine, but I didn't find any documentation about the way to map edges connected to different nodes but sharing a same label.

Example :

```<code>[A:Car] -- [OWNER] --> [B:Person]
[C:Car] -- [OWNER] --> [D:Company]
</code>```

I've tried different approaches, finally I've added a custom field that explicitly describes the class of the nodes :

Data sample

```<code>// Nodes
{"id":"A","label":"Car"}
{"id":"B","label":"Person"}
{"id":"C","label":"Car"}
{"id":"D","label":"Company"}

// Edges
{"out":"A","label":"OWNER","in":"B", "outLabel":"Car","inLabel":"Person"}
{"out":"C","label":"OWNER","in":"D", "outLabel":"Car","inLabel":"Company"}
</code>```

Here is the mapping script

```<code>load(nodesInput).asVertices {
     labelField "label"
     key "id"
}

load(edgesInput).asEdges {
    label "OWNER"
    outV "out", {
        key "id"
        label "Car"
    }
    inV "in", {
        key "id"
        labelField "inLabel"  <-- this declaration seems to fail
    }
}
</code>```

Any idea ?

答:
I believe you could accomplish the above with something like the following.

```<code>load(edgesInput).asEdges {
    label "OWNER"
    outV "out", {
        key "id"
        label "Car"
    }
    inV "in", {
        key "id"
        label it["inLabel"]
    }
}
</code>```

https://docs.datastax.com/en/latest-dse/datastax_enterprise/graph/dgl/dglMapScript.html

Title: DSE Graph Loader mapping edges

Body:
I have to map data from JSON files to DSE.
Everything is working just fine, but I didn't find any documentation about the way to map edges connected to different nodes but sharing a same label.

Example :

[A:Car] -- [OWNER] --> [B:Person]
[C:Car] -- [OWNER] --> [D:Company]

I've tried different approaches, finally I've added a custom field that explicitly describes the class of the nodes :

Data sample

// Nodes
{"id":"A","label":"Car"}
{"id":"B","label":"Person"}
{"id":"C","label":"Car"}
{"id":"D","label":"Company"}

// Edges
{"out":"A","label":"OWNER","in":"B", "outLabel":"Car","inLabel":"Person"}
{"out":"C","label":"OWNER","in":"D", "outLabel":"Car","inLabel":"Company"}

Here is the mapping script

load(nodesInput).asVertices {
     labelField "label"
     key "id"
}

load(edgesInput).asEdges {
    label "OWNER"
    outV "out", {
        key "id"
        label "Car"
    }
    inV "in", {
        key "id"
        labelField "inLabel"  <-- this declaration seems to fail
    }
}

Any idea ?

Body:
I believe you could accomplish the above with something like the following.

load(edgesInput).asEdges {
    label "OWNER"
    outV "out", {
        key "id"
        label "Car"
    }
    inV "in", {
        key "id"
        label it["inLabel"]
    }
}

https://docs.datastax.com/en/latest-dse/datastax_enterprise/graph/dgl/dglMapScript.html


问:
Lifetime of BroadcastReceiver with regard to Android O changes
If I declare a BroadcastReceiver via the mainfest file for a system broadcast (let's say for example ACTION_POWER_DISCONNECTED) the the system will call it every time the specific broadcast is send so the lifetime of the BroadcastReceiver is unrestricted.

But there are also broadcasts which can not be registered via the manifest file. For these broadcasts we have to call context.registerReceiver with a corresponding IntentFilter.  Let's say I create a BroadcastReceiver for BOOT_COMPLETED and call context.registerReceiver from it and never call unregisterReceiver does this receiver also lives forever (until the phone is rebooted)?

Apps that target Android O can no longer register broadcast receivers for implicit broadcasts in their manifest. An implicit broadcast is a broadcast that does not target that app specifically.

If my conjecture from above is right this would be an easy workaround for the system change (of course you shouldn't do it this way but it would be possible). So does a BroadcastReceiver which is registered after a BOOT_COMPLETED broadcast have the same lifetime (stays until the next reboot) as a BroadcastReceiver which is automatically registered via the manifest?

答:
Let's say I create a BroadcastReceiver for BOOT_COMPLETED and call context.registerReceiver from it and never call unregisterReceiver does this receiver also lives forever (until the phone is rebooted)?

First, BOOT_COMPLETED is one of those actions, that still will behave like they were before, meaning restriction introduced in "O" do not concern to that action.

As soon as the process of your app is killed by the system or  as soon as system clears your app's memory (as a result of low-memory of device), your broadcast registration will be lost. Otherwise I cannot see how this limitation will result in a better battery experience.

So does a BroadcastReceiver which is registered after a BOOT_COMPLETED broadcast have the same lifetime (stays until the next reboot) as a BroadcastReceiver which is automatically registered via the manifest?

If above mentioned cases are not met, i.e. the process of your app stays alive and app is not cleared from memory because of memory shortage - then yes. Once entered into cached state (the state with no active Android component) the registration will be lost again.

This short video by Nasir Khan will be helpful.


问:
How to subtract each item in a group against other items in group in t-sql
I have a table of transactions per company.  If company, transaction date, and transaction type are the same and the difference between one record's transaction price is greater than .25% with another record's of the same company, transaction date, and transaction type, then I need to select the two (or more) records.

I know I need to use group by to do this, and I will probably need to join the table to itself, but I am struggling to come up with an approach here.  How should I do this?

```<code>Transaction_ID | Company | Transction_date | Transaction_Type | Price
1              | A       |   01/01/2017     |       BUY       |   30.01
2              |   A     |     01//01/2017  |         BUY     |       37
3              |   A     |     01/02/2017   |         BUY     |      31
</code>```

答:
Perhaps</p>

```<code>Select t1.Trasaction_ID as ID1
      ,t2.Transaction_ID as ID2
      ,t1.Company
      ,t1.Transaction_Date
      ,t1.Transaction_Type
      ,t1.Price as Price1
      ,t2.Price as Price2
From transactions t1
inner join transactions t2
   on t1.Company = t2.Company
   and t1.Transaction_Date = t2.Transaction_Date
   and t1.Transaction_Type = t2.Transaction_Type
where ABS(t1.Price - t2.Price) > (t1.Price * 0.0025)
</code>```

Body:
I have a table of transactions per company.  If company, transaction date, and transaction type are the same and the difference between one record's transaction price is greater than .25% with another record's of the same company, transaction date, and transaction type, then I need to select the two (or more) records.

I know I need to use group by to do this, and I will probably need to join the table to itself, but I am struggling to come up with an approach here.  How should I do this?

Transaction_ID | Company | Transction_date | Transaction_Type | Price
1              | A       |   01/01/2017     |       BUY       |   30.01
2              |   A     |     01//01/2017  |         BUY     |       37
3              |   A     |     01/02/2017   |         BUY     |      31

Body:
Perhaps

Select t1.Trasaction_ID as ID1
      ,t2.Transaction_ID as ID2
      ,t1.Company
      ,t1.Transaction_Date
      ,t1.Transaction_Type
      ,t1.Price as Price1
      ,t2.Price as Price2
From transactions t1
inner join transactions t2
   on t1.Company = t2.Company
   and t1.Transaction_Date = t2.Transaction_Date
   and t1.Transaction_Type = t2.Transaction_Type
where ABS(t1.Price - t2.Price) > (t1.Price * 0.0025)


问:
html: {id: 'query'} doesn't work in form_for tag
In a html form generated with Ruby, I wish to use a custom id attribute values.

```<code><%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: {id: 'basic_form'}) do |f| %>
</code>```

but it is not working, and the id value is the default generated by Ruby.

Please point me to the right direction. Thank you!

UPDATE (Solved):
I guess the problem was somewhere else in the code. rolled back to previous code backup and did code changes again. It worked with the same above code. Thank you everyone for help.

答:
```<code><%= form_for resource, :as => resource_name, :url => registration_path(resource_name),:id => 'basic_form' do |f| %>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In a html form generated with Ruby, I wish to use a custom id attribute values.

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: {id: 'basic_form'}) do |f| %>

but it is not working, and the id value is the default generated by Ruby.

Please point me to the right direction. Thank you!

UPDATE (Solved):
I guess the problem was somewhere else in the code. rolled back to previous code backup and did code changes again. It worked with the same above code. Thank you everyone for help.


问:
How to build a Distributed Network with mutual consensus
What are the technologies needed to build a system which is distributed and maintains a proof of work between parties and transactions.

I've known about Blockchain and worked with IBM Fabric, but they have their own restrictions.

What are the other possible methods and technologies to build such a strong and robust system?

Thanks in advance :)

答:
Well if you want to stay block chain specific, tendermint stepped around the issues of bft by using gossip, for each round, the thing is expecting proof of work hinders scalability, strong consensus is also not very scalable.

Now if we're talking about concepts that can help you build your own solution, rather than framework x, look at event sourcing for sharable immutable transactions, if you need consistency look into chord, it's the easiest way to implement eventual consistency or gossip + crdts, or hell dynamo and cassandra use all 3.

For maintaining security look into the station to station protocol + mutual tls auth.


问:
Postgres - detect overlapping lines from 2 tables
QUESTION: I have 2 tables with bike and hike trails of a country (Poland).

```<code>Table bicycle_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |bicycle |szlak1       |ncn        |blue      |proposed
{geo2}   |bicycle |szlak2       |lcn        |red       |null
{geo3}   |bicycle |szlak3       |ncn        |green     |proposed
{geo4}   |bicycle |szlak4       |rcn        |blue      |proposed
{geo5}   |bicycle |szlak5       |lcn        |blue      |null
{geo6}   |bicycle |szlak6       |ncn        |yellow    |proposed
....and so on

Table hiking_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |hiking  |szlak1       |ncn        |blue      |proposed
{geo2}   |hiking  |szlak2       |ncn        |red       |null
{geo3}   |hiking  |szlak3       |ncn        |green     |proposed
{geo4}   |hiking  |szlak4       |ncn        |blue      |proposed
{geo5}   |hiking  |szlak5       |ncn        |blue      |null
{geo6}   |hiking  |szlak6       |ncn        |yellow    |proposed
...and so on
</code>```

{geo1},{geo2} etc. is a unique geometry of every trail.

Every trail has a unique geometry but sometimes bicycle and hiking routes overlap.
The picture below shows example in QGIS:

I would like to delete the overlapping parts as I already have them in a different database.

EDIT:
I have tried a solution suggested by Julia Leder :

```<code>create table intersections as
(select st_intersection(b.way, h.way) as overlapping_section
from bicycle_merge b, hiking_merge h
where st_intersects(g.way, h.way));
</code>```

Not all overlapping lines were detected. I'm not sure why?
Here's a picture to show the issue:

答:
This can be relatively easily done with PostGIS functions.
You need to find the overlapping section between the two geometries, which can be done with

```<code>ST_Intersection(a.geometry, b.geometry)
</code>```

Then you need to subtract that section from the original geometry from either biking or hiking geometry, which would be done with

```<code>ST_Difference(a.geometry, b.geometry)
</code>```

To put this all together:

```<code>create table intersections as
(select st_intersection(st_buffer(b.way,10), st_buffer(h.way,10)) as overlapping_section
from bicycle_merge b, hiking_merge h
where st_intersects(st_buffer(g.way, 10), st_buffer(h.way,10)));

update bicycle_merge b
set way = st_difference(b.way, overlapping_section)
from intersections where st_intersects(b.way, overlapping_section);

update hiking_merge h
set way = st_difference(h.way, overlapping_section)
from intersections where st_intersects(h.way, overlapping_section);
</code>```

This may need to be adjusted somewhat depeding on types of geometries and how you want to store them, but the above should give you the idea.

The 2nd parameter of st_buffer function takes a radius of the buffer. The units of this number depend on the srid of geometry. They can be in feet, meters or degrees depending on the SRID of your geometry, which you can check by

```<code>select st_srid(way) from biking_merge limit 0;
</code>```

Body:
QUESTION: I have 2 tables with bike and hike trails of a country (Poland).

Table bicycle_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |bicycle |szlak1       |ncn        |blue      |proposed
{geo2}   |bicycle |szlak2       |lcn        |red       |null
{geo3}   |bicycle |szlak3       |ncn        |green     |proposed
{geo4}   |bicycle |szlak4       |rcn        |blue      |proposed
{geo5}   |bicycle |szlak5       |lcn        |blue      |null
{geo6}   |bicycle |szlak6       |ncn        |yellow    |proposed
....and so on

Table hiking_merge

way      | route  | name        |network    |osmc_color| state
geometry | text   | text        |text       |text      | text
----------------------------------------------------------------
{geo1}   |hiking  |szlak1       |ncn        |blue      |proposed
{geo2}   |hiking  |szlak2       |ncn        |red       |null
{geo3}   |hiking  |szlak3       |ncn        |green     |proposed
{geo4}   |hiking  |szlak4       |ncn        |blue      |proposed
{geo5}   |hiking  |szlak5       |ncn        |blue      |null
{geo6}   |hiking  |szlak6       |ncn        |yellow    |proposed
...and so on

{geo1},{geo2} etc. is a unique geometry of every trail.

Every trail has a unique geometry but sometimes bicycle and hiking routes overlap.
The picture below shows example in QGIS:

I would like to delete the overlapping parts as I already have them in a different database.

EDIT:
I have tried a solution suggested by Julia Leder :

create table intersections as
(select st_intersection(b.way, h.way) as overlapping_section
from bicycle_merge b, hiking_merge h
where st_intersects(g.way, h.way));

Not all overlapping lines were detected. I'm not sure why?
Here's a picture to show the issue:

Body:
This can be relatively easily done with PostGIS functions.
You need to find the overlapping section between the two geometries, which can be done with

ST_Intersection(a.geometry, b.geometry)

Then you need to subtract that section from the original geometry from either biking or hiking geometry, which would be done with

ST_Difference(a.geometry, b.geometry)

To put this all together:

create table intersections as
(select st_intersection(st_buffer(b.way,10), st_buffer(h.way,10)) as overlapping_section
from bicycle_merge b, hiking_merge h
where st_intersects(st_buffer(g.way, 10), st_buffer(h.way,10)));

update bicycle_merge b
set way = st_difference(b.way, overlapping_section)
from intersections where st_intersects(b.way, overlapping_section);

update hiking_merge h
set way = st_difference(h.way, overlapping_section)
from intersections where st_intersects(h.way, overlapping_section);

This may need to be adjusted somewhat depeding on types of geometries and how you want to store them, but the above should give you the idea.

The 2nd parameter of st_buffer function takes a radius of the buffer. The units of this number depend on the srid of geometry. They can be in feet, meters or degrees depending on the SRID of your geometry, which you can check by

select st_srid(way) from biking_merge limit 0;


问:
How to delete Jade agents
I need to run my solution N times and in each iteration a set of agents is created but before passing to the next iteration (i+1), I need to shut down the platform or to delete all the agents so they can be created again in (i+1) iteration.

I have tried the .dodelete() and .kill() methods but it is not working I guess that I need to shutdown the whole platform each time but I don't know how to do it. Are there any methods or code I can use?

答:
Try this to terminate your Agent.</p>

```<code>protected void takeDown() {
    // Printout a dismissal message
    System.out.println("Agent-1 "+getAID().getName()+" terminating.");
}
</code>```

Title: How to delete Jade agents

Body:
Try this to terminate your Agent.

protected void takeDown() {
    // Printout a dismissal message
    System.out.println("Agent-1 "+getAID().getName()+" terminating.");
}