text:
Q: Why do the C# Caller Info Attributes need a default value? I just came across the C# 5 Caller Info Attributes (http://msdn.microsoft.com/en-us/library/hh534540.aspx).
This seems like a very useful feature, and I've read up some documentation (http://www.codeproject.com/Tips/606379/Caller-Info-Attributes-in-Csharp).
However, I'm just wondering: Why does one have to pass in default values? How are they used?
The following example code shows how one would use the Caller Info Attributes:
public static void ShowCallerInfo([CallerMemberName]
  string callerName = null, [CallerFilePath] string
  callerFilePath = null, [CallerLineNumber] int callerLine=-1)
{
    Console.WriteLine("Caller Name: {0}", callerName);
    Console.WriteLine("Caller FilePath: {0}", callerFilePath);
    Console.WriteLine("Caller Line number: {0}", callerLine);
}

My question is: What are the default values of null, null, and -1 used for? How is the code above different from:
public static void ShowCallerInfo([CallerMemberName]
  string callerName = "hello", [CallerFilePath] string
  callerFilePath = "world", [CallerLineNumber] int callerLine=-42)
{
    Console.WriteLine("Caller Name: {0}", callerName);
    Console.WriteLine("Caller FilePath: {0}", callerFilePath);
    Console.WriteLine("Caller Line number: {0}", callerLine);
}

The way I understand it, these are optional parameters, and the compiler supplies the default value, replacing whatever default value we assign. In that case, why are we specifying the default values? Is there some weird edge case where the compiler may not be able to fill in the values, and resorts to the defaults we had supplied? If not, then why are we being asked to enter this data? It seems rather clumsy to ask devs to supply defaults which won't ever be used.
Disclaimer: I tried googling this but I wasn't able to find anything. I'm almost afraid of asking questions on SO because most such newbie questions are met with such hostility, but as a last resort I'm going to hazard a question. Moderators/senior users, no offense intended - I really did try and find information elsewhere before posting this.

A: Those parameters need a default value because the Caller Info attributes were implemented using optional parameters and optional parameters require a default value. That way the call can be simply ShowCallerInfo() without having to send any parameters and the compiler will add the relevant ones.
Why was it implemented using optional parameters to begin with is a deeper question. They could have made it without, and the compiler would need to "inject" those parameters before actual compilation started, but as opposed to optional parameters (which is a C# 4.0 feature) it would not be backward compatible and it will break other compilers/code analysis tools.

A: They need the defaults so that the parameters can be flagged as optional. If you don't specify the parameters when calling the method, the compiler will inject the correct values for you, but only if you didn't specify them. If you do, then the "magic" of those attributes won't happen.
From my understanding, these attributes do not affect runtime and are purely for compile time so the defaults are only to make sure the parameters are optional.

A: To put it in another way, on the callee (the method called where the attribute is applied to the parameter) the parameter must exist. On the other hand, the caller must pass those arguments and the only way for the compiler to allow for an unspecified argument is to give it a default value.
Although attributes may influence code generation or runtime execution, the source must be valid if one removes all the attributes. Therefor the default value must be defined on the callee and the compiler just generate the argument value based on the applied attribute instead of the current default value defined on the callee.

A: There are a few uses mentioned in other answers which all seem valid.
Something they have missed was that these essentially tells the compiler to rewrite the calls to these functions with static values. But these values are not always available. In those cases, the compiler will not rewrite the calls, so the default values will be used.
Examples:

*

*If you compile a dll with a function that has these attributes, expose that to an in memory generated script, (say via Roslyn), that code may not have a "filename".

*

*One may argue that the generated script should then invoke the method with argument values provided instead, but that means the same code that the compiler can compile statically (i.e csc mycodefile.cs) wont work with dynamic compilation at runtime even with the same context which would be confusing.

*You can also invoke this method via reflection, which the compiler simply isnt aware of to add these values.

*

*Runtime/BCL could be built to force the reflection caller to provide these values, but there isn't any meaningful values for filename and line number in that context anyway.

*You can also add [CallerMemberName] to an attribute constructor and apply that attribute on a class. This will not have a member name.

See Member Names in Docs
Attribute constructor
The name of the method or property to which the attribute is applied. If the attribute is any element within a member (such as a parameter, a return value, or a generic type parameter), this result is the name of the member that's associated with that element.
No containing member (for example, assembly-level or attributes that are applied to types)
The default value of the optional parameter.

You can also provide the values explicitly, if you want to hide the caller information. for some reason. (May be if you use code obfuscation, these values may not affected, so you may want to provide these values in those cases to hide the caller).

See Remarks in Docs
Caller Info values are emitted as literals into the Intermediate Language (IL) at compile time. Unlike the results of the StackTrace property for exceptions, the results aren't affected by obfuscation.
You can explicitly supply the optional arguments to control the caller information or to hide caller information.


text:
Q: Weekly Dropdown Javascript So basically, I need a dropdown to be generated with date ranges for the list of weeks between two years. So, for example, if the years are 2012 and 2014, it'll generate a list of weeks such as:
1/1/12-1/7/12
1/8/12-1/14/12
etc.
Going on until the last week of 2014. If there's not enough to generate a week there, it'll simply go until 12/31/14. This is to be used to generate weekly reports via MySQL, but the back-end is already written. I just need to build the interface.
Now, before you ask, I'm not using JQuery. So JQuery solutions are appreciated, but not useful. Sorry!

A: Figured it out. Turns out I was just being dense and lazy.
Here, for the future, is the general logic:
var enddate, finaldate, startyear, endyear, i;
startyear = 何々;
endyear = 何々;
enddate = new Date(endyear, 11, 31)
finaldate = new Date(enddate)
enddate.setDate(enddate.getDate() + 6)
for (i = new Date(startyear, 0, 1); i <= enddate; i.setDate(i.getDate()+6)) {
    if (i > finaldate) {
        console.log(finaldate);
    } else {
        console.log(i);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to call function within same GAS script I have two function, one reads the Cell value upon change.
And the second one makes a Request to a URL and gets the response.
 function onEdit(e) {
     var range = e.range;
     var data = range.getValue();
     Logger.log(data)
     Logger.log(test());
 }

 function test() {
     var url = 'apps.compete.com/sites/wholesalerhinestones.org/trended/UV/?apikey=[YOUR API KEY HERE]';

     var response = UrlFetchApp.fetch(url);
     Logger.log(response);
 }

Problem is that, test() runs successfully and Logs the output to Console but upon Cell change event, cell's value is logged but test() is not called.

A: One of the issues here is you're not actually calling the function, nor are you returning anything should it be called.
It should look something like this:
function onEdit(e){
  var range = e.range;
  var data = range.getValue();
  Logger.log(data)
  var testedFunction = test();
  Logger.log(testedFunction);
 }

function test(){
var url = 'YOUR-URL-HERE';
var response = UrlFetchApp.fetch(url);
Logger.log('Response code: ' + response.getResponseCode());
return response
}

The second issue that you're having here is that your using a Simple trigger which does not allow you to access services which require authorization.
Instead using an Installable trigger for 'onEdit' might do the trick. (This is what I was using, but I was testing against 'Google.com'). It should look like this:


text:
Q: Which one about the rank and nullity is true Let $A$ and $B$ be $n$ $\times$ $n$ real matrices such that $AB$=$BA$=$0$ and $A+B$ is invertible. Which of the following are always true?
$1$. rank $(A)$=rank $(B)$.
$2$. rank $(A)$$+$rank $(B)$ =$n$
$3$. nullity $(A)$ $+$ nullity $(B)$ = $n$
$4$. $A-B$ is invertible.
I am not getting how to do. Atleast it is clear that Rank$(A+B)$= $n$. help me!

A: As has been stated by others, 1 is false taking $A=0$ and $B$ any invertible matrix.
Since $AB=0$, $A$ annihilates the image of $B$, so the nullity of $A$ must be at least as large as the rank of $B$, so $$\operatorname{nullity}(A)+\operatorname{nullity}(B)\geq \operatorname{rank}(B)+\operatorname{nullity}(B)=n$$
If $\operatorname{nullity}(A)+\operatorname{nullity}(B)>n$, then $\operatorname{nul}(A)$ and $\operatorname{nul}(B)$ are subspaces of $V$ with dimensions that sum to more than $n$. So the union of a basis for $\operatorname{nul}(A)$ with a basis for $\operatorname{nul}(B)$
has more than $n$ vectors and must be dependent. Therefore some nonzero vector $v$ is in both $\operatorname{nul}(A)$ and $\operatorname{nul}(B)$. But this contradicts the given condition that $A+B$ is invertible, since $(A+B)v=0$. Therefore $$\operatorname{nullity}(A)+\operatorname{nullity}(B)=n$$
proving 3.
2 is true by using 3 and the rank-nullity theorem: subtract each side of 3 from $2n$.
4 is true because in the given conditions, $(A+B)^2$ is invertible, and $$(A+B)^2=A^2+AB+BA+B^2=A^2-AB-BA+B^2=(A-B)^2$$

A: Since $A$ and $B$ commute, each one stabilises the kernel and image of the other. Then $A+B$ stabilises each of these kernels and images, and since $A+B$ is invertible, so is each of its restrictions. Now the restriction of$~B$ to the image of$~A$ is zero (since $BA=0$), so the restriction of$~A$ to its own image coincides with the restriction of $A+B$, and therefore is invertible. This means the image if $A$ has zero-dimensional intersection with the kernel of $A$, and by the rank-nullity theorem the two subspaces are therefore complementary in $\mathbf R^n$. The same holds similarly for kernel and image of $B$. Since the kernel of $B$ contains the image of $A$ and vice versa, these two inclusions are equalities for dimension reasons: the kernel of $B$ equals the image of $A$ and vice versa.
Now for the points in the question:

*

*certainly there is no reason why the images of $A,B$ should have the same dimension; they even cannot do so if $n$ is odd;

*on the other hand the subspaces being complimentary, the dimensions of the images of $A,B$ do add up to$~n$;

*and so do the dimensions of their kernels, which are just the same subspaces but interchanged;

*the map $A-B$ coincides with $A+B$ on the kernel of $B$, and with $-(A+B)$ on the kernel of $A$; both restrictions to these complimentary subpaces being invertible, so is $A-B$ itself.

The final argument also shows that $\lambda A+\mu B$ is invertible whenever $\lambda\neq0\neq\mu$.


text:
Q: Почему не работает кэш первого уровня Hibernate в данном примере? Вот у меня простейший метод
public List<DishResponseDTO> getAll() {
    List<Dish> dishlsit = dishRepository.findAll();
    return dishlsit.stream()
            .map(DishMapper::toDishResponseDTO)
            .collect(Collectors.toList());
}

Я его в @SpringBootTest вызываю, но с transactional
 @Test
    @Transactional
    public void get() {
        System.out.println(dishService.getAll());
        System.out.println(dishService.getAll());
        System.out.println(dishService.getAll());
    }

Разве он не выполняется в одной сессии, если стоит @Transactional?
Почему 3 вызова провоцируют 3 обращения к БД, я думал, что кэш первого уровня hibernate должен решать эти вопросы, если вызовы в границах сессии

A: Кеш первого уровня, грубо говоря, хранит такую структуру данных:
Map<EntityId, Object> entityById;

Т.е. он позволяет получить сущность по идентификатору. Кеш первого уровня действительно привязан к сессии, которая в свою очередь привязана к транзакции. Но так как кеш первого уровня хранит только мапу идентификаторов, то он не работает, когда выполняется любой другой запрос. Как в этом случае, результат запроса "получить все объекты" не может быть воссоздан из кеша первого уровня.
Для такого нужно использовать кеш второго уровня (который в свою очередь не хранит объекты, а только идентификаторы объектов для запроса).
Кеш первого уровня полезен, чтобы не делать дополнительные запросы именно по идентификатору, например, когда несколько записей в результате ссылается на один и тот же ассоциированный объект.


text:
Q: How to get data from $.post() request? I'm trying to send post JQuery request, but I can't get them out in server written using Express.
Right now, I was trying to send data in this way:
Client side
$.post('http://localhost:8080/numberOfAnsweres',{'val': 2})

Server side
app.post('/numberOfAnsweres',(req,res,next)=>{
    numberOfAnwers = req.??????
    console.log(numberOfAnwers)
})

I don't know which parameter of req should I use.
I'm also not sure if the sending method is good, is there any better way?

A: You might get the values using express with:
app.post('/numberOfAnsweres',(req,res,next)=>{
    var name = req.body.name,
    var color = req.body.color;
    var value = req.body.val;
})


text:
Q: Android audiomanager - I want to set silent mode, but applied the priority mode (lollipop) My problem is occurs in android lollipop os.
I want to set 'silent mode', but lollipop os applies to 'priority mode'. (I use AudioManager) Is there any way I can apply the 'silent mode' instead of 'priority mode'?
My code :
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

A: Due to changes in API try using the int value 0 instead of AudioManager.RINGER_MODE_SILENT
AudioManager mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setRingerMode(0);

Also try checking your manifest file
<application>
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</application>

A: I had this issue on asus 5.o device , got resolved by replacing RINGER_MODE_SILENT with RINGER_MODE_VIBRATE. this might be strange but worked best for me .
AudioManager audiomanage = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    audiomanage.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);


text:
Q: Can DevForce 2010 do data migrations? I'm looking to perform some data model (schema) migrations in our database and we use DevForce 2010. Is there any built-in support for doing schema migrations in DevForce 2010, or am I going to have to script this by hand ?

A: DevForce itself doesn't include support for schema migrations, but if you're using a Code First model you can use EF's built-in support for Code First Migrations.


text:
Q: Parse xml variables in applescript I am trying to read this xml-file with applescript.
<?xml version="1.0" encoding="UTF-8"?>
    <user>
        <username>benutzer</username>
        <password>passwort</password>
        <ip>127.0.0.1</ip>
    </user>

    <vars>
        <display>15</display>
        <sleep>60</sleep>
        <volume>22</volume>
        <app1>"Plex Media Server"</app1>
    </vars>

The original applescript looks like this:
do shell script "pmset displaysleep 15" password "mypassword" with administrator privileges
do shell script "pmset sleep 60" password "mypassword" with administrator privileges
set volume output 20
tell application "Plex Media Server"
    quit
end tell
say "Media off"

How can I insert the value of "display" tp "displayslep", the value of "app1" as the application to quit etc.?
I am using several applescripts and this would make it so much easier changing certain values without having to change each script on its own. Also, I am a beginner with not too much coding knowledge.
Thanks in advance :)

A: In response to above comment, here's some example code:
tell application "System Events"
    set xmlDoc to make new XML data with properties {name:"note", text:"
    <note>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
    </note>"}
    get value of XML element "to" of XML element "note" of xmlDoc
end tell
--> "Tove"

Recommend investing in an AppleScript book - it's a huge pain to figure out this stuff without a guide.
(Obligatory: I co-wrote the Apress book.)


text:
Q: Can I use a closed source JS file in my GPL webapp? Note: When I say "open source", I am talking about GPL. Substitute with "free" if you prefer. When I say "closed source", I mean "not GPL or MIT, etc".

We have an open source (GPLv3) webapp that we develop and sell support and hosting for
(similar model to redhat).
Note, this isn't a website that we host that happens to be open source. It's a website that our clients host (or pay us to host). Each client makes their own instance of the webapp. The entire webapp is under GPL.
A particular script that we use (FullCalendar) is licensed under MIT. But the author has added a new add-on feature that will not be open sourced (maybe, it's undecided). The exact details of this license are not available yet.
Can I purchase this new add-on script and use it in my webapp (distribute it with the website's gpl code)? I have a feeling, that distributing the script that I bought would be illegal since my clients haven't bought it. Could I work around this? Could I host the script on our servers and leave it out of the distributed source? Only distribute a minified version?
What are the rules for using closed source JS in a GPL based project?

And I'm not looking for legal advice. We're not paranoid about legal issues, we just want to make sure we aren't doing something that is obviously illegal/unethical and to understand exactly how you apply GPL to JS files. Also, I'd like to give the author of the script some feedback.

A: The simple answer is: "it depends on what the license you get says"
If the commercial license says that you can relicense so that it may be used in an open source product, then thats what the license says.  I tend to doubt that this would be the case because it would essentially mean that it would lose nearly all of its power of actually being able to monetize the work.
If the license does not allow relicensing, you fall firmly into the area covered by the FAQ item What legal issues come up if I use GPL-incompatible libraries with GPL software? .  This says that you can provide an exception to your software that it may be used in combination with non-free libraries.
Note that you are not distributing the non-free software as part of the your product. Again, the license that you get will tell you what you can and cannot do.  I do not suspect that it will allow redistribution of the software under another license.
I want to emphasize that the redistribution of third party software is determined by the license on the software. It doesn't matter if you are building this as GPL, BSD, or closed source yourself. The license of the software says if you can or cannot redistribute it (or if it is intended for a single deployment).
You may find yourself filling out a form such as the one or iText (which is AGPL) for the commercial licensing which has a quote request that includes the number of servers (production and development), number of desktops (production and non-production), number of android devices, and numbers of PDFs generated per month as part of the necessary information. You provide that information and then they give you a quote.  You say you want to freely distribute it and I suspect that quote will be rather large.
It should also be emphasized that the FSF does not consider minified javascript to be open because it does not allow the practical modification of the code. This means that even if you are allowed to put the minified javascript in your software and release it under a free license, you would be doing so against the spirit of the GPL.


text:
Q: how to use django-redis hset operation in redis cache I am using django 3.0.4 and python 3.6.9. I have to use hset operation to set some values in redis cache.

*

*My try:

from django.core.cache import caches

cache.set(), cache.get() // these operation are working

But I am not able to use hset and hget operation using this library. There is no proper documentation about this in Django official docs.
Note: I have referred this (Not A copy)

A: This is how I resolved the issue:

*

*pip install django-redis-cache (3rd party redis client)

Settings.py:
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "127.0.0.1:6379/1",
        "OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",},
    }
}

In views.py ::
from django.core.cache import caches
redis_cache=caches['default']
redis_client=redis_cache.client.get_client()
redis_client.hset('myhash','key1', 'value1')

Hope this will help.
Docs: Django-redis-cache

A: Simple:
from django.core.cache import caches
cache = caches[settings.CACHE_FROM_SETTINGS]

To store in cache:
cache.hset('hash', 'key1', 'value1')
cache.hset('hash', 'key2', 'value2')

To fetch. specific key from specific hash:
cache.hget('hash', 'key1')

To fetch all the keys for that hash, use:
cache.hgetall('hash')

hgetall return dict:
{'key1': 'value1', 'key2': 'value2', ... }

and to delete the hash set:
cache.hdel(hash, 'key')

A: Hey @Sanu Your importing line is wrong Please import cache not caches. I am surprised how are you running with "caches".
from django.core.cache import cache
cache.set("Your key", "Your dict data")
cache.get("Your key")


text:
Q: Disable mod_rewrite for subdirectory I'm running a CMS using mod_rewrite for pretty URLs, but I have another site running in a subdirectory under the CMS that requires URL rewriting disabled, so I added a couple lines in the .htaccess file:
Options -MultiViews
Options +ExecCGI

AddHandler php5-cgi .php
Action php-cgi /cgi-bin/php-wrapper.cgi
Action php5-cgi /cgi-bin/php-wrapper.cgi

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# Added following two lines
RewriteCond %{REQUEST_URI} ^/dir/
RewriteRule ^(.+) - [PT,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

This works, HOWEVER one of the directories under /dir/ is protected using mod_auth and is still being rewritten. If I take out the Require valid-user directive in the .htaccess file for this directory, everything works great.
Here is the .htaccess file from the protected directory:
RewriteEngine off

AuthType Basic
AuthName "Administration"
AuthUserFile "/home/user/admin/.htpasswd"
require valid-user

Any help would be appreciated. This has been bugging me for weeks! I did some Googling and others have had this problem, but I haven't found a solution.

A: I had the same problem, Michael, and finally found the solution

For basic authentication, the server
  writes a "401 Unauthorized" header and
  then looks for an error document based
  on a pre-defined path. Most of the
  time, the error document won't exist
  in the directory that you want to
  protect, so the request gets handled
  by the rewrite engine which throws a
  404 error.
The solution to this problem is pretty
  straightforward. You need to add a
  single line of code to your .htaccess
  file instructing Apache to ignore the
  error document. When you're done, the
  code should look something like this:
ErrorDocument 401 "Unauthorized Access"

RewriteEngine off

AuthType Basic
AuthName "Administration"
AuthUserFile "/home/user/admin/.htpasswd"
require valid-user

Hope that works for you!

A: Alternatively to Manni:
RewriteCond %{REQUEST_URI} !^/dir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

and ditch the two rules you added (assuming I've understood the problem correctly), and remove the RewriteEngine from the protected .htaccess.

A: I'd try to enclose the Rewrite statements into a <DirectoryMatch> statement next. You could simply use it with inverse logic to match every directory but the one that should not be rewritten:
<DirectoryMatch "^/(?!dir)">
    RewriteEngine on
    ...
</DirectoryMatch>


text:
Q: scan qr code link to particular page in the android app I am creating an android app that have some page with information read from the sqlite database and a qr code reader built in the app, but i have question to ask
This is my question :
when i read the qr code which contain some IDs, is it possible to link/bring to a particular page that have that IDs ?
I try to google for information about this, but i did not find any sample code or tutorial that teach how to link from qr code to particular part in the android app. From all the google information i found, i only know that i need a url, then how can i generate a url to link to the android app? does it mean that i have to create a website?
MY MAIN IDEA:
in my android app have information:
Page 1:
Apple
cost 1 dollar

Page 2:
Pear
cost 1.50 dollar

What i want to do:
Scan qr code from my android, reader retrieve Page 1 as ID, then link/go to Page 1 in the android app
I just want go to or link to that particular activity1(page1) after scan the qr code that contain 1 within that same app

A: To open url from android app use this:
String url = "http://www.example.com/YOUR-ID-GENERATED_PAGE";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

source page here on StackOverflow

A: You can use TEXT  format of  QR code to return a text rather than a URL. In your case, the returned text could be an ID. Map your IDs with the Activities you are intended to awake after scanning.Then check the ID and start your mapped Activity manually in your application.


text:
Q: onmouseover / onmouseout conflicting with JQuery .hover on chrome? This is working fine on Firefox but not on Chrome or Safari. I had jQuery .hover and was working fine but when I added a inline onmouseover / onmouseout to a image inside that div, the .hover (.main-description) wont show. It actually changes the state to "block" dynamically when I hover but the text block (.main-description) wont show.
HTML:
<img src="no-hover.png"
width="250" height="250" title="me"
onmouseover="this.src='hover.png';"
onmouseout="this.src=no-hover.png';">

JS:
$(".feature-main").hover(
    function() {
        $(this).children(".main-description").show();
    },
    function() {
        $(this).children(".main-description").hide();
    }

Any help would be appreciated. Should I come with a different solution perhaps? Move the onmouseover / onmouseout to JS too?
You can check out the site at here
Thank you!

A: Hi @Marcio it is not a good practice to make two functionalities for the same thing. You need to move the src replacement in the jquery code. I suggest something like this:
$(".feature-main").hover(
function() {
    $(this).children(".main-description").show();
    $(this).attr('src', 'hover.png');
},
function() {
    $(this).attr('src', 'no-hover.png');
    $(this).children(".main-description").hide();
}

What you have show in the url i do not see a problem on the image, but your approach is not good for the separate logic.

A: Instead go unobtrusive with mouseenter/mouseleave and remove the inline event handlers:
$(".feature-main").on({
    mouseenter:function() {
        $(this).attr('src', 'hover.png')
               .find(".main-description").show();
    },
    mouseleave:function() {
        $(this).attr('src', 'no-hover.png')
               .find(".main-description").hide();
    }
});

use .find() method if your target element is child of another child element.


text:
Q: Salesforce Service Cloud Data Import / Best Practice? I need to create a service, that creates "Case" Objects in Salesforce. The types of Cases are different and are new types will be added. Like contract cancellation, customer data change, general request,...
I would like to create a generic interface (REST) as pseudo-code:
Case createCase(type, subject, description).
The handling of cases I would like to handle inside Salesforce: so I need an object "RawCase" in Salesforce and add some kind of automation, which lookes for type, and applies RawCase-to-Contract-Cancellation-Case conversion or RawCase-to-CustomerDataChange conversion or...
The main advantage of this approach: Case handling is completely inside Salesforce, I don't need to implement the mapping with another team and software change outside of Salesforce per Case.
I am not Salesforce expert. Is something like this a no-no for Salesforce, not supported or could you please explain how you would do that?


text:
Q: email sent by PHP mail is uncoded for some but not all I've been sending email from an osCommerce site via PHP mail.  Some people have responded to say that the message received is coming in "garbled" (their description).  Looking at what they received it seems that it's something with the headers, below is an example of what they are seeing:
X-Mailer: osCommerce

Content-Type: multipart/alternative;

    boundary="=_29f52435458f0625604b0644bed12e96"

--=_29f52435458f0625604b0644bed12e96

Content-Type: text/plain; charset="iso-8859-1"

Content-Transfer-Encoding: 7bit

<email body in TEXT format goes here>

--=_29f52435458f0625604b0644bed12e96

Content-Type: multipart/related;

    boundary="=_76ef682735a0ae864990f7224bfc9522"

--=_76ef682735a0ae864990f7224bfc9522

Content-Type: text/html; charset="iso-8859-1"

Content-Transfer-Encoding: quoted-printable

<email body in HTML format goes here>

--=_76ef682735a0ae864990f7224bfc9522--

--=_29f52435458f0625604b0644bed12e96--

It looks like there's something wrong with the headers.  What's making this difficult to solve is it displays like this for some and not others.  I've sent test mails to myself and I see it as it should be displayed.
This is not an osCommerce issue, it use to send with no issue, I tweaked it recently and now I can't revert it back to what it was.  My IDE allows me to track changes in files, and I've reverted all of my changes but the problem still persists.
Is the problem being caused by the two different boundary numbers?
What I'm looking for is to see if anything above looks out of the ordinary.

A: You are sending out mail in HTML format, specifically multipart/mixed. Not all email clients are capable of reading HTML mail. You might want to look into your emailing module to see if it can send out mail in plaintext format.


text:
Q: Calculate metrics with Lifetimes python package with Spark/Python [object has no attribute 'sort_values'] I am using Lifetimes python package in my spark cluster and trying to calculate some metrics -- Lifetimes package
I have been using spark 2.4.2. I have data frame like  below sample (original data has 800K records) , containing 'invoce_date' column and some other columns (id, label, county etc)
# reproducible Spark
df = sqlCtx.createDataFrame(
    [
        ('78aa', 1, 'A', '2020-04-14 19:00:00'),
        ('14aa', 3, 'B', '2020-04-17 16:00:00'),
        ('25aa', 5, 'A', '2020-04-14 15:30:00'),
        ('36aa', 7, 'B', '2020-04-14 21:30:00')
    ],
    ('id', 'X', 'label', 'invoce_date')
)

Here I am trying to leverage Lifetimes
import lifetimes

# set the last transaction date as the end point for this historical dataset

current_date = df.agg(max("invoce_date")).collect()[0][0]

# calculate the metrics
metrics = (
  lifetimes.utils.summary_data_from_transaction_data(
    df,
    customer_id_col='id',
    datetime_col='invoce_date',
    observation_period_end = current_date,
    freq='D'
    )
  )

# display first few rows
metrics.head(10)

This return an error 'DataFrame' object has no attribute 'sort_values' , I have added  df = df.sort("invoce_date")before metric calculation but still keep getting the same error and I couldn't figure it out
Here is my datatype for reference
df.dtypes
[('id', 'string'),
 ('y', 'string'),
 ('label', 'string'),
 ('invoce_date', 'timestamp')]

A: Lifetimes uses Pandas dataframes, while the df variable in your example is a PySpark dataframe. Before using functions from the Lifetimes package you have to convert your data into a Pandas dataframe by calling df.toPandas() (more details here).
Please note that calling toPandas() will load all data into the driver's memory. Lifetimes does not support distributed computing with multiple executors.


text:
Q: Cloud code with many deletes in loop, but response.success finishes first on parse.com I have a query,  and they query may return many items.
I can go through all of them and destroy them.
The problem is since destroy is Async,  the response.success(); part is executed before all the destroys are executed,  so not all items are really deleted.
How can I make it wait until the loop is done and then only response.success();
Thanks.
garageQuery2.find({
              success: function(results) {
                alert("Successfully retrieved " + results.length + " garages to delete.");
                // Do something with the returned Parse.Object values
                for (var i = 0; i < results.length; i++) {
                  var object = results[i];
                  object.destroy({
                      success: function(myObject) {
                        // The object was deleted from the Parse Cloud.
                      },
                      error: function(myObject, error) {
                        // The delete failed.
                        // error is a Parse.Error with an error code and description.
                      }
                    });
                }

                response.success();
              },
              error: function(error) {
                alert("Error: " + error.code + " " + error.message);
              }
            });

A: Try to work with Promises
This code is based on this: https://www.parse.com/docs/js_guide#promises-series
garageQuery2.find().then(function(results) {
  // Create a trivial resolved promise as a base case.
  var promiseSeries = Parse.Promise.as();
  // the "_" is given by declaring "var _ = require('underscore');" on the top of your module. You'll use Underscore JS library, natively supported by parse.com
  _.each(results, function(objToKill) {
    // For each item, extend the promise with a function to delete it.
    promiseSeries = promiseSeries.then(function() {
      // Return a promise that will be resolved when the delete is finished.
      return objToKill.destroy();
    });
  });
  return promiseSeries;

}).then(function() {
  // All items have been deleted, return to the client
  response.success();
});

Hope it helps


text:
Q: spoj factorial (time limit exceeded error). How can i improve my solution? Here is the link to my question on spoj .
I have tried it using both recursively as well as non recursively. But I am getting time limit exceeded error. How can I improve my solution?
I have shown both the solutions below.
A) Non recursive approach.
#include <stdio.h>

int main()
{
    long long int t,n,i,j=0,y;
    unsigned long long int fact;

    scanf("%lld",&t);
    i=t;

    while(i>0)
    {
        scanf("%lld",&n);
        fact=1;

        for(y=1;y<=n;y++)
              fact=fact*y;

        j=0;

        while(fact%10==0)
              j++;

        printf("\n%lld",j);
        i--;
      }

    return 0;
}

B) Non recursively
#include <stdio.h>

unsigned long long int fact(long long int);

int main()
{
      long long int t,n,i,j=0;
      unsigned long long int y;

      scanf("%lld",&t);
      i=t;

      while(i>0)
      {

           scanf("%lld",&n);
           y=fact(n);
           j=0;

           while(y%10==0)
                 j++;

           printf("\n%lld",j);

           i--;

         }

   return 0;
}

unsigned long long int fact(long long int m)
{
   if(m==0)
        return 1;

    else
         return (m*fact(m-1));

}

A: Problem reduces to this find power of 10 in n! (factorial of n), but for that we have to find power of 2 and 5 , as 10 prime factorizes into 2 and 5
k1= [n/2] + [n/4] + [n/8] + [n/16] + ....
k2= [n/5] + [n/25] + [n/125] + [n/625] + ....

where as [x] is greatest integer function
k1= power of 2 in n!

k2= power of 5 in n!

ans=min(k1,k2)

But problem we still have is we have calculate power of 2 and 5 everytime. how to avoid that ?
 since we have to divide by power.
1. for 2 , sum=0
2. keep dividing n by 2 (sum+=n/2 and n=n/2)
3. and keep on adding the quotient to sum until n becomes 0.
4. finally sum will give power of 2 in n!

Repeat this for 5,
and minimum among both will be the answer.
Working Code:
// Shashank Jain
#include<iostream>
#include<cstdio>
#define LL long long int
using namespace std;
LL n;
LL power(LL num)
{
        LL sum=0,m,temp;
        m=n;
        while(m>0)
        {
                temp=m/num;
                sum+=temp;
                m/=num;
        }
        return sum;
}
int main()
{
        int t;
        LL k1,k2,ans;
        scanf("%d",&t);
        while(t--)
        {
                scanf("%lld",&n);
                k1=power(2);
                k2=power(5);
                ans=min(k1,k2);
                printf("%lld\n",ans);
        }
        return 0;
}
// Voila

Running Code Link :Ideone Code Link
I just submitted AC with 0.54 sec and 2.6 MB

A: Here is a hint - the number of zeros at the end of n! is given by the number of times that 10 cleanly divides n!.  This is equal to the minimum of the number of times 5 divides n! and the number of times 2 divides n!.  Try seeing if you can directly compute these values rather than trying to compute n!, since for even a reasonable n (say, n = 100) the value of n! is far too large to fit into a long long and you'll get the wrong answer.
Hope this helps!

A: //count n! tail zero
//count the number of 5 in the prime factor.
int noz(int n){
    int count;

    if(n < 5) return 0;
    count = n / 5;
    return count + noz(count);
}

A: The constraints are:

1 <= N <= 1000000000

But N! doesn't fit in a 64 bits integer (in computer memory neither). Since you can't compute the factorial itself, you have to find an other method. This page gives a serious hint.


text:
Q: Paypal is not overriding the return URL? I need to override the given default Auto return URL from the paypal button HTML code. I followed these steps:

*

*Check the Auto return Url section and gave a default URL

*Generate a Buy Now button and left the Return and Cancel URL options as it is.

*Paste the button code
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="return" value="http://www.someURL.com"/>
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="G3WQ*******">
<input type="image" src="https://www.sandbox.paypal.com/en_GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>

After successful payment on Sandbox PayPal is always redirecting me to the default URL.
Why isn't overriding it? Any help would be appreciable.
I saw a couple of similar unanswered question on PayPal community and StackOverflow as well:

*

*https://www.paypal-community.com/t5/About-Payments-Archive/Auto-Return-Custom-URL-Not-Overriding-Auto-Return-Setting-URL/td-p/1038334

*Paypal button auto-return url not overriding the default url

*Setting PayPal return URL and making it auto return?

A: You won't be able to use the return field directly in the button when you're using a hosted button.  That has to be set in the hosted button settings when creating the button (or editing it through the PayPal account.)
If you want to be able to set your own return URL on the fly then you'll have to use a non-hosted button.


text:
Q: magento 2 how to render a custom collection like category page I write a custom module with a search form with multiple select input field and with a file index.phtml to render the results page, like the image below:

But in this page I would view also the left sidebar with layered navigation as in the category page (I would red boxes also in my custom collection results page)

This is my code to create a specific collection:
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => intval($categoria)]);
$collection->addAttributeToFilter('modello', ['eq' => $modello]);
$collection->addAttributeToFilter('cilindrata', ['eq' => $cilindrata]);
$collection->addAttributeToFilter('anno', ['eq' => $anno]);
$collection->load();

This is my xml file:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="TBRB\Engine\Block\Index" name="engine_index_index" template="TBRB_Engine::index.phtml" />
    </referenceContainer>
</page>

And this is index.phtml to render the results:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_productCollection = $block->getData('custom_parameter');
$_helper = $this->helper(Magento\Catalog\Helper\Output::class);
$_block = $block->getLayout()->createBlock('Magento\Catalog\Block\Product\ListProduct');
?>

<?php if (empty($_productCollection)) :?>

<?= $block->escapeHtml(__('We can\'t find products matching the selection.')) ?>

<?php else :?>
    <?php
        echo $_block->getToolbarHtml();
        echo $_block->getAdditionalHtml();

        //GRID MODE
        $viewMode = 'grid';
        $image = 'category_page_grid';
        $showDescription = true;
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
        $pos = $block->getPositioned();
    ?>
    <div class="products wrapper <?= /* @noEscape */ $viewMode ?> products-<?= /* @noEscape */ $viewMode ?>">
        <?php $iterator = 1; ?>

            <?php foreach ($_productCollection as $key => $value) : ?>
                <?php $_product = $objectManager->create('Magento\Catalog\Model\Product')->load($value['entity_id']); ?>
                <?= /* @noEscape */ ($iterator++ == 1) ? '
' : '

' ?>
                <div class="product-item-info" data-container="product-<?= /* @noEscape */ $viewMode ?>">
                    <?php
                    $productImage = $_block->getImage($_product, $image);
                    if ($pos != null) {
                        $position = ' style="left:' . $productImage->getWidth() . 'px;'
                            . 'top:' . $productImage->getHeight() . 'px;"';
                    }
                    ?>
                    <a href="<?= $block->escapeUrl($_product->getProductUrl()) ?>"
                       class="product photo product-item-photo"
                       tabindex="-1">
                        <?php echo $productImage->toHtml()  ?>

                        <?php
                        $_productNameStripped = $block->stripTags($_product->getName(), null, true);
                        ?>

                            <a class="product-item-link"
                               href="<?= $block->escapeUrl($_product->getProductUrl()) ?>">
                                <?= /* @noEscape */ $_helper->productAttribute($_product, $_product->getName(), 'name') ?>

                        <?php if ($_product->isAvailable()) :?>

<?= $block->escapeHtml(__('In stock')) ?>

                        <?php else :?>

<?= $block->escapeHtml(__('Out of stock')) ?>

                        <?php endif; ?>

                        <?= $_block->getReviewsSummaryHtml($_product, $templateType) ?>
                        <?= $_block->getProductPrice($_product) ?>
                        <?= $_block->getProductDetailsHtml($_product) ?>

                            <div class="product actions product-item-actions"<?= strpos($pos, $viewMode . '-actions') ? $block->escapeHtmlAttr($position) : '' ?>>
                                <div class="actions-primary"<?= strpos($pos, $viewMode . '-primary') ? $block->escapeHtmlAttr($position) : '' ?>>
                                    <?php if ($_product->isSaleable()) :?>
                                        <?php $postParams = $_block->getAddToCartPostParams($_product); ?>
                                        <form data-role="tocart-form"
                                              data-product-sku="<?= $block->escapeHtml($_product->getSku()) ?>"
                                              action="<?= $block->escapeUrl($postParams['action']) ?>"
                                              method="post">
                                            <input type="hidden"
                                                   name="product"
                                                   value="<?= /* @noEscape */ $postParams['data']['product'] ?>">
                                            <input type="hidden" name="<?php echo \Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php echo $postParams['data'][\Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED]; ?>">
                                            <?= $block->getBlockHtml('formkey') ?>
                                            <button type="submit"
                                                    title="<?= $block->escapeHtmlAttr(__('Add to Cart')) ?>"
                                                    class="action tocart primary">
                                                <?= $block->escapeHtml(__('Add to Cart')) ?>
                                            </button>
                                        </form>
                                    <?php endif; ?>

                                <div data-role="add-to-links" class="actions-secondary"<?= strpos($pos, $viewMode . '-secondary') ? $block->escapeHtmlAttr($position) : '' ?>>
                                    <?php if ($addToBlock = $block->getChildBlock('addto')) :?>
                                        <?= $addToBlock->setProduct($_product)->getChildHtml() ?>
                                    <?php endif; ?>

                            <?php if ($showDescription) :?>

                                    <?= /* @noEscape */ $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                                    <a href="<?= $block->escapeUrl($_product->getProductUrl()) ?>"
                                       title="<?= /* @noEscape */ $_productNameStripped ?>"
                                       class="action more"><?= $block->escapeHtml(__('Learn More')) ?>

                            <?php endif; ?>

                <?= ($iterator == count($_productCollection)+1) ? '
' : '' ?>
            <?php endforeach; ?>

<?php endif; ?>

Thank you!!


text:
Q: HTTP/2 Not working for my resources I am using Google Cloud Compute Engine running Apache 2.
I enabled HTTP2
sudo a2enmod http2

I added this to the top of my default-ssl.conf and made it global.
Protocols h2 h2c http/1.1

The default-ssl.conf runs properly with all my other commands except protocols.
Then I restarted apache and had zero errors.
sudo systemctl restart apache2

I ran a check and I still get the following:

All my resources are not running HTTP/2. Is there another step that I am missing?


text:
Q: Elasticsearch -- determine if a given time is within a TIME range Elasticsearch: v7.2
Application: Laravel v5.7
I am trying to query to whether my document belongs to a certain time range
Here's my Index's mav_time_aired field mapping:

Now I want to filter or fetch documents that are within a certain time range (I want to retrieve documents with mav_time_aired value within 06:00:00 to 09:00:00 OR 18:00:00 to 22:00:00, so I have this kind of query:
$temp =
[
    "bool" => [
        "should" => [
            [
                "range" => [
                    "mav_time_aired" => [
                        "gte" => "06:00:00",
                        "lte" => "09:00:00",
                        'format' => "HH:mm:ss",
                    ]
                ]
            ],
            [
                "range" => [
                    "mav_time_aired" => [
                        "gte" => "18:00:00",
                        "lte" => "22:00:00",
                        'format' => "HH:mm:ss",
                    ]
                ]
            ]

        ]
    ]
];

With the use of format property, according to the documentation, I must be able to literally format the data of the document into my desired format.
Now with the given query, I am expecting that I should be able to fetch my desired output, but unfortunately, the query results to:
No result found or Empty
But looking into my documents, I have these documents:

(These are just 2 from the documents I have determined that are supposed to be retrieved)
Did I miss something from my Elasticsearch query?

A: Since this isn't escalated yet, I resorted somewhat doing the hardcoded script elasticsearch provides for its users
I made a code something like this:
$temp =
[
    "bool" => [
        "must" => [
            "script" => [
                "script" => [
                    "source" => "(doc['mav_time_aired'].value.getHour() >= 6 && !(doc['mav_time_aired'].value.getHour() >= 9 && doc['mav_time_aired'].value.getMinute() >= 0)) || (doc['mav_time_aired'].value.getHour() >= 18 && !(doc['mav_time_aired'].value.getHour() >= 22 && doc['mav_time_aired'].value.getMinute() >= 0))",
                    "lang" => "painless"
                ]
            ]
        ]
    ]
];

and for the else I simply added the must_not boolean query of Elasticsearch:
$temp =
[
    "bool" => [
        "must_not" => [
            "script" => [
                "script" => [
                    "source" => "(doc['mav_time_aired'].value.getHour() >= 6 && !(doc['mav_time_aired'].value.getHour() >= 9 && doc['mav_time_aired'].value.getMinute() >= 0)) || (doc['mav_time_aired'].value.getHour() >= 18 && !(doc['mav_time_aired'].value.getHour() >= 22 && doc['mav_time_aired'].value.getMinute() >= 0))",
                    "lang" => "painless"
                ]
            ]
        ]
    ]
];

Then I was able to fetch my desired documents


text:
Q: multi-threading not improving performance in recursive c++ program consider this recursive multi-threaded program :
#include <iostream>
#include <thread>

#define NUMTHREADS 4
using namespace std;

int g[NUMTHREADS];

thread t[NUMTHREADS];

void task1(int x)
{
    if(x+1<NUMTHREADS)
        t[x] = thread(task1, x+1);
    for(int i=0;i<100000000;i++)
        g[x]++;
    if(x+1<NUMTHREADS)
        t[x].join();
}

int main()
{
    task1(0);
    for(int i=0;i<NUMTHREADS;i++)
        cout<<g[i]<<" ";
}

I'm expecting the thread overhead to be insignificant but in fact the runtime of the program increases linearly with the number of threads.
Here's some timings on my 6-core cpu:
NUMTHREADS = 1:
$ time ./a
100000000
real    0m0.330s
user    0m0.312s
sys     0m0.015s

NUMTHREADS = 2:
$ time ./a
100000000 100000000
real    0m0.742s
user    0m1.404s
sys     0m0.015s

NUMTHREADS = 3:
$ time ./a
100000000 100000000 100000000
real    0m1.038s
user    0m2.792s
sys     0m0.000s

NUMTHREADS = 4:
$ time ./a
100000000 100000000 100000000 100000000
real    0m1.511s
user    0m5.616s
sys     0m0.015s

Any idea why this might be?

A: The execution of your threaded program is being serialised because of extreme case of false sharing while accessing the elements of g. Here is a modified version of your program that evades false sharing and runs for the same amount of time with different number of threads as long as each thread could be assigned to a different CPU core:
#include <iostream>
#include <thread>

#define NUMTHREADS 4
using namespace std;

int g[NUMTHREADS*16];

thread t[NUMTHREADS];

void task1(int x)
{
    if(x+1<NUMTHREADS)
        t[x] = thread(task1, x+1);
    for(int i=0;i<100000000;i++)
        g[x*16]++;
    if(x+1<NUMTHREADS)
        t[x].join();
}

int main()
{
    task1(0);
    for(int i=0;i<NUMTHREADS;i++)
        cout<<g[i*16]<<" ";
}

The run times with 1 and with 4 threads:
$ time ./a.out
100000000
./a.out  0.45s user 0.01s system 98% cpu 0.466 total
                                         ^^^^^^^^^^^
$ time ./a.out
100000000 100000000 100000000 100000000
./a.out  1.52s user 0.01s system 329% cpu 0.462 total
                                          ^^^^^^^^^^^

And here is a short explanation of what happens. Modern x86 CPUs access main memory in blocks of 64 bytes, called cache lines (unless non-temporal store or load instruction are used, but this is not the case here). A single cache line of that size can accommodate up to 16 elements of an int array:
|    single cache line      |  another cache line
|------+------+-----+-------|-------+-------+------
| g[0] | g[1] | ... | g[15] | g[16] | g[17] | ...
+------+------+-----+-------+-------+-------+------
    ^      ^
    |      |
    |      +------ thread 1 updates this element
    |
    +------------- thread 0 updates this element

x86 is a cache-coherent architecture, which means that when a cache line is modified in a single core, the other cores are informed that their copy of the same cache line is no longer valid and has to be reloaded from an upper level memory storage, e.g. the shared L3 cache or the main memory. Since both shared last-level cache and main memory are much slower than the private caches of each core, this leads to much slower execution.
The modified version multiplies the index in g by 16:
|     one cache line        |  another cache line
|------+------+-----+-------|-------+-------+------
| g[0] | g[1] | ... | g[15] | g[16] | g[17] | ...
+------+------+-----+-------+-------+-------+------
    ^                           ^
    |                           |
    |                           +------ thread 1 updates this element
    |
    +------------- thread 0 updates this element

It is now clear that no two threads share the same cache line and hence the cache coherency protocol is not involved in the process.
The same effect is achieved when using stack variables. Thread stacks are usually big (at least several KiB) and aligned on memory page border, hence stack variables in different threads never share the same cache line. Also the compiler further optimises access to stack variables.
See this answer for somewhat more thorough explanation and another way to prevent false sharing. Although it is about OpenMP, the concepts apply to your case too.

A: Threads increase the performance when they run on separate cores, parallel to each other. So bind each thread to different cores by setting thread affinity to different cores.
  Its probably that your threads are running on single core.
so if thread 1,2,3,4 are allocated to diff cores 1 2 3 4 (dont use 0) then all will simulteneously increase the index. See $cpuinfo to see cores of your processor. and use thread->setAffinity(core_numer); to set the core for thread.

A: You should:

*

*compile your code with at least -O2 optimazation.

*declare variant g as volatile, otherwise it may be optimized out while compiling.
On my 2-core machine, thread=1 and thread=2 cost almost the same time.

A: I believe there is quite a lot of overhead in creating and joining threads like that (see this question C++11: std::thread pooled?). Check out something like OpenMP if you want to parallelize for efficiency.


text:
Q: Berry-Esseen result for triangular arrays Let $\{\{X_{n1},\ldots,X_{nn}\},n=1,2,\ldots\}$ be a triangular array of independent random variables where each row contains identically distributed random variables.  Let $E[X_{n1}]=\mu_n<\infty$ and $E[(X_{n1}-\mu_n)^2]=\sigma_n^2<\infty$.  Furthermore, let $E[|X_{n1}-\mu_n|^3]=\rho_n<\infty$.
Let $S_n=\sum_{i=1}^nX_{ni}$ be the sum of row $n$. It's well-known that the central limit theorem holds in this case: $\frac{S_n-n\mu_n}{\sqrt{n}\sigma_n}\xrightarrow{\mathcal{D}} Z$ where $Z\sim\mathcal{N}(0,1)$ -- the proof can be found in, say, Billingsley Ch. 27.
I am wondering what is known about the rate of convergence in this scenario. I am hoping for a Berry-Esseen type of result, where $|F_n(x)-\Phi(x)|\leq \frac{C\rho_n}{\sigma^3_n\sqrt{n}}$ with $F_n(x)=P\left(\frac{S_n-n\mu_n}{\sqrt{n}\sigma_n}\leq x\right)$, however, I cannot find it.  Does anything of this nature exist?  I would be happy with a convergence rate that is $\mathcal{O}\left(\frac{1}{n^a}\right)$ with $0<a\leq\frac{1}{2}$, and am willing to impose constraints on higher-order absolute moments.
I did notice the discussion on this question, however, my scenario is simpler, and might be tractable (since the random variables are independent).  Can anyone help?


text:
Q: Conditional Formatting formula to compare two cells when one cell has a delimiter So I have in column D QtyInvoiced and in column G QtysSent. For each row, QtyInvoiced is a single number e.g. 50. QtysSent on the other hand is of the delimiter format A_B_C where A,B and C are quantities. In each case, A+B+C would be the Total QtysSent.
How can I write a conditional formatting formula that compares (in the example above), the single value 50 in column D to A+B+C and higlights both cells in the particular row if they are not equal?
I imagine it requires using SPLIT inside the formula but not sure how to construct it to tell Google Sheets to compare the sum after splitting to the value in column D and then highlight both if they are not equal.

A: try this out:
Custom formula:
=$D2<>SUM(SPLIT($G2,"_"))

*

*


text:
Q: Getting sqlite data to scope in angular in hybrid mobile app Hi I am trying to create a mobile app using sqlite for storage. I have created a service for sqlite db and trying to get the data from database to controller scope, i tried with a callback, but doesn't work. please help.
this is the code in sqlite service
  self.getAll = function(table_name, cb) {

    this.db.transaction(function(transaction) {
        transaction.executeSql("SELECT * FROM " + table_name, [],
            function(tx, result) {

                cb(result.rows);
            },
            function(error) {
                console.log("Error occurred while getting the data.");
                console.log(error);
            });
    });
}

this is the code in the main controller
 function getData(data) {
 console.log("logging from getData");
 console.log(data);

 $scope.all = data;

}

sqlite.getAll("todo", getData);

console.log('logging results outside');
console.log($scope.all);

results don't get assigned to the $scope.all variable, what can i do to get the results, the console log from within the getData function works and shows the table data.

A: The last console.log($scope.all) will always be undefined because it runs before data arrives. Rather display the all variable in your html like {{ all }}
Or use a $watch on the variable, or do your assignments inside the function after the data arrives. Depends what you want to do.


text:
Q: How to do treeshaking with vuetify? I have vue application with vuetify.
To have treeshaking in vuetify I need to import in this way: import Vuetify from 'vuetify/lib'; according to the docs.
In my vuetify application, I don't have v-dialog.
When I compile my app code with import Vuetify from 'vuetify' I can see in the dist js bundle - that have vuetify code I which I don't use (like v-dialog, v-dialog--animated).
When I compile with import Vuetify from 'vuetify/lib'; I don't see un-used code (I don't see v-dialog).
But the downside I have to declare each component I want to use.
Is there an easy way to do tree shaking? for example, I expect from vue to search for unused code in the vuetify bundle and remove it.

A: If you import vuetify from vuetify/lib and use the VuetifyLoaderPlugin it should work.
As the docs suggest you can use a plugin file to setup vuetify, so
// plugins/vuetify.js
import Vuetify from 'vuetify/lib'
import Vue from 'vue'
Vue.use(Vuetify)

export default new Vuetify({/*optional options here*/})

and on the entry file of your application
// main.js
import Vue from 'vue'
import vuetify from './plugins/vuetify'

new Vue({
  vuetify
)}.$mount('#app')

Then you need to make sure that you are using VuetifyLoader. Here is an example config for webpack
// webpack.config.js

const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin')

module.exports = {
  plugins: [
    new VuetifyLoaderPlugin()
  ],
}

source

A: Do you use the Vue CLI? If not, I would suggest to do so. You just need few commands:
Install Vue CLI
npm install -g @vue/cli

This will globally install the Vue CLI (you'll maybe need administrator privileges)
For more information see: Installation|Vue CLI
Create you App
vue create my-app

This will setup your project for Vue.js and ask you some question. You can use the default set. After that you must change into the projects directory.
cd my-app

Install Vuetify
vue add vuetify

This will install the Vuetify framework. You can use the default settings. After that you've a project setup with Vue.js + Vuetify. Also the default setting is to use tree-shaking, while building the app at the end.
For more details, I have an example here, which also includes Electron at the end. But the steps up to conifguration of Vuetify are the same. With this setup, you automatically have tree shaking.


text:
Q: Tensorflow translate.py import error: No module named translate I'm trying to run Tensorflow's translate.py from a python console rather than through bazel -build, but I get an error at these two lines:
from tensorflow.models.rnn.translate import data_utils
from tensorflow.models.rnn.translate import seq2seq_model

ImportError: No module named translate

I've checked the folder to see that the "init.py" file is there, but python seems to think there is no such module as translate.
How can i fix this?

A: The best way to do this is to navigate to folder containing the translate module and running it. You can also download the translate module to any other place and run it. However, don't forget to change the above lines to:
from translate import data_utils
from translate import seq2seq_model

A: I resolved this issue by removing all the from tensorflow.models.rnn.translate statements, leaving just
import data_utils
import seq2seq_model

in translate.py and
import data_utils

in seq2seq_model.py.


text:
Q: Gravação em arquivo de informações em C Então, gente, eu estou fazendo um trabalho que consiste essencialmente no registro de informações referentes a filmes e séries em dois arquivos (um pra cada um).
Na seção de código filmes.c eu tenho todas as funções usadas pra manipular as informações referentes aos filmes (que é um vetor que é alocado e realocado dinamicamente), possuindo as funções de ADICIONAR, REMOVER e MODIFICAR filmes (o mesmo existe na seção series.c para as mesmas operações referentes às séries).
Segue o código de filmes.c abaixo:
 void adicionarFilme(Filmes *filmes, int *posF, int *nFilmes)
 {
      *nFilmes = *nFilmes + 1;

       filmes = (Filmes *) realloc(filmes, *nFilmes * sizeof(Filmes));

       if(!filmes)
       {
          exit(1);
       }

       printf("\n\n\tNome: ");
       scanf(" %[^\n]s", filmes[*posF].nome);
       printf("\n\n\tDiretor: ");
       scanf(" %[^\n]s", filmes[*posF].diretor);
       printf("\n\n\tElenco: ");
       scanf(" %[^\n]s", filmes[*posF].elenco);
       printf("\n\n\tAno: ");
       scanf("%d", &filmes[*posF].ano);
       printf("\n\n\tGenero: ");
       scanf(" %[^\n]s", filmes[*posF].genero);

       *posF = *posF + 1; //incrementa posição do vetor
 }

 void modificarFilme(Filmes *filmes, int *nFilmes)
 {
      char nomeMod[50];
      int i, j, k;
      int tamString;
      int op;
      int segue = 1;

      printf("\n\n\t Insira o nome do filme a ser modificado: ");
      scanf(" %[^\n]s", nomeMod);

      tamString = strlen(nomeMod);

      for(i = 0; i < *nFilmes; i++)
      {
          k = 0;
          for(j = 0; j < tamString; j++)
          {
              if(filmes[i].nome[j] != nomeMod[k])
              {
                  segue = -1;
                  printf("\n\n\tFILME NAO ENCONTRADO!\n\n");
                  return;
              }
              k++;
          }
          if(segue == 1)
          {
              printf("\n\t1 - Modificar nome\n\t2 - Modificar diretor\n\t3 - Modificar elenco\n\t4 - Modificar ano\n\t5 - Modificar genero\n\n\t");
              scanf("%d", &op);

              switch(op)
              {
                  case 1: printf("\n\tInforme o novo nome: \n\n\t");
                          scanf(" %[^\n]s", filmes[i].nome);
                          break;
                  case 2: printf("\n\tInforme o novo diretor: \n\n\t");
                          scanf(" %[^\n]s", filmes[i].diretor);
                          break;
                  case 3: printf("\n\tInforme o novo elenco: \n\n\t");
                          scanf(" %[^\n]s", filmes[i].elenco);
                          break;
                  case 4: printf("\n\tInforme o novo ano: \n\n\t");
                          scanf(" %d", &filmes[i].ano);
                          break;
                  case 5: printf("\n\tInforme o novo genero: \n\n\t");
                          scanf(" %[^\n]s", filmes[i].genero);
                          break;
            }
            return;
         }
     }
 }

 void removerFilme(Filmes *filmes, int *nFilmes)
 {
     char nomeDel[50];
     int i, j, k;
     int tamString;
     int op;
     int segue = 1;
     Filmes aux;

     printf("\n\n\t Insira o nome do filme a ser removido do catalogo: ");
     scanf(" %[^\n]s", nomeDel);

     tamString = strlen(nomeDel);

     for(i = 0; i < *nFilmes; i++)
     {
         k = 0;
         for(j = 0; j < tamString; j++)
         {
             if(filmes[i].nome[j] != nomeDel[k])
             {
                segue = -1;
                printf("\n\n\tFILME NAO ENCONTRADO!\n\n");
                return;
             }
             k++;
         }
         if(segue == 1)
         {
             filmes[i].ano = -1; //para verificar. Se ano for -1, filme será removido

             for(j = 0; j < *nFilmes; j++)
             {
                 if(filmes[j].ano == -1)
                 {
                    aux = filmes[j];
                    filmes[j] = filmes[j+1];
                    filmes[j+1] = aux;
                 }
             }
         }
      }

      *nFilmes = *nFilmes - 1; //decrementa numero de filmes

      if(*nFilmes == 0)
      {
         return;
      }

      filmes = (Filmes *) realloc(filmes, *nFilmes * sizeof(Filmes));

      if(!filmes)
      {
         exit(1);
      }
 }

 void imprimeFilmes(Filmes *filmes, int *nFilmes)
 {
     int i;
     int x = 1;

     printf("\n\tFILMES\n");
     for(i = 0; i < *nFilmes ; i++)
     {
         printf("\n\tNOME:\t%s", filmes[i].nome);
         printf("\n\tDIRETOR:\t%s", filmes[i].diretor);
         printf("\n\tELENCO:\t%s", filmes[i].elenco);
         printf("\n\tANO:\t%d", filmes[i].ano);
         printf("\n\tGENERO:\t%s", filmes[i].genero);

         printf("\n\n");
         x++;
     }
 }

 void managementFilmes(int codigo, Filmes *filmes, int *posF, int *nFilmes)
 {
     if(codigo == 1)
     {
         adicionarFilme(filmes, posF, nFilmes);
     }
     if(codigo == 2)
     {
         removerFilme(filmes, nFilmes);
     }
     if(codigo == 3)
     {
         modificarFilme(filmes, nFilmes);
     }
     if(codigo == 4)
     {
         imprimeFilmes(filmes, nFilmes);
     }
     if(codigo == 0)
     {
         exit(1);
     }
}

O código pra series.c é basicamente o mesmo, então acho que não há necessidade de linkar.
> Bom o que eu gostaria de uma ajuda de vocês é a seguinte:
- Eu preciso que todos os filmes que sejam inseridos, sejam gravados em um arquivo (de preferência .txt), um abaixo do outro (como uma listinha).
- A cada vez que o programa for rodar eu preciso que os filmes que vão ser adicionados sejam adicionados logo depois do último exemplar da lista.
Imagino que a solução desse problema não seja la muito complicada, mas eu realmente estou meio perdido quanto a como fazer isso.
Uma ajuda com o próprio código pra manipulação das informações do arquivo seria imensamente apreciada.
Por fim, pra efeito de referência, segue o código do programa principal (principal.c).
int main()
{
Filmes *filmes;
Series *series;

int posF = 0;
int posS = 0;

int numeroFilmes = 0;
int numeroSeries = 0;

int isFirstTimeF = 0;
int isFirstTimeS = 0;
char codA;
int codB;

do{
    /**********************************
        Código A:

        F - Filmes
        S - Series
        X - Encerra
    ***********************************/
    printf("\n\tCOMANDOS: ");
    printf("\n\n\tF - Filmes\n\n\tS - Series\n\n\tX - Encerra\n\n\t");
    scanf("%c", &codA);

    if(codA == 'F' || codA == 'f')
    {
        /**********************************
            Código B:

            1 - Adicionar filme
            2 - Remover filme
            3 - Modificar informações de um filme
            4 - Imprime registro de filmes
            0 - Sair
        ***********************************/
        printf("\n\tCOMANDOS: ");
        printf("\n\n\t1 - Adicionar filme\n\n\t2 - Remover filme\n\n\t3 - Modificar informacoes de um filme\n\n\t4 - Imprime registro de filmes\n\n\t0 - Sair\n\n\t");
        scanf("%d", &codB);

        if(codB == 1 && isFirstTimeF == 0)
        {
            filmes = (Filmes *) malloc(sizeof(Filmes));
            isFirstTimeF = 1;
        }

        managementFilmes(codB, filmes, &posF, &numeroFilmes);
    }

    if(codA == 'S' || codA == 's')
    {
        /**********************************
            Código B:

            1 - Adicionar série
            2 - Remover série
            3 - Modificar informações de uma série
            4 - Imprime registro de séries
            0 - Sair
        ***********************************/
        printf("\n\tCOMANDOS: ");
        printf("\n\n\t1 - Adicionar serie\n\n\t2 - Remover serie\n\n\t3 - Modificar informacoes de uma serie\n\n\t4 - Imprime registro de series\n\n\t0 - Sair\n\n\t");
        scanf("%d", &codB);

        if(codB == 1 && isFirstTimeS == 0)
        {
            series = (Series *) malloc(sizeof(Series));
            isFirstTimeS = 1;
        }

        managementSeries(codB, series, &posS, &numeroSeries);
    }

}while(codA != 'X');

free(filmes);
free(series);

return 0;
}

----------------------------------------------------------------------------------------------------------------------------------
Já agradeço qualquer ajuda de antemão!
Edit: Definição das estruturas de filmes e séries:
    #include<stdio.h>
    #include<stdlib.h>

    //Estruturas principais

    typedef struct filmes
    {
        char nome[50];
        char diretor[30];
        char elenco[80];
        int ano;
        char genero[20];

    }Filmes;

    typedef struct series
    {
        char nome[50];
        char criador[30];
        char elenco[80];
        int ano;
        int numeroTemporadas;
        char genero[20];

    }Series;

    //Cabeçalho das funções de funções.h

    //FILMES
    void adicionarFilme(Filmes *filmes, int *posF, int *nFilmes, FILE *arq);
    void modificarFilme(Filmes *filmes, int *nFilmes);
    void removerFilme(Filmes *filmes, int *nFilmes);
    void imprimeFilmes(Filmes *filmes, int *nFilmes);
    void managementFilmes(int codigo, Filmes *filmes, int *posF, int *nFilmes, FILE *arq);

    //SÉRIES
    void adicionarSerie(Series *series, int *posS, int *nSeries);
    void modificarSerie(Series *series, int *nSeries);
    void removerSerie(Series *series, int *nSeries);
    void imprimeSeries(Series *series, int *nSeries);
    void managementSeries(int codigo, Series *series, int *posS, int *nSeries);


text:
Q: % CHANGE IN NEGATIVE BASE I need to find correct formula to calculate percentage change from a negative base. Assume this is my company financials where

Year-$1$ Profit: Negative $80$ Crore
Year-$2$ Profit: Negative $125$ Crore, and
Year-$3$ Profit: $200$ Crore.

Now evaluating Year-$3$ performance with Year-$2$ & Year-$1$ I get $350\%$ increase in Year-$3$ compared to Year-$1$ whereas I get $260\%$ increase in Year-$3$ as compared to Year-$2$ (taking the denominator as absolute base) But one fundamental error in it is that if we see absolute change it is more in Year-$3$ and year-$2$ comparison whereas actual $\%$ change shown is less. It is because of the larger base, in such a scenario what formula I should use to get a correct $\%$ change


text:
Q: Filling in remaining kwargs with unittest.mock.ANY Let's say I have class Foo with method bar:
class Foo:
    # ...

    def bar(self, **kwargs):
        # do something important with kwargs["important_arg"]

Now I want to test this and I use the following approach:
mock_foo = Mock()
mock_foo.bar(important_arg="hello", unimportant_arg="world")

I only care that important_arg was "hello", other args don't matter. But
mock.assert_called_with(important_arg="hello", **ANY)

fails (at least in pytest) with:
TypeError: pytest_mock.plugin.wrap_assert_called_with() argument after ** must be a mapping, not _ANY

What is the correct way to express:

The method must be called such that keyword parameter important_arg was given as "hello"; I don't care about other keyword args

? Or do I have to dig in call_args?

A: The way I solved this was by digging into call args. For example:
mock.assert_called_once()
assert 'important_arg' in mock.call_args.kwargs
assert mock.call_args.kwargs['important_arg'] == 'hello'


text:
Q: How widely supported are nested FeatureCollections in GeoJSON? I know that FeatureCollections inside FeatureCollections are not supported according to the GeoJSON spec, but I have seen multiple implementations that do support it. Are nested feature collections widely supported, and how do implementations that don't support them handle them?
Are nested attributes widely supported?


text:
Q: How to only fire event if flipswitch is manually switched I've created an jQuery Mobile flipswitch like this
<select id="flip" data-role="flipswitch">
    <option value="animal">Lion</option>
    <option value="flower">Rose</option>
</select>

and I listen to changes on this flipswitch
$( document ).on( 'change', '#flip', function( e ) {
   console.log( 'changed' );
}

But I don't want the event to be triggered if I change the value of the flipswitch by
$( '#flip' ).val( 'flower' ).flipswitch( 'refresh' );

How do I check if a flipswitch has changed by interacting with it directly or setting a value and refreshing the flipswitch?
I've created an example of the unwanted behavior under this JSFiddle.

A: You need to use .on() to attach change event and .off() to remove it - before you bind it again - whenever you change the value dynamically.
Wrap all your code in pagecreate event, it is equvilant to .ready().
$(document).on("pagecreate", "#main", function () {

    /* change event handler */
    function flipChanged(e) {
        var id = this.id,
            value = this.value;
        console.log(id + " has been changed! " + value);
    }

    /* add listener - this will be removed once other buttons are clicked */
    $("#flip").on("change", flipChanged);

    $('#setlion').on('vclick', function (e) {
        $("#flip")
            .off("change") /* remove previous listener */
            .val('animal') /* update value */
            .flipswitch('refresh') /* re-enhance switch */
            .on("change", flipChanged); /* add listener again */
    });

    $('#setrose').on('vclick', function (e) {
        $("#flip")
            .off("change")
            .val('flower')
            .flipswitch('refresh')
            .on("change", flipChanged);
    });
});

Demo


text:
Q: What exactly is  visually? Does the scroll bar belong to <html> or <body>?
I've been writing  for every html file,but don't know exactly what it is.

A: As for css definitions, the standards states that you can not define any styles on the html tag (as the html tag itself does not represent the view, it is the body, as Mauris said). But many browsers support setting style on the html anyway.
Example
This shows the page background as red, with the body as a <div> like green box:
<html style="background-color:red;overflow:scroll;">
  <head>
    <title>Page</title>
  </head>
  <body style="margin:10px;background-color:green;overflow:scroll;">
    Page content
  </body>
</html>

If you remove the style definition on the html tag, the background color and scrollbar on body is filled for entire page. The margin is only applied for content inside the body.
<html>
  <head>
    <title>Page</title>
  </head>
  <body style="margin:10px;background-color:green;overflow:scroll;">
    Page content
  </body>
</html>

A: The root element (<html>) is, according to CSS 2.1, a rendered block element like any other. It does not represent the viewport, so according to the standard it is not the element that gives the viewport its scrollbar — in fact the scroll bar does not belong to any element.
If anything represents the viewport, it is the concept of the 'initial containing block', however this is 'a level up' from the root element and can't be addresses by CSS or the DOM.
However, there are a few special cases that confuse the matter. In particular, Ionut's tests give those results because of the special behaviour specified in section 14.2:

The background of the root element becomes the background of the canvas and covers the entire canvas

That is, the root element's background spills out of its actual dimensions to fill the whole viewport and document. Secondly:

For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of 'transparent' for 'background-color' and 'none' for 'background-image', user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas, and must not paint a background for that child element

That is, although the <body> element very definitely does not represent the viewport, its background can spill out of its dimensions in the same way. This is only present as a backwards compatibility measure, as authors had grown used to specifying backgrounds on the <body> element.
So you can't use background-color to tell where the root element's dimensions or the body element's dimensions lie. A better approach is to set document.documentElement.style.border= 'dotted red 1px'. This demonstrates that the root <html> element has the dimensions of the document, not the viewport.
Except in IE Quirks Mode, where it goes around the scrollbar. In Quirks Mode, <body> represents the viewport; setting body.style.overflow.hidden removes the page's scrollbar. This is definitely wrong; you don't want Quirks Mode.
Confusing the matter further, there are some funny non-standard special-case behaviours that imply the root element is the viewport.
In IE (Standards Mode), the root element's 'overflow' property is set to 'scroll', and you can set it to 'hidden' to remove the viewport scrollbar. Also 'offsetHeight' is the height of the viewport and not the actual height of the element as demonstrated by the border.
In other browsers the offsetHeight is the expected value, but (presumably for compatibility) you can still set document.documentElement.style.overflow to 'hidden' (from the default 'visible') to remove the viewport scrollbar. Curiously in Opera the currentStyle.overflow property will still show 'visible' when you have done this.
The upshot is, if you want to ensure the viewport has no scrollbar, you write:
html { overflow: hidden; height: 100%; }

and ensure you use a Standards Mode doctype. The 'height: 100%' rule takes care of the case where a browser follows the standard and doesn't map the root element's scrollbar onto the viewport: this sets the height to match the viewport via the 'initial containing block', so there will be no need for the parent viewport to show a scrollbar.

A: Given the following markup and styling:
<!DOCTYPE html>

<html>
<head>
<title></title>
<style type="text/css">
html {
 background: green;
 overflow:scroll;
}
body {
 background: red;
 overflow:scroll;
}
</style>
</head>
<body>

</body>
</html>

We get the following visual results:
Firefox 3.5
Firefox 3.5 http://img98.imageshack.us/img98/3448/ff35.png
Internet Explorer 6
Internet Explorer 6 http://img98.imageshack.us/img98/870/ie6.png
Opera 10
Opera 10 http://img22.imageshack.us/img22/1395/o10.png
Google Chrome 3
Google Chrome 3 http://img193.imageshack.us/img193/4300/82451373.png
So, we can style the HTML element. In fact some people use this in combination with the BODY tag to get complicated backgrounds.

A: <html> has no visual. It just defines that the document is a html document and it contains the head and the body.
It's the body that has the view.
The scroll bar belongs to the window if you talk about DOM.But in CSS, you set scrollbar styles through <body>
If you use Firebug on Firefox and use the element inspector (the one where you can move your mouse and point around elements of the HTML document, and you point it at blank space where there's no elements there, it points to the <body>.

A: It's just a tag which we can say let's other tags work or to define what those tags are for. Actually Scroll bar belongs to <BODY> and <BODY> belongs to <HTML>.


text:
Q: What is the most efficient option to stream a live video feed via http? I'm trying to live stream my webcam and embed it on a webpage. In theory I achieved that by using VLC streaming.

I consume that stream locally from my webpage like this;

It works!

<video width="700" src="http://127.0.0.1:1234" autoplay type="video/ogg;">   </video>

This is working but there is a huge delay and lag when I share my screen and practically not working at all when I pick my webcam as a source.
Is there any more efficient way to achieve this via VLC player? If not what would be best option(framework, library, protocol, format etc.) to do the job?


text:
Q: Changing class attrib of element still calling old event Scenario
I have anchor with class=anchor and clicking it will change it's own class to anchor2. Two click event: anchor & anchor2 will alert($(this).attr('id')).
Problem
The problem is, after changing it's class to anchor2, it still calling the old event which alerting the anchor2 class.
What's going on? https://jsfiddle.net/3kzs7n9r/13/
EDIT
Here's my code:
Click me

A: you need to register your click event differently, as when you are registering the anchor2 event that element is not present on DOM.

A: find the below snippet it may help you
instead of having click event for CLASS. making it for ID it will as you required
on click check condition and then based on condition change class

$('#anchor').on('click', function () {
 alert('anchor clicked with class: '+$(this).attr('class'));
  if($(this).hasClass("anchor")){
   $(this).removeClass('anchor').addClass('anchor2');
  }else{
    $(this).removeClass('anchor2').addClass('anchor');
  }
});

Click me


text:
Q: Redis - Make failover master return to slave state and master take up it's old master role I have a Redis v4.0.7 cluster consisting of 4 servers. These 4 servers are all running Ubuntu v17.10 64 bit Virtual Machines (in VirtualBox) that I have on my Windows PC. I have shifted all the slaves 1 server and will be using M1 for master 1 as well as S1 for slave 1 in the following explanation of my "issue".

*

*192.168.56.101 (with a master on port 7000 (M1) and slave on port 7001 (S4))

*192.168.56.102 (with a master on port 7000 (M2) and slave on port 7001 (S1))

*192.168.56.103 (with a master on port 7000 (M3) and slave on port 7001 (S2))

*192.168.56.104 (with a master on port 7000 (M4) and slave on port 7001 (S3))

I am fiddling a little bit with the setup to check if the failover "works".
Therefore I have tried shutting down M2, which means that S2 takes over and becomes the master. This works as intended. However if I start up the (old) M2 again it is now a slave and remains as such until I shut S2 down at which point it will take over the master role again.
I was wondering if there is a certain command that I can issue to the slave that has taken over the master role which makes it take over it's (old) slave role and hand over the master role to the (old) master, in this case M2.
I have tried googling the "issue", but to no avail.

A: You can do this by running:
redis-cli -h M2_IP_ADDRESS M2_PORT CLUSTER FAILOVER

Above command will make manual failover. M2 will became master and S2 slave.


text:
Q: IzPack 5.1 - use user input variables in bash script without substitution Hopefully someone could help me here with following problem – tried to find a solution for this for weeks but unfortunately wasn't able to find one.
I am using IzPack (recently updated to 5.1) as an installer for a software package. This package contains multiple executable files (bash scripts) which use variables inside. These variables are filled with values provided by the user during the installation process (user input panel).
The problem I have is that all these values get substituted in the bash-file if it is marked as "parsable" – otherwise (if not marked as "parsable") the values are not substituted but it is not possible to access them during script execution. I have to access the values of these variables but it is no option for me to substitute them in the bash scripts because these files are not deleted after the installation is done and have to stay on the disk. In case of variable substitution all variables, also passwords, are substituted and could be seen by everybody, having read access to the file, in plaintext.
Has anyone got a solution or idea how this could be achieved using izPack? I also thought about encrypting the passwords – there exists a processor for it in izPack but unfortunately no documentation.
Thanks in advance

A: How about sanitizing or removing the files in question using the ProcessPanel?
This is typically run after the InstallPanel and before the installation is finished.


text:
Q: Dependency injection with Global.asax I am using dependency injection for the inject interface with the classes
I use it in the Global.asax like this
  new UnityContainer().RegisterType<IBookingService, BookingService>()

and controller
IBookingService bookingService

Now the thing is I want to change the injected implementation class for an interface in the controller level
How can I do it with a controller level?
i want to do some things like this in controller level
private readonly IBookingService bookingService;

if(countryCode = SE ){

bookingService = new bookingSE();

}

else IF (countryCode = NO ){

bookingService = new bookingNO();

}

i want to use Dependency injection for this

A: Make sure that you use the Unity.Mvc NuGet package. This will add a App_Start\UnityConfig.cs file to your project and you can add the registrations in its RegisterTypes method as follows:
container.RegisterType<IBookingService, BookingService>();

Perhaps you are already doing this, but I wanted to make sure since your exact code example with the new UnityContainer().RegisterType will not work.
Another interesting thing that this package does can be viewed in the App_Start\UnityWebActivator.cs file:
DependencyResolver.SetResolver(new UnityDependencyResolver(container));

This line will register the unity container as standard MVC DependencyResolver. This allows constructor injection to be applied to your controllers. With this you can define your controller as follows:
public class MyCoolController : Controller
{
    private readonly IBookingService bookingService;

    public MyCoolController(IBookingService bookingService)
    {
        this.bookingService = bookingService
    }

    public ActionResult Index()
    {
        // your usual MVC stuff here.
    }
}

In almost all cases, the use of constructor injection is advised over all forms of injection so stick with constructor injection unless there is no other way. And if you think there's no other way, please to ask here at Stackoverflow. We might be able to give some feedback on your code and design.

A: Just call Resolve
var bookingService= container.Resolve<IBookingService>()


text:
Q: After Code Signing for Gatekeeper: cannot longer access keychain items for my app I want to code sign my Mac software to make it ready for Gatekeeper and OS X Lion.
So I changed to the build settings in Xcode and selected my Developer ID certificate. Building my project was successfully.
But if I run this new app I cannot longer access the keychain items of the app!
If I remove code signing everythings works ok.
Anybody knows a solution for that problem?


text:
Q: Is there any IDE or plugin that highlights the selected react component in the browser? There are times when it's hard to read which code corresponds to which part of the page in the browser. It would be very helpful if the component or jsx tag that you select in the editor gets highlighted in the browser.
Is there any IDE (vscode, webstorm, etc) or a plugin that does this?
And if not, any suggestions on how to approach the problem?


text:
Q: Plugin de CRUD para Wordpress Alguém conhece uma ferramenta (plugin) que permita se customizar CRUDS simples e acessá-los na interface do wordpress?

A: Não é uma interface, mas só apontando aqui que não é necessário nenhum plugin pra fazer CRUDs genéricos dentro do WordPress. O sistema usa uma classe global chamada $wpdb que já traz consigo uma conexão aberta ao banco, então é só usá-la como vc usaria uma instância de PDO, por exemplo.
Exemplo do Codex:
<?php
    global $wpdb;

    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM $wpdb->postmeta
             WHERE post_id = %d
             AND meta_key = %s
            ",
            13, 'gargle'
            )
    );

Da mesma forma que vc pode rodar consultas contra as tabelas padrão do WP (como no exemplo) você pode rodar contra qualquer outra tabela que esteja no mesmo banco de dados.

A: Conheço pelo menos três:

*

*http://codecanyon.net/item/xcrud-data-management-system-php-crud/3215400

*http://www.dadabik.org/index.php?function=dadabik_crud_wordpress

*http://wpdatatables.com/crud-system-in-wordpress/
Recomendo ver as features se atendem teu caso (que você poderia ter detalhado um pouco melhor talvez). Eu gosto mais do wpDataTables


text:
Q: How to make chrome display on the top opened in selenium [Mac OS X] When I use Firefox browser then the window is on top, but for Chrome it is not.
So, how can I make Chrome window be on top?
I have seen the selenium2library\keyword\_browsermanagement.py, but can't find any useful keyword(s).

A: Found the solution worked for our project.
Before driver.get(url) we execute the following command:
osascript -e tell application "${browserName}"
   activate
   delay 1
   end tell

browserName could be safari/chrome/firefox

A: Have you tried the Get Window Identifiers, Get Window Names, Get Window Titles, List Windows keywords available in the Selenium2Library?  If you've success with one of them, you should them be able to Select Window and bring it to the forefront.
We could use a bit more context in your question, do you have multiple browsers open at once?  If so, why?


text:
Q: How do I use Web.Config transform on my connection strings? In my current project, I have some connection strings that are valid for local development machines:
<configuration>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="Data Source=localhost;Initial Catalog=MyDB;Integrated Security=SSPI"
  </connectionStrings>
....
</configuration>

How would I use the Web.Config transforms to convert from this expression to one valid for our production server? The production server one would look something like:
<configuration>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="Data Source=IPAddress,Port;Initial Catalog=SomeOtherDB;User ID=TopSecretUsername;Password=SecurePassword"
  </connectionStrings>
....
</configuration>

The syntax isn't obvious to me, and I'm completely failing at grokking the page on it.

A: You shouldn't need to create a new file, it should be in the Solution Explorer, expand Web.config, and open Web.Release.config.
Scott Allan has a good video on it here (under Configuration and Deployment > Config Transformations).

A: This works for me but I too have found it to be a bit flakey at times.
You will need to create another file called Web.Config.Release and fill it with the following:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

  <connectionStrings>
    <add name="local" connectionString="Data Source=IPAddress,Port;Initial Catalog=SomeOtherDB;User ID=TopSecretUsername;Password=SecurePassword"
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
  </connectionStrings>

  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />

  </system.web>
    <appSettings>
        <add key="default_db_connection" value="local" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
    </appSettings>
</configuration>