text:
Q: Use a pickled custom-class in another file without importing the class first Say I have file creator.py with the following code
class Mapper:
    def train(self, X,y):
         return self
    def predict(self, X):
        pass

I want to distribute this object, e.g in a google-cloud storage, such that my co-workes have access to that class aswell.
I thought it would be as easy as just using pickle to save a Mapper instance e.g
import pickle

mapper = Mapper()
mapper.train(X,y)

with open("my_mapper.pkl","wb") as f:
    pickle.dump(f,mapper)

and then in another script, in another repo, main.py I can un-pickle it
import pickle
download_model_from_storage("my_mapper.pkl") # Download the object from storage
with open("my_mapper.pkl","rb") as f:
    my_mapper = pickle.load(f)

but that throws the error
AttributeError: Can't get attribute 'Mapper' on <module '__main__' from 'c:\\code\\main.py'>.
The only way I can fix this is to first import Mapper in main.py, but that introduces a file that I'll need to track in case I want to do some changes in creator.py then I should make sure those changes are also in main.py (which is rather prone to errors).
Isn't there a way to just distribute custom classes without having access to the "mother-class"? And why not (if that's the case)


text:
Q: How to analyse several types of geo data together? I have some data gathered from a survey conducted within my city. All responses include an approximate geo location of where they were gathered (accurate to probably a couple of hundred yards which is relatively small), and things like the respondents age, sex, income range, number of dependents, etc. There are approx. 4000 responses.
What I would like to is to be able to generate what I guess you would call a model, so that given a geo point (or box) I could characterize the typical respondent from there (it doesn't really have to be really rigorous, although some kind of formal confidence measurement would be nice).
So, is the right thing to do to simply treat all the gathered attributes separately and say "Well the age of your typical respondent in that area is m with stdev s, and their income range is ..., etc."
Or is there some better way to analyse the data together to get a better profile of the respondents.
Some key phrases to google would even help at this stage, because I'm a bit lost. I thought this might be "data fusion" but I don't think it is.

A: The short answer is the "usual" way in the social sciences is to have pre-defined discrete areas and provide summary statistics for samples within those areas aggregated up. Examples of pre-defined areas may be census geographies, zip-codes, or any other neighborhood unit you can dream up.
This is the usual because it is fairly rare to have surveys geocoded to the exact location or be able to utilize that information due to privacy reasons, so typically surveys can't be geolocated besides within a general area anyway. Even if you don't have pre-defined areas you could always create a uniform grid (i.e. quadrats) and provide summary statistics. If your sampling over the city diverges from uniform though this approach will not work as well, as you could have some quadrats with few (or zero) samples and some with many samples (in fact some people justify aggregation to larger units because of such concerns).
More novel is to utilize what van Ham & Manley (2012) refer to as bespoke neighborhoods. One essentially picks a point, and then some arbitrary buffer around that point, and then estimates whatever summary statistic one is interested in based on samples around that point. Related examples can be found in Lee et al. (2008), Li & Radke (2012) and Ratcliffe & Taniguchi (2008).
If you want more continuous measurements over the entire study space, you can utilize geo-statistical kriging to estimate a continuous surface (although this is also pretty novel for social science). Similar examples can be found in the social science literature under area-to-point kriging (which is a slightly different context). See this other answer of mine for a list of scholarly examples.

Citations

*

*Lee, B. A., Reardon, S. F., Firebaugh, G., Farrell, C. R., Matthews, S. A., and O'Sullivan, D. (2008). Beyond the census tract: Patterns and determinants of racial segregation at multiple geographic scales. American Sociological Review, 73(5):766-791. PDF Here.

*Li, W. and Radke, J. D. (2012). Geospatial data integration and modeling for the investigation of urban neighborhood crime. Annals of GIS, 18(3):185-205.

*Ratcliffe, J. H. and Taniguchi, T. A. (2008). Is crime high around drug-gang street corners?: Two spatial approaches to the relationship between gang set spaces and local crime levels. Crime Patterns and Analysis, 1(1):23-46. PDF at link

*van Ham, M. and Manley, D. (2012). Neighbourhood effects research at a crossroads: Ten challenges for future research. Environment and Planning A, 44(12):2787-2793.

A: What about an estimator which is an average over its closest  k neighbors with the weights given to the neighbors decreasing with distance from the target point.
The right taper for the weights could be fit beforehand using some sort of error minimization training scheme?
Alternatively, I was thinking of a Voronoi tessalation. For a point of interest find its Voronoi cell and add in the effect of next-neighbor cells with a reduced weight and so on?
Too simplistic?
PS. Would there be a chance that the Income (say) at a location is better predicted by $fn(income, age, sex)$ of its neighbors than by merely $fn(income)$ of its neighbors?
In essence, can mixing predictors get a better predictive model than keeping them separate?
In the extreme could one ever have a situation where neighbor age alone was a better predictor of a points income than neighbor income? Just wondering.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Possible to get typeof generic type parameter? I am writing a simple de/serializer that works for any type of State. Is there any way to get the concrete types of a generic type parameter? Code sample is shown below.
type ValType = number | boolean;

interface State {
    [index: string]: ValType;
}

function serialize(x: ValType): string {
    if (typeof x === 'number') {
      return `n${x}`;
    } else {
        return `b${x}`;
    }
}

// return dummy values instead of reading from string
function deserialize(x: string, type: string): ValType {
    if (type === 'number') {
      return 0;
    } else {
        return false;
    }
}

function serializeState<T extends State>(s: T): string {
    let ret = '';

    Object.values(s).forEach(v => {
        ret += serialize(v);
    })

    return ret;
}

function deserializeState<T extends State>(s: string): T {
    // ???? how to get keys and value types from T ???? <--------------------------

    // e.g., ['number', 'boolean']
    const types = [];
    // e.g., ['counter', 'isDone']
    const keys = [];

    // deserialize based on actual types
    T ret;
    for (let i = 0; i < types.length; i++) {
        ret[keys[i]] = deserialize(s, types[i]);
    }

    return ret;
}

interface StateA extends State {
    counter: number;
    isDone: boolean;
}

const s: StateA = { counter: 1, isDone: false };
const str = serializeState(s);

console.log(deserializeState<StateA>(str));
// expected: { counter: 1, isDone: false };


text:
Q: Fast switching of a 24V valve I'm trying to make a circuit using tc4427 and some other components to make a fast switch for a 24V valve using a signal from a microprocessor. I've modeled the signal from the processor as a pulse of 5V shown in V2 and the valve is modelled as a resistor R3 and a coil C1. Do you think this circuit will work fine?

A: You must have a free wheel diode from the MOSFET output to ground, to catch back EMF. Using a TVS for that isn't a bad idea, since that will also catch various EMI spikes.

A: The driver is connected to a 5 volt power supply so there's no benefit in terms of using the driver (TC4427) to increase the drive voltage to the MOSFETs gate. And the MOSFET will quite happily operate with a 5 volt gate drive: -

So, the only benefit from using the driver is to improve the current drive into the gate capacitance (circa 10 nF). But, given that you are only switching a 24 volt valve and, I suspect that the valve speed will be in the order of milli seconds (if not tens of milli seconds) then, using your 5 volt drive from the microprocessor (via say a 330 ohm resistor) isn't going to improve the timing much.
330 ohm and 10 nF have a CR time of 3.3 μs and if it takes a couple of CR times to properly drive the MOSFET that's only 6 or 7 μs wasted. Is this too much given the bigger picture of the mechanical valve sluggishness.
You will need a back-emf catch-diode across the solenoid to prevent the MOSFET from becoming damaged when you deactivate it such as this one across the motor below: -

A: You look to be well within the avalanche rating of the transistor, so I think it will be okay. Check the simulation in LTspice for the energy and power dissipation at the desired switching frequency.
The valve probably will behave somewhat differently than a simple inductor so you should confirm with a real circuit and an oscilloscope.
The valve release time will be related to how high you allow the drain voltage to go with respect to the power supply.


text:
Q: How do I extract a single element from a JSON http response and pass it to C# as an integer? I'm writing a WCF service and trying to extract the value for SMS from the following JSON string which forms an http response. The rest of the response is superfluous for my requirements.
{"balance":{"sms":100,"mms":2},"status":"success"}

The code i've got at the moment only ever returns '0' as the integer for balance.
    public class balanceObject
    {
        public int sms { get; set;}
        public int mms {get; set;}
        public string status {get; set;}
    }

    public int balanceRequest()
    {
        using (var wb = new WebClient())
            {
                byte[] response = wb.UploadValues("http://api.txtlocal.com/balance/?apiKey=", new NameValueCollection()
            {
            {"apiKey" , api},
            });

            string result = System.Text.Encoding.UTF8.GetString(response);
            JavaScriptSerializer js = new JavaScriptSerializer();
            balanceObject request = (balanceObject)js.Deserialize(result, typeof(balanceObject));
            int balance = request.sms;
            return balance;

            }
        }

Any advice would be gratefully received.

A: Your balanceObject doesn't match your JSON. Your object should look more like this:
public class phoneObject
{
    public string status {get; set;}
    public balanceObject balance {get; set;}
}

public class balanceObject
{
    public int sms { get; set;}
    public int mms {get; set;}
}

You would then retrieve your value like so:
phoneObject request = (phoneObject)js.Deserialize(result, typeof(phoneObject));
int balance = request.balance.sms;
return balance;


text:
Q: python: algorithm - to gather items from mean Not sure whether this is the right place, but I have a question related to algorithm and I cant think of an efficient algorithm.
So thought of sharing my problem statement.. :)
To ease up what I am trying to explain, let me create a hypothetical example.
Suppose, I have a list which contains an object whcih contains two things..
lets say product id and price

Now, this is a long long list..sort of like an inventory..
out of this I have defined three price segments.. lowprice, midprice and highprice
and then k1,k2,k3 where k1,k2 and k3 are ratios.
So, the job is now,, I have to gather products from this huge inventory in such a way that there is n1 products from lowprice range, n2 products from midprice range and n3 products from high price range... where n1:n2:n3 == k1:k2:k3
Now, how do I efficiently achieve the following.
I target the low price point is 100 dollars
and I have to gather 20 products from this range..
mid price range is probably 500 dollars
and so on
So I start with 100 dollars.. and then look for items between 90 and 100 and also between 100 and 110
Let say I found 5 products in interval 1 low (90,100) and 2 products in interval 1 high (100,110)
Then, I go to next low interval and next high interval.
I keep on doing this until I get the number of products in this interval.
How do I do this?? Also there might be case, when the number of products in a particular price range is less than what I need.. (maybe mid price range is 105 dollars...).. so what should I do in that case..
Please pardon me, if this is not the right platform.. as from the question you can make out that this is more like a debative question rather than the "I am getting this error" type of question.
Thanks

A: You are probably looking for selection algorithm.
First find the n1'th smallest element, let it be e1, and the lower bound list is all elements such that element <= e1.
Do the same for the other ranges.
pseudo code for lower bound list:
getLowerRange(list,n):
  e <- select(list,n)
  result <- []
  for each element in list:
     if element <= e:
         result.append(element)
  return result

Note that this solution fails if there are many "identical" items [result will be a bigger list], but finding those items, and removing it from result list is not hard.
Note that selection algorithm is O(n), so this algorithm will consume linear time related to your list's size.

A: Approach 1
If the assignment what products belong to the three price segments never changes, why don't you simply build 3 lists, one for the products in each price segment (assuming these sets are disjoint).
Then you may pick from these lists randomly (either with or without replacement - as you like). The number of items for each class is given by the ratios.
Approach 2
If the product-price-segment assignment is intended to be pre-specified, e.g., by passing corresponding price values for each segment on function call, you may want to have the products sorted by price and use a binary search to select the m-nearest-neighbors (for example). The parameter m could be specified according to the ratios. If you specify a maximum distance you may reject products that are outside the desired price range.
Approach 3
If the product-price-segment assignment needs to be determined autonomously, you could apply your clustering algorithm of choice, e.g., k-means, to assign your products to, say, k = 3 price segments. For the actual product selection you may proceed similarly as described above.

A: It's seems like you should try a database solution rather then using a list. Check out sqlite. It's in Python by default


text:
Q: Using 'get_template_directory_uri' correctly I have a woo-commerce child theme set up. In the functions.php file I am loading an additional tab. The function which loads the tab looks like this:
   function woo_finance_tab_content() {

    echo '
Additional Tab
';

}

I'm attempting to load several php files, within this function. What is the correct way to do this though? If I have 'test.php' which I want to load inside the function, is it simply a case of using:
echo "get_template_directory_uri(/woocommerce/single-product/test.php)";

A: get_template_directory_uri(), as the name suggests, gets the URI of the theme. You want the filesystem path, which is get_template_directory():
<?php require get_template_directory() . '/woocommerce/single-product/test.php' ?>

Better yet, use the WordPress template loading system:
<?php locate_template( 'woocommerce/single-product/test.php', true /* Locate AND load the file */ ) ?>


text:
Q: How to make a program that will display a Web Page in C? I am interested in creating a Web Browser using C and the socket library (or any other library) under a Linux System.
The basic use of my Web Browser, would be to render the HTML of a webpage, into something readable to the user.
I just want someone to point me to the right direction. I also have a pretty good understanding of sockets and their system calls in C...

A: A pointer in the right direction, eh?
Well, a web browser consists of a whole mess of systems working together; even the most basic web browser must, at an absolute minimum understand HTTP/1.1 and HTML.
It must be able to fetch pages from remote servers, parse the HTML into a DOM, render that to a viewport, capture mouse clicks, let them activate hyperlinks, and navigate to new pages.
But if it can only do that, it's a poor excuse for a web browser; even the simplest of web browsers should also be able to parse and apply CSS; display JPEG, PNG and BMP images, parse XML, execute JavaScript, deal with cookies, offline storage, plugins (such as flash), and about a million other things.
The point I'm trying to make, of course, is that a web browser is in a lot of ways a poor project for learning to do software projects, because the overhead related to even basic functionality is crippling.


text:
Q: Is it possible to check whether a context variable is already set in a view within a custom context processor definition? The issue is that in some views, I am manually getting a context variable (let's say "G") of interest since I use it to find other information in that particular view (i.e.views A,B,C), but in other views (i.e. X,Y,Z), I need to get that particular context variable since this context is to be available in every single view in my project (since my base template uses the context variable). The issue with using a custom context processor is that I believe it will make an additional and IDENTICAL DB call in views (A,B,C) since those views are already getting that context variable since it's needed to get other data in the view. What I was thinking was maybe I could implement a context processor that checks whether that specific context variable is set for a given request. Is this possible? Is there an easier solution? The code below may clarify the issue for some people.
Thank you for any advice!
def viewA(request):
    g=G.objects.get(user=request.user)
    posts = Post.objects.filter(g=g)
    return direct_to_template(request,'something.html',{'G':g, 'posts':posts})

def viewX(request):
    stuff = Albums.objects.get(user=request.user)
    return direct_to_template(request,'something2.html',{'stuff':stuff})

def my_context_processor(request): #redundant in case of viewA (hits db again?)
    return {'G':G.objects.get(user=request.user)}

def ideal_processor(request):
    #check context vars to see if G is already in there
    #if it is, return {}, else, return {'G':G.objects.get(user=request.user)}

A: def always_G(request):
    if not hasattr(request, 'G'):
        {'G':G.objects.get(user=request.user)}

A: I just made middleware that sets the variabel G to request.G since I need it on virtually every request anyway. i.e.:
class GuildMiddleware(object):
    def process_request(self, request):
        request.G = figure_out_what_G_is()
        return None

Now you can use request.G anywhere in your views (and templates if you're using direct_to_template, RequestContext, etc.).


text:
Q: PHP if Month Equals then Echo CSS Style I would normally do this sort of thing in jQuery, but this will require a server side touch.  I am new to PHP and need assistance writing a basic script that will take in a numerical month the_time('m') and I simply wish to say if it equals 01 then echo "#000" and then loop through the other months 02, 03 ,04, so on and have them echo different hex codes if the month is equal.
Forgive my crude and incorrect code, but I thought this would help visualize the solution I am working towards.
style="background: #
<?php
if(the_time('m') == "01") {
    echo "000";
} else if (the_time('m') == "02"){
    echo "111";
} // so on through 12
?>
"

Any help would be greatly appreciated.  Thank you.
EDIT
The while loop code I am currently inside:
<?php while ( have_posts() ) : the_post(); ?>
<?php
$code = "f5f5f5"; // Set default
$month = the_time('m');

switch ($month) {
        case "01" :
    $code = "f5f5f5";
            break;

    case "02" :
    $code = "f3f3f3";
    break;

    case "03" :
    $code = "f1f1f1";
    break;

    case "04" :
    $code = "efefef";
    break;

    }
?>

<li id="event_<?php the_time('m_d_Y') ?>" style="background: #<?php echo $code ?>;">

A: I wouldn't really go down that path, but I'd do something like:
<div class="month-<?php echo strtolower(date('M')) ?>">Howdy

// your CSS file:
.month-jan { background: #000; }
.month-feb { background: #FFF; }
// etc

A: Try
<?php
$code = "000"; // Set default
$month = date ( "m" );

switch ($month) {
    case "02" :
        $code = "111";
        break;

    case "03" :
        $code = "CCC";
        break;

    case "04" :
        $code = "FFF";
        break;

}
?>
style="background: #<?php echo $code ?>"

A: switch (date('n')) {
    case 1:
        echo "000";
        break;
    case 2:
        echo "111";
        break;
    ...
}

Or, simpler:
$colors = array(
    1 => "000",
    2 => "111",
    ...
);
echo $colors[date('n')];

A: Take the month with php's date function, subtract one, convert to hex, and repeat it 3 times.
echo printf('%1$'.base_convert(date('n') - 1, 10, 16).'3d', date('n') - 1);

It's a little tricky and obtuse, but you avoid needing a switch or a huge chunk of elseifs


text:
Q: How to find if a set of type pair contains an element as the second member? If I have a set of following type :
std::set<std::pair<double,unsigned> > X;
and I want to find the location of the first occurrence of unsigned y which would be the second member in the std::set X.
How can I do it efficiently?
TIA

A: You can use std::find_if with a predicate.
int main() {
  std::set<std::pair<double,unsigned>> X { {1.1, 1}, {2.2, 2}, {3.3, 3} };
  unsigned valToSearch = 2;

  // the searah method with predicate:
  auto it = std::find_if(X.begin(), X.end(),
     [valToSearch](const std::pair<double,unsigned>& elem) {return elem.second == valToSearch;});

  if(it != X.end())
    std::cout << it->first << ", " << it->second;

  return 0;
}

Output

2.2, 2


text:
Q: passing username/password to openVPN CLI directly I want to make a script that asks the user for username and password and uses these for a few things at once, including connecting to OpenVPN without needing to either

*

*store the password on the disk

*ask the user for the data many times over

for example you can run net use with user and password to mount shares, however openVPN seemingly only has an option to pass a file with username and password.
On Linux there seemingly are solutions like this, however I don't seem to find anything similar for windows yet.
Is there a solution?


text:
Q: Applying xpath on xml with default namespace with XOM I have below XML which contains a default namespace
<?xml version="1.0"?>
<catalog xmlns="http://www.edankert.com/examples/">
  <cd>
    <artist>Stoat</artist>
    <title>Future come and get me</title>
  </cd>
  <cd>
    <artist>Sufjan Stevens</artist>
    <title>Illinois</title>
  </cd>
  <cd>
    <artist>The White Stripes</artist>
    <title>Get behind me satan</title>
  </cd>
</catalog>

And Im running following code expecting some result in return
Element rootElem = new Builder().build(xml).getRootElement();
xc = XPathContext.makeNamespaceContext(rootElem);
xc.addNamespace("", "http://www.edankert.com/examples/");
Nodes matchedNodes = rootElem.query("cd/artist", xc);
System.out.println(matchedNodes.size());

But the size is always 0.
I gone through

*

*https://stackoverflow.com/a/9674145/1160106 [I really didnt get the weired xpath syntax]

*http://www.edankert.com/defaultnamespaces.html#Jaxen_and_XOM [Can see some hope. Just requires a major change in my current implementation]

Looking forward for any help.

A: Unprefixed names in XPath always mean "no namespace" - they don't respect the default namespace declaration.  You need to use a prefix
Element rootElem = new Builder().build(xml).getRootElement();
xc = XPathContext.makeNamespaceContext(rootElem);
xc.addNamespace("ex", "http://www.edankert.com/examples/");
Nodes matchedNodes = rootElem.query("ex:cd/ex:artist", xc);
System.out.println(matchedNodes.size());

It doesn't matter that the XPath expression uses a prefix where the original document didn't, as long as the namespace URI that is bound to the prefix in the XPath namespace context is the same as the URI that is bound by xmlns in the document.


text:
Q: MySql check if a value is different from a value in a database i'm trying to check if a value inserted into a taxtbox is different from a value listed on a database.
for now i have this code:
<?php
include('connection.php');
if($_POST)
{
$q=$_POST['search'];
$sql_res=mysql_query("select name, surname, test, from table where name like '%$q%' or surname like '%$q%' order by field (test,1,0)");
while($row=mysql_fetch_array($sql_res))
{
$name=$row['name'];
$surname=$row['surname'];
$test=$row['test'];

$b_name=''.$q.'';
$b_surname=''.$q.'';
$final_name = str_ireplace($q, $b_name, $surname);
$final_surname = str_ireplace($q, $b_name, $surname);

$display = '
 HTML code here
';

?>

<?php echo $display?>

<?php

}
}
    if($final_name != $name){$display = "no";}

?>

and using this code, if the value exist everything works fine, otherwise i have this error:

Notice: Undefined variable: name in C:\xampp\htdocs\A\search.php on line 44
Notice: Undefined variable: final_name in C:\xampp\htdocs\A\search.php on line 44

any help?
EDIT:
Ok, i think that maybe the problem is the live search..
i mean, with your help i can show a message if the $q != $name but the problem is that this message is always visible at the bottom of the results, and as long as there's no more match, the results disappears and the message is above everything.
I think that maybe just because the search is live, the textbox value is never equal to the database one.
Is it correct?

A: try
$check = mysql_num_rows($sql_res);
if($check > 0) {
  // your while loop and other code
}

Note :- mysql_* has been deprecated use mysqli_* or PDO
or try to check empty() or isset() for check values exist
$name=(!empty($row['name']) ? $row['name'] : '');
// and also for other vars same process


text:
Q: Do not minify certain files in ASP .NET MVC 4 BundleConfig I don't want to minify all the files I use in my ASP .NET MVC 4 solution. So for example I have this in my BundleConfig.cs:
bundles.Add(new StyleBundle("~/CSS/bootstrap").Include(
    "~/Content/Bootstrap/body.css",
    "~/Content/Bootstrap/bootstrap-responsive.css",
    "~/Content/Bootstrap/bootstrap-mvc-validation.css",
    "~/Content/Bootstrap/bootstrap-theme.css",
    "~/Content/Bootstrap/bootstrap.css"
    ));

...

And to minify it, of course I use:
BundleTable.EnableOptimizations = true;

So it works great.
But now, how could I minify all my files except one bundle? I have a problem with a bundle that removes some CSS classes and would like to not minify this one.
Any help would be greatly appreciated.

A: I had a similar issue. the solution is to disable and enable minification in the view. for instance
@{
    BundleTable.EnableOptimizations = false;
 }

@Styles.Render("~/layout")
@RenderSection("CSS", false)

@{
    BundleTable.EnableOptimizations = true;
}

A: I don't know where the problem comes from but I tried to:

*

*Just bundle, not minify. It doesn't work.
bundles.Add(new Bundle("~/CSS/bootstrap").Include(
    "~/Content/Bootstrap/body.css",
    "~/Content/Bootstrap/bootstrap-responsive.css",
    "~/Content/Bootstrap/bootstrap-mvc-validation.css",
    "~/Content/Bootstrap/bootstrap-theme.css",
    "~/Content/Bootstrap/bootstrap.css"
    ));

*Override UI errors. It works but it's just a temporary patch.
Finally, I decided to use standard CSS calls (and put some comments to explain why in the code):
<link rel="stylesheet" href="/Content/Bootstrap/body.css">
<link rel="stylesheet" href="/Content/Bootstrap/bootstrap-responsive.css">
<link rel="stylesheet" href="/Content/Bootstrap/bootstrap-mvc-validation.css">
<link rel="stylesheet" href="/Content/Bootstrap/bootstrap-theme.css">
<link rel="stylesheet" href="/Content/Bootstrap/bootstrap.css">

If you have a better idea, please let us know! :)

A: Use Transforms.Clear() to skip minification but keep the files bundled
//declare bundle
var bundle = new ScriptBundle("~/javascripts/ckEditor")
                .Include("~/Scripts/ckeditor/ckeditor.js")
                .Include("~/Scripts/ckeditor/config.js");

//skip transformation. Result is that files are only bundled, but not minified.
bundle.Transforms.Clear();

bundles.Add(bundle);

You also have to eliminate the .min.js files from the directory to prevent the substitution


text:
Q: Convert byte[] with negative value to String I have this byte[] = {-53, 54, -5, -89, -69, -126, -57, 36, 49, 114, -66, 67, 39, 18, 57, -40, 50, -113, 52, -113, 111, -65, -20, -127, -84, 90, -74, -47, 94, 23, 18, -36}
How can I convert it to String? I've tried many ways to do, but all of them do not work
I'm using this library to encode my string https://github.com/scottyab/AESCrypt-Android, there are some line of code to genarate the byte[] above
private static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    final MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
    byte[] bytes = password.getBytes("UTF-8");
    digest.update(bytes, 0, bytes.length);
    byte[] key = digest.digest(); //I want to convert this byte[] to String

    log("SHA-256 key ", key);

    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    return secretKeySpec;
}

A: You should encode your byte array using Base64.
If you use Java8, Base64 is already included in java.util package.
Try the following code:
 public static void main(String args[]) throws IOException {

        byte[] b = {-53, 54, -5, -89, -69, -126, -57, 36, 49, 114, -66, 67, 39, 18, 57, -40, 50, -113, 52, -113, 111, -65, -20, -127, -84, 90, -74, -47, 94, 23, 18, -36};
         String encoded = Base64.getEncoder().encodeToString(b);
         System.out.println(encoded);

    }

Result:
  yzb7p7uCxyQxcr5DJxI52DKPNI9vv+yBrFq20V4XEtw=


text:
Q: Bitnami MEAN stack on Mac: Unknown command express I installed MEAN stack using Bitnami installer https://docs.bitnami.com/installer/infrastructure/mean/
It is installed with all ok status. But while creating a sample project as specified in https://docs.bitnami.com/installer/infrastructure/mean/get-started/get-started/, I am getting error with express sample.
I am trying in my local machine [MacBook].
Is there any specific thing I am missing while setting up stack?

A: Bitnami developer here,
Try this:

*

*Load the environment (by default, installdir is /Applications/meanstack-VERSION):

cd installdir
./use_meanstack

*

*Create a new MEAN project:

mkdir projects
cd projects
express sample
cd sample
npm install

I hope it helps


text:
Q: Upgrade virtual-node-aci-linux in Azure Kubernetes Cluster Does anyone have any links or know how to upgrade the virtual-node-aci-linux on Azure?
I am currently on version v1.19.10-vk-azure-aci-v1.4.1 however my other node pools are now on v.1.22.11 after upgrading Kubernetes.
I am getting some odd behaviour since the upgrade, It seems I now have to specify a single instance in my VMMS for the virtual-node-aci-linux node to be ready. I don't remember having to do this before.
    NAME                              STATUS   ROLES   AGE    VERSION
    aks-control-13294507-vmss000006   Ready    agent   86s    v1.22.11
    virtual-node-aci-linux            Ready    agent   164d   v1.19.10-vk-azure-aci-v1.4.1

Also previously I am sure that only my virtual-node-aci-linux was visible in the node list.
Any help would be appreciated.


text:
Q: Show sidebar when acessing a doc that is not listed in sidebars.json (docusaurus) I noticed that when I access a doc that is not inside sidebars.json, the left sidebar doesn't shows up, but if I add this doc do the JSON is shows, I want the left sidebar to be visible, even id the doc that I'm accessing is
not listed in this JSON file
left container


text:
Q: Configure object mapper to replace values with lower case I have a class Diff that looks like so:
public class Diff {

    private String path;
    private String value;
    private Operation operation;

    public enum Operation {
        ADD, REPLACE, REMOVE
    }

    // getters and setters
}

I want to create a json node using the following call:
ObjectMapper mapper = new ObjectMapper();
mapper.valueToTree(diffObject);

If I have a Diff like so:
Diff diff = new Diff();
diff.setPath("/path");
diff.setValue("value");
diff.setOperation(Operation.REPLACE);

Doing:
mapper.valueToTree(diff);

will return:
"{"path":"/path", "value":"value","operation":"REPLACE"}"

I need the word "operation" to just be "op", though.  Supposedly, there's a way to configure ObjectMapper in a way as to where when it reads "operation", it will translate it to just "op", but I have no idea how to do it.  Anybody know?

A: You can use @JsonProperty annotation
public static class Diff {

    private String path;
    private String value;

    @JsonProperty("op")
    private Operation operation;
}

[UPDATE]
Because you dont have access to the class, can you use ByteBuddy to modify the class a bit ? :)
For example:
@Test
public void byteBuddyManipulation() throws JsonProcessingException, IllegalAccessException, InstantiationException {
    ObjectMapper objectMapper = new ObjectMapper();

    AnnotationDescription annotationDescription = AnnotationDescription.Builder.forType(JsonProperty.class)
            .define("value", "op")
            .make();

    Class<? extends Diff> clazz = new ByteBuddy()
            .subclass(Diff.class)
            .defineField("operation", Diff.Operation.class)
            .annotateField(annotationDescription)
            .make()
            .load(Diff.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
            .getLoaded();

    Diff diffUpdated = clazz.newInstance();
    diffUpdated.setOperation(Diff.Operation.ADD);

    objectMapper.valueToTree(diffUpdated);   //returns "op":"ADD"
}

[UPDATE 2]
Or simply create subclass of Diff and shadow the operation field
public static class YourDiff extends Diff {
    @JsonProperty("op")
    private Operation operation;

    @Override public Operation getOperation() {
        return operation;
    }

    @Override public void setOperation(Operation operation) {
        this.operation = operation;
    }
}


text:
Q: Get object keys for properties having non-empty array as a value I have an array:
417: Array(2)
0: 24301
1: 24300
length: 2
__proto__: Array(0)
418: [24562]
length: 419
__proto__: Array(0)

Now, i need to get all those keys from this array arr whose length is greater than 0. In this case, i need the answer as ['417','418'].
I have tried to filter using each loop and .length of each element as:
My code is as:
        console.log(arr_of_sel_units);
        $.each(arr_of_sel_units, function(k, v) {
            console.log(v.length)
        });

But, it is returning error Cannot read property 'length' of undefined

A: If proper datatype (Object) used for arr, you may do Array.prototype.filter() across Object.keys() (however, it will work for your notation just as well as array is essentially an object):

const src = {a: ['1','2','3' ], b: [], c: ['1' ], d: []},

      result = Object.keys(src).filter(key => src[key].length)

console.log(result)

A: Use Object.entries, filter

let arr = [];
arr["a"] = ["1", "2", "3"];
arr["b"] = [];
arr["c"] = ["1"];
arr["d"] = [];

const res = Object.entries(arr)
  .filter(([, value]) => value.length > 0)
  .map(([key]) => key);

console.log(res);


text:
Q: What is this math font?
I designated "D" on the image.
What is this math font called?
.
Thanks in advance.

A: You can either define your own math alphabet (here \mathbfsf) for bold sans-serif
\documentclass{article}
\DeclareMathAlphabet{\mathbfsf}{OT1}{cmss}{bx}{n}
\begin{document}

$\mathsf{D}$ $\mathbfsf{D}$

\end{document}

or you can use the bm package
\documentclass{article}
\usepackage{bm}
\begin{document}

$\mathsf{D}$ $\bm{\mathsf{D}}$

\end{document}

The output is in both cases


text:
Q: How to query PointField - MongoEngine I was trying to update PointField in my flask app with upsert_one. But it always inserts new document. I know the problem is with the query which I'm passing.
Below is my model.
class Location(db.Document):
    location_name = db.StringField(required=True)
    geoCoords = db.PointField()

And the update query.
Location.objects(geoCoords=loc["geoCoords"]).upsert_one(location_name=loc["location_name"], geoCoords=loc["geoCoords"])
#loc["geoCoords"] = [77.6309395,12.9539974]

I also tried running get. But I'm getting the error message "Location matching query does not exist." for the below query.
loc = Location.objects(geoCoords=[77.6309395,12.9539974]).get()

I have following entries in my location collection.
> db.location.find()
{ "_id" : ObjectId("59c5019727bae70ad3259e67"), "geoCoords" : { "type" : "Point", "coordinates" : [ 77.6309395, 12.9539974 ] }, "location_name" : "Bengaluru" }
{ "_id" : ObjectId("59c5022d27bae70ad3259ea2"), "geoCoords" : { "type" : "Point", "coordinates" : [ 77.6309395, 12.9539974 ] }, "location_name" : "Bengaluru" }
>

I couldn't find any related information on querying the PointFiled.

A: To answer to my question. I think there is no way to get the exact points like I have mentioned in the question.
The nearest method works here is to use __near selector. This accepts the range in meters. So, you can give closest range query as per your requirement.
In my case, I gave 100 meters. Which is fine for me.
Example:
Location.objects(geoCoords__near=thelocation["geoCoords"], geoCoords__max_distance=100).upsert_one(location_name=thelocation["location_name"], geoCoords=thelocation["geoCoords"])

A: Try this:
Location.objects(geoCoords="...").update(location_name=loc["location_name"], geoCoords=loc["geoCoords"])


text:
Q: NSMenuItem enabled state, dynamic naming and target action I am having a problem with my app's menu. I want a few items in the menu to be greyed out depending on some BOOL variables.
Also, I want some of my menu items to get names depending on some BOOL variables and thereby execute different functions depending on what the menu item name is. Is this possible? As using Interface Builder you can link a menu item to one IBAction method. please tell me how to do this.
Thanks

A: See the NSMenuValidation protocol.
You implement -validateMenuItem:, which is used to determine whether a menu item should be enabled or disabled.  It's called for each menu item just before a menu is popped up.

A: Yes. You can set a menu item's enabled state and its title programmatically; see the NSMenuItem documentation. Remember to use NSLocalizedString when obtaining the title format.

A: For the second question; you don't need to use Interface Builder to hook up Target/action for Menu items.
You can use code such as this:
NSMenuItem *menuItem; // Set this to your menu item.
// Set the target to an instance of a class which contains the action method.
[menuItem setTarget:targetClass];
// Set the action to the (IBAction) method to call.
[menuItem setAction:NSSelectorFromString(@"actionMethod")];


text:
Q: BitmapImage throwing NotSupportedException on EndInit() I am trying to create an Image in WPF out of a base 64 string, however, whenever I try to create the BitmapImage for the images Source property, I get a NotSupportedException.
Code:
public ScreenCaptureWindow(string screenCaptureBase64) {
    InitializeComponent();
    byte[] imageBytes = Convert.FromBase64String(screenCaptureBase64);
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.BeginInit();
    bitmapImage.StreamSource = new MemoryStream(imageBytes);
    bitmapImage.EndInit(); //Crashes here
    image.Source = bitmapImage;
}

Link to stacktrace
Attached is a screenshot of the exception details.
Any ideas?


text:
Q: Problem showing/hiding UI elements in HTML I have written some HTML to display/hide some UI when buttons are clicked.  I want the UI to be hidden when the page loads and revealed when the "Show UI" button is clicked.
The following HTML almost works:

function showHide(thingToHide, thingToShow) {
  document.getElementById("status").innerHTML = "Shown";
  if (thingToHide == "showUI") {
    document.getElementById("status").innerHTML = "Hidden";
  }
  document.getElementById(thingToHide).style.visibility = "hidden";
  document.getElementById(thingToShow).style.visibility = "visible";
}

  <input id="showButton" type="button" onclick="showHide('hideUI', 'showUI');" value="Show UI" />

  <input id="hideButton" type="button" onclick="showHide('showUI', 'hideUI');" value="Hide UI" />

 Various UI goes here

Start

However, the "showUI" div is visible when the page first displays.  If I set the initial visibility to hidden in that div, it does not show up as expected when I click the "Show UI" button and attempt to make it visible.

A: You just need to call the function once in the script. See in below code, I have called showHide('show', 'hideUI'); just after declaring the function.

function showHide(thingToHide, thingToShow) {
  document.getElementById("status").innerHTML = "Shown";
  if (thingToHide == "showUI") {
    document.getElementById("status").innerHTML = "Hidden";
  }
  document.getElementById(thingToHide).style.visibility = "hidden";
  document.getElementById(thingToShow).style.visibility = "visible";
}
showHide('showUI', 'hideUI');

  <input id="showButton" type="button" onclick="showHide('hideUI', 'showUI');" value="Show UI" />

  <input id="hideButton" type="button" onclick="showHide('showUI', 'hideUI');" value="Hide UI" />

 Various UI goes here

Start

A: You need to execute showHide('hideUI', 'showUI'); when loading the page.
The following Javascript should work:
function showHide(thingToHide, thingToShow) {
  document.getElementById("status").innerHTML = "Shown";
  if (thingToHide == "showUI") {
    document.getElementById("status").innerHTML = "Hidden";
  }
  document.getElementById(thingToHide).style.visibility = "hidden";
  document.getElementById(thingToShow).style.visibility = "visible";
}
showHide('hideUI', 'showUI');

A: The problem with my original code is that the javascript function is BEFORE the divs.  If I set the visibility of div showUI to hidden in the HTML and I move the javascript after the HTML for the divs it works as desired.

A: This might be what your looking for. It keeps the button in the same place.
HTML
<input id="Button" type="button" onclick="showHide('UI');" value="Show UI" />

 Various UI goes here

Start

JS
function showHide(UI) {
  if (document.getElementById(UI).style.visibility === 'hidden') {
    document.getElementById("status").innerHTML = "Shown";
    document.getElementById(UI).style.visibility = "visible";
    document.getElementById('Button').value = 'Hide UI'
  } else {
    document.getElementById("status").innerHTML = "Hidden";
    document.getElementById(UI).style.visibility = "hidden";
    document.getElementById('Button').value = 'Show UI'
  }


text:
Q: Corebluetooth : Retrieving characteristic.value > 20 bytes I currently have a BLE peripheral device that streams 35 bytes of data every 100ms (arduino sketch).  On my iOS device, I've tested using Adafruit's iOS UART program and verified that the iOS device can indeed receive the full 35 bytes of data every 100ms. They use the MQTT libraries.
I am using the CoreBluetooth library and in CBPeripheral's didUpdateValueForCharacteristic: method, the characteristic.value is always 20 bytes or less.  It will usually be 20 bytes -> 100ms -> remaining 15 bytes -> 100ms...repeat.
I'd like to retrieve the entire 35 bytes in one transmission, but on the receiving end it breaks it up into 20 byte chunks whereas the adafruit iOS library using MQTT receives the entire transmission of 35 bytes in 1 shot every 100ms.
Upon further research, I noticed the use of CBPeripheralManager and the didReceiveReadRequest: method but I believe that only belong's on the peripheral BLE device, and not on the host iOS device which I am receiving the data from.
Does anyone have any idea how to retrieve the entire 35 byte transmission?


text:
Q: MatLab help! Error using plot3 Not enough input arguments fid =fopen(datafile.txt','r');
data = textscan(fid, '%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f');
plot3(data(:,5),data(:,6),data(:,7))
fclose(fid);

I am getting the error:

Error using plot3
  Not enough input arguments.

Where am I going wrong here? my data file is just columns of doubles (hence %f)

A: This is one of those cases where the error isn't very informative. The problem here isn't that there aren't enough input arguments, it's that they are of the wrong type...
Your problem is that textscan actually returns the loaded data in a 1-by-N cell array, where N is the number of columns (i.e. format specifiers, like %f) in your file. Each cell holds one column of data. You need to extract the contents of the cells using curly braces in order to pass it to plot3, like so:
plot3(data{5}, data{6}, data{7});


text:
Q: Control firing of events in TextWatcher for Android I had to recreate the functionality of AutoCompleteTextViews with EditTexts (for different reasons* & that's probably another question, but i'm down that path now).
I've got all my functionality working by issuing my api calls whenever the Text on my EditText changes. I do this by using TextWatcher (overriding the afterTextChanged method).
Is there a way i can control, the way the calls are fired with the listener?
Here's my use case:
I'm searching for California.
I check for a min. length of 3 and then start firing calls. so number of API calls currently sent = 8

*

*Cal

*Cali

*Calif

*Califo

*Califor

*Californ

*Californi

*California

Is there a way I can cancel off fired events, if i receive a new text change? So when the user types California, i wait until there's a gap where no new text is entered, and then fire a call to my API?
It doesn't have to be very accurate. An additional event fire here and there is completely acceptable. I'm looking to reduce the number of events fired from 8 to atleast 3.

I wanted to show the autocomplete results in a different listview vs. the pop-up window that comes alongside the auto-complete textview.

A: Try following TextWatcher:
TextWatcher t = new TextWatcher() {
        long lastChange = 0;

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

            // TODO Auto-generated method stub
            if (s.length() > 3) {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        if (System.currentTimeMillis() - lastChange >= 300) {
                            //send request
                        }
                    }
                }, 300);
                lastChange = System.currentTimeMillis();

            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
};


text:
Q: How have different tab bar icon color when selected I want know if there is a way to have a different color for different icon selected in a UITabBarController, i know that with this:
[[UITabBar appearance] setTintColor:[UIColor whiteColor]];

i can change the selection color for all icon, but how i can do it for different tab?

A: One way of doing this, would be by simply changing the tint color of the tabbar in the different viewcontrollers.
Let's say for example you have 3 different tabs: tab1, tab2 and tab3, all of which are displaying different viewcontrollers. Now, let's say you want to have a blue tint color in tab1 but a red tint color in tab2 and tab3.
Then, you can simply add the following line to the viewWillAppear: method of the different ViewControllers.
For the first viewController, which is shown in tab1, you'd have:
//In your viewcontroller which is shown in tab1
- (void)viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];
   // change tint color to blue
   [self.tabBarController.tabBar setTintColor:[UIColor blueColor]];
}

And for the other two, you simply put another color:
//In your viewcontrollers which are shown in tab2 and tab3
- (void)viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];
   // change tint color to red
   [self.tabBarController.tabBar setTintColor:[UIColor redColor]];
}

It's that simple. There are certainly other ways of doing this, but this one is pretty clean and straightforward.


text:
Q: Why fg command within an infinite while loop works like a "keep alive" watchdog? Recently, I've run into this implementation of a handicraft "keepalive" watchdog for a custom HTTP server:
|
|   keepalive.sh
|   init.sh
|_  main.py

There are three files. The first one being keepalive.sh: it is run as root from rc.local when the system starts up.
# keepalive.sh

while true
do
    if curl -s "localhost:8080/alive.txt" | grep -q "ALIVE"; then
        echo "UP
    else
        echo "Restarting..."
        pkill -u www-data -SIGKILL
    fi
    sleep 30
done

The second one is init.sh which is run as www-data user.
# init.sh

set -m
/usr/bin/python3 /var/www/main.py &
while true; do fg; sleep 1; done

The third one is the custom server itself main.py which needs to be kept alive.
from server import Server

HOST = '0.0.0.0'
PORT = 8080

if __name__ == "__main__":
    Server(HOST,PORT).listen()

I don't quite understand how init.sh works. With -m flag we enable job control in order to use fg from script file. What is the purpose of sending main.py to background and then doing fg in an infinite while? I understand that & is needed here to get to the loop after the server was started but why exactly fg (and not just true, for example) is used?
The other thing I do not understand is why init.sh restarts when it is killed with -SIGKILL. The Python script is launched in a separate process group with init.sh's PID as its own PPID. main.py gets killed when his parent (init.sh) gets killed, I'm all right with that. For me the question is why init.sh keeps restarting main.py (and also itself) after it's being killed with pkill.
Thanks!


text:
Q: Casting usercontrol text box to web control text box I have got the following user control:
<uc1:TextSearch runat="server" ID="tsClientName" HistoryQueryStringParameter="CN" LabelText="Client Name" />

I am trying to retrieve value of tsClientName field with the following code
TextBox txtbox = (TextBox)pnlAdvancedSearch.FindControl("tsClientName");
string var = txtbox.Text.ToString()

but I get this error:
Unable to cast object of type 'ASP.usercontrols_gridviewsearch_textsearch_ascx' to type 'System.Web.UI.WebControls.TextBox'

the user control field got the following code
<asp:TextBox runat="server" ID="txt" MaxLength="20" CssClass="title" />

A: You need to get the textbox control from user control as follows:
TextBox txtbox = (TextBox)pnlAdvancedSearch.FindControl("tsClientName").FindControl("txt");

A: There's no need to use FindControl and casting for access such as this. In the code-behind of the usercontrol, add a property to retrieve the text:
public string NameText { get { return txt.Text; } }

Then, in the page that hosts the usercontrol, you can obtain the text using:
string nameText = tsClientName.NameText;

A: So there is a TextboxText property, and it has a get accessor. That should be sufficient, as you're expecting to get the input from the user typing into the textbox.
Since the value of the TextboxText property is blank, rather than containing the value of the textbox—which we can see it's being set to by the property—the problem must be in the code-behind of the usercontrol. It must be initializing the textbox at the wrong time.


text:
Q: How to stop the error occuring in my Python curses code? I'm confused about why this error keeps popping up whenever I run some curses code.
Code:
import curses

stdscr = initscr()

Output:
Traceback (most recent call last):
  File "C:\Users\Abd-ur-Rahmaan\Desktop\Abd-Ur-Rahmaan Shabbir\Python coding\Python Advanced Shit\The first curses project\The first curses project.py", line 3, in <module>
    stdscr = curses.initscr()
  File "C:\Users\Abd-ur-Rahmaan\Desktop\lib\curses\__init__.py", line 30, in initscr
    fd=_sys.__stdout__.fileno())
AttributeError: 'NoneType' object has no attribute 'fileno'

A:
The Windows version of Python doesn't include the curses module. A ported version called UniCurses is available. You could also try the Console module written by Fredrik Lundh, which doesn't use the same API as curses but provides cursor-addressable text output and full support for mouse and keyboard input.

Refer to: https://docs.python.org/3/howto/curses.html

A: put your .py file wherever you have PATH enabled (it should be the python folder as standart)
pip install windows-curses
right click on start > run
enter the name of the file (snake.py for example)
run


text:
Q: обратные вычисления в python prettytable вот такой код
H = 10
print(H)
q = 0.8
print(q)
r = 21/q
print(r)
Ovr = q*r
print(Ovr)
L = H+Ovr
print(L)
Lv = L*.2
print(Lv)
Q = L/6
print(Q)
a = Q/(q*r*H)
print(a)

Все расчеты делаются последовательно и завязаны на первую позицию H = 10, которую можно изменять.
А как, допустим, все завязать на L и начать с нее.

A: Просто выразите все переменные используя переменные q, r и L:
from prettytable import PrettyTable

def calc(L, q, r):
    Ovr = q*r
    H = L - Ovr  # 21 - константа
    Lv = L*.2
    Q = L/6
    a = Q/(q*r*H)
    return [L, q, r, H, Lv, Q, a]

L = [12, 13, 24, 27, 31]
q = 0.8
r = 21/q

columns = ['L','q','r','H','Lv','Q','a']
tab = PrettyTable(field_names=columns, float_format=".2")
tab.add_rows([calc(l, q, r) for l in L])
print(tab)

результат:
+----+------+-------+-------+------+------+-------+
| L  |  q   |   r   |   H   |  Lv  |  Q   |   a   |
+----+------+-------+-------+------+------+-------+
| 12 | 0.80 | 26.25 | -9.00 | 2.40 | 2.00 | -0.01 |
| 13 | 0.80 | 26.25 | -8.00 | 2.60 | 2.17 | -0.01 |
| 24 | 0.80 | 26.25 |  3.00 | 4.80 | 4.00 |  0.06 |
| 27 | 0.80 | 26.25 |  6.00 | 5.40 | 4.50 |  0.04 |
| 31 | 0.80 | 26.25 | 10.00 | 6.20 | 5.17 |  0.02 |
+----+------+-------+-------+------+------+-------+


text:
Q: Angular RXJS multiple HTTP nested requests I can succesully make multiple parallel http calls using the forkjoin operator (example call all sales data)  however I need to concatenate further http calls based on the results of each of the first (sales ) http calls. I'm not sure if the mergeMap or concat operators are best and how they fit in here
example data is
sales
{saleId:100, name:'bob, uri:'http://testserver/sales/100'}
{saleId:101, name:'fred, uri:'http://testserver/sales/101'}
{saleId:102, name:'billy, uri:'http://testserver/sales/102'}

products
{id:1,saleId:101, detail:'test1', product:{id:200, uri:'http://testserver/product/200'} }
{id:1,saleId:101, detail:'test1', product:{id:201, uri:'http://testserver/product/201'} }
{id:1,saleId:101, detail:'test1', product:{id:202, uri:'http://testserver/product/202'} }

getServerChildNodes(childNodeObj: any[]): Observable<any> {
    //observablesListArray contains http sales uri
    return forkJoin(observablesListArray)
        .map((data: any[]) => {
            for (let i = 0; i < data.length; i++) {
               outputData.push(data[i].json());
            }
            return outputData;
        });
}

A: I am not sure I understand your question right, but it seems that you are looking for a way to concatenate 2 subsequent http calls, with the second requiring some data returned by the first. Plus, you want to run many of such chained calls in parallel.
If this is the case, this could be a way to approach it.
getSaleIds(): Observable<string[]>;

getSale(id: string): Observable<Sale> {
  // calls and http service and returns a Sale for a certain id
  // each Sale contains a productId to be used in the subsequent call
}

getProduct(productId: string): Observable<Product> {
  ...
}

getSaleAndThenProduct(saleId: string) {
  return getSale(saleId).pipe(
    switchMap(sale => getProduct(sale.productId),
    map(product => ({sale, product}))
  );
}

getSaleIds()
.pipe(
  map(saleIds => saleIds.map(id => getSaleAndThenProduct(id)),
  switchMap(functions => forkJoin(functions))
)
.subscribe(salesAndProducts => // do something)

salesAndProducts is an Array of objects of type {sale: Sale, product: Product}


text:
Q: python seaborn lmplot regplot for y-log scale fit I was wondering why seaborn lmplot and regplot only has the option to do logx. I have a frequent use to linearly fit log(y) ~ x and the Y-axis should always be in log scale to show the correlation (as a convention).
Is this something that can be done in Seaborn?
An option of logy=True would be nice...
Thanks.

A: You can simply set the y-axis scale to log with:
import seaborn as sns; sns.set(color_codes=True)
tips = sns.load_dataset("tips")
ax = sns.regplot(x="total_bill", y="tip", data=tips)
ax.set_yscale('log')  # set_yscale is a function, not a string

A: You can do it using the axis returned by regplot:
ax = seaborn.regplot('x', 'y', data)
ax.set(yscale='log')

A: Seaborn doesn't support this, but you can imitate what it does manually, inserting np.power(..., 10) and np.log10(...) where appropriate:
# create regression plotter object with log'd Y values
rp = sns.regression._RegressionPlotter(x[y>0], np.log10(y[y>0]))
# fit regression model
grid, yhat, err_bands = rp.fit_regression(ax)
# plot regression line with restored Y values
line, = ax.plot(grid, np.power(yhat, 10))
# plot error boundaries
ax.fill_between(
    grid,
    *[np.power(b, 10) for b in err_bands],
    facecolor=line.get_color(),
    alpha=.15,
)
# set axis to log10 scale
ax.set_yscale('log')


text:
Q: Check if char is a vowel using switch-case I'm trying to check if each character in a string using switch a statement inside a while loop. So far I have this:
//f and g - vowel and consonant count
        int f, g, ind;
        f = 0;
        g = 0;
        ind = 0;
        char letter = sentence.charAt(ind);

        while (letter != sentence.charAt(ind)) {
            switch (letter) {
                case 'a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y':
                    f += 1;
                    ind += 1;
                    break;

                //in case it's a number, the code will pass to the next char
                case 1, 2, 3, 4, 5, 6, 7, 8, 9:
                    ind += 1;
                    break;

                //in case it's a special character, the code will pass to the next char
                case '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '-', '_', '+', '=', '\\', '|', ';', ':', ',', '.', '/', '?':
                    ind += 1;
                    break;

                default:
                    g += 1;
                    ind += 1;
                    break;

            }
        }

For some reason it just returns 0 for both variables. Any suggestions? I'm to this btw so don't be too mean (a little bit is fine if I did something dumb). Also, if anyone has a more efficient way to check if the char is a special character, that would be much appreciated. Thanks in advance.

A: The variable letter never changes, so you always test the same character. Your while loop will stop when it reaches the first character that is different from the first one, so it will stop soon.
By the way, you may lighten your code calling consonants directly:
int f = 0, g = 0; // vowel and consonant counters
int ind = 0; // character index

while (ind < sentence.length()) {
    char letter = sentence.charAt(ind);
    switch (letter) {
        case 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y':
            f += 1;
            break;

        case 'b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'H',
             'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'p', 'P',
             'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'v', 'V', 'w', 'W',
             'x', 'X', 'z', 'Z':
            g += 1;
            break;

        default:
            break;
    }

    ind += 1;
}


text:
Q: How to add k-state-error class to kendo date picker I need to add k-state-error class in onChange event of Kendo date picker.
 function onChange(e) {
    if (e.date == undefined) {
        $(this).closest('span').addClass("myclass");
        $(this).parent('span').addClass("myclass");
        $(this).child('span').addClass("myclass");
    }
}

how can i access that?

A: Inside change event handler $(this) refers to DatePicker and not the original input. So you should use $(this.element) instead.
$("#date").kendoDatePicker({
    change: onChange
    }
});

function onChange(e) {
    if (!e.sender.value()) {
        $(this.element).closest('span').addClass("myclass");
        $(this.element).parent('span').addClass("myclass");
        // NOTE: The following will actually not work since it does not have child
        // $(this.element).child('span').addClass("myclass");
    }
}

EDIT: And define the style as:
.myclass {
    border: 3px solid red !important;
}

Running example here: http://jsfiddle.net/OnaBai/Csp6P/


text:
Q: JSP - Servlet "How to send table data from jsp to servlet"? I want to send table data from jsp to servlet.
Example the table structure is like
column1   column2
First     Name
Second    Name1

When i click on submit  how can i retrieve or get the data in  tags  First,Second, Name and Name1 values in servlet.
I searched but couldn't find any proper solution.
I want to know in how many ways i can achieve this.
I searched about this and found we can achieve this using  request.getParameter() or JSTL but didn't got any clear description
Please Suggest

A: You need to create a hidden input type and assign the value of td tag to it and access its value in servlet using request.getparameter("hiddenInputName")
e.g.
someData	<input type = "hidden" name = "someName" value = "someData">

Then after submitting form using post method you can access the value in servlet as
request.getParameter("someName");


text:
Q: Determine date/time of original post Is there a way to determine the original date/time of a Wordpress blog post?
Take for example this blog post.  There is no way to determine the date/time of the original posting.  However if you leave a comment then the date/time it was left is published.

A: That's not a blog "post", but a page. It doesn't share the date it was posted because it's meant to act as a web page that can change over time, not a post with information that may correlate to a single point in time.

A: If you are asking how to show the date/time on a page, this is absolutely possible. You can use the following code to display it. Just paste this code in the loop that is used in the page.php file of your theme
<?php the_time('F jS, Y') ?>

In order to style the date as you wish, see this page: http://codex.wordpress.org/Formatting_Date_and_Time


text:
Q: Image with js encodeURI does not show in email I am sending emails from my website. The email is html and contains an image.
It looks like the with encoded uris does not show in outlook, gmail etc.
This one does not show:
Path: Example
EmailSource(outlook):
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Test6

This one does show in the email:
Path:
http://www.rettilaalese.no/fileshare/filarkivroot/shop/Produktgruppe/medium.jpg
Email source(outlook):
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Test5

Hilsen Espen

The images exists and is showing in browser when using correct url(not example.com)


text:
Q: How to get a website's favicon with PHP? I want to get, requested website's favicon with PHP. I have been recommended using Google's favicon service but it is not functional. I want to do something on my own but don't know regex usage.
I found a class on Google that works on most cases but it has unacceptable error rate. You can have a look here: http://www.controlstyle.com/articles/programming/text/php-favicon/
Can somebody please help me about getting favicon using regex, please?

A: Use the S2 service provided by google. It is as simple as this
http://www.google.com/s2/favicons?domain=www.yourdomain.com

Scraping this would be much easier, that trying to do it yourself.

A: It looks like http://www.getfavicon.org/?url=domain.com (FAQ) reliably scrapes a website's favicon. I realise it's a 3rd-party service but I think it's a worthy alternative to the Google favicon service.

A: Quick and dirty:
<?php
$url = 'http://example.com/';
$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$doc->loadHTML(file_get_contents($url));
$xml = simplexml_import_dom($doc);
$arr = $xml->xpath('//link[@rel="shortcut icon"]');
echo $arr[0]['href'];

A: I've been doing something similar and I checked this with a bunch of URL and all seemed to work. URL doesn't have to be a base URL
function getFavicon($url){
    # make the URL simpler
    $elems = parse_url($url);
    $url = $elems['scheme'].'://'.$elems['host'];

    # load site
    $output = file_get_contents($url);

    # look for the shortcut icon inside the loaded page
    $regex_pattern = "/rel=\"shortcut icon\" (?:href=[\'\"]([^\'\"]+)[\'\"])?/";
    preg_match_all($regex_pattern, $output, $matches);

    if(isset($matches[1][0])){
        $favicon = $matches[1][0];

        # check if absolute url or relative path
        $favicon_elems = parse_url($favicon);

        # if relative
        if(!isset($favicon_elems['host'])){
            $favicon = $url . '/' . $favicon;
        }

        return $favicon;
    }

    return false;
}

A: According to Wikipedia, there are 2 major methods which can be used by websites to have a favicon picked up by a browser. The first is as Steve mentioned, having the icon stored as favicon.ico in the root directory of the webserver. The second is to reference the favicon via the HTML link tag.
To cover all of these cases, the best idea would be to test for the presence of the favicon.ico file first, and if it is not present, search for either the <link rel="icon" or <link rel="shortcut icon" part in the source (limited to the HTML head node) until you find the favicon. It is up to you whether you choose to use regex, or some other string search option (not to mention the built in PHP ones). Finally, this question may be of some help to you.

A: I've implemented a favicon grabber of my own, and I detailed the usage in another StackOverflow post here: Get website's favicon with JS
Thanks, and let me know if it helps you.  Also, any feedback is greatly appreciated.

A: First Method in which we can search it from fevicon.ico if found than it will show it up else not
<?php
        $userPath=$_POST["url"];
        $path="http://www.".$userPath."/favicon.ico";
        $header=  get_headers($path);
        if(preg_match("|200|", $header[0]))
        {
            echo '';
        }
        else
        {
            echo "Not found";
        }
    ?>

In other method you can search for icon and get that icon file
    <?php
$website=$_POST["url"];
$fevicon= getFavicon($website);
echo '';
function getFavicon($site)
{
            $html=file_get_contents("http://www.".$site);
            $dom=new DOMDocument();
            @$dom->loadHTML($html);
            $links=$dom->getElementsByTagName('link');
            $fevicon='';

            for($i=0;$i < $links->length;$i++ )
            {
                $link=$links->item($i);
                if($link->getAttribute('rel')=='icon'||$link->getAttribute('rel')=="Shortcut Icon"||$link->getAttribute('rel')=="shortcut icon")
                {
                    $fevicon=$link->getAttribute('href');
                }
            }
            return  $fevicon;
}
?>

A: See this answer : https://stackoverflow.com/a/22771267. It's an easy to use PHP class to get the favicon URL and download it, and it also gives you some informations about the favicon like file type or how the favicon was found (default URL, <link> tag...) :
<?php
require 'FaviconDownloader.class.php';
$favicon = new FaviconDownloader('https://code.google.com/p/chromium/issues/detail?id=236848');

if($favicon->icoExists){
    echo "Favicon found : ".$favicon->icoUrl."\n";

    // Saving favicon to file
    $filename = 'favicon-'.time().'.'.$favicon->icoType;
    file_put_contents($filename, $favicon->icoData);
    echo "Saved to ".$filename."\n\n";
} else {
    echo "No favicon for ".$favicon->url."\n\n";
}

$favicon->debug();
/*
FaviconDownloader Object
(
    [url] => https://code.google.com/p/chromium/issues/detail?id=236848
    [pageUrl] => https://code.google.com/p/chromium/issues/detail?id=236848
    [siteUrl] => https://code.google.com/
    [icoUrl] => https://ssl.gstatic.com/codesite/ph/images/phosting.ico
    [icoType] => ico
    [findMethod] => head absolue_full
    [error] =>
    [icoExists] => 1
    [icoMd5] => a6cd47e00e3acbddd2e8a760dfe64cdc
)
*/
?>

A: PHP Grab Favicon
This is a comfortable way with many parameter to get the favicon from a page URL.
How it Works

*

*Check if the favicon already exists local or no save is wished, if so return path & filename

*Else load URL and try to match the favicon location with regex

*If we have a match the favicon link will be made absolute

*If we have no favicon we try to get one in domain root

*If there is still no favicon we randomly try google, faviconkit & favicongrabber API

*If favicon should be saved try to load the favicon URL

*If wished save the Favicon for the next time and return the path & filename

So it combine both ways: Try to get the Favicon from the Page and if that don't work use an "API" Service that give back the Favicon ;-)
<?php
/*

PHP Grab Favicon
================

> This `PHP Favicon Grabber` use a given url, save a copy (if wished) and return the image path.

How it Works
------------

1. Check if the favicon already exists local or no save is wished, if so return path & filename
2. Else load URL and try to match the favicon location with regex
3. If we have a match the favicon link will be made absolute
4. If we have no favicon we try to get one in domain root
5. If there is still no favicon we randomly try google, faviconkit & favicongrabber API
6. If favicon should be saved try to load the favicon URL
7. If wished save the Favicon for the next time and return the path & filename

How to Use
----------

```PHP
$url = 'example.com';

$grap_favicon = array(
'URL' => $url,   // URL of the Page we like to get the Favicon from
'SAVE'=> true,   // Save Favicon copy local (true) or return only favicon url (false)
'DIR' => './',   // Local Dir the copy of the Favicon should be saved
'TRY' => true,   // Try to get the Favicon frome the page (true) or only use the APIs (false)
'DEV' => null,   // Give all Debug-Messages ('debug') or only make the work (null)
);

echo '<img src="'.grap_favicon($grap_favicon).'">';
```

Todo
----
Optional split the download dir into several sub-dirs (MD5 segment of filename e.g. /af/cd/example.com.png) if there are a lot of favicons.

Infos about Favicon
-------------------
https://github.com/audreyr/favicon-cheat-sheet

###### Copyright 2019 Igor Gaffling

*/

$testURLs = array(
  'http://aws.amazon.com',
  'http://www.apple.com',
  'http://www.dribbble.com',
  'http://www.github.com',
  'http://www.intercom.com',
  'http://www.indiehackers.com',
  'http://www.medium.com',
  'http://www.mailchimp.com',
  'http://www.netflix.com',
  'http://www.producthunt.com',
  'http://www.reddit.com',
  'http://www.slack.com',
  'http://www.soundcloud.com',
  'http://www.stackoverflow.com',
  'http://www.techcrunch.com',
  'http://www.trello.com',
  'http://www.vimeo.com',
  'https://www.whatsapp.com/',
  'https://www.gaffling.com/',
);

foreach ($testURLs as $url) {
  $grap_favicon = array(
    'URL' => $url,   // URL of the Page we like to get the Favicon from
    'SAVE'=> true,   // Save Favicon copy local (true) or return only favicon url (false)
    'DIR' => './',   // Local Dir the copy of the Favicon should be saved
    'TRY' => true,   // Try to get the Favicon frome the page (true) or only use the APIs (false)
    'DEV' => null,   // Give all Debug-Messages ('debug') or only make the work (null)
  );
  $favicons[] = grap_favicon($grap_favicon);
}
foreach ($favicons as $favicon) {
  echo '';
}
echo '

<tt>Runtime: '.round((microtime(true)-$_SERVER["REQUEST_TIME_FLOAT"]),2).' Sec.';

function grap_favicon( $options=array() ) {

  // Ini Vars
  $url       = (isset($options['URL']))?$options['URL']:'gaffling.com';
  $save      = (isset($options['SAVE']))?$options['SAVE']:true;
  $directory = (isset($options['DIR']))?$options['DIR']:'./';
  $trySelf   = (isset($options['TRY']))?$options['TRY']:true;
  $DEBUG     = (isset($options['DEV']))?$options['DEV']:null;

  // URL to lower case
    $url = strtolower($url);

    // Get the Domain from the URL
  $domain = parse_url($url, PHP_URL_HOST);

  // Check Domain
  $domainParts = explode('.', $domain);
  if(count($domainParts) == 3 and $domainParts[0]!='www') {
    // With Subdomain (if not www)
    $domain = $domainParts[0].'.'.
              $domainParts[count($domainParts)-2].'.'.$domainParts[count($domainParts)-1];
  } else if (count($domainParts) >= 2) {
    // Without Subdomain
        $domain = $domainParts[count($domainParts)-2].'.'.$domainParts[count($domainParts)-1];
    } else {
      // Without http(s)
      $domain = $url;
    }

    // FOR DEBUG ONLY
    if($DEBUG=='debug')print('Domain #'.@$domain.'#
');

    // Make Path & Filename
    $filePath = preg_replace('#\/\/#', '/', $directory.'/'.$domain.'.png');

    // If Favicon not already exists local
  if ( !file_exists($filePath) or @filesize($filePath)==0 ) {

    // If $trySelf == TRUE ONLY USE APIs
    if ( isset($trySelf) and $trySelf == TRUE ) {

      // Load Page
      $html = load($url, $DEBUG);

      // Find Favicon with RegEx
      $regExPattern = '/((<link[^>]+rel=.(icon|shortcut icon|alternate icon)[^>]+>))/i';
      if ( @preg_match($regExPattern, $html, $matchTag) ) {
        $regExPattern = '/href=(\'|\")(.*?)\1/i';
        if ( isset($matchTag[1]) and @preg_match($regExPattern, $matchTag[1], $matchUrl)) {
          if ( isset($matchUrl[2]) ) {

            // Build Favicon Link
            $favicon = rel2abs(trim($matchUrl[2]), 'http://'.$domain.'/');

            // FOR DEBUG ONLY
            if($DEBUG=='debug')print('Match #'.@$favicon.'#
');

          }
        }
      }

      // If there is no Match: Try if there is a Favicon in the Root of the Domain
        if ( empty($favicon) ) {
        $favicon = 'http://'.$domain.'/favicon.ico';

        // Try to Load Favicon
        if ( !@getimagesize($favicon) ) {
          unset($favicon);
        }
        }

    } // END If $trySelf == TRUE ONLY USE APIs

    // If nothink works: Get the Favicon from API
    if ( !isset($favicon) or empty($favicon) ) {

      // Select API by Random
      $random = rand(1,3);

      // Faviconkit API
      if ($random == 1 or empty($favicon)) {
        $favicon = 'https://api.faviconkit.com/'.$domain.'/16';
      }

      // Favicongrabber API
      if ($random == 2 or empty($favicon)) {
        $echo = json_decode(load('http://favicongrabber.com/api/grab/'.$domain,FALSE),TRUE);

        // Get Favicon URL from Array out of json data (@ if something went wrong)
        $favicon = @$echo['icons']['0']['src'];

      }

      // Google API (check also md5() later)
      if ($random == 3) {
        $favicon = 'http://www.google.com/s2/favicons?domain='.$domain;
      }

      // FOR DEBUG ONLY
      if($DEBUG=='debug')print(''.$random.'. API #'.@$favicon.'#
');

    } // END If nothink works: Get the Favicon from API

    // Write Favicon local
    $filePath = preg_replace('#\/\/#', '/', $directory.'/'.$domain.'.png');

    // If Favicon should be saved
    if ( isset($save) and $save == TRUE ) {

      //  Load Favicon
      $content = load($favicon, $DEBUG);

      // If Google API don't know and deliver a default Favicon (World)
      if ( isset($random) and $random == 3 and
           md5($content) == '3ca64f83fdcf25135d87e08af65e68c9' ) {
        $domain = 'default'; // so we don't save a default icon for every domain again

        // FOR DEBUG ONLY
        if($DEBUG=='debug')print('Google #use default icon#
');

      }

      // Write
      $fh = @fopen($filePath, 'wb');
      fwrite($fh, $content);
      fclose($fh);

      // FOR DEBUG ONLY
        if($DEBUG=='debug')print('Write-File #'.@$filePath.'#
');

    } else {

      // Don't save Favicon local, only return Favicon URL
      $filePath = $favicon;
    }

    } // END If Favicon not already exists local

    // FOR DEBUG ONLY
    if ($DEBUG=='debug') {

    // Load the Favicon from local file
      if ( !function_exists('file_get_contents') ) {
      $fh = @fopen($filePath, 'r');
      while (!feof($fh)) {
        $content .= fread($fh, 128); // Because filesize() will not work on URLS?
      }
      fclose($fh);
    } else {
      $content = file_get_contents($filePath);
    }
      print('Image
');
  }

  // Return Favicon Url
  return $filePath;

} // END MAIN Function

/* HELPER load use curl or file_get_contents (both with user_agent) and fopen/fread as fallback */
function load($url, $DEBUG) {
  if ( function_exists('curl_version') ) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERAGENT, 'FaviconBot/1.0 (+http://'.$_SERVER['SERVER_NAME'].'/');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $content = curl_exec($ch);
    if ( $DEBUG=='debug' ) { // FOR DEBUG ONLY
      $http_code = curl_getinfo($ch);
      print('cURL #'.$http_code['http_code'].'#
');
    }
    curl_close($ch);
    unset($ch);
  } else {
    $context = array ( 'http' => array (
        'user_agent' => 'FaviconBot/1.0 (+http://'.$_SERVER['SERVER_NAME'].'/)'),
    );
    $context = stream_context_create($context);
      if ( !function_exists('file_get_contents') ) {
      $fh = fopen($url, 'r', FALSE, $context);
      $content = '';
      while (!feof($fh)) {
        $content .= fread($fh, 128); // Because filesize() will not work on URLS?
      }
      fclose($fh);
    } else {
      $content = file_get_contents($url, NULL, $context);
    }
  }
  return $content;
}

/* HELPER: Change URL from relative to absolute */
function rel2abs( $rel, $base ) {
    extract( parse_url( $base ) );
    if ( strpos( $rel,"//" ) === 0 ) return $scheme . ':' . $rel;
    if ( parse_url( $rel, PHP_URL_SCHEME ) != '' ) return $rel;
    if ( $rel[0] == '#' or $rel[0] == '?' ) return $base . $rel;
    $path = preg_replace( '#/[^/]*$#', '', $path);
    if ( $rel[0] ==  '/' ) $path = '';
    $abs = $host . $path . "/" . $rel;
    $abs = preg_replace( "/(\/\.?\/)/", "/", $abs);
    $abs = preg_replace( "/\/(?!\.\.)[^\/]+\/\.\.\//", "/", $abs);
    return $scheme . '://' . $abs;
}

Source: https://github.com/gaffling/PHP-Grab-Favicon

A: I find PHP Simple HTML DOM Parser to be more reliable than DOMDocument. So I use this instead:
require_once 'simple_html_dom.php';
$dom = new simple_html_dom();
$dom->load(file_get_contents($url));
$favicon = '';
foreach($dom->find('link') as $e)
{
  if (!empty($e->rel) && strtolower(trim($e->rel)) == 'shortcut icon') {
    $favicon = $url.'/'.$e->href;
  }
}

print $favicon;

A: Found this thread... I have written a WordPress plugin that encompasses a lot of variations on retrieving the favicon. Since there are a lot the GPL code: http://plugins.svn.wordpress.org/wp-favicons/trunk/
It lets you run a server which you can request icons from via xml rpc requests so any client can request icons. It does have a plugin structure so you can try google, getfavicon, etc... to see if one of these services delivers anything. If not then it goes into a icon fetching mode taking into account all http statusses (301/302/404) and does it best to find an icon anywhere. After this it uses image library functions to check inside the file if it is really an image and what kind of image (sometimes the extension is wrong) and it is pluggable so you can add after image conversions or extra functionality in the pipeline.
the http fetching file does some logic around what i see above: http://plugins.svn.wordpress.org/wp-favicons/trunk/includes/server/class-http.php
but it is only part of the pipeline.
can get pretty complex once you dive into it.

A: $url = 'http://thamaraiselvam.strikingly.com/';
$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
@$doc->loadHTML(file_get_contents($url));
$xml = simplexml_import_dom($doc);
$arr = $xml->xpath('//link[@rel="shortcut icon"]');
if (!empty($arr[0]['href'])) {
    echo "";
 }
else
echo "";

A: I changed a bit Vivek second method and added a this function and it looks like this:
<?php
        $website=$_GET['u'];
        $fevicon= getFavicon($website);
        echo '';

            function getFavicon($site)
            {
            $html=file_get_contents($site);
            $dom=new DOMDocument();
            @$dom->loadHTML($html);
            $links=$dom->getElementsByTagName('link');
            $fevicon='';

            for($i=0;$i < $links->length;$i++ )
            {
                $link=$links->item($i);
                if($link->getAttribute('rel')=='icon'||$link->getAttribute('rel')=="Shortcut Icon"||$link->getAttribute('rel')=="shortcut icon")
                {
                    $fevicon=$link->getAttribute('href');
                }
            }
            return  $fevicon;
            }

    // transform to absolute path function...
    function path_to_absolute($rel, $base)
    {
    /* return if already absolute URL */
    if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;
    /* queries and anchors */
    if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
    /* parse base URL and convert to local variables:
       $scheme, $host, $path */
    extract(parse_url($base));
    /* remove non-directory element from path */
    $path = preg_replace('#/[^/]*$#', '', $path);
    /* destroy path if relative url points to root */
    if ($rel[0] == '/') $path = '';
    /* dirty absolute URL */
    $abs = "$host$path/$rel";
    /* replace '//' or '/./' or '/foo/../' with '/' */
    $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
    for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
    /* absolute URL is ready! */
    return $scheme.'://'.$abs;
    }

?>

Of course you call it with https://www.domain.tld/favicon/this_script.php?u=http://www.example.com
Still can't catch all options but now absolute path is resolved. Hope it helps.

A: If you want to retrieve the favicon from a particular website, you simply need to fetch favicon.ico from the root of their website.  Like so:
$domain = "www.example.com";
$url = "http://".$domain."/favicon.ico";
$icondata = file_get_contents($url);

... you can now do what you like with the icon data


text:
Q: Entering path containing spaces in Terminal Working on my MacBook Pro, I want to change the location of my iPhone backup to an external drive, but when entering the command on the CLI I hadn't noticed that the destination drive has a space in the name (HARDDRV BKUP). How would I enter the following
ln -s /Volumes/HARDDRV BKUP/iphonebkup/Backup/ ~/Library/Application\ Support/MobileSync

using "HARDDRV BKUP" as the name of the external drive in Terminal?  If I recall correctly, the CLI doesn't interpret SPACES the same way, and capitalization is important to take into account as well, correct?  Can someone here correct this for me?
I am new at using the CLI and most of my experience is using the GUI, so I am getting very frustrated and don't have the energy to research all my notes on this.

A: Choose one of the following:

*

*Surround the part of the path containing spaces in quotes:
ln -s /Volumes/"HARDDRV BKUP"/iphonebkup/Backup/ ~/Library/Application\ Support/MobileSync
               ^            ^

*Surround the entire path in quotes:
ln -s "/Volumes/HARDDRV BKUP/iphonebkup/Backup/" ~/Library/Application\ Support/MobileSync
      ^                                        ^

*Escape the space with a backslash \:
ln -s /Volumes/HARDDRV\ BKUP/iphonebkup/Backup/ ~/Library/Application\ Support/MobileSync
                      ^

Case sensitivity is important in these cases.


text:
Q: Design issue with Flex I am working with Flex 3.0. I am trying to nest VBoxes within a TabNavigator and that works fine. But in my first VBox I have two buttons which won't show. I am not great with design concepts anyway and am new to Flex. I have tried messing with width and height properties, using an Hbox. Could someone take a look and figure out what I could do to fix these. Here is the full Panel. The TabNavigator is close to the bottom.
<mx:Panel id="pnlMain" label="Address Search" width="100%" borderStyle="none" headerHeight="0">
    <mx:ViewStack id="vsAddressSearch" resizeToContent="true">
        <mx:Form id="frmAddressSearch" styleName="measureForm" width="300" height="100%" fontFamily="Arial" fontSize="11" verticalGap="0" horizontalGap="0" verticalScrollPolicy="off" horizontalScrollPolicy="off">
            <mx:FormItem label="Address:" paddingBottom="5" paddingTop="5" textAlign="left" fontWeight="bold" width="100%">
                <mx:TextInput width="100%" id="txtAddress" text=""/>
            </mx:FormItem>
            <mx:HRule height="5" width="100%"/>
            <mx:HBox horizontalAlign="left" paddingTop="5">
                <mx:Button label="Find Address" click="BingFindAddress()"/>
                <mx:Button label="Clear" click="clearGraphics()"/>
            </mx:HBox>
        </mx:Form>
        <mx:Form id="frmAddressSearch1" styleName="measureForm" width="100%" height="100%" fontFamily="Arial" fontSize="11" verticalGap="0" horizontalGap="0" verticalScrollPolicy="off" horizontalScrollPolicy="off">
            <mx:FormItem label="Street:" paddingBottom="5"  labelWidth="150" textAlign="left" fontWeight="bold">
                <mx:TextInput width="100%" id="address" text=""/>
            </mx:FormItem>
            <mx:FormItem label="City:" paddingBottom="5" labelWidth="150" textAlign="left" fontWeight="bold">
                <mx:TextInput width="100%" id="city" text=""/>
            </mx:FormItem>
            <mx:FormItem label="State/Province:" paddingBottom="5"  labelWidth="150" textAlign="left" fontWeight="bold">
                <mx:TextInput width="100" id="state" text="PA"/>
            </mx:FormItem>
            <mx:FormItem label="ZIP Code or Postal Code:" fontWeight="bold" labelWidth="150"  textAlign="left" paddingBottom="5" >
                <mx:TextInput width="100" id="zip" text=""/>
            </mx:FormItem>
            <mx:FormItem label="Country:" paddingBottom="5"  labelWidth="150" textAlign="left" fontWeight="bold">
                <mx:ComboBox id="country" selectedIndex="0">
                    <mx:ArrayCollection>
                        <mx:String>USA</mx:String>
                        <mx:String>Canada</mx:String>
                        <mx:String>Mexico</mx:String>
                    </mx:ArrayCollection>
                </mx:ComboBox>
            </mx:FormItem>
            <mx:HRule height="5" width="100%"/>
            <mx:HBox horizontalAlign="left" paddingTop="5">
                <mx:Button label="Find Address" click="ESRIFindAddress()"/>
                <mx:Button label="Clear" click="clearGraphics()"/>

            </mx:HBox>
        </mx:Form>
        <mx:Form id="frmAddressSearch2" styleName="measureForm" width="100%" height="100%" fontFamily="Arial" fontSize="11" verticalGap="0" horizontalGap="0" verticalScrollPolicy="off" horizontalScrollPolicy="off">
            <mx:FormItem  label="Street:" paddingBottom="5"  labelWidth="150" textAlign="left" fontWeight="bold">
                <mx:TextInput width="100%" id="bamAddress" text="273 Cumberland St"/>
            </mx:FormItem>
            <mx:FormItem  label="City:" paddingBottom="5" labelWidth="150" textAlign="left" fontWeight="bold">
                <mx:TextInput width="100%" id="bamCity" text="Harrisburg"/>
            </mx:FormItem>
            <mx:FormItem  label="State/Province:" paddingBottom="5"  labelWidth="150" textAlign="left" fontWeight="bold">
                <mx:TextInput width="100" id="bamState" text="PA"/>
            </mx:FormItem>
            <mx:FormItem  label="ZIP Code or Postal Code:" fontWeight="bold" labelWidth="150"  textAlign="left" paddingBottom="5" >
                <mx:TextInput width="100" id="bamZip" text="17102"/>
            </mx:FormItem>
            <mx:FormItem label="Country:" paddingBottom="5"  labelWidth="150" textAlign="left" fontWeight="bold">
                <mx:ComboBox id="bamCountry" selectedIndex="0">
                    <mx:ArrayCollection>
                        <mx:String>USA</mx:String>
                        <mx:String>Canada</mx:String>
                        <mx:String>Mexico</mx:String>
                    </mx:ArrayCollection>
                </mx:ComboBox>
            </mx:FormItem>
            <mx:HRule height="5" width="100%"/>
            <mx:HBox horizontalAlign="left" paddingTop="5">
                <mx:Button label="Find Address" click="BAMFindAddress()"/>
                <mx:Button label="Clear" click="clearGraphics()"/>
            </mx:HBox>
        </mx:Form>
    </mx:ViewStack>
    <mx:VBox id="frmShell" backgroundAlpha=".7" backgroundColor="#dddddd" visible="false" left="0" top="0" width="100%" height="100%"></mx:VBox>
    <mx:Text id="hintLabel" fontSize="10" color="#999999" text="" horizontalCenter="0" bottom="10" visible="false" maxWidth="290" />

    <mx:TabNavigator id="tabNavigator" width="100%" height="0%"  visible="false" creationPolicy="auto">

        <mx:VBox id="generalInformation" label="Gen. Info." width="100%">
            <mx:Label id="ard" text="">
            </mx:Label>
            <mx:Button  id="googleButton" visible="false" label="Google Directions" click="newWin('https://maps.google.com/?q=' + addressResult)"/>
            <mx:Button id="mapquestButton" visible="false" label="MapQuest Directions" click="newWin('https://mapquest.com/?q=' + addressResult)"/>
        </mx:VBox>
        <mx:VBox id="schoolDistrict" label="School District" width="100%">
        </mx:VBox>
        <mx:VBox id="paHouse" label="PA House" width="100%">
        </mx:VBox>
        <mx:VBox id="paSenate" label="PA Senate" width="100%">
        </mx:VBox>
        <mx:VBox id="usHouse" label="US House" width="100%">
        </mx:VBox>
    </mx:TabNavigator>
</mx:Panel>

A: Your buttons are set to visible="false" so they are  not going to show up.
<mx:Button  id="googleButton" visible="false" label="Google Directions" click="newWin('https://maps.google.com/?q=' + addressResult)"/>
<mx:Button id="mapquestButton" visible="false" label="MapQuest Directions" click="newWin('https://mapquest.com/?q=' + addressResult)"/>


text:
Q: "A Theory of Moderation" update The Theory of Moderation blog post has some outdated information:

Im pretty sure it is still a suggested edit at 500 reputation. (I tried it C++ templates with derived classes)
The privileges screen doesn't have it either, please update the blog post as well.


text:
Q: Getting destination member expression by source expression in AutoMapper Let say I have mapping like this:
Mapper.CreateMap<CalendarEvent, CalendarEventForm>()
    .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date))

Is it possible to get back the destination member expression by its relative source expression. Something like this:
Expression<Func<CalendarEventForm, object>> destinationExpression = Mapper.GetMemmberExpression(src => src.EventDate.Date);

Thanks in advance.


text:
Q: Integrate $\int \frac{x^7}{(x^{10} + x^6 + x^2 +1)} dx$ How I can integrate this $$\int \frac{x^7}{(x^{10} + x^6 + x^2 +1)} dx$$

A: It's not going to be pleasant, since the denominator is irreducible over the rationals.  You could write it as
$$\dfrac{1}{2} \sum_r \dfrac{r^3 \ln(x^2-r)}{5 r^4 + 3 r^2 + 1}$$
where the sum is over the five roots (one real, two complex-conjugate pairs) of $z^5 + z^3 + z + 1$.


text:
Q: Correctly begin and end an environment via commands I would like to create a set of commands in my recent document class jwjournal for temporarily switch the syntax off and on. However, when trying to end and start the main environment with commands, this error appears:
\begin{jwjournal} on input line 11 ended by \end{{}.

Below is a MWE. To my knowledge, \JournalSyntaxOn should be equivalent to \begin{jwjournal} and similarly for \JournalSyntaxOff, but it is clearly not the case here. Is there any chance that my definitions below can somehow be fixed?
\documentclass{jwjournal}
\def\JournalSyntaxOn{\begin{jwjournal}}
\def\JournalSyntaxOff{\end{jwjournal}}

\begin{document}

\end{jwjournal}   \verb|test| \begin{jwjournal}  % Works

\JournalSyntaxOff \verb|test| \JournalSyntaxOn   % Error

\end{document}

A: You may not be taking the right approach: perhaps you don't need to define a set of two commands, but an environment; something like begin{jwjournalsynt} and \end{jwjournalsynt}. Section 3.4 of the Old User Guide told you how to do this:
\newenvironment {⟨cmd⟩} [⟨num⟩] [⟨default⟩] {⟨beg-def ⟩} {⟨end-def ⟩}
\newenvironment* {⟨cmd⟩} [⟨num⟩] [⟨default⟩] {⟨beg-def ⟩} {⟨end-def ⟩}
\renewenvironment {⟨cmd⟩} [⟨num⟩] [⟨default⟩] {⟨beg-def ⟩} {⟨end-def ⟩}
\renewenvironment* {⟨cmd⟩} [⟨num⟩] [⟨default⟩] {⟨beg-def ⟩} {⟨end-def ⟩}

now, and section 2.4 of the New User Guide tells you
\NewDocumentEnvironment {⟨env⟩} {⟨arg spec⟩} {⟨beg-code⟩} {⟨end-code⟩}
\RenewDocumentEnvironment {⟨env⟩} {⟨arg spec⟩} {⟨beg-code⟩} {⟨end-code⟩}
\ProvideDocumentEnvironment {⟨env⟩} {⟨arg spec⟩} {⟨beg-code⟩} {⟨end-code⟩}
\DeclareDocumentEnvironment {⟨env⟩} {⟨arg spec⟩} {⟨beg-code⟩} {⟨end-code⟩}

@ulrike precisely points out in a comment that you are trying to define a new environment, which seems to me is still obscure to you; and that you are dealing with a special case.
While environments \begin{⟨environment⟩} . . . \end{⟨environment⟩} are typically used in cases where the code implementing the ⟨environment⟩ does not
need to access the contents of the environment (its 'body'), it is sometimes
useful to have the body as a standard argument.
This is achieved by ending the argument specification with b, which is a dedicated argument type for this situation. For instance
\NewDocumentEnvironment{twice} {O{\ttfamily} +b}
{#2#1#2} {}
\begin{twice}[\itshape]
Hello world!
\end{twice}

You may check how this is done internally (with LaTeX3 syntax), by searching \__cmd_declare_env:nnnn in the LaTeX sources.
In any event, this is a LaTeX3 thing, and not a "core" question.

A: Main problem is that the "jwjournal" enviroment uses the b xparse functionality to grab the environment body between the \begin{...} and the next \end{...}
... in the document text, not in the expansion of a macro in the document text.
This means that your \JournalSyntaxOn expands to \begin{jwjournal} which expands to some internal xparse macros trying to grab everything until an \end of the current environment is found.  Because you "hide" the corresponding \end{...} inside the \JournalSyntaxOff macro there is no \end to be found or the wrong \end or the end of the document will stop the scan process with an error message.
Thus the simplest solution is to define a normal LaTeX environment on top of "jwjournal" and/or "xparse", already proposed in the other answers and comments.
Or you have to implement your own scan and grab routines to search for \JournalSyntaxOff macro token instead of the environment \end{...}.


text:
Q: How to use Mojolicious app inside DBIx Class schema? I have Mojolicious application that uses DBIx::Class. It is working fine, but now I would like to use Mojolicious app object inside DBIx::Class schema module.
In template I use this code to display link:
<a href="<%= $self->url_for('playlist', name => $playlist->name) %>">...

Now I would like to move part of the code that generates url into DBIx::Class schema module, so that in template I could have this:
<a href="<%= $playlist->url %>">...

I tried to achieve this by creating sub url in my Schema::Result::Playlist.pm
sub url {
    my $self = shift;
    my ($app) = @_;
    return $app->url_for('playlist', name => $self->name);
}

This works, but requires passing Mojolicious app to url (ex. <%= $playlist->url($self) %>) which is not nice.
Is there an elegant way to provide Mojolicious app object to all DBIx::Class schema modules at once, maybe during app startup?
This is my schema initialization in my app startup routine:
my $schema = MyApp::Schema->connect(
    'dbi:mysql:dbname=myapp',
    'xxxx',
    'xxxx',
    { mysql_enable_utf8 => 1, },
);
$self->helper( schema => sub { $schema } );

A: The model in an MVC application should be decoupled so it can be used outside of the app too.
The controllers have the task to fetch data from the model(s) and pass it on to the view(s).
Your templates are perfectly fine, no need to change anything.