text:
Q: How can I implement frame independent movement with selectable speed I'm learning basic frame independent movement, but I have a necessary need in the implementation.
Right now, I'm searching for C++ code, but I need a complete example inside a GameLoop that allows an increase in speed. Not a gradual increase, but just the ability to move my sprite faster. I have to translate the C++ code to vb .net since there are not many examples. So let me be clear about this ->
I have a simple GameLoop. In the GameLoop, I have two calls to functions
Update()
Render()
I understand that for the Update() function I should put a deltaTime parameter. So it should be
Update(deltaTime As double)
Since this is how most examples on the web are shown, I just copied the idea but I don't have an actual frame independent setup yet.
How can I set this up and call the Render function.
Please keep in mind, that if it works, that's fine - I cut and paste a different example like that before, but there was no way to increase the speed of the moving sprite. I don't even know where to begin with this?
Please note if you only have C++ code, I will do my best to translate it, so for me it's acceptable.

A: That deltaTime idea is to allow your game to run in a way where the perceived speed of the gameplay is constant no matter how fast or slow the machine and environment are that are running the game.
You might notice if you run some poorly coded games designed for old hardware on hardware much newer that the gameplay goes way too fast and becomes unplayable on those fast machines without deliberately slowing things down. There are actual slowdown utilities just to deal with that problem, like Mo'Slow and Cpukiller. This is because these old games were coded in a way where things were being changed by a constant amount every frame instead of a variable amount based on the time that has passed.
So to avoid this problem, you move all your sprites each frame by numbers that are multiples of deltaTime. That'll give you the sense of consistent speed regardless of the speed of the machine/environment.
Now if you want an adjustable game speed on top of that where you want to allow users to deliberately make the game faster, then you introduce a second variable on top of deltaTime that you also multiply by, like gameSpeed. So your sprites should move in Update by a multiple of both deltaTime and gameSpeed.

A: I wont give you code, cause I'm positive that you will be able to fix this with a proper description, but I will gladly explain how to move your sprite without frame rate dependency.
As you said, you already pass a delta-time in to the function.
The delta time is the time that it took between now and the last time the function was called (a frame).
When you move your sprite, you probably move it by a specific number of pixels, instead of doing this every frame, you should multiply the pixel range with the delta time.
This will make into a quite simple formula:
DetlaTime * TheNumberOfPixelsToMoveInASecond.
If you mul it with 10, then the sprite will move 10 pixels in one second. Mul it with 100, it will move 100 pixels in one second.


text:
Q: remove facebook referrer via tag manager I want to solve the common facebook referrer issue with google analytics.
The problem is that when someone logs in from facebook login the source / medium attribute in google analytics is set to facebook / referral due to facebook.com document.referrer.
I have implemented a custom javascript function named JS referral excluder in tag manager like this:
function() {

var hname = {{Referrer}};
console.log('referrer value: ' + hname);

if (hname) {
    if (hname.indexOf('facebook') > -1 && window.location.href.indexOf('via=facebook') > -1 ){
        console.log('return null referrer');
        return null;
     }
}

console.log('nothing found, return referrer');
return {{Referrer}};

}

So according to above code when referrer is facebook and current page contains via=facebook string then do not return referrer.
After i added this variable to default referrer variable in tag manager as shown below

But analytics is still recording facebook.com as referral.
Any ideas?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python web scraper not getting certain values I'm having trouble with my web scraper not getting the "Odds" values and not sure what is wrong. For each piece of information, I am using a try/except to see if the element is available. I'm not sure what is wrong with getting the Odds values though. Thanks for the help
import pandas as pd
import requests
from bs4 import BeautifulSoup
import re

url = 'https://www.ncaagamesim.com/college-basketball-predictions.asp'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

table = soup.find('table')

# Get column names
headers = table.find_all('th')
cols = [x.text for x in headers]

# Get all rows in table body
table_rows = table.find_all('tr')

rows = []
# Grab the text of each td, and put into a rows list
for each in table_rows[1:]:
    odd_avail = True
    data = each.find_all('td')
    time = data[0].text.strip()

    # Get matchup and odds
    try:
        matchup, odds = data[1].text.strip().split('\xa0')
        odd_margin = float(odds.split('by')[-1].strip())
    except:
        matchup = data[1].text.strip()
        odd_margin = '-'
        odd_avail = False

    # Get favored team
    try:
        odd_team_win = data[1].find_all('img')[-1]['title']
    except:
        odd_team_win = '-'
        odd_avail = False

    # Get simulation winner
    try:
        sim_team_win = data[2].find('img')['title']
    except:
        sim_team_win = '-'
        odd_avail = False

    awayTeam = matchup.split('@')[0].strip()
    homeTeam = matchup.split('@')[1].strip()

    # Get simulation margin
    try:
        sim_margin = float(re.findall("\d+\.\d+", data[2].text)[-1])
    except:
        sim_margin = '-'
        odd_avail = False

    # If all variables available, determine odds, simulation margin points, and optimal bet
    if odd_avail == True:
        if odd_team_win == sim_team_win:
            diff = abs(sim_margin - odd_margin)
            if sim_margin > odd_margin:
                bet = odd_team_win
            else:
                if odd_team_win == homeTeam:
                    bet = awayTeam
                else:
                    bet = homeTeam
        else:
            diff = odd_margin + sim_margin
            bet = sim_team_win
    else:
        diff = -1
        bet = '-'

    # Create table
    row = {cols[0]: time, 'Matchup': matchup, 'Odds Winner': odd_team_win, 'Odds': odd_margin,
           'Simulation Winner': sim_team_win, 'Simulation Margin': sim_margin, 'Diff': diff, 'Bet' : bet}
    rows.append(row)

df = pd.DataFrame(rows)
df = df.sort_values(by = ['Diff'], ascending = False)
print (df.to_string())
# df.to_csv('odds.csv', index=False)

When I run this code everything works perfectly and gets all other values but all the odds values in the table are '-'.

A: I added a few things into the code, to account for

*

*If the odds are Even (versus if there are no odds

*If a team doesn't have a logo, to still but the team name

As far as the odds not showing. Check the csv file to see if it's there. If it is, might just be a preference you need to change in pycharm (might be just cutting off some of the string)
import pandas as pd
import requests
from bs4 import BeautifulSoup
import re

url = 'https://www.ncaagamesim.com/college-basketball-predictions.asp'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

table = soup.find('table')

# Get column names
headers = table.find_all('th')
cols = [x.text for x in headers]

# Get all rows in table body
table_rows = table.find_all('tr')

rows = []
# Grab the text of each td, and put into a rows list
for each in table_rows[1:]:
    odd_avail = True
    data = each.find_all('td')
    time = data[0].text.strip()

    # Get matchup and odds
    try:
        matchup, odds = data[1].text.strip().split('\xa0')
        odd_margin = float(odds.split('by')[-1].strip())
    except:
        matchup = data[1].text.strip()
        if 'Even' in matchup:
            matchup, odds = data[1].text.strip().split('\xa0')
            odd_margin = 0
        else:
            odd_margin = '-'
            odd_avail = False

    awayTeam = matchup.split('@')[0].strip()
    homeTeam = matchup.split('@')[1].strip()

    # Get favored team
    try:
        odd_team_win = data[1].find_all('img')[-1]['title']
    except:
        odd_team_win = '-'
        odd_avail = False

    # Get simulation winner
    try:
        sim_team_win = data[2].find('img')['title']
    except:
        if 'wins' in data[2].text:
            sim_team_win = data[2].text.split('wins')[0].strip()
        else:
            sim_team_win = '-'
            odd_avail = False

    # Get simulation margin
    try:
        sim_margin = float(re.findall("\d+\.\d+", data[2].text)[-1])
    except:
        sim_margin = '-'
        odd_avail = False

    # If all variables available, determine odds and simulation margin points
    if odd_avail == True:
        if odd_team_win == sim_team_win:
            diff = abs(sim_margin - odd_margin)
        else:
            diff = odd_margin + sim_margin
    else:
        diff = '-'

    # Create table
    row = {cols[0]: time, 'Away Team': awayTeam, 'Home Team':homeTeam, 'Odds Winner': odd_team_win, 'Odds': odd_margin,
           'Simulation Winner': sim_team_win, 'Simulation Margin': sim_margin, 'Diff': diff}
    rows.append(row)

df = pd.DataFrame(rows)
print (df.to_string())
# df.to_csv('odds.csv', index=False)


text:
Q: Custom Sort in XamDataGrid for multibinding I have a multiBinding which works great,
I want to be able to sort a certain column, it displays w:width, h:heightAs far as I understand I need to build a custom IComparer class which will to the comparison.

Here is my XAML
<igWPF:UnboundField Label="Output
Width/Height" Width="auto">
  <igWPF:Field.Settings>
    <igWPF:FieldSettings SortComparer="{StaticResource SortWidthHeightComparer }">
      <igWPF:FieldSettings.CellValuePresenterStyle>
        <Style TargetType="{x:Type igWPF:CellValuePresenter}">
         <Setter Property="Template">
          <Setter.Value>
           <ControlTemplate TargetType="{x:Type igWPF:CellValuePresenter}" >
            <TextBlock Margin="3">
             <TextBlock.Text>
              <MultiBinding Converter="{StaticResource settingsBdsToStringConverter}">
               <Binding Path="DataItem.Key"/>
               <Binding Path="DataContext.SelectedPipeMode" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type igWPF:XamDataGrid}}"/>
              </MultiBinding>
             </TextBlock.Text>
            </TextBlock>
           </ControlTemplate>
          </Setter.Value>
         </Setter>
        </Style>
       </igWPF:FieldSettings.CellValuePresenterStyle>
      </igWPF:FieldSettings>
     </igWPF:Field.Settings>
   </igWPF:UnboundField>

Here is my multibinding converter
class SettingsOutputResToStringConverter : IMultiValueConverter
    {

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values[1] is Mode && values[0] is ConfigurationKey)
            {
                var pMode = (Mode)values[1];
                var key = values[0] as ConfigurationKey;
                var res = key.GetOutput(pMode);
                return String.Format("W: {0}, H: {1}", res.Width, res.Height);
            }
            return String.Empty;
        }
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

However my problem is how to I pass the multibind result into the Comparer class
class SortWidthHeightComparer : IComparer
    {
        public int Compare(object x, object y)
        {
            return 1;
        }
    }

object x and object y , are always null

A: Gilad,
I found this post:
http://www.infragistics.com/community/forums/t/17878.aspx
It seems like a simple solution.
I'm going to try the same approach for filtering records.


text:
Q: Sharing OneNote Notebook through API As per the link to "Create sharing links on OneNote entities", it appears the OneNote API only supports sectionGroups.
POST ../sectiongroups/{sectiongroup-id}/Microsoft.OneNote.Api.GetOrCreateAnonymousSharingLink

It however seems possible to create a link to a notebook (or section) with the OneDrive API
POST ../sites/{site-id}/drive/items/{item-id}/createLink

Is there a problem with using the API this way (particularly as my notebooks don't have section groups)?


text:
Q: Core Audio (iOS 5.1) Reverb2 properties do not exist, error code -10877 I am playing with Apple's sample project "LoadPresetDemo". I have added the reverb audio unit AudioUnit kAudioUnitSubType_Reverb2 to the graph, which is the only iOS reverb available. In the CoreAudio header file "AudioUnitParameters.h", it states that Reverb2 should respond to these parameters:
enum {
    // Global, CrossFade, 0->100, 100
    kReverb2Param_DryWetMix = 0,
    // Global, Decibels, -20->20, 0
    kReverb2Param_Gain = 1,
    // Global, Secs, 0.0001->1.0, 0.008
    kReverb2Param_MinDelayTime = 2,
    // Global, Secs, 0.0001->1.0, 0.050
    kReverb2Param_MaxDelayTime = 3,
    // Global, Secs, 0.001->20.0, 1.0
    kReverb2Param_DecayTimeAt0Hz = 4,
    // Global, Secs, 0.001->20.0, 0.5
    kReverb2Param_DecayTimeAtNyquist = 5,
    // Global, Integer, 1->1000
    kReverb2Param_RandomizeReflections = 6,
};

After the AUGraph has been initialized and started, everything compiles, I hear sound.
Next, I alter the kReverb2Param_DryWetMix parameter (changing to full wet mix):
AudioUnitSetParameter(_reverbUnit, kAudioUnitScope_Global, 0, kReverb2Param_DryWetMix, 100.0f, 0);

All good, I hear sound with full wet mixed reverb.
Now hear is where I run into issues. When trying to alter any parameter other than kReverb2Param_DryWetMix I get error code -10877. It seems as if these other parameters listed in the header file do not actually exist.
For example, calling
AudioUnitSetParameter(_reverbUnit, kAudioUnitScope_Global, 0, kReverb2Param_DecayTimeAtNyquist, 20.0f, 0)

Throws the -10877 error.
Is this a bug? Have I omitted any audio frameworks? Have I not imported specific audio headers?
The current audio frameworks included are AVFoundation and AudioToolbox.
The current audio imports are
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>

I have scoured google with no solution. I know I have problems when the Google route fails. Any help would be greatly appreciated.
Note: I tested with simulator and iPhone 4S device, same problem.
UPDATE: I have tried
AudioUnitGetParameter(_reverbUnit, kReverb2Param_DecayTimeAtNyquist, kAudioUnitScope_Global, 0, &value)

and it returns a value of 0.500000, which means the property does exist. So what am I doing wrong in setting the value?

A: Doh! I realize that I was confusing AudioUnitSetParameter with AudioUnitSetProperty, including their parameters. Man, subtle but evil.


text:
Q: YouTube video goes over sidebar On a page I have embedded a video. On Ipad and also when you resize the browser window (look at the screenshot below), video goes over the sidebar.
It should regard some responsive issue.
Do you how to resolve it? Thanks

A: Yes, there are issues with responsiveness.
Add your video in a div with class yt-video. For example.
<div class="yt-video">
  <iframe width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen" src="https://www.youtube.com/embed/602q_GYXOWA?rel=0">
</div>

And add this CSS in your style.css file.
div.yt-video {
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
    max-width: 100%;
    height: auto;
}

div.yt-video iframe, div.yt-video object, div.yt-video embed{
    position: absolute;
    top: 0;
    left: 0;
    width: 100% !important;
    height: 100% !important;
}

It will make your video responsive. But make sure you always add video inside a div element with class yt-video.
EDIT
This will be your style.css
@charset "utf-8";
/* CSS Document */

@font-face {
font-family: 'ProximaNova-Regular';
src: url('../font/proximanovaregular.eot');
src: url('../font/proximanovaregular.eot?#iefix') format('embedded-opentype'),
url('../font/proximanovaregular.woff') format('woff'),
url('../font/proximanovaregular.ttf') format('truetype'),
url('../font/proximanovaregular.svg#proximanovaregular') format('svg');
font-weight: normal;
font-style: normal;
}

@font-face {
font-family: 'ProximaNova-Bold';
src: url('../font/proximanovabold.eot');
src: url('../font/proximanovabold.eot?#iefix') format('embedded-opentype'),
url('../font/proximanovabold.woff') format('woff'),
url('../font/proximanovabold.ttf') format('truetype'),
url('../font/proximanovabold.svg#proximanovabold') format('svg');
font-weight: normal;
font-style: normal;
}

@font-face {
font-family: 'ProximaNova-Semibold';
src: url('../font/proximanovasemibold.eot');
src: url('../font/proximanovasemibold.eot?#iefix') format('embedded-opentype'),
url('../font/proximanovasemibold.woff') format('woff'),
url('../font/proximanovasemibold.ttf') format('truetype'),
url('../font/proximanovasemibold.svg#proximanovasemibold') format('svg');
font-weight: normal;
font-style: normal;
}

@font-face {
font-family: 'MyriadPro-Regular';
src: url('../font/myriadproregular.eot');
src: url('../font/myriadproregular.eot?#iefix') format('embedded-opentype'),
url('../font/myriadproregular.woff') format('woff'),
url('../font/myriadproregular.ttf') format('truetype'),
url('../font/myriadproregular.svg#myriadproregular') format('svg');
font-weight: normal;
font-style: normal;
}

.header{
margin:0 -20px;
padding:15px 20px 0;
border-top:5px solid #a2dbd8;
background-color: #355f7d;
*background-color: #355f7d;
background-image: -moz-linear-gradient(top, #428999, #355f7d);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#428999), to(#355f7d));
background-image: -webkit-linear-gradient(top, #ffffff, #355f7d);
background-image: -o-linear-gradient(top, #428999, #355f7d);
background-image: linear-gradient(to bottom, #428999, #355f7d);
background-repeat: repeat-x;
}

.logo{ color:#fff;}
.logo h2{font-family:'ProximaNova-Bold'; font-size:26px; font-weight:normal; margin:0; padding:10px 0 0 0; line-height:28px;}
.logo h5{font-family:'ProximaNova-Regular'; font-size:16px; font-weight:normal; margin:0; padding:0; line-height:16px;}
.logo a{ color:#fff; text-decoration:none;}
.logo a:hover{ color:#fff; text-decoration:none;}

.phn{ color:#fff; font-size:16px; padding:23px 0 0 0;}
.phn i{ margin:0 4px;}
.phn span{font-family:'ProximaNova-Bold'; font-size:21px;}

.navigation{ margin:0; padding:0;
background-color: #d3e1f1;
*background-color: #d3e1f1;
background-image: -moz-linear-gradient(top, #ffffff, #d3e1f1);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#d3e1f1));
background-image: -webkit-linear-gradient(top, #ffffff, #d3e1f1);
background-image: -o-linear-gradient(top, #ffffff, #d3e1f1);
background-image: linear-gradient(to bottom, #ffffff, #d3e1f1);
background-repeat: repeat-x;
border:1px solid #fff;
margin:15px 0 0 0;
 -webkit-border-radius: 6px 6px 0 0;
 -moz-border-radius:6px 6px 0 0;
border-radius:6px 6px 0 0;
}

.body-container{ margin:0 -20px; padding:0 20px; background:url(../img/background.jpg) no-repeat top center;}
.banner{ margin:0; padding:0; border-bottom:5px solid #ccc; background:#38617f;}
.banner .carousel-caption{ padding-bottom:30px; padding-right:15px; padding-left:0}
.banner .carousel-caption h4{ color:#80dbe0; font-size:24px; font-weight:normal; font-family:'ProximaNova-Bold';}
.banner .carousel-caption h2{ color:#fff; font-size:40px; font-weight:normal; font-family:'ProximaNova-Bold';}

.body-wrap{ margin:0; padding:15px;
background-color: #f4f4f4;
  *background-color: #f4f4f4;
  background-image: -moz-linear-gradient(top, #ffffff, #f4f4f4);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f4f4f4));
  background-image: -webkit-linear-gradient(top, #ffffff, #f4f4f4);
  background-image: -o-linear-gradient(top, #ffffff, #f4f4f4);
  background-image: linear-gradient(to bottom, #ffffff, #f4f4f4);
  background-repeat: repeat-x;
}
.block{}
.block h5{ color:#355f7d; font-size:16px; font-weight:normal; font-family:'ProximaNova-Bold';}
.block h4{ color:#355f7d; font-size:21px; font-weight:normal; font-family:'ProximaNova-Bold';}
.block ul{ margin:0; padding:0 0 0 15px;}
.block ul li{ margin:0; padding:0; list-style:disc;}

.right-col{ margin-top:40px;}
.right-col-inner{}
.right-col-inner h4.maptitle{ color:#0270c4; font-size:16px; font-weight:normal; font-family:'ProximaNova-Bold'; margin-top:20px;}

.contentmanage h2{ margin:0; padding:0;  font-weight:normal; font-family:'ProximaNova-Bold'; color:#38617f; font-size:23px;}
.contentmanage h4{ margin:0; padding:0;  font-weight:normal; font-family:'ProximaNova-Bold'; color:#38617f; font-size:19px;}
.contentmanage p span{ font-family:'ProximaNova-Bold'; color:#38617f;}
.contentmanage p{ margin:0; padding:15px 0 0 0;}
.contentmanage ul.list-text{ margin:0; padding:15px 0 0 20px; font-family:'ProximaNova-Bold'; color:#38617f; font-size:16px;}
.contentmanage ul{ margin:0; padding:15px 0 0 20px;}

.Flexible-container {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 30px;
    height: 0;
    overflow: hidden;
  margin:10px 0 0 0;
}

.Flexible-container iframe,
.Flexible-container object,
.Flexible-container embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

.innertop-box{ margin:0 0 20px 0; padding:0;}
.innertop-box .img{  -webkit-border-radius:10px 10px 0 0;
 -moz-border-radius:10px 10px 0 0;
border-radius:10px 10px 0 0;}

.innertop-box .info{ margin:0; padding:15px; color:#fff;
background-color: #71bcbf;
  *background-color: #71bcbf;
  background-image: -moz-linear-gradient(top, #90d2d2, #71bcbf);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#71bcbf));
  background-image: -webkit-linear-gradient(top, #90d2d2, #71bcbf);
  background-image: -o-linear-gradient(top, #90d2d2, #71bcbf);
  background-image: linear-gradient(to bottom, #90d2d2, #71bcbf);
  background-repeat: repeat-x;

 -webkit-border-radius:0 0 10px 10px;
 -moz-border-radius:0 0 10px 10px;
border-radius:0 0 10px 10px;}
.innertop-box .info h3{ margin:0; padding:0; font-size:21px; line-height:30px; font-family:'ProximaNova-Bold'; font-weight:normal;}

.timetable{ margin:0; padding:0; background:url(../img/pattern.jpg);  -webkit-border-radius:6px;
 -moz-border-radius:6px;
border-radius:6px;}
.timeblock{ margin:0; padding:15px; background:url(../img/watchbg.png) no-repeat right top; font-family:'ProximaNova-Bold'; text-transform:uppercase; text-shadow:1px 1px 1px #000; color:#fff; font-size:19px; -webkit-border-radius:6px;
 -moz-border-radius:6px;
border-radius:6px;}

.quoteform{ margin:20px 0; padding:15px; background:#a5e5ef; -webkit-border-radius:10px; -moz-border-radius:10px; border-radius:10px;}
.quoteform h3{ margin:0; padding:0 0 5px 0; font-weight:normal; font-family:'ProximaNova-Regular'; line-height:26px; font-size:21px; color:#3d5b65;}
.quoteform input[type=text]{ color:#43636d;}
.quoteform input[type=submit]{ margin:5px 0 0 0;}
.quoteform form{ margin:0; padding:0;}
.quoteform  label.checkbox{ font-size:11px; co#43636d; line-height:15px;}

div.fb-like-box,
div.fb-like-box > span,
div.fb-like-box > span > iframe[style],
div.fb-comments,
div.fb-comments > span,
div.fb-comments > span > iframe[style] {width: 100% !important;}

@media only screen and (min-width: 992px) and (max-width: 1199px) {
.sub-con {
 background: #ececec none repeat scroll 0 0 !important;
    height: 250px !important;
    margin: 0 12px 0 0 !important;
    padding-top: 10px !important;
}
}

@media (min-width: 768px) and (max-width: 979px) {

.span3 {
    margin: 0 8px 0 0 !important;
}

}

div.yt-video {
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
    max-width: 100%;
    height: auto;
}

div.yt-video iframe, div.yt-video object, div.yt-video embed{
    position: absolute;
    top: 0;
    left: 0;
    width: 100% !important;
    height: 100% !important;
}

A: You just need to add the following to your css:
iframe {
 height:300px;
 max-width:100%;
}

Change the height to your desired height.


text:
Q: filter and merge two arrays with comparison based on two or more columns in dataweave 2.0 I have two big JSON arrays on which I have to filter and merge based on two columns:
mongo.NUM_CONTROL = mysql.DOCNUM
mongo.NUM_ITEM = mysql.LIN_NUM_ITEM

I already made this script on which I used map params (item and key) to do not have to map each column of each json (they have about 50 columns each)
Also, it works for comparing NUM_CONTROL with DOCNUM.
However, I couldn't make it work for NUM_ITEM and LIN_NUM_ITEM.
mongo map (mItems, mKeys) -> using (mongoCtrl = mItems.NUM_CONTROL)
{
    (mysql filter ($.*DOCNUM contains mongoCtrl) map (sItems, sKeys) -> {
        (sItems mapObject (sItem, sKey) ->
            (sKey): sItem
        ),
        (mItems mapObject (mItem, mKey) ->
            (mKey): mItem
        )
    })
}

EDIT: here are some example data
mongo =
[
    {
        "VLR_UNIT": 1581.1,
        "OBSERVACAO": null,
        "COD_NATUREZA_OP": "155",
        "VLR_TRIBUTO_ICMS": 1715.81,
        "ALIQ_ICMS_ORIGEM": 7,
        "VLR_BASE_ISENTA_IPI": 7,
        "COD_CFO": "5171",
        "VLR_TRIBUTO_ICMMST": 7,
        "VLR_BASE_REDUZIDA_IPI": 7,
        "DATA_FISCAL": "1718-78-73T77:77:77",
        "COD_EMPRESA": "TRV",
        "VLR_BASE_TRIBUTADA_ICMSST": 7,
        "VLR_BASE_ISENTA_ICMSST": 7,
        "COD_FEDERAL": "77753",
        "VLR_BASE_OUTRAS_IPI": 57637.4,
        "VLR_BASE_ISENTA_ICMS": 7,
        "VLR_DESONERADO": 7,
        "COD_PRODUTO": "1777776316",
        "RAIZ": "77787381",
        "VLR_ICMSS_N_ESCRIT": 7,
        "IND_SIMPLES_NAC": "S",
        "VLR_ITEM": 57637.4,
        "ALIQ_TRIBUTO_ICMS": 18,
        "QUANTIDADE": 31,
        "DATA_EMISSAO": "1718-78-73T77:77:77",
        "ALIQ_ICMS_DEST": 18,
        "VLR_BASE_OUTRAS_ICMS": 7,
        "NUM_DOCFIS": "777717117",
        "VLR_BASE_REDUZIDA_ICMS": 38375.16,
        "VLR_DESCONTO": 7,
        "VLR_CONTAB_ITEM": 57637.4,
        "VLR_BASE_TRIBUTADA_IPI": 7,
        "CLAS_ITEM": 4,
        "IND_PRODUTO": "1",
        "INSC_SUFRAMA": null,
        "VLR_IPI_NDESTAC": 7,
        "VLR_DIFAL": 7,
        "COD_MEDIDA": "TO",
        "VLR_FRETE": 7,
        "VLR_OUTRAS": 7,
        "COD_SITUACAO_B": "17",
        "COD_SITUACAO_A": "7",
        "VLR_TOT_NOTA": 57637.4,
        "MOVTO_E_S": "8",
        "COD_ESTAB": "7141",
        "NUM_ITEM": 1,
        "VLR_SEGURO": 7,
        "COD_MODELO": "55",
        "COD_NBM": "31758787",
        "COD_MUNICIPIO_ORIG": 6571,
        "VLR_ALIQ_ICMSST": 7,
        "SITUACAO_DOCUMENTO": "NORMAL",
        "VLR_BASE_ICMSS_N_ESCRIT": 7,
        "VLR_TRIBUTO_IPI": 7,
        "NUM_CONTROL": "7771838361",
        "VLR_BASE_OUTRAS_ICMSST": 7,
        "VLR_BASE_TRIBUTADA_ICMS": 11155.14,
        "UF_PLANTA": "BA",
        "VLR_BASE_REDUZIDA_ICMSST": 7,
        "ALIQ_TRIBUTO_IPI": 7,
        "COD_MUNICIPIO_DEST": 31357,
        "SERIE_DOCFIS": "57",
        "DIF_ALIQ_TRIBUTO": 7,
        "VLR_ICMS_NDESTAC": 7
    },
    {
        "VLR_UNIT": 1357,
        "OBSERVACAO": null,
        "COD_NATUREZA_OP": "155",
        "VLR_TRIBUTO_ICMS": 1316.46,
        "ALIQ_ICMS_ORIGEM": 7,
        "VLR_BASE_ISENTA_IPI": 7,
        "COD_CFO": "5171",
        "VLR_TRIBUTO_ICMMST": 7,
        "VLR_BASE_REDUZIDA_IPI": 7,
        "DATA_FISCAL": "1718-78-73T77:77:77",
        "COD_EMPRESA": "TRV",
        "VLR_BASE_TRIBUTADA_ICMSST": 7,
        "VLR_BASE_ISENTA_ICMSST": 7,
        "COD_FEDERAL": "77753",
        "VLR_BASE_OUTRAS_IPI": 31877,
        "VLR_BASE_ISENTA_ICMS": 7,
        "VLR_DESONERADO": 7,
        "COD_PRODUTO": "1777776833",
        "RAIZ": "78714167",
        "VLR_ICMSS_N_ESCRIT": 7,
        "IND_SIMPLES_NAC": "S",
        "VLR_ITEM": 31877,
        "ALIQ_TRIBUTO_ICMS": 18,
        "QUANTIDADE": 14,
        "DATA_EMISSAO": "1718-78-73T77:77:77",
        "ALIQ_ICMS_DEST": 18,
        "VLR_BASE_OUTRAS_ICMS": 7,
        "NUM_DOCFIS": "777717114",
        "VLR_BASE_REDUZIDA_ICMS": 15586.33,
        "VLR_DESCONTO": 7,
        "VLR_CONTAB_ITEM": 31877,
        "VLR_BASE_TRIBUTADA_IPI": 7,
        "CLAS_ITEM": 4,
        "IND_PRODUTO": "1",
        "INSC_SUFRAMA": null,
        "VLR_IPI_NDESTAC": 7,
        "VLR_DIFAL": 7,
        "COD_MEDIDA": "TO",
        "VLR_FRETE": 7,
        "VLR_OUTRAS": 7,
        "COD_SITUACAO_B": "17",
        "COD_SITUACAO_A": "7",
        "VLR_TOT_NOTA": 31877,
        "MOVTO_E_S": "8",
        "COD_ESTAB": "7141",
        "NUM_ITEM": 1,
        "VLR_SEGURO": 7,
        "COD_MODELO": "55",
        "COD_NBM": "31754777",
        "COD_MUNICIPIO_ORIG": 6571,
        "VLR_ALIQ_ICMSST": 7,
        "SITUACAO_DOCUMENTO": "NORMAL",
        "VLR_BASE_ICMSS_N_ESCRIT": 7,
        "VLR_TRIBUTO_IPI": 7,
        "NUM_CONTROL": "7771847474",
        "VLR_BASE_OUTRAS_ICMSST": 7,
        "VLR_BASE_TRIBUTADA_ICMS": 7313.67,
        "UF_PLANTA": "BA",
        "VLR_BASE_REDUZIDA_ICMSST": 7,
        "ALIQ_TRIBUTO_IPI": 7,
        "COD_MUNICIPIO_DEST": 33377,
        "SERIE_DOCFIS": "57",
        "DIF_ALIQ_TRIBUTO": 7,
        "VLR_ICMS_NDESTAC": 7
    }
]

and
mysql =
[
    {
        "DOCNUM": "7771838361",
        "NFTYPE": "Z1",
        "DOCTYP": "1",
        "DIRECT": "1",
        "DOCDAT": "Tue Sep 73 77:77:77 BST 1718",
        "PSTDAT": "Tue Sep 73 77:77:77 BST 1718",
        "MODEL": "55",
        "SERIES": "57",
        "SUBSER": null,
        "CRENAM": "A837335",
        "MANUAL": null,
        "BELNR": null,
        "GJAHR": "7777",
        "BUKRS": "TRV",
        "BRANCH": "7141",
        "PARID": "7717781611",
        "PARVW": "WE",
        "PARTYP": "C",
        "CANCEL": null,
        "COD_SIT": "77",
        "CANDAT": null,
        "NFENUM": "777717117",
        "CRT_BUPLA": "3",
        "CRT_PARTNER": null,
        "DOCREF": "7777777777",
        "NFTOT": "57637.47",
        "OBSERVAT": null,
        "MODFRETE": "1",
        "LIN_ITMNUM": "777747",
        "LIN_NUM_ITEM": "771",
        "LIN_MATNR": "777777771777776316",
        "LIN_MATKL": "57",
        "LIN_CFOP": "5171AA",
        "LIN_NBM": "3175.87.87",
        "LIN_MATORG": "7",
        "LIN_TAXSIT": "1",
        "LIN_TAXSIT1": "77753",
        "LIN_MWSKZ": null,
        "LIN_OWNPRO": "X",
        "LIN_MATUSE": "1",
        "LIN_NETWR": "57637.47",
        "LIN_TAXLW1": "B71",
        "LIN_TAXLW1": "53A",
        "LIN_NDUS3": "77",
        "LIN_WERKS": "SSA3",
        "LIN_NFNET": "57637.47",
        "LIN_NETWRT": "57637.47",
        "LIN_NFNETT": "57637.47",
        "LIN_TAXLW4": "76A",
        "LIN_TAXSI4": "76",
        "LIN_TAXLW5": "76A",
        "LIN_TAXSI5": "76",
        "LIN_XPED": "77871873",
        "LIN_NITEMPED": null,
        "LIN_INDINCENTIVO": "1",
        "LIN_REFKEY": "7787854684",
        "LIN_REFITM": "777747",
        "KNA1_KUNNR": "7717781611",
        "KNA1_REGIO": "BA",
        "KNA1_BRSCH": "7771",
        "KNA1_CRTN": null,
        "KNA1_STCD1": "77787381777177",
        "KNA1_STCD1": null,
        "KNA1_ICMSTAXPAY": "Z4",
        "LFA1_LIFNR": null,
        "LFA1_BRSCH": null,
        "LFA1_CRTN": null,
        "LFA1_ICMSTAXPAY": null,
        "LFA1_STCD1": null,
        "LFA1_STCD1": null,
        "LFA1_KTOKK": null,
        "MARA1_BEHVO": null,
        "MARA1_MTART": null,
        "MARA1_TRAGR": null,
        "MARA_BEHVO": "74",
        "MARA_MTART": "FERT",
        "MARA_TRAGR": "7771",
        "MARA_EXTWG": "71",
        "BKPF_AWKEY": "7787854684",
        "BKPF_BUKRS": "TRV",
        "BKPF_BELNR": "7787186147",
        "BKPF_GJAHR": "1718",
        "J_1BTICMSTAXPAYT_ICMSTAXPAY": null,
        "TWEWT_EXTWG": "71",
        "TWEWT_EWBEZ": "Crop Nutrition 37",
        "T777Y_KTOKK": null,
        "T777Y_TXT37": null,
        "VTTK_TKNUM": null,
        "VTTK_SHTYP": null,
        "TVTKT_BEZEI": "OUT Direct",
        "VTTP_VBELN": "7787885763",
        "LIPS_VBELN": "7787885763",
        "LIPS_MATNR": "777777771777775883",
        "T144T_BEHVO": "74",
        "VLR_BASE_TRIB_ICMS": "11155.14",
        "VLR_BASE_ISENTA_ICMS": "38375.16",
        "VLR_BASE_OUTRA_ICMS": "7.77",
        "VLR_BASE_RED_ICMS": "11.13",
        "ALIQ_TRIBUTO_ICMS": "18.77",
        "VLR_TRIBUTO_ICMS": "1715.81",
        "VLR_ICMS_NDESTAC": "7.77",
        "VLR_BASE_TRIB_ICMSST": "7.77",
        "VLR_TRIBUTO_ICMSST": "7.77",
        "ALIQ_TRIBUTO_DIFAL": "7.77",
        "VLR_DIFAL": "7.77",
        "VLR_BASE_TRIB_IPI": "7.77",
        "VLR_BASE_ISENTA_IPI": "7.77",
        "VLR_BASE_OUTRA_IPI": "57637.47",
        "VLR_BASE_RED_IPI": "7.77",
        "ALIQ_TRIBUTO_IPI": "7.77",
        "VLR_TRIBUTO_IPI": "7.77",
        "VLR_BASE_TRIB_PIS": "57637.47",
        "ALIQ_TRIBUTO_PIS": "7.77",
        "VLR_TRIBUTO_PIS": "7.77",
        "VLR_BASE_TRIB_COFINS": "57637.47",
        "ALIQ_TRIBUTO_COFINS": "7.77",
        "VLR_TRIBUTO_COFINS": "7.77"
    },
    {
        "DOCNUM": "7771847474",
        "NFTYPE": "Z1",
        "DOCTYP": "1",
        "DIRECT": "1",
        "DOCDAT": "Tue Sep 73 77:77:77 BST 1718",
        "PSTDAT": "Tue Sep 73 77:77:77 BST 1718",
        "MODEL": "55",
        "SERIES": "57",
        "SUBSER": null,
        "CRENAM": "A817347",
        "MANUAL": null,
        "BELNR": null,
        "GJAHR": "7777",
        "BUKRS": "TRV",
        "BRANCH": "7141",
        "PARID": "7717771413",
        "PARVW": "WE",
        "PARTYP": "C",
        "CANCEL": null,
        "COD_SIT": "77",
        "CANDAT": null,
        "NFENUM": "777717114",
        "CRT_BUPLA": "3",
        "CRT_PARTNER": null,
        "DOCREF": "7777777777",
        "NFTOT": "31877.77",
        "OBSERVAT": null,
        "MODFRETE": "7",
        "LIN_ITMNUM": "777717",
        "LIN_NUM_ITEM": "771",
        "LIN_MATNR": "777777771777776833",
        "LIN_MATKL": "15",
        "LIN_CFOP": "5171AA",
        "LIN_NBM": "3175.47.77",
        "LIN_MATORG": "7",
        "LIN_TAXSIT": "1",
        "LIN_TAXSIT1": "77753",
        "LIN_MWSKZ": null,
        "LIN_OWNPRO": "X",
        "LIN_MATUSE": "1",
        "LIN_NETWR": "31877.77",
        "LIN_TAXLW1": "B71",
        "LIN_TAXLW1": "53A",
        "LIN_NDUS3": "77",
        "LIN_WERKS": "SSA3",
        "LIN_NFNET": "31877.77",
        "LIN_NETWRT": "31877.77",
        "LIN_NFNETT": "31877.77",
        "LIN_TAXLW4": "76A",
        "LIN_TAXSI4": "76",
        "LIN_TAXLW5": "76A",
        "LIN_TAXSI5": "76",
        "LIN_XPED": "77814838",
        "LIN_NITEMPED": null,
        "LIN_INDINCENTIVO": "1",
        "LIN_REFKEY": "7787855161",
        "LIN_REFITM": "777717",
        "KNA1_KUNNR": null,
        "KNA1_REGIO": null,
        "KNA1_BRSCH": null,
        "KNA1_CRTN": null,
        "KNA1_STCD1": null,
        "KNA1_STCD1": null,
        "KNA1_ICMSTAXPAY": null,
        "LFA1_LIFNR": null,
        "LFA1_BRSCH": "7771",
        "LFA1_CRTN": null,
        "LFA1_ICMSTAXPAY": null,
        "LFA1_STCD1": "73741845777118",
        "LFA1_STCD1": null,
        "LFA1_KTOKK": "FPJU",
        "MARA1_BEHVO": null,
        "MARA1_MTART": null,
        "MARA1_TRAGR": null,
        "MARA_BEHVO": "74",
        "MARA_MTART": "FERT",
        "MARA_TRAGR": "7771",
        "MARA_EXTWG": "71",
        "BKPF_AWKEY": "7787855161",
        "BKPF_BUKRS": "TRV",
        "BKPF_BELNR": "7787186488",
        "BKPF_GJAHR": "1718",
        "J_1BTICMSTAXPAYT_ICMSTAXPAY": null,
        "TWEWT_EXTWG": "71",
        "TWEWT_EWBEZ": "Crop Nutrition 37",
        "T777Y_KTOKK": "FPJU",
        "T777Y_TXT37": "PJ Vendors",
        "VTTK_TKNUM": null,
        "VTTK_SHTYP": null,
        "TVTKT_BEZEI": "OUT Direct",
        "VTTP_VBELN": "7787885763",
        "LIPS_VBELN": "7787885763",
        "LIPS_MATNR": "777777771777775883",
        "T144T_BEHVO": "74",
        "VLR_BASE_TRIB_ICMS": "7313.67",
        "VLR_BASE_ISENTA_ICMS": "15586.33",
        "VLR_BASE_OUTRA_ICMS": "7.77",
        "VLR_BASE_RED_ICMS": "11.13",
        "ALIQ_TRIBUTO_ICMS": "18.77",
        "VLR_TRIBUTO_ICMS": "1316.46",
        "VLR_ICMS_NDESTAC": "7.77",
        "VLR_BASE_TRIB_ICMSST": "7.77",
        "VLR_TRIBUTO_ICMSST": "7.77",
        "ALIQ_TRIBUTO_DIFAL": "7.77",
        "VLR_DIFAL": "7.77",
        "VLR_BASE_TRIB_IPI": "7.77",
        "VLR_BASE_ISENTA_IPI": "7.77",
        "VLR_BASE_OUTRA_IPI": "31877.77",
        "VLR_BASE_RED_IPI": "7.77",
        "ALIQ_TRIBUTO_IPI": "7.77",
        "VLR_TRIBUTO_IPI": "7.77",
        "VLR_BASE_TRIB_PIS": "31877.77",
        "ALIQ_TRIBUTO_PIS": "7.77",
        "VLR_TRIBUTO_PIS": "7.77",
        "VLR_BASE_TRIB_COFINS": "31877.77",
        "ALIQ_TRIBUTO_COFINS": "7.77",
        "VLR_TRIBUTO_COFINS": "7.77"
    }
]

The expected output must have these two JSON arrays merged based on previous conditions

A: Try with this.
mongo map (mItems, mKeys) ->
{
    (mysql filter (($.DOCNUM ==  mItems.NUM_CONTROL) and  ($.LIN_NUM_ITEM as Number == mItems.NUM_ITEM)) map (sItems, sKeys) -> {
        (sItems mapObject (sItem, sKey) ->
            (sKey): sItem
        ),
        (mItems mapObject (mItem, mKey) ->
            (mKey): mItem
        )
    })
}

A: Use the following dataweave expression:
%dw 2.0
output application/json
---
flatten(mongo map (mItem, mKey) ->
    (mysql filter ($.DOCNUM ==  mItem.NUM_CONTROL) and ($.LIN_NUM_ITEM as Number == mItem.NUM_ITEM)) map (sItem, sKey) ->
        mItem ++ sItem)


text:
Q: 2D packing with obstacles Anybody know of an efficient algorithm for moving rectangles in a square which contains obstacles?
Rectangles:

*

*can rotate

*can move/teleport

*must not collide with obstacles (black squares)

Obstacles:

*

*can't be moved

*can be added anywhere

Goal: when obstacle is added, try to move rectangles so that they don't collide with any of obstacles.

A: Take a look at this: Dynamic programming - Largest square block
Basically, given the rectangles, you add an obstacle, and remove the square that the obstacle interferes with.
Then, run the linked algorithm(with the "limiters" being the obstacles and existing squares), and if a place was found that can fit a square of NxN size (N is the large part of the rectangle), and add the rectangle).
This can be optimized a bit further, and I entrust you with doing so. (Basically - the rectangles won't always be put in the most optimal place. This can be remedied, at least to some degree)
This solution will give you O(n) time and space for each obstacle added.
Possible modification you should also look into: Don't rebuild the array for each obstacle, but build it for the void-of-obstacles array, and modify it as you go along. This will save going through the entire array for every single obstacle.


text:
Q: Can i upload a AMPL file to Wolfram Alpha and let it solve it? I have a AMPL code and i need an web-based solver that return me results in a JSON/XML format. Can i do this with Wolfram Alpha API?

A: The NEOS Server has an XML-based API for accessing AMPL and various AMPL-interfaced solvers over the web. I don't know of any ready-made AMPL hook to Wolfram Alpha, however, though I would be happy to learn of one.


text:
Q: ERROR: (gcloud.compute.ssh) Could not fetch resource: - The resource was not found I'm trying to run R on Google Cloud following Google's suggested tutorial. However, I have experienced some trouble when finally creating the cluster. When creating the cluster with
elasticluster start myslurmcluster

I get the following error message
ERROR: (gcloud.compute.ssh) Could not fetch resource:
 - The resource 'projects/MY_PROJECT/zones/us-central1-b/instances/myslurmcluster-frontend001' was not found
I had run through previous stages of the tutorial several times with no problems but I suspect the issue might be related to the SSH keys so that I can sign in to my cluster.
Any help or advice greatly received!

A: ERROR: (gcloud.compute.ssh) Could not fetch resource:
 - The resource 'projects/MY_PROJECT/zones/us-central1-b/instances/myslurmcluster-frontend001' was not found

The error you are getting means that when you are trying to compute SSH, your resource was not found. The reason for this case is the instance zone and gcloud default zone are different. The command line didn't specified the instance zone. So the google cloud compute default zone was used. Obviously, The instance should not be found in the default zone. Just adding the zone option in command could solve the problem. The command format is like:

gcloud compute --project "MY_PROJECT" ssh --zone "us-central1-b" "myslurmcluster-frontend001"

To see what your default region and zone settings are, run the following gcloud command:
gcloud compute project-info describe --project [PROJECT_ID]

where [PROJECT_ID] is your own project ID.

A: Hope this helps... Easy way to find out instance zones without having to type/know instance name.
gcloud compute instances list

Should list instances and information - including (time)ZONE.


text:
Q: Can clang-format be instructed to maintain newlines in a function call parameter list? For example, in Go, the following is a correctly go-fmt'ed code
func main() {
    fmt.Println("Hello World",
        "some",
        "more", "args", "s",
        "Bye World")
}

I am able to have groups of parameters share a line and go-fmt will not second-guess me. This is IMO sensible when some parameters are related to each other and I can express that by having them share a line in the call.
On the other hand, clang-format insists either on bin-packing the parameter list, or placing every parameter on its own line, with no middle ground.
    Println("Hello World", "some", "more", "args", "s", "Bye World")

or
    Println("Hello World",
            "some",
            "more",
            "args",
            "s",
            "Bye World")

Is this how it is, or can clang-format be instructed to behave the go-fmt way in regards to these "preformatted" parameter lists?
My question is quite similar to stop clang format from breaking lines, except I believe I am expressing the specific goal here: preserve line breaks in the original parameter list (as long as it does not conflict with line length limits, etc).


text:
Q: Screenscraping a Datepicker with Scrapy + Selenium So i need to scrap a page like this for example or this and i am using Scrapy + Seleninum to interact with a datepicker calendar.
Basically i need to check for the availabilities of the rooms for each day in a month for example, so my idea was trying to click the not disabled links/dates on the datepicker and check if an error message appears or not for me to know if its available or not.
I have no idea if this is the proper way or even how to do this with this tools. I have been playing around with them but still looks like i am far from a final solution.
Does anyone know how i can tackle this or even provide the code for me to achieve this?

A: Hi please find the answer below
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://www.airbnb.pt/rooms/516301?check_in=2016-04-14&guests=1&check_out=2016-04-17");

// selecting firstdate picker -- check in

driver.findElement(By.xpath("//*[@class='col-sm-6']/input")).click();
// note calendar is not completely visible hence to make it visible
// scroll a little bit down
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,200)");
// take all calendar dates inside the list
// here i have update my code to skip stale element exception
List<WebElement> alldates = driver.findElements(By.xpath("//*[@class='ui-datepicker-calendar']/tbody/tr/td/a[contains(@class, 'ui-state-default')]"));
System.out.println("Size is : "+ alldates.size());
// suppose you want to select 27 form the all dates
// keeping it as a parameter
String dateToBeSelected = "19";  // check in
for(int i=0;i<alldates.size();i++){
    alldates = driver.findElements(By.xpath("//*[@class='ui-state-default']"));
System.out.println("dates is : " + alldates.get(i).getText());
// selects a check-in date
if( alldates.get(i).getText().equals(dateToBeSelected)){
    alldates.get(i).click();
    break;
            }
        }
// on selection of Checkin date check out calender automatically pop ups
System.out.println("--------------------------");
String datetobeselected = "27";
for(int i=0;i<alldates.size();i++){
    alldates = driver.findElements(By.xpath("//*[@class='ui-state-default']"));
System.out.println("dates is : " + alldates.get(i).getText());
// selects a check-in date
if( alldates.get(i).getText().equals(datetobeselected)){
    alldates.get(i).click();
    break;
            }
        }
// actually after calendar selection whatever text is shown in red color
// i am not sure what is it (sorry only English)

// identify the text with red color is present or not
boolean errorMsg = driver.findElement(By.xpath("//*[@class='panel-body panel-light']/div[2]/p")).isDisplayed();
if(errorMsg){
    System.out.println("error msg is displayed");
}else{
System.out.println("error msg is not - displayed");
        }

Hope this helps you also note this above example takes check-in and checkout date as parameter if you want code to take non disabled date automatically please feel free to ask i will update my answer.


text:
Q: Ubuntu Server cannot boot - HDD problems I have major problem, my Ubuntu Server won't start up after reboot, guys in Hetzner datacenter started recsue sistem up and found out this on sda:
-----------------%<-----------------
5 Reallocated_Sector_Ct   0x0033   001   001   036    Pre-fail  Always
FAILING_NOW 4095
-----------------%<-----------------

There are 3 x 1.5TB HDDs in RAID5 and on sda there was boot loader.
They insisted to replace sda with new HDD, so I confirmed.
After that they mailed me back with another thing, sdc is also corrupted...
Until 7:30 this morning everything worked fine. After that server has been frozen, and after reboot two HDD-s are corrupted... little bit weird, but no time to think about that.
They returned corrupted sda back, so "that I can restore some data..." but the problem is I was stuck.
I tried to mount sdb while in live-rescue-system and to install grub, but there is this error:
root@rescue ~ # grub-install /dev/sdb
/usr/sbin/grub-probe: error: cannot find a device for /boot/grub (is
/dev mounted?).
root@rescue ~ # mkdir /media/sdb
root@rescue ~ # mount /dev/sdb /media/sdb
mount: you must specify the filesystem type
root@rescue ~ # mount /dev/sdb /media/sdb -t auto
mount: you must specify the filesystem type
root@rescue ~ # mount /dev/sdb /media/sdb -t ext3
mount: wrong fs type, bad option, bad superblock on /dev/sdb,
         missing codepage or helper program, or other error
         In some cases useful info is found in syslog - try
         dmesg | tail  or so

Can someone please help me to try and start Ubuntu server or to somehow restore data from any of disks...
Extra info:
root@rescue ~ # ll /dev/sd
brw-rw---T 1 root disk 8,  0 Nov 18 14:04 /dev/sda
brw-rw---T 1 root disk 8,  1 Nov 18 14:06 /dev/sda1
brw-rw---T 1 root disk 8,  2 Nov 18 14:06 /dev/sda2
brw-rw---T 1 root disk 8, 16 Nov 18 14:04 /dev/sdb
brw-rw---T 1 root disk 8, 17 Nov 18 14:04 /dev/sdb1
brw-rw---T 1 root disk 8, 18 Nov 18 14:04 /dev/sdb2
brw-rw---T 1 root disk 8, 32 Nov 18 14:06 /dev/sdc

root@rescue ~ # df -h
Filesystem          Size  Used Avail Use% Mounted on
rootfs               12G  3.0M   12G   1% /
udev                 12G     0   12G   0% /dev
188.40.24.212:/nfs  1.4T  592G  722G  46% /root/.oldroot/nfs
aufs                 12G  3.0M   12G   1% /
tmpfs               2.4G  264K  2.4G   1% /run
tmpfs               5.0M     0  5.0M   0% /run/lock
tmpfs               4.8G     0  4.8G   0% /run/shm

root@rescue ~ # ll /dev/loo*
brw-rw---T 1 root disk  7,   0 Nov 18 14:04 /dev/loop0
brw-rw---T 1 root disk  7,   1 Nov 18 14:04 /dev/loop1
brw-rw---T 1 root disk  7,   2 Nov 18 14:04 /dev/loop2
brw-rw---T 1 root disk  7,   3 Nov 18 14:04 /dev/loop3
brw-rw---T 1 root disk  7,   4 Nov 18 14:04 /dev/loop4
brw-rw---T 1 root disk  7,   5 Nov 18 14:04 /dev/loop5
brw-rw---T 1 root disk  7,   6 Nov 18 14:04 /dev/loop6
brw-rw---T 1 root disk  7,   7 Nov 18 14:04 /dev/loop7
crw------T 1 root root 10, 237 Nov 18 14:04 /dev/loop-control

root@rescue ~ # fdisk -l

Disk /dev/sdb: 1500.3 GB, 1500301910016 bytes
255 heads, 63 sectors/track, 182401 cylinders, total 2930277168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000cdbda

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            3906     1060289      528192   fd  Linux raid autodetect
/dev/sdb2         1060290  2930272064  1464605887+  fd  Linux raid autodetect

Disk /dev/sda: 1500.3 GB, 1500301910016 bytes
255 heads, 63 sectors/track, 182401 cylinders, total 2930277168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000c5b77

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1            3906     1060289      528192   fd  Linux raid autodetect
/dev/sda2         1060290  2930272064  1464605887+  fd  Linux raid autodetect

Disk /dev/md0: 540 MB, 540803072 bytes
2 heads, 4 sectors/track, 132032 cylinders, total 1056256 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/md0 doesn't contain a valid partition table
root@rescue ~ # cat /proc/mdstat
Personalities : [raid1]
md1 : inactive sda2[0](S)
      1464605760 blocks

md0 : active raid1 sda1[0]
      528128 blocks [3/1] [U__]

unused devices: <none>

A: You can only mount partitions, not entire devices. A device – usually named sdx if it's a SATA drive – can hold several partitions – named after the device they are on with an added number, like sdx1 for the first partition on sdx.
In your case, try mount /dev/sdb1 /media/partition1 and mount /dev/sdb2 /media/partition2, obviously after creating those two directories.


text:
Q: How do I get a Donut Chart in R? I try to draw a Donut Chart with a tutorial code but I get an error I cannot explain.

library(ggplot2)
library(dplyr)

Calculate and cumulate percentages
df$fraction = df$freq / sum(df$freq)
df$ymax = cumsum(df$fraction)
df$ymin = c(0, head(df$ymax, n=-1))

Draw chart
ggplot(df, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) +
  geom_rect() +
  coord_polar(theta="y") +
  xlim(c(2, 4))

I get this error:

Error in geom_rect():
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in FUN():
! object 'category' not found
Run rlang::last_error() to see where the error occurred.

A: You need to change fill=category to fill=word, then it works:
df <- data.frame (word  = c("dolor", "amet", "diam", "ipsum", "lorem", "sed", "sit", "accusam", "aliquyam", "clita"),freq = c(48,24,24,24,24,24,24,12,12,12))

library(ggplot2)
library(dplyr)

df$fraction = df$freq / sum(df$freq)
df$ymax = cumsum(df$fraction)
df$ymin = c(0, head(df$ymax, n=-1))

ggplot(df, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3,
fill=word)) +
geom_rect() +
coord_polar(theta="y") +
xlim(c(2, 4))


text:
Q: Reference a hidden defined form field in PHP I am trying to create a template commenting system using Dreamweaver for a site. I have the form setup to submit the webpage and corresponding text to a mysql db. the webpage value is a hidden form field.
The form submits to the db okay but I want to create a repeating view for the comments. How do I reference the hidden form field so I can use it where "WHERE webpage=""" is called?
UPDATE: By repeating view I mean:
 <?php do { ?>

<?php echo $row_InsertRecords['text']; ?>

     <?php } while ($row_InsertRecords = mysql_fetch_assoc($InsertRecords));     ?>

My problem is I need to make partial edits to the PHP for that template so I can retrieve comments specific to the child page but Dreamweaver won't let me. It either propogates ALL of the PHP or none of it.

A: For a dynamic commenting system that uses the templates in Dreamweaver, you can use the following code in your dwt file:
$fname=basename($_SERVER['PHP_SELF']);
$query_ViewRecords = "SELECT * FROM commentsDB WHERE id='".$fname."'";

id can match a hidden value in your comment form defined as such:
<input type="hidden" name="IDField" value=<?php echo "\"$fname\""; ?>/>

The code above was part of code generated by Dreamweaver's DB functions that were later edited by me to add the WHERE clause. This way you can generate HTML that matched each child page when it is created by the template. Make sure codeOutsideHTMLIsLocked parameter is set to true for these changes to propagate to the child pages.


text:
Q: Aiogram -- set state for a exact user I'm writing a bot in python and aiogram. The point is that the administrator accepts (or rejects) user requests. Accordingly, when the administrator clicks on the button in his chat, I need to change the user's state (his uid is known). I didn't find how to do it anywhere.
I'm looking for something like
dp.set_state(uid, User.accepted))

Thanks!

A: I had the same problem
Found method set() in base class State:
class State:
    ...
    async def set(self):
        state = Dispatcher.get_current().current_state()
        await state.set_state(self.state)

So I created new class from State and overrode method this way:
    async def set(self, user=None):
        """Option to set state for concrete user"""
        state = Dispatcher.get_current().current_state(user=user)
        await state.set_state(self.state)

Usage:
@dp.message_handler(state='*')
async def example_handler(message: Message):
    await SomeStateGroup.SomeState.set(user=message.from_user.id)

If you want some mailing stuff, collect user ids and use that hint.

A: from aiogram.dispatcher import FSMContext

@dp.message_handler(state='*')
async def example_handler(message: types.Message, state: FSMContext):
    new_state = FSMContext(storage, chat_id, user_id)

then set_state() and set_data() on the new_state.
storage is the FSM storage.


text:
Q: How to findall() a sequence of regular expressions to a pandas dataframe? I am extracting some patterns with pandas findall function. However, I have several regular expressions. This, how can I findall N regular expressions with pandas?.
For example, lets say that I would like to extract the all the numbers and all the dates inside an specific column:
In:
dfs = pd.DataFrame(data={'c1': ['This dataset 11/12/98 contains 5,000 rows, which were sampled from a 500,000 11/12/12 row dataset spanning the same time period. Throughout these analyses',

                                'the number of events you count will be about 100 times smaller than they 11/12/78 actually were, but the 01/12/11 proportions of events will still generally be reflective that larger dataset. In this case, a sample is fine because our purpose is to learn methods of data analysis with Python, not to create 100% accurate recommendations to Watsi.']})

dfs

Out:
    c1
0   This dataset 11/12/98 contains 5,000 rows, whi...
1   the number of events you count will be about 1...

I tried to, but I am getting the following error:
In:
dfs['patterns'] = dfs['c1'].str.findall([r'\d+',r'(\d+/\d+/\d+)']).apply(', '.join)

dfs

Out:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-64-af2969e06a61> in <module>()
----> 1 dfs['patterns'] = dfs['c1'].str.findall([r'\d+',r'(\d+/\d+/\d+)']).apply(', '.join)
      2 dfs

/usr/local/lib/python3.5/site-packages/pandas/core/strings.py in wrapper2(self, pat, flags, **kwargs)
   1268
   1269     def wrapper2(self, pat, flags=0, **kwargs):
-> 1270         result = f(self._data, pat, flags=flags, **kwargs)
   1271         return self._wrap_result(result)
   1272

/usr/local/lib/python3.5/site-packages/pandas/core/strings.py in str_findall(arr, pat, flags)
    827     extractall : returns DataFrame with one column per capture group
    828     """
--> 829     regex = re.compile(pat, flags=flags)
    830     return _na_map(regex.findall, arr)
    831

/usr/local/Cellar/python3/3.5.2_2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/re.py in compile(pattern, flags)
    222 def compile(pattern, flags=0):
    223     "Compile a regular expression pattern, returning a pattern object."
--> 224     return _compile(pattern, flags)
    225
    226 def purge():

/usr/local/Cellar/python3/3.5.2_2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/re.py in _compile(pattern, flags)
    279     # internal: compile pattern
    280     try:
--> 281         p, loc = _cache[type(pattern), pattern, flags]
    282         if loc is None or loc == _locale.setlocale(_locale.LC_CTYPE):
    283             return p

TypeError: unhashable type: 'list'

Therefore how can I "stack", "nest" or apply several regex with findall function?. What I expect as an output is the resolution of each regular expression separated by , in a single column:
   col
0  '11/12/98', '5', '000', '500', '000', '11/12/12'
1  '100', '11/12/78', '01/12/11', '100'

UPDATE
I tried to:
dfs['patterns'] = dfs['c1'].str.map(findall(),[r'\d+',r'(\d+/\d+/\d+)']).apply(', '.join)
dfs

A: Still not clear your desired output.
But please check below code.
dfs['patterns'] = dfs['c1'].str.findall(r'\d+\/\d+\/\d+|\d+')
print dfs['patterns'].sum()

['11/12/98', '5', '000', '500', '000', '11/12/12', '100', '11/12/78', '01/12/11', '100']


text:
Q: Kinect Speech Recognition not detecting while in fullscreen This one is a weird case.  I'm using Microsoft.Speech with the Kinect in XNA.  Everything works as expected except for when I'm running the game in fullscreen on one monitor.  If I'm not fullscreen, or if I'm connected to another monitor via HDMI and in fullscreen mode, the Kinect detects and recognizes speech with no problems.  But as soon as I run the game in fullscreen, with no other HDMI connections,  Speech is never even detected, let alone recognized.  There are no errors in the initialization process.  To summarize:

*

*Windowed mode - Works as expected

*Fullscreen with second HDMI monitor connection - Works as expected

*Fullscreen with no other monitor connections - No speech detection
Possibly related, possibly not, if I run the game (or any game for that matter) in fullscreen with the other monitor plugged in, the game can't render (keeps blinking on both monitors as if it's trying to enter and leave fullscreen repeatedly) but again, speech works fine in that case.
Any thoughts?  All are appreciated, as usual.  Thanks!


text:
Q: Git: How to share the repositories without flooding with nonsignificant commits? I have a repository with my code.
I write in my own computer but the environment to run it is in a remote computer, so I am working like this:
-> Local:
|    Write
|    Commit
|    Push --------> company git server |
|                                      |
|  Remote                              |
|    Pull   <---------------------------
|    Compile
<--- Run

However,if I missed a colon, or add a newline or fix a name or all that sort of minor changes, I've been adding numerous non-significant commits and that for version control is not convenient at all.
I've thought of writing a script to sync both machines with Rsync, but not sure if that's the best way to do it.
In the end of the day I would like to have just important commits and not all the trash I am adding.
How would you guys/girls do it?

A: *

*git is much better (more effective) synchronisation tool that rsync because it stores much more meta-information. rsync has to recheck every file every time while git compares object hashes at both sides.

*If you don't like you have too many small not very interesting commits — use git rebase --interactive and squash them into commits they fix or squash them together in one Big Fix commit.

A: I would not bother about it at all. While it is true that you can use git rebase -i (docs) or (in other circumstances, not for your particular case) git merge --squash (docs) to get rid of small, inconsequential, commits, I do not see a problem to solve.
git is very efficient at tracking small changes over many commits. You are not wasting much space. The worst that could happen is that someone else sees this. If a colleague challenges you about it, you can inform them that you prefer to commit early and often (which is a common trope with git, google for it and you find supporting sites like this or that). It's the same as the old "save early, save often" for general applications.
git is designed to work well with frequent, granular commits. Especially, merge operations don't care in the slightest how many commits are between the 3 involved commits.
Be especially careful with rebasing already pushed commits, that will lead to major headaches unless you have very tight control (and knowledge) about who already has your commits in their respective repository.


text:
Q: Why is energy not conserved for an impulsive force? Why is energy conservation not valid in the case of an impulsive force?
Let me give an example of a problem that concerns my question.
Suppose a horizontally flying bullet of mass m gets stuck in a body of mass M.
So I came up with 2 equations:

*

*$(m)(v_i) = (m+M)(v_f)$

*$1/2(m)(v_i)^2 = 1/2(m+M)(v_f)^2$
So why is equation 2 incorrect?
Any help is appreciated!

A: Energy is always conserved, that is one of the strongest principles in physics. However, in some cases depending of its practicality, we talk just about the mechanical energy, which is the one not conserved in your example. In your case it is said to be an inelastical collision.
They key fact is that, what first were two distinct objects, transform into just one. When the bullet collides with the other body, it penetrates into it, deforming its volume and tearing come molecular/structural bonds apart, giving energy to some atoms of the body and increasing its temperature. This temperature, at the same time, transforms into radiation (emision of light) that also take away energy.
As you can see, there is a lot of things going on in just a simple inelastic collision. If you still want to apply energy conservation, you would need to know all this changes in total energy and write
$$
\frac{1}{2}m v_i^2=\frac{1}{2}(M+m) v_f^2 + E_{friction} + E_{chem} + E_{rad}...
$$
Or you could just group all the unknown energies into $\Delta E_{lost}$ and say
$$
\frac{1}{2}m v_i^2=\frac{1}{2}(M+m) v_f^2 + \Delta E_{lost}
$$
With that little correction you could still apply the energy conservation formula, but obviously the energy lost is not usually known, and therefore you could not use the formula in that case.

A: Here energy as a whole is conserved but mechanical energy is not conserved, the energy that is used up in penetrating the the body of mass M is not recovered in the form of Mechanical energy but is used up for deformation of the body, changing temperature of the body, sound, etc. And these energies cannot be retrieved back in the form of Mechanical energy at the time of reformation.
It does not depend on the fact if the Force is Impulsive or not but on the nature of collision i.e. if it is elastic or inelastic collision. Mechanical Energy would be conserved in elastic collision and does not depend if the force is Impulsive or not.

A: Some kinetic energy of the bullet is converted to potential energy of deformation of the object it hit, heat and sound; thus the kinetic energy is not conserved

A: Kinetic energy is only conserved in an elastic collision. Since the bullet gets stuck in the mass $M$, this collision is not elastic - in fact it is perfectly inelastic - and energy is lost due to friction etc.
Note that the key factor here is the nature of the collision, not whether the force is impulsive. Even if the bullet slowed down over a significant distance and so exerted a non-impulsive force on mass $M$, kinetic energy would still be lost in this scenario.


text:
Q: Init function in javascript and how it works I often see the following code:
(function () {
  // init part
})();

but I never could get my head around how it works. I find the last brackets especially confusing.
Could someone explain how it works in terms of Execution Contexts (EC) and Variable Objects (VO)?

A: The way I usually explain this to people is to show how it's similar to other JavaScript patterns.
First, you should know that there are two ways to declare a function (actually, there's at least five, but these are the two main culprits):
function foo() {/*code*/}
and
var foo = function() {/*code*/};
Even if this construction looks strange, you probably use it all the time when attaching events:
window.onload=function(){/*code*/};
You should notice that the second form is not much different from a regular variable declaration:
var bar = 5;
var baz = 'some string';
var foo = function() {/*code*/};

But in JavaScript, you always have the choice between using a value directly or through a variable. If bar is 5, then the next two statements are equivalent:
var myVal = bar * 100; // use 'bar'
var myVal = 5 * 100;   // don't use 'bar'

Well, if you can use 5 on its own, why can't you use function() {\*code*\} on its own too? In fact, you can. And that's called an anonymous function. So these two examples are equivalent as well:
var foo = function() {/*code*/}; // use 'foo'
foo();

(function(){/*code*/})();        // don't use 'foo'

The only difference you should see is in the extra brackets. That's simply because if you start a line with the keyword function, the parser will think you are declaring a function using the very first pattern at the top of this answer and throw a syntax error exception. So wrap your entire anonymous function inside a pair of braces and the problem goes away.
In other words, the following three statements are valid:
5;                        // pointless and stupid
'some string';            // pointless and stupid
(function(){/*code*/})(); // wonderfully powerful

[EDIT in 2020]
The previous version of my answer recommended Douglas Crockford's form of parens-wrapping for these "immediately invoked anonymous functions". User @RayLoveless recommended in 2012 to use the version shown now. Back then, before ES6 and arrow functions, there was no obvious idiomatic difference; you simply had to prevent the statement starting with the function keyword. In fact, there were lots of ways to do that. But using parens, these two statements were syntactically and idiomatically equivalent:
( function() { /* code */}() );
( function() { /* code */} )();

But user @zentechinc's comment below reminds me that arrow functions change all this. So now only one of these statements is correct.
( () => { /* code */ }() ); // Syntax error
( () => { /* code */ } )();

Why on earth does this matter? Actually, it's pretty easy to demonstrate. Remember an arrow function can come in two basic forms:
() => { return 5; };       // With a function body
() => { console.log(5); };

() => 5;                   // Or with a single expression
() => console.log(5);

Without parens wrapping this second type of arrow function, you end up with an idiomatic mess:
() => 5();              // How do you invoke a 5?
() => console.log(5)(); // console.log does not return a function!

A: Self invoking anonymous function (SIAF)
Self-invoking functions runs instantly, even if DOM isn't completely ready.
jQuery document.ready vs self calling anonymous function

A: That pattern will create a new execution context (EC) in which any local variable objects (VO's) will live, and will likewise die when the EC exits. The only exception to this lifetime is for VO's which become part of a closure.
Please note that JavaScript has no magic "init" function. You might associate this pattern with such since most any self-respecting JS library (jQuery, YUI, etc.) will do this so that they don't pollute the global NS more than they need to.
A demonstration:
var x = 1; // global VO
(function(){
    var x = 2; // local VO
})();
x == 1; // global VO, unchanged by the local VO

The 2nd set of "brackets" (those are actually called parens, or a set of parentheses), are simply to invoke the function expression directly preceding it (as defined by the prior set of parenthesis).

A: The code creates an anonymous function, and then immediately runs it. Similar to:
var temp = function() {
  // init part
}
temp();

The purpose of this construction is to create a scope for the code inside the function. You can declare varaibles and functions inside the scope, and those will be local to that scope. That way they don't clutter up the global scope, which minimizes the risk for conflicts with other scripts.

A: In simple word you can understand that whenever page load, by this second pair of brackets () function will have called default.We need not call the function.It is known as anonymous function.
i.e.
(function(a,b){
//Do your code here
})(1,2);

It same like as
var test = function(x,y) {
  // Do your code here
}
test(1,2);

A: I can't believe no-one has answered the ops question!
The last set of brackets are used for passing in the parameters to the anonymous function. So, the following example creates a function, then runs it with the x=5 and y=8
(function(x,y){
    //code here
})(5,8)

This may seem not so useful, but it has its place. The most common one I have seen is
(function($){
    //code here
})(jQuery)

which allows for jQuery to be in compatible mode, but you can refer to it as "$" within the anonymous function.

A: Its is called immediatly invoking function expression (IIFE). Mainly associated with the JavaScript closure concept. Main use is to run the function before the global variable changed, so that the expected behaviour of code can be retained.


text:
Q: android resources folder naming So i have a very stupid question. I am new to Android and trying to understand how the resources folder work.
I see that I need subfolders with ldpi, mdpi, hdpi, xhdpi, xxhdpi naming but does the naming of the actual image need to be different?
For example, If I have an image names icon.png.
In iOS:  mdpi would be icon.png,  xhdpi would be icon@2x.png and xxhdpi would be icon@3x.png.
Do I need to give different naming in Android?
If I put icon.png in 5 different folders with 5 different sizes, would there be a name conflict?
It would be very good if someone can explain it.
I read all standard android explanations but I want to make sure with someone who has actually done it.
Thanks for your time.

A: Directory Naming:
You do not need to provide a different suffix to your image file name for different screen sizes in Android like you do in iOS. The file name should be exactly the same for all the images of different sizes.
However, you need to follow Google's guidelines/conventions for directory naming. Images are called 'drawables' in Android.
Under the 'res' directory, place each image under a directory called drawable-<suffix>. Replace the <suffix> with the screen density qualifier (i.e., mdpi, hdpi, xhdpi, xxhdpi etc.)
Google recommends that you also create a directory called drawable (with no suffix) for default images. These default images will be used as fallback when Android does not find a specific image size for the user's device.
Example directory structure:
res/
    drawable/
        icon.png
        background.png
    drawable-mdpi/
        icon.png
        background.png
    drawable-hdpi/
        icon.png
        background.png
    drawable-xhdpi/
        icon.png
        background.png
    drawable-xxhdpi/
        icon.png
        background.png

Image Size Ratios:
The correct way to create images for different screen densities is by starting at a base image size for mdpi.
Say for example your base icon size is 48px x 48px. Then:
mdpi:     48px x 48px   (1x)

hdpi:     72px x 72px   (1.5x)

xhdpi:    96px x 96px   (2x)

xxhdpi:   144px x 144px (3x)

xxxhdpi:  192px x 192px (4x)

References:
Directory structure:
http://developer.android.com/guide/topics/resources/providing-resources.html
For size ratio comparison (mdpi vs hdpi vs xhdpi vs xxhdpi) go to:
http://developer.android.com/design/style/iconography.html


text:
Q: Stripe Connection Error I have the follow backend Node.js code to connect to my Stripe account to make a Charge. But I'm getting this error. I'm using Firebase Functions, and this functionality used to work before, so I doubt this is anything to do with Firebase access restrictions. Any ideas and help on this will be greatly appreciated!
var functions = require('firebase-functions');
var stripe = require('stripe')('sk_test');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');

exports.stripePay = functions.https.onRequest((request, response) => {
  if (request.method === 'POST') {
    var app = express();
    var router = express.Router();

    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cors());

    var stripetoken = request.body.cardToken;
    var amountpayable = request.body.amount;

    var charge = stripe.charges.create({
      amount: amountpayable,
      currency: 'usd',
      source: stripetoken,
      description: 'Sample transaction'
    }, function (err, charge) {
      console.log("ST4");
      if (err) {
        response.send("Failed!");
      }
      else {
        response.send({ success: true });
      }
    })
  }

{ Error: An error occurred with our connection to Stripe
    at Error._Error (/user_code/node_modules/stripe/lib/Error.js:12:17)
    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)
    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)
    at ClientRequest.<anonymous> (/user_code/node_modules/stripe/lib/StripeResource.js:192:9)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at connectErrorNT (net.js:1020:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)   type: 'StripeConnectionError', stack: 'Error: An error occurred with our connection to Stripe\n    at Error._Error (/user_code/node_modules/stripe/lib/Error.js:12:17)\n    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)\n    at Error.Constructor (/user_code/node_modules/stripe/lib/utils.js:98:13)\n    at ClientRequest.<anonymous> (/user_code/node_modules/stripe/lib/StripeResource.js:192:9)\n    at emitOne (events.js:96:13)\n    at ClientRequest.emit (events.js:188:7)\n    at TLSSocket.socketErrorListener (_http_client.js:310:9)\n    at emitOne (events.js:96:13)\n    at TLSSocket.emit (events.js:188:7)\n    at connectErrorNT (net.js:1020:8)\n    at _combinedTickCallback (internal/process/next_tick.js:74:11)\n    at process._tickDomainCallback (internal/process/next_tick.js:122:9)',   rawType: undefined,   code: undefined,   param: undefined,   message: 'An error occurred with our connection to Stripe',   detail:     { Error: getaddrinfo ENOTFOUND api.stripe.com api.stripe.com:443
       at errnoException (dns.js:28:10)
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
     code: 'ENOTFOUND',
     errno: 'ENOTFOUND',
     syscall: 'getaddrinfo',
     hostname: 'api.stripe.com',
     host: 'api.stripe.com',
     port: '443' },   raw:     { message: 'An error occurred with our connection to Stripe',
     detail:
      { Error: getaddrinfo ENOTFOUND api.stripe.com api.stripe.com:443
          at errnoException (dns.js:28:10)
          at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
        code: 'ENOTFOUND',
        errno: 'ENOTFOUND',
        syscall: 'getaddrinfo',
        hostname: 'api.stripe.com',
        host: 'api.stripe.com',
        port: '443' } },   requestId: undefined,   statusCode: undefined } Reply

A: this is a good one! Firebase blocks external API connections for Free accounts, just get any paid account and this will work!

A: Dimitris answer is correct, in more layman's terms simply get on the blaze plan and you can make calls to stripe api from Firebase Functions.


text:
Q: Ignoring 'Content-type: application/pdf' and setting to 'Content-type: application/octet-stream I have some php code code
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="'.$filename.'"');
readfile($tempfile);

The file downloads fine but when I query the mime type it returns _application/octet-stream_

A: xdg-mime is "command line tool for querying information about file type handling and adding descriptions for new file types"
This suggests that you are downloading the file (generated via PHP), saving it to disk, and then examining the saved file with the tool.
The tool has no way of knowing what the HTTP response said. It only has access to the saved file.
While the Content-Type says "This is a PDF file" it doesn't turn the file into a PDF or change the ability of tools that do not examine the HTTP header to identify what type the file is.


text:
Q: how to convert this code from Dijkstra to Astar? So I have a project of which I want to switch to Astar due to speed reasons.
But C++ is not my strongest point. Could anyone help me (or tell me how to do the..) converting the algorythm from Dijkstra to Astar?
I found this Astar implementation:
http://code.google.com/p/a-star-algorithm-implementation/
But I don't know how to use it with my existing code.
Here is the graph file which got the algorithm:
#include "Graph.h"
#include <iostream>
#include <algorithm>
#include <stack>

Graph::Graph(void)
{
}

Graph::~Graph(void)
{
    while(!mNodes.empty())
    {
        delete mNodes.back();
        mNodes.pop_back();
    }
}

void Graph::addNode(int name, bool exists, Node** NodeID )
{
    Node* pStart = NULL;
    mNodes.push_back(new Node(name,exists));
    std::vector<Node*>::iterator itr;
    itr = mNodes.begin()+mNodes.size()-1;
    pStart = (*itr);
    if(exists == true)pStart->DoesExist_yes();
    *NodeID = pStart;
}

void Graph::connect_oneway(Node* pFirst, Node* pSecond, int moveCost)
{
    if(pFirst != NULL && pSecond != NULL)
    {
        pFirst->createEdge(pSecond, moveCost);
    }
}

#define MAX_NODES (32768)
#define MAX_CONNECTIONS (5)
#include <time.h>

int * Graph::findPath_r(Node* pStart, Node* pEnd)
{
    int *arr = new int[MAX_NODES+2];

    for (int i=0; i<MAX_NODES; i++)
        arr[i] = -1;

    arr[0] = 0;
    if(pStart == pEnd)
    {
        return arr;
    }

    std::vector<Node*> openList;
    openList.push_back(pStart);
    Node* pCurrNode = NULL;

    while(!openList.empty())
    {
        //Get best node from open list (lowest F value).
        //Since we sort the list at the end of the previous loop we know
        //the front node is the best
        pCurrNode = openList.front();

        //Exit if we're are the goal
        if(pCurrNode == pEnd)
            break;

        //Remove the node from the open list and place it in the closed
        openList.erase(openList.begin());
        pCurrNode->setClosed(true); //We use a flag instead of a list for speed
        //Test all of the edge nodes from the current node
        std::vector<Edge*>* pEdges = pCurrNode->getEdges();
        Node* pEdgeNode = NULL;
        for(std::vector<Edge*>::iterator i = pEdges->begin(); i != pEdges->end(); ++i)
        {
            pEdgeNode = (*i)->pNode;
            //If it's closed we've already analysed it
            if(!pEdgeNode->getClosed() && pCurrNode->DoesExist() == true)
            {
                if(!inList(pEdgeNode,&openList))
                {
                    openList.push_back(pEdgeNode);
                    pEdgeNode->setGCost(pCurrNode->getGCost()+(*i)->moveCost);
                    pEdgeNode->calcFCost();
                    pEdgeNode->setParent(pCurrNode);
                }
                else
                {
                    //If this is a better node (lower G cost)
                    if(pEdgeNode->getGCost() > pCurrNode->getGCost()+(*i)->moveCost)
                    {
                        pEdgeNode->setGCost(pCurrNode->getGCost()+(*i)->moveCost);
                        pEdgeNode->calcFCost();
                        pEdgeNode->setParent(pCurrNode);
                    }
                }
            }
        }
        //Place the lowest F cost item in the open list at the top, so we can
        //access it easily next iteration
        std::sort(openList.begin(), openList.end(),  Graph::compareNodes);
    }
    //Make sure we actually found a path
    if(pEnd->getParent() != NULL)
    {
        //Output the path
        //Use a stack because it is LIFO
        std::stack<Node*> path;
        while(pCurrNode != NULL)
        {
            path.push(pCurrNode);
            pCurrNode = pCurrNode->getParent();
        }

        int counter = 0;
        arr[1] = 0;
        while(!path.empty())
        {
            arr[counter+2] = path.top()->getName();
            counter++;
            arr[1] += path.top()->getGCost();
            path.pop();
        }
        arr[0] = counter;
        return arr;
    }
    return arr;
}

bool Graph::inList(Node* pNode, std::vector<Node*>* pList)
{
    for(std::vector<Node*>::iterator i = pList->begin(); i != pList->end(); ++i)
    {
        if((*i) == pNode)
        {
            return true;
        }
    }

    return false;
}

bool Graph::compareNodes(Node* pFirst, Node* pSecond)
{
    return pFirst->getFCost() < pSecond->getFCost();
}

void Graph::reset(void)
{
    for(std::vector<Node*>::iterator i = mNodes.begin(); i != mNodes.end(); ++i)
    {
        (*i)->reset();
    }
}

The function for finding the path is this one:
Graph::findPath_r
What I really want to do is preserve the edges (because they decide if the road is both or one-way).
Here are the other files:
Graph.h
#ifndef _GRAPH_H_
#define _GRAPH_H

#include "Node.h"

class Graph
{
public:
    Graph(void);
    ~Graph(void);

    //void addNode(int name, bool exists);
    void addNode(int name, bool exists, Node** NodeID );
    void connect_oneway(int ppFirst, int ppSecond, int moveCost);
    void connect_oneway(Node* pFirst, Node* pSecond, int moveCost);
    //int * findPath_r(int start, int end);
    int * findPath_r(Node* pStart, Node* pEnd);
    void reset(void);
private:
    void findNodesx(int firstName, Node** ppFirstNode);
    bool inList(Node* pNode, std::vector<Node*>* pList);
    static bool compareNodes(Node* pFirst, Node* pSecond);
    std::vector<Node*> mNodes;
};

#endif

Node.h
#ifndef _NODE_H_
#define _NODE_H_

#include <string>
#include <vector>

//Forward declare Node so Edge can see it
class Node;

struct Edge
{
    Edge(Node* node, int cost) : pNode(node), moveCost(cost){}
    Node* pNode;
    int moveCost;
};

class Node
{
public:
    Node(void);
    Node(int name, bool exists);
    ~Node(void);

    void createEdge(Node* pTarget, int moveCost);

    void setGCost(int cost);
    void setClosed(bool closed);
    void setParent(Node* pParent);

    int getGCost(void);
    int getFCost(void);
    bool getClosed(void);
    Node* getParent(void);
    int getName(void);
    bool DoesExist(void);
    bool DoesExist_yes(void);
    std::vector<Edge*>* getEdges(void);

    void calcFCost(void);
    void reset(void);
private:
    int mGCost;
    int mTotal;
    bool mClosed;
    Node* mpParent;
    int mName;
    bool mHeur;
    std::vector<Edge*> mEdges;
};

#endif

Node.cpp
#include "Node.h"

Node::Node(void)
{
}

Node::Node(/*const std::string&*/int name, bool exists) : mGCost(0), mTotal(0), mClosed(false), mpParent(NULL), mName(name), mHeur(exists)
{
}

Node::~Node(void)
{
    while(!mEdges.empty())
    {
        delete mEdges.back();
        mEdges.pop_back();
    }
}

int Node::getName(void)
{
    return mName;
}

void Node::createEdge(Node* pTarget, int moveCost)
{
    mEdges.push_back(new Edge(pTarget, moveCost));
}

void Node::setClosed(bool closed)
{
    mClosed = closed;
}

bool Node::getClosed(void)
{
    return mClosed;
}

std::vector<Edge*>* Node::getEdges(void)
{
    return &mEdges;
}

int Node::getGCost(void)
{
    return mGCost;
}

void Node::setGCost(int cost)
{
    mGCost = cost;
}

void Node::calcFCost(void)
{
    mTotal = mGCost;
}

void Node::setParent(Node* pParent)
{
    mpParent = pParent;
}

int Node::getFCost(void)
{
    return mTotal;
}

bool Node::DoesExist(void)
{
    return mHeur;
}

bool Node::DoesExist_yes(void)
{
    mHeur = true;
    return true;
}

Node* Node::getParent(void)
{
    return mpParent;
}

void Node::reset(void)
{
    mGCost = 0;
    mTotal = 0;
    mClosed = false;
    mpParent = NULL;
}

A: You mentioned a library on GoogleCode. It is node clear what you want to do with, and I think the best is to write your implementation yourself.
First, you should know that Dijsktra is a special case of A*. In A*, you have an heuristic, named h; A* = possible implementation of Dijsktra when h is the null function.
Then, about your implementation, let's start with Node. It will need the following functions:
constructor, destructor
create/get edge
set/get parent
set/is closed (for speed)
set/get GCost
set/get FCost
set/is obstacle (name way more descriptive than 'DoesExist')
set/get position
reset

// optional method:
get name

Hopefully, this part of your code won't change a lot. The heuristic code will be placed in the pathfinder. The Edge class is left untouched.
Now the big one: Graph. You won't need to delete any of your public methods.
You will need a heuristic method. For the implementation which will be described, you will need an admissible consistent heuristic:

*

*it must not over-estimate the distance to the goal (admissible)

*it must be monotone (consistent)

The general case signature is int getHCost(Node* node);. If you always return 0, you will have a Dijsktra algorithm, which is not what you want. Here we will take the euclidiean distance between the node and the goal. Slower to compute than manhattan distance, but better results. You can change this afterwards.
int getHCost(Node* node, Note* goal);

This implies you must place your nodes in the 3d space. Note that the heuristic is a heuristic, ie, an estimation of the distance.
I won't write the code. I will write some pseudo-code adapted to your situation. The original pseudocode is located on the Wikipedia A* page. This pseudo-code is your findPath_r function:
function A*(start,goal)
    set all nodes to not closed // The set of nodes already evaluated.
    openset = {start}    // The set of tentative nodes to be evaluated, initially containing the start node

    start.gcost = 0    // Cost from start along best known path.
    // Estimated total cost from start to goal through y.
    start.fcost = start.gcost + getHCost(start, goal)

    while openset is not empty
        current = the node in openset having the lowest f_cost (usually the first if you use a sorted list)
        if current == goal
            return construct_path(goal)

        remove current from openset
        current.closed = true
        for each neighbor in (node connected by edge in current.edges) // Here is the condition for one-way edges
            if neighbor.closed or neighbor.obstacle
                continue

            gcost = current.gcost + dist_between(current,neighbor) // via edge distance

            if neighbor not in openset
                add neighbor to openset
                neighbor.parent = current
                neighbor.gcost = gcost
                neighbor.fcost = neighbor.gcost + getHCost(neighbor, goal)
            else if gcost < neighbor.gcost
                neighbor.parent = current
                neighbor.gcost = gcost
                neighbor.fcost = neighbor.gcost + getHCost(neighbor, goal)
                update neighbor position in openset

    return failure

function construct_path(current_node)
    std::vector<Node*> path
    while current_node != 0
        path.push_front(current_node)
        current_node = current_node.parent
    return path

The implementation above use one-way edges.
You were able to write Dijsktra algorithm in C++, so writing this pseudocode in C++ shouldn't be a problem.
Second part, performances. First, measure ;).
I have some hints that can improve performances:

*

*use a memory pool for allocation deallocation

*use an intrusive list for the open list (you can also make it auto-sorted with this technique)

I advise you to read A* for beginners, which is a useful reading, even if you don't use tilemap.


text:
Q: Configure my modem not to be a router I would like to configure my linux box to act as its own router, or maybe the better way to put it is that I want the box to connect to the internet directly with no router. There are some other questions that deal with linux-as-a-router, but these deal with situations where the linux box is actually routing to other computers. This does not apply to my situation, where only the single box is the endpoint. One reason I want to do this is that I need to have my cable modem in bridge mode so that Airport Express will work on it. Also, I would just as soon like to configure the routing (or lack of routing actually) using Linux rather than monkey around with the ISP's web interface to their modem.
Since the box is the endpoint, I assume I do not need internal addresses like 192.168.0.1 because there is no LAN, so my box's IP can just be the public facing WAN IP address. In general I think I only need to set up a few services, like DNS. What are the steps to get the box talking to the bridge?
System is Debian Wheezy. Provider is Comcast XFinity and the modem is an Arris TG862G-CT.
Just to re-iterate. I do not actually need to do any routing. There is no LAN. I just need to get the linux box sending packets out over the bridge. Presumably I need to enter static addresses, or possibly MAC addresses somewhere. I have the MAC address of the modem.
As an example of the basic problem operating in bridge mode, the web interface for the modem is probably sitting at 192.168.0.1 but since there is no router, I have no way to access that address without configuring it somehow.

A: Debian Jessie is more than a year old, and that means Wheezy has been oldstable for more than a year. Unless you have a very good reason you should upgrade.
Typically your box does not need to talk to the modem, it's just there and your box talks to the ISP's equipment. We'll need to know your ISP before we have any chance to answer how to configure your box to do that, but typically (at least from what I've heard/seen) your box should just use DHCP.
Getting your box to talk to your ISP is the same whether is should route traffic from other machines or not.


text:
Q: HibernateException: Found: clob, expected: varchar2(4000) I have a very strange bug in my application on Tomcat 7 using Hibernate 3 and ojdbc7.jar:
In the current release, a DB column got changed to CLOB, and is configured the following way:
@Column(name = "BESCHREIBUNG")
@Length(min = 0, max = 4000)
@NotNull
@Lob
public String getBeschreibung() {

This works perfectly fine in my local environment (Oracle 11g XE) and in test environment (Oracle 12), however in prelive environment (Oracle 12), I get the following error during application start:
org.hibernate.HibernateException: Wrong column type in XXXX.MYTABLE for column BESCHREIBUNG. Found: clob, expected: varchar2(4000 char)
at org.hibernate.mapping.Table.validateColumns(Table.java:283)
at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1343) at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:139)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:378)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)

Any hints on this?
I've already checked tomcat's /lib - directoryif there's an outdated ojdbc or hibernate jar, without success.

A: According to the message he is still expecting a varchar2. As he would expect a clob if he finds a @Lob, I would guess that you didn't deploy the code changes to your prelive environment (at least not successfully).

A: add column definition to solve this problem.
@Column(name = "entity_value", columnDefinition="clob")

A: I just delete the @Length(...) and it works like a charm.


text:
Q: Store and retrieve correct data I want to create a form for selecting a number of receiving then that's the reference items store correctly and retrieve correctly.

this is my angular js code
$scope.addreciveditemtemp = function(receiving,newreciveditemtemp) {
  $scope.receiving_item = [ ];
  $http.get('api/reciveditem').success(function(response) {
      $scope.receiving_item = response;
      for (var i=0;i<$scope.receiving_item.length;i++){
          var receiving_item = $scope.receiving_item[i];
          if(receiving_item.receiving_id===receiving.id){
              console.log(receiving_item);
              $http.post('api/reciveditemtemp', {
                 recived_id: receiving_item.receiving_id,
                 item_id: receiving_item.item_id,
                 cost_price: receiving_item.cost_price,
                 prequantity: receiving_item.quantity,
                 pretotal_cost: receiving_item.total_cost,
                 realtotal: receiving_item.total_cost
              }).success(function(data, status, headers, config) {
                 $scope.reciveditemtemp.push(data);
                 $http.get('api/reciveditemtemp').success(function(data) {
                     $scope.reciveditemtemp = data;
                 });
              });
           }
       }
  });
};

this is my laravel controller code
public function store()
    { $this->newItem();
}

public function newItem()
{
    $receiving_item = ReceivingItem::where('receiving_id', Input::get('item_id'))->get();
    foreach($receiving_item as $value)
    {

        $reciveditemtemps = new reciveditemtemp;
        $reciveditemtemps->recived_id = $value->receiving_id;
        $reciveditemtemps->item_id = $value->item_id;
        $reciveditemtemps->cost_price = $value->cost_price;
        $reciveditemtemps->prequantity = $value->quantity;
        $reciveditemtemps->pretotal_cost = $value->total_cost;
        $reciveditemtemps->realquantity = $value->quantity;
        $reciveditemtemps->realtotal = $value->cost_price * $value->realquantity;
        $reciveditemtemps->save();
        //return $ReceivingTemps;
    }
        return $reciveditemtemps;
}

But console answer is correct

how to solve this problem?? please help me.

A: This looks sketchy:

ERRONEOUS
 }).success(function(data, status, headers, config) {
     $scope.reciveditemtemp.push(data);
     $http.get('api/reciveditemtemp').success(function(data) {
         $scope.reciveditemtemp = data;
     });
  });

To push a value to an array and then replace the entire array does not seem right.

A: change the controller code.
public function newItem()
{
   $reciveditemtemps = new reciveditemtemp;
   $reciveditemtemps->recived_id = Input::get('receiving_id');
   $reciveditemtemps->item_id = Input::get('item_id');
   $reciveditemtemps->cost_price = Input::get('cost_price');
   $reciveditemtemps->prequantity = Input::get('prequantity');
   $reciveditemtemps->pretotal_cost = Input::get('pretotal_cost');
   $reciveditemtemps->realtotal = Input::get('realtotal');
   $reciveditemtemps->realquantity = Input::get('prequantity');
   $reciveditemtemps->save();
   return $reciveditemtemps;
}