text:
Q: Python is slowly replacing C in universities. Does this move degrade the quality of CS students? I believe learning C is one of the most important aspects for any programmer. It's a beautiful combination of a high and low level language. Some universities are moving to stop teaching C in the introductory stages and are using Python instead.
Will this move to Python, from C, degrade the quality of CS students?  If you miss out on some of the aspects of a low level language, are you missing something important from you CS degree?

A: This is an incorrect assumption, followed by an incorrect conclusion.
Teaching programming is about learning how to solve problems with computers. That can happen in a variety of different languages. C is certainly not the best, nor the worst language to start with.
You know what will degrade the quality of CS students? Not preparing them for the workplace by making them use the tools they will actually find there.

A: CS students should learn C (and some variant of assembler for that matter) to understand how computers roll. If you consider yourself not just a code slave, but a developer, you should understand how the machine and the operating system does things.

A: Two things:

*

*Computer Science is not about programming, but about higher-level concepts, algorithms, mathematical foundations of programming, that kind of thing. Any programming language taught as part of a CS curriculum serves as a vehicle to express and implement those concepts, but learning the language itself in-depth is not really a primary goal. As such, Python (being easy to learn, multi-paradigm, and low on boilerplate code) is an excellent choice for most high-level things. However, low-level programming concepts such as memory allocation, bitwise operations etc., also belong in CS, and Python provides little or no access to these, so an additional language is probably required, and C seems to be the best candidate (although assembly would also qualify, even though it's less comfortable to use).

*No programmer should enter the work force with knowledge of only one programming language. I believe that being somewhat fluent in at least two (ideally, two very different languages), and having sniffed about half a dozen more (ideally, covering a wide range of styles and paradigms), would be about right. A programmer with exposure to only one language is going to be limited to the thought patterns of that language and its community, and will lack insights gained from other languages and paradigms. Some concepts, such as for example Functional Programmign concepts like purity, currying, closures, or OOP concepts like interfaces, composition, and encapsulation, will only really 'click' once you've used them in a language designed around them. You just won't get to that point if you only ever learned one language, even if it's versatile and multi-paradigm.

A: Many programmers these days would dispute your assertion about the importance of learning C.  Many of the tricky points of C, such as

*

*keeping track of pointers

*making sure memory is allocated and
deallocated correctly

are no longer relevant to modern programming languages.  Kudos to the universities who are recognising this and switching to Python.

A: I totally agree that learning C is very important for programmers. It's the most well designed language (in my opinion).
But, I also think that for beginners, it may be OK to not start off their programming journey with C. Learning Python is GREAT experience, and learning C may not be that great at first. And for newbies, a good first impression of programming may be more important than learning the squiggly syntax of C pointers and pointer arithmetic. Hence the move.

A: Pointers and memory and stuff are hard things to explain to new students, what i see in my area is that "harder" languages are being displaced by this "newage" stuff like Python and Java. Those are easier to explain than for instance C++, Perl, even Basic.
What i think that degrades understanding is just throwing OOP and ready made Modules at students. In the end they don't really learn anything Computer-Sciency, just to parse some data into another thing with a scriptable tool.
Starting by the easy stuff just breeds lazy minds, not lazy programmers, wich we need.
But well, TLDR; version:
Python is for lazy teachers, C is for good brave teachers.
edit: I'm not flaming Python, it's great, but it's the kind of thing you have to learn on your own or with a community, but C needs a place in CS courses.

A: You must learn C but you might be better off with that not being your first language
I am core C programmers for a decade now so i might be biased. I think - Learning C is a MUST. It forces you to closest to hardware programming (even if you are no long doing assembly). For example, it really make you think in terms of how computer uses memory, heap and stack. And of course, it will be hell on earth if you happen to try understanding Assembly before you try to learn C.
Stealing comment from @TikhonJelvis

I think not having any low-level courses would be a shame. –

However, having said that- understanding how machines work is still not everything. How to program is rather elementary thing you should learn before getting deep into how machines will interpret that - so in general, whenever C was being used as a first language. So using higher level language, something which gets you started more quickly and avoid some initial hickups might make you learn some other aspects
Also, after learning to do problem solving with programming, one can reasonably delve in to design and modeling aspect again C isn't really the most important language there. I think there is a great upswing in use of Perl, Python in many machine learning, web/data mining, information retrieval, bioinformatics class of applications (the top current research areas for CS folks over say topics like networking) where you are conceptually very higher up. They are replacing languages like Fortran rather than C.

A: Learning C is one of the most important aspects of any programmer.

That is, at best, highly subjective, and I, for one, completely disagree. I think it is a good thing that universities are teaching languages which are more relevant to 2012. I think that learning C is a waste of time.

A: Programming courses teach you about programming and Python is excellent for that. C is not as great to teach about general programming. Programming is not about understanding computers, it's about creating applications. The tools we use to create applications are constantly evolving and so should CS courses.
For teaching how the computers work, there are different courses. They can show examples of low level computing with ASM or C.
C is also great tool for embedded and low latency programming so if you have courses about those subjects, you can use C.
My answer is: students aren't being degraded. CS is being made more accessible and keeping up with the times.

A: If you only want to learn to write algorithms, I guess Python is OK. If you want to learn how the underlying computer works and, among other things, how
Python programs are executed, you need a more low-level language like C.
The question also seems to contain a hint to the idea that Python is a
more recent, up-to-date language and universities tend to update their
curricula to support current technology.
With respect to this, I think this is OK in principle, but universities should
not be too obsessed with using the latest technology for teaching because

*

*Universities should teach students the concepts of computer science so that they can think independently about programming languages and other tools. Universities should not prepare potential slaves who are just able to implement what they are told to using the most fashionable language of the moment.

*A language that might be very popular today, might be obsolete ten years from now: university should concentrate on basic stuff, not on teaching a particular technology in depth.

So, Python might be more useful and more concise for certain practical applications, but it does not cover certain basic concepts (like memory
management, efficient implementation of data structures, etc) that are covered
by C. Therefore, I think that C (or a more teaching-oriented language like Pascal) should be part of the curriculum of universities.


text:
Q: Haskell: Should I get "Stack space overflow" when constructing an IntMap from a list with a million values? My problem is that when using any of the Map implementations in Haskell that I always get a "Stack space overflow" when working with a million values.
What I'm trying to do is process a list of pairs. Each pair contains two Ints (not Integers, I failed miserably with them so I tried Ints instead). I want to go through each pair in the list and use the first Int as a key. For each unique key I want to build up a list of second elements where each of the second elements are in a pair that have the same first element. So what I want at the end is a "Map" from an Int to a list of Ints. Here's an example.
Given a list of pairs like this:
[(1,10),(2,11),(1,79),(3,99),(1,42),(3,18)]

I would like to end up with a "Map" like this:
{1 : [42,79,10], 2 : [11], 3 : [18,99]}

(I'm using a Python-like notation above to illustrate a "Map". I know it ain't Haskell. It's just there for illustrative purposes.)
So the first thing I tried was my own hand built version where I sorted the list of pairs of Ints and then went through the list building up a new list of pairs but this time the second element was a list. The first element is the key i.e. the unique Int values of the first element of each pair and the second element is a list of the second values of each original pair which have the key as the first element.
So given a list of pairs like this:
[(1,10),(2,11),(1,79),(3,99),(1,42),(3,18)]

I end up with a list of pairs like this:
[(1, [42,79,10], (2, [11]), (3, [18,99])]

This is easy to do. But there is one problem. The performance of the "sort" function on the original list (of 10 million pairs) is shockingly bad. I can generate the original list of pairs in less than a second. I can process the sorted list into my hand built map in less than a second. However, sorting the original list of pairs takes 40 seconds.
So I thought about using one of the built-in "Map" data structures in Haskell to do the job. The idea being I build my original list of pairs and then using standard Map functions to build a standard Map.
And that's where it all went pear-shaped. It works well on a list of 100,000 values but when I move to 1 million values, I get a "Stack space overflow" error.
So here's some example code that suffers from the problem. Please, please note that is not the actual code that I want to implement. It is just a very simplified version of code for which the same problem exists. I don't really want to separate a million consecutive numbers into odd and even partitions!!
import Data.IntMap.Strict(IntMap, empty, findWithDefault, insert, size)

power = 6

ns :: [Int]
ns = [1..10^power-1]

mod2 n = if odd n then 1 else 0

mod2Pairs = zip (map mod2 ns) ns

-- Takes a list of pairs and returns a Map where the key is the unique Int values
-- of the first element of each pair and the value is a list of the second values
-- of each pair which have the key as the first element.
-- e.g. makeMap [(1,10),(2,11),(1,79),(3,99),(1,42),(3,18)] =
--      1 -> [42,79,10], 2 -> [11], 3 -> [18,99]
makeMap :: [(Int,a)] -> IntMap [a]
makeMap pairs = makeMap' empty pairs
  where
    makeMap' m [] = m
    makeMap' m ((a, b):cs) = makeMap' m' cs
      where
        bs = findWithDefault [] a m
        m' = insert a (b:bs) m

mod2Map = makeMap mod2Pairs

main = do
  print $ "Yowzah"
  print $ "length mod2Pairs="++ (show $ length mod2Pairs)
  print $ "size mod2Map=" ++ (show $ size mod2Map)

When I run this, I get:
"Yowzah"
"length mod2Pairs=999999"
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize -RTS' to increase it.

From the above output, it should be clear that the stack space overflow happens when I try to do "makeMap mod2Pairs".
But to my naive eye all this seems to do is go through a list of pairs and for each pair lookup a key (the first element of each pair) and A) if it doesn't find a match return an empty list or B) if it does find a match, return the list that has previously been inserted. In either case it "cons"'s the second element of the pair to the "found" list and inserts that back into the Map with the same key.
(PS instead of findWithDefault, I've also tried lookup and handled the Just and Nothing using case but to no avail.)
I've had a look through the Haskell documentation on the various Map implementations and from the point of view of performance in terms of CPU and memory (especially stack memory), it seems that A) a strict implementation and B) one where the keys are Ints would be the best. I have also tried Data.Map and Data.Strict.Map and they also suffer from the same problem.
I am convinced the problem is with the "Map" implementation. Am I right? Why would I get a stack overflow error i.e. what is the Map implementation doing in the background that is causing a stack overflow? Is it making lots and lots of recursive calls behind the scenes?
Can anyone help explain what is going on and how to get around the problem?

A: I don't have an old enough GHC to check (this works just fine for me, and I don't have 7.6.3 as you do), but my guess would be that your makeMap' is too lazy. Probably this will fix it:
makeMap' m ((a, b):cs) = m `seq` makeMap' m' cs

Without it, you are building up a million-deep nested thunk, and deeply-nested thunks is the traditional way to cause stack overflows in Haskell.
Alternately, I would try just replacing the whole makeMap implementation with fromListWith:
makeMap pairs = fromListWith (++) [(k, [v]) | (k, v) <- pairs]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery checkbox All
    One
    Two
    three
My requirement is

*

*when check All it should check One , Two, Three also.

*When i uncheck All it should uncheck One , Two, Three also

*When all check boxes check and uncheck either one , two , three in that case "All" check box should uncheck.

*check / uncheck should ne toggling

Please help

A: $(function(){
    $("#all").click(function(){
        $("input:checkbox[name='checkGroup']").attr("checked",$(this).attr("checked"));
    });

    $("input:checkbox[name='checkGroup']:not('#all')").click ( function(){
        var totalCheckboxes = $("input:checkbox[name='checkGroup']:not('#all')").length;
        var checkedCheckboxes = $("input:checkbox[name='checkGroup']:not('#all'):checked").length;

        if ( totalCheckboxes === checkedCheckboxes )
        {
            $("#all").attr("checked" , true );
        }
        else
        {
            $("#all").attr("checked" , false );
        }
    });
});

Demo

A: What is your trying?
Let's try

Toggle 5ve

<form method="post" action="" style="margin:0px">
<input type="checkbox" name="a" value="1" id="" />
<input type="checkbox" name="b" value="2" id="" />
<input type="checkbox" name="c" value="3" id="" />
<input type="checkbox" name="d" value="4" id="" />
<input type="checkbox" name="e" value="5" id="" />
<input type="checkbox" name="f" value="5" id="" />
</form>

A: This solution uses a cb class selector on the "child" textboxes. Another solution would be to select all those that don't have an id=all. It compares the length of the set of checked child checkboxes with the length of the set of all child checkboxes to determine if all should be checked.

<input type="checkbox" name="checkGroup" id="all" value="0" />All
<input type="checkbox" name="checkGroup" id="one" class="cb" value="1" />One
<input type="checkbox" name="checkGroup" id="two" class="cb" value="2" />Two
<input type="checkbox" name="checkGroup" id="three" class="cb" value="3" />Three


text:
Q: How do I call a web service from javascript Say I have a web service http://www.example.com/webservice.pl?q=google which returns text "google.com". I need to call this web service (http://www.example.com/webservice.pl) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing.
What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated.

A: EDIT:
It has been a decade since I answered this question and we now have support for cross-domain XHR in the form of CORS.
For any modern app consider using fetch to make your requests. If you need support for older browsers you can add a polyfill.
Original answer:
Keep in mind that you cannot make requests across domains.  For example, if your page is on yourexample.com and the web service is on myexample.com you cannot make a request to it directly.
If you do need to make a request like this then you will need to set up a proxy on your server.  You would make a request to that proxy page, and it will retrieve the data from the web service and return it to your page.

A: Take a look at one of the many javascript libraries out there. I'd recommend jQuery, personally. Aside from all the fancy UI stuff they can do, it has really good cross-browser AJAX libraries.
$.get(
    "http://xyz.com/webservice.pl",
    { q : "google" },
    function(data) {
        alert(data);  // "google.com"
    }
);


text:
Q: Google Sheets API extreme latency I am experiencing a median latency of over 40s on google.apps.sheets.v4.SpreadsheetsService.GetValues function. I am reading single sheet of data with 250,000 cells (14 cols x 18,000 rows). I am well under the rate limits rarely doing more than a single call in 100s and more than 200 a day.
When downloaded as CSV, the file size is ~3MB (440KB zipped).
Now, I understand that reading 3MB of data might not be instant, but 40s is order of magnitude slower than I would expect. Especially given that simple manual download as CSV takes ~1s to complete.
Am I doing something wrong? Is there a way to get data through API faster?
Example of the code I am using
  async function load(id, range) {
    await sheetsApi.spreadsheets.values.get({
      spreadsheetId: id,
      range,
      valueRenderOption: 'UNFORMATTED_VALUE',
    })
  }

  await Promise.all([
    load(id1, 'Big'), // big 250k cells sheet
    load(id1, 'Small'), // small 1000 cells sheet
    load(id2, 'Big'), // another big 250k cells sheet
  ])

Playing further with profiling I am seeing following data:
[0] Loading id2:Big took 1644ms.    // Notice how this big sheet loaded really fast.
[0] Loading id1:Small took 26345ms. // Notice that this small sheet took 26 seconds.
[0] Loading id1:Big took 27274ms.
[0] Loading id1:Small took 859ms.
[0] Loading id2:Big took 1493ms.
[0] Loading id1:Big took 1610ms.
[0] Loading id1:Small took 865ms.
[0] Loading id2:Big took 1689ms.
[0] Loading id1:Big took 1835ms.

So it seems like some kind of undisclosed rate limiting or whatever. Sometimes it's really fast, sometimes it's extremely slow.

A: If it's feasible for your situation, could you download the entire sheet as a CSV file, or 3 of them, 1 per sheet.  It's probably a lot slower for the API to filter the data rows individually out into API call results and serialize them, rather than export the whole sheet(s) to a file.


text:
Q: How to Reformulate an Image Constraint in the Dual of a Quadratic Program with Nonconvex Constraints? I have the following nonconvex optimization problem, for which I want to formulate the dual:
$\mathcal{P}:\underset{x}{\text{min}} \quad x^\top A x + b^\top x \\
\quad \ \ \text{s.t.} \quad x\in\{0,1\}^n$
where $A$ is p.s.d. I am stuck on encoding both a psuedo-inverse and an image-constraint that pop up in the derivation of the dual problem in a way that looks convex/standard. Here are my steps:
The constraint can be rewritten as the $n$ nonlinear equalities
$x_i(x_i - 1) = 0, \quad \forall i$
With this, we write the Lagrangian
$\mathcal{L}(x,\mu) = x^\top (A + \text{diag} \ \mu)x + (b - \mu)^\top x $.
Let $\Omega(\mu) = (A + \text{diag} \ \mu)$ and $\beta(\mu) = b - \mu$ for notational convenience. Note that these are affine mappings on $\mu$, in case it comes in handy later. Finding the $\tilde{x}$ which minimizes $\mathcal{L}$ gives:
$\tilde{x} = \underset{x}{\text{arginf}} \ \mathcal{L}(x,\mu) = \begin{cases} -2\Omega(\mu)^\dagger \beta(\mu), & \Omega(\mu) \succeq 0 \ \text{and} \ \beta(\mu)\in\text{Im} \ \Omega(\mu) \\
\text{unbounded}, & \text{o.w.} \end{cases}$
where $^\dagger$ indicates the Moore-Penrose pseudo-inverse, see e.g. Boyd's book $\S$A.5.4 or other Boyd reference, $\S$2.2. Making substitutions, I have the dual problem:
$\mathcal{D}: \underset{\mu}{\text{max}} \quad -\beta(\mu)^\top \Omega(\mu)^\dagger \beta(\mu) \\
\quad \ \ \text{s.t.} \quad \Omega(\mu) \succeq 0 \ \text{and} \ \beta(\mu) \in \text{Im} \ \Omega(\mu)$
In the second Boyd reference above, he uses a Schur complement reformulation for a similar problem, but with inequality constraints. I don't directly see how that translates here. Additionally, the image constraint at first glance seems to be nonconvex to me, since it looks bilinear in $\mu$. So, my questions are:
(1) Is the cost of $\mathcal{D}$ concave, as it should be? If so, is there an easy way to reformulate this to more directly see it?
(2) How can the Im constraint be reformulated in an obviously convex way?

A: Ok, I figured it out, and it's actually pretty straightforward based on Schur complement.
Introduce $\Delta \leq -\beta(\mu) Q(\mu)^\dagger \beta(\mu)$. Let the cost be to maximize $\Delta$, rearrange terms, and apply Schur complement to get a standard SDP in $(\mu, \Delta)$:
\begin{equation}
\mathcal{D}: \underset{\mu,\Delta}{\text{max}} \quad \Delta \\
\quad \quad \text{subject to} \quad \begin{bmatrix} Q(\mu) & \beta(\mu) \\
\beta(\mu)^\top & -\Delta \end{bmatrix} \succeq 0.
\end{equation}
Easy peasy!


text:
Q: Find the function $u: \mathbb R ^2\to \mathbb R^2$ that holds the property $d^3u(x,y)=0$ Find the function $u: \mathbb R ^2\to \mathbb R^2$ that holds the property $d^3u(x,y)=0$
I really would like some help with this problem because I don't even know where to start.
I thought taking the formula
$$d^3u=\frac{\partial ^3u(x,y)}{\partial x^3}dx^3+3\frac{\partial ^3u(x,y)}{\partial x^2 \partial y}dx^2dy+3\frac{\partial ^3u(x,y)}{\partial x \partial y^2}dxdy^2+\frac{\partial ^3u(x,y)}{\partial y^3}dy^3$$
but I don't know where to go from here. I would appreciate some help

A: Looking at your formula one can say the following: $d^3u(x,y)=0$ iff all third partial derivatives $$u_{xxx},\quad u_{xxy},\quad u_{xyy},\quad u_{yyy}$$ vanish identically. This is the case if all second partial derivatives
$$u_{xx},\quad u_{xy},\quad u_{yy}$$
are constants, etcetera. It follows that the most general $u:\>{\mathbb R}^2\to{\mathbb R}^2$ with $d^3u=0$ has the form
$$u(x,y)=\bigl(f(x,y),g(x,y)\bigr)$$
with $f$ and $g$ polynomials of total degree $\leq2$ in $x$ and $y$.

A: By dividing $d^3 u(x,y)$ over $(dx)^m(dy)^n$ where $m+n=3$ and $m,n\in\{0,1,2,3\}$, we obtain$${d^3 u(x,y)\over dx^3}=0\\{d^3 u(x,y)\over dx^2dy}=0\\{d^3 u(x,y)\over dxdy^2}=0\\{d^3 u(x,y)\over dy^3}=0$$which yields to the general solution$$u(x,y)=a_1x^2+a_2xy+a_3y^2+a_4x+a_5y+a_6$$


text:
Q: Display upcoming birthdays in Wordpress with ACF - exclude YEAR when query the date picker custom field One of the fields for my custom post type is the member's birthdate, including the year.
However in order to display upcoming birthday, I need to exclude the year form my query, and just use month and day. I was hoping to format the current date and the custom field date to mmdd so I can simply compare them.
The below however take the year in consideration and thus result in 12 March 1963 showing before 18 February 1965 ( simply due to the year )
function tsum_home_birthday_widget() {
// ACF Date Picker Input: j F M   Also tried nd
// ACF Date Picker Output: j F M  Also tried nd

//$currentdate = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
//$currentdate = date("nd",mktime(0,0,0,date("m"),date("d"),date("Y")));
$currentdate = date('nd');
$birthDate = get_field('breeder_birthday', false, false);

$meta_query = array (
'key' => 'breeder_birthday',
  // 'key' => $birthDate, // try to use variable so I can chnage the format of the date
'compare' => '<=', // chnage to >= once I know how to exclude the year.
'value' => $currentdate,
'type' => 'DATE',
);

$args = array(
'post_type'   => 'breeders',
'meta_key'  => 'breeder_birthday',
//'meta_key'  => $birthDate, // try to use variable so I can chnage the format of the date
'orderby' => 'meta_value_num',
'orderby' => 'meta_value',
'order'   => 'ASC',
'posts_per_page'  => '5',
'meta_query' => $meta_query,
);

$wp_query = new WP_Query( $args );
while( $wp_query->have_posts() )
{
$wp_query->the_post();

?>

<?php if( get_field('breeder_contact') ): ?>
    <?php the_field( 'breeder_contact' ); ?>
<?php endif; ?>

<?php if( get_field('breeder_birthday') ): ?>
    <?php
        $bbday = get_field('breeder_birthday', false, false);
        $bbday = new DateTime($bbday);  ?>
    <?php echo $bbday->format('d F Y'); ?>
<?php endif; ?>

<?php
}
wp_reset_query();
}
add_shortcode('Birthdays', 'tsum_home_birthday_widget');


text:
Q: When installing MYSQL do I have to have MS Excel and Visual Studio I'm new to MYSQL and following video tutorials. I don't own MS Office, why am I forced to instal MYSQL for excel and Visual studio? Can I skip those 2 parts?

A: The MySQL Installer for Windows enables the installation of most all APIs by default, such as those, but you do not have to install them. Simply press "Next" and continue with the installation process. The documentation refers to other prerequisites, such as "Microsoft Visual C++ 2013 Runtime", so you'll need that for MySQL Workbench (although you probably already have it installed). Basically, install the prerequisites for the applications you want to install, and skip the others.


text:
Q: Xamarin.Forms Graphical issues - DatePicker text is missing, Switch background is missing I am creating Xamarin.Forms application (Android and iOS) and I am experiencing graphical issues with DatePicker, Switch and other controls.

I have tried to build new sample application (which comes with Visual Studio) on several Android devices and the issue persists.
I am not experiencing this issues on Andorid simulator though.
Any help appreciated. Thanks

A: This is because of the theme of the device. (Dark / Light). You can override the colors by adding these to the style.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MainTheme" parent="MainTheme.Base">
    </style>
    <!-- Base theme applied no matter what API -->
    <style name="MainTheme.Base" parent="Theme.AppCompat.DayNight">
        <!--If you are using revision 22.1 please use just windowNoTitle. Without android:-->
        <item name="windowNoTitle">true</item>
        <!--We will be using the toolbar so no need to show ActionBar-->
        <item name="windowActionBar">false</item>
        <!-- Set theme colors from https://aka.ms/material-colors -->
        <!-- colorPrimary is used for the default action bar background -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <!-- colorPrimaryDark is used for the status bar -->
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
        <item name="colorAccent">@color/colorAccent</item>
        <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight and colorSwitchThumbNormal. -->
        <item name="windowActionModeOverlay">true</item>
        <item name="android:statusBarColor">#000000</item>
        <item name="android:datePickerDialogTheme">@style/AppCompatDialogStyle</item>
    </style>
    <style name="AppCompatDialogStyle" parent="Theme.AppCompat.Light.Dialog">
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>


text:
Q: Problem connecting to a server in a Java project I am working right now on improving a Java project built using the IntelliJ IDEA, and this project requires connecting to a local database. The problem is that I can't run it at all because of an exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Le pilote n'a pas pu établir de connexion sécurisée au serveur SQL Server à l'aide du chiffrement SSL (Secure Sockets Layer). Error: « The server selected protocol version TLS10 is not accepted by client preferences [TLS12] ». ClientConnectionId:c1722f06-2f8f-435b-953d-67697967d9a5

I am guessing it might be linked to IntelliJ settings in my computer because my co-worker copied the project too and it worked perfectly for him.


text:
Q: Why does my Sqlite database get really slow when one table gets a lot of records? I have an Sqlite database on Android and if I put 2000 records in one table all the other tables get really slow.
With 2000 records in the one table I can run a 'SELECT COUNT(*)' on a table with 0 records and it can take anywhere from 5 to 30 seconds.

A: There can be many reasons for that. The usual reasons are:

*

*Poorly written query

*Not using a primary key, assuming one even exists on the table

*Poorly designed data model (table structure)

*Lack of indexes

IMO, your case may be lack of indexes. Check if you have indexed your tables/rows.

A: "SELECT COUNT( * )", the char ' * ' need database to extract every field when sql execute.
As an additional suggest, you can use primary key in the " count( < your primary key > ) ".


text: Q: Play framework 2.2.2 project link to see/download sample application other than plays officials project i m new to play framework and web development, can any one send me link of play framework app that contains drop down list,file upload,calender and any other code(java).thank you


text:
Q: Dynamic Data in Eksternal CSS I have a file eksternal css "style.css"
<link rel="stylesheet" type="text/css" id="theme" href="css/style.css"/>

this part code is
.x-navigation > li.xn-logo > a:first-child {
  font-size: 0px;
  text-indent: -9999px;
  background: url("../img/logo.png") top center no-repeat #68A9CF;
  padding: 0px;
  border-bottom: 0px;
  color: #FFF;
  height: 60px;
  background-size: 180px 50px;
}

i want to change logo, but how to add dynamic data php in eksternal css,
i try like this, but doesn't work :(
<?php
include "connection.php";
$dataweb = mysqli_query($con,"select logo from web");
$web = mysqli_feth_object($dataweb);
?>

.x-navigation > li.xn-logo > a:first-child {
  font-size: 0px;
  text-indent: -9999px;
  background: url("../img/<?php echo $web->logo ?>") top center no-repeat #68A9CF;
  padding: 0px;
  border-bottom: 0px;
  color: #FFF;
  height: 60px;
  background-size: 180px 50px;
}

Have a solution ??
Help me thank's

A: Php doesn't work in a .css file. It only works in .php file. So you have to do the following in the .php file within the head tag
<style>
background: url("../img/<?php echo $web->logo ?>") top center no-repeat #68A9CF;
</style>

and please use the  code at the first of the file to initiate the webroot.
<?php
include "connection.php";
$dataweb = mysqli_query($con,"select logo from web");
$web = mysqli_feth_object($dataweb);
?>

It will replace the logo for you.


text:
Q: Silex app->redirect does not match routes Let my application run on localhost, the path is: localhost/silex/web/index.php, defined routes as in the code below, I'd expect visiting localhost/silex/web/index.php/redirect redirects me to localhost/silex/web/index.php/foo and displays 'foo'. Instead it redirects me to localhost/foo.
I am new to Silex and maybe I got it all wrong. Could someone explain where is the problem? Is it correct behavior and it should redirect for absolute paths? Thanks.
<?php

require_once __DIR__.'/../vendor/autoload.php';

use Symfony\Component\HttpFoundation\Response;

$app = new Silex\Application();

$app['debug'] = true;

$app->get('/foo', function() {
    return new Response('foo');
});

$app->get('/redirect', function() use ($app) {
    return $app->redirect('/foo');
});

$app->run();

A: For internal redirects, which does not change the requested URL, you can also use a sub-request:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

$app->get('/redirect', function() use ($app) {
   $subRequest = Request::create('/foo');
   return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
});

See also Making sub-Requests.

A: The redirect url expects an url to redirect to, not an in-app route. Try it this way:
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());

$app->get('/foo', function() {
    return new Response('foo');
})->bind("foo"); // this is the route name

$app->get('/redirect', function() use ($app) {
    return $app->redirect($app["url_generator"]->generate("foo"));
});

A: Up to "silex/silex": ">= 2.0", a native trait allow you to generate an URL based on the route name.
You can replace :
$app['url_generator']->generate('my-route-name');

By :
$app->path('my-route-name');

Then use it to redirect :
$app->redirect($app->path('my-route-name'));

Another possibility is to create a custom trait to directly redirect with a route name :
namespace Acme;

trait RedirectToRouteTrait
{
    public function redirectToRoute($routeName, $parameters = [], $status = 302, $headers = [])
    {
        return $this->redirect($this->path($routeName, $parameters), $status, $headers);
    }
}

Add the trait to your application definition :
use Silex\Application as BaseApplication;

class Application extends BaseApplication
{
    use Acme\RedirectToRouteTrait;
}

Then use it wherever you need it :
$app->redirectToRoute('my-route-name');


text:
Q: Append to a pickle file without deleting I've tried to write to a file using binary mode with the pickle module. This is an example:
    import pickle
    file = open("file.txt","wb")
    dict = {"a":"b","c":"d"}
    pickle.dump(dict, file)
    file.close()

But this method deletes the other dicts written before. How can I write without deleting the other things in the file?

A: You need to append to the original file, but first unpickle the contents (I assume the original file had pickled content).
What you were doing is simply overwriting the existing file with a new pickled object
import pickle

#create the initial file for test purposes only
obj = {"a":"b","c":"d"}
with open("file.txt","wb") as f:
    pickle.dump(obj, f)

#reopen and unpickle the pickled content and read to obj
with open("file.txt","rb") as f:
    obj = pickle.load(f)
    print(obj)

#add to the dictionary object
obj["newa"]="newb"
obj["newc"]="newd"

with open("file.txt","wb") as f:
    pickle.dump(obj, f)

#reopen and unpickle the pickled content and read to obj
with open("file.txt","rb") as f:
    obj = pickle.load(f)
    print(obj)

A: You can concatenate pickled objects in a file, so it's not necessary to read the file in and rewrite it. You simply need to append to the file, rather than overwriting it.
Replace:
file = open("file.txt","wb")

With:
file = open("file.txt","ab")

For more information on the file modes available and what they do, see the documentation.
And remember that you'll need multiple pickle.load()s to unpickle the data.


text:
Q: Why is my ProxyPass and uWSGI not connecting? I am trying to get a python environment live for a Django project and it's fighting me. I have installed mod_proxy_uwsgi through EasyApache4 (mod_proxy was already on). I have added the following include in the Apache include editor under pre-virtual host (Versioned):
include /etc/apache2/conf.d/userdata/std/2_4/user/domain/proxy.conf

with the following content:
ProxyPreserveHost On
ProxyPass "/"  "unix://localhost/var/run/swerth_django.sock"
ProxyPassReverse "/" "unix://localhost/var/run/swerth_django.sock"

I have used YUM installer to install uWSGI and run using a .ini file (command:uwsgi --ini php.ini) with the following content which is executing fine so far (no error messages):
[uwsgi]
chdir=/home/swerth/public_html/mysite
module=mysite.wsgi:application
env=DJANGO_SETTINGS_MODULE=mysite.settings
master=True
pidfile=/tmp/project-master.pid
socket=127.0.0.1:49152
processes=5
harakiri=20
post-buffering=1
max-requests=5000
vacuum=True
home=/home/swerth/public_html/Swerth.VirtualEnv

Despite all this, it's still not working. My Django project still isn't serving. I have a sneaky suspicion that there's something I don't understand about these systems and reverse proxying. Is there something I'm missing or messing up?

A: Ok, so turns out I was adding my Include function under the versioned part of the includes editor and it needed to be added under the global one because of how the includes editor adds the files to the main httpd.conf file (versioned wasn't being included into the main httpd.conf for some reason)


text:
Q: Find the area lying inside the circle $r=a \sin \theta$ and outside the cardioid $r=a(1-\cos \theta)$. I calculated this area to be:
$$\int_{0}^{\pi/2} \int_{a(1- \cos\theta)}^{a \sin\theta} r \  \mathrm dr\ \mathrm d \theta=a^2\int_{0}^{\pi/2} \cos\theta - \cos^2\theta \  \mathrm d \theta= a^2(1-\frac{\pi}{4}).$$
Just want to verify that my formulation and answer are correct since I do not have the correct answer myself.


text:
Q: ValueError at /post/ No JSON object could be decoded This is my json:
{
  "documents": [
                 {
                 "score": 0.5,
                 "id": "1"
                  }
               ],
   "errors":   []
}

I want to know how can I fetch 'score' without converting it into the dictionary?Because when I try to use json.loads it give me the following error:
ValueError at /post/
No JSON object could be decoded

This is the code which I am using.
def GetSentiment(documents):
    "Gets the sentiments for a set of documents and returns the
    information."
    headers = {'Ocp-Apim-Subscription-Key': accessKey}
    conn = httplib.HTTPSConnection(uri)
    body = json.dumps(documents)
    conn.request("POST", path, body, headers)
    response = conn.getresponse()
    return response.read()

documents = {'documents': [
                        {'id': '1', 'language': 'en', 'text': caption},
             ]}
result = GetSentiment(documents)
resp_dict = json.loads(result)
print resp_dict
score = resp_dict["documents"][0]["score"]
return score

A: I've looked at your JSON conversion code and it is fine :
>>> result = '{"documents": [{"score": 0.5,"id": "1"}],"errors": []}'
>>> import json
>>> resp_dict = json.loads(result)
>>> score = resp_dict["documents"][0]["score"]
>>> print score
0.5 # success !

So your issue must be with the result object, which is not what you suggested. Something must be wrong with your GetSentiment function.
What does your print result line produce ? Also, have you tried using something like requests to make your life easier ?


text:
Q: A question on topology Is there is a real differentiable function for which the graph of its derivative function is not topologically connected? Thanks a lot.

A: Every derivative has a connected graph. This follows from the more general fact that the graph of any Baire $1$ Darboux function is connected, which was first proved in [1] (see also Theorem 4.1 on p. 99 in [2], AND Theorem 7 at the top of p. 130 in [3], AND Theorem B on p. 182 in [4]). The actual observation that, since derivatives are Baire $1$ Darboux functions (Darboux himself showed "Darboux" in 1875 and Baire showed "Baire $1$" in his 1899 Ph.D. dissertation), it follows that graphs of derivatives are topologically connected in the plane, was first made in [5].
[1] Kazimierz [Casimir] Kuratowski and Wacław Sierpiński, Les fonctions de classe $1$ et les ensembles connexes punctiformes [On functions of class $1$ and connected punctiforme sets], Fundamenta Mathematicae 3 (1922), 303-313.
[2] Andrew Michael Bruckner and Jack Gary Ceder, Darboux continuity, Jahresbericht der Deutschen Mathematiker-Vereinigung 67 (1965), 93-117.
[3] Kazimierz Kuratowski, Topology, Volume II, Academic Press, 1968.
[4] Jack Gary Cedar and Terrance Laverne Pearson, A survey of Darboux Baire $1$ functions, Real Analysis Exchange 9 #1 (1983-1984), 179-194.
[5] Bronisław Knaster and Kazimierz [Casimir] Kuratowski, Sur quelques propriétés topologiques des fonctions dérivées [On some topological properties of derivative functions], Rendiconti del Circolo Matematico di Palermo (1) 49 (1925), 382-386.


text:
Q: How to regenerate new pem file using old pem file
I am having my old pem file but I want to generate new pem file.

A: I think what you want to do is change the key pair used to access an EC2 instance.
To generate a new private key, go to the EC2 console, select "Key Pairs" and then select "Create New Key Pair".
You can follow this Amazon EC2 Tutorial for how to use the new key pair with your instance; even though you haven't lost your key pair, the process is the same.
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#replacing-lost-key-pair


text:
Q: Java program not reading environment variable set from command line In my java program I am trying to use few native libraries. Everything works fine if I use my intelij IDE to run code, however if I ran the code from command line (from terminal) it gives me library linkage error
I am using Mac OS Sierra and Java 1.8
Following is my pom.xml looks like.
<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
                <mainClass>${start-class}</mainClass>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.21.0</version>
            <dependencies>
                <dependency>
                    <groupId>org.apache.maven.surefire</groupId>
                    <artifactId>surefire-junit4</artifactId>
                    <version>2.21.0</version>
                </dependency>
            </dependencies>
            <configuration>
                <forkMode>once</forkMode>
                <argLine>-Djava.library.path=/Applications/CPLEX_Studio_Community128/opl/bin/x86-64_osx/</argLine>
                <environmentVariables>
                    <DYLD_LIBRARY_PATH>/Applications/CPLEX_Studio_Community128/opl/bin/x86-64_osx/</DYLD_LIBRARY_PATH>
                </environmentVariables>
            </configuration>

        </plugin>

    </plugins>
</build>

Java code
   @Test
    public void testCPLX(){
        System.out.println("DYLD_LIBRARY_PATH env: " +System.getenv("DYLD_LIBRARY_PATH"));
        IloOplFactory oplF = new IloOplFactory();
    }

if I run this code form InteliJ IDE it runs and prints the value of DYLD_LIBRARY_PATH as /Applications/CPLEX_Studio_Community128/opl/bin/x86-64_osx/
However if run the program using following command.

mvn clean test -Dtest=test.java.cplexTests.TestCplex

I get null for DYLD_LIBRARY_PATH and so the library linkage error in next step.
I tried setting DYLD_LIBRARY_PATH path before running mvn command however it's not helping. I tried setting DYLD_LIBRARY_PATH as part of mvn command, it's not helping either.
First Try

export DYLD_LIBRARY_PATH=/Applications/CPLEX_Studio_Community128/opl/bin/x86-64_osx/
mvn clean test -Dtest=test.java.cplexTests.TestCplex

Second Try

mvn -DDYLD_LIBRARY_PATH=/Applications/CPLEX_Studio_Community128/opl/bin/x86-64_osx/ -Djava.library.path=/Applications/CPLEX_Studio_Community128/opl/bin/x86-64_osx/ -Dtest=test.java.cplexTests.TestCplex clean test

If I remove environmentVariables section from maven I get same error when I run through InteliJ Idea.


text:
Q: Not able to see the picture, just shows a black background  public class Board extends JPanel implements ActionListener {
 private Player player;
 private Timer timer;
 public ArrayList<Enemy> enemyList;
 public ArrayList<Bullet> bulletList;
 private Random randomNumber;
 public int WIDTH;
 public int HEIGHT;
 public Image plane;
 public Image enemyimage;
 private int x,y;
 private final int DELAY = 25;
 private final int B_WIDTH = 300;
 private final int B_HEIGHT = 300;
 private final int ICRAFT_X = 40;
 private final int ICRAFT_Y = 60;

public Board(){
     initBoard();
}
public void initBoard(){
    addKeyListener(new TAdapter());
    setBackground(Color.BLACK);
    setFocusable(true);
    setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
    player = new Player();
    loadImage();
    timer = new Timer(DELAY, this);
    timer.start();
}

public void loadImage(){
    ImageIcon ii = new ImageIcon("src/resources/planeimage.png");
    plane = ii.getImage();
}

@Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        doDrawing(g);
    }

public void doDrawing(Graphics g){
    Graphics2D g2d = (Graphics2D) g;

    g2d.drawImage(player.getImage(),player.getX(),player.getY(),this);

    ArrayList<Bullet> bulletList = player.getBullets();

    for (Bullet bullet : bulletList){
        g2d.drawImage(bullet.getImage(),bullet.getX(),bullet.getY(),this);
    }
}

@Override
    public void actionPerformed(ActionEvent e){
        updateBullets();
        updatePlayer();
        repaint();
    }

public void updateBullets() {

    for (int i = 0; i < bulletList.size(); i++) {

        Bullet bullet = bulletList.get(i);

        if (bullet.isVisible()) {

            bullet.move();
        } else {

            bulletList.remove(i);
        }
    }
}

public void updatePlayer(){
    player.move();
}

    private class TAdapter extends KeyAdapter {

    @Override
    public void keyReleased(KeyEvent e) {
        player.keyReleased(e);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        player.keyPressed(e);
    }
    }

This is the player class which extends a vehicle class. Player constructor is being called in the board class and i guess, the problem lies their.
public class Player extends Vehicle{
 public ArrayList<Bullet> bulletList;

 public Player(){
     super();
     initPlayer();
 }

 public void initPlayer(){
     bulletList = new ArrayList<>();
     loadImage("src/resources/planeimage.png");
     getImageDimensions();
 }

@Override
 public void move(){
     x += dx;
     y += dy;
 }

public ArrayList<Bullet> getBullets(){
     return bulletList;
 }

public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_SPACE) {
        fire();
    }

    if (key == KeyEvent.VK_LEFT) {
        dx = -1;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 1;
    }

    if (key == KeyEvent.VK_UP) {
        dy = -1;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 1;
    }
}

@Override
     public void fire() {
        bulletList.add(new Bullet(x + w, y + h / 2));
    }

 public void keyReleased(KeyEvent e){
    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = 0;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 0;
    }

    if (key == KeyEvent.VK_UP) {
        dy = 0;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 0;
    }
 }
}

public class Application extends JFrame {
 public Application() {

    initUI();
}

private void initUI() {

    add(new Board());

    setSize(1024, 768);

    setTitle("Application");
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
       EventQueue.invokeLater(() -> {

               Application ex = new Application();
               ex.setVisible(true);
    });
}

}
Application class is the main class. Board class has all the code. When i run the program, only the black background is being shown, not the images. Why is that so, what am i doing wrong. Thank you.


text:
Q: String Split to String Array without seperator Code:
string animals = "cat98dog75";

What i try to achieve :

string a = "cat98";
string b = "dog75";

Question :
How do i split the string using some range delimiter?
example :
animals.split();

A: I suggest matching with a help of regular expressions:
  using System.Text.RegularExpressions;
  ...

  string animals = "cat98dog75";

  string[] items = Regex
    .Matches(animals, "[a-zA-Z]+[0-9]*")
    .OfType<Match>()
    .Select(match => match.Value)
    .ToArray();

  string a = items[0];
  string b = items[1];

  Concole.Write(string.Join(", ", items));

Outcome:
  cat98, dog75

In case you want to split the initial string by equal size chunks:
  int size = 5;

  string[] items = Enumerable
    .Range(0, animals.Length / size + (animals.Length % size > 0 ? 1 : 0))
    .Select(index => (index + 1) * size <= animals.Length
       ? animals.Substring(index * size, size)
       : animals.Substring(index * size))
    .ToArray();

  string a = items[0];
  string b = items[1];

A: This might do the trick for you
string animals = "cat98dog75";
string[] DiffAnimals = Regex.Split(animals, "(?<=[0-9]{2})")
                            .Where(s => s != String.Empty) //Just to Remove Empty Entries.
                            .ToArray();

A: If you want to split the name of the animal and number, try following..
I know its too long....
private static void SplitChars()
    {
        string animals = "cat98dog75";
        Dictionary<string, string> dMyobject = new Dictionary<string, string>();
        string sType = "",sCount = "";
        bool bLastOneWasNum = false;
        foreach (var item in animals.ToCharArray())
        {

            if (char.IsLetter(item))
            {
                if (bLastOneWasNum)
                {
                    dMyobject.Add(sType, sCount);
                    sType = ""; sCount = "";
                    bLastOneWasNum = false;
                }
                sType = sType + item;
            }
            else if (char.IsNumber(item))
            {
                bLastOneWasNum = true;
                sCount = sCount + item;
            }
        }
        dMyobject.Add(sType, sCount);
        foreach (var item in dMyobject)
        {
            Console.WriteLine(item.Key + "- " + item.Value);
        }
    }

You will get output as
cat - 98
dog - 75
Basically, you are getting type and numbers so if you want to use the count, you don't need to split again...


text:
Q: Permission Denied even after granting the Storage Permission I have added every thing required to download files to local storage still I'm getting this error

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
FileSystemException: Creation failed, path =
'/storage/emulated/0/uth_content' (OS Error: Operation not permitted,
errno = 1)

In Manifest
<uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
   <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>

  android:requestLegacyExternalStorage="true"
  android:hardwareAccelerated="true"

<application
    android:requestLegacyExternalStorage="true" >

In pubspec.yaml
permission_handler: ^6.1.1
My Dart File
@override
  Future<int> downloadZipFile() async{
     Directory extStorage = await _externalDataSource.GetExtStoragePath();
     if(extStorage !=null) {
         var response =  await _apiDataSource.downloadZipContent(extStorage.path);
         File zipfile = await response.zipFile;
         debugPrint("Downloaded file :" + zipfile.path + "Exist: " + zipfile.existsSync().toString());
         return response.statusCode;
       }
     else{
       debugPrint("Path is empty");
       createFolder("uth_content");
     }

  }

  Future<String> createFolder(String cow) async {
    final folderName = cow;
    final path = Directory("/storage/emulated/0/$folderName");
    var status = await Permission.storage.status;
    if (!status.isGranted) {
      await Permission.storage.request();
    }
    if ((await path.exists())) {
      return path.path;
    } else {
      path.create();
      return path.path;
    }
  }

How can I ensure that the folder is created, my android api is 30

A: You are missing this permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

To get the permission use
if (await Permission.manageExternalStorage.request().isGranted) {...}

NOTE: This permission is considered pretty risky so play store will reject your app unless it's your app's core functionality.
This is what google says

Core functionality is defined as the main purpose of the app.  Without
this core functionality, the app is "broken" or rendered unusable. The
core functionality, as well as any core features that comprise this
core functionality, must all be prominently documented and promoted in
the app's description.

And if you are planning to create a file in an external directory and you are not able to find it, it's because you'd have to tell the device to refresh for the files. So I'd recommend using this package and passing your newly created file path to it or if you wanna do it manually with kotlin here's the code
    private fun broadcastFileUpdate(path: String) {
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(File(path))))
        println("updated!")
    }


text:
Q: How to custom stylesheet QToolTip I'am using Qt4.8 to create a pushbutton,and then I using setStyleSheet function to set style for this button and tooltip. But this code only applied for button and tooltip is doesn't work.
This is my code
QPushButton *status_label;

this->

cellGUI.status_label->setStyleSheet(QString::fromUtf8("QPushButton
  {color:#E6E6E6;font-weight:bolder;font-family:tahoma;font-size:6px;background-color:rgb(255,
  153, 0)} QPushButton::QToolTip
  {color:#2E2E2E;background-color:#CCCCCC;border:none}"));

Please help me.

A: You need add style sheet for QToolTip. Ex.:
QString style = QString(
    "QPushButton {"
    // StyleSheet for your push button
    "    background: blue;"
    "}"
    "QToolTip {"
    // StyleSheet for tool tip
    "    background: red;"
    "}"
    );

this->cellGUI.status_label->setStyleSheet(style);


text:
Q: Pass type to generic method determined by Type object I have generic method of an object that I want to invoke. But I have no clue of T in that moment, all I know is type of T which is set to a property of the object.
public calass SomeClass{

    public Type SomeType { get; set; }

    public void SomeMethod<T>(){

    }
}

...
var instance = new SomeClass();

...
Is it possible to do something like this?
instance.SomeMethod<SomeType>();

A: Yes, you can call it using Reflection:
var method = instance.GetType().GetMethod("SomeMethod")
             .MakeGenericMethod(instance.SomeType);

method.Invoke(instance);

Also note that SomeType is the name of your property, not the type of your property.You need to specify the type when you want to call a generic method.

A: You can add the following check in SomeMethod<T>:
if (!SomeType.IsAssignableFrom(typeof(T))) throw new Exception("Expecting type stored in SomeType.");

Or I would change the class to templated:
public class SomeClass<T>
{
    public Type InstanceType { get { return typeof(T); } }

    public void SomeMethod<T> () { }
}


text:
Q: body = 'cmd=' + urllib_parse.quote_plus(unicode(verb).encode('utf-8')) returns "name 'unicode' is not defined" When I run the following python code on Python 3.4
# -*- coding: utf-8 -*-
import unittest, time, re
from selenium.selenium import selenium

class google(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*chrome", "https://www.google.com/")
        self.selenium.start()

    def test_google(self):
        sel = self.selenium
        sel.open("/?gws_rd=ssl")
        sel.type("id=gbqfq", "")
        sel.type("id=gbqfq", "test")

    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

I have the error name 'unicode' is not defined:
======================================================================
ERROR: test_google (__main__.google)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "google.py", line 11, in setUp
    self.selenium.start()
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/selenium.py", line 201, in start
    result = self.get_string("getNewBrowserSession", start_args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/selenium.py", line 236, in get_string
    result = self.do_command(verb, args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/selenium.py", line 215, in do_command
    body = 'cmd=' + urllib_parse.quote_plus(unicode(verb).encode('utf-8'))
NameError: name 'unicode' is not defined

----------------------------------------------------------------------

What's wrong? Is there a way to workaround it?

A: Exactly as it says, unicode is no longer a built-in in 3.x - instead, the str type describes a Unicode string.
You should not be getting this message, because it's occurring within the Selenium code. This indicates that you have installed Selenium improperly - you have the 2.x code but are trying to use it from 3.x.
A quick check of the documentation suggests that 3.x is supported by Selenium - but you'll need to uninstall and reinstall it, and make sure you get it right this time.


text:
Q: Translate book-length text to mp3 audio I have a 70 chapter book that I need to have read aloud to me. My sight is failing after 45 years. I need book.txt translated to book.mp3.

A: First, run the following commands to install the dependencies:
sudo apt update
sudo apt install lame espeak

Next, run the following commands to convert the file from text to wave to mp3:
espeak -s 155 -a 200 -f book.txt -w book.wav
lame -V2 book.wav book.mp3

If you don't want the wav file you can delete the file.
The espeak command options set the speed of words per minute to 155 and the amplitude to 200.
Use espeak --help for more options.

A: If you have a dual boot, try using Balabolka .. Or borrow a friend's computer.
The official website (be careful) is http://www.cross-plus-a.com/balabolka.htm
Balabolka does work in Wine but it is 32bit so follow the instructions.
I think I used this webpage to follow the directions..
https://www.reddit.com/r/linux/comments/6z41qb/my_text_to_speech_tts_solution_wine_microsoft/
The content from that page is:
The Solution. It was surprisingly simple. Download the 32bit version of SpeechPlatformRuntime.msi from https://www.microsoft.com/en-us/download/details.aspx?id=27225 and MSSpeech_TTS_en-US_ZiraPro.msi from https://www.microsoft.com/en-us/download/details.aspx?id=27224 this should work with the other voices as well.
$export WINEARCH=win32
$export WINPREFIX=~/.wine32
$winetricks msxml3
$wine msiexec /i SpeechPlatformRuntime.msi
$wine msiexec /i MSSpeech_TTS_en-US_ZiraPro.msi

After that you should be able to use any windows tts program that uses Microsoft Speech Platform v11. I use Balabolka's Command Line Utility http://www.cross-plus-a.com/bconsole.htm it's a simple console app and doesn't require any extra dependencies.

A: There are many online services that let you convert a TXT file to MP3.
for example:
https://onlineconvertfree.com/convert-format/txt-to-mp3/
There are many others.
If you want to be able to do this offline, you can write a simple python sript, see this discussion:
https://stackoverflow.com/questions/19683282/how-can-i-convert-a-text-file-to-audio-mp3-using-ffmpeg-on-ubuntu-11-04


text:
Q: Regex is not matching all occurrences I am trying to match all occurrences  <% anything %> inside a template literal.
My regex setup looks like this.
process(template : string , data: Object) {
    let re = /<%([^%>]+)?%>/g, match;
    while (match = re.exec(template)) {
        template = template.replace(match[0], data[match[1]]);
    }
    return template;
}

if my template looks like this
`

        <%ENTRY_NUMBER%>
        <%NAME%> , <%CLASS%> , <%GENDER%> , <%AGE%>

`

it will match the first occurrence just fine then keep picking the alternate occurrences. if there is one match inside a html tag it works fine but when i use multiples like in second span element it misses alternate occurrences. I think it has something to do with < and >.
When I separate those occurrences with <> instead of comma like below it works fine.
<%NAME%> <> <%CLASS%> <> <%GENDER%> <> <%AGE%>

The result it like this
 john <> biology <> male <> 17

I have examined the regex multiple times but to no avail.

A: The problem is that re.lastIndex stores the value that is correct for the previous value of template, but since you change the template value the re.lastIndex is no longer correct for the modified string.
See a simplified example below:

let template = `<%ENTRY_NUMBER%><%NAME%><%CLASS%><%GENDER%><%AGE%>`;
let re = /<%(.+?)%>/g, match;
let data = { 'NAME':'John', 'CLASS':'A3', 'GENDER':'Male', 'AGE':'19' };
while (match = re.exec(template)) {
    console.log(re.lastIndex);
    template = template.replace(match[0], data[match[1]]);
    console.log(template);
}
console.log(template);

// Iteration 1: re.lastIndex = 16
// undefined<%NAME%><%CLASS%><%GENDER%><%AGE%>
// Index is now between <%NAME% and > -> this match will be skipped
// and so on...

Thus, it is better to modify the string on the fly inside a replace callback since all matches will get replaced once they are found, and you won't have to track the indices where to search from.
Use
process(template : string , data: Object) {
    return template.replace(/<%(.+?)%>/g, function($0, $1) {
              return data[$1] ? data[$1] : $0;
           });
}

Note that <%(.+?)%> matches <%, then captures any 1 or more chars other than line break chars, as few as possible into Group 1 and then matches %>. This way, you will also match values that contain % and > (it is important if data contains such keys).

A: The problem is you don't need a global flag g becuase you reexecute the expression over and over until will not match but a multiline flag m

let s = `

        <%ENTRY_NUMBER%>
        <%NAME%> , <%CLASS%> , <%GENDER%> , <%AGE%>

`;
const re = /<%([^\%]+)?%>/,
  data = {
    ENTRY_NUMBER: '1977',
    NAME: 'Blue',
    CLASS: 'Vertebrates',
    GENDER: 'Male',
    AGE: '40'
  };

let k = 0;
while (re.test(s) && k++ < 1000) {
  match = re.exec(s);
  if (match) s = s.replace(match[0], data[match[1]]);
}
console.log(s);


text:
Q: Difference between Entity and DTO What is the difference between a DTO and an Entity? In details these are my questions:

*

*What fields should the DTOs have? For example my entity classes are:
@Entity
public class MyFirstEntity implements Serializable {

    @Id @GeneratedValue
    private Long id;

    private String stringData;

    @OneToOne
    private MySecondEntity mySecondEntity;

    @OneToMany
    private List<MySecondEntity> mySecondEntitesList;

}

@Entity
public class MySecondEntity implements Serializable {

    @Id @GeneratedValue
    private Long id;

    private Integer integerData;

    @ManyToOne
    private MyFirstEntity myFirstEntity;

}

There is a one-sided connection (One-to-one) and a two-sided connection (Many-to-one), a simple String and Integer data and of course the ids. What to put from them in the MyFirstDTO and MySecondDTO classes?

*If there is an inheritance between the entities, then how should I represent it in the DTOs? For example:
@Entity
public class MyFirstEntity extends MySecondEntity {
    ....
}

@Entity
public class MyFirstDTO extends MySecondDTO {
    ....
}

*How should I use them? For example, I find out this: I'm working on a web project. The user of the webpage wants to register. He/She fills the forms, and sends it to the server. On the server side I create first a DTO, because its fields have the validations. From the DTO I create an Entity and persist it to the database. When there is a request for an entity, I convert the requested entity to DTO, and give it to the user on the client side. Is it a good imagination, or not?

A: Simple talk:
DTO stands for Data Transfer Object. DTOs are mainly used for transferring data between services (web services, APIs, etc.) which can encompass variety of properties of different entities (with or without their ID). Take this row as an example of a DTO: Consider that a shopping website is going to send its shipping requests to a shipping company by a web-service. Its DTO would be something like this: CustomerFullName, ShippingFee, ShippingAddress. In this example CustomerFullName is combination of properties FirstName + LastName for the Customer entity, and ShippingFee is the result of several processes of destination, tax, etc over some other entities.
On the contrary, Entities are bunch of properties gathered to represent a single entity with a specific ID (e.g., Teacher, Student, Employee, etc.). In other words, DTOs are a bunch of meaningless properties gathered to be sent to the client and a DTO doesn't necessarily have relationship to the other DTOs, while an Entity includes properties of a specific object with meaningful relation to the other entities. In a relational database paradigm, we can look at DTOs as views' row while Entities are tables' row with the primary key. @Shatayu Darbhe also have mentioned this in his/her answer.
However, Model is a combination of these two. A model can contain several related entities plus extra data to handle real-world application/UI problems. Consider a Model named CustomerOrdersModel that contains Customer Entity, List<Order> Entities, and an extra Boolean flag PayWithCredit specifying whether user is going to pay with debit-card or credit-card.

A: "Entities" refer to units of composition of the overall system data. They normally represent business objects like: bank accounts, employees, products, etc. They can be used to persist the state of the system to a database.
"Data transfer objects" are emphemeral collections of data transferred for a very specific purpose. For example, to display a list of products of a specific kind to an end user. You do not want to send all of the data that represents every product entity to the user, but only what is needed for this purpose.
The the Microsoft 2014 MVC documentation explains why you would want to create DTOs from entities. These are some examples of what they suggest that you do to convert entities to DTOs.

*

*Remove circular references.

*Hide particular properties that clients are not supposed to view.

*Omit some properties in order to reduce payload size.

*Flatten object graphs that contain nested objects, to make them more convenient for clients.

*Avoid "over-posting" vulnerabilities. (See Model Validation for a discussion of over-posting.)

*Decouple your service layer from your database layer.

But it's important to understand that none of these are hard rules that need to be followed. It all depends on what data is best to send your client and what format would be most useful for your client.
What does the client need to do with the data?

*

*Will it be edited or just viewed?

*Do clients care about the order of the int list?

*Will insertions or deletions of an int need to be made?

*Will the list need to be rearranged?

Does the client need to know about the 1-1 or 1-many relationships or the fact that there's inheritance? Sending this information may be just adding unnecessary complexity for the client.
These and other questions need to be answered before deciding what data to send the client and how to send it.

A: Difference between DTO & Entity:
Entity is class mapped to table. Dto is class mapped to "view" layer mostly.
What needed to store is entity & which needed to 'show' on web page is DTO.
Example : If I want to store employee model as follows :
Take employee as an example, I need to store gender either male/female/other.
But on JSP I need to show all three values as form 'options' so user can select one.
@Entity
public class Employee{
//annotate with @Id and others

private Long id;
private String name;
private Gender gender; //this is enum viz Male,female
}
//Now extend Dto with employee

public EmployeeDto extends Employee{
Gender[] genders=Gender.values(); //put all gender types in array.
}

while rendering jsp we can give
<select name="gender"> //pointed towards entity gender field.
  <option value="Male">Male</option>
  <option value="Female">Female</option>
  <option value="Other">Other</option>
</select>

then in spring or some other framework whichever selected will be opted as gender in entity.This is made possible because Dto had all three values of gender in it.
Similarly, as per situation things follows.
As mostly we need most of entity fields on jsp we extend dto by entity.

A: Short answer:

*

*Entities may be part of a business domain. Thus, they can implement behavior and be applied to different use cases within the domain.

*DTOs are used only to transfer data from one process or context to another. As such, they are without behavior - except for very basic and usually standardised storage and retrieval functions.
Long answer:
While the term "Data Transfer Object" (DTO) is defined quite unambiguously, the term "Entity" is interpreted differently in various contexts.
The most relevant interpretations of the term "Entity", in my opinion, are the following three:

*

*In the context of entity-relationship- and ORM-frameworks - specifically Enterprise Java and Jpa:
"An object that represents persistent data maintained in a database."

*In the context of "Domain-Driven Design" (by Eric Evans):
"An object defined primarily by its identity, rather than its attributes."

*In the context of "Clean Architecture" (by Robert C. Martin):
"An object that encapsulates enterprise-wide critical business rules."
The Jee- and Jpa-community sees entities primarily as objects mapped to
a database table. This point of view is very close to the definition of a DTO - and that's where much of the confusion probably stems from.
In the context of domain-driven-design, as well as Robert Martins point of view, however, Entities are part of a business domain and thus can and should implement behavior.


text:
Q: Filters on Weka I need to generate a filter in Java using the Weka API that will read in files and trigger an alert if a file contains a word from a predefined list. I am just beginning Weka so am not entirely sure how this would work in weka, please help :) I can't find any tutorials which are for beginners

A: Everything you need to begin with Weka API can be found in this site.
When I need to build some kind of filter, I subclass BufferedReader (java.io.BufferedReader) and override some of its methods. Weka also has some interfaces and classes that can do most of the job (like selecting only some desired attributes or normalizing data). Look inside that link to gain more knowledge about it.

A: As you are a beginner, the first thing you should learn is to properly use weka in your Java code. The following website will be helpful: Wekawiki


text:
Q: Call a script(PHP, Perl) when MYSQL insert occurs What I'm looking is to execute a script as soon as there is an INSERT on one of the MYSQL table.
I wanted to export all the contents of the inserted row into formatted Excel file. (This will be done through external script written in PHP)
Main issue is to call the script as soon as the insert occurs.
First thing that occurred to me is to create a Trigger and call the script (Found that this is not best approach. Other thing occurred to me is running a crontab
Could anyone please suggest if there is a better solution for this?
PS: The INSERT happens through an external application and I have no control over it.

A: This question was answered here: Invoking a PHP script from a MySQL trigger btw.
Anyway, other possible solution is to create environment with replication (although there will be no slave), write your own mysql client connected to the master (simulating slave server) and waiting for commands comming through.
You can also create "tail -f" script listening on binlog file.


text:
Q: The last created element isn't the one I dropped I have to do a drag and drop program so i use Vue.Draggable but when i drop my element into the second list the last created element on that list isn't the one i dropped but the one who had the value replaced.
So for instance if i have a drop array like that:
var a = [
    {
        name: 'element1'
    },
    {
        name: 'element2'
    },
    ...
]

and I drop an element before the first element of the second list, the last created element will be 'element1' and I need my program to make the last created element the one droped
I don't know how Vue.Draggable does that but when I had programmatically
an element somewhere in the second list like so secondList.splice(3, 0, newElement) the last created element is the one i want (newElement)
Here's the code from the first list:
<draggable v-model="blocks" :clone="clone" :options="draggableOptions" @end="reGenerateUuid">
    <block
        v-for="b in blocks"
        :key="b.props.uuid"
        :title="b.title"
        :image="b.image"
        @click.native="addBlock(blocks[key])" />
</draggable>

the second list is a rendered component so I can't share it because it's massive.
The second list doesn't use v-model with the draggable component but the list prop, because from what I understood I can't put a v-model on a rendered element in VueJS.
The elements draggable on the second list doesn't have the key prop because I don't want them to regenerate.
Maybe I need to specify how draggable should add the element to the second list?
Does anyone have an idea?

A:
The elements draggable on the second list doesn't have the key prop
  because i don't want them to regenerate.

You need the key prop. Otherwise Vue doesn't properly keep track of the order of elements.


text:
Q: How to count the number of different items in a range without use a pivot table excel vba I have a large range with various repeating id's.  I want to know how many unique id's are in the range, but I don't want to use a pivot table.  This question  is related, but does not have the answer.  Is there a simple way to do this using VBA?
I also saw this, but it doesn't work for me.

A: May you want to filter the column without duplicates. After that, you can use a subtotal-function.
Range("A:A").AdvancedFilter Action:=xlFilterInPlace, Unique:=True
 Range("B2").Select
 ActiveCell.FormulaR1C1 = "=SUBTOTAL(9,C[-1])"
This VBA filters a list in column A, select cell B2 and write the subtotal-function in it. I got the function with "macro record".
Did it help?
https://support.office.com/en-nz/article/Filter-for-unique-values-or-remove-duplicate-values-ccf664b0-81d6-449b-bbe1-8daaec1e83c2

A: Use a Dictionary object to load unique values, such as below:
Sub CountUnique()
    Dim oDictionary As Object
    Dim rngData As Range
    Dim nCounter As Integer

    Set oDictionary = CreateObject("Scripting.Dictionary")
    Set rngData = Range("A1:A10") 'Change the range to suit
    nCounter = 0

    For Each cel In rngData
        If Not oDictionary.exists(cel.Value) Then
            oDictionary.Add cel.Value, 0
            nCounter = nCounter + 1
        End If
    Next cel

    MsgBox nCounter

End Sub

A: Here's the simplest way I've found:
Function Count_Uniques(cell_range As Range)
    Dim n As Long
    Dim cells1 As Range
    Dim unique_count As Collection
    Set unique_count = New Collection

    On Error Resume Next
        For Each cells1 In cell_range
                 unique_count.Add cells1.Value, CStr(cells1.Value)
        Next cells1
    On Error GoTo 0

    Count_Uniques = unique_count.Count

End Function


text:
Q: How using spring-boot-starter-jpa in custom spring-boot-starter? I have my custom starter. Inside it, I define a repository. How should I define it in the configuration?  This is how I did the usual bean before.
@Bean
@ConditionalOnMissingBean(HelloWorldController.class)
public HelloWorldController helloWorldController() {
    return new HelloWorldController();
}

Repository:
@Repository
public interface CarRepository extends JpaRepository<Car, Long> {
}

And configuration
@Configuration
@EnableJpaRepositories
public class DomainConfiguration {
}

If you use this starter, context will not see the repository bean. Because I did not declare it in the configuration.I don't know how to declare it.


text:
Q: Intellij IDEA plugin development: Cannot get progress indicator for IntentionAction I would like to display a progress bar when running a custom IntentionAction in my custom IntellIJ IDEA plugin.
However, it is not displayed no matter what I do. To test whether the problem lies in the IntentionAction, I copy-paste the code to a simple implementation of an AnAction. The whole class looks like so:
    public class HelloAction extends AnAction {
    public HelloAction() {
        super("Hello");
    }

    public void actionPerformed(AnActionEvent event) {
        Project project = event.getData(CommonDataKeys.PROJECT);
        ProgressManager.getInstance().run(new Task.Modal(project, "daf", false) {
            public void run(ProgressIndicator indicator) {
                indicator.setText("This is how you update the indicator");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {}
                indicator.setFraction(0.5);  // halfway done
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {}
            }
        });
        Messages.showMessageDialog(project, "Hello world!", "Greeting", Messages.getInformationIcon());
    }
}

And it works perfectly. And when I use the same code inside an IntentionAction, nothing is displayed.
public class GenerateIntentionAction extends PsiElementBaseIntentionAction implements IntentionAction {
...
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
        ProgressManager.getInstance().run(new Task.Modal(project, "daf", false) {
            public void run(ProgressIndicator indicator) {
                indicator.setText("This is how you update the indicator");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {}
                indicator.setFraction(0.5);  // halfway done
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {}
            }
        });

I tried to run call runWithProgressSynchronously instead of run, tried making Task Modal and Backgroundable - to no avail. I do not know what is wrong besides the fact that ProgressIndicator inside IntentionAction is always an EmptyProgressIndicator

A: If your intention action is invoked inside WriteAction, you can't show modal UI from there. Overriding startInWriteAction and returning false might help.


text:
Q: NodeJS vs PHP+Apache performance test has weird results I am trying to choose the best technology for my API so I've created the simplest script ever:
PHP:
<?php

$r = [];

for($i=0;$i<=1000000;$i++) {
    $r[] = $i;
}

echo json_encode($r);

Node:
var http = require("http");

http.createServer(function(request, response) {
    var i, ret = [];

    response.writeHeader(200, {"Content-Type": "text/html"});

    for(i=0;i<=1000000;i++) {
        ret.push(i);
    }

    response.end(JSON.stringify(ret));
}).listen(8080);

Apache has a pretty default configuration without and is clean of fancy optiomizations
The response time is about 1.5s-2.3s for both PHP+Apache and NodeJS which is really weird..So do I do something wrong with node or its just that this specific functionality has no advantage over PHP+Apache?

The API should ultimatley recieve calls, insert it to a database on one side and on the other side it should fetch those results. The api should recieve about ~1million calls per day and it should be scalable so i'm trying to figure out what is the best approach here and the performance test results confused me a bit.

A: Please note that the performance benchmark results depends on the type of programs/applications you're running for benchmarking.
There are usually two types of performance measure. One is server side performance( it is measured by calculating the CPU and memory usage of the corresponding technology in the  server (Linux  Box)) and another is client side performance (It is measured by the response time using tools like Apache Bench).
Server Side CPU and Memory Usage Benchmarks : Debian.org benchmarks different programming languages/framework in Linux Box (Ubuntu). It uses a set of different types of program to measure the performance. It can be an ideal source of information. However, it only measure the server side CPU and memory usage. You can find the benchmarking result between Node and other languages (e.g. PHP) in the following link:
https://benchmarksgame.alioth.debian.org/u64q/which-programs-are-fastest.html
https://benchmarksgame.alioth.debian.org/u64q/compare.php?lang=node&lang2=php
According to their result, Node performs significantly better compared to PHP in terms of CPU usage.
Client Side Response Time Benchmarks:  Hostingadvice has compared  Node vs PHP performance in the client side. They measured the performance in terms of client side response time. You can find the result in the following link:
http://www.hostingadvice.com/blog/comparing-node-js-vs-php-performance/
According to their result, Node performs significantly better than PHP in terms of client side response time.


text:
Q: No qualifying bean of type 'Package.TestDaoRepo' available: expected at least 1 bean which qualifies as autowire candidate Hey I am using spring boot version 2.3.4 for my web application. I am writing a JUNIT Integration test case for testing my controller, service and Repo using WebMvcTest.
@ExtendWith(SpringExtension.class)
@WebMvcTest(TestCotroller.class)
class ITTestController {

@Test
void test() {
    System.out.println("Test me ");
   // URL to call. controller and rest of the logic
}

}

I am looking for minimum configuration to load so i have used @WebMvcTest.
This is my controller need to be tested
@RestController
@RequestMapping(value = APIUrlConstants.VERSION + APIUrlConstants.TEST_CONTROLLER)
public class TestCotroller {
    @Autowired
    TestServiceInf testServiceInf;

    @RequestMapping(value = APIUrlConstants.TEST_DB, method = RequestMethod.GET)
    public ResponseEntity<String> testDbStatus() {
        Long count = testServiceInf.testDbStatus();
        String responseMessage = "DB is up and running, total number of products count are --  " + count;
       return new ResponseEntity<String>(responseMessage, HttpStatus.OK);

    }

    @RequestMapping(value = APIUrlConstants.TEST_APPLICATION, method = RequestMethod.GET)
    public ResponseEntity<String> testApplicationStatus() {

        String responseMessage = testServiceInf.testApplication();
       return new ResponseEntity<String>(responseMessage, HttpStatus.OK);

    }

    }

The Service class
  @Service
public class TestServiceImpls implements TestServiceInf {

    @Autowired
    TestDaoRepo testDaoRepo;

    private static String responseMessage = "Application is up and running";

    @Override
    public Long testDbStatus() {

        Long countProduct = testDaoRepo.count();
        System.out.println(countProduct);
        return countProduct;
    }

    @Override
    public String testApplication() {

        return responseMessage;
    }

}

Repo class
@Repository
public interface TestDaoRepo extends JpaRepository<CpcMasterProduct, Long> { }

This is the error i am facing -

No qualifying bean of type 'package.TestDaoRepo' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

Please help me where i am doing wrong ?

A: @WebMvcTest won't instantiate @Repository beans. This is intentional in order to make the tests more lightweight and isolate the controller tests. Typically, you would replace your services with mocks for such tests.
See the docs for explanation.
In your case, your test would contain something like:
@ExtendWith(SpringExtension.class)
@WebMvcTest(TestCotroller.class)
class ITTestController {

@MockBean
private TestServiceInf serviceMock;

@Test
void test() {
    System.out.println("Test me ");
   // URL to call. controller and rest of the logic
}

}

If you want to do integration tests, you shouldn't use @WebMvcTest.


text:
Q: Show that the estimator of the mean is independent of the estimator of the variance in R I'm trying to illustrate with R the fact that if X1, ..., Xn are random Gaussian variables N(μ, σ^2), then the estimator of the mean (X1 + ... + Xn)/n is independent of the estimator of the variance ((X1-μ)^2 + ... (Xn-μ)^2))/n.
I have established that mathematically with the Cochran's theorem.
Now with R, I'm introducing
x = rnorm(50, 3, 1) #50 N(3,1) random variables for instance.
piX1 = rep_len(mean(x), 50) #(this gives me a 50-length vector containing mean(x)
piX2 = rep_len(x - mean(x), 50)
tab1 = table(piXV1, piXV2)
chi = chisq.test(tab1)

This give me a p-value of 1, which makes me skeptical as to whether the Chi Square test actually tests if piX1 and piX2 are independent.. Can anyone tell me if it's actually working?
Thanks!

A: The code below generates 10000 independent samples and calculates mean and variance. Then, a test on Pearson's correlation between mean and variance estimates was applied.
mnvr <- sapply(1:10000, function(k) {
  x = rnorm(50, 3, 1)
  mn <- mean(x)
  vr <- var(x)
  return(c(mn,vr))
})

cor.test(mnvr[1,], mnvr[2,])

#         Pearson's product-moment correlation
#
# data:  mnvr[1, ] and mnvr[2, ]
# t = -0.001029, df = 9998, p-value = 0.9992
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
#  -0.01961036  0.01958978
# sample estimates:
#          cor
# -1.02906e-05


text:
Q: Cannot add the msExchArchiveGUID in Powershell I cannot add the GUID value for msExchArchiveGUID in powershell. Error reports of "constraint violation" or "A value for the attribute was not in the acceptable range of values" depending on which powershell cmdlet is used. From what I can tell the value that needs to be input needs to be up to 16 characters. Anything more and it errors. For example, the GUID value I need to write is 5C669E441173CF4394995E43EC8ED9ED. When pasted using ADSIEdit the output looks like: 5C 66 9E 44 11 73 CF 43 94 99 5E 43 EC 8E D9 ED. If I add the same value using Powershell it errors. How can I write the value in Powershell to give the same result like adding using ADSIEdit?
E.g
Set-aduser -identity "someone" -add @{msExchArchiveGUID="A format the works!
"}

A: The solution is a bit convoluted (and probably obvious to all but me!) which I will show below.. I'm sure a more concise answer is out there..
I get the GUID value using quest (rather that get-remotemailbox)
Get-QADUser -Service domain -Identity someone -IncludeAllProperties|select msExchArchiveGUID

    This presents the archive GUID as 5C669E441173CF4394995E43EC8ED9ED

    So.....
    $oct = "5C669E441173CF4394995E43EC8ED9ED"
    $oct1 = $oct.substring(0,2)
    $oct2 = $oct.substring(2,2)
    $oct3 = $oct.substring(4,2)
    $oct4 = $oct.substring(6,2)
    $oct5 = $oct.substring(8,2)
    $oct6 = $oct.substring(10,2)
    $oct7 = $oct.substring(12,2)
    $oct8 = $oct.substring(14,2)
    $oct9 = $oct.substring(16,4)
    $oct10 = $oct.substring(20,12)

    $strOut = "$oct4" + "$oct3" + "$oct2" + "$oct1" + "-" + "$oct6" + "$oct5" + "-" + "$oct8" + "$oct7" + "-" + "$oct9" + "-" + "$oct10"

Output is "449E665C-7311-43CF-9499-5E43EC8ED9ED"
    $Id = [GUID]("449e665c-7311-43cf-9499-5e43ec8ed9ed")
    Set-ADUser -Identity $IPGUser -Clear msexcharchiveGUID
    Set-ADUser User -Add @{msexchArchiveGUId=$id}


text:
Q: Cart Price Rules by condition In my code i can apply 50% discount on cart but i want this discount to apply only when product from a specific category is added.
        \Magento\Quote\Model\Quote $quote,
        \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
        \Magento\Quote\Model\Quote\Address\Total $total
    ) {

        parent::collect($quote, $shippingAssignment, $total);
        //$address             = $shippingAssignment->getShipping()->getAddress();
        $label               = 'RolusTech Discount';
        $discountAmount      = 0;
        $appliedCartDiscount = 0;
        if($total->getDiscountDescription()) {
            // If a discount exists in cart and another discount is applied, the add both discounts.
            $appliedCartDiscount = $total->getDiscountAmount();
            $discountAmount      = $total->getDiscountAmount()+$discountAmount;
            $label               = $total->getDiscountDescription().', '.$label;
        }

        $disc = $total->getSubtotal();
        $disc1 = -$disc/2;
        $total->setDiscountDescription($label);
        $total->setDiscountAmount($disc1);
        $total->setBaseDiscountAmount($disc1);
        $total->setSubtotalWithDiscount($total->getSubtotal() + $disc1);
        $total->setBaseSubtotalWithDiscount($total->getBaseSubtotal() + $disc1);

        if(isset($appliedCartDiscount)) {
            $total->addTotalAmount($this->getCode(), $disc1 - $appliedCartDiscount);
            $total->addBaseTotalAmount($this->getCode(), $disc1 - $appliedCartDiscount);
        } else {
            $total->addTotalAmount($this->getCode(), $disc1);
            $total->addBaseTotalAmount($this->getCode(), $disc1);
        }

        return $this;
    }```


text:
Q: Python program executed via "$ python project.py  " I can't figur out what that exctly means/ how i have to write a program to work when executed that way ("$ python project.py  "). Thanks for helping out a beginner.

A: This form simply calls the python interpreter (python) explicitly, and then passes the script as the first argument. This is mostly equivalent to:
$ project.py <string> <array>

...but calling the interpreter explicitly will work even if the script is not marked as executable or doesn't have the interpreter defined at the top of the file (e.g. /usr/bin/python or /usr/bin/env python).
If you're being asked to call your script in the python project.py form, you don't have to do anything special.


text:
Q: DynamoDb , unable to update the item dynamically using expressions I am trying to update Dynamo Table using expression, I am trying to generate keys dynamically. The issue looks like if they key has space in it, expressions don't evaluate properly.
Following in my update implementation:
        update_expression = 'SET {}'.format(','.join(f'#{p}=:{p}' for p in row_as_dict))
        expression_attribute_values = {f':{p}': v for p, v in row_as_dict.items()}
        expression_attribute_names = {f'#{p}': p for p in row_as_dict}

        if result_set.get('Item') and result_set.get('Item').get(primary_key):
            TABLE.update_item(
                Key={
                    primary_key: row_as_dict[primary_key],
                    sort_key: row_as_dict[sort_key]
                },
                UpdateExpression=update_expression,
                ExpressionAttributeValues=expression_attribute_values,
                ExpressionAttributeNames=expression_attribute_names
            )

if i print the values for  update_expression and expression_attribute_values and expression_attribute_names i get following output.
update_expression
SET #Ref No=:Ref No,#FT/Hot=:FT/Hot,#Irfan watch List=:Irfan watch List,#F.Soahil watchList=:F.Soahil watchList,#HR Responible=:HR Responible,#Pipeline(Adv/Ref)=:Pipeline
(Adv/Ref),#Source=:Source,#Date Submitted=:Date Submitted,#Name=:Name,#Candidate Location=:Candidate Location,#Tech =:Tech ,#Current Company=:Current Company,#Exp=:Exp,#Position being considered for=:Position being considered for,#Proj. / Gen Hiring=:Proj. / Gen Hiring,#Comments / Latest Status / Next Step=:Comments / Latest Status / Next Step,#Status=:Status,#hiring status=:hiring status,#Link to Lever=:Link to Lever,#LinkedIn Link / Resume=:LinkedIn Link / Resume,#Interview Feedback Google Doc=:Interview Feedback Google Doc,#Email=:Email

expression_attribute_values
{':Ref No': '1', ':FT/Hot': 'NaN', ':Irfan watch List': 'NaN', ':F.Soahil watchList': 'NaN', ':HR Responible': 'Khurram', ':Pipeline\r\n(Adv/Ref)': 'Referred', ':Source': 'Usman Khan', ':Date Submitted': '17-Dec', ':Name': 'Asif Mahmood Mughal Zain', ':Candidate Location': 'ISL', ':Tech ': 'Spark. Hadoop\r\nSQL, Big Data', ':Current Company': 'Zain Telecom', ':Exp': '18+', ':Position being considered for': 'Senior SA', ':Proj. / Gen Hiring': 'General', ':Comments / Latest Status / Next Step': 'Muhammaf Naseer      Recommneded\r\nAdeel Ashraf                Recommended\r\nFaheem Khan              Recommended\r\n\r\nAccepted offer.will join on 6 jan', ':Status': 'Joined', ':hiring status': 'Hired', ':Link to Lever': 'Link to Lever', ':LinkedIn Link / Resume': 'Asif Mehmood Mughal', ':Interview Feedback Google Doc': 'Link to Feedback', ':Email': 'some_email1@test.com'}

expression_attribute_names
{'#Ref No': 'Ref No', '#FT/Hot': 'FT/Hot', '#Irfan watch List': 'Irfan watch List', '#F.Soahil watchList': 'F.Soahil watchList', '#HR Responible': 'HR Responible', '#Pipeline\r\n(Adv/Ref)': 'Pipeline\r\n(Adv/Ref)', '#Source': 'Source', '#Date Submitted': 'Date Submitted', '#Name': 'Name', '#Candidate Location': 'Candidate Location', '#Tech ': 'Tech ', '#Current Company': 'Current Company', '#Exp': 'Exp', '#Position being considered for': 'Position being considered for', '#Proj. / Gen Hiring': 'Proj. / Gen Hiring', '#Comments / Latest Status / Next Step': 'Comments / Latest Status / Next Step', '#Status': 'Status', '#hiring status': 'hiring status', '#Link to Lever': 'Link to Lever', '#LinkedIn Link / Resume': 'LinkedIn Link / Resume', '#Interview Feedback Google Doc': 'Interview Feedback Google Doc', '#Email': 'Email'}

The Error generated is

An error occurred (ValidationException) when calling the UpdateItem operation: ExpressionAttributeValues contains invalid key: Syntax error; key: ":hiring status"

A: You can't have spaces in your attribute keys/values in the expression. So :hiring status needs to be something like :hiring_status.

A: Go Dynamof!
You might be very interested in dynamof. Its a library purposed to do exactly what your trying to do. At the very least you can take a peak and check out how it handles dynamically creating all the expressions.
I suggest you take a look at the args module.
It has the functions that do what your trying to do. The args module gets some help from another module (the request builder) in dynamof that is responsible for some preprocessing of the entire action's arguments so the args module's functions get an easy to use and parse RequestTree object.
Answer...
I would just use dynamof - but I'm biased. If you want to write it yourself, heres a little example on how its been done straight from dynamof.
def UpdateExpression(request: RequestTree):
    def expression(attr):
        if attr.func is not None:
            return attr.func.expression(attr)
        return f'{attr.alias} = {attr.key}'
    key_expressions = [expression(key) for key in request.attributes.values]
    key_expression = ', '.join(key_expressions)
    return f'SET {key_expression}'

NOTE: The attr.alias is whats used to handle the special name cases - like spaces. Its set in the request builder module mentioned above.
disclaimer: I wrote dynamof