Q: Practical Tcpdump examples? I want to collect tcpdump examples, as many as possible!

E.g.: how to filter FTP passwords on eth0; OR how to filter HTTP 404 errors, etc.

A: It doesn't do any filtering, but this example creates a handy continuous packet sniffer:
tcpdump -n -C 128 -W 100 -z /home/user/compress_logs.pl -i br0 -w /home/user/packetlogs/packetlog.pcap &

*

*-n don't do reverse lookup on IPs, don't convert port numbers to text descriptions, don't convert MAC addesses to names, etc..

*-C 128 rotate capture files every 128,000,000 bytes

*-W 100 limit the number of capture files being rotated (see -C) to 100

*-z /home/user/compress_logs.pl run script compress_logs.pl on each rotated capture file

*-i br0 capture on interface br0

*-w /home/user/packetlogs/packetlog.pcap use file name /home/user/packetlogs/packetlog.pcap

*& this is parsed by bash; indicates that the command should be run in the background (asynchronously)

Put it in /etc/rc.local to run on boot. It captures all packets on interface br0, which could be two interfaces in-line as a tap or two interfaces hooked to a passive tap, or one interface hooked to a mirrored switch port (I've used all three in practice)
It writes ~128MB files and will automatically rotate up to 100 of them. When it captures 128MB of data, it will close the file, open a new one, and fork the specified command with the old filename as an argument - in this case a little Perl script that compresses the previous capture file for quicker transfer off the IDS server.
I use this when I have to monitor a connection for a long time (like a day or two) and need to go back and find an event that occurred at a specific time. The small files are much easier to handle in Wireshark than one huge pcap file.

A: Capture only HTTP POST data:
tcpdump tcp[2:2] = 80 and \(tcp[20:4] = 1347375956
or tcp[24:4] = 1347375956
or tcp[28:4] = 1347375956
or tcp[32:4] = 1347375956
or tcp[36:4] = 1347375956
or tcp[40:4] = 1347375956
or tcp[44:4] = 1347375956
or tcp[48:4] = 1347375956
or tcp[52:4] = 1347375956
or tcp[56:4] = 1347375956
or tcp[60:4] = 1347375956\)

A bit unwieldly but certainly useful. tcp[2:2] captures, starting from position 2 of the TCP header, 2 bytes (which are the port, port 80 being for HTTP traffic).
Then we want to compare the first 4 bytes of TCP data to 'POST'. The TCP header is minimum 20 (decimal) bytes, but since the TCP options are variable length, from 0 to 40 bytes (padded to a 32-bit boundary and starting at ), we have to test every 4 bytes from 20 to 60 (decimal). Finally, 1347375956 is the base10 big-endian binary representation of the ASCII text 'POST'. Use the values below for other HTTP types:

*

*GET 1195725856 (includes the space after 'GET' which is needed because we are comparing with 4 bytes)

*POST 1347375956

*PUT 1347769376 (includes space)

*DELETE 1145392197 (just 'DELE', actually)

For other types, convert the 4 ASCII characters to hex (you must use 4 characters exactly), then treat the hex bytes as one number and convert it to decimal. For example, POST is 50 4f 53 54. 504f5354 converted to decimal is 1347375956.

A: Capture everything to a file (so you can analyze it later with Wireshark or something):
sudo tcpdump -i en0 -s0 -w ~/capture.pcap

*

*-i en0 capture on interface en0

*-s0 use the whole packet (don't truncate -- snarf 0)

*-w ~/capture.pcap write to packet capture file ~/capture.pcap

A: Filter-making cheat sheet:
http://staff.washington.edu/dittrich/talks/core02/tools/tcpdump-filters.txt

A: If you want to monitor clients DNS requests on an OpenWRT router:
tcpdump -n -i br-lan dst port 53

*

*-n don't do reverse lookup on IPs, don't convert port numbers to text descriptions, don't convert MAC addesses to names, etc..

*-i br-lan capture on interface br-lan

*dst port 53 filter destination port 53, the port for DNS service


Q: Import different openapi.json file to spring boot app I have custom openapi.json file and empty spring boot app. When I start the app I want it to import that file and show it in swagger-ui URL.
I couldn't find how to do it. All answers were how to generate openapi.json file from code. But my task is opposite.


Q: EXTJS 4.1.1. iframes reloads when switching tabs in TabPanel on Firefox: I've got a problem with PDF's in the TabPanel (only on Firefox). They are reloading everytime I switch tabs. The PDF is in a iframe.
Because of it the user can not compare two PDF files. When you click a tab with a PDF it loads 10 seconds, then you switch to a second tab and it also loads 10 seconds and so on....
I know this problem with Firefox has been around for years (which relates IFRAME, OBJECT, elements, FF reinitializes the objects, if their size changes).
It cannot be that there is no solution for this problem.
However, I have not found any for Extjs4 yet.
It would be great if someone could help me with it.


Q: Javascript regex to strip selective html tags I am trying to strip all (except some) html tags from a string using regex. What I am trying currently trying is as follows:
var a = "

This is a test

";
var b = a.replace(/(\<|\<\/)[^\>,p,li,br,b]*\>/ig,"");

but b's value is returned as "

This is a test

"
It seems any tags that contain even a single instance of [>,p,li,br,b] are not being removed, as here all pre, span and p contains the character p. However, I only want to ignore the exact characters in [^\>,p,li,br,b].
The output I am expecting is "
This is a test
".
what am I doing wrong ?

A: var a = "

This is a test

";
var b = a.replace(/\<(?!\/?(p|li|br|b)[ >])[^>]*\>/ig,"");

This regex matches the leading < or </ only if it is not followed by one of the tag names you want to keep p, li, br, b (followed by a space or closing >, so that it doesn't think
 is
).
Then it matches everything up to the closing >.

A: See this answer.
That said, square brackets [] match on single characters, not words - for more information on what yours is doing, see the bottom of this answer.  Instead, you would need to use parentheses (?:p|li|br|b) to match words - the ?: is used to avoid capturing.  Also, the parentheses would occur outside of the square brackets.
Since you're using a negative match you may wish to look into lookarounds; specifically, the section on Positive and Negative Lookbehind.

[^\>,p,li,br,b] translates to not > and not , and not p and not , and not l and not i and not , and not b and not r and not , and not b.


Q: Difficulty deploying lumen app I'm trying to deploy a small application to my remote server, however, I seem to be having difficulty with some of the routes.  Bare in mind that everything works on my local machine.
Here is what I've done:

*

*Uploaded the entire project to /home/user/app

*Moved contents of /home/user/app/public to /home/user/public_html/api

*Modified /home/user/public_html/api/index.php from:

$app->run();
to
$request = Illuminate\Http\Request::capture();
$app->run($request);

...this allowed my first route to work, but I cannot load any other routes such as:
http://www.mywebsite.com/api/v1/book
Please note that only http://www.mywebsite.com/api is the only route that loads correctly.
My routes.php looks like this:
$app->get('/', function() use ($app) {
    return "Lumen RESTful API";
});

$app->group(['prefix' => 'api/v1','namespace' => 'App\Http\Controllers'], function($app)
{
    $app->get('book','BookController@index');

    $app->get('book/{id}','BookController@getbook');

    $app->post('book','BookController@createBook');

    $app->put('book/{id}','BookController@updateBook');

    $app->delete('book/{id}','BookController@deleteBook');
});

My .htaccess is as follows:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

The error I am receiving:

Let me know if you need any more information?
Any help would be greatly appreciated!

A: Change route group prefix to:
$app->group(['prefix' => 'v1'


Q: переадресация RedirectMatch исключить параметр На сервере в фоновом режиме происходит ресайзинг изображений, поэтому для контроля кэша сделан след. костыль из переадресаций:
.htaccess
RedirectMatch "^/images/uploaded/([0-9]+)/([^\.]+)\.(png|jpg|gif)$" /image_view.php?user_id=$1\&file=$2.$3

<?php
if (isset($_GET['file']) && isset($_GET['user_id'])) {
    $path_to_image = 'images/uploaded/' . intval($_GET['user_id']) . '/' . $_GET['file'];
    $modified = filemtime($path_to_image);

    header('Location:' . $path_to_image . '?' . $modified, true, 303);
}

Как не сложно догадаться, тут происходит зацикливание, т.к. php генерирует переадресацию по тому же пути, с добавлением параметра $modified , как исключить из htaccess эту переадресацию и учитывать обращения к (png|jpg|gif) без символа "?"

A: Может быть стоит заменить RedirectMatch на RewriteCond и RewriteRule
RewriteEngine On

RewriteCond %{QUERY_STRING} ^$
RewriteCond %{REQUEST_URI} ^\/images\/uploaded\/(\d+)/([^\.]+)\.(png|jpg|gif)$
RewriteRule .* http://your.site/image_view.php?user_id=%1&file=%2.%3 [L]


Q: Propositional S5: is there a consistent set requiring continuously many worlds? A recent question asked whether in systems of modal propositional logic having the "finite model property" there are consistent sets of sentences that were not satisfied by a finite model. @Carl Mummert gave an example for S5 showing there are in fact such sets.
A "world" in such models may be taken to be a set of sentence letters, or equivalently a function from the set of sentence letters to {1, 0}, or etc. Since there are countably many sentence letters, a model that contains all possible worlds has continuously many worlds. (Let's assume we're using S5 models with no "accessibility relationship" between worlds, so we may disregard models which are partitioned by that relationship.)
Varying the original question, is there a consistent set of sentences that is not satisfiable in any S5 model with a countable set of worlds? Is there a set requiring continuously many?

A: I assume the intention is to find a countable set of sentences that has no countable model. That is essentially the negation of the Lowenheim-Skolem theorem.
Most modal logics have the Lowenheim-Skolem property, because they can be translated into first-order logic. This method can also be used to prove a compactness theorem for these logics. So these logics will have countable models for all countable consistent theories (this means a countable number of worlds, for propositional logics).
For propositional S5 there is a particularly simple translation. Each propositional variable $A$ of the modal logic becomes a unary predicate $A(x)$ of first-order logic. The modal operators are translated as quantifiers: $\Box(A \land B)$ becomes $(\forall w)[A(w) \land B(w)]$, etc. This translation preserves satisfiability. The objects in the first-order system correspond exactly to the worlds in the modal system, and the semantics match perfectly when the modal system is S5.  For other modal systems, more complicated translations are required.


Q: Why can't backpropagation be used for binary threshold neurons I was reading that backpropagation can't be used for binary threshold neurons.
Binary threshold neurons calculate a cost using some weights, so why can't those weights be changed with backpropagation?

A: Strictly speaking, binary threshold neurons have piecewise constant activation functions such that the derivative of this activation function and thus the weight change is always zero (the undefined derivative at the step of this function is practically irrelevant).
If the step is approximated by a sigmoidal activation with a very large but finite slope, then backprop can theoretically be applied, but might converge very slowly.


Q: How does the onDraw(Canvas) function of the View class work? I need to implement an interactive graph in Android
For a start I am trying to see how this code works
There, in a class called LineChartView Which extends the user generated class ChartView which extends the View class, there is an @overrideed function called onDraw(Canvas canvas). How and when does this function get called? the output of that code is a bunch of graphs on full screen, but my interactive graph should only take up a part of the screen. Does the onDraw() function get called automatically? If so, when? And what is the size of the canvas? Is it always the full screen occupied by the current activity's window?

A: in this link View Android Developer there is a section on implementing a custom view
onDraw(Canvas canvas) is called whenever a view should render its content
if you define to use this view in your layout xml or even in code you can specify the attributes
android:layout_width=
android:layout_height=

and those attributes will be applied to the size that the view will use
in your layout.xml
<your.package.name.extendedviewclass
android:layout_width="100dp"
android:layout_height="100dp"/>


Q: Javascript uncaugh error in promise even with a catch With Javascript, I am trying to make a call to an external API when a form is submited.
I am using promises in order to set follow up actions once the call is done and to catch eventual errors.
This is where my problem is, even if I think I am catching my errors correctly, the console throws an

Uncaught (in promise) error : [The error I throw]

I do not understand why.
Here is a minimal version of my code which would reproduce the error when the refreshToken is expired :
try {
        functionGeneratingTheError();
    } catch (error) {
        doSomethingElse();
    }

function functionGeneratingTheError() {

    var getTokenCallPayload = {
        "client_id" : clientId,
        "client_secret" : clientSecret,
        "refresh_token" : refreshToken,
        "grant_type" : "refresh_token"
    };
    var getTokenCallOptions = {
        "method" : "POST",
        "body" : JSON.stringify(getTokenCallPayload),
        "muteHttpExceptions" : false
    };
    fetch(tokenURL, getTokenCallOptions)
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error("Error");
        }
    })
    .then(data => {
        doSomething();
    })
    .then(response=> {
        doSomethingAgain();
    })
    .catch(error => {
        throw error;
    });
}

If I understand correctly, when the fetch is a bad request, it should throw the error "Error" which should then be caught in the first catch and run the doSomethingElse() function.
However, instead of doing that, I get this error in the browser console "Uncaught (in promise) Error: Error"
What am I doing wrong ?
I have tried including the fetch in a try{}catch(){} but it doesn't change anything.
I also tried not throwing the error and directly call my doSomethingElse() function, but then the following .then fails because data is undefined.

A: Change your functionGeneratingTheError function to return the chained promise like below:
function functionGeneratingTheError() {

    var getTokenCallPayload = {
        "client_id" : clientId,
        "client_secret" : clientSecret,
        "refresh_token" : refreshToken,
        "grant_type" : "refresh_token"
    };
    var getTokenCallOptions = {
        "method" : "POST",
        "body" : JSON.stringify(getTokenCallPayload),
        "muteHttpExceptions" : false
    };

    return
    fetch(tokenURL, getTokenCallOptions)
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error("Error");
        }
    })
    .then(data => {
        doSomething();
    })
    .then(response=> {
        doSomethingAgain();
    })
    .catch(error => {
        throw error;
    });
}

And then await it in your calling code by wrapping the calling code inside an async self invoking function like so:
(async function() {
try {
        await functionGeneratingTheError();
    } catch (error) {
        doSomethingElse();
    }
})();

You can read more about async/await here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function


Q: $.ajax not loading data data everytime from server I have written a simple jQuery.ajax function which loads a user control from the server on click of a button. The first time I click the button, it goes to the server and gets me the user control. But each subsequent click of the same button does not goes to the server to fetch me the user control.
Since my user control fetches data from db, I need to reload the user control everytime i hit the button. But if anyhow I get my user control to unload from the page, and re-click the button, it goes to the server and fetches me the user control. Here's the code:

$("#btnLoad").click(function() {
    if ($(this).attr("value") == "Load Control") {
 $.ajax({
  url: "AJAXHandler.ashx",
  data: { "lt": "loadcontrol" },
  dataType: "html",
  success: function(data) {
   content.html(data);
  }
 });
 $(this).attr("value", "Unload Control");
    }
    else {
 $.ajax({
  url: "AJAXHandler.ashx",
  data: { "lt": "unloadcontrol" },
  dataType: "html",
  success: function(data) {
   content.html(data);
  }
 });
 $(this).attr("value", "Load Control");
    }
});

Please let me know if there is any other way I can get my user control loaded from server everytime I click the button.

A: Add a cache property with the value false to the objects you pass to jQuery.ajax.
 $.ajax({
  url: "AJAXHandler.ashx",
  cache: false,
  data: { "lt": "loadcontrol" },
  dataType: "html",
  success: function(data) {
   content.html(data);
  }
 });

You can set this globally by:
jQuery.ajaxSetup({
    cache: false
});

jQuery will used cached responses for anything except SCRIPT/ JSONP by default.

A: If your btnLoad is inside the user control you're reloading, you need to do this instead:
$("#btnLoad").live('click', function() {

When loading ajax, you're replacing the elements, and any event handlers bound directly to them.  If you use .live() instead, it won't be destroyed as part of the callback...it works differently and the event handler lives higher in the DOM, so it doesn't get blown aware with the button itself.


Q: Mikrotik Router Management via Web App I need help in building a project. Let me first describe my project -
I want to build a Web application (using php / php framework(laravel) , html, css, javaScript, bootstrarp ) that will help ISP owner to manage their router (most of them use Mikrotik router).
Reason to build this App:
Most ISP provider here use Mikrotik router to manage their internet business. But managing the router using Winbox ( a desktop based windows software that is build to manage Mikrotik router) seems complex to them. Just for creating new ip to assign a new user, blocking a user if he/she do not pay bills and managing bandwidth they need to operate winbox every time which they find difficult. My approach is to build a web application that will ease their work.
The features I want to provide are-

*

*Creating new IP address and addressing them to user (internet user / end user)

*Manage bandwidth of an IP address

*Block / Lock any particular IP address automatically (in this case any particular user) who have not paid their monthly bill on certain date of a month

*Re-enabling blocked IP address on paying their dues automatically

*Showing daily graph of bandwidth received and used

*Recording client history (client IP address, Monthly rent, Name, Address etc.)

*Recording payment history of client

*Auto bill calculation / due calculation

*Auto sort out of due users of months

I am able to do 6 - 9  features as described but I have no idea how to implement 1 - 5 features !
Problem That I am facing :
a. I don't know how to connect to a MikrotiK router via web application
b. If some how i can access to the MikrotiK router using router IP address , I don't know how to create new IP address on that router database
c. how to manage bandwidth via web application
d. how to block / lock ip address !
Points I get myself :
I think using management vlan (router Ip address) i can access to that router form command promt using ssh/telnet. After that what would be the command to create, lock/block, manage bandwidth of an IP address ? IF all this things can be done using command prompt, how can I make it for my web application ?
Can anyone please help me with this, referring any link?? I googled but only thing I find is Mikrotik router management manual !

A: I did part of what you are asking for a customer weeks ago. Your question is to broad, very extensive, it will take months to accomplishes the job.
Start your project with the basic that you can find at http://wiki.mikrotik.com/wiki/API_PHP_class, then you can grow your application and post specific questions about your problems in places like stackoverflow or reddit.
Follow a sample to connect to the API, then execute commands and then disconnect.
$API = new RouterosAPI();
$API->debug = true; // turn debug on to learn more about your api
if ($API->connect($server , $username , $passwd, $port)) {

    // wireless registration table
    $API->write('/interface/wireless/registration-table/print',false);
    $API->write('=stats=');
    // print output here

} else {

    // connection fails
}
$API->disconnect();

Ref.:

*

*https://www.reddit.com/r/mikrotik/

*http://wiki.mikrotik.com/wiki/API_PHP_class

A: You should either use APIs or a remote command protocols like ssh/telnet(PHP-SSH2).
This is a PHP API project you could use:
https://github.com/BenMenking/routeros-api
After connecting you can commit commands just like you do on mikrotik console.
Mikrotik commands wiki

A: In my opinion you better use Radius server with database on MySQL. Mikrotik works perfect with Radius. In application implement interface with the database and all interaction with Mikrotik leaves to Radius. Read about FreeRadius for example:
https://www.howtoforge.com/authentication-authorization-and-accounting-with-freeradius-and-mysql-backend-and-webbased-management-with-daloradius


Q: system.diagnostics.contracts.contract exists in both v4.0 v3.5 I just upgraded to visual studio 2010 and installed the code contracts msi.  When I try to use it I get a compiler error that the system.diagnostics.contracts.contract dll exists in both the v3.5 and v4 framework.  Anyone know what I should do to resolve this?  Thanks.

A: If you're upgrading a .NET 3.5 project that uses contracts to .NET 4.0, make sure you remove your reference to the Microsoft.Contracts assembly.
The Microsoft.Contracts assembly provides code contracts for use in .NET 2.0 or 3.5 projects, but is provided by default with .NET 4.0 in mscorlib, so you don't need it. They both share the System.Diagnostics.Contracts namespace, so by having references to both at the same time, the compiler isn't able to figure out which one you're trying to use.

A: I solved it by first installing it, thou that did not actually solve it.
Then removed the references and then I changed the project versions to 4.5 and after that, it worked.


Q: can't list files in a directory I'm using CF 7 and this code is not returning any files:
<cfset fileLocation = "\\server\uploader\pass-fail">
<cfdirectory
  action = "list"
  directory = fileLocation
  name = "pass_fail_files"
  >

     <cfdump var="#pass_fail_files#" expand="yes"   label="files in pass-fail" >

     <cfoutput>#pass_fail_files.name#</cfoutput>
     <cfoutput>#pass_fail_files.directory#</cfoutput>
     <cfoutput>#pass_fail_files.size#</cfoutput>
     <cfoutput>#pass_fail_files.type#</cfoutput>
     <cfoutput>#pass_fail_files.dateLastModified#</cfoutput>
     <cfoutput>#pass_fail_files.attributes#</cfoutput>
     <cfoutput>#pass_fail_files.mode# </cfoutput>

I have checked to make sure that the directory indeed has several text files.  But when I run the code, all I get is:
alt text http://img682.imageshack.us/img682/5603/nofiles.png
What am I doing wrong?

A: I've just tried this:
<cfset fileLocation = "\\192.168.8.20\websites">
<cfdirectory
  action = "list"
  directory = "#fileLocation#"
  name = "pass_fail_files"
  >
<cfdump var="#pass_fail_files#" expand="yes"   label="files in pass-fail" >

On CF7, CF8 and Railo, and works everytime.
Notice I updated your code so it uses the directory attribute as directory = "#fileLocation#" as opposed to directory = fileLocation.
Trying your code, I never got results, but didn't get errors either. Changing it to use double-quotes and hashes did the trick, as it stopped using it as a variable.
Hope it helps you.

A: My first question would be, does the ColdFusion Service User have read access on folder?
Actually, I think your code should be

<cfdirectory
  action = "list"
  directory = "#fileLocation#"
  name = "pass_fail_files"
  >

I think right now, you're telling it to look in a directory named "fileLocation".

A: Assuming you've done all the latest CF7 updates/patches/hotfixes..


Q: About Communities- Portal User Error I am using Google Open ID Connect to link up with Communities , I have configured everything as in the documentation ,
but I am getting the below error in the url:
 "Cannot create Portal user without contact"
So anyone please help me , my google registration handler is as follows :
  global class GoogleOpenIDConnect implements Auth.RegistrationHandler{
    global User createUser(Id portalId, Auth.UserData data){
    User u = new User();
    Profile p = [SELECT Id FROM profile WHERE id='00e240000011E3g'];
    u.username = data.email;
    u.email = data.email;
    u.lastName = data.lastName;
    u.firstName = data.firstName;
    u.timeZoneSidKey = 'Europe/Paris';
    u.localesidkey = 'en_GB';
    u.emailEncodingKey = 'UTF-8';
    u.languagelocalekey = 'en_US';
    String alias = data.firstName + data.lastName;
    if(alias.length() > 8) {
    alias = alias.substring(0, 8);
   }
    u.alias = alias;
    u.profileId = p.Id;
    return u;
    }

 global void updateUser(Id userId, Id portalId, Auth.UserData data){
   User u = new User(id=userId);
   u.email = data.email;
   u.lastName = data.lastName;
   u.firstName = data.firstName;
  update(u);
 }

}

A: Community Users needs a Contact (linked to a valid Contact).
So you have to do something like in the createUser method:
Account acc = new Account(Name = data.lastname);
insert acc;//you can also query an account
Contact cnt = new Contact(FirstName = data.firstname, LastName = data.lastname, AccountId = acc.Id);
insert cnt;//you can create a PersonAccount instead
u.contactid = cnt.Id;
return u;


Q: Poincare-like inequality on compact Riemannian manifolds I am looking for a Poincare Inequality on balls but instead of euclidean space, I have a compact Riemannian manifold without boundary. The inequality I am looking for is the equivalent of
$$ \int_{B_{r}(x)} |f(y) - f(z)|^{p} dy \leq c r^{n+p-1} \int_{B_{r}(x)} |Df(y)|^{p} |y-z|^{1-n} dy$$
where $f \in C^{1}(B_{r}(x))$ and $z \in B_{r}(x)$.
I would be grateful for any source you can point me to. I am also interested to know if there is a version of this inequalilty if the manifold has boundary.
Thank you.

A: A more accurate concept of the inequality you are looking is a Sobolev-type inequality or more precisely Hardy's inequality. The proof of this inequality can be found in most books on weighted Sobolev inequality, say the excellent book by V. G. Maz'ya. If you just want a directly proof, say for instance the following paper
"Kinnunen, Juha; Martio, Olli, Hardy's inequalities for Sobolev functions. (English summary)
Math. Res. Lett. 4 (1997), no. 4, 489–500. "
I would like to talk more about this inequality from the point view of capacity or equivalently non-linear potential. The standard proof of all (fractional) Sobolev-type inequality based on point-wise characterization of Sobolev functions, which basically reads as for a.e. $x,y$
$$|u(x)-u(y)|\leq c(n)|x-y|^{1-\alpha/p}(M_{\alpha/p}|Du|(x)+M_{\alpha/p}|Du|(y)),$$
where $M_\beta$ is the standard fractional maximal operator. In order to gain global estimates, one just integrate the above inequality and use the boundedness of the maximal operator. The equivalence of characterizations of Sobolev function can be found in the nice book of J.Heinonen,
"Lectures on Analysis on Metric Spaces, Springer Verlag, Universitext 2001."
or the forthcoming book of J.Heinonen et al. "Sobolev spaces on metric measure spaces, an approach based on upper gradients."
Hardy-type inequalities are usually regarded as weighted Sobolev type inequality by considering the potential term $|y-z|^{k}$ or $d(y,\partial \Omega)^k$ as a general weight. I encourage you to read the nice paper by
P.Koskela, P.Hajlasz, Isoperimetric inequalities and imbedding theorems in irregular domains. J. London Math. Soc. (2) 58 (1998), no. 2, 425–450
and
P.Koskela, P.Hajlasz, Sobolev met Poincaré. Mem. Amer. Math. Soc. 145 (2000), no. 688, x+101 pp.
The basic capacity view is to regard the right-hand side as certain capacity, and characterize the Sobolev/Hardy type inequality in terms of certain capacity. Then one could use the standard techniques from potential theory to do capacity estimates. This point of view is quite important in proving Sobolev/Hardy type inequality for irregular domains or in metric setting. As a sample, you could also read the following paper.
Koskela, Pekka; Lehrbäck, Juha, Weighted pointwise Hardy inequalities. (English summary)
J. Lond. Math. Soc. (2) 79 (2009), no. 3, 757–779.
See also the homepage of J.Luhrback for the recent progress on Hardy type inequality for general domains: http://users.jyu.fi/~juhaleh/publ.html.
If you want a global inequality with a uniform constant, then you have to impose (non-negative) lower bounded on the Ricci curvature (in metric measure spaces as well). In the smooth compact Riemannian setting, the constant is of course uniform.

A: The same inequality holds on Riemannian manifolds, at least if you want it for small $r$.
Fix a point $x\in M$ and let $r_0$ be the injectivity radius at it.
If $0<r\leq\frac12r_0$, then $\exp_x:U_r\to B_r(x)$ is a diffeomorphism and bi-Lipschitz continuous with a Lipschitz constant independent of $r$.
Here $B_r(x)\subset M$ is the ball in the Riemannian metric and $U_r\subset T_xM$ is the ball of radius $r$ in the tangent plane at $x$.
The tangent plane is just a Euclidean space, so your original estimate holds in $U_r$, and you can apply it to $f\circ\exp_p:U_r\to\mathbb R$.
Since the exponential map is a bi-Lipschitz diffeomorphism $\exp_x:U_r\to B_r(x)$, you get the same estimate (possibly with worse a constant) on $B_r(x)$.
If you take $r$ very small, you can make the Lipschitz constant arbitrarily close to one and give an arbitrarily small loss of constant in the final estimate.
If you have some curvature bounds (especially if the manifold is compact), the constant $c$ in the estimate can be chosen uniformly; without any such assumptions it will depend on $x$.


Q: Redirect POST-request in apache I'm trying to do a transparent redirect of a post-request in my apache server.
The request looks like this:
POST www.domain.com//maincontroller.php/api

I want to redirect this to:
POST www.domain.com/maincontroller.php/api

I don't want a 301 redirect but instead a silent redirect (edit the Post address and send it to httpd).
Everything I tried with mod_rewrite didn't rewrite the POST, but successfully rewrote a GET.

A: Coworker found it !
    RewriteCond %{THE_REQUEST} POST
    RewriteCond %{THE_REQUEST} ^[A-Z]+\s//+(.*)\sHTTP/[0-9.]+$ [OR]
    RewriteCond %{THE_REQUEST} ^[A-Z]+\s(.*/)/+\sHTTP/[0-9.]+$
    RewriteRule .* http://%{HTTP_HOST}/%1 [P]


Q: Django Session Form (save form temporarily) I have created a page for review form. All users can fill out the form, but only logged in users can submit the form. If users is not logged in, they will be redirected to the login page. After they login, they will be redirected to the profile page.
So the flow will be like this  :
User fills out the form > click the submit > redirected to login page > user login and redirected to profile page (at the same time, the form they have filled in is automatically saved)
I want the form they have filled in automatically saved after they login. How to do that?
My idea is to create a session that saves the form temporarily, then save to database after they login. But I'm confused how to write the code
Can anyone explain a bit what a django session is like? and how to write code to handle this problem?

A: You can try something like,

1 User fills out the form and hits submit

2 in the POST view where you handle the form, use the "**is_authenticated**" function and,
    a)if the user is authenticated you handle the form as usual...
    b)else set the contents of the form into a session variable in the views and redirect to the login page like,

request.session['review_body'] = request.post.get(the_form_body_field)

3 as per what you've said, after login it goes to profile page and form is submitted...
    a)so in views where you serve the profile page, check if the session variable containing form data's exist and has values
    b)if yes, directly save the contents from your views and clear the session data


Q: Chef - Returning a variable from powershell script I would like to know if there is a way to return a variable value from a powershell script defined in powershell_script resource?
My powershell resource looks like following:
powershell_script "Test Script" do
  code <<-EOH
    Write-Host "Hello World!"
   return "test"
  EOH
end

I would like to use the returned value test from the script to use in other resources based on if conditions.
Thanks

A: Ohai!
I think you actually want to use the PowershellOut Mixin found here in the Powershell cookbook.
Chef resources rarely return values, but that's what heavy-weight resources are for!
If you have the powershell cookbook, you can do this:
include Chef::Mixin::PowershellOut
cmd = powershell_out!('command')
cmd.stdout #=> ...
cmd.stderr #=> ...

A: We actually came across this exact issue and solved it by writing our own Mixlib to get the exit code from a powershell script. Example:
# get the result object (and exit code) from the code execution:
result = Mixlibrary::Core::Shell.windows_script_out(:powershell, mycode)
exit_status = result.exitstatus

@carpNick is planning on open-sourcing this perhaps as soon as this week....at the moment it only handles powershell, but we plan on implementing support for other types as well (bash, win modules, etc.) -- which should be fairly easy to add on support for others.
We are currently using it in-house and it works great. I'm sure Chef will want to review Nick's excellent code once he gets it out there. We are just waiting on legal to tell us what open-source license to use.
Ask Nick for more details... @carpnick | https://github.com/carpnick


Q: add record via has_many with default scope Records are added with default scope, but not with required.
class PostsTag
  # published is false by default
end

class Post
  has_many :posts_tags

  {published: true, private: false}.each do |key, val|
    has_many "#{key}_tags",
      through: "posts_tags",
      conditions: ["posts_tags.published = ?", val],
      source: :tag
  end
end

#--------------------

Post.first.published_tags << Tag.first
Post.first.published_tags.count # = 0
Post.first.private_tags.count # = 1

What do I wrongly? Thanks for advance.

A: Inserting a new Tag into published_tags does not set its published attribute to true by default.
What you need to do is to extend the published_tags association and override the << method of it to set the published attribute to true upon insertion. The code will look something like that:
has_many :published_tags do
  def <<(tag)
    tag.published = true
    proxy_association.owner.posts_tags+= [tag]
  end
end

I've written a full working example of exactly this case here, you should definitely have a look at it to get some more insights.


Q: Find out max divisor of a positive integer I need to find the biggest divisor of a positive integer and output it. Divisor should not be 1 or be equal to the integer itself. If it's a prime number the output should be "0". I have this code so far. However it doesn't work. It only works when I use "break" instead of "return 0" statement, but according to the task I should not use break :( How can I fix it? Thnx
#include <stdio.h>

int main() {
    int input, maxDiv;
    int div = 2;

    scanf("%d", &input);

    for ( ; div <= input/2; div += 1 ) {
        if ( input % div == 0 ) {
            maxDiv = input / div;
            return 0;
        } else {
            maxDiv = 0;
        }
    }

    printf("%d\n", maxDiv);

    return 0;
}

A: You can rewrite it this way
int main(){
    int input, maxDiv = 0;
    int div = 2;

    scanf("%d", &input);

    for(; !maxDiv; div++)
        if(!(input%div))
            maxDiv = input/div;

    printf("%d\n", ( maxDiv == 1 || input < 0 ? 0 : maxDiv ) );
    return 0;
}

It is an infinite loop that will exit as soon as maxDiv != 0. The complexity is O(sqrt (n)) as there is always a divisor of n less than or equal to sqrt(n), so the code is bound to exit (even if input is negative).
I forgot, you have to handle the case where input is zero.

A: Maybe you can declare a flag?
#include <stdio.h>

int main() {
    int input, maxDiv;
    int div = 2;
    char found = 0;

    scanf("%d", &input);

    for ( ; div <= input/2 && !found ; div += 1 ) {
        if ( input % div == 0 ) {
            maxDiv = input / div;
            found = 1;
        } else {
            maxDiv = 0;
        }
    }

    printf("%d\n", maxDiv);

    return 0;
}

A: You can stop the loop when you reach sqrt(input)... it's not that difficult to find a perfectly good integer sqrt function.
There's not a lot of point dividing by all the even numbers after 2.  In fact there's not a lot of point dividing by anything except the primes.  It's not hard to find the primes up to sqrt(INT_MAX) (46340, for 32-bit integer)... there are tables of primes freely available if you don't want to run a quick sieve to generate same.
And the loop...
  maxdiv = 0 ;
  i = 0 ;
  sq = isqrt(input) ;
  while ((maxdiv == 0) && (prime[i] < sq))
    {
       if ((input % prime[i]) == 0)
         maxdiv = input / prime[i] ;
       i += 1 ;
     } ;

assuming a suitable integer sqrt function and a table of primes... as discussed.

A: Since you are looking for the largest divisor, is there a reason you're not looping backward to 2? If there isn't, then there should be no need for a break statement or any special logic to exit the loop as you should keep looping until div is greater than input / 2, testing every value until you find the largest divisor.
maxDiv = -1;
for (div = input / 2;
     div >= 2 && maxDiv == -1;
     --div)
  {
    if (input % div == 0)
      maxDiv = div;
  }

maxDiv += (maxDiv == -1);

printf ("%d\n", maxDiv);

I added the extra condition of maxDiv being -1, which is like adding a conditional break statement. If it is still -1 by the end of the loop, then it becomes 0 because maxDiv += 1 is like writing maxDiv = -1 + 1, which is 0.
Without any jump statement such as break, this sort of test is what you must do.
Also, regarding your code, if I input 40, the if statement will be triggered when div is 2, and the program will end. If the return 0 is changed to a break, maxDiv will be 2, not 20. Looping backward will find 20 since 40/2=20, and 40%20==0.

A: Let us denote D to the max divisor of a given composite number N > 1.
Then, obviously, the number d = N / D is the min non-trivial divisor of N.
If d would not a primer number, then d would have a non-trivial divisor p < d.
By transitivity, this implies that p is a divisor of N, but this fact would contradict the fact that d is the min divisor of N, since p < d.

*

*So, d must be a prime number.

In particular, it is enouth to search over those numbers which are less than sqrt(N), since, if p is a prime number greater than sqrt(N) which divies N, then N / p <= sqrt(N) (if not, *p * (N / p) > sqrt(N)sqrt(N) == N, wich is absurd).
This shows that it's enough to do the search the least divisor d of N just within the range of primer numbers from 2 to sqrt(N).
For efficiency, the value sqrt(N) must be computed just once before the loop.
Moreover, it is enough a rough approximation of sqrt(N), so we can write:
   #include <math.h>
   #include <stdio.h>

   int main(void)
   {
      int N;
      scanf("%d",&N);

      // First, we discard the case in that N is trivial
      // 1 is not prime, but indivisible.
      // Change this return if your want.
      if (N == 1)
         return 0;
      // Secondly, we discard the case in that N is even.
      if (N % 2 == 0)
         return N / 2;

      // Now, the least prime divisor of N is odd.
      // So, we increment the counter by 2 in the loop, by starting in 3.

      float sqrtN = fsqrt(N); // square root of N in float precision.
      for(d = 3; d <= sqrtN; d += 2)
         if (N % d == 0)
            return N/d;

      // If the loop has reached its end normally,
      // it means that N is prime.

      return 0;
   }

I think that the problem is not well stated, since I consider that a better flag to signalize that N is prime would be a returned value of 1.
There are more efficient algorithms to determine primality, but they are beyond the scope of the present question.


Q: PC System keeps crashing due to overheating In October I had the problem the first time. My desktop PC crashed as if the power would just be gone. But it only occured when I had my case closed, so I opened it and everything was fine. But yesterday it started crashing again.
I assume a component is overheating but I'm not sure which one it is. The possibilities are (I think):

*

*Power supply

*Processor

*Mainboard chipset

According to Open Hardware Monitor the temperatures of my processor (AMD FX-6100) is 45 °C writing this post, 60-70 °C watching a video and 70-80 °C in a video game.
The chipset (ITE IT8720F) has 3 temperatures that go from 40/60/60 °C (browser) over 45/80/85 °C (video) to 50/90/95 °C.
GPU is always under 45 °C
The only other additional information I can give is that the shutdown makes exactly the sound as if you would just pull the plug.
How can I determine which component is actually problematic?

A: Your processor and chipset temperatures under load seem pretty high. What type of CPU fan are you using? What are your ambient (room) temperatures?
Here are a few things to check:

*

*Is your CPU fan running?

*Chipset idle temperature in the BIOS (this way you know which number is accurate in your harware monitor).

You might consider getting an aftermarket CPU cooler if the fan is working properly, though AMD stock coolers are usually pretty good. Re-applying thermal paste could also help.

A: After removing every bit of dust I could access (especially under the CPU fan) my computer runs crash free even with close cased. Additionally I added a bit of WD-40 on the fan.
The only problem is, that the displayed CPU temperature might bi not so accurate, because I doubt it can be 12 °C while the room has 20 °C. ;)


Q: extract individual words from string c++ I am trying to make a C++ program that receives user input, and extracts the individual words in the string, e.g. "Hello to Bob" would get "Hello", "to", "Bob". Eventually, I will be pushing these into a string vector. This is the format I tried to use when designing the code:
//string libraries and all other appropriate libraries have been included above here
string UserInput;
getline(cin,UserInput)
vector<string> words;
string temp=UserInput;
string pushBackVar;//this will eventually be used to pushback words into a vector
for (int i=0;i<UserInput.length();i++)
{
  if(UserInput[i]==32)
  {
    pushBackVar=temp.erase(i,UserInput.length()-i);
    //something like words.pushback(pushBackVar) will go here;
  }
}

However, this only works for the first space encountered in the string.It does not work if there are any spaces before the word (e.g. if we have "Hello my World", pushBackVar will be "Hello" after the first loop, and then "Hello my" after the second loop, when I want "Hello" and "my".) How do I fix this? Is there any other better way to extract individual words from a string? I hope I haven't confused anyone.

A: See Split a string in C++?
#include <string>
#include <sstream>
#include <vector>

using namespace std;

void split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

So in your case just do:
words = split(temp,' ');

A: You can use the operator >> direct to a microbuffer (string) to extract the word. (getline is not needed). Take a look at the function below:
vector<string> Extract(const string& Text) {
    vector<string> Words;
    stringstream ss(Text);
    string Buf;

    while (ss >> Buf)
        Words.push_back(Buf);

    return Words;
}

A: #include <algorithm>        // std::(copy)
#include <iostream>         // std::(cin, cout)
#include <iterator>         // std::(istream_iterator, back_inserter)
#include <sstream>          // std::(istringstream)
#include <string>           // std::(string)
#include <vector>           // std::(vector)
using namespace std;

auto main()
    -> int
{
    string user_input;
    getline( cin, user_input );
    vector<string> words;
    {
        istringstream input_as_stream( user_input );
        copy(
            istream_iterator<string>( input_as_stream ),
            istream_iterator<string>(),
            back_inserter( words )
            );
    }

    for( string const& word : words )
    {
        cout << word << '\n';
    }
}

A: Here I have created a vector of words from the sentence.
#include<bits/stdc++.h>
using namespace std;
int main(){
string s = "the devil in the s";
string word;
vector<string> v;
for(int i=0; i<s.length(); i++){
    if(s[i]!=' '){
        word+=s[i];
    }
    else{
        v.push_back(word);
        if(i<s.length()+1)
            word.clear();
    }
}
v.push_back(word);
for(auto i:v){
    cout<<i<<endl;
  }
}


Q: Designing a database connection class in VS 2005 I am working on designing a SQL Server database connection class in VB.net 2005. The idea behind doing this will be so a developer can can call the class, pass it a stored procedure name along with the parameters, and get return values back (if any).
My question is, how would I design the class so the stored proc parameters are dynamic?
My second question is, how would I account for the data type being passed to the stored procedure?

A: This assumes SQL Server, but the SqlParameter type could be changed to match the connection type. As items are added to this list the data type would have to be identified.
    Imports System.Data.SqlClient
    Dim Params As List(Of SqlParameter)

    Public Property ParameterList() As List(Of SqlParameter)
        Get
            Return Params
        End Get
        Set(ByVal value As List(Of SqlParameter))
            Params = value
        End Set
    End Property

You'll have to loop through the list and add each parameter to a command object.


Q: Replacing tabs with spaces from nth column to last column I have a tab-separated file which looks as follows:
GCF_000014165.1_ASM1416v1.dist_nbr_anntn        WP_011558474.1  1155234 1156286 44173   polyketide synthase [Mycobacterium]
GCF_000014165.1_ASM1416v1.dist_nbr_anntn        WP_011558475.1  1156298 1156807 12      isoprenylcysteine       carboxyl        methyltransferase       [Mycobacterium]
GCF_000014165.1_ASM1416v1.dist_nbr_anntn        WP_011558476.1  1156804 1157820 -3      NAD(P)/FAD-dependent    oxidoreductase  [Mycobacterium]

How do I replace tabs from column 6 to the last column with spaces?
The output should look as follows:
GCF_000014165.1_ASM1416v1.dist_nbr_anntn        WP_011558474.1  1155234 1156286 44173   polyketide synthase [Mycobacterium]
GCF_000014165.1_ASM1416v1.dist_nbr_anntn        WP_011558475.1  1156298 1156807 12      isoprenylcysteine carboxyl methyltransferase [Mycobacterium]
GCF_000014165.1_ASM1416v1.dist_nbr_anntn        WP_011558476.1  1156804 1157820 -3      NAD(P)/FAD-dependent oxidoreductase [Mycobacterium]

A: With GNU sed, it's as simple as:
sed 's/\t/ /6g' file

The s command can be followed by zero or more of the following flags:
g

Apply the replacement to all matches to the regexp, not just the
  first.
number

Only replace the numberth match of the regexp.
interaction in s command Note: the POSIX standard does not specify
  what should happen when you mix the g and number modifiers, and
  currently there is no widely agreed upon meaning across sed
  implementations. For GNU sed, the interaction is defined to be: ignore
  matches before the numberth, and then match and replace all matches
  from the numberth on.

See sed, a stream editor: The s Command


Q: clicking href on capybara I'm trying to tell Capybara/Cucumber to click on href  but failed trying different options. Here's the code:

      Option 1
      More

      Option 2
      More

   ...

1st attempt was to have find_link('More').click the "link".
within(all(.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated>a).[0]) do
    find_link('More').click
end

That didn't work. I've tried having it clicked straight away.
find(all('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated>a')[0]).click

That didn't work either.
Just wondering if there's any other way to click Option 1? Or Option 2? These options need to be tested individually.

A: Assuming the elements are visible on the page (not sure what the animation classes on the h6 elements are actually doing) then your first attempt wont work because of the extra > a on the selector in the within - which means you're finding the a already and then saying inside that find another a.  Your second attempt won't work because find takes a selector type and selector (selector type defaults to css) to match against elements, but all returns an array of elements (you call either find to return one element or all to return multiple elements) - the following should work instead
within(all('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated')[0]) do
  find_link('More').click
end

which is saying inside the first .animation-visible... matching element find a link with 'More' for its text and click it.  This could also be written
within(first('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated', minimum: 1)) do
  click_link('More')
end

That is basically the same thing except the minimum: 1 option will make it wait until at least one matching element is on the page (good for if your previous call is #visit or the elements are loading via ajax
Note: you could use the minimum: 1 (or whatever number of elements you're expecting to appear on the page) on the first example too
The find_link calls suggested in the other answer won't work because find_link doesn't take a css selector, it takes a string to match against the text, id, or title of the link.  So the following would work
find_link('More', href: 'http://some.com/page1/').click

or
click_link('More', href: 'http://some.com/page1/')

A: Wouldn't these work?
First link
find_link("a[href$='page1/']").click

Second link:
find_link("a[href$='page2/']").click

Translation of the css selector:
  Find the link that ends with XXX


Q: PHP while() wrapping items I have this html code:

and I am looking for a way to implement it in my php while (wordpress).
The while is as
while ( have_posts() ) : the_post();
   echo '

';
endwhile;

I've tried a lot of stuff, but none have worked. I need to divide every 2 items and put them in a wrap
 after that the next 4 items in
 and after that the next 3 items in

I did a lot of searching, but I am not even sure what to search for.

A: A little crude but here's one solution
$i = 0; // Number of items made so far in the row
$mode = 0; // Current row type enumerated by $elem
$elem = array(2,4,3); // Enumeration of the desired row sizes
while ( have_posts() ) : the_post();
    // Make a new row when there's no items yet
    if ($i == 0) echo '
';
    echo '

';
    $i++;
    // Once the items in the current row has reached the row's maximum size
    if ($i % $elem[$mode] == 0):
        echo '
';
        $i = 0; // Reset items made for the row back to 0
        $mode = ($mode + 1) % 3; // Increment mode and wrap if necessary
    endif;
endwhile;
if ($i > 0) echo '
'; // Finish the last row if it wasn't finished

This is what the modulos was built for!


Q: How to display all projects in the Project View in PHPStorm? In eclipse / Zend Studio the project manager displays per default all projects of the workspace (or of one of its Working Sets, if selected):

Now I'm looking for the according configuration in PHPStorm, that shows only one project per window:

How can I see all my projects in the project view of the same window?

A: PhpStorm does not support multiple independent projects in one window / frame:
https://youtrack.jetbrains.com/issue/WI-15187 -- star/vote/comment to get notified on progress.

But ... you can list files from another project there (in Project View panel). If that is good enough, then just go to Settings | Directories and add desired folder as an Additional Content Root. P.S. This also means that the setting from current project will be applied to all content roots.


Q: How can I prevent RMySQL errors and show to user in Shiny? I have a Shiny App that executes a query to a MySQL database like this example:
UI
textAreaInput("query")

SERVER
data <- reactive({
  df<-dbGetQuery(conection, input$query)
  return(df)
})

The problem is that when the user types a wrong syntax in the textAreaInput the Shiny App closes and the error is shown in the R Console.
What I want is to print that error in the app so the user can try again and write another query.
Can someone help me please?

A: We can use tryCatch. Here is a complete example based on  @Fan Li's answer here
library(RSQLite)
con <- dbConnect(SQLite(), dbname="sample.sqlite")
dbWriteTable(con, "test", data.frame(value1 = letters[1:4], value2 = letters[5:8]))
dbDisconnect(con)

library(shiny)
library(RSQLite)
runApp(list(
  ui = bootstrapPage(
    #select * from te fail
    #select * from test work
    textAreaInput("query",'Query'),
    actionButton("action", label = "Run Query"),
    hr(),
    tableOutput("table")
  ),
  server = function(input, output){
    #Reactive is eager by definition and it will signal unreal/annoying errors, hence I used eventReactive
    data <- eventReactive(input$action,{
      tryCatch({
        con <- dbConnect(SQLite(), dbname="sample.sqlite")
        data<-dbGetQuery(con, input$query)
        dbDisconnect(con)
        return(data)
        },
               error = function(e){
                 showModal(
                   modalDialog(
                     title = "Error Occurred",
                     tags$i("Please enter valid query and try again"),br(),br(),
                     tags$b("Error:"),br(),
                     tags$code(e$message)
                   )
                 )
               })
    })
    output$table <- renderTable(data())
  }))


Q: How do I update my HTML Selects with ajax based on other Selects? I've got this search page with 7 different Selects and 2 textfields.
The data wich is stored in the selects is fetched from a MYSQL database.
Now when I make a choice, I want the other selects to update based on the choise I made.
This needs to be accomplished with Ajax. Can someone point me in the right direction?

A: collect the values of already filled selects, and send them to the server to obtain the filtered values list.
let's say you have an car manufacturer / model selector.
<select name="manufacturer">
 <option value="1">Acura</option>
 <option value="2">Audi</option>
 ...
</select>

<select name="model"></select>

the function to fill "model" select with values should look like this:
$.get('/get_models_by_manufacturer', {manuf: $('select[name=manufacturer']).val()}, function(data){
  // data returned by the server is expected to be html code of options NOT surrounded with <select>
  $('select[name=model]').html(data);
});

A: IF your're using jquery there is an discussion: http://forum.jquery.com/topic/how-to-reload-a-select-in-a-form-using-ajax-via-jquery


Q: EF Code first - many to many relation mapping table with extra columns I am having a User Model and and a Group Model.  User and Group share a many to many relationship. In when I translate this to table, I want to have a mapping table. I am using the following to achieve this.
modelBuilder.Entity<UserGroup>()
        .HasMany(a => a.Users)
         .WithMany(b => b.UserGroup)

         .Map(mc =>
         {

             mc.ToTable("UserUserGroupMapping");
             mc.MapLeftKey("UserId");
             mc.MapRightKey("UserGroupId");

         });

This creates a table with UserId and UserGroupId as columns. However I have few challenges,
I would like to be able to add an Identity column to this table and some audit columns (ex: Created by, created date) to the table. I am not sure how to do this.
Can any one help me here?
Thanks

A: I think it'll work if you do the following:

*

*Remove the configuration you showed in the code snippet above

*Add a mapping table and configure its table name to match the original table name.
// name this whatever you want
class UserUserGroupMapping
{
    public UserUserGroupMappingId { get; set; }
    public int UserId { get; set; }
    public virtual User User { get; set; }
    public int UserGroupId { get; set; }
    public virtual UserGroup UserGroup { get; set; }
    // other properties
}

modelBuilder.Entity<UserUserGroupMapping>()
    .HasKey(um => um.UserUserGroupMappingId)
    .ToTable("UserUserGroupMapping");

*Replace the many-to-many collection properties from User and UserGroup and replace it with one-to-many associations
class User
{
    // other properties
    // remove this:
    // public virtual ICollection<UserGroup> UserGroup { get; set; }
    public virtual ICollection<UserUserGroupMapping> UserGroupMappings { get; set; }
}

class UserGroup
{
    // other properties
    // remove this:
    // public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<UserUserGroupMapping> UserMappings { get; set; }
}

modelBuilder.Entity<UserUserGroupMapping>()
    .HasRequired(um => um.UserGroup).WithMany(g => g.UserMappings)
    .HasForeignKey(um => um.UserGroupId);

modelBuilder.Entity<UserUserGroupMapping>()
    .HasRequired(um => um.User).WithMany(g => g.UserGroupMappings)
    .HasForeignKey(um => um.UserId);

*Use the package manager to Add-Migration and remove anything from the scaffolded migration that might attempt to drop the old table and create a new table. The migration will need to at least (I might be missing some here):

*

*DropPrimaryKey for the original key columns

*AddColumn for the new columns (with Int(identity:true, nullable: false) for the new primary key column)

*AddPrimaryKey for the new key column

Then you can use the methods outlined in this answer to retrieve entities.


Q: Does delete[] need to be called on the original pointer position According to answers in this question : "How does delete[] "know" the size of the operand array?"

your allocator will keep track of how much memory you have allocated

and

How free knows how much memory to deallocate"

Yes, the memory block size is stored "somewhere" by malloc (normally in the block itself), so that's how free knows. However, new[]/delete[] is a different story. The latter basically work on top of malloc/free. new[] also stores the number of elements it created in the memory block (independently of malloc), so that later delete[] can retrieve and use that number to call the proper number of destructors

Does this mean that delete[] is independent on where the pointer points to? Is the following code valid or will it result in memory leaks?
void createArray(){
    char* someArray = new char[20];
    readData(someArray);
    //Is this delete still valid after moving the pointer one position?
    delete[] someArray;
}

char readData(char* &arr){
    char value = *arr;
    //Let it point to the next element
    arr += 1;
    return value;
}

A: Yes it does. If you change a new[]-ed pointer value and then call delete[] operator on it you are invoking undefined behavior:
char* someArray = new char[20];
someArray++;
delete[] someArray; // undefined behavior

Instead store the original value in a different pointer and call delete[] on it:
char* someArray = new char[20];
char* originalPointer = someArray;
someArray++; // changes the value but the originalPointer value remains the same
delete[] originalPointer; // OK

A: You might be interested to know what new and delete really do under the covers (some licence taken, ignores exceptions and alignment):
template<class Thing>
Thing* new_array_of_things(std::size_t N)
{
  std::size_t size = (sizeof(Thing) * N) + sizeof(std::size_t);
  void* p = std::malloc(size);
  auto store_p = reinterpret_cast<std::size_t*>(p);
  *store_p = N;
  auto first = reinterpret_cast<Thing*>(store_p + 1);
  auto last = first + N;
  for (auto i = first ; i != last; ++i)
  {
    new (i) Thing ();
  }
  return first;
}

template<class T>
void delete_array_of_things(Thing* first)
{
    if (first)
    {
        auto store_p = reinterpret_cast<std::size_t*>(first) - 1;
        auto N = *store_p;
        while (N--)
        {
            (first + N)->~Thing();
        }
        std::free(store_p);
    }
}

Summary:
The pointer you are given is not a pointer to the beginning of the allocated memory. The size of the array is stored just before the memory that provides storage for the array of objects (glossing over some details).
delete[] understands this and expects you to offer the pointer that was returned by new[], or a copy of it.

A: General rule is that you can delete only pointers you got from new. In an non-array version you are allowed to pass a pointer to base class subobject created with new (granted the base class has virtual destructor). In case of array version, it must be the same pointer.
From cppreference

For the second (array) form, expression must be a null pointer value or a pointer value previously obtained by an array form of new-expression. If expression is anything else, including if it's a pointer obtained by the non-array form of new-expression, the behavior is undefined.


Q: Android calendarview font size I am using Xamarin for building android application this is my first app. I have a CalendarView I need to change the font size and style of the day.
I tried the below code the font color changed but the size is too small. The minimum API level is 11 and target API level is 16. I am using galaxy note 2 for testing.
<style name="Widget.CalendarView.Custom" parent="@android:style/Widget.CalendarView">
    <item name="android:focusedMonthDateColor">@color/gray</item>
    <item name="android:weekDayTextAppearance">@android:style/TextAppearance.Medium</item>
    <item name="android:dateTextAppearance">?android:attr/textAppearanceLarge</item>
    <item name="android:selectedWeekBackgroundColor">@android:color/transparent</item>
</style>

A: All you need to do is reference a different style that includes a slightly bigger font for the size of the date. I'm not exactly sure why yours isn't working using the styles.xml as it seems correct. However I would just simply add it to the XML attributes for the calendar. This will be fine as presumably you're only using one Calendar and therefore it isn't really inefficient. Add this line to the calendar XML:
android:dateTextAppearance="@android:style/TextAppearance.Large"

Hope this helps you!

A: You should change "android:dateTextAppearance", you can check this reference too ;)
CalendarView
also you can try this
Style will save the world!


Q: How to know most used procedure in my database? I completed my project, there are many procedures used and now I got the job to find the mostly used procedure and there average execution time.
In this way I know what are the procedures I need to tune first?
It there any way to get procedure execution history for a particular database?

A: I believe you can use the sys.dm_exec_query_stats dynamic management view.  There are two columns in this view called execution_count, and total_worker_time that will help you.
execution_count gives the total number of times the stored procedure in question was executed since the last time it was recompiled.
total_worker_time gives the total CPU time in milliseconds that was spent executing this stored procedure since the last time it was recompiled.
Here is an MSDN link:
http://msdn.microsoft.com/en-us/library/ms189741.aspx

A: You can use dm_exec_cached_plans to look for the stored procedures that have been compiled into query plans.  The function dm_exec_query_plan can be used to retrieve the object id for a plan, which in turn can be translated into the procedure's name:
select  object_name(qp.objectid)
,       cp.usecounts
from    sys.dm_exec_cached_plans cp
cross apply
        sys.dm_exec_query_plan(cp.plan_handle) qp
where   cp.objtype = 'Proc'
order by
        cp.usecounts desc

A: I think you want to check SQL Server Profiler for this.
You can check the details in MSDN and other places as well.
But, before using it in production server, you need to keep in mind that:
 Profiler adds too much overhead to production server. So, first check when your site has less no of hits, and go ahead.

A: This is what the SQL Server Profiler is for. With it you can keep track of query run count, execution time, etc.


Q: Email sending from ASP.net fails on IIS server I have implemented email service in my ASP.net application, and am using SmtpClient class to send email. The mail sending works perfectly fine from my local code, however it throws exception when published on the server.
The code is pretty basic, as below:
var message = new MailMessage();
message.To.Add(new MailAddress(recipientEmail));
message.Subject = subject;
message.Body = emailBody;

using (var smtp = new SmtpClient())
{
    smtp.Credentials = new NetworkCredential(EmailSettings.Username, EmailSettings.Password);
    smtp.Host = EmailSettings.Host;
    smtp.Port = EmailSettings.Port;
    smtp.EnableSsl = true;
    await smtp.SendMailAsync(message);
}

The exception which is being thrown is as follows:
"Syntax error, command unrecognized. The server response was: "


Q: Using struct in a switch statement I'm trying to create a struct that can be used in a switch statement. I'm using a bunch of wierd compilers like keil armcc and old-fashioned gcc 4.7.1.
That also means c++11 is not an option.
For some time this idea actually worked:
struct Test
{
    const int a;

    Test() : a(1) {}

    template<typename T>
    operator T() const;

    operator int() const {return a;}

};

...

Test t;

switch(t)
{
case 1:
    break;
}

That compiled just fine. Now I'm trying to move to more recent version of gcc without breaking compatibility with armcc.
But now gcc gives me this:
error: ambiguous default type conversion from 'Test'
 switch(t)
         ^
error:   candidate conversions include 'template<class T> Test::operator T() const'

And I can't really understand where is the ambiguity since template operator has no body.
Is there any way to fix this?

A: You could assign to a temporary int:
int n = t;
switch (n) {
   ...
}

In the context of switch (t), the compiler considers coercion to integer types including int, unsigned int, long.  By assigning to a variable of type int, we collapse the wave function force it to pick the conversion we want, and there's no ambiguity when we get to the switch.
You should also seriously consider making your template conversion operator explicit if you can, as a catch-all conversion can lead to unpleasant surprises.

A: switch(t)
{
case 1:
    break;
}

Here the compiler doesn't know what conversion operator to call; it's ambiguous. It could instantiate your templated conversion operator for a few different integral types or call your int conversion operator. The fact that the templated conversion operator function is undefined doesn't matter to overload resolution.
The simplest solution is to use switch (static_cast<int>(t)).


Q: How to fail a cucumber scenario In my scenario, i need to validate if there exists 10 objects in a page.
If any of the object doesn't exists, then the step should be failed and eventually the scenario should also be reported as failed, but the script execution should continue to validate the remaining object exists.
I know scenario.getStatus()give if the scenario is failed, but how can i set the status of the scenario to failed? Importantly the script execution should continue afterwards.

A: Depending on the testing framework you are using junit or testng you can use the concept of soft assertion. Basically it will collect all the errors and throw an assertion error if something is amiss.
To fail a scenario you just need an assertion to fail, no need to set the status of the scenario. Cucumber will take care of that if an assertion fails.
For testng you can use the SoftAssert class - http://testng.org/javadocs/org/testng/asserts/SoftAssert.html You will get plenty tutorials for this. Call to doAssert will trigger of the verification of all stored assertions.
For junit you can use the ErrorCollector Rule class -
http://junit.org/junit4/javadoc/4.12/org/junit/rules/ErrorCollector.htmlenter link description here As cucumber does not support @Rule annotation, you need to inherit from this class and override the verify property to change its modifier to public in place of protected. Create an instance of the new class and add the assertions. Call to verify method will start the verification.

A: QAF provides assertion and verification concepts, where on assertion failure scenario exited with failed status and in case of verification scenario continue for next step and final status of step/scenario is failed if one or more verification failure.
You also can set step status failure using step listener which result in test failure. With use of step listener, you also can continue even step failure by converting exception to verification failure.

A: It is not a good idea to continue executing steps after a step failure because a step failure can leave the World with an invariant violation. A better strategy is to increase the granularity of your scenarios. Instead of writing a single scenario with several "Then" statements, use a list of examples to separately test each postconditions. Sometimes a scenario outline and list of examples can consolidate similar stories. https://cucumber.io/docs/reference#scenario-outline
There is some discussion about adding a feature to tag certain steps to continue after failure. https://github.com/cucumber/cucumber/issues/79
There are some other approaches to continuing through scenario steps after a failure here: continue running cucumber steps after a failure


Q: WordPress add_action style arguments works but changes admin panel I've made a code so you can easily add a style sheet to the site, this is for our framework.
It works but if I use this the CSS changes the dashboard layout either? Same with customizer, if I don't use this method, but just a normal wp enqueue it works but that's not what I want.
    class theme_setup{
        function main_css_setup($css) {
            wp_enqueue_style( 'style', get_template_directory_uri().'/css/'.$css.'.css' );
        }
        function add_css_main($css){
            add_action( 'wp_enqueue_scripts', array($this, 'main_css_setup'),10,1 );
            do_action( 'wp_enqueue_scripts', $css );
        }
    }
$theme_setup = new theme_setup();
$theme_setup->add_css_main('main');

Dashboard change:
First example
Second example
I think it has something to do with the do_action, I searched on my best behave, but without any luck.
I'm using the 'do_action' to pass the argument that the user gives with the add_css_main, I know I can use global variables, but these are "static", and that will make the idea be gone of a flexible function.

Update:

function themename_custom_logo_setup($height,$width) {
    $defaults = array(
        'height'      => $height,
        'width'       => $width,
        'flex-height' => true,
        'flex-width'  => true,
        'header-text' => array( 'site-title', 'site-description' ),
    );
    add_theme_support( 'custom-logo', $defaults );
}

    function add_custom_logo($width,$height){
    add_action( 'after_setup_theme', array($this, 'themename_custom_logo_setup' ),10,2);
    do_action( 'after_setup_theme', $height,$width);
}

$theme_setup->add_custom_logo(88,250);

Does work, but the variables are not even passed at al.

A: This should avoid loading the CSS with this conditional (maybe apply it somewhere else in your code):
function add_css_main($css){
    if( !is_admin() ) {
        add_action( 'wp_enqueue_scripts', array($this, 'main_css_setup'),10,1 );
        do_action( 'wp_enqueue_scripts', $css );
    }
}


Q: E/AndroidRuntime: FATAL EXCEPTION: main PID: 5112 Hy
I am new to Android / Java is I am facing a BMO problem
I code it but it does not work
an idea ??
thank you
<string name="onCreate_Go">onCreate Go</string>

            <TextView
            android:id="@+id/scrollTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp" />

import android.widget.TextView;

private  final TextView txt = (TextView) this.findViewById(R.id.scrollTxt);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txt.setText(R.string.onCreate_Go);
}

5112-5112/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.gmail.test1, PID: 5112
                                                 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.gmail.test1/com.gmail.test1.MainActivity}: java.lang.NullPointerException
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:136)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5017)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                     at dalvik.system.NativeStart.main(Native Method)
                                                  Caused by: java.lang.NullPointerException
                                                     at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:117)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:149)
                                                     at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:29)
                                                     at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:54)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:202)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
                                                     at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
                                                     at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                     at com.gmail.test1.MainActivity.(MainActivity.java:13)
                                                     at java.lang.Class.newInstanceImpl(Native Method)
                                                     at java.lang.Class.newInstance(Class.java:1208)
                                                     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:136)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5017)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                     at dalvik.system.NativeStart.main(Native Method)
02-16 16:41:21.634 5112-5112/? I/Process: Sending signal. PID: 5112 SIG: 9

A: Please add your Activity in your  AndroidManifest.xml. like below code:
<activity android:name=".activities.MainActivity"/>

Also put the findViewById() after setContentView() so it can actually return something other than null.

A: You can't initialize the textView before call "setContentView" method. I recommend you create a "init" method where initialize all layout's elements and call it after "setContentView"


Q: Integrate SFMC with Firebase to send Push Notifications Our App development team has a mobile app in Xamarin which does not support the SFMC SDK for Mobile Push. So, now they want to introduce firebase layer so that SFMC can send the notification to firebase and app team can pull the same from firebase and trigger the notifications to actual consumer device.
So, is there any feature available in SFMC to connect with firebase. Also, is it possible to send push notifications from SFMC when the app has been developed without the sdk.

A: SFMC uses Google's and Apple's push messaging services to deliver all messages.  What you would need to do is get the individuals device registered with the Marketing Cloud servers.  Please contact your Salesforce support representative as the routes to accomplish this are not publicly documented.


Q: How can I upload a file to a GitHub Codespaces environment? I use GitHub Codespaces, but I don't know how to upload a single file to GitHub Codespaces without the assistance of, for example, github.

A: Simple Drag and Drop has worked for me.
To update the answer, there is now also an update option if you right click in the explorer view:

A: I was able to transfer a ton of training data from firebase to a codespace using firebase-admin.
in the codespace terminal:
pip install firebase-admin
pip install --ignore-installed <other firebase-admin dependencies>
run whatever script you use to download things from firebase

note that there are storage limits


Q: How not to remove first number in the sentence and remove later occurances of numbers in Python? I have a sentence that consists of numbers and words. I am looking for a solution to remove numbers except at the beginning. I have tried the following code, but it's removing all the numbers.
x = '45 is fourth five 45 when 9 and 5 are multiplied'

re.sub('\d', '', x)

Its output was
'is Fourth five when and are multiplied'

But need the output in the following manner.
'45 is Fourth five when and are multiplied'

Note:

*

*The number may or may not present at the beginning.

*Inside the sentence, there can be alphanumeric (460KG), then it should be changed (KG). That means, except at the beginning, the number should be removed elsewhere.
example :
6-apples price is 56Rs

I need an output as
6-apples price is Rs

A: You can use this:
x = '45 is fourth five 45 when 9 and 5 are multiplied'

string = re.sub(r'(?<!^)\b\d+\s', '', x)

Result:
>>> print(string)

45 is fourth five when and are multiplied

A: Using Pypi regex library, you can do:
import regex

x = '45 is fourth five 45 when 9 and 5 are multiplied'
print regex.sub(r'(?<=\D*\d+\D+)\d+ ?', '', x)

Output:
45 is fourth five when and are multiplied

Explanation:
(?<=        # positive lookbehind, make sure we have before:
    \D*         # 0 or more non digits
    \d+         # 1 or more digits
    \D+         # 1 or more non digits
)           # end lookbehind
\d+         # 1 or more digits
 ?          # optional space


Q: Eclipse Marketplace hangs (Luna, Java8) My newly installed Eclipse Luna hangs when I launch Marketplace. I tried to move my workspace out of the way, clean everything, re-install and start fresh.
It would still hang and has to be killed -9.  I saved the stack trace (as well as versions of the OS, Java, and Eclipse) at https://gist.github.com/c51821cbd4e676cd7c9f
The funny part is, things go just fine if I switch back Java1.7.0_25.  I'd like to use Java8 though.
Is that a known problem and are there ways around it?

A: I would try to un-install and install again the Java8 JDK. Have you tried that?
Have you got multiple JDK installed? If yes try with just Java8 (un-install the others).
Or try also to run eclipse with
eclipse -vm c:\java8path\jre\bin\javaw.exe

or
eclipse -vm c:\java8path\jre\bin\client\jvm.dll


Q: The adjoint representation defines an action on the Grassmannian Let $G$ be a Lie group and $H$ be any Lie subgroup. Regard the Lie algebra $\mathfrak h$ as a point in the Grasmannian $Gr_k(\mathfrak g)$ where $k:=\dim _\mathbb R \mathfrak h$.
I want to understand why the adjoint representation $Ad :G\to GL_\mathbb R(\mathfrak g)$ yields a smooth action of $G$ on  $Gr_k(\mathfrak g)$ and why the isotropy group $G_\mathfrak h$ is the normalizer
$$N_G(H^0):=\{g\in G; \ gH^0g^{-1}=H^0\}$$
where $H^0$ is the identity connected component.

A: Let $V$ be a (real) vector space, let $U\subset V$ be a linear subspace, and let $T:V\to V$ be a linear automorphism. Then $T$ carries $U$ to another linear subspace of the same dimension as $U$. This explains why a group action on $V$ yields an action of the same group on all the Grassmannians of $V$.
The isotropy group $G_\mathfrak{h}$ is defined by $$G_\mathfrak{h}:=\{g\in G\;|\;\mathrm{Ad}_g(\mathfrak{h})=\mathfrak{h}\}.$$ Now, for $g\in G$ and $\xi\in\mathfrak{h}$ we have $$\mathrm{exp}(\mathrm{Ad}_g(\xi))=g\cdot\mathrm{exp}(\xi)\cdot g^{-1}.$$ If $g\in N_G\left(H^0\right)$, then RHS is in $H^0$, which means that $\mathrm{Ad}_g(\xi)\in\mathfrak{h}.$ Conversely, if $g\in G_\mathfrak{h}$, then $\mathrm{Ad}_g(\xi)\in\mathfrak{h},$ and it follows from the above equality that $g\cdot\mathrm{exp}(\xi)\cdot g^{-1}\in H^0.$ The claim now follows from the fact that $H^0$ is generated by $\mathrm{exp}(\mathfrak{h}).$


Q: Resampling of MultiIndex I would like a daily breakdown of a dataset by type.  There are not records for every day for every type, where they don't exist I would like NaN.
I'm able to get a 'resampled to daily' result, but the type is ommitted.
The code below should be a fully working example (well, working apart from the known error at the end!):
import pandas as pd
import datetime as dt

df = pd.DataFrame({
    'Date': [dt.datetime(2021,1,1), dt.datetime(2021, 1, 3), dt.datetime(2020,1,2)],
    'Type': ['A', 'A', 'B'],
    'Value': [1,2,3]
})

df.set_index('Date', inplace=True)
#   this loses the 'type'
print(df.resample('1D').mean())

df = df.reset_index().set_index(['Date', 'Type'])

#   this raises an exception "TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'"
print(df.resample('1D').mean())

Output I'm looking for is a row for every day / type combo:

date
type
value

20210101
A
1

20210102
A
NaN

20210103
A
2

20210101
B
NaN

20210102
B
3

20210103
B
NaN

Any advice or pointers gratefully received.

A: If need resample per groups is possible use Grouper for resample per days and then for add missing values is used Series.unstack with DataFrame.stack:
df = (df.groupby(['Type', pd.Grouper(freq='1D', key='Date')])['Value']
        .mean()
        .unstack()
        .stack(dropna=False)
        .reset_index(name='Value')

      )
print (df)
  Type       Date  Value
0    A 2021-01-01    1.0
1    A 2021-01-02    NaN
2    A 2021-01-03    2.0
3    B 2021-01-01    NaN
4    B 2021-01-02    3.0
5    B 2021-01-03    NaN

If need only append missing datetimes per groups is used DataFrame.reindex:
mux = pd.MultiIndex.from_product([df['Type'].unique(),
                                  pd.date_range(df['Date'].min(), df['Date'].max())],
                                  names=['Date','Type'])
df = df.set_index(['Type','Date']).reindex(mux).reset_index()
print (df)
  Date       Type  Value
0    A 2021-01-01    1.0
1    A 2021-01-02    NaN
2    A 2021-01-03    2.0
3    B 2021-01-01    NaN
4    B 2021-01-02    3.0
5    B 2021-01-03    NaN


Q: Bootstrap carousel image height change according to sm md sx lg The issue is quality of  image at smaller screens i.e 320px 375px 425px gets blur as i mention height in the class.. I am mentioning the height as i want the image to fit screen initially without user needing to scroll down to look for further information
My question here is should i resize the image so that it has quality in it..
Am sharing my code
 CSS
'
.carousel{
    background-color: #2f4357;

}
.carousel .item img{
    margin: 0 auto;
    height:570px;/* Align slide image horizontally center */
}
.bs-example{
    margin: 20px;
}

'
html
    '

'

A: You do not need to set any height or width to images in Bootstrap carousel if you are using them as img source. You need to add height only if you are using them as a background image. For this, you need to add height to .item class and set the background properties for the same.


Q: handling page orientation change in Xamarin When using Xamarin, what is the best or most accepted method of handling changes in orientation?
I have a carousel page which rotates through 5 content pages (the same page, just different text/images), in the content pages I have a 6 row grid, each row containing either an image, text or a button.
When changing from portrait to landscape I reset the size and padding of these within OnSizeAllocated. This seems to work randomly for 3 out of 5 content pages, the text in the other 2 will be out of position, and it's not always the same 3 that work either.
I'm guessing there's a better way to do this than manually resize things?
protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height); //must be called
            if (this.width != width || this.height != height)
            {
                this.width = width;
                this.height = height;
                //reconfigure layout
                if (width > height)
                {
                    img.HeightRequest = 62.5;
                    img.WidthRequest = 62.5;
                    logo.HeightRequest = 52.5;
                    logo.WidthRequest = 142.27;
                    headerStack.Padding = new Thickness(0, -60, 0, 0);
                    txtStack.Padding = new Thickness(20, -60, 20, 0);
                    sIndicator.Padding = new Thickness(20, 0, 20, 100);
                    sButton.Padding = new Thickness(0, -40, 0, 0);
                }
                else
                {
                    img.WidthRequest = 250;
                    img.HeightRequest = 250;
                    logo.HeightRequest = 70;
                    logo.WidthRequest = 189.7;
                    headerStack.Padding = new Thickness(20, 40, 20, 0);
                    txtStack.Padding = new Thickness(20, 0, 20, 0);
                    sIndicator.Padding = new Thickness(20, 25, 20, 0);
                }
            }
        }

A: With a few tweaks to what I was setting I got this working just fine, would still be interested in other peoples' views on how they do it.


Q: Function to show result in multiple divs I need to make this script to print the result (true, or false) for the transparency of the image in the divs according to the area if its transparent or not.
Here is the example where I can see the result if its transparent but only on mouse move and for pixel by pixel according to the pointer.
https://jsfiddle.net/kdichev/0jhazjoa/
Here i have put a overlay over the image with 1/10 of the size square divs which I would like to change colors depending if they have transparent pixels in their area or not
https://jsfiddle.net/kdichev/ae9pjstm/1/
Ideally if there is one pixel below the box it should have a red background color or print in it false.
(function () {
var img = new Image(),
    output = document.getElementById('transparent'),
    bImg = document.getElementById('img');
img.src = bImg.src;

function isTransparent(e) {
    var x = e.pageX - this.offsetLeft,
        y = e.pageY - this.offsetTop;

    var canvas = document.getElementById('imgcheck-canvas') || (function (_this) {
        var e = document.createElement('canvas');
        e.setAttribute('width', _this.width);
        e.setAttribute('height', _this.height);
        e.setAttribute('id', _this.id + '-canvas');
        e.setAttribute('style', 'display:none;');
        document.body.appendChild(e);
        var cx = e.getContext('2d');
        cx.drawImage(_this, 0, 0, _this.width, _this.height);
        return e;
    })(this);
    if (canvas.getContext === undefined) {
        return false;
    }
    var ctx = canvas.getContext('2d');

    output.innerHTML = ((ctx.getImageData(x, y, 1, 1).data[3] === 0) ? true : false);
}

function init() {
    console.log('init');
    bImg.addEventListener('mousemove', isTransparent, false);
}

img.addEventListener('load', init, true);

})();


Q: Object.entries and addEventListener I have this object and I want to display the key in the options that gets created and the value in the .info
 tag. I then want to change the info text, when I change the city by using an addEventListener.
My question is, is it possible to use the info in for(const [city, info] of entries) in a addEventListener function? I tried to have the eventListener in the for loop but that didn't work out right. But can I somehow pass the info to another function? Or is it better too just loop the keys and then do another loop for the values in an addEventListener function?

let citiesWithInfo = {"New York": 'The biggest city in the world.',
    "Los Angeles": 'Home of the Hollywood sign.',
    "Maui": 'A city on the beautiful island of Hawaii.',
    "Vancover": 'It\'s a city where it rains alot. And I mean alot.',
    "Miami": 'The samba city of the world.'
};

const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);

for(const [city, info] of entries) {
    let optionCity = document.createElement("option");
    optionCity.textContent = city;
    optionCity.value = city;
    cityWithInfoPrompt.appendChild(optionCity);

    let currentCity = cityWithInfoPrompt.options[cityWithInfoPrompt.selectedIndex];
    if(currentCity.textContent == city) {
        document.querySelector(".info").textContent = info;
    }
}

    <select name="cities-with-info" id="cities-with-info"></select>

Info:

A: You can attach the event outside the loop where you can match the value between the selected value and the object property name:

let citiesWithInfo = {"New York": 'The biggest city in the world.',
    "Los Angeles": 'Home of the Hollywood sign.',
    "Maui": 'A city on the beautiful island of Hawaii.',
    "Vancover": 'It\'s a city where it rains alot. And I mean alot.',
    "Miami": 'The samba city of the world.'
};

const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);

for(const [city, info] of entries) {
    let optionCity = document.createElement("option");
    optionCity.textContent = city;
    optionCity.value = city;
    cityWithInfoPrompt.appendChild(optionCity);
}

cityWithInfoPrompt.addEventListener('change', function(){
  let currentCity = this.options[this.selectedIndex].value;
  document.querySelector(".info").textContent = citiesWithInfo[currentCity];
});
// On page load
// Create event
var event = new Event('change');
// Dispatch the event
cityWithInfoPrompt.dispatchEvent(event);

    <select name="cities-with-info" id="cities-with-info"></select>

Info:

Solution using  Arrow Function (() => {}) and Event.target

let citiesWithInfo = {"New York": 'The biggest city in the world.',
    "Los Angeles": 'Home of the Hollywood sign.',
    "Maui": 'A city on the beautiful island of Hawaii.',
    "Vancover": 'It\'s a city where it rains alot. And I mean alot.',
    "Miami": 'The samba city of the world.'
};

const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);

for(const [city, info] of entries) {
    let optionCity = document.createElement("option");
    optionCity.textContent = city;
    optionCity.value = city;
    cityWithInfoPrompt.appendChild(optionCity);
}

cityWithInfoPrompt.addEventListener('change', () => {
  let currentCity = event.target.value;
  document.querySelector(".info").textContent = citiesWithInfo[currentCity];
});
// On page load
// Create event
var event = new Event('change');
// Dispatch the event
cityWithInfoPrompt.dispatchEvent(event);

    <select name="cities-with-info" id="cities-with-info"></select>

Info:

A: I used this code for the addEventListener to get the info from the object to the info HTML tag.
cityWithInfoPrompt.addEventListener("change", (e) => {
    let selectedCity = e.target.value
    for(const [city, info] of entries) {
        if(selectedCity == city) {
            document.querySelector(".info").textContent = info;
        }
    }
});


Q: How to integrate git hooks with eclipse I am trying to setup pre-commit hook which we have customized to our requirement .
It is working fine in git bash but it is unable to pick up the hook from eclipse .
How can I integrate or configure so the pre-commit hook gets invoked.