问:
C++ Calling Member Function by Function Pointer Error
I'm programming a Discrete Event Simulator (DES) where events will be user programmed functions.
I have a Class called UserEvents and a private member function called Add

```<code>    void Add(const void *Parameters, void *ReturnValue);
</code>```

I'm trying to make a vector that would store the following struct:

```<code> typedef struct FunctionPointerAlias { std::string FAlias; void(UserEvents::*FPointer)(const void*, void*); };
</code>```

Based on a string, I want to call different functions. Thus switch would be nice but switch can't handle strings (and I don't want to hash my strings).
So I made a vector with a struct (string Alias, FunctionPointer) and then I'll iterate over my vector looking for the user's inputed string, recovering the corresponding function pointer and calling it.

All user functions should be of type void, receiving parameters and returning values through void* pointers as such:

```<code>void UserEvents::Add(const void *Parameters, void *ReturnValue)
{
    int *A = (int*)Parameters;
    int *B = A;
    B++;

    int *C = (int*)ReturnValue;
    *C = *A + *B;

    //memcpy(ReturnValue, &C, sizeof(int));
    return;
}
</code>```

(TL;DR) The problem lies when I try to call the function pointed by the function pointer. I get the error "Expression preceding parentheses of apparent call must have (pointer-to-) function type" on the line right above return in the "Add" if.

```<code>    void UserEvents::Choose(const std::string Alias, const void *Parameters, void *ReturnValue)
{
    if (Alias == "Example")
    {
        // *ReturnValue = Function(Parameters)
        return;
    }

    if (Alias == "Add") {
        void (UserEvents::*FunctionPointer)(const void*, void*) = &UserEvents::Add;
        (*FunctionPointer)(Parameters, ReturnValue);
        return;
    }
}
</code>```

答:
I didn't understand what you need very well, so I tried to do something general, you should use the pattern in your own class:</p>

```<code>#include <iostream>
#include <string>

typedef void(*STR_FUNC)(const void*, void*);

struct FUNCTION_POINTER_ALIAS
{
    std::string FAlias;
    STR_FUNC fn;
};

void FN0(const void *Parameters, void *ReturnValue)
{
    std::cout << *(std::string*) Parameters << " FN0" << std::endl;
}

void FN1(const void *Parameters, void *ReturnValue)
{
    std::cout << *(std::string*) Parameters << " FN1" << std::endl;
}

void FN2(const void *Parameters, void *ReturnValue)
{
    std::cout << *(std::string*) Parameters << " FN2" << std::endl;
}

int main()
{
    FUNCTION_POINTER_ALIAS Items[] = {{"str0", FN0}, {"str1", FN1}, {"str2", FN2}};
    for (int i = 0; i < sizeof(Items) / sizeof(FUNCTION_POINTER_ALIAS); ++i)
        Items[i].fn(&Items[i].FAlias, NULL);
}
</code>```

Body:
I'm programming a Discrete Event Simulator (DES) where events will be user programmed functions.
I have a Class called UserEvents and a private member function called Add

    void Add(const void *Parameters, void *ReturnValue);

I'm trying to make a vector that would store the following struct:

 typedef struct FunctionPointerAlias { std::string FAlias; void(UserEvents::*FPointer)(const void*, void*); };

Based on a string, I want to call different functions. Thus switch would be nice but switch can't handle strings (and I don't want to hash my strings).
So I made a vector with a struct (string Alias, FunctionPointer) and then I'll iterate over my vector looking for the user's inputed string, recovering the corresponding function pointer and calling it.

All user functions should be of type void, receiving parameters and returning values through void* pointers as such:

void UserEvents::Add(const void *Parameters, void *ReturnValue)
{
    int *A = (int*)Parameters;
    int *B = A;
    B++;

    int *C = (int*)ReturnValue;
    *C = *A + *B;

    //memcpy(ReturnValue, &C, sizeof(int));
    return;
}

(TL;DR) The problem lies when I try to call the function pointed by the function pointer. I get the error "Expression preceding parentheses of apparent call must have (pointer-to-) function type" on the line right above return in the "Add" if.

    void UserEvents::Choose(const std::string Alias, const void *Parameters, void *ReturnValue)
{
    if (Alias == "Example")
    {
        // *ReturnValue = Function(Parameters)
        return;
    }

    if (Alias == "Add") {
        void (UserEvents::*FunctionPointer)(const void*, void*) = &UserEvents::Add;
        (*FunctionPointer)(Parameters, ReturnValue);
        return;
    }
}

Body:
I didn't understand what you need very well, so I tried to do something general, you should use the pattern in your own class:

#include <iostream>
#include <string>

typedef void(*STR_FUNC)(const void*, void*);

struct FUNCTION_POINTER_ALIAS
{
    std::string FAlias;
    STR_FUNC fn;
};

void FN0(const void *Parameters, void *ReturnValue)
{
    std::cout << *(std::string*) Parameters << " FN0" << std::endl;
}

void FN1(const void *Parameters, void *ReturnValue)
{
    std::cout << *(std::string*) Parameters << " FN1" << std::endl;
}

void FN2(const void *Parameters, void *ReturnValue)
{
    std::cout << *(std::string*) Parameters << " FN2" << std::endl;
}

int main()
{
    FUNCTION_POINTER_ALIAS Items[] = {{"str0", FN0}, {"str1", FN1}, {"str2", FN2}};
    for (int i = 0; i < sizeof(Items) / sizeof(FUNCTION_POINTER_ALIAS); ++i)
        Items[i].fn(&Items[i].FAlias, NULL);
}


来源: stackexchange

问:
Aurelia with out a router, navigate to login.html and not /#login
I'm writing custom views for Identity Server 3 for its login, logout, consent, etc.  I want to use Aurelia but in Identity server I have to pass in the actual html file.  So, how can I navigate to localhost:9000/login.html and not localhost:9000/#login

Thanks

答:
With @Ashley Grant's help, I was able to create an aurelia replacement for IViewService example coded in angular. Identity Server 3 IView Service Example

It's honestly quite easy.  Just create a standard aurelia project and put your html in app.html and view model in app.js.  In addition to having the vendor_bundle reference link in your Index.html you will also have to create a link for the app_bundle as well because of a bug that tries to locate app_bundle in the root of your folder structure for Identity Server.

If anyone is interested in the source I can put something together just IM me.

ContentLicense: CC BY-SA 3.0


问:
Rspec bundle is broken in TextMate and rvm
I've had a difficult time since I started using rvm.  I've done all the rvm/textmate set up and have the latest bundles but I still can't run Rspec test from textmate.

I have the latest bundle from github.com/rspec/rspec-tmbundle.git
and it's installed in ~/Library/Application\ Support/TextMate/Bundles/
 RSpec.tmbundle

RVM default is using the system ruby 1.8.6

Rspec gem versions

gem list --local | grep spec
blue_light_special (0.2.0)
rspec (2.2.0)
rspec-core (2.2.1, 2.0.1)
rspec-expectations (2.2.0, 2.0.1)
rspec-mocks (2.2.0, 2.0.1)
rspec-rails (2.0.1, 1.3.2)

TextMate

TM_RUBY=/Users/jspooner/.rvm/bin/rvm-auto-ruby

The Error: rspec/core (LoadError)

/Users/jspooner/Library/Application Support/TextMate/Bundles/RSpec.tmbundle/Support/lib/rspec/mate.rb:29:in require': no such file to load -- rspec/core (LoadError) from /Users/jspooner/Library/Application Support/TextMate/Bundles/RSpec.tmbundle/Support/lib/rspec/mate.rb:29 from /tmp/textmate-command-8073.rb:2:inrequire' from /tmp/textmate-command-8073.rb:2

答: Did you try following the instructions here: http://rvm.io/integration/textmate/</p>


问:
postgresql limit the number of foreign key available for a given table
Here the situation, I am setting up a database using postgresql. In my database I have a league and a number of team associated with the league how can I set a minimum number of team that can be associated with a particular league ?</p>

答:
It's possible to do this with triggers. When a team is added (INSERTed), removed (DELETEd) or UPDATEd to change teams, a BEFORE trigger should SELECT 1 FROM league WHERE league_id = NEW.team_id FOR UPDATE to lock the associated league row for the new and/or old team, depending on the type of change.

Then an AFTER trigger does a COUNT query for the old and/or new leagues to check that the constraint is satisfied and RAISEs an exception if it isn't.

You'd need a field to mark a league "active" or "inactive" where the constraint is only checked when it's active, otherwise you'd never be able to create the first few teams.


问:
Rails no stack trace but 400 error in nginx log
I'm sending an POST to rails with an image so it's a multi part form and it often works just fine.

But sometime I get a nginx log 400 error for the POST but nothing in the rails log to give me information on why the 400 happened vs 200.

This happens like 50% of the time but the other 50% I get a 200 and the image is stored just fine.

Any idea where to look next to see the real reason behind the 400? I don't have enough information at this point to debug. 400 just means Mal-formed post but what is Mal formed?

答:
Look in nginx error log; you might need to enable it:

https://www.nginx.com/resources/admin-guide/logging-and-monitoring/


问:
React native use fetch inside for loop
In my React native app, I have an array of objects, each object has 3 properties: address, latitude and longitude. Latitude and longitude are initially null, so I m using google api for reverse geocoding. Since it is an array, I m looping inside my array and fetch google url to get lat and lng from given address. But when I try to save latitude and longitude inside my object, I have an error:

TypeError: undefined is not an object (evaluating:
  locations[i].latitude =
  responseJson.results[0].geometry.location.lat)

Here is my code:

for (var i = 0; i < locations.length; i++){

          if (locations[i].address){

            var googleRequestUrl = this.state.GoogleAPIUrl + locations[i].address;

            fetch(googleRequestUrl)
            .then((response) => response.json())
            .then((responseJson) => {
              locations[i].latitude = responseJson.results[0].geometry.location.lat;
              locations[i].longitude = responseJson.results[0].geometry.location.lng;
            })
            .catch((error) => {
              console.warn(error);
            })
            .done();
          }
        }```

The google API I m using is: "https://maps.googleapis.com/maps/api/geocode/json?address="

I have already checked if I m getting the response with response.text(): it gives me a complete response, with lat and lng.

I cannot understand why it gives me that error, what am I doing wrong? Is there something wrong with having fetch inside a loop? Or the problem is something else?

Any suggestions or better solutions are appreciated

答:
this code:

```<code>.then((responseJson) => {
    locations[i].latitude = responseJson.results[0].geometry.location.lat;
    locations[i].longitude = responseJson.results[0].geometry.location.lng;
})
</code>```

isn't going to do what you want it to do.

Since this bit of code runs asynchronously, it will use the value of i that it finds at the time of execution.  And by time you get a response from the server, your for loop will already have completed execution.  And the value of i at the end of the for loop?  It will be 4.

So you will be trying to store the value (for every fetch) in locations[4] which is undefined.

To fix this issue, you could do a couple things:

1. The easiest, if you are using ES6 is to declare a constant in the for loop equal to the loop variable.  This basically creates a closure over the index to allow you to reference the correct value later.  It'll look something like:

```<code>for (var i = 0; i < locations.length; i++){
    if (locations[i].address){
        var googleRequestUrl = this.state.GoogleAPIUrl + locations[i].address;

        const index = i;
        fetch(googleRequestUrl)
        .then((response) => response.json())
        .then((responseJson) => {
            locations[index].latitude = responseJson.results[0].geometry.location.lat;
            locations[index].longitude = responseJson.results[0].geometry.location.lng;
        })
        .catch((error) => {
            console.warn(error);
        })
        .done();
    }
}
</code>```

pass the loop variable to another function that fetches the data and performs the change

use an array map function that basically does #2 but with anonymous functions

```</p>

```locations.map((location) => {
    if (location.address) {
        var googleRequestUrl = this.state.GoogleAPIUrl + location.address;
        fetch(googleRequestUrl)
        .then((response) => response.json())
        .then((responseJson) => {
            location.latitude = responseJson.results[0].geometry.location.lat;
            location.longitude = responseJson.results[0].geometry.location.lng;
        })
        .catch((error) => {
            console.warn(error);
        })
        .done();
    }
);
```

ContentLicense: CC BY-SA 4.0

Title: React native use fetch inside for loop

Body:
In my React native app, I have an array of objects, each object has 3 properties: address, latitude and longitude. Latitude and longitude are initially null, so I m using google api for reverse geocoding. Since it is an array, I m looping inside my array and fetch google url to get lat and lng from given address. But when I try to save latitude and longitude inside my object, I have an error:

TypeError: undefined is not an object (evaluating:
  locations[i].latitude =
  responseJson.results[0].geometry.location.lat)

Here is my code:

for (var i = 0; i < locations.length; i++){

          if (locations[i].address){

            var googleRequestUrl = this.state.GoogleAPIUrl + locations[i].address;

            fetch(googleRequestUrl)
            .then((response) => response.json())
            .then((responseJson) => {
              locations[i].latitude = responseJson.results[0].geometry.location.lat;
              locations[i].longitude = responseJson.results[0].geometry.location.lng;
            })
            .catch((error) => {
              console.warn(error);
            })
            .done();
          }
        }

The google API I m using is: "https://maps.googleapis.com/maps/api/geocode/json?address="

I have already checked if I m getting the response with response.text(): it gives me a complete response, with lat and lng.

I cannot understand why it gives me that error, what am I doing wrong? Is there something wrong with having fetch inside a loop? Or the problem is something else?

Any suggestions or better solutions are appreciated

Body:
this code:

.then((responseJson) => {
    locations[i].latitude = responseJson.results[0].geometry.location.lat;
    locations[i].longitude = responseJson.results[0].geometry.location.lng;
})

isn't going to do what you want it to do.

Since this bit of code runs asynchronously, it will use the value of i that it finds at the time of execution.  And by time you get a response from the server, your for loop will already have completed execution.  And the value of i at the end of the for loop?  It will be 4.

So you will be trying to store the value (for every fetch) in locations[4] which is undefined.

To fix this issue, you could do a couple things:

1. The easiest, if you are using ES6 is to declare a constant in the for loop equal to the loop variable.  This basically creates a closure over the index to allow you to reference the correct value later.  It'll look something like:

for (var i = 0; i < locations.length; i++){
    if (locations[i].address){
        var googleRequestUrl = this.state.GoogleAPIUrl + locations[i].address;

        const index = i;
        fetch(googleRequestUrl)
        .then((response) => response.json())
        .then((responseJson) => {
            locations[index].latitude = responseJson.results[0].geometry.location.lat;
            locations[index].longitude = responseJson.results[0].geometry.location.lng;
        })
        .catch((error) => {
            console.warn(error);
        })
        .done();
    }
}

pass the loop variable to another function that fetches the data and performs the change

use an array map function that basically does #2 but with anonymous functions

```

locations.map((location) => {
    if (location.address) {
        var googleRequestUrl = this.state.GoogleAPIUrl + location.address;
        fetch(googleRequestUrl)
        .then((response) => response.json())
        .then((responseJson) => {
            location.latitude = responseJson.results[0].geometry.location.lat;
            location.longitude = responseJson.results[0].geometry.location.lng;
        })
        .catch((error) => {
            console.warn(error);
        })
        .done();
    }
);


问:
Does Binding work ONLY with DependencyProperty?
MSDN says,

Each binding typically has these four components: a binding target
  object, a target property, a binding
  source, and a Path to the value in the
  binding source to use. For example, if
  you want to bind the content of a
  TextBox to the Name property of an
  Employee object, your target object is
  the TextBox, the target property is
  the Text property, the value to use is
  Name, and the source object is the
  Employee object.

The target property must be a dependency property.

The above excerpt explains why the following code works,

```<code><TextBox Text="{Binding EmployeeName}">
</code>```

It works because Text is a dependency property. Upto this point, everything is fine!

My question is,

IF target property must be a dependency property for Binding to work, then how does the folllowing Setter work? Please note that Value in Setter is NOT a dependency property!

```<code><Style TargetType="{x:Type TextBox}">
      <Setter Property="Text" Value="{Binding EmployeeName}"/>
</Style>
</code>```

I've an explanation for it. But I'm not sure if that is correct. Let me first explain it, and then, you guys correct me if I'm wrong. :-)

I think, since the type of Value is Object, that means, it can hold instances of ANY type. It can hold an instance of even Binding type. It, however, cannot take part in the process of evaluating (or resolving) the Binding expression, since it's not a dependency property. So Style object simply transfers this Binding object (which Value holds) from Setter to the TextBox as such, without evaluating/resolving the Binding value. As such the above Setter becomes equivalent to this:

```<code> Text="{Binding EmployeeName}"
</code>```

And since now, Text is a dependency property, it can resolve the Binding value. So it first appears that target of binding is Value, but in reality, Text is the target of the binding.

It's like Setter is a postman, Value itself is postman's Bag, Binding instance (i.e what Value holds) is a Letter. Postman (i.e Setter) delivers the Letter(i.e Binding instance) to the Target (i.e Text property), without opening it, i.e without knowing what Message (i.e EmployeeName) the Letter carries.

Please correct me if I'm wrong.

答:
That's correct. If you look at the source code of WPF toolkit controls you can see how it's done. The DataGrid does it in quite a few places (e.g. specific columns passing the Content binding to the cell). I'll try to remember to add a link to a specific file and line where it's done after work.

Edit
A good example is the Binding property in the DataGridBoundColumn class. You can see it used in

```<code>internal void ApplyBinding(DependencyObject target, DependencyProperty property)
</code>```

If you're interested in advanced patterns to make WPF and Silverlight controls I highly recommend looking through their respective toolkits. They're well-commented in general and some of the controls are using some cool code.

ContentLicense: CC BY-SA 2.5

Body:
MSDN says,

Each binding typically has these four components: a binding target
  object, a target property, a binding
  source, and a Path to the value in the
  binding source to use. For example, if
  you want to bind the content of a
  TextBox to the Name property of an
  Employee object, your target object is
  the TextBox, the target property is
  the Text property, the value to use is
  Name, and the source object is the
  Employee object.

The target property must be a dependency property.

The above excerpt explains why the following code works,

<TextBox Text="{Binding EmployeeName}">

It works because Text is a dependency property. Upto this point, everything is fine!

My question is,

IF target property must be a dependency property for Binding to work, then how does the folllowing Setter work? Please note that Value in Setter is NOT a dependency property!

I've an explanation for it. But I'm not sure if that is correct. Let me first explain it, and then, you guys correct me if I'm wrong. :-)

I think, since the type of Value is Object, that means, it can hold instances of ANY type. It can hold an instance of even Binding type. It, however, cannot take part in the process of evaluating (or resolving) the Binding expression, since it's not a dependency property. So Style object simply transfers this Binding object (which Value holds) from Setter to the TextBox as such, without evaluating/resolving the Binding value. As such the above Setter becomes equivalent to this:

 Text="{Binding EmployeeName}"

And since now, Text is a dependency property, it can resolve the Binding value. So it first appears that target of binding is Value, but in reality, Text is the target of the binding.

It's like Setter is a postman, Value itself is postman's Bag, Binding instance (i.e what Value holds) is a Letter. Postman (i.e Setter) delivers the Letter(i.e Binding instance) to the Target (i.e Text property), without opening it, i.e without knowing what Message (i.e EmployeeName) the Letter carries.

Please correct me if I'm wrong.

Body:
That's correct. If you look at the source code of WPF toolkit controls you can see how it's done. The DataGrid does it in quite a few places (e.g. specific columns passing the Content binding to the cell). I'll try to remember to add a link to a specific file and line where it's done after work.

Edit
A good example is the Binding property in the DataGridBoundColumn class. You can see it used in

internal void ApplyBinding(DependencyObject target, DependencyProperty property)

If you're interested in advanced patterns to make WPF and Silverlight controls I highly recommend looking through their respective toolkits. They're well-commented in general and some of the controls are using some cool code.


问:
UIDocumentInteractionController file attachment error
so I'm working on exporting a .txt file from Xcode, but whenever I try to export it, say through email, it creates an email with no attachments and an empty message. When I try to export it to iCloud Drive, a white screen comes up for a second, then leaves. When I check iCloud Drive, the file isn't there. What is wrong here?</p>

```<code>let message = testLabel.text

func getDocumentsDirectory() -> NSString {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory as NSString
}

let filePath = getDocumentsDirectory().appendingPathComponent("matrixFile.txt")

do{
    try message?.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
}catch let error as NSError{
    testLabel.text = String(describing: error)
}

let documentInteractionController = UIDocumentInteractionController()
documentInteractionController.url = NSURL.fileURL(withPath: filePath)
documentInteractionController.uti = "public.data, public.content"
documentInteractionController.name = "matrixFile"
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
</code>```

答:
Your UTI is wrong. For a text file you should use "public.text". But there is a constant for this already - kUTTypePlainText. You just need to import MobileCoreServices to use it.

```<code>import MobileCoreServices
</code>```

then:

```<code>documentInteractionController.uti = kUTTypePlainText as String
</code>```

You should also use the proper initializer when creating the controller:

```<code>let documentInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: filePath))
documentInteractionController.uti = kUTTypePlainText as String
documentInteractionController.name = "matrixFile"
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
</code>```

And I would only create and show the controller if the text isn't nil and you successfully write the file:

```<code>if let message = testLabel.text {
    let filePath = getDocumentsDirectory().appendingPathComponent("matrixFile.txt")

    do {
        try message.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
        let documentInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: filePath))
        documentInteractionController.uti = kUTTypePlainText as String
        documentInteractionController.name = "matrixFile"
        documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
    } catch let error as NSError {
        testLabel.text = String(describing: error)
    }
}
</code>```

Body:
so I'm working on exporting a .txt file from Xcode, but whenever I try to export it, say through email, it creates an email with no attachments and an empty message. When I try to export it to iCloud Drive, a white screen comes up for a second, then leaves. When I check iCloud Drive, the file isn't there. What is wrong here?

let message = testLabel.text

func getDocumentsDirectory() -> NSString {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory as NSString
}

let filePath = getDocumentsDirectory().appendingPathComponent("matrixFile.txt")

do{
    try message?.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
}catch let error as NSError{
    testLabel.text = String(describing: error)
}

let documentInteractionController = UIDocumentInteractionController()
documentInteractionController.url = NSURL.fileURL(withPath: filePath)
documentInteractionController.uti = "public.data, public.content"
documentInteractionController.name = "matrixFile"
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)

Body:
Your UTI is wrong. For a text file you should use "public.text". But there is a constant for this already - kUTTypePlainText. You just need to import MobileCoreServices to use it.

import MobileCoreServices

then:

documentInteractionController.uti = kUTTypePlainText as String

You should also use the proper initializer when creating the controller:

let documentInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: filePath))
documentInteractionController.uti = kUTTypePlainText as String
documentInteractionController.name = "matrixFile"
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)

And I would only create and show the controller if the text isn't nil and you successfully write the file:

if let message = testLabel.text {
    let filePath = getDocumentsDirectory().appendingPathComponent("matrixFile.txt")

    do {
        try message.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
        let documentInteractionController = UIDocumentInteractionController(url: URL(fileURLWithPath: filePath))
        documentInteractionController.uti = kUTTypePlainText as String
        documentInteractionController.name = "matrixFile"
        documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
    } catch let error as NSError {
        testLabel.text = String(describing: error)
    }
}


问:
awk Getting ALL line but last field with the delimiters
I have to make a one-liner that renames all files in the current directory
that end in ".hola" to ".txt".

For example:

sample.hola and name.hi.hola will be renamed to sample.txt and name.hi.txt respectively

I was thinking about something like:

ls -1 *.hola | awk '{NF="";print "$0.hola $0.txt"}' (*)

And then passing the stdin to xargs mv -T with a |

But the output of (*) for the example would be sample and name hi.

How do I get the output name.hi for name.hi.hola using awk?

答:
Well, for your specific problem, I recommend the rename command. Depending on the version on your system, you can do either rename -s .hola .txt *.hola, or rename 's/\.hola$/.txt/' *.hola.

Also, you shouldn't use ls to get filenames. When you run ls *.hola, the shell expands *.hola to a list of all the filenames matching that pattern, and ls is just a glorified echo at that point. You can get the same result using e.g. printf '%s\n' *.hola without running any program outside the shell.

And your awk is missing any attempt to remove the .hola. If you have GNU awk, you can do something like this:

```<code>awk -F. '{old=$0; NF-=1; new=$0".txt"; print old" "new}'
</code>```

That won't work on BSD/MacOS awk. In that case you can do something like this:

```<code>awk -F. '{
  old=$0; new=$1;
  for (i=2;i<NF;++i) { new=new"."$i };
  print old" "new".txt"; }'
</code>```

Either way, I'm sure @EdMorton probably has a better awk-based solution.

Body:
Well, for your specific problem, I recommend the rename command. Depending on the version on your system, you can do either rename -s .hola .txt *.hola, or rename 's/\.hola$/.txt/' *.hola.

Also, you shouldn't use ls to get filenames. When you run ls *.hola, the shell expands *.hola to a list of all the filenames matching that pattern, and ls is just a glorified echo at that point. You can get the same result using e.g. printf '%s\n' *.hola without running any program outside the shell.

And your awk is missing any attempt to remove the .hola. If you have GNU awk, you can do something like this:

awk -F. '{old=$0; NF-=1; new=$0".txt"; print old" "new}'

That won't work on BSD/MacOS awk. In that case you can do something like this:

awk -F. '{
  old=$0; new=$1;
  for (i=2;i<NF;++i) { new=new"."$i };
  print old" "new".txt"; }'

Either way, I'm sure @EdMorton probably has a better awk-based solution.


问:
Wpf Window "super class"
Some 30 years ago, I developed a big app for fresh fruit packers. I followed a nice paradigm, taken from Informix-4GL: the same screen allows the user to set a "query by example" or to insert a new "record", or update one of them after a successfully one. It maintained a "current list" (the resulting query result and the new records added) wich could be navegated with PgUp and PgDwn Keys. Of course, all that stuff was expressed as mapped text.
The very important thing is that the screen was idle until the user did a "command" to start a new query, an insert or update (or even a delete) operation.
Now, it's the time to evolve that app.
I'm thinking in Wpf and its Preview* group of routed events, to catch the main user "command".
But because there are lots of screens (near one for every entity in the database) it's important to set what is common between them.
Is it the best way (in Wpf) to set one or two "super classes" of Windows for this approach?
TIA </p>

答:
Technically — sure, you can create a class that inherits from System.Windows.Window, have all windows in your app inherit from that one, and implement some common logic in that class.

However, this approach is not considered a best practice for WPF and other XAML-based platforms. Your window and other GUI classes should only contain code specific to presentation. Your model classes that handle the DB queries should not depend on the exact GUI you’re using to present these models.

While not required, a third-party MVVM library is helpful to e.g. provide design-time models for the IDE. As for the specific library, lately I prefer Caliburn Micro, before that I had positive experience with MVVM Light.

With MVVM, it’s fine to have a base model class with some logic that’s common across different model classes. In fact, many libraries encourage you to do so. They provide their own base classes for your models. Such as Screen or PropertyChangedBase from Caliburn Micro.

Title: Wpf Window "super class"


问:
How do I spread out the tabs in AppBar?
I'm trying to spread out these tabs on my app. I have looked around but I can't find anything about it.

What I want is Tab1 to be on the left, Tab3 on the way right and Tab2 in the middle.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable">

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Tab1" />

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Tab2" />

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Tab3" />
    </android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.master.moonbot.MoonBot">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</code>```

答:
Delete app:tabMode="scrollable" and it will default to fixed.</p>

```<code><android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
</code>```

Title: How do I spread out the tabs in AppBar?

Body:
I'm trying to spread out these tabs on my app. I have looked around but I can't find anything about it.

What I want is Tab1 to be on the left, Tab3 on the way right and Tab2 in the middle.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable">

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Tab1" />

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Tab2" />

        <android.support.design.widget.TabItem
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Tab3" />
    </android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.master.moonbot.MoonBot">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

Body:
Delete app:tabMode="scrollable" and it will default to fixed.

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >


问:
bash vs csh vs others - which is better for application maintenance?

Possible Duplicate:

  What Linux shell should I use?

I am starting to get proficient in a Linux environment and i'm trying to pick a weapon of choice in terms of command shell scripting (as i'm still a big n00b at this) that will help me (and others) manage, test and administer a set of server side applications running on a *NIX environment.

My question is: What is(are) the preferred command shell(s)  out there when the following criteria are considered:

How easy is it to learn/understand for a junior dev who has never had an exposure to shell scripting?

Is there a big pool of developers out there that know this shell script?

Is it safe and easy to use - will script errors be silent or give intelligent error output, will it let the uninitiated shoot them selves in the foot?

How portable is it? - Can i expect the same script to run in OpenSolaris as well as Redhat, FreeBSD? (granted command syntax and options for specific OS will change accordingly)

How standard is it? Is it expected to be included on most distro's of *NIX or does it have to be installed additionally?

I understand that there are camps out there who hold strong feelings for/against specific command shells, i am just looking for an informed opinion.

答:
bash is the standard and is very good at interactive use (good completion supporting many programs, history, readline support, many kinds of string expansion). It is also good at scripting, for a shell (arrays and hashes, quoting, string manipulation); though writing reliable scripts requires you to learn a lot more.

If you want your programs to be able to grow, work with elaborate data structures, and use some useful libraries, you should learn a language like python, ruby or perl. Most of those have interactive interpreters as well, not as convenient as a shell but useful for quick testing. IPython, for Python, is particularly useful; it lets you explore documentation very easily, can load and reload source, includes a debugger. It also includes some standard shell commands and can pass the rest to a standard shell by prefixing them with a !.

Thanks to being interactive most shells are easy enough to learn once you start using them exclusively

I believe bash, and the posix subset, is better known by a wide margin. But the languages I mentioned are as well known as many shells.

You can easily shoot yourself in the foot, convenience often makes undesirable things easy.

and 5. Portability of the shell itself shouldn't be a problem; you may need to recompile to get more modern features on some of the OSes you mention. Using a full-blown language with its own libraries will help smoothe the variation of your multiplicity of platforms.


问:
error in java package after add watson developer cloud library
I tried to make a TTS app using watson TTS and bluemix, but when I use this code

```<code>compile 'com.ibm.watson.developer_cloud:text-to-speech:3.5.1'
</code>```

to add watson developer cloud library, there is an error showing in MyApplication.java saying that:

'com.ibm.mobilefirstplatform.clientsdk.android.core.api.BMSClient
  package does not exist'

Please help.

Screenshot:

答:
I'm a contributor in the com.ibm.watson.developer_cloud:text-to-speech module and we don't have any dependency to com.ibm.mobilefirstplatform.clientsdk.android.core.api.BMSClient.

I think the problem is in another dependency not in the text-to-speech.

Body:
I tried to make a TTS app using watson TTS and bluemix, but when I use this code

compile 'com.ibm.watson.developer_cloud:text-to-speech:3.5.1'

to add watson developer cloud library, there is an error showing in MyApplication.java saying that:

'com.ibm.mobilefirstplatform.clientsdk.android.core.api.BMSClient
  package does not exist'

Please help.

Screenshot:


答:
Given you are just trying to drop them then you can drop the min twice:</p>

```<code>In [1]:
d = { ... }
for _ in range(2):
    del d[min(d, key=d.get)]
print(d)

Out[1]:
{('F2', 'F1'): 0.9154929577464789, ('F4', 'F3'): 0.9130434782608695}
</code>```

Title: Drop dict entries with the lowest values

Body:
In the following dict how can I drop the two entries with the lowest values?

{('F2', 'F1'): 0.9154929577464789,
 ('F2', 'F3'): 0.8285714285714286,
 ('F4', 'F1'): 0.8285714285714286,
 ('F4', 'F3'): 0.9130434782608695}

Body:
Given you are just trying to drop them then you can drop the min twice:

In [1]:
d = { ... }
for _ in range(2):
    del d[min(d, key=d.get)]
print(d)

Out[1]:
{('F2', 'F1'): 0.9154929577464789, ('F4', 'F3'): 0.9130434782608695}


问:
How to imitate the html BR tag with javascript
Hello right now I have 3 things in the body after the div.

A button and two images. What I want to do is for them to have a new line so the button is in one line, the image is in their own line and the second image is in their own line also.

I tried document.write("
") but it just completely breaks my code.here is the current code

```<code>var button = document.createElement("button");
button.innerHTML = "Do Something";
document.body.appendChild(button)

var img7 = document.createElement('img')
img7.src = 'g.png'
document.body.appendChild(img7)

var img8 = document.createElement('img')
img8.src = 'h.png'
document.body.appendChild(img8)
</code>```

it is in pure javascript so there i can't use
 to break a new line

答:
You can create and append a
 in JavaScript the same way you did for each :

```<code>var button = document.createElement("button");
button.innerHTML = "Do Something";
document.body.appendChild(button)

var br = document.createElement('br')
document.body.appendChild(br)

var img7 = document.createElement('img')
img7.src = 'g.png'
document.body.appendChild(img7)

document.body.appendChild(br.cloneNode())

var img8 = document.createElement('img')
img8.src = 'h.png'
document.body.appendChild(img8)
</code>```

Body:
Hello right now I have 3 things in the body after the div.

A button and two images. What I want to do is for them to have a new line so the button is in one line, the image is in their own line and the second image is in their own line also.

I tried document.write("
") but it just completely breaks my code.here is the current code

var button = document.createElement("button");
button.innerHTML = "Do Something";
document.body.appendChild(button)

var img7 = document.createElement('img')
img7.src = 'g.png'
document.body.appendChild(img7)

var img8 = document.createElement('img')
img8.src = 'h.png'
document.body.appendChild(img8)

it is in pure javascript so there i can't use
 to break a new line

Body:
You can create and append a <br> in JavaScript the same way you did for each <img>:

var button = document.createElement("button");
button.innerHTML = "Do Something";
document.body.appendChild(button)

var br = document.createElement('br')
document.body.appendChild(br)

var img7 = document.createElement('img')
img7.src = 'g.png'
document.body.appendChild(img7)

document.body.appendChild(br.cloneNode())

var img8 = document.createElement('img')
img8.src = 'h.png'
document.body.appendChild(img8)


问:
Get root website url in javascript for redirect
I want to redirect to Login page from every page in my website after session timeout.
I try to set window.location to the login page:

```<code>var ParentUrl = encodeURIComponent(window.parent.location.href);
document.location.href = "~/Login.appx?ReturnUrl=" + ParentUrl;
</code>```

but "~" seems to be unsupported.
my Login page is located under my root folder.

for example:
*http://server/website/*Login.aspx

How can I get this url in javascript?

Thanks a lot,

Inbal.

答:
I modified PerKristian's answer so it would work in my situation,

```<code>function getBaseUrl() {
    var re = new RegExp(/^.*\/\/[^\/]+/);
    return re.exec(window.location.href);
}
</code>```

matches everything up till the first lone /

for example

http://stackoverflow.com/questions/14135479/get-root-website-url-in-javascript-for-redirect

will return http://stackoverflow.com

Body:
I want to redirect to Login page from every page in my website after session timeout.
I try to set window.location to the login page:

var ParentUrl = encodeURIComponent(window.parent.location.href);
document.location.href = "~/Login.appx?ReturnUrl=" + ParentUrl;

but "~" seems to be unsupported.
my Login page is located under my root folder.

for example:
*http://server/website/*Login.aspx

How can I get this url in javascript?

Thanks a lot,

Inbal.

Body:
I modified PerKristian's answer so it would work in my situation,

function getBaseUrl() {
    var re = new RegExp(/^.*\/\/[^\/]+/);
    return re.exec(window.location.href);
}

matches everything up till the first lone /

for example

http://stackoverflow.com/questions/14135479/get-root-website-url-in-javascript-for-redirect

will return http://stackoverflow.com


问:
avoiding nested for loops python
I have a function which takes in expressions and replaces the variables with all the permutations of the values that I am using as inputs. This is my code that I have tested and works, however after looking through SO, people have said that nested for loops are a bad idea however I am unsure as to how to make this more efficient. Could somebody help? Thanks. </p>

```<code>def replaceVar(expression):

    eval_list = list()

    a = [1, 8, 12, 13]
    b = [1, 2, 3, 4]
    c = [5, 9, 2, 7]

    for i in expression:
        first_eval = [i.replace("a", str(j)) for j in a]
        tmp = list()
        for k in first_eval:
            snd_eval = [k.replace("b", str(l)) for l in b]
            tmp2 = list()
            for m in snd_eval:
                trd_eval = [m.replace("c", str(n)) for n in c]
                tmp2.append(trd_eval)
            tmp.append(tmp2)
        eval_list.append(tmp)
    print(eval_list)
    return eval_list

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))
</code>```

答:
So, your current structure addresses one of the inefficiencies that the solutions with itertools.product will not address. Your code is saving the intermediately substituted expressions and reusing them, rather than redoing these substitutions with each itertools.product tuple. This is good and I think your current code is efficient.

However, it is brittle and only works when substituting in exactly three variables. A dynamic programming approach can solve this issue. To do so, I'm going to slightly alter the input parameters. The function will use two inputs:

expressions - The expressions to be substituted into

replacement_map - A dictionary which provides the values to substitute for each variable

The dynamic programming function is given below:

```<code>def replace_variable(expressions, replacement_map):
    return [list(_replace_variable([e], replacement_map)) for e in expressions]

def _replace_variable(expressions, replacement_map):
    if not replacement_map:
        for e in expressions:
            yield e
    else:
        map_copy = replacement_map.copy()
        key, value_list = map_copy.popitem()
        for value in value_list:
            substituted = [e.replace(key, value) for e in expressions]
            for e in _replace_variable(substituted, map_copy):
                yield e
</code>```

With the example usage:

```<code>expressions = ['a+b', 'a-b']

replacement_map = {
    'a': ['1', '2'],
    'b': ['3', '4']
}

print replace_variable(expressions, replacement_map)
# [['1+3', '1+4', '2+3', '2+4'], ['1-3', '1-4', '2-3', '2-4']]
</code>```

Note that if you're using Python 3.X, you can use the yield from iterator construct instead of reiterating over e twice in _replace_variables. This function would look like:

```<code>def _replace_variable(expressions, replacement_map):
    if not replacement_map:
        yield from expressions

    else:
        map_copy = replacement_map.copy()
        key, value_list = map_copy.popitem()
        for value in value_list:
            substituted = [e.replace(key, value) for e in expressions]
            yield from _replace_variable(substituted, map_copy)
</code>```

Title: avoiding nested for loops python

Body:
I have a function which takes in expressions and replaces the variables with all the permutations of the values that I am using as inputs. This is my code that I have tested and works, however after looking through SO, people have said that nested for loops are a bad idea however I am unsure as to how to make this more efficient. Could somebody help? Thanks.

def replaceVar(expression):

    eval_list = list()

    a = [1, 8, 12, 13]
    b = [1, 2, 3, 4]
    c = [5, 9, 2, 7]

    for i in expression:
        first_eval = [i.replace("a", str(j)) for j in a]
        tmp = list()
        for k in first_eval:
            snd_eval = [k.replace("b", str(l)) for l in b]
            tmp2 = list()
            for m in snd_eval:
                trd_eval = [m.replace("c", str(n)) for n in c]
                tmp2.append(trd_eval)
            tmp.append(tmp2)
        eval_list.append(tmp)
    print(eval_list)
    return eval_list

print(replaceVar(['b-16+(c-(a+11))', 'a-(c-5)+a-b-10']))

Body:
So, your current structure addresses one of the inefficiencies that the solutions with itertools.product will not address. Your code is saving the intermediately substituted expressions and reusing them, rather than redoing these substitutions with each itertools.product tuple. This is good and I think your current code is efficient.

However, it is brittle and only works when substituting in exactly three variables. A dynamic programming approach can solve this issue. To do so, I'm going to slightly alter the input parameters. The function will use two inputs:

expressions - The expressions to be substituted into

replacement_map - A dictionary which provides the values to substitute for each variable

The dynamic programming function is given below:

def replace_variable(expressions, replacement_map):
    return [list(_replace_variable([e], replacement_map)) for e in expressions]

def _replace_variable(expressions, replacement_map):
    if not replacement_map:
        for e in expressions:
            yield e
    else:
        map_copy = replacement_map.copy()
        key, value_list = map_copy.popitem()
        for value in value_list:
            substituted = [e.replace(key, value) for e in expressions]
            for e in _replace_variable(substituted, map_copy):
                yield e

With the example usage:

expressions = ['a+b', 'a-b']

replacement_map = {
    'a': ['1', '2'],
    'b': ['3', '4']
}

print replace_variable(expressions, replacement_map)
# [['1+3', '1+4', '2+3', '2+4'], ['1-3', '1-4', '2-3', '2-4']]

Note that if you're using Python 3.X, you can use the yield from iterator construct instead of reiterating over e twice in _replace_variables. This function would look like:

def _replace_variable(expressions, replacement_map):
    if not replacement_map:
        yield from expressions

    else:
        map_copy = replacement_map.copy()
        key, value_list = map_copy.popitem()
        for value in value_list:
            substituted = [e.replace(key, value) for e in expressions]
            yield from _replace_variable(substituted, map_copy)


问:
Convert each bit in byte to first bit of each nibble in 32 bit int
I have a byte b. I am looking for the most efficient bit manipulation to
convert each bit in b to the first bit of each nibble in a 32 bit int x.

For example, if b = 01010111, then x = 0x10101111

I know I can do a brute force approach:

```<code>x = (b&1) | (((b>>1)&1)<<4) | ......
</code>```

Edit: this for an OpenCL kernel for GPU

答:
PDEP

As user harold mentioned in the comments, PDEP is the instruction that just does exactly what you want - but it's only available on x86 (as far as I know), and it has terrible1 performance on the newest AMD chips.

LUT

Barring that, a lookup table of 256 x 4-byte entries  seems reasonable - at the cost of 1K of pressure on your cache subsystem. You'll find a lot of smart people advocate against LUTs due to the hidden cost of cache misses - but if this particular operation is in fact "hot" then it may turn out to be the fastest even when factoring in any additional misses.

As with any LUT solution, you should be especially careful to benchmark it not only with micro-benchmarks, but in the full application to evaluate the effect of memory pressure.

You could also consider a compromise split-LUT solution that uses one or two 16-entry LUTs for each nibble of the byte, where the result is calculated something like:

```<code>int32 x = high_lut[(b & 0xF0) >> 4] | low_lut[b & 0xF]
</code>```

This cuts the size of the LUTs down by a factor of between ~11 to 322, since we have much fewer entries and some entries can be 2 bytes rather than 4 bytes.

Bit Manipulation

If you really want a bit manipulation solution, to impress your inlaws or something, you can try something like the following:

Split the byte into nibbles and use multiplication by 0x00001111 (low nibble) and 0x01111000 (high nibble) to splat the low (resp. high) nibble into the low (resp high) half of the 4-byte word, and combine the results with or or add. So if your byte had bits abcd efgh you'll have a word like abcd abcd abcd abcd efgh efgh efgh efgh.

and this result with a mask that picks out the bit that belongs in each nibble (although it usually won't be in the right place). The mask is something like 0x84218421 and the result (in binary) will be something like a000 0b00 00c0 000d e000 0f00 00g0 000h.

Now move the 6 out of 8 bits that aren't in the high bit to the right position using the carry behavior of subtraction, something like: ((x | 0x08880888) - 0x01110111) ^ 0x08880888.

The basic idea in the last step is that you set the high bit of each nibble, and subtract 1 from the nibble. So for example, you have the 0b00 nibble, which becomes 1b00 - 1 - the subtraction carries though all the zeros, and stops at the first one, which is either the high bit (b is zero) or b if it is one. So you effectively set the high bit based on the value of the selected bit. Note that you don't need to do this for a or e since they are already in the right place.

The final xor is needed because the above actually sets the high bit to the opposite value as the selected bit, so we need to flip it.

I didn't try it out, so there are no doubt bugs, but the basic idea should be sound. There is probably various ways to optimize it further, but it's not too bad as is: a couple of multiplications and perhaps a half-dozen bit-operations. On platforms with slow multiplications you can probably find another approach for the first step that uses only 1 multiplication combined with a few more primitive operations, or zero at the cost of several more operations.

1 Fully 18x worse throughput than Intel - evidently AMD opted not to implement the circuit to do PDEP in hardware and instead implement it via a series of more elementary operations.

2 The largest reduction is if you share a single 16-entry LUT for both the high and low nibble, although this requires an additional shift for the result of the high nibble lookup. The smaller reduction, shown in the example, uses two 16-entry LUTs: one 4-byte one for the high nibble, and a 2-byte one for the low nibble, and avoids the shift.

Body:
I have a byte b. I am looking for the most efficient bit manipulation to
convert each bit in b to the first bit of each nibble in a 32 bit int x.

For example, if b = 01010111, then x = 0x10101111

I know I can do a brute force approach:

x = (b&1) | (((b>>1)&1)<<4) | ......

Edit: this for an OpenCL kernel for GPU

Body:
PDEP

As user harold mentioned in the comments, PDEP is the instruction that just does exactly what you want - but it's only available on x86 (as far as I know), and it has terrible1 performance on the newest AMD chips.

LUT

Barring that, a lookup table of 256 x 4-byte entries  seems reasonable - at the cost of 1K of pressure on your cache subsystem. You'll find a lot of smart people advocate against LUTs due to the hidden cost of cache misses - but if this particular operation is in fact "hot" then it may turn out to be the fastest even when factoring in any additional misses.

As with any LUT solution, you should be especially careful to benchmark it not only with micro-benchmarks, but in the full application to evaluate the effect of memory pressure.

You could also consider a compromise split-LUT solution that uses one or two 16-entry LUTs for each nibble of the byte, where the result is calculated something like:

int32 x = high_lut[(b & 0xF0) >> 4] | low_lut[b & 0xF]

This cuts the size of the LUTs down by a factor of between ~11 to 322, since we have much fewer entries and some entries can be 2 bytes rather than 4 bytes.

Bit Manipulation

If you really want a bit manipulation solution, to impress your inlaws or something, you can try something like the following:

Split the byte into nibbles and use multiplication by 0x00001111 (low nibble) and 0x01111000 (high nibble) to splat the low (resp. high) nibble into the low (resp high) half of the 4-byte word, and combine the results with or or add. So if your byte had bits abcd efgh you'll have a word like abcd abcd abcd abcd efgh efgh efgh efgh.

and this result with a mask that picks out the bit that belongs in each nibble (although it usually won't be in the right place). The mask is something like 0x84218421 and the result (in binary) will be something like a000 0b00 00c0 000d e000 0f00 00g0 000h.

Now move the 6 out of 8 bits that aren't in the high bit to the right position using the carry behavior of subtraction, something like: ((x | 0x08880888) - 0x01110111) ^ 0x08880888.

The basic idea in the last step is that you set the high bit of each nibble, and subtract 1 from the nibble. So for example, you have the 0b00 nibble, which becomes 1b00 - 1 - the subtraction carries though all the zeros, and stops at the first one, which is either the high bit (b is zero) or b if it is one. So you effectively set the high bit based on the value of the selected bit. Note that you don't need to do this for a or e since they are already in the right place.

The final xor is needed because the above actually sets the high bit to the opposite value as the selected bit, so we need to flip it.

I didn't try it out, so there are no doubt bugs, but the basic idea should be sound. There is probably various ways to optimize it further, but it's not too bad as is: a couple of multiplications and perhaps a half-dozen bit-operations. On platforms with slow multiplications you can probably find another approach for the first step that uses only 1 multiplication combined with a few more primitive operations, or zero at the cost of several more operations.

1 Fully 18x worse throughput than Intel - evidently AMD opted not to implement the circuit to do PDEP in hardware and instead implement it via a series of more elementary operations.

2 The largest reduction is if you share a single 16-entry LUT for both the high and low nibble, although this requires an additional shift for the result of the high nibble lookup. The smaller reduction, shown in the example, uses two 16-entry LUTs: one 4-byte one for the high nibble, and a 2-byte one for the low nibble, and avoids the shift.


问:
MySQL Querying Duplicates
So, I have a database called teams, and it currently looks like this:

```<code>team_id | leader_id | student_id
1       | 123456    | 1234
2       | 1234      | 123456, 1234567890
3       | 1234      | 123456
4       | 0         | 12345, 1234, 1234567890
5       | 0         |
6       | 0         |
</code>```

My students database looks like this

```<code>student_id | first_name | last_name
123456     | qwer       | qwer
0          | asd        | zxc
1234567890 | mmm        |nnn
</code>```

The user inputs a leader_id, and the user can input up to 7 student_id. The problem is that if the user inputs 1 student_id, everything is normal, but when the user inputs more than 1 student_id, than it stores the data more than once.

Example:

If the user enters 1234 as the leader_id, and enters 123456 and 1234567890 as the student_id, than it should store the data in one row, not separate the data into 2 rows.

Another thing is that in the last 3 rows, the user inputs 3 student_id, and the data gets stored in 1 row, but it adds 2 extra rows with nothing for the student_id

My PHP

```<code><?php

    error_reporting(0);

    require '../../connect.php';

    $leader_id = $_POST['leader_id'];
    $student_id = array(
        $_POST['student_id_1'],
        $_POST['student_id_2'],
        $_POST['student_id_3'],
        $_POST['student_id_4'],
        $_POST['student_id_5'],
        $_POST['student_id_6']
    );

    $students_save = array();

    if(!empty($leader_id)) {

        foreach ($student_id as $id) {

            if(!empty($id)) {

                array_push($students_save, $id);

            }
        }

        foreach ($students_save as $save) {

            $check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");

            if(mysqli_num_rows($check_id)>0) {

                $students_save = implode(", ", $students_save);

                $result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
                    VALUES ('$leader_id', '$students_save');");

                    if($result) {

                        header("Location: ../../../admin.php?message=Success!");

                    } else {

                        header("Location: ../../../admin.php?message=Sorry we ran into an error");

                    }

            } else {

                header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");

            }

        }

    } else if(empty($leader_id)){

        header("Location: ../../../admin.php?Please add you're input values");

    }

 ?>
</code>```

答:
Try the below code if it helps,

```<code><?php
error_reporting(0);
require '../../connect.php';

$leader_id = $_POST['leader_id'];
$student_id = array();
if(isset($_POST['student_id_1'])) $student_id[] = $_POST['student_id_1'];
if(isset($_POST['student_id_2'])) $student_id[] = $_POST['student_id_2'];
if(isset($_POST['student_id_3'])) $student_id[] = $_POST['student_id_3'];
if(isset($_POST['student_id_4'])) $student_id[] = $_POST['student_id_4'];
if(isset($_POST['student_id_5'])) $student_id[] = $_POST['student_id_5'];
if(isset($_POST['student_id_6'])) $student_id[] = $_POST['student_id_6'];

if(!empty($leader_id)) {
  $students_save = implode(", ", $student_id);
  $check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id IN ($students_save)");
  if(mysqli_num_rows($check_id)>0) {
    //$student_ids = array();
    //while($row = $check_id->fetch_array(MYSQLI_ASSOC))  $student_ids[] = $row['student_id'];
    //$students_save = implode(", ", $student_ids);
    $result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id) VALUES ('$leader_id', '$students_save');");
    if($result) {
        header("Location: ../../../admin.php?message=Success!");
    } else {
        header("Location: ../../../admin.php?message=Sorry we ran into an error");
    }
  } else {
    header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");
  }
} else if(empty($leader_id)) {
  header("Location: ../../../admin.php?Please add you're input values");
}
?>
</code>```

This code should help you.

Note: I have added comment to a part of the code. If you remove the commenting, then it will only insert the student_id which exists in the students table.

Title: MySQL Querying Duplicates

Body:
So, I have a database called teams, and it currently looks like this:

team_id | leader_id | student_id
1       | 123456    | 1234
2       | 1234      | 123456, 1234567890
3       | 1234      | 123456
4       | 0         | 12345, 1234, 1234567890
5       | 0         |
6       | 0         |

My students database looks like this

student_id | first_name | last_name
123456     | qwer       | qwer
0          | asd        | zxc
1234567890 | mmm        |nnn

The user inputs a leader_id, and the user can input up to 7 student_id. The problem is that if the user inputs 1 student_id, everything is normal, but when the user inputs more than 1 student_id, than it stores the data more than once.

Example:

If the user enters 1234 as the leader_id, and enters 123456 and 1234567890 as the student_id, than it should store the data in one row, not separate the data into 2 rows.

Another thing is that in the last 3 rows, the user inputs 3 student_id, and the data gets stored in 1 row, but it adds 2 extra rows with nothing for the student_id

My PHP

<?php

    error_reporting(0);

    require '../../connect.php';

    $leader_id = $_POST['leader_id'];
    $student_id = array(
        $_POST['student_id_1'],
        $_POST['student_id_2'],
        $_POST['student_id_3'],
        $_POST['student_id_4'],
        $_POST['student_id_5'],
        $_POST['student_id_6']
    );

    $students_save = array();

    if(!empty($leader_id)) {

        foreach ($student_id as $id) {

            if(!empty($id)) {

                array_push($students_save, $id);

            }
        }

        foreach ($students_save as $save) {

            $check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id = $save");

            if(mysqli_num_rows($check_id)>0) {

                $students_save = implode(", ", $students_save);

                $result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id)
                    VALUES ('$leader_id', '$students_save');");

                    if($result) {

                        header("Location: ../../../admin.php?message=Success!");

                    } else {

                        header("Location: ../../../admin.php?message=Sorry we ran into an error");

                    }

            } else {

                header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");

            }

        }

    } else if(empty($leader_id)){

        header("Location: ../../../admin.php?Please add you're input values");

    }

 ?>

Body:
Try the below code if it helps,

<?php
error_reporting(0);
require '../../connect.php';

$leader_id = $_POST['leader_id'];
$student_id = array();
if(isset($_POST['student_id_1'])) $student_id[] = $_POST['student_id_1'];
if(isset($_POST['student_id_2'])) $student_id[] = $_POST['student_id_2'];
if(isset($_POST['student_id_3'])) $student_id[] = $_POST['student_id_3'];
if(isset($_POST['student_id_4'])) $student_id[] = $_POST['student_id_4'];
if(isset($_POST['student_id_5'])) $student_id[] = $_POST['student_id_5'];
if(isset($_POST['student_id_6'])) $student_id[] = $_POST['student_id_6'];

if(!empty($leader_id)) {
  $students_save = implode(", ", $student_id);
  $check_id = mysqli_query($link, "SELECT student_id FROM students WHERE student_id IN ($students_save)");
  if(mysqli_num_rows($check_id)>0) {
    //$student_ids = array();
    //while($row = $check_id->fetch_array(MYSQLI_ASSOC))  $student_ids[] = $row['student_id'];
    //$students_save = implode(", ", $student_ids);
    $result = mysqli_query($link, "INSERT INTO teams (leader_id, student_id) VALUES ('$leader_id', '$students_save');");
    if($result) {
        header("Location: ../../../admin.php?message=Success!");
    } else {
        header("Location: ../../../admin.php?message=Sorry we ran into an error");
    }
  } else {
    header("Location: ../../../admin.php?message=A Student ID Doesn't Exist");
  }
} else if(empty($leader_id)) {
  header("Location: ../../../admin.php?Please add you're input values");
}
?>

This code should help you.

Note: I have added comment to a part of the code. If you remove the commenting, then it will only insert the student_id which exists in the students table.


问:
UIAlertAction Background color
I have a problem with an UIAlertController, it doesn't display with a background color correctly... Can you help me?

This is the code:

```<code>let alert = UIAlertController(title: "Choose qty", message: "", preferredStyle: UIAlertControllerStyle.alert)
let pickerController = PickerQtyController()
alert.setValue(pickerController, forKey: "contentViewController")
// Testing color
alert.view.tintColor=UIColor.blue
let backView = alert.view.subviews.last?.subviews.last
backView?.layer.cornerRadius = 10.0
backView?.backgroundColor = UIColor.blue
// Btns
let saveBtn = UIAlertAction(title: "Save", style: UIAlertActionStyle.default) {
    UIAlertAction in
    print("UIAlertController: Saved")
    pickerController.saveNewValueOfPicker()
}
let cancelBtn = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
    UIAlertAction in
    print("UIAlertController: Canceled")
}
alert.addAction(saveBtn)
alert.addAction(cancelBtn)
self.present(alert, animated: true)
</code>```

Thank you!

答:
It is ugly and wrong design. You should create a custom view controller and add your pick controller into it. Change the background to transparent and set the modal presentation style to over current context to display the custom view controller.</p>

```<code>self.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
</code>```

Title: UIAlertAction Background color

Body:
I have a problem with an UIAlertController, it doesn't display with a background color correctly... Can you help me?

This is the code:

let alert = UIAlertController(title: "Choose qty", message: "", preferredStyle: UIAlertControllerStyle.alert)
let pickerController = PickerQtyController()
alert.setValue(pickerController, forKey: "contentViewController")
// Testing color
alert.view.tintColor=UIColor.blue
let backView = alert.view.subviews.last?.subviews.last
backView?.layer.cornerRadius = 10.0
backView?.backgroundColor = UIColor.blue
// Btns
let saveBtn = UIAlertAction(title: "Save", style: UIAlertActionStyle.default) {
    UIAlertAction in
    print("UIAlertController: Saved")
    pickerController.saveNewValueOfPicker()
}
let cancelBtn = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
    UIAlertAction in
    print("UIAlertController: Canceled")
}
alert.addAction(saveBtn)
alert.addAction(cancelBtn)
self.present(alert, animated: true)

Thank you!

Body:
It is ugly and wrong design. You should create a custom view controller and add your pick controller into it. Change the background to transparent and set the modal presentation style to over current context to display the custom view controller.

self.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext


问:
AngularDart - upload to shared hosting server
so I have my AngularDart app up and running on my machine (I used stagehand). Now is the time where I want to upload it to a shared hosting server. My question is: what is the correct procedure to do that? Because obviously Dart doesn't run natively and the compiled js files are required. (I already have access to the file manager of my server).

Thanks in advance

答:
Use the build command of the pub tool.

https://webdev.dartlang.org/tools/pub/pub-build

Use pub build when you’re ready to deploy your web app. When you run
  pub build, it generates the assets for the current package and all of
  its dependencies, putting them into new directory named build.


问:
CSS Only Tooltip Arrow - With Background, Border & Box-shadow?

Tooltip CSS

```<code>.has-tooltip .tooltip {
    position: absolute;
    left: 50%;
    top: -40px;
    opacity: 0;
    -webkit-transition: ease-out 300ms opacity;
       -moz-transition: ease-out 300ms opacity 0ms;
         -o-transition: ease-out 300ms opacity 0ms;
            transition: ease-out 300ms opacity 0ms;
    -webkit-transition-delay: 0ms;
    pointer-events: none;
    z-index: 9999;
}
.has-tooltip .tooltip span {
    position: relative;
    left: -50%;
    display: block;
    padding: 2px 8px;
    font-size: 14px;
    color: #fff;
    white-space: nowrap;
    background: rgba(45, 45, 45, 1);
    border: 1px solid rgba(204,204,204,0.60);
    -webkit-border-radius: 6px;
       -moz-border-radius: 6px;
            border-radius: 6px;
    -webkit-box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
       -moz-box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
            box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
}
</code>```

View Live Example

What I Am Trying To Achieve

By only having one element, have a tooltip styled as seen in the link above with a tooltip arrow which also has the same look applied to appear to be one element. I've seen multiple which place another element within for the arrow however I'm hoping to achieve this without needing to do so.

Questions

How can I have a tooltip arrow which gives the impression it is part of the tooltip with the same styles applied.

Note: If you provide code, could you please fully explain what you have done so I can implement a top tip as well as a bottom tip.

答:
You could use a pseudo element, i.e. ::before, and by rotate it 45 deg and positioning it about half its height from the bottom so it looks like an arrow.

a.has-tooltip {
  position: relative;
  transition: opacity 0.5s;
}
a.has-tooltip span {
  position: absolute;
  left: 20%; top: 50%;
  transform: translate(0,-150%);
  background: #333;
  color: white;
  border-radius: 10px;
  box-shadow: 2px 2px 6px rgba(0,0,0,0.5);
  padding: 10px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
  border: 4px solid #999;
}
a.has-tooltip span::before {
  content: '';
  position: absolute;
  left: 20%; top: calc(100% - 10px);
  height: 20px; width: 20px;
  transform: rotate(45deg);
  background: inherit;
  box-shadow: 2px 2px 4px rgba(0,0,0,0.3);
  z-index: -1;
  border: inherit;
  border-width: 0 4px 4px 0;
}

a.has-tooltip:hover span {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br><br><br>
<span>Hi! I'm a tooltip!</span>
  Hi! I'm a link!
</code>```

Updated based on a comment

When one make a shadow like this, and as it is actually a square, their 2 shadows intersect

a.has-tooltip {
  position: relative;
  transition: opacity 0.5s;
}
a.has-tooltip span {
  position: absolute;
  left: 20%; top: -10%;
  transform: translate(0,-150%);
  background: #333;
  color: white;
  border-radius: 5px;
 -webkit-box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
    -moz-box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
   box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
  padding: 10px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
  border: 1px solid #FFFFFF;
}
a.has-tooltip span::before {
  content: '';
  position: absolute;
  left: 10%; top: calc(100% - 10px);
  height: 20px; width: 20px;
  transform: rotate(45deg);
  background: inherit;
  -webkit-box-shadow: 4px 4px 0px 2px rgba(0,0,0,0.50);
    -moz-box-shadow: 4px 4px 0px 2px rgba(0,0,0,0.50);
       box-shadow: 4px 4px 0px 2px rgba(0,0,0,0.50);
  z-index: -1;
  border-right: 1px solid #FFFFFF;
  border-bottom: 1px solid #FFFFFF;
}

a.has-tooltip:hover span { opacity: 1; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br><br><br><br>
<span>Hi! I'm a tooltip!</span>
  Hi! I'm a link!
</code>```

To fix that is almost impossible, unless one use a SVG, though here is 2 possible solutions.

Give the shadow a non transparent color

a.has-tooltip {
  position: relative;
  transition: opacity 0.5s;
}
a.has-tooltip span {
  position: absolute;
  left: 20%; top: -10%;
  transform: translate(0,-150%);
  background: #333;
  color: white;
  border-radius: 5px;
 -webkit-box-shadow: 0px 0px 0px 6px rgba(128,128,128,1);
    -moz-box-shadow: 0px 0px 0px 6px rgba(128,128,128,1);
   box-shadow: 0px 0px 0px 6px rgba(128,128,128,1);
  padding: 10px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
  border: 1px solid #FFFFFF;
}
a.has-tooltip span::before {
  content: '';
  position: absolute;
  left: 10%; top: calc(100% - 10px);
  height: 20px; width: 20px;
  transform: rotate(45deg);
  background: inherit;
  -webkit-box-shadow: 4px 4px 0px 2px rgba(128,128,128,1);
    -moz-box-shadow: 4px 4px 0px 2px rgba(128,128,128,1);
       box-shadow: 4px 4px 0px 2px rgba(128,128,128,1);
  z-index: -1;
  border-right: 1px solid #FFFFFF;
  border-bottom: 1px solid #FFFFFF;
}

a.has-tooltip:hover span { opacity: 1; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br><br><br><br>
<span>Hi! I'm a tooltip!</span>
  Hi! I'm a link!
</code>```

Use the other pseudo, ::after, as the shadow, which will be transparent. With this one need to play a little with the size of the main shadow and the position of the ::after pseudo.

a.has-tooltip {
  position: relative;
  transition: opacity 0.5s;
}
a.has-tooltip span {
  position: absolute;
  left: 20%; top: -10%;
  transform: translate(0,-150%);
  background: #333;
  color: white;
  border-radius: 5px;
 -webkit-box-shadow: 0px 0px 0px 5px rgba(0,0,0,0.50);
    -moz-box-shadow: 0px 0px 0px 5px rgba(0,0,0,0.50);
   box-shadow: 0px 0px 0px 5px rgba(0,0,0,0.50);
  padding: 10px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
  border: 1px solid #FFFFFF;
}
a.has-tooltip span::before {
  content: '';
  position: absolute;
  left: 10%; top: calc(100% - 10px);
  height: 20px; width: 20px;
  transform: rotate(45deg);
  background: inherit;
  z-index: -1;
  border-right: 1px solid #FFFFFF;
  border-bottom: 1px solid #FFFFFF;
}
a.has-tooltip span::after {
  content: '';
  position: absolute;
  left: calc(10% - 5px); top: calc(100% + 6px);
  width: 0;
  height: 0;
  border-left: 16px solid transparent;
  border-right: 16px solid transparent;
  border-top: 16px solid rgba(0,0,0,0.50);
  z-index: -2;
}

a.has-tooltip:hover span { opacity: 1; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br><br><br><br>
<span>Hi! I'm a tooltip!</span>
  Hi! I'm a link!
</code>```

Body:
Tooltip CSS

.has-tooltip .tooltip {
    position: absolute;
    left: 50%;
    top: -40px;
    opacity: 0;
    -webkit-transition: ease-out 300ms opacity;
       -moz-transition: ease-out 300ms opacity 0ms;
         -o-transition: ease-out 300ms opacity 0ms;
            transition: ease-out 300ms opacity 0ms;
    -webkit-transition-delay: 0ms;
    pointer-events: none;
    z-index: 9999;
}
.has-tooltip .tooltip span {
    position: relative;
    left: -50%;
    display: block;
    padding: 2px 8px;
    font-size: 14px;
    color: #fff;
    white-space: nowrap;
    background: rgba(45, 45, 45, 1);
    border: 1px solid rgba(204,204,204,0.60);
    -webkit-border-radius: 6px;
       -moz-border-radius: 6px;
            border-radius: 6px;
    -webkit-box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
       -moz-box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
            box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
}

View Live Example

What I Am Trying To Achieve

By only having one element, have a tooltip styled as seen in the link above with a tooltip arrow which also has the same look applied to appear to be one element. I've seen multiple which place another element within for the arrow however I'm hoping to achieve this without needing to do so.

Questions

How can I have a tooltip arrow which gives the impression it is part of the tooltip with the same styles applied.

Note: If you provide code, could you please fully explain what you have done so I can implement a top tip as well as a bottom tip.

Body:
You could use a pseudo element, i.e. ::before, and by rotate it 45 deg and positioning it about half its height from the bottom so it looks like an arrow.

a.has-tooltip {
  position: relative;
  transition: opacity 0.5s;
}
a.has-tooltip span {
  position: absolute;
  left: 20%; top: 50%;
  transform: translate(0,-150%);
  background: #333;
  color: white;
  border-radius: 10px;
  box-shadow: 2px 2px 6px rgba(0,0,0,0.5);
  padding: 10px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
  border: 4px solid #999;
}
a.has-tooltip span::before {
  content: '';
  position: absolute;
  left: 20%; top: calc(100% - 10px);
  height: 20px; width: 20px;
  transform: rotate(45deg);
  background: inherit;
  box-shadow: 2px 2px 4px rgba(0,0,0,0.3);
  z-index: -1;
  border: inherit;
  border-width: 0 4px 4px 0;
}

a.has-tooltip:hover span {
  opacity: 1;
}

<br><br><br>
<a href="#" class="has-tooltip" id="link"><span>Hi! I'm a tooltip!</span>
  Hi! I'm a link!
</a>

Updated based on a comment

When one make a shadow like this, and as it is actually a square, their 2 shadows intersect

a.has-tooltip {
  position: relative;
  transition: opacity 0.5s;
}
a.has-tooltip span {
  position: absolute;
  left: 20%; top: -10%;
  transform: translate(0,-150%);
  background: #333;
  color: white;
  border-radius: 5px;
 -webkit-box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
    -moz-box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
   box-shadow: 0px 0px 0px 6px rgba(0,0,0,0.50);
  padding: 10px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
  border: 1px solid #FFFFFF;
}
a.has-tooltip span::before {
  content: '';
  position: absolute;
  left: 10%; top: calc(100% - 10px);
  height: 20px; width: 20px;
  transform: rotate(45deg);
  background: inherit;
  -webkit-box-shadow: 4px 4px 0px 2px rgba(0,0,0,0.50);
    -moz-box-shadow: 4px 4px 0px 2px rgba(0,0,0,0.50);
       box-shadow: 4px 4px 0px 2px rgba(0,0,0,0.50);
  z-index: -1;
  border-right: 1px solid #FFFFFF;
  border-bottom: 1px solid #FFFFFF;
}

a.has-tooltip:hover span { opacity: 1; }

<br><br><br><br>
<a href="#" class="has-tooltip" id="link"><span>Hi! I'm a tooltip!</span>
  Hi! I'm a link!
</a>

To fix that is almost impossible, unless one use a SVG, though here is 2 possible solutions.

Give the shadow a non transparent color

a.has-tooltip {
  position: relative;
  transition: opacity 0.5s;
}
a.has-tooltip span {
  position: absolute;
  left: 20%; top: -10%;
  transform: translate(0,-150%);
  background: #333;
  color: white;
  border-radius: 5px;
 -webkit-box-shadow: 0px 0px 0px 6px rgba(128,128,128,1);
    -moz-box-shadow: 0px 0px 0px 6px rgba(128,128,128,1);
   box-shadow: 0px 0px 0px 6px rgba(128,128,128,1);
  padding: 10px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
  border: 1px solid #FFFFFF;
}
a.has-tooltip span::before {
  content: '';
  position: absolute;
  left: 10%; top: calc(100% - 10px);
  height: 20px; width: 20px;
  transform: rotate(45deg);
  background: inherit;
  -webkit-box-shadow: 4px 4px 0px 2px rgba(128,128,128,1);
    -moz-box-shadow: 4px 4px 0px 2px rgba(128,128,128,1);
       box-shadow: 4px 4px 0px 2px rgba(128,128,128,1);
  z-index: -1;
  border-right: 1px solid #FFFFFF;
  border-bottom: 1px solid #FFFFFF;
}

a.has-tooltip:hover span { opacity: 1; }

<br><br><br><br>
<a href="#" class="has-tooltip" id="link"><span>Hi! I'm a tooltip!</span>
  Hi! I'm a link!
</a>

Use the other pseudo, ::after, as the shadow, which will be transparent. With this one need to play a little with the size of the main shadow and the position of the ::after pseudo.

a.has-tooltip {
  position: relative;
  transition: opacity 0.5s;
}
a.has-tooltip span {
  position: absolute;
  left: 20%; top: -10%;
  transform: translate(0,-150%);
  background: #333;
  color: white;
  border-radius: 5px;
 -webkit-box-shadow: 0px 0px 0px 5px rgba(0,0,0,0.50);
    -moz-box-shadow: 0px 0px 0px 5px rgba(0,0,0,0.50);
   box-shadow: 0px 0px 0px 5px rgba(0,0,0,0.50);
  padding: 10px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
  border: 1px solid #FFFFFF;
}
a.has-tooltip span::before {
  content: '';
  position: absolute;
  left: 10%; top: calc(100% - 10px);
  height: 20px; width: 20px;
  transform: rotate(45deg);
  background: inherit;
  z-index: -1;
  border-right: 1px solid #FFFFFF;
  border-bottom: 1px solid #FFFFFF;
}
a.has-tooltip span::after {
  content: '';
  position: absolute;
  left: calc(10% - 5px); top: calc(100% + 6px);
  width: 0;
  height: 0;
  border-left: 16px solid transparent;
  border-right: 16px solid transparent;
  border-top: 16px solid rgba(0,0,0,0.50);
  z-index: -2;
}

a.has-tooltip:hover span { opacity: 1; }

<br><br><br><br>
<a href="#" class="has-tooltip" id="link"><span>Hi! I'm a tooltip!</span>
  Hi! I'm a link!
</a>


问:
equivalent of rand('state',sum(100*clock)) in python
I am not very familiar with python. I have searched a lot and I want to exactly transfer below line to python:

% MATLAB code
rand('state',sum(100*clock))
```

I know that I should use  np.random.seed() and np.random.RandomState()

but I was not able how to choose and using them to have exactly that equivalent. Thanks

答:
You don't need such a thing in Python.  Unlike MATLAB which uses the same fixed random seed by default, Python automatically sets a new random seed each time, either by system-provided randomness or by the system clock depending on the platform.  You only need to manually set the seed if you want to use the same seed each time.  This is covered in the documentation:

random.seed(a=None, version=2)
  If a is omitted or None, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).

If you want to manually reset the seed to a new random value (which you only need to do if you previously set it to a fixed value), you can just do:

```<code>>>> import random
>>>
>>> random.seed()
</code>```

Or for numpy:

```<code>>>> import numpy as np
>>>
>>> np.random.seed()
</code>```

Body:
I am not very familiar with python. I have searched a lot and I want to exactly transfer below line to python:

% MATLAB code
rand('state',sum(100*clock))

I know that I should use  np.random.seed() and np.random.RandomState()

but I was not able how to choose and using them to have exactly that equivalent. Thanks

Body:
You don't need such a thing in Python.  Unlike MATLAB which uses the same fixed random seed by default, Python automatically sets a new random seed each time, either by system-provided randomness or by the system clock depending on the platform.  You only need to manually set the seed if you want to use the same seed each time.  This is covered in the documentation:

random.seed(a=None, version=2)
  If a is omitted or None, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).

If you want to manually reset the seed to a new random value (which you only need to do if you previously set it to a fixed value), you can just do:

>>> import random
>>>
>>> random.seed()

Or for numpy:

>>> import numpy as np
>>>
>>> np.random.seed()


问:
Insert filename into text file with sed
I've been learning about sed and finding it very useful, but cannot find an answer to this in any of the many guides and examples ... I'd like to insert the filename of a text file, minus its path and extension, into a specific line within the text itself. Possible?</p>

答:
wrt I've been learning about sed then you may have been wasting your time as there isn't a lot TO learn about sed beyond s/old/new. Sure there's a ton of other language constructs and things you could do with sed, but in practice you should avoid them all and simply use awk instead. If you edit your question to include concise, testable sample input and expected output and add an awk tag then we can show you how to do whatever you want to do the right way.

Meanwhile, it sounds like all you need is:

```<code>$ cat /usr/tmp/file
a
b
c
d
e

$ awk 'NR==3{print gensub(/.*\//,"",1,FILENAME)} 1' /usr/tmp/file
a
b
file
c
d
e
</code>```

The above inserts the current file name before line 3 of the open file. It uses GNU awk for gensub(), with other awks you'd just use sub() and a variable.

Title: Insert filename into text file with sed

Body:
wrt I've been learning about sed then you may have been wasting your time as there isn't a lot TO learn about sed beyond s/old/new. Sure there's a ton of other language constructs and things you could do with sed, but in practice you should avoid them all and simply use awk instead. If you edit your question to include concise, testable sample input and expected output and add an awk tag then we can show you how to do whatever you want to do the right way.

Meanwhile, it sounds like all you need is:

$ cat /usr/tmp/file
a
b
c
d
e

$ awk 'NR==3{print gensub(/.*\//,"",1,FILENAME)} 1' /usr/tmp/file
a
b
file
c
d
e

The above inserts the current file name before line 3 of the open file. It uses GNU awk for gensub(), with other awks you'd just use sub() and a variable.


问:
R: stratify by 2 factor variables in ggplot
```<code>library(ggplot2)
iris$Sepal.Length2 <- ifelse(iris$Sepal.Length < 5, 1, 0)
iris$Sepal.Width2 <- ifelse(iris$Sepal.Width < 3, 1, 0)

SmallLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 1],
                         status = "Small Length")
LargeLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 0],
                         status = "Large Length")
SmallWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 1],
                         status = "Small Width")
LargeWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 0],
                         status = "Large Width")

Length <- rbind(SmallLength, LargeLength)
Width <- rbind(SmallWidth, LargeWidth)
ggplot(Length, aes(Petal.Length, fill = status)) + geom_density(alpha = 0.2) + labs(x = "Petal Length")
</code>```

I have a continuous variable, Petal.Length, and I would like to stratify it by Sepal.Length, and Sepal.Width, both of which I have coded as binary variables. In the above plot, I stratified Petal.Length by Sepal.Length only. How can I further stratify it by Sepal.Width? The resulting plot should perhaps have 4 colors I think...1 for Petal.Length that have small length and small width, 1 for small length and large width, 1 for large length and small width, and 1 for large length and large width.

答:
One way to accomplish this is by placing the variable that you would like to stratify the graph upon inside the geom_density layer as such:

```<code>ggplot(data = df, aes(x = , y = ) +
  geom_line(aes(color = factored_variable))
</code>```

For more detail: Plotting two variables as lines using ggplot2 on the same graph

Body:
library(ggplot2)
iris$Sepal.Length2 <- ifelse(iris$Sepal.Length < 5, 1, 0)
iris$Sepal.Width2 <- ifelse(iris$Sepal.Width < 3, 1, 0)

SmallLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 1],
                         status = "Small Length")
LargeLength <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Length2 == 0],
                         status = "Large Length")
SmallWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 1],
                         status = "Small Width")
LargeWidth <- data.frame(Petal.Length = iris$Petal.Length[iris$Sepal.Width2 == 0],
                         status = "Large Width")

Length <- rbind(SmallLength, LargeLength)
Width <- rbind(SmallWidth, LargeWidth)
ggplot(Length, aes(Petal.Length, fill = status)) + geom_density(alpha = 0.2) + labs(x = "Petal Length")

I have a continuous variable, Petal.Length, and I would like to stratify it by Sepal.Length, and Sepal.Width, both of which I have coded as binary variables. In the above plot, I stratified Petal.Length by Sepal.Length only. How can I further stratify it by Sepal.Width? The resulting plot should perhaps have 4 colors I think...1 for Petal.Length that have small length and small width, 1 for small length and large width, 1 for large length and small width, and 1 for large length and large width.

Body:
One way to accomplish this is by placing the variable that you would like to stratify the graph upon inside the geom_density layer as such:

ggplot(data = df, aes(x = , y = ) +
  geom_line(aes(color = factored_variable))

For more detail: Plotting two variables as lines using ggplot2 on the same graph


问:
Amazon SimpleDB vs Amazon RDS
I work at a small ecommerce site and we're looking to move to all Amazon hosted services and I'm unsure the exact difference in RDS and SimpleDB.  RDS can use MySQL, can SimpleDB not?</p>

答:
RDS is basically a relational database in the SQL vein, whereas SDB is a non-relational database. I'd recommend reading through all the info on the Amazon Web Services (AWS) site, as they answer all the questions you might have.

From the AWS FAQs:

Q: When would I use Amazon RDS vs. Amazon EC2 Relational Database AMIs vs. Amazon SimpleDB?

  Amazon Web Services provides a number of database alternatives for developers. Amazon RDS enables you to run a fully featured relational database while offloading database administration; Amazon SimpleDB provides simple index and query capabilities with seamless scalability; and using one of our many relational database AMIs on Amazon EC2 and Amazon EBS allows you to operate your own relational database in the cloud. There are important differences between these alternatives that may make one more appropriate for your use case.

More information about AWS database options

Title: Amazon SimpleDB vs Amazon RDS