text:
Q: Clarify two columns of the same name I have this query:
SELECT CableNumber, CblType, ApprxmtLngth, ME.EquipmentNumber, ME2.EquipmentNumber, CblStatus, InstallMthd, S.PrdtCd FROM CableId C
 INNER JOIN MajorEquipment ME ON C.FromLoc = ME.MEId
 INNER JOIN MajorEquipment ME2 ON C.ToLoc = ME2.MEId
 INNER JOIN SupplierInfo S ON C.SupplierId = S.SupplierId WHERE
 (@CblType IS NULL OR CblType LIKE @CblType)
 AND (@CblStatus IS NULL OR CblStatus LIKE @CblStatus)
 AND (@FromLoc IS NULL OR ME.EquipmentNumber LIKE @FromLoc)
 AND (@ToLoc IS NULL OR ME2.EquipmentNumber LIKE @ToLoc);

When I pass the result into a model, how do I define which EquipmentNumber goes into which variable?
while (mySqlReader.Read())
{
    CableID_Controller.CList.Add(new CableID_Model
    {
        CableNumber = Convert.ToString(mySqlReader["CableNumber"]),
        CableType = Convert.ToString(mySqlReader["CblType"]),
        SupplierPart = Convert.ToString(mySqlReader["PrdtCd"]),
        CableLength = Convert.ToInt32(mySqlReader["ApprxmtLngth"]),
        InstallMethod = Convert.ToString(mySqlReader["InstallMthd"]),
        Origin = Convert.ToString(mySqlReader["ME.EquipmentNumber"]),
        Destination = Convert.ToString(mySqlReader["ME2.EquipmentNumber"]),
        Status = Convert.ToString(mySqlReader["CblStatus"])
     });
}

Because ME.EquipmentNumber and ME2.EquipmentNumber are not the actual names of the headers.

A: Description
Just give the columns different alias (EquipmentNumber1 and EquipmentNumber2) in your query and code with the as operator. You have to remove the ME1 and ME2 in your code too.
Sample
SELECT CableNumber, CblType, ApprxmtLngth, ME.EquipmentNumber as EquipmentNumber1, ME2.EquipmentNumber as EquipmentNumber2, CblStatus, InstallMthd, S.PrdtCd FROM CableId C
 INNER JOIN MajorEquipment ME ON C.FromLoc = ME.MEId
 INNER JOIN MajorEquipment ME2 ON C.ToLoc = ME2.MEId
 INNER JOIN SupplierInfo S ON C.SupplierId = S.SupplierId WHERE
 (@CblType IS NULL OR CblType LIKE @CblType)
 AND (@CblStatus IS NULL OR CblStatus LIKE @CblStatus)
 AND (@FromLoc IS NULL OR ME.EquipmentNumber LIKE @FromLoc)
 AND (@ToLoc IS NULL OR ME2.EquipmentNumber LIKE @ToLoc);

while (mySqlReader.Read())
{
    CableID_Controller.CList.Add(new CableID_Model
    {
        CableNumber = Convert.ToString(mySqlReader["CableNumber"]),
        CableType = Convert.ToString(mySqlReader["CblType"]),
        SupplierPart = Convert.ToString(mySqlReader["PrdtCd"]),
        CableLength = Convert.ToInt32(mySqlReader["ApprxmtLngth"]),
        InstallMethod = Convert.ToString(mySqlReader["InstallMthd"]),
        Origin = Convert.ToString(mySqlReader["EquipmentNumber1"]),
        Destination = Convert.ToString(mySqlReader["EquipmentNumber2"]),
        Status = Convert.ToString(mySqlReader["CblStatus"])
     });
}

More Information

*

*How to MySQL - ALIAS

A: Modify your query by adding aliases to the returned columns:
SELECT CableNumber,
       CblType,
       ApprxmtLngth,
       ME.EquipmentNumber AS EquipmentNumber1,
       ME2.EquipmentNumber AS EquipmentNumber2,
       CblStatus,
       InstallMthd, [...]

You can then refer to EquipmentNumber1 and EquipmentNumber2 respectively.

A: Could you not give the columns different aliases?

SQL aliases are used to temporarily rename a table or a column
  heading.

Something like
SELECT
 CableNumber,
 CblType,
 ApprxmtLngth,
 ME.EquipmentNumber as MEEquipmentNumber,
 ME2.EquipmentNumber as ME2EquipmentNumber,
 CblStatus,
 InstallMthd,
 S.PrdtCd
...

You would then use these aliases in your C# code. Something like
while (mySqlReader.Read())
{
    CableID_Controller.CList.Add(new CableID_Model
    {
        CableNumber = Convert.ToString(mySqlReader["CableNumber"]),
        CableType = Convert.ToString(mySqlReader["CblType"]),
        SupplierPart = Convert.ToString(mySqlReader["PrdtCd"]),
        CableLength = Convert.ToInt32(mySqlReader["ApprxmtLngth"]),
        InstallMethod = Convert.ToString(mySqlReader["InstallMthd"]),
        Origin = Convert.ToString(mySqlReader["MEEquipmentNumber"]),
        Destination = Convert.ToString(mySqlReader["ME2EquipmentNumber"]),
        Status = Convert.ToString(mySqlReader["CblStatus"])
     });
}


text:
Q: Nested hashtable access in erb In an erb template, I access an element (item.attributes[:Post]) which is a hash.
I verified its class by printing
<%= (item.attributes[:Post]).class %> => Hash

I can call general methods on it
<%= (item.attributes[:Post]).methods %> => works as expected

But I can not access any hash specific function.
<%= (item.attributes[:Post]).count %>  => NoMethodError: undefined method `count' for nil:NilClass

Do you have any idea why ?

A: try to print the value as p item.attributes[:Post]) which is nil. nil is an instance of NilClass, which has no count method.
nil.methods.include? :count  #=>false

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check if growth rate is worse than quadratic? Let's say I have collected a dataset for estimating algorithmic complexity:

x
t

1
1

2
4

3
9

4
16

where x is the input size and t is the elapsed time. This may be O(1), O(logn), O(n), O(n^2), O(n^3) etc.. To find the closest class, it would be necessary to run a linear/non-linear regression to fit the data and find the curve of the best fit. However, that would be too time consuming.
My question is: is there a quick way to tell if the rate of growth is worse than O(n^2)?


text:
Q: Animate div if page is scrolled down I want to animate my header if the page is scrolled down (lets say 300px).
How can i realize this in jquery?
Something like :
if (scrolled > 300px) {
$('.mydiv').slideUp();
}
else (scrolled < 300px) {
$('.mydiv').slideDown();
 }

thank you!

A: Try this:
$(document).scroll(function() {
    if( $(this).scrollTop() > 300 ) {
        $('.mydiv').slideUp();
    } else {
        $('.mydiv').slideDown();
    }
});


text:
Q: Hive and sql( any sql query) I am posting question here related to hive dataware house?I have below sample data
    Id,name,transctions
1,apple,(1,1,1,1)
2,mango,(1,1,1)
3,kiwi,(1,1,1)
...........
.......

In transctions column  my data is array type. I am expecting below output.
Id,name,transtion
1,apple,4
2,mango,3
3,kiwi,3

A: I am guessing you want the size of the array:
select id, name, [size(transactions)][1]
from t;


text:
Q: How to get the length of a unicode string? If I do the following:
ustr = unicode()
ustr = '青皮'
print len(ustr)

I get an output of 6. But that's the number of bytes.
How do I get an output of 2? (i.e. the actual number of unicode code points)


text:
Q: Text fades in/out on new bootstrap carousel slide I have built a bootstrap carousel that changes a p tag's text depending on the active carousel slide. How would I go about fading that text out when a slide's interval is about to end, and fade in the new, altered text upon the new slide becoming active?
Here is the jQuery (JSFiddle example below):
$(document).ready(function () {
$('.carousel').carousel({
    interval: 2000
});

var arrMessages = ["Text for Image 1 class!",
                   "Text for Image 2 class!",
                   "Text for Image 3 class!"]

var $msg = $("#sticksCarouselMessage");
$('#sticksCarousel').on('slid.bs.carousel', function () {

    var text = "",
         $active = $('div.active'),
         index = $('div.item').index($active);

    $msg.text(arrMessages[index]);

});

});
JSFIDDLE: https://jsfiddle.net/CharlieMcShane/hja32vjn/

A: You could use jQuery fadeIn/fadeOut similar to this:
$msg.fadeOut('fast', function() {
    $msg.text(arrMessages[index]);
}).fadeIn('fast');

$(document).ready(function() {
  $('.carousel').carousel({
    interval: 2000
  });

  var arrMessages = ["Text for Image 1 class!",
    "Text for Image 2 class!",
    "Text for Image 3 class!"
  ]

  var $msg = $("#sticksCarouselMessage");
  $('#sticksCarousel').on('slid.bs.carousel', function() {
    $msg.fadeOut('fast', function() {
      $msg.text(arrMessages[index]);
    }).fadeIn('fast');

    var text = "",
      $active = $('div.active'),
      index = $('div.item').index($active);
  });
});
/*-- Carousel bars --*/

.carousel-indicators.middle {
  left: 0;
  right: 0;
  top: auto;
  bottom: 15px;
  text-align: center;
}

.carousel-indicators.middle li {
  float: none;
  display: inline-block;
  width: 35px;
  border-radius: 0px;
}

/*-- Carousel Next/Prev --*/

.carousel .carousel-control {
  top: 50%;
}

.carousel .left.carousel-control:after {
  content: "<";
  font-size: 20px;
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.carousel .right.carousel-control:after {
  content: ">";
  font-size: 20px;
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/*-- Carousel Pre-text --*/

#sticksCarouselMessage {
  text-align: center;
}

<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>

Text for Image 1 class!

A: Use keyframes to animate the text:

@keyframes myText {
  0%  { opacity: 0; }
  5% { opacity: .5; }
  10% { opacity: 1; }
  90% { opacity: 1; }
  95% { opacity: .5; }
  100% { opacity: 0; }
}
#sticksCarouselMessage {
  animation: myText 2s infinite;
}


text:
Q: Why doesn't Magento 2.1 hint footer section? I'm learning magento 2. I enabled hints from admin panel .I try to find in root directory but have had no success. In my screenshot, My question is
why does magento not hint footer section? where is store footer section in magento root directory? Please suggest how it works?
Thanks.


text:
Q: Find smallest and biggest number of an array with reduce function in javascript Just a matter of curiosity. With the reduce function, we could easily find the smallest and the biggest number inside an array separately. Just like that:
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];
a.reduce(function(prev,cur,index,array){
    return prev > cur ? prev : cur;
}); // returns 11

a.reduce(function(prev,cur,index,array){
    return prev < cur ? prev : cur;
}); // returns -1

Given that, why this don't work?
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];
var smallest = 0;
var biggest = 0;
a.reduce(function(prev,cur,index,array){
    smallest = prev < cur ? prev : cur;
    biggest =  prev > cur ? prev : cur;
});
console.log([smallest, biggest]); // prints [11,11]

Tested on repl.it.

A: In the following:
a.reduce(function(prev,cur,index,array){
    smallest = prev < cur ? prev : cur;
    biggest =  prev > cur ? prev : cur;
});

the function supplied to reduce has no return statement so it returns undefined. So after the first iteration, prev is set to undefined.
If either expression in the abstract relational comparison algorithm is undefined, the expression returns undefined (see step 3.c), which evaluates to false. So from the second iteration onward, both smallest and biggest are set to cur and at the end they're both set to the last value in the array.

A: Two problems.
First, the lambda parameter to reduce has no return value.  If you aren't going to return something, reduce is just forEach with more parameters that don't mean anything.
Second, at each element, you compare cur to prev instead of comparing cur to biggest and smallest.

A: I know this is ancient but here is how to solve such issues using array reduce:
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];

var minNumber = a.reduce(function(prev,cur) {
    return prev < cur ? prev : cur;
}, +Infinity);

var maxNumber = a.reduce(function(prev,cur) {
    return prev > cur ? prev : cur;
}, -Infinity);

Personally I'd just use Math.min/max:
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];

Math.min(...a) // will give -1
Math.max(...a) // will give 11

A: While using reduce, you need to return something inside reduce, otherwise reduce forgets previous values.
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];
var initial = {
  smallest: a[0],
  biggest: a[0]
};
var result = a.reduce((prev, cur) => {
  prev.smallest = prev < cur ? prev : cur;
  prev.biggest = prev > cur ? prev : cur;
  return { smallest, biggest};
}, initial);

console.log(result);
// Prints object as,
// { smallest: -1, biggest: 11 }


text:
Q: How can I find the variation in strings in a single column using Snowflake SQL? Say I have a table like this:

Person1
Person2

Dave
Fred

Dave
Dave

Dave
Mike

Fred
Dave

Dave
Mike

Dave
Jeff

In column 'Person1' clearly Dave is the most popular input, so I'd like to produce a 'similarity score' or 'variation within column' score that would reflect that in SQL (Snowflake).
In contrast, for the column 'Person2' there is more variation between the strings and so the similarity score would be lower, or variation within column higher. So you might end up with a similarity score output as something like: 'Person1': 0.9, 'Person2': 0.4.
If this is just row-wise Levenshtein Distance (LD), how can I push EDITDISTANCE across these to get a score for each column please? At the moment I can only see how to get the LD between 'Person1' and 'Person2', rather than within 'Person1' and 'Person2'.
Many thanks

A: You proposed values of 0.9 and 0.4 seem like ratio's of sameness, so that can be calculated with a count and ratio_of_report like so:

with data(person1, person2) as (
    select * from values
        ('Dave','Fred'),
        ('Dave','Dave'),
        ('Dave','Mike'),
        ('Fred','Dave'),
        ('Dave','Mike'),
        ('Dave','Jeff')
), p1 as (
    select
      person1
      ,count(*) as c_p1
      ,ratio_to_report(c_p1) over () as q
    from data
    group by 1
    qualify row_number() over(order by c_p1 desc) = 1
), p2 as (
    select
      person2
      ,count(*) as c_p2
      ,ratio_to_report(c_p2) over () as q
    from data
    group by 1
    qualify row_number() over(order by c_p2 desc) = 1
)
select
    p1.q as p1_same,
    p2.q as p2_same
from p1
cross join p2
;

giving:

P1_SAME
P2_SAME

0.833333
0.333333

Editdistance:
So using a full cross join, we can calculate the editdistance of all values, and find the ratio of this to the total count:
with data(person1, person2) as (
    select * from values
        ('Dave','Fred'),
        ('Dave','Dave'),
        ('Dave','Mike'),
        ('Fred','Dave'),
        ('Dave','Mike'),
        ('Dave','Jeff')
), combo as (
select
    editdistance(da.person1, db.person1) as p1_dist
    ,editdistance(da.person2, db.person2) as p2_dist
from data as da
cross join data as db
)
select count(*) as c
    ,sum(p1_dist) as s_p1_dist
    ,sum(p2_dist) as s_p2_dist
    ,c / s_p1_dist as p1_same
    ,c / s_p2_dist as p2_same
from combo
 ;

But given editdistance gives a result of zero for same and positive value for difference, the scaling of these does not align with the desired result...
JAROWINKLER_SIMILARITY:
Given the Jarowinklet similarity result is already scaled between 0 - 100, it makes more sense to be able to average this..
select
     avg(JAROWINKLER_SIMILARITY(da.person1, db.person1)/100) as p1_dist
    ,avg(JAROWINKLER_SIMILARITY(da.person2, db.person2)/100) as p2_dist
from data as da
cross join data as db;

P1_DIST
P2_DIST

0.861111111111
0.527777777778


text:
Q: Show only, when taxonomy has posts? I'd like to query posts by taxonomy like this:
<?php
global $post;
$terms = get_the_terms( $post->ID , 'movies', 'string');
$do_not_duplicate[] = $post->ID;

if(!empty($terms)){
    foreach ($terms as $term) {
        query_posts( array(
        'movies' => $term->slug,
        'showposts' => 4,
        'caller_get_posts' => 1,
        'post__not_in' => $do_not_duplicate ) );
        if(have_posts()){
            while ( have_posts() ) : the_post(); $do_not_duplicate[] = $post->ID; ?>
do stuff

            <?php endwhile; wp_reset_query();
        }
    }
}
?>

But I only want to show this, while there are posts with the same taxonomy to show up.
How could I do this?
Something like: if has taxonomy AND has post?
Thanks!
AD

A: If you take a look at the array that get_the_terms() returns, you'll see that it includes a "count".
If I understand your question correctly, you're looking to find all posts with a count greater than 1 (i.e. terms that are on more than the current post). So, I think you can simply change your foreach statement to this (the second line is the change):
foreach ($terms as $term) {
  if( $term->count > 1 ) {
    query_posts( array(
    'movies' => $term->slug,
    'showposts' => 4,
    'caller_get_posts' => 1,
    'post__not_in' => $do_not_duplicate ) );
    if(have_posts()){
        while ( have_posts() ) : the_post(); $do_not_duplicate[] = $post->ID; ?>
              // do stuff
        <?php endwhile; wp_reset_query();
    }
  }
}

Also, get_the_terms() only accepts two parameters (at least according to the Codex), so I'm not sure on what that third parameter is doing. It's possibly not doing anything? If you're trying to get terms from two taxonomies, check out wp_get_object_terms()


text:
Q: Why pseudoscalar can decay to photons I think I have a misunderstanding of quantum numbers. We know that photon  $\gamma$ has negative parity and pseudoscalar $P$ by definition has negative parity.
So one would think that decay $P \rightarrow \gamma \gamma$ is not allowed, because initial state has parity $-1$ and final state has parity $(-1)(-1)=1$.

*

*However, one can write effective Lagrangian containing $PF_{\mu\nu}\tilde{F}^{\mu\nu}$ and study $P\rightarrow \gamma \gamma$ which has non-zero amplitude.

*In Two Higgs Doublet Model, a pseudoscalar can decay into photons via triangular loop diagram.
So it seems that quantum numbers do not allow this decay, however it still happens.
If someone understands what I have in mind, I would very much appreciate an explanation.

A: You're forgetting about the parity of the spatial wavefunctions, which provides extra sign flips. For example, if the two photons come out in an $s$-wave, the spatial wavefunction has positive parity, while if they come out in a $p$-wave, it has negative parity. This is just like how the parity of $|\ell m \rangle$ in the hydrogen atom is $(-1)^\ell$.
In this case, you've shown that parity forbids the $s$-wave decay, but the $p$-wave is allowed.


text:
Q: Javascript: running on mobile but not on desktop(chrome, opera, safari) I'm working with the HTML5 geolocation api. I'm getting a weird error. i got a function called doGeolocate that is called when the user land on the page. That load the map with the wright location data. And i got a button that recall the same function when ever the user want to recenter the map. But when a user tap the button on a desktop(chrome,opera, safari) except firefox it doesn't work.
While on the other there is no problem. Once debug it seem like the code locationCallback isn't call properly the second time even tho it is on load.
doGeolocate: function(){
    if (navigator.geolocation) {
        console.log("doGeolocate");
        var locationCallback = helper.callback(this, function(position) {
            this.initialGeolocationPosition(position);
            if(!this.positionMarker){
            this.createPositionMarker(position);
            }
        });
        var err = function(err) {
            console.log("");
        };
        var options = {
            maximumAge: 0
        };
    navigator.geolocation.getCurrentPosition(locationCallback,err,options);
    }
  },


text:
Q: Workaround from client side for invalid HTTP response headers that contain both Transfer-Encoding and Content-Length?Can see response using Postman I'm calling an API that returns 5 keys in the header including Transfer-encoding:chunked and Content-Length values, in the header.
According to  stackoverflow question, and this below, this is illegal:

"...Node.js server returns a parse error with code HPE_UNEXPECTED_CONTENT_LENGTH when consuming the endpoint, because the response headers contains both Transfer-encoding:chunked and Content-Length values.
  This is considered has an error as specified in RFC 7230 section 3.3.3.3 :
  If a message is received with both a Transfer-Encoding and a Content-Length header field, the Transfer-Encoding overrides the Content-Length. Such a message might indicate an attempt to perform request smuggling (Section 9.5) or response splitting (Section 9.4) and ought to be handled as an error. A sender MUST remove the received Content-Length field prior to forwarding such a message downstream." (1)

I'm using node.js and npm-request module to send the request and try and parse the response. The function being called is
function createPostAPI(req, res, userid, detailText, title, location, custImpact){
 var myJSONObject = {
    "userId" : userid,
    "apiKey" : "{API-Key}",
    "detail" : {
      "detailText" : detailText
    },
    "info" : {
      "title":title
      "location" : location,
      "priority" : 0,
      "customerImpact" : custImpact
    }
  }

  request1({
    url: "http://theAPIurl",
    method: "POST",
    body:JSON.stringify(myJSONObject)
    json: true,   // <--Very important!!!
    body: myJSONObject
  }, function (error, response, body){
      console.log(error);
      console.log(response);
      console.log(body);
  });
}

This is the error i get as expected :
{ Error: Parse Error
at Error (native)
at Socket.socketOnData (_http_client.js:362:20)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:547:20) bytesParsed: 194, code: 'HPE_UNEXPECTED_CONTENT_LENGTH' }

However, I can see that the API call is working, since I can visually verify that it's working! Also using Postman I can see the response that I need!
Postman Response:
The header with the 2 headers (content-length and transfer-encoding):

The response body that I need that i can see being returned:

So finally my question is, is there anything i can do from my side (client) to avoid the error and read that http response from the server (even though the format is wrong)? How come I can see the body in Postman? Any ideas would be truly appreciated!
Using node v6.10.3
Reference:
(1) https://jira.spring.io/browse/SPR-15212


text:
Q: Python 3 how to properly return a value in function for later use I'm a python newbie. I created a calculator program that will accept 2 number and a type of operation from user. I already have a working code for this but I want to further simplify the code by exploring and using function.
Here's the portion of the code:
def addition(num1,num2):
    sum = num1 + num2
    print('The sum is ', sum)
def subtraction(num1,num2):
    sub = num1 - num2
    print('The difference is ', sub)
def inputNumber():
    num1 = float(input('Enter the first number: '))
    num2 = float(input('Enter the second number: '))
    return num1,num2
print('Enter the corresponding number to perform the operation:\n')
print('1 - addition')
print('2 - subtraction')
print('q - quit')
while True:
    try:
        operation = input('Select operation > ').lower()
    if operation == 'q':
        break
    elif operation == '1':
        addition(inputNumber())
    elif operation == '2':
        subtraction(inputNumber())
    else:
        print('Not valid. Try again.')
except:
    print('Invalid!')

My problem is after entering 2 numbers it doesn't perform the operation. I think the problem is the 2 input values didn't return properly.
Thanks

A: This should help. inputNumber function is returning a single tuple of both your float.
def addition(num):    #--->Update
    sum = num[0] + num[1]     #--->using index to get first and second number.
    print('The sum is ', sum)
def subtraction(num):    #--->Update
    sub = num[0] - num[1]      #--->using index to get first and second number.

    print('The difference is ', sub)
def inputNumber():
    num1 = float(input('Enter the first number: '))
    num2 = float(input('Enter the second number: '))
    return num1,num2                 #-----> Returns a tuple. EX: (3.0, 4.0)
print('Enter the corresponding number to perform the operation:\n')
print('1 - addition')
print('2 - subtraction')
print('q - quit')
while True:
    try:
        operation = input('Select operation > ').lower()
        if operation == 'q':
            break
        elif operation == '1':
            addition(inputNumber())
        elif operation == '2':
            subtraction(inputNumber())
        else:
            print('Not valid. Try again.')
    except Exception, e:
        print('Invalid!', e)

A: def addition((num1,num2)):
    sum = num1 + num2
    print('The sum is ', sum)
def subtraction((num1,num2)):
    sub = num1 - num2
    print('The difference is ', sub)
def inputNumber():
    num1 = float(raw_input('Enter the first number: '))
    num2 = float(raw_input('Enter the second number: '))
    return num1,num2
print('Enter the corresponding number to perform the operation:\n')
print('1 - addition')
print('2 - subtraction')
print('q - quit')
while True:
    try:
        operation = raw_input('Select operation > ').lower()
        if operation == 'q':
            break
        elif operation == '1':
            import pdb;pdb.set_trace()
            addition(inputNumber())
        elif operation == '2':
            subtraction(inputNumber())
        else:
            print('Not valid. Try again.')
    except:
        print('Invalid!')

*

*Use raw_input to take inputs from user containing string as well as int (applicable for python 2 only)

*Check Try except indentation.

*return keyword returns in a tuple, so modify addition and subtraction.

A: The problem is that your functions expect two inputs, but get a tuple (that is what a function return when you use return foo, bar)
you can expand the tuple using an astrix like this (also fixed indentation issue):
def addition(num1,num2):
    sum = num1 + num2
    print('The sum is ', sum)
def subtraction(num1,num2):
    sub = num1 - num2
    print('The difference is ', sub)
def inputNumber():
    num1 = float(input('Enter the first number: '))
    num2 = float(input('Enter the second number: '))
    return num1,num2
print('Enter the corresponding number to perform the operation:\n')
print('1 - addition')
print('2 - subtraction')
print('q - quit')
while True:
    try:
        operation = input('Select operation > ').lower()
        if operation == 'q':
            break
        elif operation == '1':
            addition(*inputNumber())
        elif operation == '2':
            subtraction(*inputNumber())
        else:
            print('Not valid. Try again.')
    except:
        print('Invalid!')


text:
Q: Extract and unzip an email attachment I have a piece of Python code that trawls my email inbox for a specific daily email based on the sender and the subject line and then downloads the attachment to a local drive for later use.  The attachment was a csv file and the code worked fine.  Now the sender has changed the attachment to be a zipped file.
How do I amend my code to be able to download the zip and extract the csv file?
I have tried some of the solutions provided on this site but I cannot get the them to work so I thought it might be worth seeing if anyone had any way to amend the code I already have.
extract attachment


text:
Q: subquery mysql to get realted data from three tables I am fetching related data from 3 tables.
table useracc has users account transactions with order id in details column. This is basic table on which query to find 'gift%' in details column runs...
"SELECT * FROM `useracc` WHERE `details` LIKE 'gift%' ORDER BY `id` DESC"

Now i want to fetch the Order id from these results in details column which is given as 'gift order id:245'. i want this 245 and run another query to look for 245 in 2nd table i.e. transaction.
i want to fetch column senderemail in table transaction where column orderid is 245. suppose this returns abc@abc.com
now in third table i.e. users i want to find the username related to that email.
i want to run query to fetch column username in table users where useremail is abc@abc.com.
this username is to be displayed in every row of table format containing the results of our first query
how can i do this using subquery. please help

A: SELECT u.username, ua.*
FROM useracc AS ua
JOIN transaction AS t ON ua.details = CONCAT('gift order id:', t.id)
JOIN users AS u ON u.useremail = t.senderemail
WHERE ua.details LIKE 'gift order id:%'
ORDER BY ua.id DESC

The WHERE clause isn't strictly necessary, since it's redundant with the ON condition. But it might speed up the query -- try it with and without and see which is faster.


text:
Q: Background color changes while scrolling I was randomly browsing the net when I chanced upon this site:
http://www.libertyinnorthkorea.org/summit/
I was intrigued by how the background color changes while scrolling down the page. As a newbie web developer I want to inquire if you guys know how it was programmed, did they used JavaScript, flash and PHP? Do you guys have any sample code for this?

A: You can use the window.onscroll event and body.scrollTop property in javascript.


text:
Q: Using custom loader and criteria in Hibernate Assume that in my existing production database, I have a table Students. Majority of students are ex. students, which I would like to separate from current students. More specifically, I'd like to keep Students table for students that are currently enrolled and move the other ones to Students_history table. Likewise with some other tables connected to Students. The motivation for this is that want to have (school_name, student_id) as a primary key, and sometimes same schools will reassign student_id, thus I will have same student_id for some student that graduated 10 years ago and another that is currently enrolled. This student_id is something beyond my control, it's from the data coming into the application. The second thing is that many operations on my table will be much faster, as there are much less current students than all students (including ones that graduated).
The best solution I was able to find includes defining triggers on Students table, where deleting them moves students (and other data that references student entries) to the corresponding Student_history table. The part I'm trying to figure out is how to make Hibernate work with this. I'd like to show entries from both tables (Students and Students_history) in the web app, just like it's working currently. To show this data in web interface, I'm using GWT, where data is fetched using:
Criteria criteria = session.createCriteria(Students.class);

Using criteria helps greatly when sorting and filtering items in web app. I've tried specifying custom query for loading, like this:
@Entity
@Table(name = "Students")
@Loader(namedQuery = "students")
@NamedNativeQuery(name = "students", query = "select * from students union all select * from students_history WHERE Id = ?", resultClass = Students.class)

After the query follows a definition of Students class. This does not work - the query that Hibernate generates with the forementioned criteria does not include any mention of students_history.
I'm using postgreSQL, Hibernate 4 and Java 1.6.
My questions are:

*

*Am I on the right track separating current and old students? By this, I mean using helper table and stored procedures upon deletion.

*Can Hibernate criteria work with custom loading query defined with @Loader annotation? I expected that Hibernate will use my loader query as a basis for criteria. If this is possible, any code snippet or link will be welcome.

A: Named queries are a feature that helps you reuse you HQL/SQL interrogations.
They don't anything to do with the Criteria API, which is a different way of selecting from the database. So there is no way the Criteria will use your loader query.
Think about is this way: the Criteria API builds an SQL query from scratch using the criteria you provide. In your case, it would have to first interpret your loader query and then build around it a correct SQL.


text:
Q: Trigger On Very Short Pulse - VHDL I'm using a CMOD A7 (Artix 7) and I need to trigger a process based on a pulse of around 10ns duration (blue line):

Normally I'd do triggering like this by having a process constantly compare the current value of the input line with the last value using a temporary register to hold the last value. However, I believe the oscillator on this board has a period of around 83ns which is far too slow for this approach.
If I was using pure digital electronics, this would be easy, connect a flipflop to the trigger, poll the output of that flipflop (which would change and latch with the input) and then reset it once I've read it and started my actions. So I would imagine there's a way to do this in VHDL but I'm led to believe using if rising_edge() on non-clock signals is a no-go.
Where do I start with this?

A: So the solution here is twofold:
Firstly, I can derive a 100MHz clock using the onboard MCCM and Vivado's ClockWiz IP.
I can also use the FDCE component provided by Vivado to utilise one of the onboard flipflops to extend the pulses and reset it after passing it through a few flipflops for synchronisation.
I've not tested this yet but I believe it should work:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
library unisim;
use unisim.vcomponents.all;

entity input_syncroniser is
    generic
    (
        in_pipe_len: in positive := 5
    );

    port
     (
        clk : in STD_LOGIC;
        rst : in STD_LOGIC;
        din : in STD_LOGIC;

        dfo : out STD_LOGIC
      );
end input_syncroniser;

architecture behavioural of input_syncroniser is

    signal delayed_pulse:   std_logic := '0';
    signal in_pipe:         std_logic_vector(in_pipe_len - 1 downto 0) := (others => '0');
    signal pipe_head:       std_logic := '0';

begin

    FDCE_inst : FDCE
    generic map
    (
        INIT => '0'
    )
        port map
    (
        Q => delayed_pulse,
        C => din,
        CE => '1',
        CLR => pipe_head,
        D => '1'
    );

    input_synchroniser: process(clk)
    begin
        if (rising_edge(clk)) then
            in_pipe <= in_pipe(in_pipe'high downto in_pipe'low) & delayed_pulse;
        end if;
    end process;

    pipe_head <= in_pipe(in_pipe'high);
    dfo <= pipe_head;

end behavioural;


text:
Q: R question, how to plot a histgram when the given data is range?
I know how to plot the data if the data is given one to one, but I am wondering how to plot a histogram of it if the data is given in a range

A: Try this approach as mentioned by @stefan using geom_bar() as you have the values summarised. Here the code using tidyverse functions:
library(tidyverse)
#Data
df <- data.frame(Class.limits=c('90-98','99-107','108-116','117-125','126-134'),
                 Frequency=c(6,22,43,28,9),stringsAsFactors = F)
#Plot
df %>% mutate(Class.limits=factor(Class.limits,levels = unique(Class.limits),ordered = T)) %>%
  ggplot(aes(x=Class.limits,y=Frequency))+
  geom_bar(stat = 'identity',color='black',fill='red',alpha=0.5)+
  theme_bw()+
  theme(axis.text = element_text(color='black',face='bold'),
        axis.title = element_text(color='black',face='bold'))

Output:


text:
Q: Error android.content.res.Resources$NotFoundException: File from xml type layout resource ID #0x102000a Hey, I'm trying to create a design for a list that looks like (and mostly behaves like) the call log, like shown here:

For this I downloaded the source code and I'm studying it for know what class and xml file implement it.
And I found this two xml files recent_calls_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="?android:attr/listPreferredItemHeight"
android:paddingLeft="7dip">

<com.psyhclo.DontPressWithParentImageView
    android:id="@+id/call_icon" android:layout_width="wrap_content"
    android:layout_height="match_parent" android:paddingLeft="14dip"
    android:paddingRight="14dip" android:layout_alignParentRight="true"

    android:gravity="center_vertical" android:src="@android:drawable/sym_action_call"
    android:background="@drawable/call_background" />

<include layout="@layout/recent_calls_list_item_layout" />

and the other is recent_calls_list_item_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

<View android:id="@+id/divider"
    android:layout_width="1px"
    android:layout_height="match_parent"
    android:layout_marginTop="5dip"
    android:layout_marginBottom="5dip"
    android:layout_toLeftOf="@id/call_icon"
    android:layout_marginLeft="11dip"
    android:background="@drawable/divider_vertical_dark"
/>

<ImageView android:id="@+id/call_type_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="4dip"
/>

<TextView android:id="@+id/date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/divider"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="8dip"
    android:layout_marginLeft="10dip"

    android:textAppearance="?android:attr/textAppearanceSmall"
    android:singleLine="true"
/>

<TextView android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="36dip"
    android:layout_marginRight="5dip"
    android:layout_alignBaseline="@id/date"

    android:singleLine="true"
    android:ellipsize="marquee"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:textStyle="bold"
/>

<TextView android:id="@+id/number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/label"
    android:layout_toLeftOf="@id/date"
    android:layout_alignBaseline="@id/label"
    android:layout_alignWithParentIfMissing="true"

    android:singleLine="true"
    android:ellipsize="marquee"
    android:textAppearance="?android:attr/textAppearanceSmall"
/>

<TextView android:id="@+id/line1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@id/divider"
    android:layout_above="@id/date"
    android:layout_alignWithParentIfMissing="true"
    android:layout_marginLeft="36dip"
    android:layout_marginBottom="-10dip"

    android:textAppearance="?android:attr/textAppearanceLarge"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:gravity="center_vertical"
/>

And my activity is this:
public class RatedCalls extends ListActivity {

private static final String LOG_TAG = "RecentCallsList";
private TableLayout table;
private CallDataHelper cdh;
private TableRow row;
private TableRow row2;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.recent_calls_list_item);
    Log.i(LOG_TAG, "calling from onCreate()");

    cdh = new CallDataHelper(this);
    table = new TableLayout(getApplicationContext());
    row = new TableRow(getApplicationContext());

    startService(new Intent(this, RatedCallsService.class));
    Log.i(LOG_TAG, "Service called.");
    fillList();

}

public void onResume() {

    super.onResume();
    fillList();

}

public void fillList() {

    List<String> ratedCalls = new ArrayList<String>();
    ratedCalls = this.cdh.selectTopCalls();

    setListAdapter(new ArrayAdapter<String>(RatedCalls.this,
            android.R.id.list, ratedCalls));

    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            Toast.makeText(getApplicationContext(),
                    ((TextView) view).getText(), Toast.LENGTH_LONG).show();
        }
    });

}

}
And then I tried to run it on the android emulator, and then it the LogCat returned an error like this:

Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

So inside the recent_calls_list_item.xml I declared this:
<ListView android:id="@android:id/list" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:layout_x="1px"
    android:layout_y="1px">
</ListView>

And now with this declared I tried to run in the emulator, but the LogCat returns another error:

android.content.res.Resources$NotFoundException: File  from xml type layout resource ID #0x102000a

So, my question is, why is this happening? And if you have another solution for implement a view like this I'm trying.
Thanks.

A: I had the same problem. I was setting the text like this:
statusView.setText(firstVisiblePosition);

The problem was that firstVisiblePosition was an integer. Compiler didn't complain. Fixed it by
statusView.setText(""+firstVisiblePosition);

A: Sounds lame but if you are using Eclipse, have you tried cleaning and rebuilding your project? That fixed a similar problem I was having.

A: I am also able to solve the problem by converting the Integer value to String while using:
name.setText(name_value_needs_to_be_string);

where name is a TextView.

A: The compiler interprets your int argument as a resource reference and assumes you are calling:
 public final void setText (int resourceId)

but your intention was to call
 public final void setText (CharSequence text)

To fix it, do like so:
myTextView.setText(Integer.toString(myIntegerValue));

A: set the id of your listView to
android:id="@id/android:list"

I dont know, whether
android:id="@android:id/list"

does work correctly

A: Just Clean and rebuild you project. it will work.

A: I solved this problem by copying XML file from layout-land directory to layout (or vice versa). Some devices have default landscape mode, others portrait. If that file does not exist in that mode, it throws this exception.

A: In my case, just some id in my xml was incorrect. Check your ids in your layouts
Error reference:

app:layout_constraintBottom_toBottomOf="@id/loginEmail"

Real reference:

app:layout_constraintBottom_toBottomOf="@id/loginEmailEntryCode"


text:
Q: Consider a measure space $(X,\mathcal{M},\mu$). Prove that if $\lambda$ is a measure on $\mathcal{M}$ such that $\lambda(B) \geq \mu(B)$, for all $B \in \mathcal{M}$, then there exists a measure $\nu$ on $\mathcal{M}$, such that $\lambda = \mu + \nu$.
Define $\nu$ such that for all $B \in \mathcal{M}$ such that $\lambda(B) = \infty$ we have $\nu(B) = \infty$, and for all $B \in \mathcal{M}$ such that $\lambda(B) < \infty$ we have $\nu(B) = \lambda(B) - \mu(B)$. Clearly for all $B \in \mathcal{M}$ we have $\lambda(B)  = \mu(B) + \nu(B)$. So it suffice to show $\nu$ is a measure on $\mathcal{M}$. Since for all $B \in \mathcal{M}$ we have $\lambda(B) \geq \nu(B)$, it follows that $\nu(B) = \lambda(B) - \mu(B) \geq 0$. Since $\lambda(\emptyset) = 0 < \infty$ it follows that $\nu(\emptyset) = \lambda(\emptyset) - \mu(\emptyset) = \lambda(\emptyset) - 0 = \lambda(\emptyset) = 0$ where the second equality holds from the fact that $\mu$ is a measure and the fourth equality holds from the fact that $\lambda$ is a measure. Now consider an arbitrary countable collection of disjoint set $\{E_j\}_{j = 1}^\infty \in \mathcal{M}$ such that  $\cup_{j = 1}^\infty E_j \in \mathcal{M}$. Suppose $\lambda(\cup_{j = 1}^\infty E_j) < \infty$, it follows that $\nu(\cup_{j = 1}^\infty E_j) = \lambda(\cup_{j = 1}^\infty E_j) - \mu(\cup_{j = 1}^\infty E_j) = \sum_{j = 1}^\infty \lambda(E_j ) - \mu(\cup_{j = 1}^\infty E_j)= \sum_{j = 1}^\infty \lambda(E_j) - \sum_{j = 1}^\infty \mu(E_j) = \sum_{j = 1}^\infty (\lambda(E_j) - \mu(E_j)) = \sum_{j = 1}^\infty \nu(E_j)$
were the second equality holds from the fact that $\lambda$ is a measure on $\mathcal{M}$ and the third equality holds from the fact that $\nu$ is a measure on $\mathcal{M}$.
MY PROBLEM: I don't know how to prove if $\lambda(\cup_{j = 1}^\infty E_j) = \infty$ then $\nu(\cup_{j = 1}^\infty E_j) = \sum_{j = 1}^\infty \nu(E_j)$.
I think in the case where one of the $\lambda(E_i) = \infty$ it suffices to say $\nu(\cup_{j = 1}^\infty E_j) = \lambda(\cup_{j = 1}^\infty E_j) = \sum_{j = 1}^\infty \lambda(E_j) = \infty = \nu(E_i) = \sum_{j = 1}^\infty \nu(E_j)$. But I don't know how to go about proving if $\sum_{j = 1}^\infty \lambda(E_j) = \infty$ that $\sum_{j = 1}^\infty
 \lambda(E_j) - \mu(E_j) = \infty$ as well?

A: If we let $\nu(B)=\infty$ when $\lambda(B)=\infty$ and $\nu(B)=\lambda(B)-\mu(B)$ if $\lambda(B)<\infty$, then we run into a problem for $\sigma$-additivity, for example if $(B_n)$ is a sequence of disjoint sets such that $\lambda(B_n)=n^{-1}+n^{-2}$ and $\mu(B_n)=n^{-1}$, then $B:=\bigcup_{n\geqslant 1}B_n$ has an infinite $\lambda$-measure hence $\nu(B)$ is infinite but $\sum_{n\geqslant 1}\nu(B_n)$ is finite. Letting  $\nu(B)=0$ when $\lambda(B)=\infty$ does not work for the same reason.
Instead, it was suggested in the comments to define
$$
\nu(B):=\sup\left\{\lambda(A)-\mu(A), A\in\mathcal M, A\subseteq B, \mu(A)<+\infty\right\}.
$$
We have to check that $\nu$ does the job.

*

*$\nu(\emptyset)=0$ since the only subset of $\emptyset$ is $\emptyset$ and
$\lambda(\emptyset)-\mu(\emptyset)=0$.

*Also, we observe that if $B\subset B'$, then $\nu(B)\leqslant \nu(B')$ because
every subset of $B$ is also a subset of $B'$.

*We have to check the equality $\lambda(B)=\mu(B)+\nu(B)$. If $\mu(B)$ is infinite, this is trivial since $\lambda(B)$ is also infinite. If $\mu(B)$ is finite, then $\nu(B)=\mu(B)$ hence the equality hold.

*It remains to check the $\sigma$-additivity. Let $\left(B_j\right)_{j\geqslant 1}$ be a sequence of pairwise disjoint elements of $\mathcal M$. First we prove the sub-additivity. Let $B:=\bigcup_{n\geqslant 1}B_n$. Then
$$
\nu(B)=\sup\left\{\sum_{j\geqslant 1}\lambda(A\cap B_j)-\mu(A\cap B_j), A\in\mathcal M, A\subseteq B, \mu(A)<+\infty\right\}\\\leqslant
\sum_{j\geqslant 1}\sup\left\{\lambda(A\cap B_j)-\mu(A\cap B_j), A\in\mathcal M, A\subseteq B, \mu(A)<+\infty\right\}
$$
and if $A\in\mathcal M$ is such that $A\subseteq B$, then $A\cap B_j\subset B_j$ and has finite $\mu$-measure hence
$$
\sup\left\{\lambda(A\cap B_j)-\mu(A\cap B_j), A\in\mathcal M, A\subseteq B, \mu(A)<+\infty\right\}\leqslant \nu(B_j),
$$
which proves that $\nu\left(\bigcup_{j\geqslant 1}B_j\right)\leqslant \sum_{j\geqslant 1}\nu(B_j)$.

For the other direction, in view of the second bullet, we can assume that $\nu(B_j)$ is finite for all $j$. Let $\varepsilon$ be fixed. By definition of $\nu$, we can find $A_j\in\mathcal M$ such that $\mu(A_j)$ is finite and
$\lambda(A_j)-\mu(A_j)>\nu(B_j)-\varepsilon 2^{-j}$. Let us fix $J\geqslant 1$ (we have to truncate the union because we are not sure that $\bigcup_{j\geqslant 1}\mu(A_j)$ is finite). Using again the second bullet, we derive that
$$
\nu\left(\bigcup_{j\geqslant 1}B_j\right)\geqslant\nu\left(\bigcup_{j= 1}^JB_j\right).
$$
Now, $\bigcup_{j=1}^J A_j$ belongs to $\mathcal M$, its $\mu$-measure is finite and is contained in  $\bigcup_{j= 1}^JB_j$ hence
$$
\lambda\left(\bigcup_{j=1}^J A_j\right)-\mu\left(\bigcup_{j=1}^J A_j\right)
\leqslant \nu\left(\bigcup_{j= 1}^JB_j\right).
$$
Since $A_j\subset B_j$ and the $B_j$ are disjoint, we derive that
$$
\nu\left(\bigcup_{j= 1}^JB_j\right)\geqslant \sum_{j=1}^J\lambda(A_j)-\mu(A_j)
\geqslant\sum_{j=1}^J\nu(B_j)-\varepsilon.
$$
We got in total that for all $J\geqslant 1$ and all $\varepsilon>0$,
$$
\nu\left(\bigcup_{j\geqslant 1}B_j\right)\geqslant\sum_{j=1}^J\nu(B_j)-\varepsilon
$$
hence we can conclude.


text:
Q: Builder c++ Rave Reports encoding problem with cyrillic When  i  try save rave project in pdf\html file, have incorrect encoding.
When choose format  and press SAVE, it ussually  save in iso-8859-1 code.
But i need cp1251 (cyrillic).
For example "Ïëîùàäü" instead of "Площадь".

A: I would guess that the best solution to your problem would be to use Unicode, rather than a codepage such as CP1251. Is it possible to use Unicode with Rave Reports?

A: I have the same problem when I want o save reprt to pdf format. I have to create TRvRenderPDF and set it as RenderObject but pdf file was viewed not correctrly.

*

*The TRvRenderPDF component not unicode-compatible(that is very bad) that is why all text in report coverted into Ansi with active codepage(for cyrillic it is CP1251). Now we have pdf file with text in CP1251 encoding.

*As default TRvRenderPDF generate pdf with font TYPE1 Helvetica(by the standart of the format pdf it is build-in). But text is interpreted with encoding ISO 8859-1(or CP1252) but it encoding was CP1251 tha is why we have "Ïëîùàäü" or something analogous.

What we can to do:

*

*Get font TYPE1(CP1252) where service symbols(numbers like in cyrillic letters in CP1251) replaced with cyrillic glyphs. For example a link and we need to install it.

*Now we need tor replace old font name(Helvetica) from generated pdf document with new font name(AGHelvetica). You can dow it with text editor or i your's programm(read file -> find -> replace -> save file).

That all situation.
P.S. Sorry for my english.
P.P.S. If set property of pdf render EmbedBaseFonts = true, pdf document were saved with TrueType fonts, but problem stay. Neew to see to unicode render? but not this one.


text:
Q: How to draw text on picturebox? I googled for "Drawing text on picturebox C#" ,but I couldnt find anything useful.Then I googled for "Drawing text on form C#" and I found some code,but it doesnt work the way I want it to work.
    private void DrawText()
    {
        Graphics grf = this.CreateGraphics();
        try
        {
            grf.Clear(Color.White);
            using (Font myFont = new Font("Arial", 14))
            {
                grf.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new PointF(2, 2));
            }
        }
        finally
        {
            grf.Dispose();
        }
    }

When I call the function,the background color of the form becomes white(it's black by default).
My questions:
1:Will this work on a picturebox?
2:How to fix the problem?

A: You don't want that call to Clear() - that's why it's turning the background white, and it will cover up your picture.
You want to use the Paint event in the PictureBox. You get the graphics reference from e.Graphics, and then use the DrawString() that you have in your sample.
Here's a sample. Just add a picture box to your form, and add an event handler for the Paint event:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Font myFont = new Font("Arial", 14))
    {
        e.Graphics.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new Point(2, 2));
    }
}

(Note that you won't see the text at design time - you'll have to run the program for it to paint).


text:
Q: jpcap not printing out packets Trying to capture packets using jpcap.
However for some reason,my code will not print out packets.Only devices.
I don't understand why it's not working.
import jpcap.PacketReceiver;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.packet.Packet;
import jpcap.*;

public class JpcapTip implements PacketReceiver {
    public void receivePacket(Packet packet){
       System.out.println(packet);
      //  System.out.println(packet.toString());
    }

    public static void main(String[] args) throws java.io.IOException{
        NetworkInterface[] devices =  JpcapCaptor.getDeviceList();

        for (int i = 0; i < devices.length; i++) {
            System.out.println(devices[i].description); // devices[0]

        }

        NetworkInterface deviceName = devices[0];

        JpcapCaptor  jpcap = JpcapCaptor.openDevice(devices[0], 1028, false, 1);
        jpcap.loopPacket(-1, new JpcapTip());

        //
   }
}

My compiler output.-
run:
Microsoft
Qualcomm Atheros Ar81xx series PCI-E Ethernet Controller
Microsoft
java.lang.NoSuchMethodError: setRoutingOption
    at jpcap.JpcapCaptor.nativeOpenLive(Native Method)
    at jpcap.JpcapCaptor.openDevice(JpcapCaptor.java:68)
    at JpcapTip.main(JpcapTip.java:23)


text:
Q: AngularJS directive communication and page template - inner directive doesn't work Have some trouble with directive communication and in particular with inner and outer custom tags.
So, I have the following HTML code:

<title>Directives</title>

<meta charset="utf-8">

    <outer>
        <inner></inner>
    </outer>

And I have the following JavaScript code for my AngularJS directives:
var app = angular.module("app", []);

app.directive("outer", function() {
    return {
        template: "
This is outer message
",
        restrict: "E",
        replace: false,
        controller: function() {
            this.say = function(message) {
                console.log(message);
            }
        }
    }
});

app.directive("inner", function() {
    return {
        restrict: "E",
        require: "^outer",
        replace: false,
        controller: function($scope) {},
        link: function(scope, element, attrs, outerCtrl) {
            outerCtrl.say("This is inner message");
        }
    }
});

It looks very simple. I want to display one message to the screen and another one to console logger. But the second one doesn't appear until I comment template: "
This is outer message
" line! I suppose that the problem is connected with page rendering (link and compile functions). Actually I've got confused with it and I can't fix this bug.
Can anyone help me?

A: If you provide a template, it will replace the content of <outer> (the replace option only controls whether the <outer> tag is replaced as well).
Because of that, the <inner> directive is no longer linked. If you want to provide a template while still linking the inner tag. You need to use a transclusion:
app.directive("outer", function() {
    return {
        template: "
This is outer message

",
        restrict: "E",
        replace: false,
        transclude: true,
        controller: function() {
            this.say = function(message) {
                console.log(message);
            }
        }
    }
});

This will insert inner inside the div with ng-transclude.

A: You've stumbled upon the answer to your own question.  The template option of the outer directive will replace the elements
<outer>
  <inner></inner>
<outer>

with your template to just be

This is outer message

thus removing the inner directive from being instantiated.  Take a look at the difference of the DOM using your dev tools to see how it's different using the template and not using it


text:
Q: Do all graphs of C1 functions have Hausdorff dimension 1? Suppose f is a real-valued function of one variable, and suppose f is of differentiability class C1.  My question is, if $\Gamma$ is the graph of f, then must $\dim_H(\Gamma)=1$?  If anyone knows of a published proof of the answer, I'd appreciate a reference greatly.

A: Let $f \colon I \to \mathbb{R}$. Since $f$ is $C^1$, the graph $\Gamma_f$ is locally bilipschitz to $I$, via the projection. It follows that Hausdorff dimension is the same as that of $I$ (being defined in terms of the metric space structure only), so it is $1$.
Disclaimer: I haven't seen these topics for quite a while, so I may have said something stupid.

A: In spirit, the solution is in any calculus book, using the length formula
$$L(f) = \int_a^b \sqrt{f'(x)^2+1} dx.$$
You also need the theorem that a continuous function on a closed interval is bounded.


text:
Q: Product ID for in app purchase My app id is like com.MyApp-01. I have to use in app purchase in my app.What product id should i create on iTunes. As per apple rules i need to create product id like com.MyApp-01.productID for testing but i can't add  this symbol '-'in product id .

A: The product ID doesn't have to start with your bundle ID. You can simply drop the dash and use com.MyApp.productID, or even just productID.


text:
Q: jQuery fadein image on change then fadeout on load I have some simple image slider that I've made. I have list of small images, and whenever one of them is clicked, I replace source of target big image with clicked (+ some manipulation with src to get bigger image from server).
Now I want on small image click to fadeout big image, and when new image is loaded to fade it in.
Tried with this code:
ul.find('img').click(function() {
    $('#big_image')
        .fadeOut()
        .attr('src', this.src.replace('/small/', '/big/')) // Some other src
        .load(function() {
            $(this).fadeIn();
        });
});

Problem with this is that when browser caches images, onclick image is immediately loaded, and then faded in and out, which looks a bit annoying.
This:
ul.find('img').click(function() {
    $('#big_image')
        .load(function() {
            $(this).fadeIn();
        })
        .attr('src', this.src.replace('/small/', '/big/'))
        .load(function() {
            $(this).fadeIn();
        });
});

does not fade at all.
Any idea?

A: Fixed with
ul.find('img').click(function() {
    $('#big_image').fadeOut(500, function() {
        $(this).attr('src', this.src.replace('/small/', '/big/'))
            .load(function() {
                $(this).fadeIn();
            });
    });
});

A: When I did something like this I used this jQuery plugin:
http://flesler.blogspot.com/2008/01/jquerypreload.html
It can automatically load a large image and replace a small one with it. The library doesn't automatically fade them, it just switches them, but it does give you a handle to trigger an event when the large image is done loading.


text:
Q: NSDate from stange looking string I have an NSDictionary with the value for date as:
 "Date":"/Date(1314313200000+0100)/",
How can I turn this into an NSDate as it contains strings lie "Date": and / ?

A: 1314313200000 is milliseconds since the epoch-date (1970-01-01), and 0100 is the timezone. You need to parse this info out from the string and build a date from it. The NSScanner class is a good fit for parsing information out of strangely formatted text.
// Init a scanner with your date string
NSScanner* scanner = [NSScanner scannerWithString:@"Date:/Date(1314313200000+0100)/"];
// Skip everything up to a valid numeric character
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
                        intoString:NULL];
// Parse numeric value into a 64bit variable
long long milliseconds = 0;
[scanner scanLongLong:&milliseconds];
// Create a date instance from milliseonds sinve 1970-01-01
NSDate* date = [NSDate dateWithTimeIntervalSince1970:milliseconds / 1000.0];

If the time-zone is also important just skip the + sign and parse a new number.


text:
Q: How many ways to place $n$ balls in $k$ bins with the minimum number of balls in any bin equal to $m$? I apologize if this question does not make sense.
I have $k$ bins and $n$ balls. $m$ represents the size of the smallest bin in terms of how many balls it contains.
For example if I have five bins and balls distributed as such: 2,3,5,2,4: $m$ here is 2.
So based on having $n$ balls and $k$ bins with a minimum bin size of $m$, how many ways are there to arrange this?

A: I assume from your example that the balls are indistinguishable, but the bins are not.
Let us first answer the question for "every bin has at least $m$ balls": Since each of the $k$ bins must have at least $m$ balls, we can remove $m$ balls from each bin: after removing these $mk$ balls, what we are left with is a distribution of $n - mk$ balls into $k$ bins, with any sort of distribution allowed. (Equivalently, we want the number of integer solutions to $y_1 + \dots y_k = n$ where each $y \ge m$; we can set $x_i = y_i - m$ and ask for nonnegative solutions to $x_1 + \dots + x_k = n - mk$ instead.)
The number of ways of distributing $(n-mk)$ balls into $k$ bins, or the number of nonnegative integer solutions to $x_1 + \dots + x_k = n - mk$, is $$\binom{n-mk+k-1}{k-1}$$
(see "stars and bars"), so that is the answer to our question (every bin having at least $m$ balls).
Now to your question, that the minimum number of balls among all bins is exactly $m$ (rather than at least $m$). This precisely means that:

*

*every bin has at least $m$ balls

*not every bin has at least $m+1$ balls

So we just subtract the number of solutions where every bin has at least $m + 1$ balls as above, getting the answer:
$$\binom{n-mk+k-1}{k-1} - \binom{n-mk-1}{k-1}$$

A: Let there be $x_i$ balls in bin $i$ where $i=1...k$. The total number of balls being $n$ means that
$x_1+x_2+...+x_k=n$.
Since each $x_i>=m$ you may define $y_i=x_i-m$ and have $y_i>=0$, and also
[1] $y_1+y_2+...+y_k=n-mk.$
Now you want at least one of these $y_k$ to be $0$, which complicates the count.
That is, there is a standard formula for the number of solutions to [1] if you just require nonnegative $y_i$, but requiring at least one of them to be zero may be harder.
Maybe an approch based on the fact that "at least one being 0" is the complement of "all being at least 1" will help.


text:
Q: How to invoke my custom decoder in android source code I am trying to add my software HEVC decoder to android source code. I wish to generate the libstagefright.so file.
I have referred to other similar questions and were not of much help for me. I was not able to get a clear picture with the following questions or the reference guide.
1)Integrating a Codec to Android multimedia framework.
2)Integrate a custom decoder to play on android and display fps at the same time.
3)How to register a OMX core for adding a new decoder.
Can someone please help me with the steps for integration of a new custom decoder with Android.
Right now, I have just added the  to media_codecs.xml and { "OMX.google.h265.decoder" , "hevcdec" , "video_decoder.hevc" } in SoftOMXPlugin.cpp file.
Which other files need to be edited for a new format to be added to android source code?
Which functions invoke my decoder source code(Does the softomxcplugin source file invoke my decoder ?).

A: From your query and earlier discussions, please find the steps to integrate a HEVC component into Android framework. Since, your component is a SW component, you would have to integrate the same as a SoftVideoDecoderOMXComponent.
What is SoftVideoDecoderOMXComponent?
In the latest releases of the Android Stagefright framework, SW accelerated codecs are integrated into the framework using an OMX like interface. Earlier, this wasn't the case and had some challenges of it's own. So, Google have streamlined the integration strategy and mandated that all SW codecs will employ a SoftOMXComponent like interface.
Majority of the OMX IL calls are handled by the base class and hence, the implementation of a new codec component is relatively easy as described below.
I would take the example of AVC codec integration to provide an overview. It is highly recommended that the reader is familiar with OMX IL 1.1.2 specification which describes the structure, functioning and state machine of an OMX IL video decoder component.
Note: HEVC is not yet a part of OMX IL specification and hence, the recommendation is mainly to understand the structure and functioning of the component.
Creation of SoftHEVC component
Please refer to the header file of SoftAVC.h and the corresponding source SoftAVC.cpp.
You will have to implement a similar set of files. It is highly recommended to reuse the overall implementation from AVC due to some inherent similarities.
SoftHEVC.cpp implementation

*

*You would have to define a SoftHEVC component in SoftHEVC.h which derives from SoftVideoDecoderOMXComponent. This would ensure that all OMX calls are handled suitably by the base class.

*You would have to define a table of support profile-level combinations as found in CodecProfileLevel.

*In the constructor, you can initialize most of the variables in a similar fashion. Since this is a video decoder component, you will have to initialize 2 ports viz.,input and output. ctor invokes a initDecoder to initialize the component. You would also have to implement a similar functionality for your codec.

*The dtor is self explanatory and hence, I will skip explaining the same.

*onQueueFilled is invoked when a buffer filled with a frame worth of bitstream data is provided for processing on input port or a free buffer is provided for output. This invokes the main decoding function H264SwDecDecode. Now, for the first frame, you could encounter a change in resolutions as compared to the originally initialized resolution. This is handled by 2 scenarios as described in the next point.

*You would observe 2 functions handlePortSettingsChanged and handleCropRectEvent. These 2 events are important from an output buffer's perspective. handlePortSettingsChanged signifies a change in the output buffer dimensions as compared to the originally initialized size and hence, provides an event callback to the user to free up the current allocation and reallocate the same.
handleCropRectEvent indicates that the __cropping window__which is communicated to the user. Usually, this doesn't require a buffer reallocation.

*drainOneOutputBuffer will copy the decoded frame onto the output port's buffer and notify the caller about the availability of the decoded buffer.

*In onQueueFilled, after a successful decode, the input buffer which has been consumed is also returned back to the caller.

*The rest of the functions are very straightforward and I feel you could simply reuse majority of the implementation.

*For registration of the component, you will have to implement createSoftOMXComponent which creates the SoftHEVC component as shown here.
Since, you have already handled the registered the component, I am skipping that part. Just for reference, I presume you have registered the component in kComponents array in SoftOMXPlugin. Also, since HEVC is not a known MIME type, you would have to register the same. There would be a change required in MediaDefs.cpp where you will have to introduce a new entry, MEDIA_MIMETYPE_VIDEO_HEVC similar to existing formats like AVC and support changes in OMXCodec.cpp and ACodec.cpp.
With these steps, I presume you should be able to integrate your SW decoder and be able to realize your playback.


text:
Q: M1 MacBookpro install brew when I install brew completely ,then I want to process "brew install redis",there is a problem "Error: Failed to download resource "openssl@1.1"
Download failed: https://ghcr.io/v2/homebrew/core/openssl%401.1-1.1.1k.arm64_big_sur.bottle.tar.gz"


text:
Q: MySQL Error: 1064 the ambiguous error Well, hello. I have this php script which is the backend process of my DataTables table. Here's the code:

<?php

session_start();

// $username = $_SESSION['username'];

if (empty($_SESSION['username'])) {
    session_destroy();
    header('location:login.php');
}

/*
 * Script:    DataTables server-side script for PHP and MySQL
 * Copyright: 2010 - Allan Jardine, 2012 - Chris Wright
 * License:   GPL v2 or BSD (3-point)
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Easy set variables
 */

/* Array of database columns which should be read and sent back to DataTables. Use a space where
 * you want to insert a non-database field (for example a counter or static image)
 */
$aColumns = array('id', 'date', 'wo_number', 'sheet_no', 'step', 'reg_no', 'start_time', 'finish_time', 'status_shift', 'status_working', 'personnel_name', 'title_WO');

/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "id";

/* DB table to use */
$sTable = "daily_activity_control_card-man";

/* Database connection information */
// $gaSql['user']       = "root";
// $gaSql['password']   = "";
// $gaSql['db']         = "hidden";
//$gaSql['server']     = "localhost";

$gaSql['user'] = "hidden";
$gaSql['password'] = "hidden";
$gaSql['db'] = "hidden";
$gaSql['server'] = "localhost";

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP server-side, there is
 * no need to edit below this line
 */

/*
 * Local functions
 */
function fatal_error($sErrorMessage = '')
{
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
    die($sErrorMessage);
}

/*
 * MySQL connection
 */
if (!$gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password'])) {
    fatal_error('Could not open connection to server');
}

if (!mysql_select_db($gaSql['db'], $gaSql['link'])) {
    fatal_error('Could not select database ');
}

/*
 * Paging
 */
$sLimit = "";
if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
    $sLimit = "LIMIT " . intval($_GET['iDisplayStart']) . ", " .
        intval($_GET['iDisplayLength']);
}

/*
 * Ordering
 */
$sOrder = "";
if (isset($_GET['iSortCol_0'])) {
    $sOrder = "ORDER BY  ";
    for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
        if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
            $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . "
                    " . ($_GET['sSortDir_' . $i] === 'asc' ? 'asc' : 'desc') . ", ";
        }
    }

    $sOrder = substr_replace($sOrder, "", -2);
    if ($sOrder == "ORDER BY") {
        $sOrder = "";
    }
}

/*
 * Filtering
 * NOTE this does not match the built-in DataTables filtering which does it
 * word by word on any field. It's possible to do here, but concerned about efficiency
 * on very large tables, and MySQL's regex functionality is very limited
 */
$sWhere = "";
if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
    $sWhere = "WHERE (";
    for ($i = 0; $i < count($aColumns); $i++) {
        if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true") {
            $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch']) . "%' OR ";
        }
    }
    $sWhere = substr_replace($sWhere, "", -3);
    $sWhere .= ')';
}

/* Individual column filtering */
for ($i = 0; $i < count($aColumns); $i++) {
    if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
        if ($sWhere == "") {
            $sWhere = "WHERE ";
        } else {
            $sWhere .= " AND ";
        }
        $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
    }
}

/*
 * SQL queries
 * Get data to display
 */

$sQuery = " SELECT a.*, b.personnel_name, c.title_WO FROM `daily_activity_control_card-man` as a INNER JOIN `personnel_master_data` as b ON a.reg_no = b.reg_no INNER JOIN `work_order` as c on a.wo_number = c.wo_number
        $sOrder
        $sLimit
    ";
$rResult = mysql_query($sQuery, $gaSql['link']) or fatal_error('MySQL Error: ' . mysql_errno());

/* Data set length after filtering */
$sQuery = "
        SELECT FOUND_ROWS()
    ";
$rResultFilterTotal = mysql_query($sQuery, $gaSql['link']) or fatal_error('MySQL Error: ' . mysql_errno());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];

/* Total data set length */
$sQuery = "
        SELECT COUNT(" . $sIndexColumn . ")
        FROM   $sTable
    ";
$rResultTotal = mysql_query($sQuery, $gaSql['link']) or fatal_error('MySQL Error: ' . mysql_errno());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];

/*
 * Output
 */
/*
$output = array(
    "sEcho" => intval($_GET['sEcho']),
    "iTotalRecords" => $iTotal,
    "iTotalDisplayRecords" => $iFilteredTotal,
    "aaData" => array()
);
*/

while ($aRow = mysql_fetch_array($rResult)) {
    $row = array();
    for ($i = 0; $i < count($aColumns); $i++) {
        if ($aColumns[$i] == "version") {
            /* Special output formatting for 'version' column */
            $row[] = ($aRow[$aColumns[$i]] == "0") ? '-' : $aRow[$aColumns[$i]];
        } else if ($aColumns[$i] != ' ') {
            /* General output */
            $row[] = $aRow[$aColumns[$i]];
        }
    }
    $output['aaData'][] = $row;
}

echo json_encode($output);
?>

I get MySQL Error: 1064 when I try to run the php file, the file didn't gave me JSON response which I needed to display the data to my DataTables.
Can anyone help me with this?
Thank you.

A: Error 1064 says that your SQL syntax has an error.
Try putting backticks (`) around your table name. I believe MySQL will let you use dashes (-) in a table name, but you have to quote the table name when referring to it or you get an SQL syntax error.
$sQuery = "
    SELECT COUNT(" . $sIndexColumn . ")
    FROM   `$sTable`
";

A: I think when you are replacing "$sOrder", Your are not using alias for column name


text:
Q: How to parse simple math expressions using two variables in javascript I'm making a project to solve Runge-Kutta methods (numeric methods)
I need to parse simple maths expressions whit two variables from input text and paste in js code
For example this is one of the methods:

var x = 1, // this is the firt variable
    y = 2, // this is the second variable
    yn, fun, h = 0.05;

var i = 0;

// This is Euler method
while (x < 2) {

    i += 1;
    // this is the funcion and depends to two variables
    //here is when I need to paste the function using global variables
    fun = ((1 + x) / (1 + y));
    yn = y + h * (fun);
    console.log(" # " + i + " Yn+1 = " + yn + " Yn = " + y + " x = " + x + "\n");
    x += h;
    y = yn;

}

This is my idea for the html, is only design:
I need to take the value in the input text and parse it in js code

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link href="style.css" rel="stylesheet">
    <title>Document</title>

Runge-Kutta Methods

Enter the function in the terms of X and Y:

            <input type="text" value="((1 + x) / (1 + y))" id="input" class="form-control" />

H:

                                    <input type="number" value="H" id="input" class="form-control" />

X:

                                    <input type="number" value="X" id="input" class="form-control" />

f(X):

                                    <input type="number" value="Y" id="input" class="form-control" />

                  <button type="button" class="btn btn-default">Euler</button>

                  <button type="button" class="btn btn-default">Euler improved</button>

                  <button type="button" class="btn btn-default">Ralston</button>

                        Yn+1
                        Yn
                        X

A: If you want to parse simple maths expressions, you have to use , then you can replace your 'x' and 'y' and you can use the function you wrote in the input.
I used you example to calculate the result of the function on click on 'euler' button.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link href="style.css" rel="stylesheet">
    <title>Document</title>

Runge-Kutta Methods

Enter the function in the terms of X and Y:

            <input type="text" id="fun" value="((1 + x) / (1 + y))" id="input" class="form-control" />

H:

                                    <input type="number" value="0" id="inputh" class="form-control" />

X:

                                    <input type="number" value="0" id="inputx" class="form-control" />

f(X):

                                    <input type="number" value="0" id="inputy" class="form-control" />

                  <button type="button" class="btn btn-default" onclick="euler()">Euler</button>

                  <button type="button" class="btn btn-default">Euler improved</button>

                  <button type="button" class="btn btn-default">Ralston</button>

                        Yn+1
                        Yn
                        X


text:
Q: Ajax async call for new window today I am stacked with some question about async work of jquery ajax.I am pretty new to js and especially for jquery.
After click on button new tab opened and filled with pretty long request(a lot of data returned) and freeze other part of site (tab wi button) until request is done.
Is there any possibilitty to make it work async, so my old tab will work while request computating?
Current js code for open new window
window.open(request, '_blank')
Which one obviously not async
May be something like
Var O = window.open() ;
O. Ajax(blablabla)
UPD:
I solved problem by creating new  element with rel="norefferer" and imitate click on that element, so new tab will open in new process and don't block main tab

A: AJAX is async (it literally means "asynchronous JavaScript and XML").
You just need to use it properly, as follow :
$.ajax({
    url: "https://www.example.com",
    "success": function(result) {
        // This part will be called after the ajax request was successful
        /*
        insert your code here,
        but be aware that, as CBroe noted in the comments,
        window.open() could be blocked by modern browser
        */
    }
 });

Read the jquery documentation on AJAX for more info.


text:
Q: VMWare guest OS is not using full hard drive space I'm wondering if you can give me some insight on how to figure this out.  I've recently virtualized a w2k3 server that had 10GB C:\ drive size.  Once I finished virtualizing it, I expanded the disk to 20GB for C:\ and within guest OS (W2K3) computer management settings, you can see it recognizes as 20GB partition C:.  But for some reason, if I opened windows explorer and see the properties of C:\, it will only show total size of 10GB.
Does anyone know how to solve this?
EDIT: This is how I expanded my disk.  I used VMWare converter, used the option within VMWare converter to expand my C:\ partition.  After finishing virtualizing to ESXi server, I didn't touch it in W2k3.  No manual expansion of disk required in w2k3, it just reads it as 20GB while Windows Explorer shows 10GB still.
EDIT: this is exactly my problem according to vmware kb.
http://kb.vmware.com/selfservice/microsites/search.do?cmd=displayKC&docType=kc&externalId=1005890&sliceId=1&docTypeID=DT_KB_1_1&dialogID=74780861&stateId=0%200%2080507132
Anyone ever experienced this before?

A: It sounds like you have increased the size of the disk; but not the partition.
In Windows, Manage the computer, and go to Disk Management (Storage -> Disk Management).  Is the disk listed as "Basic" or "Dynamic"?
If it is Dynamic, your best bet is to use a P2V tool (VMware Converter, Platespin, etc) to create a new identical machine with bigger disks (Converter does this easily).  You simply tell converter it is a physical machine and walk through the prompts, giving the appropriate disks more space.  It handles the partition increase for you.
If the disk is still Basic, you can use a partition editor (I use a bootable ISO for the Gnome Partition Editor - gparted).
Warning - make sure you have good backups of your data.  Do this on a test system the first time - I am not responsible for lost data.
Shut down the VM cleanly (if the file system is not quiesced, the process will fail).  Boot from the gparted CD.  The partition editor will start, and you will see the partition and disk sizes are different.  Click Resize, drag the partition to fill the drive and hit apply.  You'll wait a bit while it works and then be told to reboot.  Voila!

A: An easier way to do what Cybersylum said is to just use Paragorn, should be faster as well I believe.


text:
Q: php json_encode() output skipping characters randomly I am using PHP 5.3.15 (cli) (built: Jul 20 2012 23:10:20) on an amazon ec2 instance. When I make a call to json_encode() the resulting JSON randomly skips characters so that the JSON is no longer valid. This happens only some of the time even when the call is made with the exact same parameters/data. The curious thing is that it happens in different spots, random spots, with no pattern. It does not happen with the same data and the same code, and the same version of PHP on my local MAMP installation

..."updateTime":"2012-12-21 03:24:14","createTime":"2012-12-21:"21","updateTime":"2012-12-25 19:33:25",...

You can see the effect above at the 21:"21".  I don't even know where to begin solving this problem.
I've rebooted and even created new virtual instances of the server.
I am in grievous need of help. Anything you could suggest would be awesome!!

A: you must set json encode Parameter for  QUOT or another
 $json=json_encode($array,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);

this is a sample of json encode that is on php.net
 <?php
   $a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");

   echo "Normal: ",  json_encode($a), "\n";
   echo "Tags: ",    json_encode($a, JSON_HEX_TAG), "\n";
   echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n";
   echo "Quot: ",    json_encode($a, JSON_HEX_QUOT), "\n";
   echo "Amp: ",     json_encode($a, JSON_HEX_AMP), "\n";
   echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
   echo "All: ",     json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT |JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";

   $b = array();

   echo "Empty array output as array: ", json_encode($b), "\n";
   echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";

   $c = array(array(1,2,3));

   echo "Non-associative array output as array: ", json_encode($c), "\n";
   echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";

    $d = array('foo' => 'bar', 'baz' => 'long');

   echo "Associative array always output as object: ", json_encode($d), "\n";
   echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
 ?>

output:
 Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
 Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
 Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
 Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
 Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
 Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"]
 All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]

 Empty array output as array: []
 Empty array output as object: {}

 Non-associative array output as array: [[1,2,3]]
 Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

 Associative array always output as object: {"foo":"bar","baz":"long"}
 Associative array always output as object: {"foo":"bar","baz":"long"}

A: I used a proxy to analyze what was going on. I was making two identical requests right after each other. It may be important to note that the requests were in objective-c and that it may not be php that was breaking, but merely the second request canceling the first.


text:
Q: Instrumenting bytecode at method level if(iHandles[f].getInstruction() instanceof IFEQ  ) {
            getFieldInstruction = iHandles[f+1].getInstruction();
            System.out.println("found IF");
            InstructionList iprint = iFactory.createPrintln("The control is in IF");
            iList.setPositions();
            main.setMaxStack();
            main.setMaxLocals();
            main.removeLineNumbers();
            iList.insert(getFieldInstruction, iprint);
            main.setInstructionList(iList);

        }

In the above code I am instrumenting the bytecode at if statements.
I'm using constants like IFEQ or IF_ICMPNE to search for an if statement in a bytecode.
I want to instrument the bytecode at every method. What constants can I use to do this ? Or how is it possible?

A: The above code works for if ... getFieldInstruction = iHandles[0].getInstruction();
to instrument methods.


text:
Q: How to get the title and description of a channel? I want to get the channel list description and its title like

https://www.youtube.com/playlist?list=PLzvCFYRLS3sJcpeaY2FECjhYOKGqW2ZDW

will show this information:

channel title: top 50 english songs 2014
channel description: pop slow romance the best (Y) top 50 songs
arrange randomly :) hope u enjoy my first playlist

This is the link I'm using, but it doesn't contain the channel description and channel list title:

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,contentDetails&maxResults=50&pageToken=&playlistId=PLzvCFYRLS3sJcpeaY2FECjhYOKGqW2ZDW&key=[youtube-api]

A:
https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=PLzvCFYRLS3sJcpeaY2FECjhYOKGqW2ZDW&key={YOUR-API-KEY}

Will get you information for a specific playlist. You can grab the title and description from the items that are returned.
"title": "top 50 english songs 2014",
"description": "pop slow romance the best (Y) top 50 songs arrange randomly :) hope u enjoy my first playlist",


text:
Q: How can I get 2 properties from my fetch in my dictionary I right now I have:
 fetchRequest.resultType = NSDictionaryResultType;
    fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"realLocationName"]];

which gives me something like this:
self.dict=
    (
            {
            realLocationName = "some where";
        },
            {
            realLocationName = somewhereelse;
        }
    )

I want to get a second attribute value from cd in this dictionary but im not sure how?
I tried doing something like this but it just overwrites the realLocationName with locationID
 fetchRequest.resultType = NSDictionaryResultType;
 fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"realLocationName"]];
 fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"locationId"]];

A: On the 3rd line:
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"locationId"]];

you've overwritten what you'd set on the 2nd line:
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"realLocationName"]];

You have to set one array as propertiesToFetch:
NSDictionary *properties = [entity propertiesByName];
fetchRequest.propertiesToFetch = @[properties[@"realLocationName"], properties[@"locationId"]];

I've used literals for creating and accessing NSArray and NSDictionary.


text:
Q: Length of a polar Curve $r = f\theta$ Determine an expression for the length of the curve $r = f(\theta)$ between $\theta = a$ and $\theta = b$.
I think I will need to convert to rectangular coordinates in some way. After that, I will probably need to find an integral to express the length. How do I go about doing this?

A: There is a similarity between the expressions in Cartesian and polar coordinates.
In both expressions, you are finding the length of the arc by combining motion in two perpendicular coordinates.
In rectangular, you have the x-speed, which is $1$, and the y-speed, which is $\displaystyle \frac{dy}{dx}$ (per x unit), hence $\displaystyle \int \sqrt{1+\left(\frac{dy}{dx}\right)^2}\,dx$
In polar, however, the curve moves in the tangential direction with speed $f(\theta)$ (per radian) and in the outward direction with speed $f'(\theta)$ per radian, hence $\displaystyle \int \sqrt{f(\theta)^2+f'(\theta)^2}d\theta$.
Parametric is the most obvious, in terms of $t$, it is simply $\displaystyle \int \sqrt{\left(\frac{dx}{dt}\right)^2+\left(\frac{dy}{dt}\right)^2}\,dx$ using both the $x$ velocities and $y$ velocities at each point.


text:
Q: extract 9 digit number from a string I basically have an array in php which contains a string, I basically need to filter the string in order to get a 9 digit ID number (which is surrounded by brackets), im sure there could be a way to do this with regex but im clueless.
I know that regex returns its results as an array as there could be multiple results but I know that there will not be multiple results for each string and therefore I need to put the result straight in to my already existing array if possible
example:
function getTasks(){
   //filter string before inserting into array
   $str['task'] = "meeting mike (298124190)";

   return $str;
}

A: by using preg_replace you just have one line filter....
 $str['task'] = preg_replace('/.*\((\d{9})\).*/', '$1', "meeting mike (298124190)");

using preg_match
$strings = array("meeting mike (298124190)", "meeting mike (298124190)", "meeting mike (298124190)");
foreach ($strings as $string) {
    if (preg_match("|\(([\d]{9})\)|", $string, $matches)) {
        $str[] = $matches[1];
        // OR $str['task'][] = $matches[1];
    }
}
print_r($str);

A: <?php
    $str = "meeting mike (298124190)";
    preg_match("/([0-9]{9})/s", $str, $result);

    print_r($result); // $result is an array with the extracted numbers
?>

A: Well, assuming it is the only one (9 digit number surrounded by brackets) the following will do:
preg_match("|\(([0-9]{9})\)|", $str['task'], $matches);
return $matches[1]; //Will contain your ID.

A: its somthing like :
$str = "meeting mike (298124190)";
$pattern = '/[0-9]{9}/';
if (preg_match($pattern, $str, $matches))
{

    echo $matches[0];
}


text:
Q: Protecting data from direct access by other applications in windows Is there a way to protect some cryptographic data from applications other than my own in Windows? I'm not concerned about protecting it from the user - this is obviously impossible - but, rather, from non-elevated applications other than my own.
I'm aware that I could simply run the application's core code as a service, with the data accessible only to system accounts, but I would prefer if I could keep the application running under a token not much more permissive than the user's normal token.
Additionally, I would prefer not to have a dependency on .NET if possible.

A: CryptProtectData
can do per-user encryption (it is per-user if you do not pass CRYPTPROTECT_LOCAL_MACHINE flag). However if you opt for per-user encryption, other users including elevated admins won't decrypt it.


text:
Q: Fortran calculates 0 for a fraction PROGRAM TRYY

implicit none

REAL:: x_value=2
REAL:: y_value=3
REAL:: answer

IF ((x_value >= 0 .AND. x_value < 10) .AND. (y_value >= 0 .AND. y_value < 10)) THEN
  answer = (1/3)*(x_value) + (1/2)*(y_value)
  WRITE(*,*) answer
ELSE
  WRITE(*,*)
END IF

STOP
END PROGRAM TRYY

This should read 2.16667, but instead it reads 0 because there are fractions in there. The fractions are (1/3) and (1/2). When I change them to 0.3 and 0.5 respectively, it gives me 2.1
I don't want that. I want (1/3) and (1/2) to work. What is happening?