Programs & Examples On #Miniport

Enabling/Disabling Microsoft Virtual WiFi Miniport

You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it. After that, you start your cmd with admin privileges, then try:

netsh wlan start hostednetwork

The thread has exited with code 0 (0x0) with no unhandled exception

Stop this error you have to follow this simple steps

  1. Open Visual Studio
  2. Select option debug from the top
  3. Select Options
  4. In Option Select debugging under debugging select General
  5. In General Select check box "Automatically close the console when debugging stop"
  6. Save it

Then Run the code by using Shortcut key Ctrl+f5

**Other wise it still show error when you run it direct

How to use particular CSS styles based on screen size / device

@media queries serve this purpose. Here's an example:

@media only screen and (max-width: 991px) and (min-width: 769px){
 /* CSS that should be displayed if width is equal to or less than 991px and larger 
  than 768px goes here */
}

@media only screen and (max-width: 991px){
 /* CSS that should be displayed if width is equal to or less than 991px goes here */
}

Git SSH error: "Connect to host: Bad file number"

If SSH is blocked over 22

just update your origin to https

git remote set-url origin https://github.com/ACCOUNT_NAME/REPO_NAME.git

verify that changes were made

git remote -v

Check if a number is int or float

What you can do too is usingtype() Example:

if type(inNumber) == int : print "This number is an int"
elif type(inNumber) == float : print "This number is a float"

Disabling the long-running-script message in Internet Explorer

In my case, while playing video, I needed to call a function everytime currentTime of video updates. So I used timeupdate event of video and I came to know that it was fired at least 4 times a second (depends on the browser you use, see this). So I changed it to call a function every second like this:

var currentIntTime = 0;

var someFunction = function() {
    currentIntTime++;
    // Do something here
} 
vidEl.on('timeupdate', function(){
    if(parseInt(vidEl.currentTime) > currentIntTime) {
        someFunction();
    }
});

This reduces calls to someFunc by at least 1/3 and it may help your browser to behave normally. It did for me !!!

How to use bootstrap datepicker

man you can use the basic Bootstrap Datepicker this way:

<!DOCTYPE html>
<head runat="server">
<title>Test Zone</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Css/datepicker.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../Js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#pickyDate').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

and inside body:

<body>
<div id="testDIV">
    <div class="container">
        <div class="hero-unit">
            <input  type="text" placeholder="click to show datepicker"  id="pickyDate"/>
        </div>
    </div>
</div>

datepicker.css and bootstrap-datepicker.js you can download from here on the Download button below "About" on the left side. Hope this help someone, greetings.

Difference Between One-to-Many, Many-to-One and Many-to-Many?

1) The circles are Entities/POJOs/Beans

2) deg is an abbreviation for degree as in graphs (number of edges)

PK=Primary key, FK=Foreign key

Note the contradiction between the degree and the name of the side. Many corresponds to degree=1 while One corresponds to degree >1.

Illustration of one-to-many many-to-one

How to store printStackTrace into a string

You have to use getStackTrace () method instead of printStackTrace(). Here is a good example:

import java.io.*;

/**
* Simple utilities to return the stack trace of an
* exception as a String.
*/
public final class StackTraceUtil {

  public static String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
  }

  /**
  * Defines a custom format for the stack trace as String.
  */
  public static String getCustomStackTrace(Throwable aThrowable) {
    //add the class name and any message passed to constructor
    final StringBuilder result = new StringBuilder( "BOO-BOO: " );
    result.append(aThrowable.toString());
    final String NEW_LINE = System.getProperty("line.separator");
    result.append(NEW_LINE);

    //add each element of the stack trace
    for (StackTraceElement element : aThrowable.getStackTrace() ){
      result.append( element );
      result.append( NEW_LINE );
    }
    return result.toString();
  }

  /** Demonstrate output.  */
  public static void main (String... aArguments){
    final Throwable throwable = new IllegalArgumentException("Blah");
    System.out.println( getStackTrace(throwable) );
    System.out.println( getCustomStackTrace(throwable) );
  }
} 

The system cannot find the file specified. in Visual Studio

The system cannot find the file specified usually means the build failed (which it will for your code as you're missing a # infront of include, you have a stray >> at the end of your cout line and you need std:: infront of cout) but you have the 'run anyway' option checked which means it runs an executable that doesn't exist. Hit F7 to just do a build and make sure it says '0 errors' before you try running it.

Code which builds and runs:

#include <iostream>

int main()
{
   std::cout << "Hello World";
   system("pause");
   return 0;
}

Extract parameter value from url using regular expressions

Why dont you take the string and split it

Example on the url

var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"

you can do a split as

var params = url.split("?")[1].split("&");

You will get array of strings with params as name value pairs with "=" as the delimiter.

How to redirect 404 errors to a page in ExpressJS?

I used the handler below to handle 404 error with a static .ejs file.

Put this code in a route script and then require that file.js through app.use() in your app.js/server.js/www.js (if using IntelliJ for NodeJS)

You can also use a static .html file.

//Unknown route handler
 router.get("[otherRoute]", function(request, response) {
     response.status(404);
     response.render("error404.[ejs]/[html]");
     response.end();
 });

This way, the running express server will response with a proper 404 error and your website can also include a page that properly displays the server's 404 response properly. You can also include a navbar in that 404 error template that links to other important content of your website.

IIS error, Unable to start debugging on the webserver

Do you use or have IIS Rewrite installed on your machine? I have a similar problem on my machine but to get round it, I have web.config open as the current page in VS and press f5. I then have to navigate to the page to debug. It seems to work for me.

Increase permgen space

On Debian-like distributions you set that in /etc/default/tomcat[67]

Android Studio Gradle Already disposed Module

Sometimes gradlew clean or Invalidate Cache and Restart does not help, because these methods do not clean Android Studio specific files by themselves.

In this case, close AS and remove .idea directory and .iml file in a root project where settings.gradle file exists. This will make AS rebuild from the fresh ground.

Call a global variable inside module

You need to tell the compiler it has been declared:

declare var bootbox: any;

If you have better type information you can add that too, in place of any.

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Occasionally when a disk runs out of space, the message "transaction log for database XXXXXXXXXX is full due to 'LOG_BACKUP'" will be returned when an update SQL statement fails. Check your diskspace :)

Python speed testing - Time Difference - milliseconds

I am not a Python programmer, but I do know how to use Google and here's what I found: you use the "-" operator. To complete your code:

from datetime import datetime

tstart = datetime.now()

# code to speed test

tend = datetime.now()
print tend - tstart

Additionally, it looks like you can use the strftime() function to format the timespan calculation in order to render the time however makes you happy.

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

How can I call a method in Objective-C?

I think what you're trying to do is:

-(void) score2 {
    [self score];
}

The [object message] syntax is the normal way to call a method in objective-c. I think the @selector syntax is used when the method to be called needs to be determined at run-time, but I don't know well enough to give you more information on that.

Finding the average of an array using JS

With ES6 you can turn Andy's solution into as a one-liner:

_x000D_
_x000D_
let average = (array) => array.reduce((a, b) => a + b) / array.length;_x000D_
console.log(average([1,2,3,4,5]));
_x000D_
_x000D_
_x000D_

Hibernate: How to fix "identifier of an instance altered from X to Y"?

I solve this by instancing a new instance of depending Object. For an example

instanceA.setInstanceB(new InstanceB());
instanceA.setInstanceB(YOUR NEW VALUE);

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

Open Popup window using javascript

First point is- showing multiple popups is not desirable in terms of usability.

But you can achieve it by using multiple popup names

var newwindow;
function createPop(url, name)
{    
   newwindow=window.open(url,name,'width=560,height=340,toolbar=0,menubar=0,location=0');  
   if (window.focus) {newwindow.focus()}
}

Better approach will be showing both in a single page in two different iFrames or Divs.

Update:

So I will suggest to create a new tab in the test.aspx page to show the report, instead of replacing the image content and placing the pdf.

How does true/false work in PHP?

This is covered in the PHP documentation for booleans and type comparison tables.

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string '0'
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE.

Open Facebook page from Android app?

Best answer I have found, it's working great.

Just go to your page on Facebook in the browser, right click, and click on "View source code", then find the page_id attribute: you have to use page_id here in this line after the last back-slash:

fb://page/pageID

For example:

Intent facebookAppIntent;
try {
    facebookAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/1883727135173361"));
    startActivity(facebookAppIntent);
} catch (ActivityNotFoundException e) {
    facebookAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://facebook.com/CryOut-RadioTv-1883727135173361"));
    startActivity(facebookAppIntent);
}

Npm Please try using this command again as root/administrator

Here is how I fixed the problem in Windows. I was trying to install the CLI for Angular.

  1. Turn off firewall and antivirus protections.

  2. Right click the nodejs folder (under Program Files), select Properties (scroll all the way down), click the Security tab, and click all items in the ALLOW column (for All System Packages and any user or group that allows you to add the “allow” checkmark).

  3. Click the Windows icon. Type cmd. Right click the top result and select Run as Administrator. A command window results.

  4. Type npm cache clean. If there is an error, close log files or anything open and rerun.

  5. Type npm install -g @angular/cli (Or whatever npm install command you are using)

  6. Check the installation by typing ng –version (Or whatever you need to verify your install)

Good luck! Note: If you are still having problems, check the Path in Environmental Variables. (To access: Control Panel ? System and Security ? System ? Advanced system settings ? Environment variables.) My path variable included the following: C:\Users\Michele\AppData\Roaming\npm

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Use Rescue mode with cd and mount the filesystem. Try to check if any binary files or folder are deleted. If deleted you will have to manually install the rpms to get those files back.

https://askubuntu.com/questions/92946/cannot-boot-because-kernel-panic-not-syncing-attempted-to-kill-init

Filling a List with all enum values in Java

I wouldn't use a List in the first places as an EnumSet is more approriate but you can do

List<Something> somethingList = Arrays.asList(Something.values());

or

List<Something> somethingList =
                 new ArrayList<Something>(EnumSet.allOf(Something.class));

Stick button to right side of div

Another solution: change margins. Depending on the siblings of the button, display should be modified.

button {
    display:      block;
    margin-left:  auto;
    margin-right: 0;
}

javascript get child by id

This works well:

function test(el){
  el.childNodes.item("child").style.display = "none";
}

If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.

Change the On/Off text of a toggle button Android

Set the XML as:

<ToggleButton
    android:id="@+id/flashlightButton"
    style="@style/Button"
    android:layout_above="@+id/buttonStrobeLight"
    android:layout_marginBottom="20dp"
    android:onClick="onToggleClicked"
    android:text="ToggleButton"
    android:textOn="Light ON"
    android:textOff="Light OFF" />

What is the difference between "mvn deploy" to a local repo and "mvn install"?

From the Maven docs, sounds like it's just a difference in which repository you install the package into:

  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Maybe there is some confusion in that "install" to the CI server installs it to it's local repository, which then you as a user are sharing?

Using C++ filestreams (fstream), how can you determine the size of a file?

You can seek until the end, then compute the difference:

std::streampos fileSize( const char* filePath ){

    std::streampos fsize = 0;
    std::ifstream file( filePath, std::ios::binary );

    fsize = file.tellg();
    file.seekg( 0, std::ios::end );
    fsize = file.tellg() - fsize;
    file.close();

    return fsize;
}

Can there exist two main methods in a Java program?

the possibility of two main(String[] args) methods within the same scope create confusion for the JVM. It fails to use them as overloaded methods. So the signatures in terms of parameters) must be different.

PHP Fatal error: Call to undefined function mssql_connect()

I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line

; On windows: extension_dir = "ext"

I changed it to:

; On windows: extension_dir = "C:\php\ext"

And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.

SQL Logic Operator Precedence: And and Or

I'll add 2 points:

  • "IN" is effectively serial ORs with parentheses around them
  • AND has precedence over OR in every language I know

So, the 2 expressions are simply not equal.

WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
     (
     some_col = 1 OR
     some_col = 2 OR 
     some_col = 3 OR 
     some_col = 4 OR 
     some_col = 5
     )
     AND
     some_other_expr

So, when you break the IN clause up, you split the serial ORs up, and changed precedence.

How to iterate over a TreeMap?

    //create TreeMap instance
    TreeMap treeMap = new TreeMap();

    //add key value pairs to TreeMap
    treeMap.put("1","One");
    treeMap.put("2","Two");
    treeMap.put("3","Three");

    /*
      get Collection of values contained in TreeMap using
      Collection values()        
    */
    Collection c = treeMap.values();

    //obtain an Iterator for Collection
    Iterator itr = c.iterator();

    //iterate through TreeMap values iterator
    while(itr.hasNext())
      System.out.println(itr.next());

or:

   for (Map.Entry<K,V> entry : treeMap.entrySet()) {
        V value = entry.getValue();
        K key = entry.getKey();
   }

or:

   // Use iterator to display the keys and associated values
   System.out.println("Map Values Before: ");
   Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
     System.out.println(key + " = " + value);
   }

When does Java's Thread.sleep throw InterruptedException?

The InterruptedException is usually thrown when a sleep is interrupted.

Observable Finally on Subscribe

The only thing which worked for me is this

fetchData()
  .subscribe(
    (data) => {
       //Called when success
     },
    (error) => {
       //Called when error
    }
  ).add(() => {
       //Called when operation is complete (both success and error)
  });

Get current URL with jQuery?

 var currenturl = jQuery(location).attr('href');

Xcode project not showing list of simulators

For those coming from Unity, even if you manage to make them show up (by changing Build Settings > Supported Platforms to iOS it would not run in the simulator.

Instead, you need to select this Simulator SDK :

enter image description here

And make sure something other than Metal exist.

enter image description here

Then the simulator device list will be there from start.

How to pass data from Javascript to PHP and vice versa?

There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.

<script language="javascript" type="text/javascript">
 function _vals(target, value){
   form1.all("target").value=target;
   form1.all("value").value=value;
   form1.submit();
 }
</script>

Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.

I'm sure there's probably more methods which are better, but these are just a few that spring to mind.

EDIT: Building on this from what others have said using the above method you would have an anchor tag like

<a onclick="_vals('name', 'val')" href="#">My Link</a>

And then in your PHP you can get form data using

$val = $_POST['value'];

So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.

How do I unload (reload) a Python module?

2018-02-01

  1. module foo must be imported successfully in advance.
  2. from importlib import reload, reload(foo)

31.5. importlib — The implementation of import — Python 3.6.4 documentation

How can I color dots in a xy scatterplot according to column value?

Recently I had to do something similar and I resolved it with the code below. Hope it helps!

Sub ColorCode()
Dim i As Integer
Dim j As Integer
i = 2
j = 1

Do While ActiveSheet.Cells(i, 1) <> ""


If Cells(i, 5).Value = "RED" Then
ActiveSheet.ChartObjects("YourChartName").Chart.FullSeriesCollection(1).Points(j).MarkerForegroundColor = RGB(255, 0, 0)



Else

If Cells(i, 5).Value = "GREEN" Then
ActiveSheet.ChartObjects("YourChartName").Chart.FullSeriesCollection(1).Points(j).MarkerForegroundColor = RGB(0, 255, 0)

Else

If Cells(i, 5).Value = "GREY" Then
ActiveSheet.ChartObjects("YourChartName").Chart.FullSeriesCollection(1).Points(j).MarkerForegroundColor = RGB(192, 192, 192)

Else

If Cells(i, 5).Value = "YELLOW" Then
ActiveSheet.ChartObjects("YourChartName").Chart.FullSeriesCollection(1).Points(j).MarkerForegroundColor = RGB(255, 255, 0)

End If
End If
End If
End If

i = i + 1
j = j + 1

Loop



End Sub

Bootstrap 4 navbar color

You can just use "!important" to get your custom color

.navbar {
 background-color: yourcolor !important;
 }

iOS 7 status bar back to iOS 6 default style in iPhone app?

I am late for this Answer, but i just want to share what i did, which is basically the easiest solution

First of all-> Go to your info.plist File and add Status Bar Style->Transparent Black Style(Alpha of 0.5)

Now ,here it Goes:-

Add this code in your AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
     //Whatever your code goes here
  if(kDeviceiPad){

     //adding status bar for IOS7 ipad
         if (IS_IOS7) {
              UIView *addStatusBar = [[UIView alloc] init];
              addStatusBar.frame = CGRectMake(0, 0, 1024, 20);
              addStatusBar.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; //change this to match your navigation bar
              [self.window.rootViewController.view addSubview:addStatusBar];
                    }
                }
    else{

         //adding status bar for IOS7 iphone
        if (IS_IOS7) {
            UIView *addStatusBar = [[UIView alloc] init];
            addStatusBar.frame = CGRectMake(0, 0, 320, 20);
            addStatusBar.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; //You can give your own color pattern
            [self.window.rootViewController.view addSubview:addStatusBar];
        }

    return YES;
   }

XAMPP on Windows - Apache not starting

I spent over 3 hours to find out solution. Actually port 80 was being used by "system" service so I tried to change port from 80 to 8080 in "httpd" file but same problem raised "port 80 is used by system". It had driven me mad for 3 hours as every thing was changed like port , localhost server etc pointing to 8080.

At last I found mistake that was server root. Basically "Server Root" in "httpd" should be pointing to apache foler of xampp. In my case that's was

ServerRoot "xampp/apache"

I just changed it as follows:

ServerRoot "C:/xampp/apache" 

It has worked successfully and now everything is running with OK status.

How can I change the width and height of slides on Slick Carousel?

I initialised the slider with one of the properties as

variableWidth: true

then i could set the width of the slides to anything i wanted in CSS with:

.slick-slide {
    width: 200px;
}

File changed listener in Java

I've written a log file monitor before, and I found that the impact on system performance of polling the attributes of a single file, a few times a second, is actually very small.

Java 7, as part of NIO.2 has added the WatchService API

The WatchService API is designed for applications that need to be notified about file change events.

How do I view / replay a chrome network debugger har file saved with content?

  1. Open Chrome & click F12
  2. Click Network
  3. Drag and drop the har file in the chrome network tab.

enter image description here

Git push error '[remote rejected] master -> master (branch is currently checked out)'

Here is one test you can do to see how the bare server stuff work:

Imagine you have a workstation and a server with live site hosted on it, and you want to update this site from time to time (this also applies to a situation where two developers are sending their work back and forth through a bare middleman).

Initialization

Create some directory on your local computer and cd into it, then execute these commands:

# initialization
git init --bare server/.git
git clone server content
git clone server local
  1. First you create a bare server directory (notice the .git at the end). This directory will serve as a container for your repository files only.
  2. Then clone your server repository to a newly created content directory. This is your live/production directory which will be served by your server software.
  3. The first two directories resides on your server, the third one is a local directory on your workstation.

Workflow

Now here is the basic workflow:

  1. Enter the local directory, create some files and commit them. Finally push them to the server:

    # create crazy stuff
    git commit -av
    git push origin master
    
  2. Now enter the content directory and update the server's content:

    git pull
    
  3. Repeat 1-2. Here content may be another developer that can push to the server too, and local as you may pull from him.

How to programmatically disable page scrolling with jQuery

You can cover-up the window with a scrollable div for preventing scrolling of the content on a page. And, by hiding and showing, you can lock/unlock your scroll.

Do something like this:

#scrollLock {
    width: 100%;
    height: 100%;
    position: fixed;
    overflow: scroll;
    opacity: 0;
    display:none
}

#scrollLock > div {
    height: 99999px;
}

function scrollLock(){
    $('#scrollLock').scrollTop('10000').show();
}

function scrollUnlock(){
    $('#scrollLock').hide();
}

Hiding axis text in matplotlib plots

If you are like me and don't always retrieve the axes, ax, when plotting the figure, then a simple solution would be to do

plt.xticks([])
plt.yticks([])

Cannot find "Package Explorer" view in Eclipse

The simplest, and best long-term solution

Go to the main menu on top of Eclipse and locate Window next to Run and expand it.

 Window->Reset Perspective... to restore all views to their defaults

It will reset the default setting.

Is there a way to disable initial sorting for jquery DataTables?

As per latest api docs:

$(document).ready(function() {
    $('#example').dataTable({
        "order": []
    });
});

More Info

Is it possible to set the stacking order of pseudo-elements below their parent element?

Try it out

el {
  transform-style: preserve-3d;
}
el:after {
  transform: translateZ(-1px);
}

ORA-12170: TNS:Connect timeout occurred

Issue because connection establishment or communication with a client failed to complete within the allotted time interval. This may be a result of network or system delays.

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

Script not served by static file handler on IIS7.5

I stumbled upon this question when I ran into the same issue. The root cause of my issue was an incorrectly-configured app pool. It was set for 2.0 inadvertently, when it needed to be set to 4.0. The answer at the following link helped me uncover this issue: http://forums.iis.net/t/1160143.aspx

Connection Java-MySql : Public Key Retrieval is not allowed

If you are getting the following error while connecting the mysql (either local or mysql container running the mysql):

java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed

Solution: Add the following line in your database service:

command: --default-authentication-plugin=mysql_native_password

commons httpclient - Adding query string parameters to GET/POST request

If you want to add a query parameter after you have created the request, try casting the HttpRequest to a HttpBaseRequest. Then you can change the URI of the casted request:

HttpGet someHttpGet = new HttpGet("http://google.de");

URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
        "That was easy!").build();

((HttpRequestBase) someHttpGet).setURI(uri);

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

Changing file permission in Python

No need to remember flags. Remember that you can always do:

subprocess.call(["chmod", "a-w", "file/path])

Not portable but easy to write and remember:

  • u - user
  • g - group
  • o - other
  • a - all
  • + or - (add or remove permission)
  • r - read
  • w - write
  • x - execute

Refer man chmod for additional options and more detailed explanation.

Linking a qtDesigner .ui file to python/pyqt?

In order to compile .ui files to .py files, I did:

python pyuic.py form1.ui > form1.py

Att.

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:

location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
{
    root   /path/to/static-content;
}

location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic

C#: How to add subitems in ListView

add:

.SubItems.Add("asdasdasd");

to the last line of your code so it will look like this in the end.

listView1.Items.Add("sdasdasdasd").SubItems.Add("asdasdasd");

Pandas DataFrame to List of Lists

This is very simple:

import numpy as np

list_of_lists = np.array(df)

Converting an integer to a hexadecimal string in Ruby

You can give to_s a base other than 10:

10.to_s(16)  #=> "a"

Note that in ruby 2.4 FixNum and BigNum were unified in the Integer class. If you are using an older ruby check the documentation of FixNum#to_s and BigNum#to_s

Node.js request CERT_HAS_EXPIRED

Try to temporarily modify request.js and harcode everywhere rejectUnauthorized = true, but it would be better to get the certificate extended as a long-term solution.

What is difference between mutable and immutable String in java

A mutable variable is one whose value may change in place, whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable.

Cannot find vcvarsall.bat when running a Python script

I tried the solution here to set an environment variable via the command line, but this didn't work. I did this both from a regular command prompt and from the Visual Studio Developer command prompt.

I could overcome this problem like this:

  1. go to the Environment variables screen and created a new variable there VS100COMNTOOLS and let it point to my Visual Studio installation folder C:\Program Files\Microsoft Visual Studio 12.0\Common7\Tools\
  2. Go to the above folder. Inside this folder there is the file vsvars32.bat. Copy this file and rename it to vsvarsall.bat

My configuration is Visual Studio 2013 (12.0) and Python 3.4.2

How Many Seconds Between Two Dates?

.Net provides the TimeSpan class to do the math for you.

var time1 = new Date(YYYY, MM, DD, 0, 0, 0, 0)
var time2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0)

Dim ts As TimeSpan = time2.Subtract(time1)

ts.TotalSeconds

Install specific branch from github using Npm

There are extra square brackets in the command you tried.

To install the latest version from the v1 branch, you can use:

npm install git://github.com/shakacode/bootstrap-loader.git#v1 --save

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

In case it helps someone, I had a similar issue and the error was because of two reasons:

  1. Not using the app's namespace before the url name

    {% url 'app_name:url_name' %}
    
  2. Missing single quotes around the url name (as pointed out here by Charlie)

How to print out more than 20 items (documents) in MongoDB's shell?

Could always do:

db.foo.find().forEach(function(f){print(tojson(f, '', true));});

To get that compact view.

Also, I find it very useful to limit the fields returned by the find so:

db.foo.find({},{name:1}).forEach(function(f){print(tojson(f, '', true));});

which would return only the _id and name field from foo.

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

How can I determine whether a specific file is open in Windows?

In OpenedFilesView, under the Options menu, there is a menu item named "Show Network Files". Perhaps with that enabled, the aforementioned utility is of some use.

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

Wouldn't you be better off with

<asp:HyperLink ID="HyperLink1" runat="server" 
            NavigateUrl="CMS_1.aspx" 
            Target="_blank">
    Click here
</asp:HyperLink>

Because, to replicate your desired behavior on an asp:Button, you have to call window.open on the OnClientClick event of the button which looks a lot less cleaner than the above solution. Plus asp:HyperLink is there to handle scenarios like this.

If you want to replicate this using an asp:Button, do this.

<asp:Button ID="btn" runat="Server" 
        Text="SUBMIT"
        OnClientClick="javascript:return openRequestedPopup();"/>

JavaScript function.

var windowObjectReference;

function openRequestedPopup() {
    windowObjectReference = window.open("CMS_1.aspx",
              "DescriptiveWindowName",
              "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
}

How to fix IndexError: invalid index to scalar variable

Basically, 1 is not a valid index of y. If the visitor is comming from his own code he should check if his y contains the index which he tries to access (in this case the index is 1).

How do I create my own URL protocol? (e.g. so://...)

Here's a list of the registered URI schemes. Each one has an RFC - a document defining it, which is almost a standard. The RFC tells the developers of new applications (such as browsers, ftp clients, etc.) what they need to support. If you need a new base-level protocol, you can use an unregistered one. The other answers tell you how. Please keep in mind you can do lots of things with the existing protocols, thus gaining their existing implementations.

How to use shared memory with Linux in C

Here's a mmap example:

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/*
 * pvtmMmapAlloc - creates a memory mapped file area.  
 * The return value is a page-aligned memory value, or NULL if there is a failure.
 * Here's the list of arguments:
 * @mmapFileName - the name of the memory mapped file
 * @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
 * @create - determines whether or not the area should be created.
 */
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)  
{      
  void * retv = NULL;                                                                                              
  if (create)                                                                                         
  {                                                                                                   
    mode_t origMask = umask(0);                                                                       
    int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);                                           
    umask(origMask);                                                                                  
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      perror("open mmapFd failed");                                                                   
      return NULL;                                                                                    
    }                                                                                                 
    if ((ftruncate(mmapFd, size) == 0))               
    {                                                                                                 
      int result = lseek(mmapFd, size - 1, SEEK_SET);               
      if (result == -1)                                                                               
      {                                                                                               
        perror("lseek mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               

      /* Something needs to be written at the end of the file to                                      
       * have the file actually have the new size.                                                    
       * Just writing an empty string at the current file position will do.                           
       * Note:                                                                                        
       *  - The current position in the file is at the end of the stretched                           
       *    file due to the call to lseek().  
              *  - The current position in the file is at the end of the stretched                    
       *    file due to the call to lseek().                                                          
       *  - An empty string is actually a single '\0' character, so a zero-byte                       
       *    will be written at the last byte of the file.                                             
       */                                                                                             
      result = write(mmapFd, "", 1);                                                                  
      if (result != 1)                                                                                
      {                                                                                               
        perror("write mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
      retv  =  mmap(NULL, size,   
                  PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                     

      if (retv == MAP_FAILED || retv == NULL)                                                         
      {                                                                                               
        perror("mmap");                                                                               
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
    }                                                                                                 
  }                                                                                                   
  else                                                                                                
  {                                                                                                   
    int mmapFd = open(mmapFileName, O_RDWR, 00666);                                                   
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      return NULL;                                                                                    
    }                                                                                                 
    int result = lseek(mmapFd, 0, SEEK_END);                                                          
    if (result == -1)                                                                                 
    {                                                                                                 
      perror("lseek mmapFd failed");                  
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 
    if (result == 0)                                                                                  
    {                                                                                                 
      perror("The file has 0 bytes");                           
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                              
    retv  =  mmap(NULL, size,     
                PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                       

    if (retv == MAP_FAILED || retv == NULL)                                                           
    {                                                                                                 
      perror("mmap");                                                                                 
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 

    close(mmapFd);                                                                                    

  }                                                                                                   
  return retv;                                                                                        
}                                                                                                     

Enter key press in C#

private void Input_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            MessageBox.Show("Enter pressed");
        }
    }

This worked for me.

Regular expression \p{L} and \p{N}

These are Unicode property shortcuts (\p{L} for Unicode letters, \p{N} for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)

At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:

[\p{L}\p{N}_.-]*

How to convert characters to HTML entities using plain JavaScript

Best solution is posted at phpjs.org implementation of PHP function htmlentities

The format is htmlentities(string, quote_style, charset, double_encode) Full documentation on the PHP function which is identical can be read here

reading external sql script in python

A very simple way to read an external script into an sqlite database in python is using executescript():

import sqlite3

conn = sqlite3.connect('csc455_HW3.db')

with open('ZooDatabase.sql', 'r') as sql_file:
    conn.executescript(sql_file.read())

conn.close()

System.Net.WebException: The remote name could not be resolved:

Open the hosts file located at : **C:\windows\system32\drivers\etc**.

Hosts file is for what?

Add the following at end of this file :

YourServerIP YourDNS

Example:

198.168.1.1 maps.google.com

Access Google's Traffic Data through a Web Service

There is no way (or at least no reasonably easy and convenient way) to get the raw traffic data from Google Maps Javascript API v3. Even if you could do it, doing so is likely to violate some clause in the Terms Of Service for Google Maps. You would have to get this information from another service. I doubt there is a free service that provides this information at the current time, but I would love it if someone proved me wrong on that.

As @crdzoba points out, Bing Maps API exposes some traffic data. Perhaps that can fill your needs. It's not clear from the documentation how much traffic data that exposes as it's only data about "incidents". Slow traffic due to construction would be in there, but it's not obvious to me whether slow traffic due simply to volume would be.

UPDATE (March 2016): A lot has happened since this answer was written in 2011, but the core points appear to hold up: You won't find raw traffic data in free API services (at least not for the U.S., and probably not most other places). But if you don't mind paying a bit and/or if you just need things like "travel time for a specific route taking traffic into consideration" you have options. @Anto's answer, for example, points to Google's Maps For Work as a paid API service that allows you to get travel times taking traffic into consideration.

Custom format for time command

To use the Bash builtin time rather than /bin/time you can set this variable:

TIMEFORMAT='%3R'

which will output the real time that looks like this:

5.009

or

65.233

The number specifies the precision and can range from 0 to 3 (the default).

You can use:

TIMEFORMAT='%3lR'

to get output that looks like:

3m10.022s

The l (ell) gives a long format.

NULL or BLANK fields (ORACLE)

A NULL column is not countable, however a row that has a NULL column is. So, this should do what you're looking for:

SELECT COUNT (*) FROM TABLE WHERE COL_NAME IS NULL OR LENGTH(TRIM (COL_NAME)) = 0

Note, that there are non-printing characters that this will not address. For example U+00A0 is the non-breaking space character and a line containing that will visually appear empty, but will not be found by the tests above.

Elasticsearch query to return all records

If you want to pull many thousands of records then... a few people gave the right answer of using 'scroll' (Note: Some people also suggested using "search_type=scan". This was deprecated, and in v5.0 removed. You don't need it)

Start with a 'search' query, but specifying a 'scroll' parameter (here I'm using a 1 minute timeout):

curl -XGET 'http://ip1:9200/myindex/_search?scroll=1m' -d '
{
    "query": {
            "match_all" : {}
    }
}
'

That includes your first 'batch' of hits. But we are not done here. The output of the above curl command would be something like this:

{"_scroll_id":"c2Nhbjs1OzUyNjE6NU4tU3BrWi1UWkNIWVNBZW43bXV3Zzs1Mzc3OkhUQ0g3VGllU2FhemJVNlM5d2t0alE7NTI2Mjo1Ti1TcGtaLVRaQ0hZU0FlbjdtdXdnOzUzNzg6SFRDSDdUaWVTYWF6YlU2Uzl3a3RqUTs1MjYzOjVOLVNwa1otVFpDSFlTQWVuN211d2c7MTt0b3RhbF9oaXRzOjIyNjAxMzU3Ow==","took":109,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":22601357,"max_score":0.0,"hits":[]}}

It's important to have _scroll_id handy as next you should run the following command:

    curl -XGET  'localhost:9200/_search/scroll'  -d'
    {
        "scroll" : "1m", 
        "scroll_id" : "c2Nhbjs2OzM0NDg1ODpzRlBLc0FXNlNyNm5JWUc1" 
    }
    '

However, passing the scroll_id around is not something designed to be done manually. Your best bet is to write code to do it. e.g. in java:

    private TransportClient client = null;
    private Settings settings = ImmutableSettings.settingsBuilder()
                  .put(CLUSTER_NAME,"cluster-test").build();
    private SearchResponse scrollResp  = null;

    this.client = new TransportClient(settings);
    this.client.addTransportAddress(new InetSocketTransportAddress("ip", port));

    QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
    scrollResp = client.prepareSearch(index).setSearchType(SearchType.SCAN)
                 .setScroll(new TimeValue(60000))                            
                 .setQuery(queryBuilder)
                 .setSize(100).execute().actionGet();

    scrollResp = client.prepareSearchScroll(scrollResp.getScrollId())
                .setScroll(new TimeValue(timeVal))
                .execute()
                .actionGet();

Now LOOP on the last command use SearchResponse to extract the data.

What is the scope of variables in JavaScript?

Variables declared globally have a global scope. Variables declared within a function are scoped to that function, and shadow global variables of the same name.

(I'm sure there are many subtleties that real JavaScript programmers will be able to point out in other answers. In particular I came across this page about what exactly this means at any time. Hopefully this more introductory link is enough to get you started though.)

Hibernate Error executing DDL via JDBC Statement

Dialects are removed in recent SQL so use

  <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect"/>

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

If other solutions doesn't work for you, just try (as root) this:

amportal restart

Hope it helps ;-)

NameError: name 'reduce' is not defined in Python

you need to install and import reduce from functools python package

Creating a very simple linked list

public class Node<T>
{
    public T item;
    public Node<T> next;
    public Node()
    {
        this.next = null;
    }
}


class LinkList<T>
{
    public Node<T> head { get; set; }
    public LinkList()
    {
        this.head = null;
    }


    public void AddAtHead(T item)
    {
        Node<T> newNode = new Node<T>();
        newNode.item = item;
        if (this.head == null)
        {
            this.head = newNode;
        }
        else
        {
            newNode.next = head;
            this.head = newNode;
        }
    }

    public void AddAtTail(T item)
    {
        Node<T> newNode = new Node<T>();
        newNode.item = item;
        if (this.head == null)
        {
            this.head = newNode;
        }
        else
        {
            Node<T> temp = this.head;
            while (temp.next != null)
            {
                temp = temp.next;
            }
            temp.next = newNode;
        }
    }

    public void DeleteNode(T item)
    {
        if (this.head.item.Equals(item))
        {
            head = head.next;
        }
        else
        {
            Node<T> temp = head;
            Node<T> tempPre = head;
            bool matched = false;
            while (!(matched = temp.item.Equals(item)) && temp.next != null)
            {
                tempPre = temp;
                temp = temp.next;
            }
            if (matched)
            {
                tempPre.next = temp.next;
            }
            else
            {
                Console.WriteLine("Value not found!");
            }
        }
    }

    public bool searchNode(T item)
    {
        Node<T> temp = this.head;
        bool matched = false;
        while (!(matched = temp.item.Equals(item)) && temp.next != null)
        {
            temp = temp.next;
        }
        return matched;

    }
    public void DisplayList()
    {
        Console.WriteLine("Displaying List!");
        Node<T> temp = this.head;
        while (temp != null)
        {
            Console.WriteLine(temp.item);
            temp = temp.next;
        }
    }

}

Select a Dictionary<T1, T2> with LINQ

var dictionary = (from x in y 
                  select new SomeClass
                  {
                      prop1 = value1,
                      prop2 = value2
                  }
                  ).ToDictionary(item => item.prop1);

That's assuming that SomeClass.prop1 is the desired Key for the dictionary.

How do I pre-populate a jQuery Datepicker textbox with today's date?

Try this

$(this).datepicker("destroy").datepicker({
            changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: "dd-mm-yy",  showOn: "focus", yearRange: "-5:+10"
        }).focus();

set the iframe height automatically

If you a framework like Bootstrap you can make any iframe video responsive by using this snippet:

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" src="vid.mp4" allowfullscreen></iframe>
</div>

C++: Print out enum value as text

This solution doesn't require you to use any data structures or make a different file.

Basically, you define all your enum values in a #define, then use them in the operator <<. Very similar to @jxh's answer.

ideone link for final iteration: http://ideone.com/hQTKQp

Full code:

#include <iostream>

#define ERROR_VALUES ERROR_VALUE(NO_ERROR)\
ERROR_VALUE(FILE_NOT_FOUND)\
ERROR_VALUE(LABEL_UNINITIALISED)

enum class Error
{
#define ERROR_VALUE(NAME) NAME,
    ERROR_VALUES
#undef ERROR_VALUE
};

inline std::ostream& operator<<(std::ostream& os, Error err)
{
    int errVal = static_cast<int>(err);
    switch (err)
    {
#define ERROR_VALUE(NAME) case Error::NAME: return os << "[" << errVal << "]" #NAME;
    ERROR_VALUES
#undef ERROR_VALUE
    default:
        // If the error value isn't found (shouldn't happen)
        return os << errVal;
    }
}

int main() {
    std::cout << "Error: " << Error::NO_ERROR << std::endl;
    std::cout << "Error: " << Error::FILE_NOT_FOUND << std::endl;
    std::cout << "Error: " << Error::LABEL_UNINITIALISED << std::endl;
    return 0;
}

Output:

Error: [0]NO_ERROR
Error: [1]FILE_NOT_FOUND
Error: [2]LABEL_UNINITIALISED

A nice thing about doing it this way is that you can also specify your own custom messages for each error if you think you need them:

#include <iostream>

#define ERROR_VALUES ERROR_VALUE(NO_ERROR, "Everything is fine")\
ERROR_VALUE(FILE_NOT_FOUND, "File is not found")\
ERROR_VALUE(LABEL_UNINITIALISED, "A component tried to the label before it was initialised")

enum class Error
{
#define ERROR_VALUE(NAME,DESCR) NAME,
    ERROR_VALUES
#undef ERROR_VALUE
};

inline std::ostream& operator<<(std::ostream& os, Error err)
{
    int errVal = static_cast<int>(err);
    switch (err)
    {
#define ERROR_VALUE(NAME,DESCR) case Error::NAME: return os << "[" << errVal << "]" #NAME <<"; " << DESCR;
    ERROR_VALUES
#undef ERROR_VALUE
    default:
        return os << errVal;
    }
}

int main() {
    std::cout << "Error: " << Error::NO_ERROR << std::endl;
    std::cout << "Error: " << Error::FILE_NOT_FOUND << std::endl;
    std::cout << "Error: " << Error::LABEL_UNINITIALISED << std::endl;
    return 0;
}

Output:

Error: [0]NO_ERROR; Everything is fine
Error: [1]FILE_NOT_FOUND; File is not found
Error: [2]LABEL_UNINITIALISED; A component tried to the label before it was initialised

If you like making your error codes/descriptions very descriptive, you might not want them in production builds. Turning them off so only the value is printed is easy:

inline std::ostream& operator<<(std::ostream& os, Error err)
{
    int errVal = static_cast<int>(err);
    switch (err)
    {
    #ifndef PRODUCTION_BUILD // Don't print out names in production builds
    #define ERROR_VALUE(NAME,DESCR) case Error::NAME: return os << "[" << errVal << "]" #NAME <<"; " << DESCR;
        ERROR_VALUES
    #undef ERROR_VALUE
    #endif
    default:
        return os << errVal;
    }
}

Output:

Error: 0
Error: 1
Error: 2

If this is the case, finding error number 525 would be a PITA. We can manually specify the numbers in the initial enum like this:

#define ERROR_VALUES ERROR_VALUE(NO_ERROR, 0, "Everything is fine")\
ERROR_VALUE(FILE_NOT_FOUND, 1, "File is not found")\
ERROR_VALUE(LABEL_UNINITIALISED, 2, "A component tried to the label before it was initialised")\
ERROR_VALUE(UKNOWN_ERROR, -1, "Uh oh")

enum class Error
{
#define ERROR_VALUE(NAME,VALUE,DESCR) NAME=VALUE,
    ERROR_VALUES
#undef ERROR_VALUE
};

inline std::ostream& operator<<(std::ostream& os, Error err)
{
    int errVal = static_cast<int>(err);
    switch (err)
    {
#ifndef PRODUCTION_BUILD // Don't print out names in production builds
#define ERROR_VALUE(NAME,VALUE,DESCR) case Error::NAME: return os << "[" #VALUE  "]" #NAME <<"; " << DESCR;
    ERROR_VALUES
#undef ERROR_VALUE
#endif
    default:
        return os <<errVal;
    }
}
    ERROR_VALUES
#undef ERROR_VALUE
#endif
    default:
    {
        // If the error value isn't found (shouldn't happen)
        return os << static_cast<int>(err);
        break;
    }
    }
}

Output:

Error: [0]NO_ERROR; Everything is fine
Error: [1]FILE_NOT_FOUND; File is not found
Error: [2]LABEL_UNINITIALISED; A component tried to the label before it was initialised
Error: [-1]UKNOWN_ERROR; Uh oh

CSS to line break before/after a particular `inline-block` item

Maybe it's is completely possible with only CSS but I prefer to avoid "float" as much as I can because it interferes with it's parent's height.

If you are using jQuery, you can create a simple `wrapN` plugin that is similar to `wrapAll` except it only wraps "N" elements and then breaks and wraps the next "N" elements using a loop. Then set your wrappers class to `display: block;`.

(function ($) {
    $.fn.wrapN = function (wrapper, n, start) {
        if (wrapper === undefined || n === undefined) return false;
        if (start === undefined) start = 0;
        for (var i = start; i < $(this).size(); i += n)
           $(this).slice(i, i + n).wrapAll(wrapper);
        return this;
    };
}(jQuery));

$(document).ready(function () {
    $("li").wrapN("<span class='break' />", 3);
});

Here is a JSFiddle of the finished product:

http://jsfiddle.net/dustinpoissant/L79ahLoz/

How to automatically start a service when running a docker container?

I have the same problem when I want to automatically start ssh service. I found that append

/etc/init.d/ssh start
to
~/.bashrc
can resolve it ,but only you open it with bash will do.

Foreach in a Foreach in MVC View

You have:

foreach (var category in Model.Categories)

and then

@foreach (var product in Model)

Based on that view and model it seems that Model is of type Product if yes then the second foreach is not valid. Actually the first one could be the one that is invalid if you return a collection of Product.

UPDATE:

You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?

I'm surprised your code compiles when you said you are returning a model of Product type. Here's how you can do it:

@foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>

    <div>
        <ul>    
            @foreach (var product in category.Products)
            {
                <li>
                    put the rest of your code
                </li>
            }
        </ul>
    </div>
}

That suggest that instead of returning a Product, you return a collection of Category with Products. Something like this in EF:

// I am typing it here directly 
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)

Why are elementwise additions much faster in separate loops than in a combined loop?

It's because the CPU doesn't have so many cache misses (where it has to wait for the array data to come from the RAM chips). It would be interesting for you to adjust the size of the arrays continually so that you exceed the sizes of the level 1 cache (L1), and then the level 2 cache (L2), of your CPU and plot the time taken for your code to execute against the sizes of the arrays. The graph shouldn't be a straight line like you'd expect.

Show an image preview before upload

HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReader interface which lets web applications asynchronously read the contents of files .

Here's a quick example that makes use of the FileReader class to read an image as DataURL and renders a thumbnail by setting the src attribute of an image tag to a data URL:

The html code:

<input type="file" id="files" />
<img id="image" />

The JavaScript code:

document.getElementById("files").onchange = function () {
    var reader = new FileReader();

    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("image").src = e.target.result;
    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);
};

Here's a good article on using the File APIs in JavaScript.

The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:

_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
    var files = evt.target.files;_x000D_
_x000D_
    // Loop through the FileList and render image files as thumbnails._x000D_
    for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
      // Only process image files._x000D_
      if (!f.type.match('image.*')) {_x000D_
        continue;_x000D_
      }_x000D_
_x000D_
      var reader = new FileReader();_x000D_
_x000D_
      // Closure to capture the file information._x000D_
      reader.onload = (function(theFile) {_x000D_
        return function(e) {_x000D_
          // Render thumbnail._x000D_
          var span = document.createElement('span');_x000D_
          span.innerHTML = _x000D_
          [_x000D_
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
            e.target.result,_x000D_
            '" title="', escape(theFile.name), _x000D_
            '"/>'_x000D_
          ].join('');_x000D_
          _x000D_
          document.getElementById('list').insertBefore(span, null);_x000D_
        };_x000D_
      })(f);_x000D_
_x000D_
      // Read in the image file as a data URL._x000D_
      reader.readAsDataURL(f);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
_x000D_
_x000D_

Hash string in c#

The fastest way, to get a hash string for password store purposes, is a following code:

    internal static string GetStringSha256Hash(string text)
    {
        if (String.IsNullOrEmpty(text))
            return String.Empty;

        using (var sha = new System.Security.Cryptography.SHA256Managed())
        {
            byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] hash = sha.ComputeHash(textData);
            return BitConverter.ToString(hash).Replace("-", String.Empty);
        }
    }

Remarks:

  • if the method is invoked often, the creation of sha variable should be refactored into a class field;
  • output is presented as encoded hex string;

Can I use complex HTML with Twitter Bootstrap's Tooltip?

This parameter is just about whether you are going to use complex html into the tooltip. Set it to true and then hit the html into the title attribute of the tag.

See this fiddle here - I've set the html attribute to true through the data-html="true" in the <a> tag and then just added in the html ad hoc as an example.

Python convert decimal to hex

A version using iteration:

def toHex(decimal):
    hex_str = ''
    digits = "0123456789ABCDEF"
    if decimal == 0:
       return '0'

    while decimal != 0:
        hex_str += digits[decimal % 16]
        decimal = decimal // 16

    return hex_str[::-1] # reverse the string

numbers = [0, 16, 20, 45, 255, 456, 789, 1024]
print([toHex(x) for x in numbers])
print([hex(x) for x in numbers])

Code signing is required for product type 'Application' in SDK 'iOS5.1'

This error was caused, for me, by different circumstances. A downloaded project tutorial had a default setting of [Project]>Targets>Build Settings>Architectures>Build Active Architecture Only>Release = "Yes." I wasn't intending to build a release, so the solution was to set Release (which presumably requires not just a developer profile but distribution profile) to "No."

Fetch first element which matches criteria

This might be what you are looking for:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();

And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .orElse(null); /* You could also create a default object here */


An example:
public static void main(String[] args) {
    class Stop {
        private final String stationName;
        private final int    passengerCount;

        Stop(final String stationName, final int passengerCount) {
            this.stationName    = stationName;
            this.passengerCount = passengerCount;
        }
    }

    List<Stop> stops = new LinkedList<>();

    stops.add(new Stop("Station1", 250));
    stops.add(new Stop("Station2", 275));
    stops.add(new Stop("Station3", 390));
    stops.add(new Stop("Station2", 210));
    stops.add(new Stop("Station1", 190));

    Stop firstStopAtStation1 = stops.stream()
            .filter(e -> e.stationName.equals("Station1"))
            .findFirst()
            .orElse(null);

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}

Output is:

At the first stop at Station1 there were 250 passengers in the train.

How to add target="_blank" to JavaScript window.location?

window.location sets the URL of your current window. To open a new window, you need to use window.open. This should work:

function ToKey(){
    var key = document.tokey.key.value.toLowerCase();
    if (key == "smk") {
        window.open('http://www.smkproduction.eu5.org', '_blank');
    } else {
        alert("Kodi nuk është valid!");
    }
}

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

In my case, on commenting out the

<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> 

in the web.config file was throwing "Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata".

Description Box using "onmouseover"

I'd try doing this with jQuery's .hover() event handler system, it makes it easy to show a div with the tooltip when the mouse is over the text, and hide it once it's gone.

Here's a simple example.

HTML:

?<p id="testText">Some Text</p>
<div id="tooltip">Tooltip Hint Text</div>???????????????????????????????????????????

Basic CSS:

?#?tooltip {
display:none;
border:1px solid #F00;
width:150px;
}?

jQuery:

$("#testText").hover(
   function(e){
       $("#tooltip").show();
   },
   function(e){
       $("#tooltip").hide();
  });??????????

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

What is the best way to remove accents (normalize) in a Python unicode string?

Some languages have combining diacritics as language letters and accent diacritics to specify accent.

I think it is more safe to specify explicitly what diactrics you want to strip:

def strip_accents(string, accents=('COMBINING ACUTE ACCENT', 'COMBINING GRAVE ACCENT', 'COMBINING TILDE')):
    accents = set(map(unicodedata.lookup, accents))
    chars = [c for c in unicodedata.normalize('NFD', string) if c not in accents]
    return unicodedata.normalize('NFC', ''.join(chars))

Two column div layout with fluid left and fixed right column

CSS:

#sidebar {float: right; width: 200px; background: #eee;}
#content {overflow: hidden; background: #dad;}

HTML:

<div id="sidebar">I'm 200px wide</div>
<div id="content"> I take up the remaining space <br> and I don't wrap under the right column</div>

The above should work, you can put that code in wrapper if you want the give it width and center it too, overflow:hidden on the column without a width is the key to getting it to contain, vertically, as in not wrap around the side columns (can be left or right)

IE6 might need zoom:1 set on the #content div too if you need it's support

Enums in Javascript with ES6

You could use ES6 Map

const colors = new Map([
  ['RED', 'red'],
  ['BLUE', 'blue'],
  ['GREEN', 'green']
]);

console.log(colors.get('RED'));

How can I make a list of lists in R?

You can easily make lists of lists

list1 <- list(a = 2, b = 3)
list2 <- list(c = "a", d = "b")
mylist <- list(list1, list2)

mylist is now a list that contains two lists. To access list1 you can use mylist[[1]]. If you want to be able to something like mylist$list1 then you need to do somethingl like

mylist <- list(list1 = list1, list2 = list2)
# Now you can do the following
mylist$list1

Edit: To reply to your edit. Just use double bracket indexing

a <- list_all[[1]]
a[[1]]
#[1] 1
a[[2]]
#[1] 2

How to print a int64_t type in C

With C99 the %j length modifier can also be used with the printf family of functions to print values of type int64_t and uint64_t:

#include <stdio.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
    int64_t  a = 1LL << 63;
    uint64_t b = 1ULL << 63;

    printf("a=%jd (0x%jx)\n", a, a);
    printf("b=%ju (0x%jx)\n", b, b);

    return 0;
}

Compiling this code with gcc -Wall -pedantic -std=c99 produces no warnings, and the program prints the expected output:

a=-9223372036854775808 (0x8000000000000000)
b=9223372036854775808 (0x8000000000000000)

This is according to printf(3) on my Linux system (the man page specifically says that j is used to indicate a conversion to an intmax_t or uintmax_t; in my stdint.h, both int64_t and intmax_t are typedef'd in exactly the same way, and similarly for uint64_t). I'm not sure if this is perfectly portable to other systems.

how to get a list of dates between two dates in java

Back in 2010, I suggested to use Joda-Time for that.

Note that Joda-Time is now in maintenance mode. Since 1.8 (2014), you should use java.time.

Add one day at a time until reaching the end date:

int days = Days.daysBetween(startDate, endDate).getDays();
List<LocalDate> dates = new ArrayList<LocalDate>(days);  // Set initial capacity to `days`.
for (int i=0; i < days; i++) {
    LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);
    dates.add(d);
}

It wouldn't be too hard to implement your own iterator to do this as well, that would be even nicer.

What are good examples of genetic algorithms/genetic programming solutions?

I made a complete GA framework named "GALAB", to solve many problems:

  • locating GSM ANTs (BTS) to decrease overlap & blank locations.
  • Resource constraint project scheduling.
  • Evolutionary picture creation. (Evopic)
  • Travelling salesman problem.
  • N-Queen & N-Color problems.
  • Knight's tour & Knapsack problems.
  • Magic square & Sudoku puzzles.
  • string compression, based on Superstring problem.
  • 2D Packaging problem.
  • Tiny artificial life APP.
  • Rubik puzzle.

Do I need a content-type header for HTTP GET requests?

The problem with not passing over the content-type on a GET message is that sure the content-type is irrelevant because the server side determines the content anyway. The problem that I have encountered is that there are now a lot of places that set up their webservices to be smart enough to pick up the content-type that you pass and return the response in the 'type' that you request. Eg. we are currently messaging with a place that defaults to JSON, however, they have set their webservice up so that if you pass a content-type of xml they will then return xml rather than their JSON default. Which I think going forward is a great idea

Exec : display stdout "live"

Inspired by Nathanael Smith's answer and Eric Freese's comment, it could be as simple as:

var exec = require('child_process').exec;
exec('coffee -cw my_file.coffee').stdout.pipe(process.stdout);

error: command 'gcc' failed with exit status 1 while installing eventlet

What worked for me on CentOS was:

sudo yum -y install gcc
sudo yum install python-devel

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Bootstrap Modal immediately disappearing

A Likely Cause

This is typical behavior for when the JavaScript for the Modal plugin gets loaded twice. Please check to make sure that the plugin isn't getting double loaded. Depending on the platform you are using, the modal code could be loaded from a number a sources. Some of the common ones are:

  • bootstrap.js (the full BootStrap JS suite)
  • bootstrap.min.js (same as above, just minified)
  • bootstrap-modal.js (the standalone plugin)
  • a dependency loader, e.g., require('bootstrap')

Debugging Tips

A good place to start is to inspect the registered click event listeners using the developer tools in your browser. Chrome, for instance, will list the JS source file where the code to register the listener can be found. Another option is to try searching the sources on the page for a phrase found in the Modal code, e.g., var Modal.

Unfortunately, these won't always find things in all cases. Inspecting the network requests can be a little more robust at giving you a picture of everything loaded on a page.

A (Broken) Demo

Here's a demo of what happens when you load both the bootstrap.js and bootstrap-modal.js (just to confirm your experience):

Plunker

If you scroll down to the bottom of the source on that page, you can remove or comment out the <script> line for the bootstrap-modal.js and then verify that now the modal will function as expected.

Searching for UUIDs in text with regex

@ivelin: UUID can have capitals. So you'll either need to toLowerCase() the string or use:

[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}

Would have just commented this but not enough rep :)

PHP + curl, HTTP POST sample code?

curlPost('google.com', [
    'username' => 'admin',
    'password' => '12345',
]);


function curlPost($url, $data) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error !== '') {
        throw new \Exception($error);
    }

    return $response;
}

What is a practical, real world example of the Linked List?

In operating systems ... one may use a linked list to keep track of what processes are running and what processes are sleeping ... a process that is running and wants to sleep ... gets removed from the LinkedList that keeps track of running processes and once the sleep time is over adds it back to the active process LinkedList

Maybe newer OS are using some funky data structures ... linked lists can be used there

How to check the input is an integer or not in Java?

You can try this way

 String input = "";
 try {
   int x = Integer.parseInt(input); 
   // You can use this method to convert String to int, But if input 
   //is not an int  value then this will throws NumberFormatException. 
   System.out.println("Valid input");
 }catch(NumberFormatException e) {
   System.out.println("input is not an int value"); 
   // Here catch NumberFormatException
   // So input is not a int.
 } 

Understanding events and event handlers in C#

I agree with KE50 except that I view the 'event' keyword as an alias for 'ActionCollection' since the event holds a collection of actions to be performed (ie. the delegate).

using System;

namespace test{

class MyTestApp{
    //The Event Handler declaration
    public delegate void EventAction();

    //The Event Action Collection 
    //Equivalent to 
    //  public List<EventAction> EventActions=new List<EventAction>();
    //        
    public event EventAction EventActions;

    //An Action
    public void Hello(){
        Console.WriteLine("Hello World of events!");
    }
    //Another Action
    public void Goodbye(){
        Console.WriteLine("Goodbye Cruel World of events!");
    }

    public static void Main(){
        MyTestApp TestApp = new MyTestApp();

        //Add actions to the collection
        TestApp.EventActions += TestApp.Hello;
        TestApp.EventActions += TestApp.Goodbye;

        //Invoke all event actions
        if (TestApp.EventActions!= null){
            //this peculiar syntax hides the invoke 
            TestApp.EventActions();
            //using the 'ActionCollection' idea:
            // foreach(EventAction action in TestApp.EventActions)
            //     action.Invoke();
        }
    }

}   

}

How to get Git to clone into current directory

The following is probably not fully equivalent to a clone in all cases but did the trick for me:

git init .
git remote add -t \* -f origin <repository-url>
git checkout master

In my case, this produces a .git/config file which is equivalent to the one I get when doing a clone.

How to view data saved in android database(SQLite)?

Open DDMS than in DATA>DATA>"Select your package like com.example.foo"> than select your database folder than pull that data in eclipse you can see the pull an push icon on top right side ...

Transform only one axis to log10 scale with ggplot2

Another solution using scale_y_log10 with trans_breaks, trans_format and annotation_logticks()

library(ggplot2)

m <- ggplot(diamonds, aes(y = price, x = color))

m + geom_boxplot() +
  scale_y_log10(
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  theme_bw() +
  annotation_logticks(sides = 'lr') +
  theme(panel.grid.minor = element_blank())

How to avoid Python/Pandas creating an index in a saved csv?

There are two ways to handle the situation where we do not want the index to be stored in csv file.

  1. As others have stated you can use index=False while saving your
    dataframe to csv file.

    df.to_csv('file_name.csv',index=False)

  2. Or you can save your dataframe as it is with an index, and while reading you just drop the column unnamed 0 containing your previous index.Simple!

    df.to_csv(' file_name.csv ')
    df_new = pd.read_csv('file_name.csv').drop(['unnamed 0'],axis=1)

Convert number of minutes into hours & minutes using PHP

check this link for better solution. Click here

How to convert hh:mm:ss to minutes

$minutes=$item['time_diff'];
$hours =   sprintf('%02d',intdiv($minutes, 60)) .':'. ( sprintf('%02d',$minutes % 60));

How to avoid HTTP error 429 (Too Many Requests) python

Another workaround would be to spoof your IP using some sort of Public VPN or Tor network. This would be assuming the rate-limiting on the server at IP level.

There is a brief blog post demonstrating a way to use tor along with urllib2:

http://blog.flip-edesign.com/?p=119

How to link to apps on the app store

This worked for me perfectly using only APP ID:

 NSString *urlString = [NSString stringWithFormat:@"http://itunes.apple.com/app/id%@",YOUR_APP_ID];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

The number of redirects is ZERO.

Using comma as list separator with AngularJS

You can use CSS to fix it too

<div class="some-container">
[ <span ng-repeat="something in somethings">{{something}}<span class="list-comma">, </span></span> ]
</div>

.some-container span:last-child .list-comma{
    display: none;
}

But Andy Joslin's answer is best

Edit: I changed my mind I had to do this recently and I ended up going with a join filter.

How to retrieve field names from temporary table (SQL Server 2008)

The temporary tables are defined in "tempdb", and the table names are "mangled".

This query should do the trick:

select c.*
from tempdb.sys.columns c
inner join tempdb.sys.tables t ON c.object_id = t.object_id
where t.name like '#MyTempTable%'

Marc

I can’t find the Android keytool

Okay, so this post is from six months ago, but I thought I would add some info here for people who are confused about the whole API key/MD5 fingerprint business. It took me a while to figure out, so I assume others have had trouble with it too (unless I'm just that dull).

These directions are for Windows XP, but I imagine it is similar for other versions of Windows. It appears Mac and Linux users have an easier time with this so I won't address them.

So in order to use mapviews in your Android apps, Google wants to check in with them so you can sign off on an Android Maps APIs Terms Of Service agreement. I think they don't want you to make any turn-by-turn GPS apps to compete with theirs or something. I didn't really read it. Oops.

So go to http://code.google.com/android/maps-api-signup.html and check it out. They want you to check the "I have read and agree with the terms and conditions" box and enter your certificate's MD5 fingerprint. Wtf is that, you might say. I don't know, but just do what I say and your Android app doesn't get hurt.

Go to Start>Run and type cmd to open up a command prompt. You need to navigate to the directory with the keytool.exe file, which might be in a slightly different place depending on which version JDK you have installed. Mine is in C:\Program Files\Java\jdk1.6.0_21\bin but try browsing to the Java folder and see what version you have and change the path accordingly.

After navigating to C:\Program Files\Java\<"your JDK version here">\bin in the command prompt, type

keytool -list -keystore "C:/Documents and Settings/<"your user name here">/.android/debug.keystore"

with the quotes. Of course <"your user name here"> would be your own Windows username.

(If you are having trouble finding this path and you are using Eclipse, you can check Window>preferences>Android>Build and check out the "Default Debug keystore")

Press enter and it will prompt you for a password. Just press enter. And voila, at the bottom is your MD5 fingerprint. Type your fingerprint into the text box at the Android Maps API Signup page and hit Generate API Key.

And there's your key in all its glory, with a handy sample xml layout with your key entered for you to copy and paste.

Lists in ConfigParser

Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.

Get Substring - everything before certain char

String str = "223232-1.jpg"
int index = str.IndexOf('-');
if(index > 0) {
    return str.Substring(0, index)
}

How to get min, seconds and milliseconds from datetime.now() in python?

What about:

datetime.now().strftime('%M:%S.%f')[:-4]

I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

EDIT

If the %f modifier doesn't work for you, you can try something like:

now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]

Again, I'm assuming you just want to truncate the precision.

How to add percent sign to NSString

uese following code.

 NSString *searchText = @"Bhupi"
 NSString *formatedSearchText = [NSString stringWithFormat:@"%%%@%%",searchText];

will output: %Bhupi%

'react-scripts' is not recognized as an internal or external command

This worked for me:

  • Go to the project folder in CLI and type npm install.Go for a similar command if using yarn etc.

  • Then type npm start if you are using Npm. Go for a similar command if using yarn etc.

  • The file starts working

How to remove an app with active device admin enabled on Android?

You could also create a new DevicePolicyManager and then use removeAdmin(adminReceiver) from an onClickListener of a button in your app

//set the onClickListener here
{
   ComponentName devAdminReceiver = new ComponentName(context, deviceAdminReceiver.class);
   DevicePolicyManager dpm = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
   dpm.removeActiveAdmin(devAdminReceiver);
}

And then you can uninstall

Invisible characters - ASCII

An invisible Character is ?, or U+200b

?

CSS media query to target only iOS devices

As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.

If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS

Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.

.iOS-device {
      style-you-want-to-set: yada;
}

jQuery selector regular expressions

If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^ JQuery selector.

For example if your want to only select div with id starting with "abc", you can use:

$("div[id^='abc']")

A lot of very useful selectors to avoid use of regex can be find here: http://api.jquery.com/category/selectors/attribute-selectors/

How print out the contents of a HashMap<String, String> in ascending order based on its values?

You'll need to make a list of the keys, sort them according to the corresponding values, then iterate over the sorted keys.

Map<String, String> map = getMyMap();
List<String> keys = new ArrayList<String>(map.keySet());
Collections.sort(keys, someComparator);
for (String key: keys) {
    System.out.println(key + ": " + map.get(key));
}

As for what to use for someComparator, here are some handy, generic Comparator-creating routines I often find useful. The first one sorts by the values according to their natural ordering, and the second allows you to specify any arbitrary Comparator to sort the values:

public static <K, V extends Comparable<? super V>>
        Comparator<K> mapValueComparator(final Map<K, V> map) {
    return new Comparator<K>() {
        public int compare(K key1, K key2) {
            return map.get(key1).compareTo(map.get(key2));
        }
    };
}

public static <K, V>
        Comparator<K> mapValueComparator(final Map<K, V> map,
                                         final Comparator<V> comparator) {
    return new Comparator<K>() {
        public int compare(K key1, K key2) {
            return comparator.compare(map.get(key1), map.get(key2));
        }
    };
}

How do I give ASP.NET permission to write to a folder in Windows 7?

The full command would be something like below, notice the quotes

icacls "c:\inetpub\wwwroot\tmp" /grant "IIS AppPool\DefaultAppPool:F"

Joining two lists together

You could try:

List<string> a = new List<string>();
List<string> b = new List<string>();

a.AddRange(b);

MSDN page for AddRange

This preserves the order of the lists, but it doesn't remove any duplicates which Union would do.

This does change list a. If you wanted to preserve the original lists then you should use Concat (as pointed out in the other answers):

var newList = a.Concat(b);

This returns an IEnumerable as long as a is not null.

How can I disable notices and warnings in PHP within the .htaccess file?

Fortes is right, thank you.

When you have a shared hosting it is usual to obtain an 500 server error.

I have a website with Joomla and I added to the index.php:

ini_set('display_errors','off');

The error line showed in my website disappeared.

Bootstrap4 adding scrollbar to div

Use the overflow-y: scroll property on the element that contains the elements.

The overflow-y property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.

Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:

<ul class="nav nav-pills nav-stacked" style="height: 250px; overflow-y: scroll;">
  <li class="nav-item">
    <a class="nav-link active" href="#">Active</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" href="#">Disabled</a>
  </li>
</ul>

Java - Convert image to Base64

To begin with, this line of code:

while ((bytesRead = fis.read(byteArray)) != -1)

is equivalent to

while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)

So it's writing into the byteArray from offset 0, rather than from where you wrote to before.

You need something like this:

int offset = 0;
int bytesRead = 0;

while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
    offset += bytesRead;
}

After you have read the data (bytes) in then, you can convert it to Base64.

There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.

I would ditch the byte array and go with something like this:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);

Or condense it further as Thilo has with FileUtils.

SQL update trigger only when column is modified

Whenever a record has updated a record is "deleted". Here is my example:

ALTER TRIGGER [dbo].[UpdatePhyDate]
   ON  [dbo].[M_ContractDT1]
   AFTER UPDATE
AS 
BEGIN
    -- on ContarctDT1 PhyQty is updated 
    -- I want system date in Phytate automatically saved
    SET NOCOUNT ON;

    declare @dt1ky as int   

    if(update(Phyqty))
    begin
        select @dt1ky = dt1ky from deleted

        update M_ContractDT1 set PhyDate=GETDATE() where Dt1Ky=  @dt1ky     

    end

END

It works fine

AngularJS - Find Element with attribute

You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

So, for this HTML:

<div ng-controller='MyCtrl'>
    <div>
        <div name='foo' class='myElementClass'>this one</div>
    </div>
</div>

This AngularJS code should work:

angular.module('MyClient').controller('MyCtrl', [
    '$scope',
    '$element',
    '$log',
    function ($scope, $element, $log) {

        // Find the element by its class attribute, within your controller's scope
        var myElements = $element.find('.myElementClass');

        // myElements is now an array of jQuery DOM elements

        if (myElements.length == 0) {
            // Not found. Are you sure you've included the full jQuery?
        } else {
            // There should only be one, and it will be element 0
            $log.debug(myElements[0].name); // "foo"
        }

    }
]);

Accessing dict_keys element by index in Python3

Python 3

mydict = {'a': 'one', 'b': 'two', 'c': 'three'}
mykeys = [*mydict]          #list of keys
myvals = [*mydict.values()] #list of values

print(mykeys)
print(myvals)

Output

['a', 'b', 'c']
['one', 'two', 'three']

Also see this detailed answer

Xcode 6.1 Missing required architecture X86_64 in file

Following changes you have to make that's it(change architecture into armv7 and remove others) :-

Change you have to make

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Check element CSS display with JavaScript

Basic JavaScript:

if (document.getElementById("elementId").style.display == 'block') { 
  alert('this Element is block'); 
}

How to run the sftp command with a password from Bash script?

Another way would be to use lftp:

lftp sftp://user:password@host  -e "put local-file.name; bye"

The disadvantage of this method is that other users on the computer can read the password from tools like ps and that the password can become part of your shell history.

A more secure alternative which is available since LFTP 4.5.0 is setting the LFTP_PASSWORDenvironment variable and executing lftp with --env-password. Here's a full example:

LFTP_PASSWORD="just_an_example"
lftp --env-password sftp://user@host  -e "put local-file.name; bye"

LFTP also includes a cool mirroring feature (can include delete after confirmed transfer --Remove-source-files):

lftp -e 'mirror -R /local/log/path/ /remote/path/' --env-password -u user sftp.foo.com

Client to send SOAP request and receive response

As an alternative, and pretty close to debiasej approach. Since a SOAP request is just a HTTP request, you can simply perform a GET or POST using with HTTP client, but it's not mandatory to build SOAP envelope.

Something like this:

using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace HGF.Infraestructure.Communications
{
    public class SOAPSample
    {
        private readonly IHttpClientFactory _clientFactory;
        private readonly ILogger<DocumentProvider> _logger;

        public SOAPSample(ILogger<DocumentProvider> logger,
                          IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
            _logger = logger;
        }

        public async Task<string> UsingGet(int value1, int value2)
        {
            try
            {
                var client = _clientFactory.CreateClient();
                var response = await client.GetAsync($"https://hostname.com/webservice.asmx/SampleMethod?value1={value1}&value2={value2}", HttpCompletionOption.ResponseHeadersRead);

                //NULL check, HTTP Status Check....

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Oops! Something went wrong");
                return ex.Message;
            }
        }


        public async Task<string> UsingPost(int value1, int value2)
        {
            try
            {
                var content = new StringContent($"value1={value1}&value2={value2}", Encoding.UTF8, "application/x-www-form-urlencoded");

                var client = _clientFactory.CreateClient();
                var response = await client.PostAsync("https://hostname.com/webservice.asmx/SampleMethod", content);

                //NULL check, HTTP Status Check....

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Oops! Something went wrong");
                return ex.Message;
            }
        }
    }
}

Of course, it depends on your scenario. If the payload is too complex, then this won't work

One DbContext per web request... why?

Another issue to watch out for with Entity Framework specifically is when using a combination of creating new entities, lazy loading, and then using those new entities (from the same context). If you don't use IDbSet.Create (vs just new), Lazy loading on that entity doesn't work when its retrieved out of the context it was created in. Example:

 public class Foo {
     public string Id {get; set; }
     public string BarId {get; set; }
     // lazy loaded relationship to bar
     public virtual Bar Bar { get; set;}
 }
 var foo = new Foo {
     Id = "foo id"
     BarId = "some existing bar id"
 };
 dbContext.Set<Foo>().Add(foo);
 dbContext.SaveChanges();

 // some other code, using the same context
 var foo = dbContext.Set<Foo>().Find("foo id");
 var barProp = foo.Bar.SomeBarProp; // fails with null reference even though we have BarId set.

How to get all elements inside "div" that starts with a known text

With modern browsers, this is easy without jQuery:

document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');

The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".

Note that all browsers released since June 2009 support this.

How do I execute a PowerShell script automatically using Windows task scheduler?

I also could not launch scripts, after heavy searching nothing helped. No -ExecutionPolicy, no commands, no files and no difference between "" and ''.

I simply put the command I ran in powershell in the argument tab: ./scripts.ps1 parameter1 11 parameter2 xx and so on. Now the scheduler works. Program: Powershell.exe Start in: C:/location/of/script/

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

Open Bootstrap Modal from code-behind

All of the example above should work just add a document ready action and change the order of how you perform the updates to the texts, also make sure your using Script manager alternatively non of this will work for you. Here is the text within the code behind.

aspx

<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <asp:UpdatePanel ID="upModal" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
                <ContentTemplate>
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title"><asp:Label ID="lblModalTitle" runat="server" Text=""></asp:Label></h4>
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        </div>
                        <div class="modal-body">
                            <asp:Label ID="lblModalBody" runat="server" Text=""></asp:Label>
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Close</button>
                        </div>
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </div>

Code Behind

lblModalTitle.Text = "Validation Errors";
lblModalBody.Text = form.Error;
upModal.Update();
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$(document).ready(function () {$('#myModal').modal();});", true);

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

Works after removing the scope reference and the function arguments:

"use strict";

describe("Request Notification Channel", function() {
    var requestNotificationChannel, rootScope;

    beforeEach(function() {
        module("messageAppModule");

        inject(function($injector, _requestNotificationChannel_) {
            rootScope = $injector.get("$rootScope");
            requestNotificationChannel = _requestNotificationChannel_;
        })
        spyOn(rootScope, "$broadcast");
    });


    it("should broadcast delete message notification with provided params", function() {
        requestNotificationChannel.deleteMessage(1, 4);
        expect(rootScope.$broadcast).toHaveBeenCalledWith("_DELETE_MESSAGE_", { id: 1, index: 4} );
    });
});

Reload .profile in bash shell script (in unix)?

Try:

#!/bin/bash
# .... some previous code ...
# help set exec | less
set -- 1 2 3 4 5  # fake command line arguments
exec bash --login -c '
echo $0
echo $@
echo my script continues here
' arg0 "$@"

Detecting Windows or Linux?

apache commons lang has a class SystemUtils.java you can use :

SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS

Get file name from URL

If you don't need to get rid of the file extension, here's a way to do it without resorting to error-prone String manipulation and without using external libraries. Works with Java 1.7+:

import java.net.URI
import java.nio.file.Paths

String url = "http://example.org/file?p=foo&q=bar"
String filename = Paths.get(new URI(url).getPath()).getFileName().toString()

Error during installing HAXM, VT-X not working

Did you get a message about enabling the Execute Disable bit?

You can enable the XD bit by running the following command (as administrator) and then reboot.

bcdedit /set nx AlwaysOn

Usually, this error: "This computer meets requirements for HAXM, but VT-x is not turned on" means that your system does have Intel VT, but you need to go into the BIOS to actually enable it.

I also ran into these instructions -might be helpful to you: http://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows

Did you ever get it to work?

How to Parse a JSON Object In Android

In your JSON format, it do not have starting JSON object

Like :

{
    "info" :       <!-- this is starting JSON object -->
        {
        "caller":"getPoiById",
        "results":
        {
            "indexForPhone":0,
            "indexForEmail":"NULL",
            .
            .
         }
    }
}

Above Json starts with info as JSON object. So while executing :

JSONObject json = new JSONObject(result);    // create JSON obj from string
JSONObject json2 = json.getJSONObject("info");    // this will return correct

Now, we can access result field :

JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"

I think this was missing and so the problem was solved while we use JSONTokener like answer of yours.

Your answer is very fine. Just i think i add this information so i answered

Thank you

Angular: Cannot find a differ supporting object '[object Object]'

Something that has caught me out more than once is having another variable on the page with the same name.

E.g. in the example below the data for the NgFor is in the variable requests. But there is also a variable called #requests used for the if-else

<ng-template #requests>
  <div class="pending-requests">
    <div class="request-list" *ngFor="let request of requests">
      <span>{{ request.clientName }}</span>
    </div>
  </div>
</ng-template>

Call PHP function from jQuery?

Thanks all. I took bits of each of your solutions and made my own.

The final working solution is:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
            data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
            success: function(data) {
                $('#twitter-loader').remove();
                $('#twitter-container').html(data);
            }
        });
   });
</script>

Dynamic function name in javascript?

function myFunction() {
    console.log('It works!');
}

var name = 'myFunction';

window[name].call();

What is the strict aliasing rule?

Type punning via pointer casts (as opposed to using a union) is a major example of breaking strict aliasing.

Insert data using Entity Framework model

var context = new DatabaseEntities();

var t = new test //Make sure you have a table called test in DB
{
    ID = Guid.NewGuid(),
    name = "blah",
};

context.test.Add(t);
context.SaveChanges();

Should do it

center MessageBox in parent form

I really needed this in C# and found Center MessageBox C#

Here's a nicely formatted version

using System;
using System.Windows.Forms;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;   

public class MessageBoxEx
{
    private static IWin32Window _owner;
    private static HookProc _hookProc;
    private static IntPtr _hHook;

    public static DialogResult Show(string text)
    {
        Initialize();
        return MessageBox.Show(text);
    }

    public static DialogResult Show(string text, string caption)
    {
        Initialize();
        return MessageBox.Show(text, caption);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons)
    {
        Initialize();
        return MessageBox.Show(text, caption, buttons);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
    {
        Initialize();
        return MessageBox.Show(text, caption, buttons, icon);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
    {
        Initialize();
        return MessageBox.Show(text, caption, buttons, icon, defButton);
    }

    public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
    {
        Initialize();
        return MessageBox.Show(text, caption, buttons, icon, defButton, options);
    }

    public static DialogResult Show(IWin32Window owner, string text)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption, buttons);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption, buttons, icon);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption, buttons, icon, defButton);
    }

    public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options)
    {
        _owner = owner;
        Initialize();
        return MessageBox.Show(owner, text, caption, buttons, icon,
                               defButton, options);
    }

    public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);

    public const int WH_CALLWNDPROCRET = 12;

    public enum CbtHookAction : int
    {
        HCBT_MOVESIZE = 0,
        HCBT_MINMAX = 1,
        HCBT_QS = 2,
        HCBT_CREATEWND = 3,
        HCBT_DESTROYWND = 4,
        HCBT_ACTIVATE = 5,
        HCBT_CLICKSKIPPED = 6,
        HCBT_KEYSKIPPED = 7,
        HCBT_SYSCOMMAND = 8,
        HCBT_SETFOCUS = 9
    }

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);

    [DllImport("user32.dll")]
    private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    [DllImport("User32.dll")]
    public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);

    [DllImport("User32.dll")]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

    [DllImport("user32.dll")]
    public static extern int UnhookWindowsHookEx(IntPtr idHook);

    [DllImport("user32.dll")]
    public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern int GetWindowTextLength(IntPtr hWnd);

    [DllImport("user32.dll")]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);

    [DllImport("user32.dll")]
    public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);

    [StructLayout(LayoutKind.Sequential)]
    public struct CWPRETSTRUCT
    {
        public IntPtr lResult;
        public IntPtr lParam;
        public IntPtr wParam;
        public uint message;
        public IntPtr hwnd;
    } ;

    static MessageBoxEx()
    {
        _hookProc = new HookProc(MessageBoxHookProc);
        _hHook = IntPtr.Zero;
    }

    private static void Initialize()
    {
        if (_hHook != IntPtr.Zero)
        {
            throw new NotSupportedException("multiple calls are not supported");
        }

        if (_owner != null)
        {
            _hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
        }
    }

    private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode < 0)
        {
            return CallNextHookEx(_hHook, nCode, wParam, lParam);
        }

        CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
        IntPtr hook = _hHook;

        if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
        {
            try
            {
                CenterWindow(msg.hwnd);
            }
            finally
            {
                UnhookWindowsHookEx(_hHook);
                _hHook = IntPtr.Zero;
            }
        }

        return CallNextHookEx(hook, nCode, wParam, lParam);
    }

    private static void CenterWindow(IntPtr hChildWnd)
    {
        Rectangle recChild = new Rectangle(0, 0, 0, 0);
        bool success = GetWindowRect(hChildWnd, ref recChild);

        int width = recChild.Width - recChild.X;
        int height = recChild.Height - recChild.Y;

        Rectangle recParent = new Rectangle(0, 0, 0, 0);
        success = GetWindowRect(_owner.Handle, ref recParent);

        Point ptCenter = new Point(0, 0);
        ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
        ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);


        Point ptStart = new Point(0, 0);
        ptStart.X = (ptCenter.X - (width / 2));
        ptStart.Y = (ptCenter.Y - (height / 2));

        ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
        ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;

        int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
                                height, false);
    }

}

Check if an image is loaded (no errors) with jQuery

Realtime network detector - check network status without refreshing the page: (it's not jquery, but tested, and 100% works:(tested on Firefox v25.0))

Code:

<script>
 function ImgLoad(myobj){
   var randomNum = Math.round(Math.random() * 10000);
   var oImg=new Image;
   oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
   oImg.onload=function(){alert('Image succesfully loaded!')}
   oImg.onerror=function(){alert('No network connection or image is not available.')}
}
window.onload=ImgLoad();
</script>

<button id="reloadbtn" onclick="ImgLoad();">Again!</button>

if connection lost just press the Again button.

Update 1: Auto detect without refreshing the page:

<script>
     function ImgLoad(myobj){
       var randomNum = Math.round(Math.random() * 10000);
       var oImg=new Image;
       oImg.src="YOUR_IMAGELINK"+"?rand="+randomNum;
       oImg.onload=function(){networkstatus_div.innerHTML="";}
       oImg.onerror=function(){networkstatus_div.innerHTML="Service is not available. Please check your Internet connection!";}
}

networkchecker = window.setInterval(function(){window.onload=ImgLoad()},1000);
</script>

<div id="networkstatus_div"></div>

Add Text on Image using PIL

One thing not mentioned in other answers is checking the text size. It is often needed to make sure the text fits the image (e.g. shorten the text if oversized) or to determine location to draw the text (e.g. aligned text top center). Pillow/PIL offers two methods to check the text size, one via ImageFont and one via ImageDraw. As shown below, the font doesn't handle multiple lined, while ImageDraw does.

In [28]: im = Image.new(mode='RGB',size=(240,240))                                                            
In [29]: font = ImageFont.truetype('arial')
In [30]: draw = ImageDraw.Draw(im)
In [31]: t1 = 'hello world!'
In [32]: t2 = 'hello \nworld!'
In [33]: font.getsize(t1), font.getsize(t2) # the height is the same
Out[33]: ((52, 10), (60, 10)) 
In [35]: draw.textsize(t1, font), draw.textsize(t2, font)  # handles multi-lined text
Out[35]: ((52, 10), (27, 24)) 

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

How to make System.out.println() shorter

Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.

Task continuation on UI thread

If you have a return value you need to send to the UI you can use the generic version like this:

This is being called from an MVVM ViewModel in my case.

var updateManifest = Task<ShippingManifest>.Run(() =>
    {
        Thread.Sleep(5000);  // prove it's really working!

        // GenerateManifest calls service and returns 'ShippingManifest' object 
        return GenerateManifest();  
    })

    .ContinueWith(manifest =>
    {
        // MVVM property
        this.ShippingManifest = manifest.Result;

        // or if you are not using MVVM...
        // txtShippingManifest.Text = manifest.Result.ToString();    

        System.Diagnostics.Debug.WriteLine("UI manifest updated - " + DateTime.Now);

    }, TaskScheduler.FromCurrentSynchronizationContext());

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

long __builtin_expect(long EXP, long C);

This construct tells the compiler that the expression EXP most likely will have the value C. The return value is EXP. __builtin_expect is meant to be used in an conditional expression. In almost all cases will it be used in the context of boolean expressions in which case it is much more convenient to define two helper macros:

#define unlikely(expr) __builtin_expect(!!(expr), 0)
#define likely(expr) __builtin_expect(!!(expr), 1)

These macros can then be used as in

if (likely(a > 1))

Reference: https://www.akkadia.org/drepper/cpumemory.pdf

Open window in JavaScript with HTML inserted

You can open a new popup window by following code:

var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');

Afterwards, you can add HTML using both myWindow.document.write(); or myWindow.document.body.innerHTML = "HTML";

What I will recommend is that first you create a new html file with any name. In this example I am using

newFile.html

And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id. in this example I have given id="mainBody" to my newFile.html <body> tag

<body id="mainBody">

Then open this file using

<script>    
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>

And add whatever you want to add in your body tag. using following code

<script>    
 var myWindow = window.open("newFile.html","newWindow","width=500,height=700");  

   myWindow.onload = function(){
     let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
   myWindow.document.getElementById('mainBody').innerHTML = content;
    } 

myWindow.window.close();
 </script>

it is as simple as that.

How do I change the android actionbar title and icon

This is very simple to accomplish

If you want to change it in code, call:

setTitle("My new title");
getActionBar().setIcon(R.drawable.my_icon);

And set the values to whatever you please.

Or, in the Android manifest XML file:

<activity android:name=".MyActivity" 
       android:icon="@drawable/my_icon" 
       android:label="My new title" />  

To enable the back button in your app use:

 getActionBar().setHomeButtonEnabled(true);
 getActionBar().setDisplayHomeAsUpEnabled(true);

The code should all be placed in your onCreate so that the label/icon changing is transparent to the user, but in reality it can be called anywhere during the activity's lifecycle.

Get cart item name, quantity all details woocommerce

Since WooCommerce 2.1 (2014) you should use the WC function instead of the global. You can also call more appropriate functions:

foreach ( WC()->cart->get_cart() as $cart_item ) {
   $item_name = $cart_item['data']->get_title();
   $quantity = $cart_item['quantity'];
   $price = $cart_item['data']->get_price();
   ...

This will not only be clean code, but it will be better than accessing the post_meta directly because it will apply filters if necessary.

Reading a registry key in C#

You're looking for the cunningly named Registry.GetValue method.

How to identify numpy types in python?

That actually depends on what you're looking for.

  • If you want to test whether a sequence is actually a ndarray, a isinstance(..., np.ndarray) is probably the easiest. Make sure you don't reload numpy in the background as the module may be different, but otherwise, you should be OK. MaskedArrays, matrix, recarray are all subclasses of ndarray, so you should be set.
  • If you want to test whether a scalar is a numpy scalar, things get a bit more complicated. You could check whether it has a shape and a dtype attribute. You can compare its dtype to the basic dtypes, whose list you can find in np.core.numerictypes.genericTypeRank. Note that the elements of this list are strings, so you'd have to do a tested.dtype is np.dtype(an_element_of_the_list)...

Replace \n with actual new line in Sublime Text

For Windows line endings:

(Turn on regex - Alt+R)

Find: \\r\\n

Replace: \r\n

illustration

Auto expand a textarea using jQuery

There are a lot of answers for this but I found something very simple, attach a keyup event to the textarea and check for enter key press the key code is 13

keyPressHandler(e){ if(e.keyCode == 13){ e.target.rows = e.target.rows + 1; } }

This will add another row to you textarea and you can style the width using CSS.

Dynamic SELECT TOP @var In SQL Server

Its also possible to use dynamic SQL and execute it with the exec command:

declare @sql  nvarchar(200), @count int
set @count = 10
set @sql = N'select top ' + cast(@count as nvarchar(4)) + ' * from table'
exec (@sql)

What resources are shared between threads?

Thread share the heap (there is a research about thread specific heap) but current implementation share the heap. (and of course the code)

Remove non-numeric characters (except periods and commas) from a string

You could use filter_var to remove all illegal characters except digits, dot and the comma.

  • The FILTER_SANITIZE_NUMBER_FLOAT filter is used to remove all non-numeric character from the string.
  • FILTER_FLAG_ALLOW_FRACTION is allowing fraction separator " . "
  • The purpose of FILTER_FLAG_ALLOW_THOUSAND to get comma from the string.

Code

$var1 = '12.322,11T';

echo filter_var($var1, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);

Output

12.322,11

To read more about filter_var() and Sanitize filters