text:
Q: What is the origin of the visually complex space ship motif in cover art? I've noticed that a fair number of space-related sci-fi novels have cover art involving visually complex space ships that are unrelated to the plot.
Some examples I've noticed:

*

*Leviathan Wakes, Abaddon's Gate (and all of the Expanse series)

*Ender's Game, Speaker for the Dead (and the rest of the Ender series)

What is the origin of this motif? Are there prominent earlier examples?

A: I don't think there's a particularly simple answer to this. By the late 40s, the rocket ship -- usually based on the shape of the V2 -- was ubiquitous, to the point that by around 1960, some libraries would indicate that a book was SF by putting a rocket sticker on the spine. Winston used:  In effect, a rocket became the icon that said "SF". (Valigursky was especially known for his elegant rockets and did many covers in the 50s and 60s, but he was by no means alone. Nor did he limit himself to things that looked like V2s!)  Here's one from 1953 by Richard Powers:
Artists wanted to do more and art directors wanted more, and needed to have their book covers simultaneously say "this is SF" and "this is something new and different", and one solution was to have a more fanciful spaceship on the cover.  For some reason, this was especially common in the UK where artists like Rick Foss painted spaceships which couldn't possibly be intended to be real.
So my best answer is that you see the result of seventy-five years of artists and publishers collaborating to creatively use the rocket (or spaceship, these days) to signify SF and sell books.


text:
Q: Attempt to apply non- function, randomForest I have a data set(train2) with 79 variables(numeric and text combined) and the SalePrice as the last column. I am trying to create a randomForest model, this is what I get as an error:
Forest <- randomForest(SalePrice~., data = train2, na.action = TRUE)

Error in model.frame.default(formula = SalePrice ~ ., data = train2, na.action = TRUE) :
attempt to apply non-function

Do you have any idea how I can solve this error?

A: @joran is correct. I also want to steer you in the direction of exploring these two:
ntree Number of trees to grow. This should not be set to too small a number, to ensure
that every input row gets predicted at least a few times.
mtry Number of variables randomly sampled as candidates at each split. Note that
the default values are different for classification (sqrt(p) where p is number of
variables in x) and regression (p/3)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flow charts in PowerPoint I am creating some flow charts in PowerPoint.
As you know, when these charts get complicated, the lines run into each other and create confusion: are they meant to connect, or were they intended to go through?
I believe Visio has a solution to this where connecting lines automatically "jump" other connecting lines, depicted as a curve. Does PowerPoint have something similar to this?

A: In a word, no. At least not yet. I would suggest adding a dot or something where the lines are supposed to connect.

A: The easiest way I found was to use the "rainbow" shape, set it to zero width so it looks like a line, then connect lines to each end of it.
I had to use non-elbow connectors or else they misbehave and come in from the wrong directions (still haven't figured that one out!)
Sample below:

A: I have experimented with Route diagram pieces of Wikipedia which were invented to depict sub-way and train maps.
Sample diagram created in PowerPoint:

The building blocks for the diagram are route icons of 10x10 mm².
Using PowerPoint's "snap to grid" feature, these icons can be easily positioned to align properly. I keep the icons in a PowerPoint template file. To insert a given icon in my diagram, I simply copy it via mouse ctlr-left-click-drag&drop.

A: My solution is similar, but a bit more simple. I create two rectangles to mask a certain part of the overlapping lines. Once you have "calibrated" the correct size and distance between the rectangles, you can copy-paste and turn them around.
Sorry, not enough reputation to show an example.


text:
Q: How to use the original filename in a multi file template in resharper? I have a multi file template in resharper and I can use $NAME$ macro to get the name of the original file to use to name the other files in the template.  But I also want to use the $NAME$ of the original file in the content of the other file template.
Is this possible?  I can't see a macro which seems suitable for the internal variables as onlt the Current File Name seems available.
Anyone know if this is possible or how I might workaround this?

A: Unfortunately, there isn't a macro that will give you this. I've added a feature request that you can vote on and track (and more specific detail as to what your requirements are would be useful) - http://youtrack.jetbrains.com/issue/RSRP-415055
It is possible to write your own macros as part of a plugin, but there isn't a sure-fire way of getting the name of the first document in the created file set. The IHotspotSessionContext instance that is passed to the macro via IHotspotSession.Context property includes an enumerable of IDocument, from which you can get IDocument.Moniker, which will be the full path for file based documents. However, there's no guarantee of the order of the enumerable - it's backed by a hashset. You might be able to rely on implementation details (small set, no removes) to be able to use the first document as the original, but there is really no guarantee of this.

A: As a workaround, you may create a parameter $FILENAME$ (macro "Current file name without extension") in the first file e.g. in the comments, like:
class Foo
{
     //$FILENAME$
}

Then you may call this parameter in other files of the multifile template - this parameter will contain the name of the first file since the first file will be generated before other ones.


text:
Q: Excel 2019: Copy data from sheet2 columns B, C, D to sheet1 columns B, C, D based on value of sheet1 column A I have the following conditions:

*

*I have a Workbook with 2 WorkSheets named Data and Users

*In Data, I have column A populated with numbers ranging from 1 to 9999999

*In Users, I have column A populated with numbers ranging form 1 to 9999999

*In Users, I have multiple rows of each of the numbers (example 10 rows of 1, 18 rows of 2, 32 rows of 3, etc.)

*In Data, cells B, C and D are empty

*In Users, cells B, C and D contain email, first name, last name

What I am trying to do is to copy Users : B, C and D values to Data : B, C and D empty cells.
I'm trying to use the INDEX and MATCH functions, but cannot get it to run - continually getting errors.
Here is an example of what I've tried in a test cell in my Users sheet:
=INDEX(Users!A:A,MATCH(1,(A2=Data!:A:A),0))

So, to clarify.
I have:
Users sheet:
A     B          C     D

1     me@me.com  First Last

Data sheet:
A     B          C     D
1
1
1
1

My objective is to populate every row in Data with the values of Users B, C and D whenever the value in column A matches.
The end result would look like:
Data sheet:
A     B          C     D
1     me@me.com  First Last
1     me@me.com  First Last
1     me@me.com  First Last
1     me@me.com  First Last

Thanks in advance.


text:
Q: Read from file after end-of-file is reached I have a function named readNextString(ifstream &file , char* &pBuffer) which extracts the next string from a file, until ',' or '\n' is reached, removes whitespace at the beginning and at the end of the string, saves the rest in pBuffer and returns true if everything worked fine - false otherwise. Everything works until the end-of-file is reached. When the eof flag is set I can't move my get pointer.
I've tried this:
if(file.eof())
{
   file.clear();
   file.seekg(0 , ios::end)
}

...and then remove whitespaces at the end of the string. This almost helped. The function extracts the string without the spaces but I get an infinite loop.
My actual question is: How can I check if the next char is EOF, and if I can't - is there any alternative way to do this?
Here is my actual function:
bool readNextString(ifstream &file , char* &pBuffer)
{
    if(file.eof()){
        return false;
    }
    for(; file.good() && isWhitespace(file.peek()) && !file.eof() ; file.seekg(1 , ios::cur))
        ;
    if(file.eof()){
        cout << "The file is empty.\n";
        return false;
    }else{
        streamoff startPos = file.tellg();
        cout << "startPos : " << startPos << endl;
        for(;file.good() && file.peek()!='\n' && file.peek()!=',' && file.peek()!= EOF; file.seekg(1 , ios::cur))
            ;
        streamoff A = file.tellg();
        cout << "A : " << A << endl;
        file.seekg(-1 , ios::cur);
        for(;file.good() && isWhitespace(file.peek()) ; file.seekg(-1 , ios::cur))
            ;
        file.seekg(2 , ios::cur);
        streamoff endPos = file.tellg();
        cout << "endPos : " << endPos << endl;
        pBuffer = new char[endPos-startPos];
        if(pBuffer)
        {
            file.seekg(startPos , ios::beg);
            file.get(pBuffer , endPos-startPos , ',' || '\n');
            for(;file.good() && file.peek()!='\n' && file.peek()!=',' && file.peek()!= EOF; file.seekg(1 , ios::cur))
                ;
            file.seekg(2 , ios::cur);
            streamoff temp = file.tellg();
            cout << "temp : " << temp << endl;
            return true;
        }else{
            cout << "Error! Not enough memory to complete the task.\nPlease close some applications and try again.\n";
            return false;
        }
    }
}

And that's one place where I call it:
void printCities()
{
    ifstream city ;
    city.open("cities.txt", fstream::in);
    if(city.is_open())
    {
        char *currCity;
        int counter = 1;
        while(readNextString(city , currCity))
        {
            cout << counter++ << ". " << currCity << endl;
            delete[] currCity;
            currCity = NULL;
        }
        if(city.eof())
            cout << "There are no cities added.\n";
        city.close();
    }else
        cout << "Error by opening 'cities.txt'.Make sure that the file exist and try again.\n";
}

Hope I was clear enough. If you find some other mistakes or possible errors I'll be glad to hear it and learn from it.

A:
How can I check if the next char is EOF?

Like this
if (file.peek() == EOF)
{
    // next char is EOF
    ...
}

A: First, don't use seek to skip whitespace.  Just get the
character and be done with it.
Second, you seem to misunderstand the meaning of
istream::good() and istream::eof().  There is never
anytime where istream::good() is appropriate, and
istream::eof() is usually only appropriate after input has
failed.  As for your loop skipping white space, the usual
solution would be:
while ( isspace( file.peek() ) && file.peek() != EOF ) {
    file.get();     //  ignore read character...
}

Similar comments hold for the other loops as well, except that
you won't want to ignore the read characters.  To collect
characters up to the next ',', for example:
std::string field;
while ( file.peek() != ',' && file.peek() != EOF ) {
    field.push_back( file.get() );
}

(And your file.get( pBuffer, endPos - startPos, ',' || '\n' )
certainly doesn't do what you expect it to; the expression ','
|| '\n' will always evaluate to true, which, when converted
to a char, is '\01.)
Finally, while the above strategy will work, it's far preferable
to input larger units of text into an std::stream, and parse
that.  If the text is line oriented, use something like:
std::string line;
while ( std::getline( file, line ) ) {
    //  Parse line, using std::istringstream if appropriate,
    //  although this doesn't seem to be the case for your code.
}

This is orders of magnitude simpler than what you are doing.

A: Ok.I did it otherwise! getline() for the WIN !  :D
So this is my code (this time is much more readable) :
bool readNextString(ifstream &file , char pBuffer[] )
{
    while(isWhitespace(file.peek()) && !file.eof())
        file.ignore(1);
    if(!file.eof())
    {
        streamoff start = file.tellg();
        stringstream toComma;
        if(file.getline(pBuffer , 200 , ','))
        {
            toComma << pBuffer;
            toComma.getline(pBuffer ,200, '\n');
            int i=strlen(pBuffer)-1;
            for(; isWhitespace(pBuffer[i]) ;i--)
                ;
            pBuffer[i+1] = '\0';
            file.clear();
            file.seekg(start + strlen(pBuffer) , file.beg);
            return true;
        }else return false;
    }
    return false;
}

I've made some changes in my other function too:
void printCities()
{
    ifstream city ;
    city.open("cities.txt", fstream::in);
    if(city.is_open())
    {
        if(!isEmpty(city))
        {
            char currCity[200];
            int counter = 1;
            while(readNextString(city , currCity) && counter < 10)
                cout << counter++ << ". " << currCity << endl;
        }else
            cout << "There are no cities added.\n";
        city.close();
    }else
        cout << "Error by opening 'cities.txt'.Make sure that the file exist and try again.\n";
}

The function isEmpty(ifstream &file) returns true if the file is empty and false otherwise.
Thanks to all for help !
Best regards !


text:
Q: How to run same cucumber scenario for multiple regions using tags associated with the scenario Description of problem:
I am trying to run same cucumber scenario for multiple regions using cucumber and java.
What I am trying to achieve?

*

*There are three different regions au, nl and gb associated with my scenario (specified as tags)

*I want to use all 3 tags to run my scenario one after another

What I have tried ?
I am not sure how to achieve same using cucumber. please find below code for reference
@au-en @nl-nl @gb-en
Scenario: A new user can place order using ecom sites
Given the Guest user buying product
Then the user perform checkout

//step definition cucumber
@Before
public void setUp(Scenario scenario) {
    listTags= (List) scenario.getSourceTagNames();
    listTags
            .stream()
            .forEach(System.out::println);
}

 @Given("^the Guest user buying product$") {
 public void buyProduct() {

        for(Object item : listTags) {
        System.out.println("******item*********" + item);

        homepage.navigateToPage(baseUrl.concat(url)); //call url
        productSelection.selectProduct();
        productSelection.AddTobasket()
        basketPageSteps.clickCheckoutButton();
        }

}

@Then("^the user perform checkout$")
public void theUserIsOnTheCheckoutCompletePage() {
       cheeckoutPage.ClickCheckout();
}

A: Defining multiple tags next to each other separated by space means that, it's going to execute the scenario whenever either or all them are mentioned in CucumberOptions like below:
@RunWith(Cucumber.class)
@Cucumber.Options(format = {"pretty", "html:target/cucumber"}, tags = {"@au-en,@nl-nl,@gb-en"})

public class runTest { }`

Coming back to your requirement, if you want to run the scenario for each of the tags separately, you can follow either of the below method:

*

*If the scenario's implementation is supposed to be same for each region, then you can use Scenario Example, where for the same scenario you would be parameterising the region details under 'Example' section. Something like this:
Scenario Outline: eating
Given there are <start> cucumbers
When I eat <eat> cucumbers
Then I should have <left> cucumbers
Examples:
| start | eat | left |
|    12 |   5 |    7 |
|    20 |   5 |   15 |

*If the scenario's implementation is going to be different for each region, then you can define scenarios for each region and have a specific tag attached above the respective region implementation. Now, you can mention these tags in CucumberOptions like before in the order you want to call and execute.
Here are some references for Item 1: [https://cucumber.io/docs/cucumber/api/#tags] and Item 2: [https://www.tutorialspoint.com/cucumber/cucumber_tags.htm]

A: You have the following options here:

*

*Do a Cucumber run for each region

*Write separate scenarios for each region (this one uses tags)

*Write a single scenario that tests all 3 regions at the same time
You need to choose the one that best meets your needs.
1 Do a Cucumber run for each region
Here you set up external state before the cucumber run so that cucumber can pick the region to use for this particular run.
This would be really useful if you have loads of scenarios you want to run against various regions, and if the application behaves in the same way for each region
2 Write separate scenarios for each region
Here you could use tags so you can do things like only run gb-en scenarios in a particular run. You would have something like
@gb-en
Scenario: Can buy in GB
  ...

@nl@nl
Scenario: Can buy in the Netherlands
  ...

This is a really good way of testing regional behaviour
3. Write a single scenario that tests all 3 regions at the same time
This is the one you seem to want, however I don't think you'll want to do what is required.
Here you have to write a scenario like
Scenario: Regional buying
  Given the following regions en-gb ...
  When I buy something from each region
  Then I should see I have bought something from each region

This one is pretty ugly. Here you have to have a step that buys something for each region, which is going to be pretty complex. The step will have to

*

*change the region

*buy the product

*save the result

and then repeat that for each region.


text:
Q: Audio stops after a while or music change in Arch Linux I'm facing an issue which i fix every time by unplugging and plugging the jack in audio output in my motherboard,
i tried removing all sound drivers such as alsa and pulseaudio, then reinstall them, but nothing changed, audio stops each time i change the music.

OS : Arch Linux x64
Motherboard : MSI MS-7817

A: I had the same issue on my MSI laptop. Upgrading to the latest kernel from LTS solved it.


text:
Q: Back button strangely disappearing in UINavigationController but keeps working Under iOS7 I've been experiencing an issue where the back button item will not show up if it has been set with a specific background image:
int imageSize = 21; //REPLACE WITH YOUR IMAGE WIDTH

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-400.f, 0)
                                                   forBarMetrics:UIBarMetricsDefault];
UIImage *barBackBtnImg = [[UIImage imageNamed:@"BackArrowDark.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, imageSize, 0, 0)];

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:barBackBtnImg
                                                forState:UIControlStateNormal
                                              barMetrics:UIBarMetricsDefault];

Upon doing this, any ViewController that I push in the navigation controller will have no back button item appearing, even though pressing where it should be, will make it appear, and any subsequent pushes of this view controller will have the button present on the screen.
This issue is only appearing under iOS7: everything works perfectly under iOS6.
Changing the back button completely with a leftBarButtonItem disables the back swipe, so that is not an option.
Any idea what I am doing wrong?
Thanks much for your consideration.

A: Make sure you are not calling this in the view controller:
self.navigationController.navigationBar.tintColor = [UIColor redColor];

In iOS 7, this will tint the navigation bar but will also make your buttons invisible, yet functional just as you are describing.

A: After trying different solutions, I found that changing the backIndicatorImage works best under iOS7, and it seems to be in line with the iOS7 interface paradigm:
[[UINavigationBar appearance] setTintColor:[UIColor grayColor]];
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault]; // Takes out title

UIImage *backButtonImage = [UIImage imageNamed:@"BackArrowDark.png"];

if ([UINavigationBar instancesRespondToSelector:@selector(setBackIndicatorImage:)]) {
  [[UINavigationBar appearance] setBackIndicatorImage:backButtonImage];
  [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:backButtonImage];
} else {
  int imageSize = 21; // REPLACE WITH YOUR IMAGE WIDTH

  [[UIBarButtonItem appearance] setBackButtonBackgroundImage:[backButtonImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, imageSize, 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
}

With this method:

*

*When going back in the navigation controller, the back button item transition is the same as with the default indicator (a departure from the back button sliding away as well under iOS6);

*Under iOS6, the backButton is changed and keeps its default iOS6 behaviour.

*I'm happy!


text:
Q: Date to DateTime conversion in DataWeave 2 Input date is coming in this format "2022-04-30" and I want to convert it to date time and time should be zeros like 2022-05-15T00:00:00Z.
How it can be achieved using DataWeave 2.0?

A: Convert the input string to a Date, then add the time to create a DateTime output. Then just convert to String. The default pattern seem to be adequate that you need.
%dw 2.0
output application/json
var sourceDate="2022-04-30"
---
(sourceDate as Date {format: "yyyy-MM-dd"} ++ |00:00:00Z|) as String

Output:
"2022-04-30T00:00:00Z"

A: If you want the result as String you can just Append "T00:00:00Z" to your date string
%dw 2.0
output application/json
var sourceDate="2022-04-30"
---
sourceDate ++ "T00:00:00Z"

And if you want a DateTime Object you can just coerce it to DateTime using as keyword. It will work as your date string is already in the required format.
%dw 2.0
output application/json
var sourceDate="2022-04-30"
---
(sourceDate ++ "T00:00:00Z") as DateTime


text:
Q: Programmatically fetch all data from multiple cloud apps like salesforce, sap and oracle using soap based web services I need to programmatically fetch almost all data from multiple applications like salesforce, sap and oracle. Most of these applications provide soap based APIs via web services. I wrote a bit of client code using Apache Axis (wsdl2java) to fetch records from one entity (table) such as contacts. There are tens or hundreds of entities in most applications. I figure I would've to write lot of code to get all the data. Is there a better way to go about this?

A: I realize you said you need to programmatically access the data, but have a look at salesforce's data export feature.
For programatic export using the SOAP API, if you're wanting to stay loosely typed and not hard code the entity list you support, you'll probably want to use the Partner API. You'll do a describeGlobal() to get the list of supported entities, aka Objects. Then you can do a describeSObjects() to get the list of fields for an Object. At that point you can query from that Object and retrieve the records.
You might also want to look at the Bulk API, which is designed for dealing with large data sets. The payload is CSV, which may be easier for you to deal with.

A: If you want to extract data on a regular basis, you can use Talend Open Studio (Opensource) to extract all data; we are doing that using Talend in several SF projects. It generates java code that you can deploy on any server running java and use cron as a scheduler.
We have also written a java based app that uses metadata to dynamically fetch all SF custom objects in order to automatically extract the daily changes from each object for daily (incremental) backup.
Klaus

A: Ok. This is an attempt to answer my own question. I just got an idea:
I am thinking I might be able to achieve this by figuring out mapping between all the objects and their corresponding wrapper classes that Axis or jax-ws generates and then creating the meta-data (object_type, class_name, method_name, data_types, etc.,) and then having a meta-data driven code to fetch all the records. Do you think that would be a good approach?
Really appreciate if I could get more ideas and comments from the community. Thanks very much.


text:
Q: JMenuBar dropping down to a "custom" JPanel and "erased" The JMenuItems of JMenuBar drops down to a JPanel added to the JFrame, but the JPanel erases the JMenuItems.
Do I supposed to pause the re-drawing of the JPanel?
I'm using getGraphics() on the JPanel for drawing an image, this method is called from a thread with (for example) 200 ms delay.
edit:
It's a (very simple) game inside the JPanel.
(I've added a field paused to the JPanel and i've edited the paint method so it repaints the JPanel only if paused is false, however I don't know if this "solution" is good. (It's set to true when the user clicks on the menu and set to false when selects or cancels it.)

A: You should always be repainting the JPanel from the Event Dispatch Thread, not an arbitrary thread.  If you want to do this in order to animate the panel (e.g. with the 200ms delay you mention) then consider using javax.swing.Timer, which periodically fires an ActionEvent on the Event Dispatch Thread.
Example
  public class MyPanel extends JPanel {
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      // Add additional graphics operations here.
    }
  }

  final JPanel panel = new MyPanel();
  int delay = 200; // Milliseconds

  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          panel.repaint();
      }
  };

  new Timer(delay, taskPerformer).start();

A:
I'm using getGraphics() on the JPanel
  for drawing an image

Never use the getGraphics() method like that. You have no control over when the component should be repainted. Custom painting should be done by overriding the paintComponent() method of the panel. When you use the Timer you just use panel.repaint() and the Swing repaint manager should look after the details of what needs to be painted.

A: Have a look at javax.swing.Timer documentation
https://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/Timer.html
It has code right at the top to fire an event on fixed interval.


text:
Q: Selenium sendkeys for vb.net app with gridcell I have following html page generated dyamically in vb.net app
    <td class="GridCellRightAlign" role = "gridcell" aria-describedBy = "grdFromActInfo_colheader_2"> 0.00 </td>   I am using C# with Selenium WebDriver to sendkeys in this field using xpath. But it does not work. The C# Selenium code is as follows By.XPath("//*[@id'grdFromActInfo']/table/tbody/tr[1]/td[1]/table/tbody[2]/tr/td/div[2]/table/tbody/tr/th).SendKeys("25"). I generated this xpath in Chrome Dev Tools using Inspect option

A: var element = driver.FindElement(By.XPath("//*[@id'grdFromActInfo']/table/tbody/tr[1]/td[1]/table/tbody[2]/tr/td/div[2]/table/tbody/tr/th");
element.SendKeys("25");


text:
Q: CSS li отступ от вложенности Как заменить данный CSS циклом, добавляющим +20px padding к каждому следующему элементу в дереве li? необходим именно padding!

$(document).ready(function(){
    $("#admindivisionmenu li").each(function() {
     if($(this).has("ul").length) {
      $(this).prepend('

');
  } else {
   $(this).find("a").first().addClass("admindivisionmenu-without-clild");
  }
    });
    $(".admindivisionmenu-child").click(function() {

     if($(this).hasClass('admindivisionmenu-child-close')) {
      $(this).parent().find('ul').first().slideDown();
   $(this).removeClass('admindivisionmenu-child-close').addClass('admindivisionmenu-child-open');
     } else {
      $(this).parent().find('ul').slideUp();
   $(this).parent().find('div').removeClass('admindivisionmenu-child-open').addClass('admindivisionmenu-child-close');
     }

    });

});
.admin-division-menu > ul > li a.admindivisionmenu-without-clild {padding-left: 20px;}

.admin-division-menu > ul > li > ul > li a.admindivisionmenu-without-clild {padding-left: 30px;}
.admin-division-menu > ul > li > ul > li .admindivisionmenu-child {margin-left: 30px;}

.admin-division-menu > ul > li > ul > li > ul > li a.admindivisionmenu-without-clild {padding-left: 50px;}
.admin-division-menu > ul > li > ul > li > ul > li .admindivisionmenu-child {margin-left: 50px;}

.admin-division-menu > ul > li > ul > li > ul > li > ul > li a.admindivisionmenu-without-clild {padding-left: 70px;}
.admin-division-menu > ul > li > ul > li > ul > li > ul > li .admindivisionmenu-child {margin-left: 70px;}

.admin-division-menu > ul > li > ul > li > ul > li > ul > li > ul > li a.admindivisionmenu-without-clild {padding-left: 90px;}
.admin-division-menu > ul > li > ul > li > ul > li > ul > li > ul > li .admindivisionmenu-child {margin-left: 90px;}

Раздел 1

Раздел 2

Раздел 3

Раздел 4

Раздел 8

Раздел 9

Раздел 5

Раздел 6

Раздел 7

A: Так годится?

div {
  position: relative;
  float: left;
}

li:before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  border-top: 1px solid;
}

Раздел 1

Раздел 2

Раздел 3

Раздел 4

Раздел 8

Раздел 9

Раздел 5

Раздел 6

Раздел 7


text:
Q: How to set the ResourceId in AWS::ApiGateway::Method if was implicitly created by AWS SAM? I have an API that is defined as IaC with AWS SAM usign AWS::Serverless::Api for the API Gateway and API Event Source for the Methods.
I developed a method that requires a non lambda proxy integration and some mapping templates in the integration response, so to implement these functionalities in IaC I had to use AWS::ApiGateway::Method from Cloud Formation Templates.
The problem is with the ResourceId property, because is a third level resource in the API, Cloud Formation expects a reference to a AWS::ApiGateway::Resource but the upper levels were implicitly created by AWS SAM with the following code:
PrismShiftDayMacroserviceLambda:
Type: AWS::Serverless::Function
Properties:
  FunctionName: !Ref ServiceName
  CodeUri: !Ref ServicePath
  Role: !Sub 'arn:aws:iam::${AWS::AccountId}:role/lambda_execution_role'
  Events:
    GetShiftDay:
      Type: Api
      Properties:
        Method: GET
        Path: /api/shiftDays/{id}
        RequestParameters:
          - method.request.path.id
        RestApiId: !Ref PrismShiftDayMacroserviceApi
    PostShiftDay:
      Type: Api
      Properties:
        RestApiId: !Ref PrismShiftDayMacroserviceApi
        Path: /api/shiftDays
        Method: POST
    SearchShiftDay:
      Type: Api
      Properties:
        RestApiId: !Ref PrismShiftDayMacroserviceApi
        Path: /api/shiftDays
        Method: GET
    PatchShiftDay:
      Type: Api
      Properties:
        RestApiId: !Ref PrismShiftDayMacroserviceApi
        Path: /api/shiftDays/{id}
        Method: PATCH

Is it possible to get a reference to the resource that was implicitly created by AWS SAM?


text:
Q: Deserializing an XML into a object: XML element with xsi:nil="true" should have null value (and not empty value) for respective property in object When de-serializing the below XML into Parent class, ElementTwo and ElementThree are empty strings, which is expected. But ElementOne should have been null but instead this is also empty string.
What does i:nil="true" mean?
XML
<?xml version = \"1.0\" ?>
<Parent
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ElementOne xsi:nil="true"/>
<ElementTwo></ElementTwo>
<ElementThree />
<ElementFour>Value</ElementFour>
</Parent>

C# Class
public class Parent
{
    public string ElementOne { get; set; }
    public string ElementTwo { get; set; }
    public string ElementThree { get; set; }
    public string ElementFour { get; set; }
}

When de-serializing the XML into an object, the XML element with xsi:nil="true" is not being converted as null. Instead, it is assigned as empty string. But I've a requirement where it should be converted as null only. Please help me to figure out a solution or point put where I went wrong
I've given the sample used in below fiddle link:
https://dotnetfiddle.net/VfNJYv

A: Put
[XmlElement(IsNullable=true)]

above the
Public string ElementOne get/set property
.NET fiddle


text:
Q: The Klein bottle can be immersed in $\mathbb{R}^3$ and embedded in $\mathbb{R}^4$ How can one show that the Klein bottle can be immersed in $\mathbb{R}^3$ and embedded in $\mathbb{R}^4$?
We define the Klein bottle as the quotient space of $I^2=[0,1]\times [0,1]$ under the relation $\sim$ for which $(0,y)\sim (1,1-y)$ and $(x,0)\sim (x,1)$.
If we found a continuous $f:I^2\to R^k$ which is constant over the fibers of $\pi:I^2\to I^2/{\sim}$ then we'd have a continuous $g:I^2/{\sim}\to\mathbb{R}^k$ such that $g\pi=f$.
What do I need for $g$ to be an immersion? And to be an embedding?
How can I show that there is an immersion for $k=3$ and an embedding for $k=4$ (without finding it explicitly)?


text:
Q: Get Indian postal codes from address string with other numbers I am working on an Address parsing project where, I need to detect various components of the address, such as city, state, postal_code, street_no etc.
I wrote a regular expression to filter out the postal codes handling all user inputs.
sample_add = "16th main road btm layout 560029 5-6-00-76 56 00 78 560-029 25 -000-1"
regexp = re.compile(r"([\d])[ -]*?([\d])[ -]*?([\d])[ -]*?([\d])[ -]*?([\d])[ -]*?([\d])")
print(re.findall(regexp, sample_add))

Output :- [560029, 560076, 560078, 560029, 250001]

This is able to identify postal_codes for such addresses, However, when an address like the following comes, it combines the Street nos and interprets it as the postal code,
Ex. `sample_add_2 = "House no 323/46 16th main road, btm layout, bengaluru 560029"

In this case, the postal code is identified as 323461, while the correct one should have been 560029.

A: If I undestood it right we search for a 6 digit number but wich can include some delimiters like - , but not \.This should handle it. (If not, please explaind you´re desired outcome):
\b(\d[\- ]*){6}\b(?<! )

https://regex101.com/r/wxYgwr/3


text:
Q: Cypress: Getting "Parameter supplied to cy.request() contained a circular reference at the path specWindow" when using command inside a command I have 2 different commands that I intend to use inside each other. The 1st one generates an object and the second one uses it to send as body of a cy.request.
They look like this
Cypress.Commands.add("objectGeneration", function(search, method, block){
  let body = {}
  if(search === 'something') {
    body.search = search,
    body.method = method,
    body.block = block
  }
  return body
})

Cypress.Commands.add("sendReq", (search, method, block) {
  cy.request({
    method: 'POST',
    URL: 'URL',
    body: cy.objectGeneration(search, method, block)

  })

})

In my test I call them this way (where each testCase variable comes from a helper object I import into my test case.
it("Name of the test", function(){
  cy.sendReq(testCase.search, testCase.method, testCase.block).then((resp => {..}...
})

When trying to run this, I get the following Cypress error:

The body parameter supplied to cy.request() contained a circular
reference at the path specwindow body can only be a string or an
object with no circular references.

All of this would work fine when objectGeneration was just a function and not a command. I think my issue might have to do with the return in a command. Any suggestions?
Thanks

A: Ran into a similar issue trying to send a Decimal value (using decimal.js) as part of the body.
In the end I serialized the object myself and sent it this in the request. In your case I would think that this should also work:
Cypress.Commands.add("sendReq", (search, method, block) {
  const serialized = JSON.stringify(cy.objectGeneration(search, method, block))

  cy.request({
    method: 'POST',
    URL: 'URL',
    body: serialized,
    headers: { 'Content-Type': 'application/json' }
  })
})


text:
Q: Implementing monadic bind for Nullable<> *and* reference types I have this function:
public static U? IfNotNull<T, U>(this T? self, Func<T, U?> func)
    where T : struct
    where U : struct
{
    return (self.HasValue) ? func(self.Value) : null;
}

Example:
int? maybe = 42;
maybe.IfNotNull(n=>2*n); // 84

maybe = null;
maybe.IfNotNull(n=>2*n); // null

I want it to work on implicitly-nullable reference types as well as explicit Nullable<> types. This implementation would work:
public static U IfNotNull<T, U>(this T? self, Func<T, U> func)
    where T : struct
    where U : class
{
    return (self.HasValue) ? func(self.Value) : null;
}

But of course overload resolution does not look at type constraints, so you can't have both at once. Is there a solution to this?

A:
But of course overload resolution does not look at type constraints

Well it does... but not the type constraints of the method itself. It looks at type constraints on the parameter types.
In C# 4 (which has optional parameters) you can do this... but I'd really suggest you don't:
public class MustBeStruct<T> where T : struct {}
public class MustBeClass<T> where T : class {}

public static U? IfNotNull<T, U>(this T? self, Func<T, U?> func,
                       MustBeStruct<U> ignored = default(MustBeStruct<U>))
    where T : struct
    where U : struct
{
    return (self.HasValue) ? func(self.Value) : null;
}

public static U IfNotNull<T, U>(this T? self, Func<T, U> func,
                                MustBeClass<U> ignored = null)
    where T : struct
    where U : class
{
    return (self.HasValue) ? func(self.Value) : null;
}

See this blog post for more details of this horrible, horrible hack.
Personally I'd probably just name the two methods differently so that overload resolution didn't need to work so hard - and neither did the readers of your code.

A: So I ended up with this:
public static U IfNotNull<T, U>(this T self, Func<T, U> func)
    where U : class
{
    return (self != null)
        ? func(self)
        : (U)null;
}

public static U? IfNotNull<T, U>(this T self, Func<T, U?> func)
    where U : struct
{
    return (self != null)
        ? (U?)func(self)
        : null;
}

The overload resolver seems to be happy with this. It's a tiny bit of extra work for Nullable<> types:
object o = null;
o.IfNotNull(x => x.ToString());
o.IfNotNull(x => x.GetHashCode() as int?);

int? i = null;
i.IfNotNull(x => Math.Abs(x.Value).ToString());
i.IfNotNull(x => Math.Abs(x.Value) as int?);


text:
Q: C++ compiler, force pass by reference Is it possible to set as default a C++ compiler to interpret all parameter passing as being by-reference defining a new modifier to specify that you need a passage by copy.
Programming I found that only rerely I need to pass data by copy so, at least for me, would be much more effective to have "reference by default"

A: Not only there isn't such a feature, there can never be one. Doing so would make well-defined programs ill-formed or worst, having Undefined Behaviour.
Consider this simple well-formed program:
struct X {};

auto bar(X x) -> decltype(x)
{
    return x;
}

auto test()
{
    bar(X{});
}

How would you transform it? There is no way to make bar take reference and not change the semantics of the program or make it UB
If you make bar take l-value reference then it can't accept a temporary:
struct X {};

auto bar(X& x) -> decltype(x)
{
    return x;
}

auto test()
{
    bar(X{});
}

<source>:12:5: error: no matching function for call to 'bar'

    bar(X{});

    ^~~

<source>:4:6: note: candidate function not viable: expects an l-value for 1st argument

auto bar(X& x) -> decltype(x)

     ^

1 error generated.

If you make it take an r-value reference then you cannot return it without further modifications:
struct X {};

auto bar(X&& x) -> decltype(x)
{
    return x;
}

auto test()
{
    bar(X{});
}

<source>:6:12: error: rvalue reference to type 'X' cannot bind to lvalue of type 'X'

    return x;

           ^

1 error generated.

Ok, you can solve this particular problem by moving the parameter. But that is well beyond what you initially set to change. Nevertheless, for the sake of the argument let's say you do, or that the original program was already doing it:
#include <utility>

struct X { };

auto bar(X&& x) -> decltype(x)
{
    return std::move(x);
}

auto test()
{
    bar(X{});
}

This finally indeed compiles. But do you see the problem? You return a reference to an expired object, you return a dangling reference:
// before

#include <utility>

struct X { auto foo() const {} };

auto bar(X x) -> decltype(x) // bar returns a prvalue
{
    return x;
    // or
    // return std::move(x); // redundant, but valid and equivalent
}

auto test()
{
    const X& xr = bar(X{}); // xr prolongs the lifetime of the temporary returned by `bar`

    xr.foo(); // OK, no problem
}

// after

#include <utility>

struct X { auto foo() const {} };

auto bar(X&& x) -> decltype(x) // now bar returns an xvalue
{
    return std::move(x);
}

auto test()
{
    const X& xr = bar(X{}); // xr cannot prolong the life of an xvalue
    // the temporary objects created as part of calling `bar` is now expired
    // and xr references it
    // any attempt to use xr results in UB

    xr.foo(); // Undefined Behaviour
}

There is no way to do what you want to do.
The burden is on you, the programmer: if you need values write values, if you need references write references. It's as simple as that.

A: No.
I haven't heard of any compiler having this feature.


text:
Q: ListView with complex items, how to know the state of items? I have LinearLayout:
<LinearLayout
  xmlns:android= "http://schemas.android.com/apk/res/android"
  android:layout_width= "fill_parent"
  android:layout_height= "fill_parent">
<TextView android:id="@+id/DictLink" android:layout_width="wrap_content" android:layout_height="wrap_content" ></TextView>
<CheckBox android:text="" android:id= "@+id/DictTitle" android:layout_width="fill_parent" android:layout_height="wrap_content" ></CheckBox>
</LinearLayout>

It used as Item in ListView. Code below create a array adapter for ListView.
ArrayList< HashMap< String, String >> adapter_list = new ArrayList< HashMap< String, String > >();

    for ( String dict : dict_list )
    {
      String [ ] data = dict.split( ";" );
      HashMap< String, String > adapter_entry = new HashMap< String, String >();
      adapter_entry.put( FIELD_TITLE, data[ 0 ] );
      adapter_entry.put( FIELD_LINK, data[ 2 ] );
      adapter_list.add( adapter_entry );
    }

    String [ ] from =
    { FIELD_TITLE, FIELD_LINK };
    int [ ] to =
    { R.id.DictTitle, R.id.DictLink};

    final ListAdapter adapter = new SimpleAdapter( this, adapter_list, R.layout.dict_list_item , from, to );

How can I know which checkboxes are checked and which not?

A: The ListView class has functions that will help you:
int ListView.getCheckedItemPosition() (for single-selection lists)
SparseBooleanArray ListView.getCheckedItemPositions() (for multi-selection lists)
And more:
http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemIds()


text:
Q: How to deal with (presumable) UTF-8 strings in C programs on OSX Hopefully the question title describes my issue well enough.
Platform: OSX 10.8, llvm with clang++ compiler
I have got a directory with filenames in Japanese or Cyrillic characters. Those filenames are displayed correctly (e.g. via ls) in iTerm2 with en_EN.UTF-8 locale and Monaco 10 font (not sure if locale/font make a difference, but it seems it should). A vanilla xterm without UTF-8 support, however, prints scrambled symbols or '?' characters for non-ASCII characters.
Here is the actual question:
In C++ program, I use readdir() from dirent.h to list the contents of a directory containing filenames in Japanese or Cyrillic characters. Printing the d_name property of the struct dirent result of readdir() displays the correct characters in the Xcode terminal. That is, e.g. Japanese kanji really are displayed as such.
Same is true when executing the program from iTerm2. Again, scrambled characters in non-UFT-8 xterm.

*

*Since the byte size of Japanese filenames does not equal the number
of characters displayed, I boldly assume, the dirent.h functions work
with UTF-8 strings. Is it possible that all of the OSX C-Library
works that way?

*Therefor, is it safe to e.g. alter the struct dirent.d_name or
strcpy it and create a new file using that altered string? Is it possible to step in some trap that leads to '?????' filenames being written instead of kanji?

*Would setting a different locale, e.g. "C", mess things up (does not
seem that way when using setlocale(LC_ALL,"C")).
Note: I am not interested in possible 3rd party alternatives to dirent.h. I wrote the program solely to shed some light on how OSX deals with locale and character encoding.

A: UTF-8 is designed to be backwards-compatible with ASCII from the point of view of legacy string-handling code. This includes strcpy() and friends.
So yes, in your code it's generally safe to handle these strings as you would any other string*; it's only at display time that the clever stuff happens.
* as long as you're not meddling with individual characters in the string.

A: A valid UTF8 string doesn't contain any null characters, so any string operations should work on UTF8 encoded strings. You probably do not want to take substrings of it or modify the bytes in it though, since some of the characters are encoded in multiple bytes.
Most of the APIs which handle char* are not aware and doesn't care about the encoding, so they should be safe to use.
setlocale will affect certain operations, mostly related to dealing with character types, ordering, and formatting.
When you print the string, it goes out as a bunch of bytes. The terminal emulator interprets it as UTF8 and pick the correct characters. xterm, being unaware of unicode, will of course not be able to interpret it correctly and display the proper characters.


text:
Q: Storm (v0.9.2-incubating) Supervisor starting error after I rebooted the machine Recently I've deployed storm on a local virtual machine using VMWare. The version deployed is v0.9.2-incubating release version The issue I am facing is that '$ storm supervisor' does NOT work after EVERY SINGLE reboot.
Right now, the lousy fix I am using to clean up storm.local.dir directory. And I hope someoen can help me to get a novel solution for this.
Zookeeper version: zookeeper-3.4.6
Storm version: 0.9.2-incubating (uses Netty transport)
zeromq version: zeromq-4.0.5
jzmq version: jzmq-master (wget https://github.com/nathanmarz/jzmq/archive/master.zip)
Both Storm and Zookeeper run on the same machine.
OS: Ubuntu 14.04 LTS
Processor: Intel® Core™ i5-2410M CPU @ 2.30GHz
RAM: 1001.4 MiB

The error Message I got after running '$ storm supervisor' is shown below:
2014-11-10 12:09:56 b.s.event [ERROR] Error when processing event java.lang.RuntimeException: java.io.EOFException
    at backtype.storm.utils.Utils.deserialize(Utils.java:93) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at backtype.storm.utils.LocalState.snapshot(LocalState.java:45) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at backtype.storm.utils.LocalState.get(LocalState.java:56) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at backtype.storm.daemon.supervisor$sync_processes.invoke(supervisor.clj:207) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at clojure.lang.AFn.applyToHelper(AFn.java:161) ~[clojure-1.5.1.jar:na]
    at clojure.lang.AFn.applyTo(AFn.java:151) ~[clojure-1.5.1.jar:na]
    at clojure.core$apply.invoke(core.clj:619) ~[clojure-1.5.1.jar:na]
    at clojure.core$partial$fn__4190.doInvoke(core.clj:2396) ~[clojure-1.5.1.jar:na]
    at clojure.lang.RestFn.invoke(RestFn.java:397) ~[clojure-1.5.1.jar:na]
    at backtype.storm.event$event_manager$fn__2378.invoke(event.clj:39) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at clojure.lang.AFn.run(AFn.java:24) ~[clojure-1.5.1.jar:na]
    at java.lang.Thread.run(Thread.java:701) ~[na:1.6.0_33]
Caused by: java.io.EOFException: null
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2323) ~[na:1.6.0_33]
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2792) ~[na:1.6.0_33]
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:800) ~[na:1.6.0_33]
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298) ~[na:1.6.0_33]
    at backtype.storm.utils.Utils.deserialize(Utils.java:88) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    ... 11 common frames omitted
2014-11-10 12:09:56 b.s.event [ERROR] Error when processing event java.lang.RuntimeException: java.io.EOFException
    at backtype.storm.utils.Utils.deserialize(Utils.java:93) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at backtype.storm.utils.LocalState.snapshot(LocalState.java:45) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at backtype.storm.utils.LocalState.get(LocalState.java:56) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at backtype.storm.daemon.supervisor$mk_synchronize_supervisor$this__6330.invoke(supervisor.clj:307) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at backtype.storm.event$event_manager$fn__2378.invoke(event.clj:39) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    at clojure.lang.AFn.run(AFn.java:24) ~[clojure-1.5.1.jar:na]
    at java.lang.Thread.run(Thread.java:701) ~[na:1.6.0_33]
Caused by: java.io.EOFException: null
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2323) ~[na:1.6.0_33]
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2792) ~[na:1.6.0_33]
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:800) ~[na:1.6.0_33]
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298) ~[na:1.6.0_33]
    at backtype.storm.utils.Utils.deserialize(Utils.java:88) ~[storm-core-0.9.2-incubating.jar:0.9.2-incubating]
    ... 6 common frames omitted

A: I also ran through same problem. If you google a bit with the errors, you would find this mail-archive . The solution according to this is:

*

*Stop all the storm and zookeeper processes.

*Then clear the storm and zookeeper data directories. You fixed your Storm data directory
in your storm.yaml file and zookeeper data directory in your zoo.cfg or any file named
by you.

*Restart the processes.
everything seemed fine.


text:
Q: Generate bookmarks in Word 2010 programmatically, with the header name as the bookmark name
I need to generate bookmarks in Word 2010 programmatically, with the header name as the bookmark name.
I have the following code which makes a word a bookmark, but the bookmark name remains the same as the string Heading 1 is only available in the name variable:
Sub bookmarking()
    Selection.EndKey Unit:=wdLine, Extend:=wdExtend
    With ActiveDocument.Bookmarks
        .Add Range:=Selection.Range, Name:=" Heading 1"
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With
End Sub

Instead of the Heading 1 in the name variable, I want content from the clipboard. Please help me replace that Heading 1 with clipboard content.

A: Use a DataObject from the Microsoft Forms 2.0 Object Library:
Private Function GetClipboardData()
    Dim objDataObject As MSForms.DataObject ''need to add reference in Tools |References
    Set objDataObject = New MSForms.DataObject

    objDataObject.GetFromClipboard
    On Error Resume Next
    GetClipboardData = objDataObject.GetText
    If Err.Number = -2147221404 Then
       MsgBox "Error: current clipboard data is either empty or is not text. Clibpoard must contain text."
    End If
End Function

Then, back your main code, have the bookmark name be this clipboard data:
...
.Add Range:=Selection.Range, Name:=GetClipboardData()
...

Is this a good start for you? There are other ways which may be more robust depending on your needs. However this should serve as good proof-of-concept.


text:
Q: ** (Mix) The database for PhoenixHerokuWsmoak.Repo couldn't be created, reason given: psql: could not connect to server ** (Mix) The database for PhoenixHerokuWsmoak.Repo couldn't be created, reason given: psql: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

A: If you have this problem, Well, that's because Postgres isn't running locally. I'm not even sure it's installed. The easiest way to do that on a Mac is to grab Postgres.app from http://postgresapp.com and copy it to the /Applications folder.
Trying again:
$ mix ecto.create


text:
Q: Interesting Query in MySQL with conditions Here is the question:
Management wants to know which specific aircraft have always been assigned to the same hangar lot (each aircraft is assigned to a lot for only a year and then renewed if requested. But the lot may or may not be the same lot upon renewal; the pk for lots table is registration number and date assigned. List the aircraft registration number, hangar location, hangar capacity. Each aircraft should appear only once in your report.
Here is lots table:

lot_nbr, hangar_nbr, reg_nbr, date_assigned
'7706', '1', '505', '2011-07-17'
  '7707', '1', '505', '2012-07-18'
    '7708', '1', '505', '2013-12-22'
    '8801', '2', '101', '2011-01-22'
    '8802', '2', '101', '2012-01-22'
    '8803', '2', '303', '2011-01-10'
    '8803', '2', '202', '2011-04-12'
    '8803', '2', '202', '2012-04-12'
    '9902', '3', '303', '2012-01-10'
    '9904', '3', '404', '2011-01-10'
    '9905', '3', '404', '2012-01-10'

Here is hangar table:

hangar_nbr, location, capacity, manager_nbr
'1', 'South RW', '24', '902'
  '2', 'North RW', '12', '902'
  '3', 'West RW', '25', '902'

Here is aircraft table: (Might be needed)

reg_nbr, plane_type, manufacturer, resident, date_service
  '101', 'SE', 'Prop', 'Lear', '1', '1998-12-01'
  '202', 'DE Prop', 'Cessna', '1','1999-11-22'
  '303', 'SE Jet', 'Bombardier', '1', '2000-07-06'
   '404','ME Jet', 'Lear', '1', '2001-02-24'
   '505', 'SE Prop', 'Cessna', '0','2003-12-01'
   '606', 'DE Prop', 'Bombardier', '1', '2004-11-22'
   '707','SE Jet', 'Lear', '1', '2005-07-06'
  '808', 'ME Jet', 'Cessna', '0','2005-02-24'
   '909', 'SE Prop', 'Bombardier', '1', '2002-02-12'

The query I want (Exactly):

reg_nbr, location, capacity
   '202', 'North RW', '12'

Here is what I tried:
SELECT lots.reg_nbr, location, capacity
FROM hangar, lots
WHERE lots.hangar_nbr = hangar.hangar_nbr AND reg_nbr='202'
GROUP BY lots.reg_nbr

My Problem:
As shown above I wanted to show aircraft with reg_nbr '202' in my result because it is the only aircraft that has been allocated the same lot_nbr every time but unfortunately the way I did i.e writing reg_nbr ='202' in WHERE clause is not the way query should be done. I want to show how get this results but with a real and legal query. Thanks a lot for your effort.

A: Presumably, reg_nbr is for the aircraft.  You can get the aircraft with a using a single table, group by, and having clause:
SELECT reg_nbr, hangar_nbr, lot_nbr
FROM lots
GROUP BY reg_nbr
HAVING MAX(hangar_nbr) = MIN(hangar_nbr) AND
       MAX(lot_nbr) = MIN(lot_nbr)

A: SELECT reg_nbr
FROM lots
GROUP BY reg_nbr
HAVING COUNT(DISTINCT lot_nbr) = 1


text:
Q: Reach the attributes of an input element in the template - AngularJS I would like to reach the attributes of an input element the way something like this:
<input name="name" type="text" class="form-control" id="salonName" data-ng-model="salon.name" ng-minlength=3 ng-maxlength=30 required/>
    This works: {{myForm.name.$viewValue}}
    This does not: {{myForm.name.id}}
    This does not too: {{myForm.name.ngMinlength}}

A: You can do that by using simple directive, like:
JS
var fessmodule = angular.module('myModule', []);

fessmodule.controller('fessCntrl', function ($scope) {});
fessmodule.$inject = ['$scope'];

fessmodule.directive("myDirective", function () {
            return function(scope, element, attrs) {
                scope.name = attrs['name'];
                scope.type = attrs['type'];
                scope.class = attrs['class'];
                scope.id = attrs['id'];
                scope.ngMinlength = attrs['ngMinlength'];
                scope.ngMaxlength = attrs['ngMaxlength'];
                scope.ngModel = attrs['ngModel'];
                scope.required = attrs['required'];
            };
    });

Add directive to HTML:
<input my-directive
            name="name"
            type="text"
            class="form-control"
           id="salonName"
           data-ng-model="salon.name"
           ng-minlength=3
           ng-maxlength=30
           required/>

 Name: {{name}}

 type: {{type}}

 class: {{class}}

 ngMinlength: {{ngMinlength}}

 ngMaxlength: {{ngMaxlength}}

 ngModel: {{ngModel}}

 required: {{required}}

Demo Fiddle


text:
Q: Move a game object between two positions in a sin wave I have two positions in a unity scene and I want a sphere game object to move between them. This is easy enough to do with the move towards command, but what I want to happen is the ball to accelerate when leaving one, then decelerate when approaching the next in a controlled curve. I need it to osculate between the two positions in a manor similar to that of a ball being rolled.
I was told that I could do this with a sin wave, however I'm unsure how. Is there a simple way to do this ?

A: Preamble
There are a number of ways to solve your problem, not only by using sine function.
Sine function example
Here's an example:
public float frequency = 1.0f; // in Hz
public Vector3 positionA;
public Vector3 positionB;
private float elapsedTime = 0.0f;

public void Update()
{
    elapsedTime += Time.deltaTime;
    float cosineValue = Mathf.Cos(2.0f * Mathf.PI * frequency * elapsedTime);
    transform.position = positionA + (positionB - positionA) * 0.5f * (1 - cosineValue);
}

Cosine is used here instead of sine just for convenience.

A: I faced with almost the same task. My objects were located in random positions, the line between two of them was not parallel to axis. So, I created common solution which can helps anybody.
Here is demo video, source code on Github.
The script is very simple by itself. All we need to do is calculate two vectors - vector of main direction and orthogonal vector. After this we need to subordinate orthogonal vector by sine function, and then perform addition of these two vectors, so the sum will move object following exact sine curve.
void FixedUpdate () {
    float t = Time.time - startTime;
    rb.velocity = direction * speed + orthogonal * amplitude * Mathf.Sin (frequency * t);
}

You can find more details here - how to setup scene, components, etc.


text:
Q: Git hooks: where do I put them after I push to remote repo I've read the git hooks documentation and I'ms still trying to figure out where I put scripts for git hooks for certain events, and how I manage them:
Preconditions:

*

*Create bare git repository foo on some machine A

*Jenkins running on machine A

*I clone my repository foo to machine B

*I make some changes to foo on machine B

*Commit changes to foo on B

*Push changes to foo to A

*Assume master branch

Desired Behavior:
After pushing to machine A, I want Jenkins to kick off a build on machine A
One machine A, there is a hooks directory with various hook scripts samples.
One machine B, there is a .git/hooks directory with various hook script samples.
Questions:

*

*Where do I put the script to cause Jenkins to rebuild my app? On machine A or on machine B?

*What would the name be? post-push?

*If I put them on machine B, don't the scripts get wiped out if I delete my clone of foo and re-clone the repository?

*Would I have to re-create them if I re-clone?

*Are git hooks themselves version under git version control or do you just manage them free of source control?

Thanks

A:
Where do I put the script to cause Jenkins to rebuild my app?

On the machine that runs Jenkins (so on Machine A).

What would the name be? post-push?

You want a post-receive hook (assuming A is your remote), which:

[...] is run on the remote when pushing after the all refs have been
  updated. It does not take parameters, but receives info through stdin
  in the form of "  ". Because it is
  called after the updates, it cannot abort the process.

-

If I put them on machine B, don't the scripts get wiped out if I delete my clone of foo and re-clone the repository?
Would I have to re-create them if I re-clone?

Yes. Because:

Are git hooks themselves version under git version control or do you just manage them free of source control?

They are not because active hooks live in .git/hooks which is not under version control. See that answer for more details.
That said, this may be an XY problem. You probably don't want to do this specifically to trigger builds, but use Jenkins' polling to scan for changes, which would probably be simpler to manage.


text:
Q: Error in connecting to mongodb cluster with replica sets in another host I have an nodejs application in staging environment which need a MongoDB replication set to run. I have created my MongoDB instance like below:
$ mongod --port 27017 --replSet rs0 --dbpath /data/db1 --smallfiles --oplogSize 128
$ mongod --port 27018 --replSet rs0 --dbpath /data/db2 --smallfiles --oplogSize 128
$ mongod --port 27019 --replSet rs0 --dbpath /data/db2 --smallfiles --oplogSize 128

and set db1 as primary. the application also running in the same host and connect to the database like this:
const { connectionString, replicaSet } = config.mongodb;

try {
  mongoose
    .connect(
      connectionString,
      {
        useNewUrlParser: true,
        replicaSet,
      },
    )
    .then(() => mongoose.connection.db.admin().command({ setFeatureCompatibilityVersion: '4.0' }));

which connectionString is: mongodb://localhost:27017/x.
now I running application in my machine and want to connect it to host database so I change connectionString to: mongodb://172.16.25.66:27017/x but MongoNetworkError: failed to connect to server [localhost:27019] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27019] I am confused, why its logged 127.0.0.1:29019? I think it should be the host IP address not local?
how can fix this so that I could connect to staging host MongoDB with application in local?
Edit:
if Ip put console.log(connecitonString) in above code the result would be same as the input.
But I figured out something interesting, when I delete replicaSet option in connect function it works ok! can anybody explain this?


text:
Q: Create Github Actions dashboard Is there a way to crease a summary dashboard for all my Github actions. This is something we had with Jenkins. We could see all deployment status on a single page.
From my research I found that there are tools out there like: ccmenu, nevergreen and so on but I am not too convinced about them.
I think, that I have seen some solutions for "system" status that include the CI portion but I cannot remember and Google is not helping me a lot.
Thanks for the help

A: In GitHub, you either get a status badge from your builds which would be generated as:
https://github.com/<OWNER>/<REPOSITORY>/actions/workflows/<WORKFLOW_FILE>/badge.svg

Or by clicking the options menu on your workflow page:

Then you can use these badges in your dashboard.

Also, with the new update you can create Job summaries:
jobs:
  foo:
    runs-on: ubuntu-latest
    steps:
      - name: Something
        ...
      - name: Generate list using Markdown
        run: |
          my_table="
          | Column1     | Status             | Something |
          |-------------|--------------------|-----------|
          | :octocat:   | :white_check_mark: | Passed    |
          | :honey_pot: | :x:                |           |
          "
          echo "# This is an example" >> $GITHUB_STEP_SUMMARY
          echo "Using \`markdown\`" >> $GITHUB_STEP_SUMMARY
          echo "$my_table" >> $GITHUB_STEP_SUMMARY

Result:

Then you can use one last action to write/emit your Github run URL for example to your dashboard.
See:

*

*https://github.blog/2022-05-09-supercharging-github-actions-with-job-summaries/

*https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary

*https://docs.github.com/en/actions/monitoring-and-troubleshooting-workflows/adding-a-workflow-status-badge

Other than that, I don't think that we can answer with recommendations for tools and products that may do that for you. But seems that the tools you found may do the job very well.


text:
Q: How to implement an ASP.NET Core controller supporting Razor and Angular? Currently, I'm writing a web application in C# ASP.NET Core and Razor Pages.
In the future I want to replace my frontend with an Angular application. Now I'm wondering how to set up my controllers to serve both technologies.
The problem is, that my controller methods have to return a ViewResult object to properly render the view when using Razor Pages. The result obviously can't be used in Angular and the controller methods aren't really RESTful which I want them to be.
So is there a way to implement a controller supporting Razor and Angular?
Thanks in advance

A: If you are going the angular way, not really. Angular expects communication using Xhr requests.
There is even a template in net core for angular applications: https://learn.microsoft.com/en-us/aspnet/core/client-side/spa/angular?view=aspnetcore-3.1&tabs=visual-studio
In theory you could achieve what you want with some duplication.
I.e.:
[HttpGet]
public ActionResult Index()
{
     IndexViewModel viewModel = GetIndexModel();
     // Add action logic here
     return View(viewModel);
}

[HttpGet]
public IndexViewModel GetIndexModel() {
   // return the view model.
}

The second get function can be used as xhr request from your angular application. This is not really recommended. Going angular is a good opportunity to turn your api to Rest and properly handle the data in your spa.


text:
Q: Javascript change width of div onclick I'm trying to do three things onclick:

*

*have element with id="notes_content" change display:none to display: block

*have element with id="oct" change width = "1190px" to width = "550px"

*have elements with class="oct_days" change width = "168px" to width = "73px"
Fiddle of full code: http://jsfiddle.net/ascottz/jX3wh/
The first two happen, but the third does not. I suspect it is a syntax error, but can't catch it myself.

A: getElementsByClassName returns an array of dom elements, it is not a single instance. You must loop over the array and style each element.
Have a look at the updated fiddle.
for( var i = 0; i < days.length; i++ ){
    days[i].style.width = "73px";
}

http://jsfiddle.net/jX3wh/4/

A: document.getElementsByClassName returns somewhat an array of elements, so you cannot simply refer to it as a DOM element in hope that it will work as you refer to each element of the collection (that is possible in jQuery, btw), so you have to use the foreach loop (doesn't matter how are you gonna achieve this -- via simple for(), or for(x in y), or any other way).
I usually use Array.forEach function, but the specific type of an array returned by the document.getElementsByClassName does not have such function in prototype, so you have to use [].forEach.call(inWhat,function(what){}) syntax, or fallback to for(...) syntax.
Check out this: http://jsfiddle.net/jX3wh/1/
Dunno if it works.

A: Also, what the f is this???
<div onclick="javascript:showDiv();" class="oct_days">

I am really very surprised this works. You should use onclick="showDiv()" instead, I think.
Somebody, please, tell me how does it work!


text:
Q: Spring Boot [2.6.6] is not compatible with this Spring Cloud release train We're trying to upgrade spring boot version to 2.6.6 and faced up with "Spring Boot [2.6.6] is not compatible with this Spring Cloud release train" (when running integration tests).
In additional
spring-cloud.version = 2021
We're using org.springframework.cloud (spring-cloud-starter-openfeign & spring-cloud-openfeign-cores) 3.1.1
according to the documentation , spring boot support 2.6.6 should be compatible.

A: You could try and set your spring cloud version to
spring-cloud.version = 2021.0.1

If it is not that simple mistake I am sorry. The documentation that you linked to is correct. Spring Boot [2.6.6] is compatible with spring-cloud.version 2021.x.x. openfeign 3.1.1 is also part of springCloud 2021.x.x. I have multiple project with this configuration running. In all of them the runtime as well as the integration test are working properly. Otherwise a stacktrace would be nice to gain further information :)

A: I have multimodule project using maven.
After migrating for Spring-Boot version 2.4.2 to 2.6.6, I face multiple issues.

*

*First one is the application won't be able to find the Bootstrap class. The error is:
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.Bootstrapper
To fix the issue I need to add the dependency in the pom.xml of the module:
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-bootstrap</artifactId>
    </dependency>

*

*Second problem I face is to this "Spring Cloud release train"

In this case I need to upgrade the Spring-Cloud version to "2021.0.1" which is compatible with Spring-Boot 2.6.6

*

*Third problem I face is this error while starting the application:
"No spring.config.import property has been defined"
The reason for this error is that some of the "bootstrap.properties" files are deprecated in the new version so application won't starts. To fix this, we need  to add below property in application.properties or application.yml file.
spring.config.import=optional:configserver:


text:
Q: error in receiving serial data after sometime My microcontroller continuously sends data in this format "900 899|900 898|900 800 900 700|900 799 900 756|". My Java code reads the data correctly for some time, but later it receives something like this " 900 899900 899".(note that there is a space before my first 900 which is causing error) causing "java.lang.NumberFormatException:" at the statement where i convert the string to int.. Please help me with this bug...
Note: Check these readings "900 808 900 899|900 806 900 899| 900 899900 899|" It was supposed to read 900 804, instead it is reading the value received previously i.e 900 899
import java.io.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;

import javax.comm.*;

public class SimpleRead implements Runnable, SerialPortEventListener {

static int X[];
static int Y[];
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
byte[] readBuffer = new byte[500];
byte[] noOfBalls = new byte[2];
byte[] temp = new byte[1];
static int arrayEnd = 0;

public SimpleRead(CommPortIdentifier portId) {

    try {
        serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
    }
    catch (PortInUseException e) {System.out.println(e);}

    try {
        inputStream = serialPort.getInputStream();
    }
    catch (IOException e) {System.out.println(e);}

    try {
        serialPort.addEventListener(this);
    }
    catch (TooManyListenersException e) {System.out.println(e);}

    serialPort.notifyOnDataAvailable(true);

    try {
        serialPort.setSerialPortParams(115200,
            SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1,
            SerialPort.PARITY_NONE);
    }
    catch (UnsupportedCommOperationException e) {System.out.println(e);}

    readThread = new Thread(this);
    readThread.start();
}

public void run() {
    try {
        Thread.sleep(20000);
    } catch (InterruptedException e) {System.out.println(e);}
}

public void serialEvent(SerialPortEvent event) {
    switch(event.getEventType()) {
    case SerialPortEvent.BI:
    case SerialPortEvent.OE:
    case SerialPortEvent.FE:
    case SerialPortEvent.PE:
    case SerialPortEvent.CD:
    case SerialPortEvent.CTS:
    case SerialPortEvent.DSR:
    case SerialPortEvent.RI:
    case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
        break;
    case SerialPortEvent.DATA_AVAILABLE:
        arrayEnd = 0;
        try {
            while (inputStream.available() > 1 ) {
          /*    for(int i=0; i< 2; i++){
                    inputStream.read(temp);
                    noOfBalls[i] = temp[0];
                }
                String tmp = new String(noOfBalls);
                int iterations = Integer.parseInt(tmp);
                iterations = iterations * 2;
                for(int j =0; j< iterations; j++){*/
                inputStream.read(temp);
                if (temp[0] == '|') break;
                else
                    readBuffer[arrayEnd++] = temp[0];

                //}
           }
        } catch (IOException e) {System.out.println(e);}
        createXYArray();

       // serialPort.close();/****closing for now, later not needed*/
        break;
    }
}

private void createXYArray() {
    System.out.println(new String(readBuffer));
    X = new int[100];
    Y = new int[100];
    byte[] tmpXY = new byte[3];
    int i = 0;
    while(i < readBuffer.length){
        if(readBuffer[i]==0) break;
        int j=0;
        while(readBuffer[i]!=' ' && j!=3){
            //System.out.println(i);
            tmpXY[j] = readBuffer[i];
            //System.out.println("x "+tmpXY[j]);
            i++; j++;
        }
//  if(j!=3) break;
            createX(tmpXY);
        i++;
        j = 0;
        while(readBuffer[i]!=' ' && j!=3 ){
            tmpXY[j] = readBuffer[i];
        //  System.out.println("y "+tmpXY[j]);
            i++;
            j++;
        }
    /*  if(j==3){
            for (int k = 0; k < 3; k++) {
                three[k] = tmpXY[k];
            }
            createY(three);
        }
        else   */
            createY(tmpXY);
        i++;
    }
}

private static void createY(byte[] tmpY2) {

    String tmp = new String(tmpY2);
    Y[arrayEnd] = Integer.parseInt(tmp);
    //System.out.println(Y[arrayEnd]+" y");
    arrayEnd++;
}

private static void createX(byte[] tmpX2) {

    String tmp = new String(tmpX2);
    X[arrayEnd] = Integer.parseInt(tmp);
    //System.out.println(X[arrayEnd]+" x");

}
}

A: Use the trim method on the String objects you're parsing. That will remove any leading or trailing spaces.

A: Ok guys, i figured out what the error was. In the statement "while (inputStream.available() > 1 ) ", we have to replace 1 with -1. I dont really know why, but i did trial and error and i found it working properly for while (inputStream.available() > -1 ) .
If anyone knows why, please add in comments..


text:
Q: Doesn't dispose() method of ConnectionMultiplexer flushes all keys and the redis database it is connected to? I have cached my database using Redis. When I run dispose() method on instance of redis's connectionmultiplexer class, it does not flushes out keys and the database.
---
 private static ConnectionMultiplexer _conn;
private static ConnectionMultiplexer Connection
    {
        get
        {
            lock (Lock)
            {

                    //Close & Dispose Old connection
                    if (_connection != null)
                    {
                           _conn.Close(false);
                           _conn.Dispose();
                           _conn = null;
                    }

                   ---
                   ---

                    return _conn;
            }
        }
    }

Question: What exactly this dispose() method do then? Shouldn't it flush out and clear all redis database which are connected to _conn?

A: Why should the client ever flush Redis automatically??
The thing would not be usable by anyone actually using it as a distributed cache (many connected clients using the shared cache...).
Redis has a FLUSH and FLUSHALL command which work per server, you can explicitly call those.
See
https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/KeysScan.md

A: The Dispose(...) operation on the ConnectionMultiplexer closes the connections and releases other resources like ServerEndpoint objects associated with the ConnectionMultiplexer object. it doesn't issue any commands to Redis.
The sources are here: https://github.com/StackExchange/StackExchange.Redis/blob/master/StackExchange.Redis/StackExchange/Redis/ConnectionMultiplexer.cs


text:
Q: Odoo Boolean Graph? I'd like to display a graph in odoo. in which i have two fields:
Date in the x-axis.
Boolean in the y-axis.
odoo use the nvd3.js to display this charts,
this is the view.xml:
<record model="ir.ui.view" id="id_view">
            <field name="name">test.base.graph.view16</field>
            <field name="model">module.base</field>
            <field name="type">graph</field>
            <field name="arch" type="xml">
                <graph string="test" type="bar" >
                     <field name="date" interval="day" type="row"/>
                     <field name="boolean" type="measure"/>
                </graph>
            </field>
</record>

this code doesn't work for me, it return an empty graph. any one have idea about this issue.

A: Simulate both fields as integers, one by one.
Clearer:
Add two additional fields:
'date_sim': fields.integer("Date simulation"),
 'bool_sim': fields.integer("Bool simulation")
And for the first two fields, just add two methods decorated by @api.onchange
And in their bodies just update the _sim fields with corresponding values.
And at last you should use the new fields in your view.

A: Try the following:
<record model="ir.ui.view" id="id_view">
    <field name="name">test.base.graph.view16</field>
    <field name="model">module.base</field>
    <field name="arch" type="xml">
        <graph string="test" type="bar" stacked="True" interval="day">
            <field name="date" type="row" interval="day"/>
            <field name="boolean" type="measure"/>
        </graph>
    </field>
</record>


text:
Q: How to ignore newlines in TextField? Simple question that I'm not finding an answer to--I have a TextField that's multi-line but I don't want to allow newlines in the text. E.g., if the user is typing and hits [Enter], I don't want a newline to register in the TextField. How do I do that?
I tried catching it in the onChanged event, but got weird rendering results:
      onChanged: (value) {
        if (value.endsWith('\n')) {
          _textController.text = value.trim();
        }
      },

A: You should try using BlacklistingTextInputFormatter in inputFormatters.
inputFormatters: [
  FilteringTextInputFormatter.deny(new RegExp(r"\n"))
],

A: What if you use following parameters:
TextField(keyboardType: TextInputType.text, maxLines: 3,);


text:
Q: Correctly format WiX bundle MSI Package Install Condition I have an MSI that I need to install under certain conditions and I am struggling to work out how to write the condition to achieve it. I followed this page, http://wixtoolset.org/documentation/manual/v3/bundle/bundle_define_searches.html to produce this condition, and two product searches creating the variables.
<util:ProductSearch ProductCode="34DA9145-859A-4645-A0BD-6F22C551F8A9"
                    Result="version"
                    Variable="StandAloneMmaVersion"/>
<util:ProductSearch ProductCode="EE0183F4-3BF8-4EC8-8F7C-44D3BBE6FDF0"
                    Result="version"
                    Variable="AzureMmaVersion"/>

InstallCondition="StandAloneMmaVersion < 8.0.110720.0 OR AzureMmaVersion < 8.0.110720.0"

However when executed this produces the error message:

Error 0x8007000d: Failed to parse condition "StandAloneMmaVersion < 8.0.110720.0 OR AzureMmaVersion < 8.0.110720.0". Unexpected character at position 24.

The page shows the < typed out but Visual Studio refused to build like that hence escaping them.
For bonus points what I would really like, but have not been able to find any examples of, is that I would like install condition to only affect install, not repair or modify.

A: In Burn, version constants must have a v prefix:
StandAloneMmaVersion < v8.0.110720.0


text:
Q: Why does Python json module represent floats in dictionary keys as strings? See the following code:
>>> import json
>>> m = {}
>>> m[0.0] = 1.0
>>> json.dumps(m)
'{"0.0": 1.0}'

In the value of the JSON, we have 1.0.  But in the key we have "0.0" (a Json string).
This ambiguous handling of floats just cost me some debugging time.  Does anyone know why python's json module does this?

A: Because a JSON key must be a string. See the RFC.


text:
Q: SQL Server 2008 Trigger which sends email Does anyone know why this wouldn't work?  It's a trigger which checks the value of a field on insert and update and sends an email with the value of an id column from the offending row.
ALTER TRIGGER [dbo].[DB]
ON [dbo].[table]
AFTER INSERT, UPDATE AS
BEGIN
IF EXISTS(SELECT 1 FROM inserted WHERE value = 5)
   BEGIN
      EXEC msdb.dbo.sp_send_dbmail
        @recipients = 'me@derp.com',
        @profile_name = 'MailProfile',
        @subject = 'DB.dbo.table trigger',
        @body = '',
        @execute_query_database = 'DB',
        @query = 'USE DB SET NOCOUNT ON SELECT id FROM dbo.table WHERE value = 5';
   END
END

The problem seems to be the @query in the sp_send_dbmail function.  When I manually try triggering it I receive the following error;
No row was updated.
The data in row x was not committed.
Error Source: .Net SqlClient Data Provider.
Error Message:  Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
Correct the errors and retry or press ESC to cancel the change(s).

When I remove @execute_query_database and @query and add some plain text to the @body var the trigger works and I receive an email.
I've also tried changing the @query value to something really simple e.g. SELECT "Test" as test but this didn't help.
I'm completely new to triggers so if the problem is painfully obvious... apologies :)

A: You need semi-colons:
@query = 'USE DB; SET NOCOUNT ON; SELECT id FROM dbo.table WHERE value = 5;';


text:
Q: find all unique triplets in array with sum equal to zero in c++ Hello I have refered this program and there mention in comment // DO NOT write int main() function, and when i run run this code it will give me error:- /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o: In function _start':
(.text+0x20): undefined reference tomain'
collect2: ld returned 1 exit status
I wrote main for it bu still it wont compile please suggest any suggestion for this issue. Thanx in advanced. I wrote my code as below:-
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > vv;
        if(num.size()<3){
            return vv;
        }

        sort(num.begin(), num.end());
        // In general, we can make the triples unique by the set trick
        // For 3Sum, it is guaranteed by 1, 2, 3
        for(int i = 0; i<num.size()-2; i++){
            if(i>0 && num[i]==num[i-1]){                // 1
                continue;
            }
            // convert 3Sum to 2Sum
            int target = -num[i];
            if(target<0){
                break;
            }
            int j = i+1;
            int k = num.size()-1;
            while(j<k){
                if(num[j]+num[k]==target){
                    vector<int> v;
                    v.push_back(num[i]);
                    v.push_back(num[j]);
                    v.push_back(num[k]);
                    vv.push_back(v);
                }
                if(num[j]+num[k]<=target){

                    // Don't forget ++

                    while(num[j++]==num[j] && j<k){};   // 2
                }
                else{
                    while(num[k--]==num[k] && k>j){};   // 3
                }
            }
        }
        return vv;
    }
};

A: 1- if you want create library (build  time link or run time link) no need to use c++ EntryPoint (I mean main fumction)
but if use want create portable executable file you need an Entry Point for your Project, for building this code you need last version of g++ to support c++14, if you realy want build a runtime library (.so) add -shared option to g++ command line


text:
Q: Read content of Web Browser in WPF Hello Developers I want to read external content from Website such as element between  tag . I am using Web Browser Control and here is my code however this Code just fills my Web browser control with the Web Page
public MainWindow()
{
    InitializeComponent();

    wbMain.Navigate(new Uri("http://www.annonymous.com", UriKind.RelativeOrAbsolute));
}

A: You can use the Html Agility Pack library to parse any HTML formatted data.
HtmlDocument doc = new HtmlDocument();
doc.Load(wbMain.DocumentText);

var nodes = doc.SelectNodes("//a[@href"]);

NOTE: The method SelectNode accepts XPath, not CSS or jQuery selectors.
var node = doc.SelectNodes("id('my_element_id')");

A: As I understood from your question, you are only trying to parse the HTML data, and you don't need to show the actual web page.
If that is the case than you can take a very simple approach and use HttpWebRequest:
    var _plainText = string.Empty;
    var _request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
    _request.Timeout = 5000;
    _request.Method = "GET";
    _request.ContentType = "text/plain";
    using (var _webResponse = (HttpWebResponse)_request.GetResponse())
    {
        var _webResponseStatus = _webResponse.StatusCode;
        var _stream = _webResponse.GetResponseStream();
        using (var _streamReader = new StreamReader(_stream))
        {
            _plainText = _streamReader.ReadToEnd();
        }
    }

A: Try this:
dynamic doc = wbMain.Document;
var htmlText = doc.documentElement.InnerHtml;

edit: Taken from here.


text:
Q: What is the the output of the following C programme? I don't know what the compilar is doing with ++*p;
Can anyone explain me pictorically what is going on inside the memory in this code?
int main()
{
    int arr[]={1,2,3,4};
    int *p;
    p=arr;
    ++*p;
    printf("%d",*p);
}

A: The answer should be 2
The reason is ++*p is is actually incrementing the first member in the array by 1.

A: You are incrementing the first element in that array by creating another int pointer p that points to the element. The line
 ++*p

increments the value of the object pointed to by p - in this case it is the first element in the array.

A: Let's take this line :
++*p

This will first dereference the p pointer, so access arr[0], then increment it.
if you print arr[0] now, it will be 2.
Then you print *p that is the same as printing arr[0], it equals 2.
Try replacing the first element by 41, your code will print 42.

A: When you have a pointer int *p, then p means "the memory address p points to and *p means "the contents of the memory address where p points to". ++ means pre-increment, which means increase the value by 1. Since the associativity of unary operators such as * and ++(prefix operators) is right-to-left, and * is closer to p than ++ when traversed right-to-left, * operates before ++. Therefore ++*p means "increment the value pointed to by p", not "increment p then get the value". It is clearer to write ++(*p), but it means the same thing.
The thing to understand is the difference between "increment the pointer", which means point to another value (e.g. ++p) and "increment the value that the pointer points to" (e.g. ++*p).
You can work this out, but that is all the information you need to understand it.

A: Making up the actual memory addresses and using "ma" for memory address
at memory address starting at 1000 we have 4 continuous 4-byte (sizeof(int) = 4) slots.
  each slot contains the integer value given in the array initializer:
  arr
  ma1000 ... ma1015
  _____________________
  |   1|   2|   3|   4|
  _____________________

arr gives the starting address of the 4 int slots and how many there are.
  p holds the address of an integer and refers to one 8-byte slot in memory (assuming we are on a 64-bit system where pointers are 8 bytes - 64 address bits/8bits-per-byte) at location 2000.
  After the statement p = arr, p holds the address 1000
  p                     *p or arr[0]
  ma2000 .. ma2007      ma1000 .. ma1003
  __________            ________
  |    1000|            |    1 |
  __________            ________

*p gives the value at the memory address pointed to by p. p holds  memory address 1000 and memory address 1000 contains 1, thus *p results in 1.
++*p says to increment the value of the int "pointed to" by p. p holds memory address 1000 which holds the value 1. The value at address 1000 then goes from 1 to 2
 arr
 ma1000 ... ma1015
 _____________________
 |   2|   2|   3|   4|
 _____________________

printf then prints the int value at the address "pointed to" by p, which is 2.
  p                     *p or arr[0]

  ma2000 .. ma2007       ma1000 .. ma1003
  ___________           ___________
  |     1000|           |        2|
  ___________           ___________

A: This is a very basic concept in understanding of pointers.
p = arr ;

The above code will make the pointer " p " to point towards what the " arr " is pointing to. " arr " itself is pointing to the 1st element.
*arr = *(arr + 0) = arr[0] = 1
*(arr + 1) = arr[1] = 2
*(arr + 2) = arr[2] = 3

and so on...
So now when you do ++(*arr) that means ++(1) = 2
As p = arr, you can do the remaining replacement and math.


text:
Q: Is there any way in php to get time zone list as like window pc? Is there any way in php to get time zone list as like window pc
i want php code to get timezones in dropdown list,they are display like in this page https://code.google.com/p/cartotheque/wiki/TimeZoneList (cities have similar timezones in one option)......not in this( https://en.wikipedia.org/wiki/List_of_time_zones_by_country )page

A: Updated 1.0
I already adjust the way you wanted.
Full code
function timezone_list() {
    static $timezones = null;

    if ($timezones === null) {
        $timezones = [];
        $offsets = [];
        $now = new DateTime();

        foreach (DateTimeZone::listIdentifiers() as $timezone) {
            $now->setTimezone(new DateTimeZone($timezone));
            $offsets[] = $offset = $now->getOffset();
            $timezones[$timezone] = '(' . format_GMT_offset($offset) . ') ' . format_timezone_name($timezone);
        }

        array_multisort($offsets, $timezones);
    }

    return $timezones;
}

function format_GMT_offset($offset) {
    $hours = intval($offset / 3600);
    $minutes = abs(intval($offset % 3600 / 60));
    return 'GMT' . ($offset ? sprintf('%+03d:%02d', $hours, $minutes) : '');
}

function format_timezone_name($name) {
    $name = str_replace('/', ', ', $name);
    $name = str_replace('_', ' ', $name);
    $name = str_replace('St ', 'St. ', $name);
    return $name;
}

The Output will display like this
Array
(
    [Pacific/Midway]    => (GMT-11:00) Pacific, Midway
    [Pacific/Niue]      => (GMT-11:00) Pacific, Niue
    [Pacific/Pago_Pago] => (GMT-11:00) Pacific, Pago Pago
    [America/Adak]      => (GMT-10:00) America, Adak
    [Pacific/Honolulu]  => (GMT-10:00) Pacific, Honolulu
    [Pacific/Johnston]  => (GMT-10:00) Pacific, Johnston
    [Pacific/Rarotonga] => (GMT-10:00) Pacific, Rarotonga
    [Pacific/Tahiti]    => (GMT-10:00) Pacific, Tahiti
    [Pacific/Marquesas] => (GMT-09:30) Pacific, Marquesas
    [America/Anchorage] => (GMT-09:00) America, Anchorage
    etc (and so on)
)

A: There is: timezone-identifiers-list.

A: You can get timezone, but as you know PHP is server side language so it will give you server timezone, so to get timezone like window pc you need to use some client side javascript, you can use jstz plug-in and you can find it here

http://pellepim.bitbucket.org/jstz/
Example after integration of plugin :
var timezone = jstz.determine();
timezone.name();

And it will give you answer "Asia/Kolkata"

A: Use can get timezone Listing using something like this:
<?php
    $timezones = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
    echo '<pre>';
        print_r($timezones );
    echo '</pre>';
?>


text:
Q: Plot overlaps of time intervals I have the following df
Id   a_min_date      a_max_date      b_min_date     b_max_date       c_min_date       c_max_date           d_min_date     a_max_date
1    2014-01-01      2014-01-10      2014-01-05     2014-01-15            NA               NA              2014-02-20       2014-05-01
2    2014-02-01      2014-02-10       NA              NA               2015-02-20       2015-03-01             NA               NA

I have added the intervals of each group (a, b, c,d) by ID. First, I have converted the start and end dates to lubridate intervals.
I want to plot the intervals and calculate the time difference in days between the end of each group and the start of next group if there is no overlap.
I tried to use IRanges package and converted the dates into integers (as used here (link)), but does not work for me.
ir <- IRanges::IRanges(start = as.integer((as.Date(df$a_min_date))), end = as.integer((as.Date(df$a_max_date))))
bins <- disjointBins(IRanges(start(ir), end(ir) + 1))
dat <- cbind(as.data.frame(ir), bin = bins)

ggplot(dat) +
  geom_rect(aes(xmin = start, xmax = end,
                ymin = bin, ymax = bin + 0.9)) +
  theme_bw()

I got this error for my orginal df:
Error in .Call2("solve_user_SEW0", start, end, width, PACKAGE = "IRanges") :
  solving row 1: range cannot be determined from the supplied arguments (too many NAs)

Does someone have another solution using other packages?

A: To my knowledge, IRanges is the best package out there to solve this problem.
IRanges needs range values (in this case dates) to compare and does not handle undefined values (NAs)
To solve this problem, I would remove all rows with NAs in df before doing the analysis.
df <- df[complete.cases(df[ , 1:2]),]

Explanation and other ways to remove NAs see Remove rows with all or some NAs (missing values) in data.frame.
If this does not fix the problem, you could convert the dates into integers. Important there is that the dates have the year-month-day format to result in correct intervals.
Example:
str <- "2006-06-26"

splitted<- unlist(strsplit(str,"-"))
[1] "2006" "06"   "26"

result <- paste(splitted,collapse="")
[1] "20060626"


text:
Q: How to print the TAX or GST of products seperately with tax rates I need to print the tax rates of different products separately.Currently i could get the total tax when i'm placing order.I had already changed Tax Calculation Method Based On unit prize in configuration.Please help me to fix it.

Configuration settings