text:
Q: How can i fill part of image with color? I have image which i add in my form.How can i fill part of image?
I have this

What I'm trying to achieve:

A: To floodfill an area you need a foodfill routine and very little else.
See this example:

It uses two pictureboxes, also a label to display the chosen color.
And two mouse click events, one to pick the color:
private void pictureBoxPalette_MouseClick(object sender, MouseEventArgs e)
{
    Point sPt = scaledPoint(pictureBoxPalette, e.Location);
    lbl_color.BackColor = ((Bitmap)pictureBoxPalette.Image).GetPixel(sPt.X, sPt.Y);
}

..and one to call the fill:
private void pictureBoxTgt_MouseClick(object sender, MouseEventArgs e)
{
    Point sPt = scaledPoint(pictureBoxTgt, e.Location);
    Bitmap bmp = (Bitmap)pictureBoxTgt.Image;
    Color c0 = bmp.GetPixel(sPt.X, sPt.Y);
    Fill4(bmp, sPt, c0, lbl_color.BackColor);
    pictureBoxTgt.Image = bmp;
}

The Floodfill routine is taken from this post; it is basically a direct implementation of a wikipedia algorithm..:
static void Fill4(Bitmap bmp, Point pt, Color c0, Color c1)
{
    Color cx = bmp.GetPixel(pt.X, pt.Y);
    if (cx.GetBrightness() < 0.01f) return;  // optional, to prevent filling a black grid
    Rectangle bmpRect = new Rectangle(Point.Empty, bmp.Size);
    Stack<Point> stack = new Stack<Point>();
    int x0 = pt.X;
    int y0 = pt.Y;

    stack.Push(new Point(x0, y0) );
    while (stack.Any() )
    {
        Point p = stack.Pop();
        if (!bmpRect.Contains(p)) continue;
        cx = bmp.GetPixel(p.X, p.Y);
        if (cx.ToArgb() == c0.ToArgb())  //*
        {
            bmp.SetPixel(p.X, p.Y, c1);
            stack.Push(new Point(p.X, p.Y + 1));
            stack.Push(new Point(p.X, p.Y - 1));
            stack.Push(new Point(p.X + 1, p.Y));
            stack.Push(new Point(p.X - 1, p.Y));
        }
    }
}

Note: (*) Color equality will fail if one of the colors is a known or named color. So we need to convert to a common format..
Update
I have updated the code to include a function that will scale a mouse click location to an image pixel point; now it will work with SizeMode=StretchImage as well, so you can work on the whole image..
static Point scaledPoint(PictureBox pb, Point pt)
{
    float scaleX = 1f * pb.Image.Width / pb.ClientSize.Width;
    float scaleY = 1f * pb.Image.Height / pb.ClientSize.Height;
    return  new Point((int)(pt.X * scaleX), (int)(pt.Y * scaleY));
}

Of course you can then save the Image.
Note that your original image is 4bpp and must be converted to 24bpp or better before coloring..
Also note that for SizeMode=Zoom the calculations are a little more involved. Here is an example that should work with any SizeMode.:
static Point scaledPoint(PictureBox pbox, Point pt)
{
    Size si = pbox.Image.Size;
    Size sp = pbox.ClientSize;
    int left = 0;
    int top = 0;

    if (pbox.SizeMode == PictureBoxSizeMode.Normal ||
        pbox.SizeMode == PictureBoxSizeMode.AutoSize) return pt;
    if (pbox.SizeMode == PictureBoxSizeMode.CenterImage)
    {
        left = (sp.Width - si.Width) / 2;
        top = (sp.Height - si.Height) / 2;
        return new Point(pt.X - left, pt.Y - top);
    }
    if (pbox.SizeMode == PictureBoxSizeMode.Zoom)
    {
        if (1f * si.Width / si.Height < 1f * sp.Width / sp.Height)
            left = (sp.Width - si.Width * sp.Height / si.Height) / 2;
        else
            top = (sp.Height - si.Height * sp.Width / si.Width) / 2;
    }

    pt = new Point(pt.X  - left, pt.Y - top);
    float scaleX = 1f * pbox.Image.Width / (pbox.ClientSize.Width - 2 * left) ;
    float scaleY = 1f * pbox.Image.Height / (pbox.ClientSize.Height - 2 * top);
    return new Point((int)(pt.X * scaleX), (int)(pt.Y * scaleY));
}


text:
Q: Custom Icon not Showing in Play Store Today I created a custom image for my app and this includes the custom icon on what should it look in Play Store however when we upload it using Admin Console the uploaded apk files has only an icon of Green Background with White Suitcase. Our custom icon does not show. How to fix it? Is there something we forgot?

A: Tag <application> in AndroidManifest.xml has two attributes for you app icon:
<application
    android:icon="@mipmap/ic_launcher"
    android:roundIcon="@mipmap/ic_launcher_round">
...
</application>

android:roundIcon is used on supported devices. Check if you have set these two types of icon

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get timestamp difference using Ant I need to calculate time difference using Ant.
Basically it has 2 variables. One is assigned the current time, and the other one has a different time. I need to get the time difference using Ant. Something like below. If anyone have code please reply.
variable a = current time;
variable b = different time
echo (a - b) ;

A: Here is a much simpler solution:
<script language="javascript">
  project.setProperty('startTime', new Date().getTime());
</script>
...
<script language="javascript">
  project.setProperty('elapsedTime', new Date().getTime() - startTime)
</script>
<echo>Elapsed time: ${elapsedTime} ms</echo>

A: Alternative to @LeFunes answer (and uses the tstamp task)
<tstamp prefix="task.start">
<format property="millis" pattern="SSS"/>
</tstamp>
<tstamp prefix="task">
  <format property="start" pattern="E, dd MMM YYYY hh:mm:ss"/>
</tstamp>
<time-consuming-task/>
<tstamp prefix="task.stop">
<format property="millis" pattern="SSS"/>
</tstamp>
<tstamp prefix="task">
  <format property="stop" pattern="E, dd MMM YYYY hh:mm:ss"/>
</tstamp>
<script language="javascript">
  project.setProperty("task.diff",
    Math.abs(
      (Date.parse(project.getProperty("task.stop")) +
         +project.getProperty("task.stop.millis")) -
      (Date.parse(project.getProperty("task.start")) +
         +project.getProperty("task.start.millis"))))
</script>
<echo>
  task completed in ${task.diff} ms
</echo>

NOTE:
 this doesn't consider milliseconds
 updated to consider the milliseconds

A: <?xml version="1.0" encoding="UTF-8"?>
<project name="TEST ANT" default="test" basedir="..">
    <target name="test" description="">

        <script language="javascript"> <![CDATA[
            var ts1 = new Date();
            project.setProperty("current.time.1", ts1.toLocaleString());
            project.setProperty("current.time.1.mill", ts1.getTime());
        ]]></script>
        <echo>Timestamp 1: ${current.time.1} [${current.time.1.mill}]</echo>

        <sleep milliseconds="1300"></sleep>

        <script language="javascript"> <![CDATA[
            var ts2 = new Date();
            project.setProperty("current.time.2", ts2.toLocaleString());
            project.setProperty("current.time.2.mill", ts2.getTime());
        ]]></script>
        <echo>Timestamp 2: ${current.time.2} [${current.time.2.mill}]</echo>

        <script language="javascript"> <![CDATA[
            project.setProperty("res", project.getProperty("current.time.2.mill")-project.getProperty("current.time.1.mill"));
        ]]></script>
        <echo>Diff: ${res}</echo>
    </target>
</project>

A: If you don't want to use JavaScript, you can use the Math task provided by the Ant-Contrib utilities.
The Ant-Contrib are fairly old, and I don't know if anyone is still maintaining them, but they're very popular to use in Ant build files since they add some very useful tasks.
I recommend including the ant-contrib-1.0b3.jar into the project itself. When other people use your project, they'll also have the Ant-Contrib jar. I put ant-lib/ac/ant-contrib-1.0b3.jar under your project's home directory. I use ant-lib for all of my optional jars:
<project name="my.project"
    ...
    xmlns:ac="antlib:net.sf.antcontrib">

   ...

    <taskdef uri="antlib:net.sf.antcontrib"
        resource="net/sf/antcontrib/antlib.xml">
        <classpath>
            <fileset dir="${basedir}/antlib/ac"/>
        </classpath>
    </taskdef>

    ....

Now, you can use your math task like this:
    <ac:math result="time.diff"
        operation="-"
        operand1="${diff.time}"
        operand2="${initial.time}"/>

The ac: is an XML namespace that was declared in your <project/> entity, and was connected to your tasks via the uri parameter in the <taskdef/> entity. This allows you to have multiple optional Ant tasks that may have tasks with duplicate names. This is a good idea in case you use multiple optional task libraries that have the same task names.


text:
Q: How to fix step size in do loop? I apply the following command:
Do[Print[var[u] = u], {u, -1, 1, 0.1}]

It produces out put. But when i recall the value var[-0.4] as below:
In[2]:= var[-0.4]

Out[2]= var[-0.4]

It produces var[-0.4] instead of the value.
It can be handled if i replace step size 0.1 by 1/10 but i want to work with decimal point form.
It may be due to floating point. If any one may help to give a good suggestion on it. It will be highluy appreciated.

A: It is a precision issue
Clear[var]

Do[var[u] = u, {u, -1, 1, 0.1}]

DownValues[var][[15]]//FullForm

(*  RuleDelayed[HoldPattern[var[0.40000000000000013`]], 0.40000000000000013`]  *)

Consequently, you would need to enter
var[0.40000000000000013]

(*  0.4  *)

%//InputForm

(*  0.40000000000000013  *)

To avoid the precision issue, use exact numbers
Clear[var]

Do[var[u] = u,{u, -1, 1, 1/10}]

Then
var[4/10] == var[2/5] == 2/5

(*  True  *)


text:
Q: Draggable background/area in vis.js timeline for selecting a time period We would like to have an editable time range on the vis.js timeline in the same way as an event can be edited. So 1) the user could drag backwards or forwards in time if they grab by the middle, and also 2) edit the length by grabbing and dragging either and of the area.
The editing and their callbacks work very well on the items themselves, but not on the backgrounds. The goal is to let the user to select an interval.

A: I think it's not possible to drag backgrounds or change their size like the items. But what you can do is to add new items with a field to differentiate them from others items and with custom css, you can modify them to look like backgrounds and the drag and resize will works on these "new" backgrounds.


text:
Q: JQuery Detect Scroll at Bottom I wish to achieve content load when the user scrolls to the bottom of the page.
I am having a problem. It works fine on desktop browsers but not on mobile. I have implemented a dirty fix to make it work on the iPhone, but is not optimal as it won't work on other sized mobile devices.
My website is www.cristianrgreco.com, scroll down to see the effect in action
The problem is adding the scroll and the height do not equal the height on mobile devices, whereas they do on desktop browsers.
Is there a way to detect for mobile browsers?
Thanks in advance.
Below is the code currently being used:
$(document).ready(function () {
        $(".main").hide().filter(":lt(3)").show();
        if ($(document).height() == $(window).height()) {
            // Populate screen with content
        }
        else if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
            window.onscroll = function () {
                if ($(document).height() - $(window).scrollTop() <= 1278) {
                    // At the moment only works on iPhone
                }
            }
        }
        else {
            $(window).scroll(function () {
                if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
                    // Works perfect for desktop browsers
                }
            })
        }
})

A: If you can, you should really avoid trying to hit an exact number.
Using Stelok's function above, you can test like this:
if ($win.height() + $win.scrollTop() > (getDocumentHeight()-10)) {

It's a bit softer - the user may not have quite scrolled to the exact last pixel but thinks he/she is at the bottom.

A: An improved jQuery version of the code
var scrollRefresh = {
    pastTop: false,
    pastBottom: false,
    previous: 0,
    bottom: function(callback) {
      var pBottom = $(window).height() + $(window).scrollTop() >= $(document).height();
      if(!this.pastBottom && pBottom) {
        callback($(window).height() + $(window).scrollTop());
        this.pastBottom = true;
      } else {
        if(!pBottom) this.pastBottom = false;
      }
      this.previous = $(window).scrollTop();
    },
    top: function(callback) {
      var pTop = $(window).scrollTop() < this.scrollPrevious && $(window).scrollTop <= 0;
      if(!this.pastTop && pTop) {
        callback($(window).scrollTop());
        this.pastTop = true;
      } else {
        if(!pTop) this.pastTop = false;
      }
      this.previous = $(window).scrollTop();
    }
  }

  $(window).scroll(function() {
    scrollRefresh.top(function(pos) {
      console.log("Loading top. " + pos);
      alert("scrolled to top"); //You should delete this line
    });
    scrollRefresh.bottom(function(pos) {
      console.log("Loading bottom. " + pos);
      alert("scrolled to bottom"); //You should delete this line
    });
  });

A: This is what worked for me:
(window.innerHeight + window.scrollY) == $(document).height()

Found here:
Javascript: How to detect if browser window is scrolled to bottom?

A: For anyone who looks here later, I solved this by adding height=device-height to the meta viewport tag:
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0">

You can then carry on using $(document).scroll(function(){});
This worked with iOS 5

A: Bullet proof way to get document height on all browsers:
function getDocumentHeight() {
    return Math.max(
        Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
        Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
        Math.max(document.body.clientHeight, document.documentElement.clientHeight)
    );
}

A: Using jquery and Strelok's getDocumentHeight() below (cheers!) I found the following worked pretty well.  Testing for equality didn't work for me as the iPhone only registered a scroll value at the end of the slide which was actually greater than the document height:
$(window).scroll(function () {
  var docHeight = getDocumentHeight();
  if ($(window).scrollTop() + $(window).height() >= docHeight) {
    // Do stuff
  }
});

A: Have you added the meta tag for iphones which sets the content size to the viewport of the phone?
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">

EDIT:
So I tried this on my phone (android, gingerbread) and the issue wasn't so much the code not working it was the content displayed does not force the page to scroll. As soon as I zoomed in and scrolled down more content dynamically loaded. You could try adding content until the content added is greater than $(window).height();

A: you can also use an endless scroll plugin: https://github.com/fredwu/jquery-endless-scroll
https://github.com/paulirish/infinite-scroll
i'm using the endless scroll and it works great on my laptop and iphone

A: Here is an aggregate of the other answers which works very well for me. It could be written as a jQuery plugin sometime.
// Handles scrolling past the window up or down to refresh or load more data.
var scrolledPastTop = false;
var scrolledPastBottom = false;
var scrollPrevious = 0;

function getDocumentHeight() {
  return Math.max(
      Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
      Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
      Math.max(document.body.clientHeight, document.documentElement.clientHeight)
  );
}

function bottomScrollRefresh(callback) {
  var pastBottom = $window.height() + $window.scrollTop() > getDocumentHeight();
  if(!scrolledPastBottom && pastBottom) {
    callback($window.height() + $window.scrollTop());
    scrolledPastBottom = true;
  } else {
    if(!pastBottom) scrolledPastBottom = false;
  }
  scrollPrevious = $window.scrollTop();
}

function topScrollRefresh(callback) {
  var pastTop = $window.scrollTop() < scrollPrevious && $window.scrollTop() <= 0;
  if(!scrolledPastTop && pastTop) {
    callback($window.scrollTop());
    scrolledPastTop = true;
  } else {
    if(!pastTop) scrolledPastTop = false;
  }
  scrollPrevious = $window.scrollTop();
}

To use this in your code, add something like this:
window.onscroll = function() {
  topScrollRefresh(function(pos) {
      console.log("Loading top. " + pos);
  });
  bottomScrollRefresh(function(pos) {
    console.log("Loading bottom. " + pos);
  });
};

Works great for my PhoneGap/Cordova app.

A: Though the question was asked 5 years ago, still it is more than relevant in today's UI/UX context. And I would like to add my two cents.
var element = document.getElementById('flux');
if (element.scrollHeight - element.scrollTop === element.clientHeight)
{
    // element is at the end of its scroll, load more content
}

Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Determine_if_an_element_has_been_totally_scrolled


text:
Q: get image hight and with in Titanium I need to get the hight and width of an image from a server that i need to show directly to the user.
so e have tried to create a imageView and put the image in it so i could read the hight and width of the imageView
var image = Ti.UI.createImageView({
                image : //host Site,
                width : "auto",
                height : "auto"
            });

var hight = image.height;
var width = image.width;

but it returns always hight = auto and width = auto.
how can i get the height and width like fro example hight = 630 and width = 320?

A: First, listen to the load or postlayout event : http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.ImageView-event-load
Instead this event, you can get the Dimension of the ImageView : http://docs.appcelerator.com/platform/latest/#!/api/Titanium.UI.ImageView-method-getRect like this :
var rect = image.getRect();

A: I figured out how to get the hight and width of an image
 var image = Ti.UI.createImageView({
                image : //host Site,
                width : "auto",
                height : "auto"
            });

var hight = image.toBlob().height;
var width = image.toBlob().width;

i hade only to add toBolob() where i'm trying to get the height and width


text:
Q: Why when I use stack() the number of rows increase? I tried to merge the two columns begin and end to Flag and Timestamp with this piece of code:
print(df_DisponibilityAlarm.shape)

df_DisponibilityAlarm = (df_DisponibilityAlarm.stack()
 .rename_axis([None, 'Flag'])
 .reset_index(level=1, name='Timestamp'))

print(df_DisponibilityAlarm.shape)

The result is :
                         begin                          end
0                          NaN  2019-10-21  07:48:28.272688
1                          NaN  2019-10-21  07:48:28.449916
2  2019-10-21  07:48:26.740378                          NaN
3  2019-10-21  07:48:26.923764                          NaN
4                          NaN  2019-10-21  07:48:41.689466
5  2019-10-21  07:48:37.306045                          NaN
6                          NaN  2019-10-21  07:58:00.774449
7  2019-10-21  07:57:59.223986                          NaN
8                          NaN  2019-10-21  08:32:37.004455
9  2019-10-21  08:32:35.755252                          NaN

(13129, 2)
(13140, 2)

    Flag                    Timestamp
0    end  2019-10-21  07:48:28.272688
1    end  2019-10-21  07:48:28.449916
2  begin  2019-10-21  07:48:26.740378
3  begin  2019-10-21  07:48:26.923764
4    end  2019-10-21  07:48:41.689466
5  begin  2019-10-21  07:48:37.306045
6    end  2019-10-21  07:58:00.774449
7  begin  2019-10-21  07:57:59.223986
8    end  2019-10-21  08:32:37.004455
9  begin  2019-10-21  08:32:35.755252

It works ! But when I looked closely, I see when I use "stack()" the number of the rows increase... I don't understand why, can you explain me please ? I need this to validate my starting hypothesis.

A: EDITED
Inherently, stack() function makes your dataset longer BUT as you can see in your sample printout:
rows that contained NaN are not included after stacking. <-------------

Consider the test case below, added TEST_VALUE:
begin,end
NaN,2019-10-21  07:48:28.272688
NaN,2019-10-21  07:48:28.449916
2019-10-21  07:48:26.740378,NaN
2019-10-21  07:48:26.923764,NaN
NaN,2019-10-21  07:48:41.689466
2019-10-21  07:48:37.306045,TEST_VALUE
NaN,2019-10-21  07:58:00.774449
2019-10-21  07:57:59.223986,NaN
NaN,2019-10-21  08:32:37.004455
2019-10-21  08:32:35.755252,NaN

df = pd.read_clipboard(sep=',')

print(df.shape)
print(df.stack().shape)
print(df.stack())

(10, 2)
(11, )
0  end      2019-10-21  07:48:28.272688
1  end      2019-10-21  07:48:28.449916
2  begin    2019-10-21  07:48:26.740378
3  begin    2019-10-21  07:48:26.923764
4  end      2019-10-21  07:48:41.689466
5  begin    2019-10-21  07:48:37.306045
   end                       TEST_VALUE
6  end      2019-10-21  07:58:00.774449
7  begin    2019-10-21  07:57:59.223986
8  end      2019-10-21  08:32:37.004455
9  begin    2019-10-21  08:32:35.755252

# this part is strange
print(df.stack()[5])
begin    2019-10-21  07:48:37.306045
end                       TEST_VALUE
dtype: object

It's pretty strange how index 5 is as compared to the rest and I don't have an answer as to why it is a type of multiindex and the rest in the Series are not, but let us continue...
As you can see this added an extra row for TEST_VALUE and AGAIN any value with NaN is not included in the stacked version.
I would "standardize" or make sure your data contains either NaN or date, or fill your NaN with some other value using fillna().
If you wanted to keep your data the way it is, you could also process your data in chunks to zero in on WHERE(in my sample its TEST_VALUE) the data is not uniformed like so:
# read df in as an iterator with chunks

df1 = pd.read_clipboard(
                    sep=',',
                    chunksize=3  # change this to whatever chunksize you need
)

def test_chunks(df_iterator):
    """
    Function that compares original df chunk size shape to stacked chunksize shape
    Returns: original chunk where there is a mismatch in shapes
    """
    for df_chunk in df_iterator:
        original = df_chunk.shape[0]
        stacked = df_chunk.stack().shape[0]
        if original != stacked:
            return df_chunk

bad_chunk = test_chunks(df1)
print(bad_chunk)

                         begin                          end
3  2019-10-21  07:48:26.923764                          NaN
4                          NaN  2019-10-21  07:48:41.689466
5  2019-10-21  07:48:37.306045                   TEST_VALUE

So, although I cannot be sure because I don't have access to your full data, my verdict would be that it is a data uniformity issue.
I hope this is helpful.


text:
Q: Google Sign in doesn't return any result when 'Use another account' to sign in This seems to be a basic feature but after following the signing-in tutorial, it only works if I choose the account that is already registered on the device.
After choosing 'Use another account' and completing some steps to authenticate it looses the call-back result, (onActivityResult is not called).
I use GoogleSignInOptions: no exception occurs and I can't add any listener to detect exceptions.
However, GoogleApiClient works fine but there are some deprecated methods, thus I decided to switch to GoogleSignInOptions to avoid deprecation issues.
Initizlization:
googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

googleSignInClient = GoogleSignIn.getClient(this, googleSignInOptions);

when click:
signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signIn();
            }
        });

private void signIn() {
        googleSignInClient.signOut();
        Intent signInIntent = googleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, 123);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123 && data != null) {
            handleSignInResult(data);
        }
    }

    private void handleSignInResult(Intent data) {
        Task<GoogleSignInAccount> signInTask = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount googleSignInAccount = signInTask.getResult(ApiException.class);
            if (googleSignInAccount != null) {
                updateUI(googleSignInAccount);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

Anyone can help please?

A: UPDATE: This bug has now been fixed in the Oauth2 Library

So I ran into the same issue as well.  What I have found is that this is an open issue reported back in March.  So this is probably not an issue with your code.
I found another stackoverflow question about the difference between Oauth2 and googleAuthUtil, using the other library mentioned, I have found that this bug doesn't exist.
I imported this package into my gradle
implementation('com.google.api-client:google-api-client-android:1.23.0') {
    exclude group: 'org.apache.httpcomponents'
}

and authenticate off of the GoogleAccountCredential object.
    GoogleAccountCredential credential = new GoogleAccountCredential(context, scope);
    startActivityForResult(credential.newChooseAccountIntent(), resultCode);

You need GET_ACCOUNTS permission for this method.


text:
Q: Windows Server Service Bus | Deployment So far I'm aware that the supported topologies range from single node installation to 3 node installation of Windows Server Service Bus.
What would be the expected behaviour if a farm of only two nodes is created? Is it better to use just one node rather than two nodes?
Thanks in advance.

A: As per my knowledge performance of most messaging scenarios is bound by SQL server I/O and to optimize the SQL Server hard disks for write performance. If the server is equipped with sufficient memory, SQL Server rarely reads data from disk. If the server is equipped with more than two disks, stripe the disks that contain the log and data stores.
Considering above points when tuning the SQL Server that hosts the Service Bus for Windows Server container databases  it always perform better for 3 nodes installation rather than two.

A: As discussed in a Microsoft forum the only supported topologies are single node or three nodes.
On a two node scenario if one of the nodes fail, the whole system will fail.


text:
Q: Will upgrading my AWS EC2 t3.small instance to t3.medium give better CPU performance? I'm currently using an EC2 t3.small instance (unlimited mode) for a service that is CPU bound and usually runs at 60-90% of max CPU utilization, but occasionally hits 100%. I want to upgrade to an instance with greater CPU performance so I don't hit max CPU utilization.
My question is: will upgrading to a larger t3 instance (e.g. t3.medium) give more CPU performance? From what I've been able to discern, the t3.medium still has 2 vCPUs just like t3.small. So will it give the same performance, just with more RAM and a higher baseline utilization/more CPU credits? In that case, the t3.xlarge with 4 vCPUs seems to be the next upgrade in the t3 family that gives more CPU capacity. But if that is the case, it seems like a c5.large would be the cheaper upgrade step.
Is my thinking correct here or am I missing something?

A: After experimenting with different instance types, I came to the following conclusions:

*

*Tried the c5a.large instance. It had very similar CPU performance to a t3.small instance. Still hitting the 100% utilization cap.

*c5.large instance: Slightly better performance than c5a.large, but still hitting the CPU cap.

*t3a.xlarge instance: with 4 vCPUs, I had much more CPU capacity and did not hit 100% CPU. I was using about 30 CPU credits per hour above the baseline, so I ended up with...

*t3.xlarge: slightly better performance than t3a.xlarge and therefore using fewer CPU credits (about 15 per hour) which made this more cost effective than a t3a.xlarge.

So, in conclusion, a t3.medium was indeed not a suitable upgrade over a t3.small for increased CPU capacity. A c5.large was marginally better, but the real upgrade solution was going to a t3a.xlarge or t3.xlarge.


text:
Q: I want to edit a test case in ALM while QTP script is running simultaneously on the same machine? How can we do that? I want to edit test case which is present in ALM while QTP script is running on the same machine at the same time. Can anybody please suggest me how to do this?

A: Below the checkout description coming from REST API library.
A different solution can be to implement a single point of report. It means you can create your own tool that is reporting real time to QC and it is also able to get real time input by QTP tool. (of course it is then more complicated)
Hope this can help you a bit! Have a nice day.
check-out description:
Checks out an entity.
URL
/qcbin/rest/domains/{domain}/projects/{project}/{entity collection}/{Entity ID}/versions/check-out
Remarks
POST the comment and version number with an XML compliant with the check-out-parameters Schema.
The version is optional. If not specified, the latest version is checked out.
The comment is optional. A comment can be entered either on check-in or check-out. If a comment is entered on check-in, it overrides any comment entered on check-out.
If neither a comment nor a version is specified, the input XML is not required. If no XML is sent, do not specify a content-type header.


text: Q: @IBInspectable not working either with making class as @IBDesignable i am trying to make my variable initialization custom and put in utilities of the story board but it is not coming in the utilities section my UIView class implementation can appear on my storyboard using @IBDesignable i have no reputation to put images


text:
Q: Sequel makes duplicate entries I'm using Sequel with Sinatra and I've been trying it out and I noticed that it creates duplicate entries (3x).I've tried to debug it but in the end I couldn't understand why is this occurring.
This is my code:
require 'sinatra'
require 'mysql2'
require 'sequel'

 DB=Sequel.connect(
                      :adapter => "mysql2",
                      :host =>"localhost",
                      :user => "root",
                      :password => "",
                      :database => "test"
                      )
  if !DB.table_exists? :users
    DB.create_table :users do
      primary_key :id
      String :username ,:size=>20 #,:unique=>true
      String :password ,:size=>30
  end
  puts "Schema created"
else
  puts "Already exists"
end

  class User < Sequel::Model;end

class Test < Sinatra::Base

  get '/:username' do
    "Creating user"
    User.create(:username => "#{params['username']}",:password => "test")
  end
end


text:
Q: About CPU usage function I'm trying to run this function that shows you the % CPU usage (not application, global)
Private Function USO_CPU() As Integer
    Dim obj_WMI As Object, obj_INFO_CPU As Object, Porcentaje As Integer

    obj_WMI = GetObject("winmgmts:").InstancesOf("Win32_Processor")
    For Each obj_INFO_CPU In obj_WMI
        If obj_WMI.Count > 1 Then
            Porcentaje = Porcentaje + obj_INFO_CPU.LoadPercentage
        Else
            Porcentaje = obj_INFO_CPU.LoadPercentage
        End If
    Next

    If obj_WMI.Count > 1 Then
        Porcentaje = Porcentaje \ obj_WMI.Count
        obj_WMI = Nothing
        obj_INFO_CPU = Nothing
    End If

    USO_CPU = Porcentaje
    Exit Function

End Function

But I get this:

Not found exception 'System.InvalidCastException' en Microsoft.VisualBasic.dll
Info: Conversion of 'DBNull' into 'Integer' not valid

I know that the error is caused by variable types, but I tried to set "Porcentaje" as String, Integer, etc and the error persists.
How can I fix this?

A: Your query is returning some null data that you need to convert to your datatype
 Dim loadPerc = If(Convert.IsDBNull(obj_INFO_CPU.LoadPercentage), 0, Convert.ToInt32(obj_INFO_CPU.LoadPercentage))

---- update -----
For Each obj_INFO_CPU In obj_WMI
    Dim loadPerc = If(Convert.IsDBNull(obj_INFO_CPU.LoadPercentage), 0, Convert.ToInt32(obj_INFO_CPU.LoadPercentage))

    If obj_WMI.Count > 1 Then
        Porcentaje = Porcentaje + loadPerc
    Else
        Porcentaje = loadPerc
    End If
Next


text:
Q: How to fix fonts in Windows Mozilla Firefox? Whenever I format my computer, I usually just copy/paste all the .ttf and .fon files into the Fonts system folder.
I can't be sure 100%, but I think that after I did that, Firefox stopped displaying some website's fonts correctly, and I mean the usual default ones, like Arial, Helvetica, etc.
I don't have this problem in any other program, other than Firefox.
Here is a screenshot of what Digg looks on my laptop right now:

It looks weird, the font is messed up somehow.
How do I fix it? I'm on Windows 7, Firefox 3.6.10.

A: This specific problem is due to installing a version of the Helvetica font (very commonly used on the web) that either Windows or Firefox can't display. To confirm, all you have to do is paste the following text in your Firefox address bar and hit enter:
data:text/html,
Helvetica
   abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

Helvetica Neue
  abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

If it displays as weird symbols, then you can be sure that's your problem.
To fix it, all you have to do is go to %WINDIR%\Fonts and delete all the fonts named Helvetica.
If for some reason, Windows doesn't allow you to, you have to go to the registry, navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts and then delete all the entries that have Helvetica on their name.
If you are using Windows 7 64-bit, you also have to delete the Helvetica entries from the following registry key.
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\Fonts

After this, you only need to reboot your computer and the fonts will be displayed correctly again. At least that fixed it for me.

A: I was just struggling with the same problem (albeit with Google Chrome) and stumbled upon this topic. Because I'm using a PC at work, I don't have the privileges to make registry edits. I found another workaround however, which probably only works on Chrome, but at least it fixed the problem for me. So although it's not about Firefox, I still want to share it, in case somebody else ends up in this topic as well.

*

*Open Google Chrome

*Open a new tab and enter the following in the address bar:

chrome://flags/#disable-direct-write

*Click "enable" to enable this switch, disabling the use of Microsoft DirectWrite by Google Chrome.

*Close and re-open Chrome.

Source & credits: https://youtu.be/cHHBnHRcOjQ

A: Go to your firefox preferences, under the "Content" tab there should be a "Default Font" combobox. Try switching the setting to one of the usual Microsoft fonts. If not, it is possible that you simply don't have the Microsoft fonts installed. Apparently, you can get some of the core fonts here: http://web.nickshanks.com/fonts/microsoft-core-web-fonts


text:
Q: css arrange two elements one after another How can i display the two links for small screen one after another. Now the two links are left and right. But i want those link one up and another at bottom.

Text

                        XX Download
                        BB Download

@media screen and (max-width:580px){
  .homeContent {
    h1 {
      font-size: 3rem !important;
    }
    .content {
      .pdf {
        a {
          // one after another
        }
      }
    }
  }
}

A: Adding display:block on a will do what you want, like so (I am using css so that it works here):

@media screen and (max-width: 580px) {
  a {
    display: block;
  }
}

Text

      XX Download
      BB Download


text:
Q: SQL Query Sorting I have a table which I want to run a query against to pull out data to a csv file. The data needs to be sorted by username and I only want output of people created within the last seven days.
So far I can pull out the data that I need, but can't quite figure how to achieve the piece surrounding only the last seven days. My query looks like this at present;
SELECT
  user_name,
  created_date
FROM DATABASENAME.dbo.tbl_user
WHERE user_name LIKE 'guest-%'

A line of the resulting output (once in the csv) looks like;
guest-12343,2016-09-20 19:57:50.347

Can anyone recommend how I might be able to adapt the statement to be more selective on with the data in the created_date column?

A: For getting data within 7 days add this in your where clause
AND created_date >= DATEADD(day, -6, convert(date, GETDATE()))

For Sorting with user name add this @end
ORDER BY user_name

So final Query will be :
SELECT user_name, created_date FROM DATABASENAME.dbo.tbl_user WHERE user_name like 'guest-%' created_date >= DATEADD(day, -7, convert(date, GETDATE())) ORDER BY user_name

A: SELECT user_name, created_date
FROM DATABASENAME.dbo.tbl_user
WHERE
    user_name like 'guest-%'
    AND Created_Date >= CAST(GETDATE() - 7 AS DATE)
ORDER BY user_name

Assuming you want from 12:01 AM 7 days ago and that Created_Date can never be greater than Now [Getdate()]

A: You can use created_date in your WHERE clause.  Now the question is how do you define "last seven days."  If you want 7 * 24 hours before now, it would be
SELECT user_name, created_date
FROM DATABASENAME.dbo.tbl_user
WHERE user_name like 'guest-%'
  AND created_date >= GETDATE() - 7

If you want your 7 day period to be 6 full days plus today, it would be:
SELECT user_name, created_date
FROM DATABASENAME.dbo.tbl_user
WHERE user_name like 'guest-%'
  AND created_date >= CONVERT(DATE, GETDATE() - 6)

Or if you want your 7 day period to be 7 full days not including today, it would be:
SELECT user_name, created_date
FROM DATABASENAME.dbo.tbl_user
WHERE user_name like 'guest-%'
  AND created_date >= CONVERT(DATE, GETDATE() - 7)
  AND created_date < CONVERT(DATE, GETDATE())

This is assuming created_date is storing dates in the server's timezone. If it has UTC dates, change GETDATE() to GETUTCDATE().


text:
Q: What is occurring inside the lattice structure of metal when compression happens? I was browsing reddit and saw this post. It is a gif of a factory, with a huge press squashing a hot chunk of metal.
I'm specifically interested in the behavior that is happening after the initial press when the slag falls off. When the press starts compressing the metal, it begins shooting off what looks like to be sparks.

The only way I can think of explaining that is with the metallic bond's "sea of electrons" model.

Which when the lattice structure starts to be compressed, there is less space for the valence electrons to freely occupy, and thus a greater electromagnetic potential from neighboring electrons. This would mean that the valence electrons would have a higher possibility of being shot off in the form of sparks.
What I'm not understanding is, if the chunk of metal has had an increase in EM potential due to compression, why does that potential not force it back into it's previous position when the press is lifted? Are the valence electrons lost in the sparks enough to create equilibrium at the new pressure?

A: when it is being deformed in the hot press, the atoms in its lattice are being pushed past one another, and the solid metal flows like stiff taffy.
The slag on the outside is brittle, and when it exfoliates, a fresh new red-hot iron surface is exposed to air. It violently oxidizes, producing flames and sparks.
Each time the ingot is deformed more, the oxide layer covering the surface of the iron cracks and splits, exposing crevices of hot iron to the air, and in those zones, the iron oxidizes again, and shoots out tiny hot flames.
Those flames are not electric sparks.


text:
Q: if not found any page or url then redirect index.php I want to redirect like http://localhost/project/g47sh to http://localhost/project/index.php
But when I am write on URL http://localhost/project/g47sh then 404 error is generated so I want to if any page or directory not found the redirect index.php and also pass not found URL path.


text:
Q: Django serving static images defined inside CSS file I'm running django 1.5.1 and I'm trying to serve some static images defined inside my css. I have no problem serving the css itself and static images defined in the templates. Also styles defined in the css are applied correctly to my template. The only things that don't work are the images defined inside the css.
Here is a sample of my css file defining a class that includes a static image:
.outer_banner
{
    background:url(/images/banner2.png) bottom center no-repeat;
    padding:300px 0;
}

Here is an example of my template using the class defined in the css:
{% load staticfiles %}
<!DOCTYPE html>
<html>
    <head>

        <link href="{% static 'css/style.css' %}" rel="stylesheet" type="text/css" />

        <!-- more header stuff here -->
    </head>

<body>

    <section class="outer_banner">

        <!-- other stuff here -->

    </section>
</body>
</html>

Thanks!

A: Well you're problem has nothing to do with Django and that's a good thing.  It's simply the path to your images is not being served correctly by your CSS file.
If you have something like this folder structure;
static
    images
        banner2.png
    css
        main.css
    js

In order for your css to find your image assuming that is the folder structure you need to move back one folder so the url to your image inside your css file would look like this;
.outer_banner
{
    background:url(../images/banner2.png) bottom center no-repeat;
    padding:300px 0;
}


text:
Q: GeoIP2 Javascript ONLY redirecting to else but not specific countries The following GeoIP2 javascript is ONLY redirecting to the "else" URL regardless of country/location. It isn't redirecting to the correct URL for that country but instead just sending all traffic to the "else" URL... what have I done wrong and how can I fix it?

<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
<script language="JavaScript">
geoip2.country(
    function (response) {

        if (response.country.iso_code == "AU") {
            window.location = "http://track.cpapower.net/tiny/nEZJp?transid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&_ocid=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&offerid=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "CO") {
            window.location = "http://funloadia.com/whatsapp/coweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "DE") {
            window.location = "http://funloadia.com/whatsapp/demob.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "EC") {
            window.location = "http://funloadia.com/whatsapp/ecweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "FR") {
            window.location = "http://funloadia.com/whatsapp/frweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "ES") {
            window.location = "http://funloadia.com/whatsapp/esweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "KE") {
            window.location = "http://funloadia.com/whatsapp/keweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "MX") {
            window.location = "http://funloadia.com/whatsapp/mxweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "MY") {
            window.location = "http://funloadia.com/whatsapp/myweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "NL") {
            window.location = "http://funloadia.com/whatsapp/nlweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "PT") {
            window.location = "http://funloadia.com/whatsapp/myweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "RO") {
            window.location = "http://funloadia.com/whatsapp/myweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "SG") {
            window.location = "http://funloadia.com/whatsapp/myweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        if (response.country.iso_code == "ZA") {
            window.location = "http://funloadia.com/whatsapp/myweb.php?sid=<?php echo str_replace("-", " ", $_GET["sid"]); ?>&sid2=<?php echo str_replace("-", " ", $_GET["sid2"]); ?>&sid3=<?php echo str_replace("-", " ", $_GET["sid3"]); ?>"
        }

        else {
            window.location = "http://funloadia.com/whatsapp/"
        }
    }
);
</script>

A: I think the problem with your code is you have if conditions and else at the end, which will be executing in any case, so try using if..elseif..else, as:
if (response.country.iso_code == "AU") {
    window.location = ". . . ";
}
else if (response.country.iso_code == "CO") {
    window.location = ". . .";
}
. . .
else {
    window.location = "http://funloadia.co..";
}

A: I believe I fixed this. I needed to add "else" in front of "if" for the other countries! Just like in GeoIP1


text:
Q: Javadoc comments for class members I have a lots of class member variable. Each of them is important and would ideally require a comment explaining what it is about. If I try to add element comment to each of them, it end up looking something like :
/**
 *
 */
private int[] violationCounterRise = new int[Consts.NUMBER_OF_PMU];
/**
 *
 */
private String eSeverity;
/**
 *
 */

And so on .. which makes code very messy and unreadable. Is there any other way to add javadoc comments to avoid clumsiness in this particular scenario ?

A: No, there isn't.  However, inserting a blank line may actually help readability.
/**
 *
 */
private int[] violationCounterRise = new int[Consts.NUMBER_OF_PMU];

/**
 *
 */
private String eSeverity;

Also, consider that JavaDoc for private fields is generated only if you enable the -private option.  Since private fields will only matter when looking at the source code, you might not need to generate them in the first place, in which case //-style comments would work too.
Finally, think about why you have so many member variables in the first place.  It may be the case that your class violates the Single Responsibility Principle and needs refactoring.


text:
Q: JavaScript - typeof Object vs Object() console.log(typeof Object)    => function
console.log(typeof Object())  => object

What is the explanation behind this ?
P.S - I'm a newbie to JavaScript.

A: I think you're having trouble grasping the concept of first-class functions. This happens a lot to Java programmers who start programming in JavaScript and expect it to be similar to Java because of the nomenclature. So let me make this clear:
JavaScript is nothing like Java.
First class functions are a difficult concept to understand if you've been exposed to too much Java dogma radiation.
The basic idea of first-class functions in JavaScript is that:
Functions are objects.
This is a really good thing because it means that we can pass functions as arguments to other functions and return functions from other functions. This allows us to do a lot of cool stuff. For example:
function compose(f, g) {
    return function (x) {
        return f(g(x));
    };
}

Here the compose function takes two other functions as parameters and returns another function which is mathematically equivalent to f . g. For example:
function thrice(x) {
    return 3 * x;
}

function plusOne(x) {
    return x + 1;
}

var thricePlusOne = compose(plusOne, thrice);

This is equivalent to writing:
function thricePlusOne(x) {
    return plusOne(thrice(x));
}

Once you get the hang of it functional programming will come naturally to you. It's very simple.
Anyway, let's talk about constructors. A constructor is a function which returns an object. For example Object is a constructor. Hence:
console.log(typeof Object); => function

I want you to think of the typeof operator as a function. If it helps, you could write it as follows:
console.log(typeof(Object)); => function

See what we are doing here? We're passing the typeof operator a constructor function. Hence console.log displays function.
On the other hand in the following code console.log displays object:
console.log(typeof Object()); => object
console.log(typeof(Object())); => object

The reason this happens is because you're calling Object and passing the return value of Object to console.log. In this case the return value of Object is an empty object (i.e. {}).
Note however that most constructors in JavaScript only return objects when you prefix the function call with the new keyword. This makes JavaScript code look more like Java. However all the native constructors (e.g. Object, Array, Function, Number, String, Boolean, etc.) allow you to omit the new keyword. Hence the following two statements are equivalent:
console.log(typeof Object()); => object
console.log(typeof new Object); => object

This is not usually true for user defined constructors. You can make constructors which allow you to omit new but that's beyond the scope of this answer.

A: Object is simply the name of a function and calling it as it is you're referring to the code of Fuzion (object in a nutshell is just the name of the container), this means that the function is executed.
Writing "object ()" instead're actually performing the function then the amount taken into account by your "if" is not the function itself but the value that the function returns.
Example:
 var a = function () {
      return "say hello";
 }

 b = a // -> b is a perfect copy of a (function)*
 c = a() // -> c is the returned string "say hello", if u write d = b () d has same value of c because write a() or b() fire the same function

* is the same if you write:
var b = function(){
   return "say hello";
}

Whenever you call a function with () javascript solve it, writing the name of the function without () JavaScript will consider the function itself.
example, write:
typeof Object() //--> object

is the same to write:
typeof {} //--> object

because javascript solve Object() function and consider the typeof the returned value.
my english suck... sorry.

A: Object is a function because you can call it using Object()
However what you do now when using typeof(Object()) is to call the function Object() first, take its return value and get the type of that return value, which is an object in this case.
However when you just call typeof(Object) then you don't execute the function Object(), instead you just check what type the variable Object is. And because this variable is a function you can call with Object() it tells you that typeof(Object) is a function


text:
Q: Hide element in mobile app but not in mobile browser I'm using a cloud application to build an intranet. One of the widgets uses HTML5 geolocation. The widget works as expected on desktop and mobile browsers.
However, the platform also has an app which is basically just a browser; on the app (smartphone and tablet), the widget does display anything.
I'm wondering if there's a media query that I can use to hide the widget only when using the app. I'd like it to still appear on mobile browsers though. If it's not possible through CSS, maybe with jQuery?


text:
Q: Apache Cassandra / Presto select query We have 2 node cluster with RF2.  When we select data using Presto and passing all partition key in where condition. Sometime data is returned and sometimes it is not though the cqlsh does return data everytime.  a high level summary is like this -
Table X.Y with partition keys A, B and C
when run select query like "select * from X.Y where A=1 and B=2 and C=3"  It sometimes returns data on one node and sometimes it return on both nodes and sometimes only on 1 node. I am trying to run query using Presto-CLI.  One interesting fact is that if I reduce the partition key from 3 to 2 in where condition and reformat the query like this -
"select * from X.Y where A=1 and B=2"
or
"select * from X.Y where A=1 and C=3"
or
"select * from X.Y where B=2 and C=3"
It everytime retruns data on both nodes.
Please help here.


text:
Q: can't get old documents when I update mongoengine from 0.8.6 to 0.9.0 I was using mongodb with mongoengine 0.8.6 and flask for web framework
when I update my mongoengine to 0.9.0 I can't get old documents in database but when I create a new Document I have no problem to get it !
the error that raised is :
raise FieldDoesNotExist(msg)
FieldDoesNotExist: The field 'notification_actions' does not exist on the document 'User'

and when I delete the field that mentioned above for example in this case notification_actions it raised this error with another field and the thing that make me surprised is the new Document that I create have the same fields !
the class definition:
class User(Document):
    stores = EmbeddedDocumentListField(UserStore)
    password = StringField(max_length=255, required=True)
    email = StringField(max_length=255, required=True)
    forget_password_key = StringField()
    mail_verify_key = StringField()
    firstName = StringField(max_length=45)
    lastName = StringField(max_length=45)
    marital = StringField(max_length=1)
    address = StringField()
    state = StringField()
    city = StringField()
    postal = IntField()
    websites = ListField(StringField(max_length=65))
    sex = StringField(max_length=1)
    interest = StringField()
    birthday = DateTimeField()
    skills = StringField()
    phone = StringField()
    cellphone = StringField()
    fax = StringField()
    avatar = StringField()
    msg = IntField(default=0)
    group = StringField()
    created_at = DateTimeField(default=datetime.datetime.now, required=True)

the Document that I try to get it but mongoengine raise error :
{
    "_id" : ObjectId("55c74ba4e3615342fd0b541c"),
    "_keywords" : [],
    "address" : "",
    "banks" : [
        {
            "id" : "55518df6123dbb06402f0e0b",
            "bank_name" : "mellat",
            "account_num" : "603799112344011",
            "card_num" : "223333"
        }
    ],
    "categories" : [],
    "cellphone" : "",
    "city" : "13",
    "created_at" : ISODate("2015-04-01T01:03:18.140Z"),
    "deliveries" : [],
    "delivery" : {
        "courier" : true,
        "post_custom_made" : true,
        "post_leading" : true,
        "free_for_price" : 0,
        "area_support" : "",
        "price_for_area_selected" : 0
    },
    "description" : "",
    "domain" : "ehsanco",
    "domains" : [
        {
            "domain" : "ehsanco.bab.ir",
            "is_active" : true,
            "can_delete" : false,
            "is_default" : true
        },
        {
            "domain" : "ielecom.org",
            "is_active" : false,
            "can_delete" : true,
            "is_default" : false
        }
    ],
    "email" : "emahmoudi98@gmail.com",
    "external_domains" : [
        {
            "domain" : "ielecom.org",
            "is_active" : false,
            "must_buy" : false
        }
    ],
    "fax" : "",
    "inventories" : [
        {
            "store" : ObjectId("551b048e123dbb0524c04983")
        }
    ],
    "is_dealer" : false,
    "logo" : "download",
    "marketplace" : "bab.ir",
    "menu" : [
        ObjectId("55b60037123dbb4e200560f6")
    ],
    "msg" : 0.0000000000000000,
    "notification_actions" : [
        {
            "name" : "buy",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "comment",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "pay",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "contact",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "out_of_stock",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "new_user",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        }
    ],
    "password" : "pbkdf2:sha1:1000$1bca0pNG$b3d7085bf5090057af6fa79e617a5830ac72793e",
    "pay_way" : [],
    "payment" : {
        "zarinpal_is_active" : true,
        "cart_to_card_is_active" : true,
        "coordinatad_is_active" : true
    },
    "phone" : "",
    "related_store" : [],
    "state" : "8",
    "store" : ObjectId("551b048e123dbb0524c04983"),
    "store_name" : "ehsanco",
    "stores" : null,
    "theme" : ObjectId("55850cb7123dbb7c6e1590a6"),
    "theme_history" : [
        ObjectId("55094c6a123dbb2e1c280c0b"),
        ObjectId("55094c6a123dbb2e1c280c0c"),
        ObjectId("55850cb7123dbb7c6e1590a6")
    ],
    "websites" : [],
    "zarinpal" : {
        "zarinpal_id" : "zp.118902",
        "valet_id" : 1
    }
}

and the Document that I can get it from mongoengine:
{
    "_id" : ObjectId("55c74ba4e3615342fd0b5425"),
    "banks" : [],
    "categories" : [],
    "created_at" : ISODate("2015-07-01T08:55:43.052Z"),
    "devices" : [],
    "domains" : [
        {
            "domain" : "khallaghi.bab.ir",
            "is_active" : true,
            "can_delete" : false,
            "is_default" : true
        }
    ],
    "email" : "mdkhallaghi@gmail.com",
    "freeze" : false,
    "inventories" : [
        {
            "store" : ObjectId("55936bc7123dbb512c534206")
        }
    ],
    "is_dealer" : false,
    "keywords" : [],
    "marketplace" : "bab.ir",
    "menu" : [],
    "msg" : 0.0000000000000000,
    "notification_actions" : [
        {
            "name" : "comment",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "buy",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "new_user",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "pay",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "contact",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        },
        {
            "name" : "out_of_stack",
            "has_email" : true,
            "has_sms" : false,
            "has_site_alert" : true
        }
    ],
    "ordering_freeze" : false,
    "password" : "pbkdf2:sha1:1000$99sS9KCg$572b4c418fe0f7cd6b2d0e303f622353aae0a6a0",
    "pay_way" : [],
    "redirect_all_domain_to_default" : true,
    "related_store" : [],
    "store" : ObjectId("55936bc7123dbb512c534206"),
    "store_name" : "khallaghi",
    "stores" : null,
    "tax" : 0.0000000000000000,
    "theme" : ObjectId("55850cb7123dbb7c6e15909e"),
    "theme_history" : [],
    "websites" : []
}

the query that I written :
tmp = User.objects(email=email).count()
users = User.objects(
    email=email
    ).first()

and the funny thing is that the first query is running correctly but the second raises an error
the full error :
    Traceback (most recent call last):
  File "/usr/lib/python2.7/logging/__init__.py", line 859, in emit
    msg = self.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 732, in format
    return fmt.format(record)
  File "/usr/lib/python2.7/logging/__init__.py", line 471, in format
    record.message = record.getMessage()
  File "/usr/lib/python2.7/logging/__init__.py", line 331, in getMessage
    msg = str(self.msg)
  File "/home/mohammad/shopify/env/local/lib/python2.7/site-packages/mongoengine/queryset/queryset.py", line 58, in __repr__
    self._populate_cache()
  File "/home/mohammad/shopify/env/local/lib/python2.7/site-packages/mongoengine/queryset/queryset.py", line 93, in _populate_cache
    self._result_cache.append(self.next())
  File "/home/mohammad/shopify/env/local/lib/python2.7/site-packages/mongoengine/queryset/base.py", line 1359, in next
    _auto_dereference=self._auto_dereference, only_fields=self.only_fields)
  File "/home/mohammad/shopify/env/local/lib/python2.7/site-packages/mongoengine/base/document.py", line 709, in _from_son
    obj = cls(__auto_convert=False, _created=created, __only_fields=only_fields, **data)
  File "/home/mohammad/shopify/env/local/lib/python2.7/site-packages/mongoengine/base/document.py", line 81, in __init__
    raise FieldDoesNotExist(msg)
FieldDoesNotExist: The field 'domain' does not exist on the document 'User'
Logged from file extended_logging.py, line 113
127.0.0.1 - - [09/Sep/2015 15:24:53] "POST /store/login/ HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/mohammad/shopify/project/utils/auth.py", line 53, in decorated_function
    return f(*args, **kwargs)
  File "/home/mohammad/shopify/project/utils/template.py", line 16, in decorated_function
    return f(*args, **kwargs)
  File "/home/mohammad/shopify/project/apps/store/views/auth.py", line 52, in login
    user = users[0]
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/mongoengine/queryset/base.py", line 161, in __getitem__
    _auto_dereference=self._auto_dereference, only_fields=self.only_fields)
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/mongoengine/base/document.py", line 709, in _from_son
    obj = cls(__auto_convert=False, _created=created, __only_fields=only_fields, **data)
  File "/home/mohammad/shopify/env/lib/python2.7/site-packages/mongoengine/base/document.py", line 81, in __init__
    raise FieldDoesNotExist(msg)
FieldDoesNotExist: The field 'domain' does not exist on the document 'User'

the summery of error is when I call first() function the error raises and it says can't find domain field in User collection


text:
Q: How does delay work on the stm32l152RC? I just bought an stm32l152RC and was wondering how the delay works.
The system clock is 16Mhz.
Code:
static volatile uint32_t TimingDelay;
void Delay(__IO uint32_t nCount);

int main(void) {
    Config_Systick();
    char *RCCp = (char*) 0x40023800;
    int *PBp = (int *) 0x40020400;
    // RCC Config
    *((int*) (RCCp + 28)) |= 0x3f;
    *((int*) (RCCp + 32)) |= 1;
    *PBp = 0x5000;

    while (1) {
        GPIO_TOGGLE(GPIOB, LD_GREEN); //toggle green led
        Delay(1000); // 1 second?
    }
} // end of main

    RCC_ClocksTypeDef RCC_Clocks;
    void Config_Systick() {
        RCC_GetClocksFreq(&RCC_Clocks);
        SysTick_Config(RCC_Clocks.HCLK_Frequency / 1000); // setting changed to / 1000
    }

    void TimingDelay_Decrement(void) {
        if (TimingDelay != 0x00) {
            TimingDelay--;
        }
    }

    void Delay(uint32_t nTime) {
        TimingDelay = nTime;
        while (TimingDelay != 0) {
        };
    }

When I execute Delay(1000); in this case the Delay is 1 second, could someone please explain why the delay is 1 second?

A: After doing some research this is the answer I came up with.
doing SysTick_Config(RCC_Clocks.HCLK_Frequency / 1000); means you'r setting 1000 ticks per second. when you do Delay(100) the delay will be 100 ms.


text:
Q: Count item across multiple columns in same table I have a table that looks like below
TableA
------------------------------------
id| ColumnA   | ColumnB   | ColumnC
------------------------------------
1 | A        | B         | B
2 | B        | D         | D
3 | C        | E         | A
------------------------------------

How to count the each of occurrence of each item in each column?
The result that I want is like below:
--------------------
Result    | Counter
--------------------
A         | 2
B         | 3
C         | 1
D         | 2
E         | 1

For single column I can use this SQL:
SELECT ColumnA, COUNT(*)
FROM TableA
GROUP BY ColumnA
HAVING COUNT(*) > 0

What about multiple column? Any help would be great!

A: Try this;)
select c as Result, count(1) as Counter from (
    select ColumnA c from TableA
    union all
    select ColumnB c from TableA
    union all
    select ColumnC c from TableA ) t
group by c

A: can can do it like this:
SELECT ColumnA as Result, sum(1) as Counter FROM (
  SELECT ColumnA FROM youTable
  UNION ALL
  SELECT ColumnB FROM youTable
  UNION ALL
  SELECT ColumnC FROM youTable
) AS res
GROUP BY ColumnA;


text:
Q: Proof the recurrence relation of order statistics using induction I read order statistics from the book The Design and Analysis of Computer Algorithms", by Aho, Hopcroft, Ullman, Addison-Wesley
As per the algorithm the recurrence relation given
T(n)<= cn for n<=49 .....1
T(n)<= T(n/5) + T(3n/4) + cn   for n>=50 .....2
How can I prove it by induction T(n)<= 20cn?
I have two more questions
For the 1st equation why they define n<=49 and for the 2nd equation n>=50
Thank you.


text:
Q: Profunctors as a Kleisli bicategory There is some discussion on the nLab on seeing the free cocompletion $\mathbf{Psh}(\mathbf{A}) = [\mathbf{A}^{op}, \mathbf{Sets}]$, as a pseudomonad.  The Yoneda embedding $よ \colon \mathbf{A} \to \mathbf{Psh}(\mathbf{A})$ gives the unit and that the multiplication would be the unique functor $\mu \colon \mathbf{Psh}(\mathbf{Psh}(\mathbf{A})) \to \mathbf{Psh}(\mathbf{A})$ such that $\mu \circ よ = \mathrm{id}$. However, this creates some size issues.
On the other hand, composition of profunctors $p \colon \mathbf{B} \to \mathbf{Psh}(\mathbf{A})$ and $q \colon \mathbf{C} \to \mathbf{Psh}(\mathbf{B})$ can be defined (following Remark 5.6 in This is the (co)end...) as $\mathsf{Lan}_よ(p) \circ q$, which looks like composition in a Kleisli category for the (pseudo)monad.
Can we get the bicategory of profunctors as a Kleisli construction over the free-completion pseudomonad? Can we deal somehow with the size issues? Is there any reference where this construction is discussed?

A: This beautiful story take place in $\mathsf{Cat}$, the bicategory of locally small categories. There, the construction of small presheaves induces a pseudomonad whose pseudoalgebrabas are cocomplete categories and whose Kleisli category is $\mathsf{Prof}$. A part of this story is folklore and is partially discussed in Lex Colimits, by Garner and Lack, Prop 2.2.
Another part of this story is explained in Relative pseudomonads, Kleisli bicategories, and substitution monoidal structures, with the relative approach, that tends to complicate a bit the things but shows a very nice direction.

A: A nice account of this is given in Martin Hyland's Elements of a theory of algebraic theories.


text:
Q: Can SQL 2008 and SQL 2008 R2 reside in a single machine? I do know that it would be much better if I try it first.
But the problem is that its my client's dedicated server with many websites running on it.
So, I cannot actually test that there.
The server is Windows Server 2008. My queries are

*

*Does SQL 2008 R2 express and SQL 2008 reside on the same machine?

*Does installing SQL 2008 R2 need OS upgrade to Windows Server 2008 R2?

*What will the side effects of this be?

A: Yes, absolutely! SQL Server 2005 and later happily instance stacks together, and to be fair SQL Server 2000 does it quite well too.
Windows 2008 will be fine - I haven't personally tried that combination. Having said all that, I'd recommend always doing it on a scratch box first!
Two or more instances on the same OS will require their max memory setting to be configured appropriately, and both instances monitored for performance.
SQL Server 2008 requirements:
http://technet.microsoft.com/en-us/library/ms143506(SQL.100).aspx
SQL Server 2008 R2 requirements:
http://msdn.microsoft.com/en-us/library/ms143506.aspx


text:
Q: Using A Different StyleSheet For Different Browsers? So far I'm using this JS to load a different stylesheet if one the specified browser. At the moment though, it's not working for me. It doesn't display any of the stylesheets. I cant find whats wrong.
<script type="text/javascript">
if ( $.browser.mozilla == true ) {
  document.write("<link type=\"text/css\" rel=\"stylesheet\" href=\"css\FF.css\">");
}
</script>
<script type="text/javascript">
if ( $.browser.chrome == true ) {
  document.write("<link type=\"text/css\" rel=\"stylesheet\" href=\"css\Chrome.css\">");
}
</script>

A: The comment above is correct that this is no longer a JQuery function.
As you say you are doing this is because the content looks different, try using these tools instead:

*

*http://modernizr.com/ - will allow you to style by what elements work, rather than what browser you are in

*http://necolas.github.io/normalize.css/ - will help standardise the default styles of elements

*http://jigsaw.w3.org/css-validator/

*http://validator.w3.org/ - valid code is more likely to work in all browsers.

Failing that, ask the specific question here (ideally using jsfiddle) - it is rare for css not to work on all new browsers or for a simple workaround not to be possible.
Also: it is almost impossible to test in all browsers nowadays as there are so many, so knowing a single script works on everything you have tested should give confidence that it will work on those you have not tested.

A: This feature was removed in jQuery 1.9: http://jquery.com/upgrade-guide/1.9/
On this page this library is suggested to get this functionality: http://modernizr.com/

A: Pure javascript version tested on Chrome & Firefox. Should work on Opera. Past on your page where you want. Better if at the bottom before
document.addEventListener("DOMContentLoaded",browsercss);

function browsercss() {
    navigator.sayswho = function () {
        var c = navigator.userAgent,
            b, a = c.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if (/trident/i.test(a[1])) return b = /\brv[ :]+(\d+)/g.exec(c) || [], "IE " + (b[1] || "");
        if ("Chrome" === a[1] && (b = c.match(/\bOPR\/(\d+)/), null != b)) return "Opera " + b[1];
        a = a[2] ? [a[1], a[2]] : [navigator.appName, navigator.appVersion, "-?"];
        null != (b = c.match(/version\/(\d+)/i)) && a.splice(1, 1, b[1]);
        return a.join(" ")
    }();
    var stylesheet = "";

    if (navigator.sayswho.indexOf('Chrome') >= 0) {
        stylesheet = 'http://example.com/chrome.css';
    }
    if (navigator.sayswho.indexOf('Mozilla') >= 0) {
        stylesheet = 'http://example.com/mozilla.css';
    }
    if (navigator.sayswho.indexOf('Opera') >= 0) {
        stylesheet = 'http://example.com/mozilla.css';
    }

    loadcss = document.createElement('link');
    loadcss.setAttribute("rel", "stylesheet");
    loadcss.setAttribute("type", "text/css");
    loadcss.setAttribute("href", stylesheet);

    document.getElementsByTagName("head")[0].appendChild(loadcss);
}

A: You can use JavaScript to detect and change the css for different browsers but the code is a bit bulky.
Use link
Different CSS files for Different Browsers


text:
Q: changing value of a private member of a class in c++ without using member or friend function Using pointer, I am able to modify the private value of the class in the code below.
Does it violate the C++ concept that private member can only be modified by member or friend functions?
#include<iostream>
using namespace std;

class demo
{
        private: int info;

        public:
                 demo()
                 {
                         info=10;
                 }

                 void print_info()
                 {
                       cout<<info;
                 }
};

int main()
{

     demo ob;
     int* ptr=(int*)&ob;

     *ptr=20;

     ob.print_info();

     return 0;
}

A: Access descriptors in C++ are a static mechanism. Compliance is checked at compile time by the compiler, and no memory of the privacy level of methods or attributes is retained at run time, nor are any checks performed by then.
By using a C-style cast you are completely circumventing C++ static checks and all bets are off.

A: The exact posted code has has defined behavior under c++11, since demo is a standard-layout class and info (the data member) is accessed as a compatible type, but it is bad style.
Standard-layout class must:

*

*Have the same access control for all data members

*Have no virtual functions

*Only inherit from standard-layout classes

*At most one class in its class hierarchy has data members

*Has no data members with the same type as any in the class hierarchy

This text is simplified from 9.7 of the draft standard. In my terminology, class hierarchy includes the class itself, and data members only covers non-static data members.
Accessing the data member with an incompatible type would cause undefined behavior, as always. For instance short is undefined, but char and int is defined.
In short, such access is defined if the class is standard-layout . So be VERY careful. You can check if a type is standard-layout with std::is_standard_layout

A: The C++ mechanism of public, protected and private members is meant to protect you from accidents, not from malicious intent.
Re-interpreting a pointer as if it points at something else (like you do with int* ptr=(int*)&ob) counts as 'malicious intent' and usually means that you are stepping beyond the C++ language. What happens is entirely up to the compiler and it does not have to be consistent in what it does.

Note that there are other ways to expose private data, for example:
class demo
{
    private: int info;

    public:
             demo()
             {
                     info=10;
             }

             int* expose_info()
             {
                    return &info;
             }
};

This is entirely legal in C++ (although usually a bad idea). The public/protected/private mechanism works only on names (so the name info is inaccessible for outsiders), but if you can get your hands on a pointer/reference to a private member, you have full access to that member.

A: This has been happening accidentally for years via buffer overflows, bad aliases, and other pointer errors. You write memory past the bounds of an array, and viola! you are corrupting the (possibly private) memory in another object. You are using a pointer that has been de-allocated elsewhere, then another process creates an object at that address and viola!, you are corrupting memory. The accessibility features of C++ are for writing contracts and separating concerns in your design for your users. Just like in C# and JAVA, it doesn't prevent anyone--most likely yourself accidentally-- from misusing pointers.
On a side note, you can also use memcpy to copy one class to another using the same exact idea. You should never actually do that in production code, but it can easily be done.

A: In 'The C++ Programming Language' the author Bjarne Stroustrup writes:

The protection of private data relies on restriction of the use of the class member names. It can therefore be circumvented by address manipulation and explicit type conversion. But this, of course, is cheating, C++ protects against accident rather than deliberate circumvention (fraud). Only hardware can offer perfect protection against malicious use of a general-purpose language, and even that is hard to do in realistic systems.

It can be said that manipulation is legal but it is a bad practice to preform such manipulations on private member variables.

A: There are very few guarantees about the layout of instance variables in C++. For example, the presence of the "private" or "public" keyword means that the C guarantee about members have ascending memory addresses is gone. So if you had another member int info2; there would be no guarantee that your code works. I'm not sure if there is any guarantee for the code as it is.
According to user2229152 your code will work. How sure are you that user2229152 is correct? Would you bet on it? It may work today and stop working when you switch to a newer compiler version. Or compile for a different processor. Do you feel lucky?


text:
Q: Working on Tensorflow :: ModuleNotFoundError: No module named '_pywrap_tensorflow_internal' I am stuck since hours but the issue is still not resolved.
I am using only the CPU version and getting the same No module named 'pywrap_tensorflow_internal' error ::
Traceback (most recent call last):
File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
return importlib.import_module(mname)
File "C:\Python\Python36\lib\importlib_init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 994, in _gcd_import
File "", line 971, in _find_and_load
File "", line 955, in _find_and_load_unlocked
File "", line 658, in _load_unlocked
File "", line 571, in module_from_spec
File "", line 922, in create_module
File "", line 219, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in
_pywrap_tensorflow_internal = swig_import_helper()
File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
return importlib.import_module('pywrap_tensorflow_internal')
File "C:\Python\Python36\lib\importlib_init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "", line 1, in
import tensorflow
File "C:\Python\Python36\lib\site-packages\tensorflow_init_.py", line 24, in
from tensorflow.python import *
File "C:\Python\Python36\lib\site-packages\tensorflow\python_init_.py", line 49, in
from tensorflow.python import pywrap_tensorflow
File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in
raise ImportError(msg)
ImportError: Traceback (most recent call last):
File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
return importlib.import_module(mname)
File "C:\Python\Python36\lib\importlib_init_.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 994, in _gcd_import
File "", line 971, in _find_and_load
File "", line 955, in _find_and_load_unlocked
File "", line 658, in _load_unlocked
File "", line 571, in module_from_spec
File "", line 922, in create_module
File "", line 219, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in
_pywrap_tensorflow_internal = swig_import_helper()
File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
return importlib.import_module('pywrap_tensorflow_internal')
File "C:\Python\Python36\lib\importlib_init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'
Failed to load the native TensorFlow runtime.
See https://www.tensorflow.org/install/install_sources#common_installation_problems
for some common reasons and solutions. Include the entire stack trace
above this error message when asking for help.
Checked the previous solutions that have been mentioned on StackOverflow and Github and based on those made the following changes:-
**1. I have placed msvcp140.dll in system32(64-bit file) and SysWOW64(32-bit file) as advised in https://www.youtube.com/watch?v=61vwFxnnh5c

*I have also downloaded and installed Microsoft Visual C++ 2015 Redistributable Update 3

*On running the selfcheck.py, I am getting the following result::
ERROR: Failed to import the TensorFlow module.**
WARNING! This script is no longer maintained!
Since TensorFlow 1.4, the self-check has been integrated with TensorFlow itself,
and any missing DLLs will be reported when you execute the import tensorflow
statement. The error messages printed below refer to TensorFlow 1.3 and earlier,
and are inaccurate for later versions of TensorFlow.
Python version is 3.6.
TensorFlow is installed at: C:\Python\Python36\lib\site-packages\tensorflow
Could not load 'cudart64_80.dll'. The GPU version of TensorFlow
requires that this DLL be installed in a directory that is named in
your %PATH% environment variable. Download and install CUDA 8.0 from
this URL: https://developer.nvidia.com/cuda-toolkit
Could not load 'nvcuda.dll'. The GPU version of TensorFlow requires that
this DLL be installed in a directory that is named in your %PATH%
environment variable. Typically it is installed in 'C:\Windows\System32'.
If it is not present, ensure that you have a CUDA-capable GPU with the
correct driver installed.
Could not load 'cudnn64_5.dll'. The GPU version of TensorFlow
requires that this DLL be installed in a directory that is named in
your %PATH% environment variable. Note that installing cuDNN is a
separate step from installing CUDA, and it is often found in a
different directory from the CUDA DLLs. You may install the
necessary DLL by downloading cuDNN 5.1 from this URL:
https://developer.nvidia.com/cudnn
Could not find cuDNN.
Please Help

A: I encountered the same issue and the problem was with the version of TensorFlow. Follow the below steps in order to remedy this situation:

*

*Open the terminal via Anaconda navigator.

*Run the command:
conda install tensorflow

*Try working with your code again and it will just work fine.


text:
Q: JS: Error in IE, compatible in Chrome and Firefox I'm having IE give me this error for a small function I wrote:

Message: Object expected Line: 13
  Char: 52 Code: 0

Here is my code (please excuse the formatting):
function SectionTwo()
{
    if (xmlhttp.readyState==4) {
        if( xmlhttp.status==200 ) {
            if( xmlhttp.responseText.indexOf( "404 Error" ) >= 0 ) { }
            else {
                var idtagsArray = ["KT501-1_8","KT502-15_30","KT503-15_37","KT504-10_30","KT505-30_80","KT506-30_90","KT507-20_50","KT510-15_1440","KT512-0_1_2_3_4","KT513-30_80","KT514-0_1","KT520-0_1","KT525-0_1_2","KT526-0_1","KT527-0_9999","KT529-0_9999","KT531-0_9999","KT533-0_9999","KT535-0_250","KT536-0_9999","KT538-0_9999","KT548-0_1","KT549-0_1","KT550-102_120", "KT551-80_98","KT552-15_37","KT553-0_30","KT554-50_90","KT555-20_50","KT565-0_10","KT566-0_20","KT567-0_30","KT568-0_50","KT569-1_10","KT570-1_10","KT571-2_10","KT572-2_10","KT573-1_20","KT574-1_30"];
                for(var tag = 0; tag < idtagsArray.length; tag++) {
                    UpdateImage( idtagsArray[tag], xmlhttp.responseText);
                }
            }
        }
    }
}

The last line is line 13. I also have another function called SectionOne which is identical to the above except that it calls UpdatePoint instead of UpdateImage, and that one does not error out.
Chrome and Firefox do not show any JS errors and work as intended. Here is the UpdateImage function:
function UpdateImage( usediv, data )
{
    if( data == null || data.length <= 0 ) {
        update_value.innerText = 0;
        return
    }

    // [A5:1][A6:1][A7:1][A8:1]
    var start       = data.indexOf( "[" + usediv + ":" ) + 2 + usediv.length ;
    var end         = data.indexOf( "]", start );
    var data_value  = data.slice( start , end ) ;

    if( data_value > 0 )
    {
        document.getElementById(usediv).style.display = "";
    }
    else
    {
        document.getElementById(usediv).style.display = "none";
    }
}

Any ideas would be appreciated.

A: Could it be the lack of a semi-colon on the return in UpdateImage?
Edit:
In that case you just have some obscure syntax oddity that IE is confused about (happens all the time :)).
Start removing code. Get rid of all those nested if's (probably should be refactored anyway). Don't do a for loop, just call UpdateImage( idtagsArray[0], xmlhttp.responseText ). Make your idtagsArray only 1 element long. Etc.

A: Could it be the missing semicolon after return in your function UpdateImage?


text:
Q: How to create a new dataframe from existing dataframe with certain condition - python I have a dataframe looks like below.
   text      country    language
-----------------------------------
  football     US         Eng
  baseball     JP         Jpn
  swimming     UK         Eng
  running      FR         Fra
  rugby        NZ         Eng
  Hockey       NL         Dut

In python, I want to extract rows which contain strings 'ball' and 'ing' in the column 'text' and make a new dataframe with those rows like below.
   text      country    language
-----------------------------------
  football     US         Eng
  baseball     JP         Jpn
  swimming     UK         Eng
  running      FR         Fra

A: Using pandas, you can slice using multiple conditions, just watch out for tricky parenthesis on the syntax.
df = pd.DataFrame({'A': ['foo', 'bar', 'fooing', 'barball'],
                   'B': [1, 2, 3, 4]})

df_slice = df[(df.A.str.contains('ing')) | (df.A.str.contains('ball'))]

That should yield
df_slice
A        B
fooing   3
barball  4

If your goal is to slice in words that end in ing or ball, use endswith() instead of contains() in the conditions. Hope it helps!


text:
Q: User in any time zone enters a date in Pacific Time OK maybe I'm being exceptionally dense about this... but I'm wondering how I can make it so that users worldwide in any time zone who use a time picker to enter a time in Pacific Time, and then see it printed back to them in Pacific Time (either PST or PDT, depending) after save. Let's take the example of someone in New York. I'm thinking the flow should be like this:

*

*On the input field, this person selects "1pm" (meaning 1pm Pacific Time)

*The JS reads it as 1pm Eastern Time, converts that to UTC Unix timestamp

*The UTC Unix timestamp is POSTed to database

*On the show result, the timestamp is converted to Pacific Time. However you see there's now obviously the problem that the Pacific Time will read "10am" because the POSTed timestamp was for an Eastern time

A: Basically, you could use the following function:
function convertUtcToPacificTime(utcDate) {
    var timezoneOffset = new Date().getTimezoneOffset();

    // set the time back 7 hours for PDT or 8 hours for PST
    // from the current utc date
    utcDate.setTime(utcDate.getTime()-(timezoneOffset/60)*3600*1000);
}

.getTimezoneOffset() retrieves the difference between the current timezone and UTC in minutes, hence why I'm dividing by 60. In PDT the function would return 420, while in PST 480 (7 and 8, respectively, when divided by 60).
Your HTML select box could look as follows:
<select class="time-select">
   <option value="<!-- timestamp for 1 pm UTC -->">1 pm</option>
   <option value="<!-- timestamp for 2 pm UTC -->">2 pm</option>
   ...
</select>

Once you get the timestamp that the user selected, you can convert it using the function above:
$('.time-select').change(function() {
   var timestamp = $(this).val();
   var date = new Date(timestamp);
   if (!isNaN(date)) { // check if date is valid
       convertUtcToPst(date);

       // the 'date' var now contains
       // the PST date of the selected timestamp

       // post the timestamp to the DB
   } else {
       // handle invalid date scenario
   }
});

Also, to compute the UTC timestamp just call .getTime() on a JS Date object.

A: If I understand well, your problem would be solved if you can change the time zone in the date you already have (built from the time picker) that is in local (whatever it is) to Pacific Time.
Using moment and moment-timezone, you can do that with the following:
function convertLocalToPst(localDate) {
  var pacific = moment().tz('US/Pacific');
  var m = moment(moment(d).utc().format("MM/DD/YYYY HH:mm"));

  m = pacific.isDST() ? m.utcOffset('-0800') : m.utcOffset('-0700');
  return m.toDate();
}


text:
Q: Is there a way to force power off for the Samsung NP N150plus series? There seems to be a nifty way to power off the Series 9 laptop (pinhole + paperclip) when the laptop goes into panic mode and using the on-off switch for 4s+ no longer works. There does not seem to be an equivalent pinhole on the NP-N150 (JP0PUK) netbook.
Any idea what to do apart from letting it run out of battery? (This is after a kernel panic when trying to upgrade ubuntu).

A: Nearly all modern main boards are designed so that holding the power button down for an extended period will force a cold shutdown, even in a frozen state. If that does not work, pulling the battery and the power cord definitely will, though it is not advised.


text:
Q: How do I destructure an array wrapped in the Promise keyword in javascript? I am trying to retrieve data from a PSQL table. And this is my code for that:
async function requestData() {
   var selectQuery = `SELECT "fName", "lName", "phoneNumber", "eMail" FROM public."User"`;
   const {rows} = await client.query(selectQuery);
   client.end;
   return rows;
}

This function is returning:
an array inside the Promise keyword. {[]}
I want to destructure the array inside to present the data and I cannot figure out any possible way of doing it. I tried using foreach loop and other ways but it is not working.
When this function runs in its own file, it gives normal output of an array of objects.
async function requestData() {
   var selectQuery = `SELECT "fName", "lName", "phoneNumber", "eMail" FROM public."User"`;
   const {rows} = await client.query(selectQuery);
   client.end;
   console.log(rows);
   return rows;
}

It is giving normal output in the file, but when I am exporting this output, it is wrapping the output in the promise keyword. I tried going through the documentation but I didn't find any way to destructure this.
This is the code in the file that I have imported:
const adminData = require("./data/adminDataObjects");
console.log(adminData.users.table);

And this is the code in the adminDataObjects file where I have defined this function:
users: {
    body: ``,
    table: requestData(),
    script: `<script>document.querySelector('.users').classList.add('active')</script>`,
  },

I am new to node js and I have already tried to search for the solution in different blog posts, stackoverflow answers and MDN documentation. I even read blog posts about asynchronous javascript and completed a tutorial on promises.

A: As already mentioned in one of the comment by Andy that the return type of an asynchronous function is a promise, it was the problem here.
I asked one of my friend to resolve the promise and the "Promise" keyword that was showing up went away. Apparently I was making a syntax error while resolving the promise.
This is the code with the problem that is returning return value as an array within an object of the promise keyword.
const adminData = require("./data/adminDataObjects");
console.log(adminData.users.table);

This is how I resolved this error:
    const adminData = require("./data/adminDataObjects");
    app.get("/admin/:path", async (req, res) => {
      const requestKeyword = req.params.path;
      if (requestKeyword === "dashboard") {
        res.render("admin-panel", { data: adminData.dashboard });
      } else if (requestKeyword === "users") {
        var finalValue
        await adminData.users.table.then((value)=>{
           finalValue=value;
        })
        console.log(finalValue);
      } else{
        res.render("admin-panel", { data: adminData.orders });
      }
    });


text:
Q: Reduceness and faithfully flatness I have a "well known question" for which I do not find a reference.

Let $A$ and $B$ be a commutative rings and $A\rightarrow B$ be a faithfully flat morphism. Let $C$ be a ring over $A$. Is it true that $$C_{red}\otimes B\cong (C\otimes B)_{red}?$$
  In other words does faithful flatness commute with taking the reduced structure?

A: It's not hard to find a field extension $k\subset K$ such that $K\otimes_kK$ is not reduced.


text:
Q: How can I overpass syntax error at this code? I was working for my project , i crossed with syntax error while
creating table. Could you help me?
Taking values from textfields , will use for considering attribute names
String ac2 = a2.getText();
String ac3 = a3.getText();
String ac4 = a4.getText();
String ac5 = a5.getText();
String ac6 = a6.getText();
String ac7 = a7.getText();
String ac8 = a8.getText();
String ac9 = a9.getText();

Taking values from combobox to determine type of attribute
String t1 = c1.getSelectedItem().toString();
String t2 = c2.getSelectedItem().toString();
String t3 = c3.getSelectedItem().toString();
String t4 = c4.getSelectedItem().toString();
String t5 = c5.getSelectedItem().toString();
String t6 = c6.getSelectedItem().toString();
String t7 = c7.getSelectedItem().toString();
String t8 = c8.getSelectedItem().toString();
String t9 = c9.getSelectedItem().toString();

My query to create table
String sql = "CREATE TABLE " + tablename + "(\n"
            +"Name" +t1 + "PRIMARY KEY NOT NULL ,\n"
            +ac2 +t2 + ",\n"
            +ac3 +t3 + ",\n"
            +ac4 +t4 + ",\n"
            +ac5 +t5 + ",\n"
            +ac6 +t6 + ",\n"
            +ac7 +t7 + ",\n"
            +ac8 +t8 + ",\n"
            +ac9 +t9 + ",\n"
            +");";
 try(Statement stmnt = connection.createStatement()  ){
        stmnt.execute(sql);
    }
    catch(SQLException e){
        JOptionPane.showMessageDialog(null,e);
    }

I am using jdbc for sqlite , with this code I am aiming to create a
table from user given values.
I am taking error unrecognized token("2TEXT") now.

A: remove the last comma and add space between attribute and type
String sql = "CREATE TABLE " + tablename + "(\n"
            +"Name" +t1 + "PRIMARY KEY NOT NULL ,\n"
            +ac2 + " " + t2 + ",\n"
            +ac3 +" " + t3 + ",\n"
            +ac4 +" " + t4 + ",\n"
            +ac5 +" " + t5 + ",\n"
            +ac6 +" " + t6 + ",\n"
            +ac7 +" " + t7 + ",\n"
            +ac8 +" " + t8 + ",\n"
            +ac9 +" " + t9 +");";

A: I can see a number of actual or potential syntax errors.

*

*You have not put a space between the column names and the corresponding types.

*There is a trailing comma in the list.

*Any of the input names (tablename, ac2, ac3 etcetera) could have a value that is an SQL keyword.

*Any of the input types (t1, t2, etcetera) could have a value that is not a valid SQL column type specification.

I suggest that you print out the SQL that you are building in sql ... and look at it carefully.