Programs & Examples On #Phpcrawl

PHPCrawl is a framework for crawling/spidering websites written in the programming language PHP.

Convert spark DataFrame column to python list

See, why this way that you are doing is not working. First, you are trying to get integer from a Row Type, the output of your collect is like this:

>>> mvv_list = mvv_count_df.select('mvv').collect()
>>> mvv_list[0]
Out: Row(mvv=1)

If you take something like this:

>>> firstvalue = mvv_list[0].mvv
Out: 1

You will get the mvv value. If you want all the information of the array you can take something like this:

>>> mvv_array = [int(row.mvv) for row in mvv_list.collect()]
>>> mvv_array
Out: [1,2,3,4]

But if you try the same for the other column, you get:

>>> mvv_count = [int(row.count) for row in mvv_list.collect()]
Out: TypeError: int() argument must be a string or a number, not 'builtin_function_or_method'

This happens because count is a built-in method. And the column has the same name as count. A workaround to do this is change the column name of count to _count:

>>> mvv_list = mvv_list.selectExpr("mvv as mvv", "count as _count")
>>> mvv_count = [int(row._count) for row in mvv_list.collect()]

But this workaround is not needed, as you can access the column using the dictionary syntax:

>>> mvv_array = [int(row['mvv']) for row in mvv_list.collect()]
>>> mvv_count = [int(row['count']) for row in mvv_list.collect()]

And it will finally work!

How to find a hash key containing a matching value

You could use hashname.key(valuename)

Or, an inversion may be in order. new_hash = hashname.invert will give you a new_hash that lets you do things more traditionally.

How to add dividers and spaces between items in RecyclerView?

public class CommonItemSpaceDecoration extends RecyclerView.ItemDecoration {

        private int mSpace = 0;
        private boolean mVerticalOrientation = true;

    public CommonItemSpaceDecoration(int space) {
        this.mSpace = space;
    }

    public CommonItemSpaceDecoration(int space, boolean verticalOrientation) {
        this.mSpace = space;
        this.mVerticalOrientation = verticalOrientation;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.top = SizeUtils.dp2px(view.getContext(), mSpace);
        if (mVerticalOrientation) {
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.set(0, SizeUtils.dp2px(view.getContext(), mSpace), 0, SizeUtils.dp2px(view.getContext(), mSpace));
            } else {
                outRect.set(0, 0, 0, SizeUtils.dp2px(view.getContext(), mSpace));
            }
        } else {
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.set(SizeUtils.dp2px(view.getContext(), mSpace), 0, 0, 0);
            } else {
                outRect.set(SizeUtils.dp2px(view.getContext(), mSpace), 0, SizeUtils.dp2px(view.getContext(), mSpace), 0);
            }
        }
    }
}

This will add space in every item's top and bottom(or left and right).Then you can set it to your recyclerView.

recyclerView.addItemDecoration(new CommonItemSpaceDecoration(16));

SizeUtils.java

public class SizeUtils {
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

If you want to check syntax error for any nginx files, you can use the -c option.

[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]# 

How to convert a PNG image to a SVG?

There is a website where you can upload your image, and see the result.

http://vectormagic.com/home

But if you want to download your svg-image, you need to register. (If you register, you get 2 images for free)

How to populate a sub-document in mongoose after creating it?

@user1417684 and @chris-foster are right!

excerpt from working code (without error handling):

var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel    = mongoose.model('items', ItemSchema);

var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {

  var new_item = new ItemModel(new_item);
  new_item.subitem = new_sub_item._id;
  new_item.save(function (error, new_item) {
    // so this is a valid way to populate via the Model
    // as documented in comments above (here @stack overflow):
    ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
      callback(new_item.toObject());
    });
    // or populate directly on the result object
    new_item.populate('subitem', function(error, new_item) {
      callback(new_item.toObject());
    });
  });

});

How to open the second form?

Form1 OpenNewForm = new Form1();
OpenNewForm.Show();

"OpenNewForm" is the name of the Form. In the second the form opens.

If you want to close the previous form:

this.Close();

Pretty printing JSON from Jackson 2.2's ObjectMapper

If you'd like to turn this on by default for ALL ObjectMapper instances in a process, here's a little hack that will set the default value of INDENT_OUTPUT to true:

val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)

Is there an easy way to add a border to the top and bottom of an Android View?

Just as @Nic Hubbard said, there is a very easy way to add a border line.

<View
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="#000000" >
</View>

You can change the height and background color to whatever you want.

Email address validation in C# MVC 4 application: with or without using Regex

Expanding on Ehsan's Answer....

If you are using .Net framework 4.5 then you can have a simple method to verify email address using EmailAddressAttribute Class in code.

private static bool IsValidEmailAddress(string emailAddress)
{
    return new System.ComponentModel.DataAnnotations
                        .EmailAddressAttribute()
                        .IsValid(emailAddress);
}

If you are considering REGEX to verify email address then read:

I Knew How To Validate An Email Address Until I Read The RFC By Phil Haack

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

How to plot vectors in python using matplotlib

What did you expect the following to do?

v1 = [0,0],[M[i,0],M[i,1]]
v1 = [M[i,0]],[M[i,1]]

This is making two different tuples, and you overwrite what you did the first time... Anyway, matplotlib does not understand what a "vector" is in the sense you are using. You have to be explicit, and plot "arrows":

In [5]: ax = plt.axes()

In [6]: ax.arrow(0, 0, *v1, head_width=0.05, head_length=0.1)
Out[6]: <matplotlib.patches.FancyArrow at 0x114fc8358>

In [7]: ax.arrow(0, 0, *v2, head_width=0.05, head_length=0.1)
Out[7]: <matplotlib.patches.FancyArrow at 0x115bb1470>

In [8]: plt.ylim(-5,5)
Out[8]: (-5, 5)

In [9]: plt.xlim(-5,5)
Out[9]: (-5, 5)

In [10]: plt.show()

Result:

enter image description here

python numpy machine epsilon

An easier way to get the machine epsilon for a given float type is to use np.finfo():

print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

How do I loop through rows with a data reader in C#?

Or you can try to access the columns directly by name:

while(dr.Read())
{
    string col1 = (string)dr["Value1"];
    string col2 = (string)dr["Value2"];
    string col3 = (string)dr["Value3"];
}

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

In my case Microsoft.Common.CurrentVersion.targets was corrupted. I copied this file from other system and it worked.

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

Can I access constants in settings.py from templates in Django?

I found this to be the simplest approach for Django 1.3:

  1. views.py

    from local_settings import BASE_URL
    
    def root(request):
        return render_to_response('hero.html', {'BASE_URL': BASE_URL})
    
  2. hero.html

    var BASE_URL = '{{ JS_BASE_URL }}';
    

What is bootstrapping?

I belong to the generation who flipped switches to enter a boot program. In the early 1980s, I worked on a microcomputer called Micro-78, developed by Electronics Corporation of India Ltd (ECIL). It was a sort of clone of Altair 8800. I distinctly remember what happens when a small boot program was entered using the toggle switches and executed by pressing a button. The program reads a second boot program contained in the 1st track of the floppy disk and overwrites it on itself in such a way that the second boot program starts executing to load a disk operating system. I think the term "bootstrap" refers to this process of the first boot program reading and overwriting the second boot program on itself, in a way "pulling itself up" with the additional functionality of the second boot program. That may be the origin of the original meaning of "the bootstrap program".

How to verify if $_GET exists?

Normally it is quite good to do:

echo isset($_GET['id']) ? $_GET['id'] : 'wtf';

This is so when assigning the var to other variables you can do defaults all in one breath instead of constantly using if statements to just give them a default value if they are not set.

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

What worked for me was to pass the activity instead of the context.

I wanted a custom layout for my dialog, but to keep my code separate, I created it in a separate Class, else I would have to copy and paste that chunk of code into every activity where I want to use the dialog.

Solution explains my situation but it gives the core solution:

  1. As I was using a ViewAdapter I initialised the adapter with the Activity (not context ex. ->[kotlin] activity: Activity) as a parameter -> ex. [kotlin] this@MainActivity
  2. Then I passed that parameter to the Viewholder
  3. After which passing it again to the class that will inflate the Dialog.

Use the activity[optional name]: Activity[mandatory type] every where until it gets to the dialog you want to inflate

Its a lot of passing around, but it does make more sense over copy and pasting the same code everywhere

How to change the style of the title attribute inside an anchor tag?

a[title="My site"] {
    color: red;
}

This also works with any attribute you want to add for instance:

HTML

<div class="my_class" anything="whatever">My Stuff</div>

CSS

.my_class[anything="whatever"] {
    color: red;
}

See it work at: http://jsfiddle.net/vpYWE/1/

How can I autoplay a video using the new embed code style for Youtube?

You need to add an extra parameter, alongside the autoplay=1

allow="autoplay"

making it:

<iframe src="your-video-url?rel=0&amp;controls=0&amp;showinfo=0&amp;autoplay=1" frameborder="0" allow="autoplay; encrypted-media"></iframe>

"The import org.springframework cannot be resolved."

Right click project name in Eclipse, -->Maven-->Select Maven Profiles... Then tick the maven profile you want to set. After click OK, Eclipse will automatically import the maven setting to your project. If you check your project's Property, you will find Maven Dependencies Library has been added.

How to get child element by ID in JavaScript?

Using jQuery

$('#note textarea');

or just

$('#textid');

jquery onclick change css background image

I think this should be:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

How to sum the values of one column of a dataframe in spark/scala

Simply apply aggregation function, Sum on your column

df.groupby('steps').sum().show()

Follow the Documentation http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html

Check out this link also https://www.analyticsvidhya.com/blog/2016/10/spark-dataframe-and-operations/

Sample database for exercise

If you want a big database of real data to play with, you could sign up for the Netflix Prize contest and get access to their data, which is pretty large (a few gigs of entries).

3rd party edit

The URL above does not contain the dataset anylonger (october 2016). The wikipedia page about the Netflix Prize reports that a law suit was settled regarding privacy concerns.

Format Date/Time in XAML in Silverlight

<TextBlock Text="{Binding Date, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}" />

will return you

04/07/2011 at 1:28 PM (-04)

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I encountered the same problem, probably when I uninstalled it and tried to install it again. This happens because of the database file containing login details is still stored in the pc, and the new password will not match the older one. So you can solve this by just uninstalling mysql, and then removing the left over folder from the C: drive (or wherever you must have installed).

Datatables on-the-fly resizing

Use "bAutoWidth": false and go through the example given below. It is working for me.

Example:

$('#tableId').dataTable({
 "bAutoWidth": false
});

Store a cmdlet's result value in a variable in Powershell

Just access the Priority property of the object returned from the pipeline:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

(This won't work if Get-WSManInstance returns multiple objects.2)

For the second question: to get two properties there are several options, problably the simplest is to have have one variable* containing an object with two separate properties:

$var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use, assuming only one process:

$var.Priority

and

$var.ProcessID

If there are multiple processes $var will be an array which you can index, so to get the properties of the first process (using the array literal syntax @(...) so it is always a collection1):

$var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)

and then use:

$var[0].Priority
$var[0].ProcessID

1 PowerShell helpfully for the command line, but not so helpfully in scripts has some extra logic when assigning the result of a pipeline to a variable: if no objects are returned then set $null, if one is returned then that object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.

2 This changes in PowerShell V3 (at the time of writing in Release Candidate), using a member property on an array of objects will return an array of the value of those properties.

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

Make div stay at bottom of page's content all the time even when there are scrollbars

This is an intuitive solution using the viewport command that just sets the minimum height to the viewport height minus the footer height.

html,body{
height: 100%
}
#nonFooter{
min-height: calc(100vh - 30px)
}

#footer {
height:30px;
margin: 0;
clear: both;
width:100%;
}

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

There are a couple of parallization bugs in SQL server with abnormal input. OPTION(MAXDOP 1) will sidestep them.

EDIT: Old. My testing was done largely on SQL 2005. Most of these seem to not exist anymore, but every once in awhile we question the assumption when SQL 2014 does something dumb and we go back to the old way and it works. We never managed to demonstrate that it wasn't just a bad plan generation on more recent cases though since SQL server can be relied on to get the old way right in newer versions. Since all cases were IO bound queries MAXDOP 1 doesn't hurt.

Android webview & localStorage

setDatabasePath() method was deprecated in API level 19. I advise you to use storage locale like this:

webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
}

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

Cannot construct instance of - Jackson

For me there was no default constructor defined for the POJOs I was trying to use. creating default constructor fixed it.

public class TeamCode {

    @Expose
    private String value;

    public String getValue() {
        return value;
    }

    **public TeamCode() {
    }**

    public TeamCode(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "TeamCode{" +
                "value='" + value + '\'' +
                '}';
    }

    public void setValue(String value) {
        this.value = value;
    }

}

Python: finding an element in a list

From Dive Into Python:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5

Show/Hide Div on Scroll

$.fn.scrollEnd = function(callback, timeout) {          
  $(this).scroll(function(){
    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback,timeout));
  });
};

$(window).scroll(function(){
    $('.main').fadeOut();
});

$(window).scrollEnd(function(){
    $('.main').fadeIn();
}, 700);

That should do the Trick!

C# password TextBox in a ASP.net website

//in aspx page

<asp:TextBox ID="password" runat="server" TextMode="Password" />

//in MVC cshtml

@Html.Password("password", "", new { id = "password", Textmode = "Password" })

How to use AND in IF Statement

I think you should append .value in IF statement:

If Cells(i, "A").Value <> "Miami" And Cells(i, "D").Value <> "Florida" Then
    Cells(i, "C").Value = "BA"
End IF

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

For me I think there might be some issue in installing android NDK from android studio. I was able to resolve this in following manner

Downloaded android ndk from

https://developer.android.com/ndk/downloads/index.html

and placed inside ndk-bundle (where your android sdk is installed ). For more info check this screens.

https://app.box.com/s/dfi4h9k7v4h0tmbu3z9qnqx3d12fdejn

The import org.apache.commons cannot be resolved in eclipse juno

expand "Java Resources" and then 'Libraries' (in eclipse project). make sure that "Apache Tomcat" present.

if not follow- right click on project -> "Build Path" -> "Java Build Path" -> "Add Library" -> select "Server Runtime" -> next -> select "Apache Tomcat -> click finish

Unable to connect to SQL Server instance remotely

  1. Open the SQL Server Configuration Manager.... 2.Check wheather TCP and UDP are running or not.... 3.If not running , Please enable them and also check the SQL Server Browser is running or not.If not running turn it on.....

  2. Next you have to check which ports TCP and UDP is using. You have to open those ports from your windows firewall.....

5.Click here to see the steps to open a specific port in windows firewall....

  1. Now SQL Server is ready to access over LAN.......

  2. If you wan to access it remotely (over internet) , you have to do another job that is 'Port Forwarding'. You have open the ports TCP and UDP is using in SQL Server on your router. Now the configuration of routers are different. If you give me the details of your router (i. e name of the company and version ) , I can show you the steps how to forward a specific port.

Unfortunately MyApp has stopped. How can I solve this?

Logcat - To check the logs in the development phase of Android Studio

Initially clear the Logcat and let the app crash again so you can get only crashed log detail. You have to check the Stack trace

While, Unfortunately, MyApp has stopped. There are many reasons for it. You can check same in logs. For this, you can use the Log.e("TAG","Message");

Common error during app crash like:

  1. Coding mistake(Wrong use of keywords).
  2. Mismatch property name.
  3. Unsupported plugin(maybe).
  4. Mismatch version(maybe).
  5. Activity missing in AndroidManifest file.
  6. Permission missing in AndroidManifest file.
  7. Most common NullPointerException.
  8. Declared but not defined.

To resolve app crash error:

  • Keep in mind above points and go through it.
  • With the error, you will get the file name also in blue colour (click on them and jump to code from error is occurring).

mongodb how to get max value from collections

As one of comments:

db.collection.find().sort({age:-1}).limit(1) // for MAX
db.collection.find().sort({age:+1}).limit(1) // for MIN

it's completely usable but i'm not sure about performance

How to do the equivalent of pass by reference for primitives in Java

For a quick solution, you can use AtomicInteger or any of the atomic variables which will let you change the value inside the method using the inbuilt methods. Here is sample code:

import java.util.concurrent.atomic.AtomicInteger;


public class PrimitivePassByReferenceSample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        AtomicInteger myNumber = new AtomicInteger(0);
        System.out.println("MyNumber before method Call:" + myNumber.get());
        PrimitivePassByReferenceSample temp = new PrimitivePassByReferenceSample() ;
        temp.changeMyNumber(myNumber);
        System.out.println("MyNumber After method Call:" + myNumber.get());


    }

     void changeMyNumber(AtomicInteger myNumber) {
        myNumber.getAndSet(100);

    }

}

Output:

MyNumber before method Call:0

MyNumber After method Call:100

PHP: Get key from array?

If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Type

netsh wlan set hostednetwork mode=allow ssid=hotspotname key=123456789

perform all steps in proper order.. for more detail with image ,have a look..this might help to setup hotspot correctly.

http://www.infogeekers.com/turn-windows-8-into-wifi-hotspot/

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

You must use the column names and then set the values to insert (both ? marks):

//insert 1st row            
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();

React.js: Set innerHTML vs dangerouslySetInnerHTML

According to Dangerously Set innerHTML,

Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

Our design philosophy is that it should be "easy" to make things safe, and developers should explicitly state their intent when performing “unsafe” operations. The prop name dangerouslySetInnerHTML is intentionally chosen to be frightening, and the prop value (an object instead of a string) can be used to indicate sanitized data.

After fully understanding the security ramifications and properly sanitizing the data, create a new object containing only the key __html and your sanitized data as the value. Here is an example using the JSX syntax:

function createMarkup() {
    return {
       __html: 'First &middot; Second'    };
 }; 

<div dangerouslySetInnerHTML={createMarkup()} /> 

Read more about it using below link:

documentation: React DOM Elements - dangerouslySetInnerHTML.

Declaring abstract method in TypeScript

No, no, no! Please do not try to make your own 'abstract' classes and methods when the language does not support that feature; the same goes for any language feature you wish a given language supported. There is no correct way to implement abstract methods in TypeScript. Just structure your code with naming conventions such that certain classes are never directly instantiated, but without explicitly enforcing this prohibition.

Also, the example above is only going to provide this enforcement at run time, NOT at compile time, as you would expect in Java/C#.

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

Select first row in each GROUP BY group?

Very fast solution

SELECT a.* 
FROM
    purchases a 
    JOIN ( 
        SELECT customer, min( id ) as id 
        FROM purchases 
        GROUP BY customer 
    ) b USING ( id );

and really very fast if table is indexed by id:

create index purchases_id on purchases (id);

Search for a string in all tables, rows and columns of a DB

I think this can be an easiest way to find a string in all rows of your database -without using cursors and FOR XML-.

CREATE PROCEDURE SPFindAll (@find VARCHAR(max) = '')
AS
BEGIN
    SET NOCOUNT ON;
    --
    DECLARE @query VARCHAR(max) = ''

    SELECT  @query = @query + 
            CASE 
                WHEN @query = '' THEN '' 
                ELSE ' UNION ALL '
            END +
            'SELECT ''' + s.name + ''' As schemaName, ''' + t.name + ''' As tableName, ''' + c.name + ''' As ColumnName, [' + c.name + '] COLLATE DATABASE_DEFAULT As [Data] FROM [' + s.name + '].[' + t.name + '] WHERE [' + c.name + '] Like ''%' + @find + '%'''
    FROM 
        sys.schemas s
        INNER JOIN
        sys.tables t ON s.[schema_id] = t.[schema_id]
        INNER JOIN 
        sys.columns c ON t.[object_id] = c.[object_id]
        INNER JOIN
        sys.types ty ON c.user_type_id = ty.user_type_id
    WHERE
        ty.name LIKE '%char'

    EXEC(@query)
END

By creating this stored procedure you can run it for any string you want to find like this:

EXEC SPFindAll 'Hello World'

The result will be like this:

schemaName | tableName | columnName | Data
-----------+-----------+------------+-----------------------
schema1    | Table1    | Column1    | Hello World
schema1    | Table1    | Column1    | Hello World!
schema1    | Table2    | Column1    | I say "Hello World".
schema1    | Table2    | Column2    | Hello World

What's a standard way to do a no-op in python?

If you need a function that behaves as a nop, try

nop = lambda *a, **k: None
nop()

Sometimes I do stuff like this when I'm making dependencies optional:

try:
    import foo
    bar=foo.bar
    baz=foo.baz
except:
    bar=nop
    baz=nop

# Doesn't break when foo is missing:
bar()
baz()

PHP: Inserting Values from the Form into MySQL

There are two problems in your code.

  1. No action found in form.
  2. You have not executed the query mysqli_query()

dbConfig.php

<?php

$conn=mysqli_connect("localhost","root","password","testDB");

if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}

?>

index.php

 include('dbConfig.php');

<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="$1">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" type="text/css" href="style.css">

<title>test</title>


</head>
<body>

 <?php

  if(isset($_POST['save']))
{
    $sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

    $result = mysqli_query($conn,$sql);
}

?>

<form action="index.php" method="post"> 
<label id="first"> First name:</label><br/>
<input type="text" name="username"><br/>

<label id="first">Password</label><br/>
<input type="password" name="password"><br/>

<label id="first">Email</label><br/>
<input type="text" name="email"><br/>

<button type="submit" name="save">save</button>

</form>

</body>
</html>

Connection Java-MySql : Public Key Retrieval is not allowed

Give connection URL as jdbc:mysql://localhost:3306/hb_student_tracker?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC

Get current folder path

for .NET CORE use System.AppContext.BaseDirectory

(as a replacement for AppDomain.CurrentDomain.BaseDirectory)

How to get an element by its href in jquery?

Yes, you can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="http://google.com"]');

Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinksToGoogle = $('a[href^="http://google.com"]');

NameError: global name 'unicode' is not defined - in Python 3

Hope you are using Python 3 , Str are unicode by default, so please Replace Unicode function with String Str function.

if isinstance(unicode_or_str, str):    ##Replaces with str
    text = unicode_or_str
    decoded = False

AngularJS is rendering <br> as text not as a newline

You need to either use ng-bind-html-unsafe ... or you need to include the ngSanitize module and use ng-bind-html:

with ng-bind-html-unsafe

Use this if you trust the source of the HTML you're rendering it will render the raw output of whatever you put into it.

<div><h4>Categories</h4><span ng-bind-html-unsafe="q.CATEGORY"></span></div>

OR with ng-bind-html

Use this if you DON'T trust the source of the HTML (i.e. it's user input). It will sanitize the html to make sure it doesn't include things like script tags or other sources of potential security risks.

Make sure you include this:

<script src="http://code.angularjs.org/1.0.4/angular-sanitize.min.js"></script>

Then reference it in your application module:

var app = angular.module('myApp', ['ngSanitize']);

THEN use it:

<div><h4>Categories</h4><span ng-bind-html="q.CATEGORY"></span></div>

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

It can work as easy as this, choose the location you want, in this case I choose D3

Sheets("Put your Sheet's name here").Range("D3") = Now

Example, my sheet is called Sources

Sheets("Sources").Range("D3") = Now

How can I properly use a PDO object for a parameterized SELECT query

if you are using inline coding in single page and not using oops than go with this full example, it will sure help

//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw); 

//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";

//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);

//view the entire array (for testing)
print_r($result);

//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

FileSystemWatcher Changed event is raised twice

You could try to open it for write, and if successful then you could assume the other application is done with the file.

private void OnChanged(object source, FileSystemEventArgs e)
{
    try
    {
        using (var fs = File.OpenWrite(e.FullPath))
        {
        }
        //do your stuff
    }
    catch (Exception)
    {
        //no write access, other app not done
    }
}

Just opening it for write appears not to raise the changed event. So it should be safe.

Fatal error: Call to undefined function sqlsrv_connect()

i have same this because in httpd.conf in apache PHPIniDir D:/wamp/bin/php/php5.5.12 that was incorrect

Entity Framework Refresh context?

yourContext.Entry(yourEntity).Reload();

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

How to center canvas in html5

Just center the div in HTML:

  #test {
     width: 100px;
     height:100px;
     margin: 0px auto;
     border: 1px solid red;
   }


<div id="test">
   <canvas width="100" height="100"></canvas>
</div>

Just change the height and width to whatever and you've got a centered div

http://jsfiddle.net/BVghc/2/

How to set the LDFLAGS in CMakeLists.txt?

Look at:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

WinForms DataGridView font size

    private void UpdateFont()
    {
        //Change cell font
        foreach(DataGridViewColumn c in dgAssets.Columns)
        {
            c.DefaultCellStyle.Font = new Font("Arial", 8.5F, GraphicsUnit.Pixel);
        }
    }

Is there a way to reduce the size of the git folder?

git clean -d -f -i is the best way to do it.

This will help to clean in a more controlled manner.

-i stands for interactive.

How to close existing connections to a DB

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

Clear the value of bootstrap-datepicker

I was having similar trouble and the following worked for me:

$('#datepicker').val('').datepicker('update');

Both method calls were needed, otherwise it didn't clear.

Doing HTTP requests FROM Laravel to an external API

Based upon an answer of a similar question here: https://stackoverflow.com/a/22695523/1412268

Take a look at Guzzle

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' =>  ['user', 'pass']]);
echo $res->getStatusCode(); // 200
echo $res->getBody(); // { "type": "User", ....

Take a list of numbers and return the average

Simple math..

def average(n):
    result = 0
    for i in n:
      result += i
      ave_num = result / len(n)
    return ave_num

input -> [1,2,3,4,5]
output -> 3.0

jQuery change method on input type="file"

I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange="" attribute to the input tag:

<input type='file' onchange='getFilename(this)'/>

function getFileName(elm) {
   var fn = $(elm).val();
   ....
}

EDIT:

function getFileName(elm) {
   var fn = $(elm).val();
   var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
   alert(filename);
}

How to get process ID of background process?

pgrep can get you all of the child PIDs of a parent process. As mentioned earlier $$ is the current scripts PID. So, if you want a script that cleans up after itself, this should do the trick:

trap 'kill $( pgrep -P $$ | tr "\n" " " )' SIGINT SIGTERM EXIT

Formatting a double to two decimal places

string.Format will not change the original value, but it will return a formatted string. For example:

Console.WriteLine("Earnings this week: {0:0.00}", answer);

Note: Console.WriteLine allows inline string formatting. The above is equivalent to:

Console.WriteLine("Earnings this week: " + string.Format("{0:0.00}", answer));

join list of lists in python

What you're describing is known as flattening a list, and with this new knowledge you'll be able to find many solutions to this on Google (there is no built-in flatten method). Here is one of them, from http://www.daniel-lemire.com/blog/archives/2006/05/10/flattening-lists-in-python/:

def flatten(x):
    flat = True
    ans = []
    for i in x:
        if ( i.__class__ is list):
            ans = flatten(i)
        else:
            ans.append(i)
    return ans

How to set background color of view transparent in React Native

Here is my solution to a modal that can be rendered on any screen and initialized in App.tsx

ModalComponent.tsx

import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet, Platform } from 'react-native';
import EventEmitter from 'events';
// I keep localization files for strings and device metrics like height and width which are used for styling 
import strings from '../../config/strings';
import metrics from '../../config/metrics';

const emitter = new EventEmitter();
export const _modalEmitter = emitter

export class ModalView extends Component {
    state: {
        modalVisible: boolean,
        text: string, 
        callbackSubmit: any, 
        callbackCancel: any,
        animation: any
    }

    constructor(props) {
        super(props)
        this.state = {
            modalVisible: false,
            text: "", 
            callbackSubmit: (() => {}), 
            callbackCancel: (() => {}),
            animation: new Animated.Value(0)
        } 
    }

    componentDidMount() {
        _modalEmitter.addListener(strings.modalOpen, (event) => {
            var state = {
                modalVisible: true,
                text: event.text, 
                callbackSubmit: event.onSubmit, 
                callbackCancel: event.onClose,
                animation: new Animated.Value(0)
            } 
            this.setState(state)
        })
        _modalEmitter.addListener(strings.modalClose, (event) => {
            var state = {
                modalVisible: false,
                text: "", 
                callbackSubmit: (() => {}), 
                callbackCancel: (() => {}),
                animation: new Animated.Value(0)
            } 
            this.setState(state)
        })
    }

    componentWillUnmount() {
        var state = {
            modalVisible: false,
            text: "", 
            callbackSubmit: (() => {}), 
            callbackCancel: (() => {})
        } 
        this.setState(state)
    }

    closeModal = () => {
        _modalEmitter.emit(strings.modalClose)
    }

    startAnimation=()=>{
        Animated.timing(this.state.animation, {
            toValue : 0.5,
            duration : 500
        }).start()
    }

    body = () => {
        const animatedOpacity ={
            opacity : this.state.animation
        }
        this.startAnimation()
        return (
            <View style={{ height: 0 }}>
                <Modal
                    animationType="fade"
                    transparent={true}
                    visible={this.state.modalVisible}>

                    // render a transparent gray background over the whole screen and animate it to fade in, touchable opacity to close modal on click out

                    <Animated.View style={[styles.modalBackground, animatedOpacity]} > 
                        <TouchableOpacity onPress={() => this.closeModal()} activeOpacity={1} style={[styles.modalBackground, {opacity: 1} ]} > 
                        </TouchableOpacity>
                    </Animated.View>

                    // render an absolutely positioned modal component over that background
                    <View style={styles.modalContent}>

                        <View key="text_container">
                            <Text>{this.state.text}?</Text>
                        </View>
                        <View key="options_container">
                            // keep in mind the content styling is very minimal for this example, you can put in your own component here or style and make it behave as you wish
                            <TouchableOpacity
                                onPress={() => {
                                    this.state.callbackSubmit();
                                }}>
                                <Text>Confirm</Text>
                            </TouchableOpacity>

                            <TouchableOpacity
                                onPress={() => {
                                    this.state.callbackCancel();
                                }}>
                                <Text>Cancel</Text>
                            </TouchableOpacity>

                        </View>
                    </View>
                </Modal>
            </View> 
        );
    }

    render() {
        return this.body()
    }
}

// to center the modal on your screen 
// top: metrics.DEVICE_HEIGHT/2 positions the top of the modal at the center of your screen
// however you wanna consider your modal's height and subtract half of that so that the 
// center of the modal is centered not the top, additionally for 'ios' taking into consideration
// the 20px top bunny ears offset hence - (Platform.OS == 'ios'? 120 : 100)
// where 100 is half of the modal's height of 200
const styles = StyleSheet.create({
    modalBackground: {
        height: '100%', 
        width: '100%', 
        backgroundColor: 'gray', 
        zIndex: -1 
    },
    modalContent: { 
        position: 'absolute', 
        alignSelf: 'center', 
        zIndex: 1, 
        top: metrics.DEVICE_HEIGHT/2 - (Platform.OS == 'ios'? 120 : 100), 
        justifyContent: 'center', 
        alignItems: 'center', 
        display: 'flex', 
        height: 200, 
        width: '80%', 
        borderRadius: 27,
        backgroundColor: 'white', 
        opacity: 1 
    },
})

App.tsx render and import

import { ModalView } from './{your_path}/ModalComponent';

render() {
    return (
        <React.Fragment>
            <StatusBar barStyle={'dark-content'} />
            <AppRouter />
            <ModalView />
        </React.Fragment>
    )
}

and to use it from any component

SomeComponent.tsx

import { _modalEmitter } from './{your_path}/ModalComponent'

// Some functions within your component

showModal(modalText, callbackOnSubmit, callbackOnClose) {
    _modalEmitter.emit(strings.modalOpen, { text: modalText, onSubmit: callbackOnSubmit.bind(this), onClose: callbackOnClose.bind(this) })
}

closeModal() {
    _modalEmitter.emit(strings.modalClose)
}

Hope I was able to help some of you, I used a very similar structure for in-app notifications

Happy coding

Get current time in milliseconds in Python?

time.time() may only give resolution to the second, the preferred approach for milliseconds is datetime.

from datetime import datetime
dt = datetime.now()
dt.microsecond

javascript regex for special characters

function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text 
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}

This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.

What is log4j's default log file dumping path

To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:

# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Follow this tutorial to learn more about log4j usage:

http://www.mkyong.com/logging/log4j-log4j-properties-examples/

How to correctly get image from 'Resources' folder in NetBeans

This was a pain, using netBeans IDE 7.2.

  1. You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
  2. Add a resource folder to the src folder:

    • (project)
      • src
        • project package folder (contains .java files)
        • resources (whatever name you want)
        • images (optional subfolders)
  3. After the clean/build this structure is propogated into the Build folder:

    • (project)
      • build
        • classes
          • project package folder (contains generated .class files)
          • resources (your resources)
          • images (your optional subfolders)

To access the resources:

dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));

and:

if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {

worked for me. Note that in one case there is a leading "/" and in the other there isn't. So the root of the path to the resources is the "classes" folder within the build folder.

Double click on the executable jar file in the dist folder. The path to the resources still works.

What's the key difference between HTML 4 and HTML 5?

From Wikipedia:

  • New parsing rules oriented towards flexible parsing and compatibility
  • New elements – section, video, progress, nav, meter, time, aside, canvas
  • New input attributes – dates and times, email, url
  • New attributes – ping, charset, async
  • Global attributes (that can be applied for every element) – id, tabindex, repeat
  • Deprecated elements dropped – center, font, strike

How to set background image of a view?

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];

more info with example project

How to verify if nginx is running or not?

The modern (systemctl) way of doing it:

systemctl is-active nginx

You can use the exit value in your shell scripts as follows:

systemctl -q is-active nginx && echo "It is active, do something"

How to read values from properties file?

 [project structure]: http://i.stack.imgur.com/RAGX3.jpg
-------------------------------
    package beans;

        import java.util.Properties;
        import java.util.Set;

        public class PropertiesBeans {

            private Properties properties;

            public void setProperties(Properties properties) {
                this.properties = properties;
            }

            public void getProperty(){
                Set keys = properties.keySet();
                for (Object key : keys) {
                    System.out.println(key+" : "+properties.getProperty(key.toString()));
                }
            }

        }
    ----------------------------

        package beans;

        import org.springframework.context.ApplicationContext;
        import org.springframework.context.support.ClassPathXmlApplicationContext;

        public class Test {

            public static void main(String[] args) {
                // TODO Auto-generated method stub
                ApplicationContext ap = new ClassPathXmlApplicationContext("resource/spring.xml");
                PropertiesBeans p = (PropertiesBeans)ap.getBean("p");
                p.getProperty();
            }

        }
    ----------------------------

 - driver.properties

    Driver = com.mysql.jdbc.Driver
    url = jdbc:mysql://localhost:3306/test
    username = root
    password = root
    ----------------------------



     <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:util="http://www.springframework.org/schema/util"
               xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

            <bean id="p" class="beans.PropertiesBeans">
                <property name="properties">
                    <util:properties location="classpath:resource/driver.properties"/>
                </property>
            </bean>

        </beans>

How can I iterate over an enum?

If you knew that the enum values were sequential, for example the Qt:Key enum, you could:

Qt::Key shortcut_key = Qt::Key_0;
for (int idx = 0; etc...) {
    ....
    if (shortcut_key <= Qt::Key_9) {
        fileMenu->addAction("abc", this, SLOT(onNewTab()),
                            QKeySequence(Qt::CTRL + shortcut_key));
        shortcut_key = (Qt::Key) (shortcut_key + 1);
    }
}

It works as expected.

Catch a thread's exception in the caller thread in Python

Wrap Thread with exception storage.

import threading
import sys
class ExcThread(threading.Thread):

    def __init__(self, target, args = None):
        self.args = args if args else []
        self.target = target
        self.exc = None
        threading.Thread.__init__(self)

    def run(self):
        try:
            self.target(*self.args)
            raise Exception('An error occured here.')
        except Exception:
            self.exc=sys.exc_info()

def main():
    def hello(name):
        print(!"Hello, {name}!")
    thread_obj = ExcThread(target=hello, args=("Jack"))
    thread_obj.start()

    thread_obj.join()
    exc = thread_obj.exc
    if exc:
        exc_type, exc_obj, exc_trace = exc
        print(exc_type, ':',exc_obj, ":", exc_trace)

main()

Download file through an ajax call php

@joe : Many thanks, this was a good heads up!

I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file

So that's how I did it (using JQuery to handle the AJAX request):

  1. Initial post request:

    var parameters = {
         pid     : "mypid",
       "files[]": ["file1.jpg","file2.jpg","file3.jpg"]
    }

    var options = { url: "request/url",//replace with your request url type: "POST",//replace with your request type data: parameters,//see above context: document.body,//replace with your contex success: function(data){ if (data) { if (data.path) { //Create an hidden iframe, with the 'src' attribute set to the created ZIP file. var dlif = $('<iframe/>',{'src':data.path}).hide(); //Append the iFrame to the context this.append(dlif); } else if (data.error) { alert(data.error); } else { alert('Something went wrong'); } } } }; $.ajax(options);

The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:

 //Code to create the zip file
 //......
 //Id of the file
 $zipid = "myzipfile.zip"
 //Download Link - it can be prettier
 $dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
 //JSON response to be handled on the client side
 $result = '{"success":1,"path":"'.$dlink.'","error":null}';
 header('Content-type: application/json;');
 echo $result;

The "request/download" can perform some security checks, if needed, and generate the file transfer:

$fn = $_GET['file'];
if ($fn) {
  //Perform security checks
  //.....check user session/role/whatever
  $result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
  if (file_exists($result)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename='.basename($result));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($result));
    ob_clean();
    flush();
    readfile($result);
    @unlink($result);
  }

}

How to convert string to Title Case in Python?

I would like to add my little contribution to this post:

def to_camelcase(str):
  return ' '.join([t.title() for t in str.split()])

Change the maximum upload file size

I resolved this issue by creating a file called .user.ini in the directory where the PHP file scripts reside (this means any PHP script in this directory gets the new file size limit)

The contents of .user.ini were:

upload_max_filesize = 40M
post_max_size = 40M

How to use ESLint with Jest

ESLint supports this as of version >= 4:

/*
.eslintrc.js
*/
const ERROR = 2;
const WARN = 1;

module.exports = {
  extends: "eslint:recommended",
  env: {
    es6: true
  },
  overrides: [
    {
      files: [
        "**/*.test.js"
      ],
      env: {
        jest: true // now **/*.test.js files' env has both es6 *and* jest
      },
      // Can't extend in overrides: https://github.com/eslint/eslint/issues/8813
      // "extends": ["plugin:jest/recommended"]
      plugins: ["jest"],
      rules: {
        "jest/no-disabled-tests": "warn",
        "jest/no-focused-tests": "error",
        "jest/no-identical-title": "error",
        "jest/prefer-to-have-length": "warn",
        "jest/valid-expect": "error"
      }
    }
  ],
};

Here is a workaround (from another answer on here, vote it up!) for the "extend in overrides" limitation of eslint config :

overrides: [
  Object.assign(
    {
      files: [ '**/*.test.js' ],
      env: { jest: true },
      plugins: [ 'jest' ],
    },
    require('eslint-plugin-jest').configs.recommended
  )
]

From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724

Read Excel File in Python

A somewhat late answer, but with pandas, it is possible to get directly a column of an excel file:

import pandas

df = pandas.read_excel('sample.xls')
#print the column names
print df.columns
#get the values for a given column
values = df['Arm_id'].values
#get a data frame with selected columns
FORMAT = ['Arm_id', 'DSPName', 'Pincode']
df_selected = df[FORMAT]

Make sure you have installed xlrd and pandas:

pip install pandas xlrd

Why is my asynchronous function returning Promise { <pending> } instead of a value?

I had the same issue earlier, but my situation was a bit different in the front-end. I'll share my scenario anyway, maybe someone might find it useful.

I had an api call to /api/user/register in the frontend with email, password and username as request body. On submitting the form(register form), a handler function is called which initiates the fetch call to /api/user/register. I used the event.preventDefault() in the beginning line of this handler function, all other lines,like forming the request body as well the fetch call was written after the event.preventDefault(). This returned a pending promise.

But when I put the request body formation code above the event.preventDefault(), it returned the real promise. Like this:

event.preventDefault();
    const data = {
        'email': email,
        'password': password
    }
    fetch(...)
     ...

instead of :

     const data = {
            'email': email,
            'password': password
        }
     event.preventDefault();
     fetch(...)
     ...

moment.js get current time in milliseconds?

var timeArr = moment().format('x');

returns the Unix Millisecond Timestamp as per the format() documentation.

Where does PHP's error log reside in XAMPP?

You can also open the xampp control panel and click on the Button "logs":

enter image description here

firefox proxy settings via command line

I don't think you can. What you can do, however, is create different profiles for each proxy setting, and use the following command to switch between profiles when running Firefox:

firefox -no-remote -P <profilename>

How do you reverse a string in place in JavaScript?

String.prototype.reverse_string=function() {return this.split("").reverse().join("");}

or

String.prototype.reverse_string = function() {
    var s = "";
    var i = this.length;
    while (i>0) {
        s += this.substring(i-1,i);
        i--;
    }
    return s;
}

How to get text from EditText?

Place the following after the setContentView() method.

final EditText edit =  (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);

if var == False

I think what you are looking for is the 'not' operator?

if not var

Reference page: http://www.tutorialspoint.com/python/logical_operators_example.htm

How to read a file in reverse order?

for line in reversed(open("filename").readlines()):
    print line.rstrip()

And in Python 3:

for line in reversed(list(open("filename"))):
    print(line.rstrip())

What's a clean way to stop mongod on Mac OS X?

I prefer to stop the MongoDB server using the port command itself.

sudo port unload mongodb

And to start it again.

sudo port load mongodb

Convert UTC/GMT time to local time

I'd just like to add a general note of caution.

If all you are doing is getting the current time from the computer's internal clock to put a date/time on the display or a report, then all is well. But if you are saving the date/time information for later reference or are computing date/times, beware!

Let's say you determine that a cruise ship arrived in Honolulu on 20 Dec 2007 at 15:00 UTC. And you want to know what local time that was.
1. There are probably at least three 'locals' involved. Local may mean Honolulu, or it may mean where your computer is located, or it may mean the location where your customer is located.
2. If you use the built-in functions to do the conversion, it will probably be wrong. This is because daylight savings time is (probably) currently in effect on your computer, but was NOT in effect in December. But Windows does not know this... all it has is one flag to determine if daylight savings time is currently in effect. And if it is currently in effect, then it will happily add an hour even to a date in December.
3. Daylight savings time is implemented differently (or not at all) in various political subdivisions. Don't think that just because your country changes on a specific date, that other countries will too.

bootstrap jquery show.bs.modal event won't fire

Wrap your function in $(document).ready(function() { }), or more simply, $(function() {. In CoffeeScript, this would look like

$ ->
  $('#myModal').on 'show.bs.modal', (event)->

Without it, the JavaScript is executing before the document loads, and #myModal is not part of the DOM yet. Here is the Bootstrap reference.

Is there a format code shortcut for Visual Studio?

Change these shortcuts in Visual Studio

Tools ? Options ? Environment ? Keyboard

and then change the command

"Edit.FormatDocument" or "Edit.FormatSelection"

assign the same shortcut alt + shift +f as in visual studio code in order to not remember another one and confuse between each other.

What is the 'new' keyword in JavaScript?

The new keyword changes the context under which the function is being run and returns a pointer to that context.

When you don't use the new keyword, the context under which function Vehicle() runs is the same context from which you are calling the Vehicle function. The this keyword will refer to the same context. When you use new Vehicle(), a new context is created so the keyword this inside the function refers to the new context. What you get in return is the newly created context.

Postman addon's like in firefox

I liked PostMan, it was the main reason why I kept using Chrome, now I'm good with HttpRequester

https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

Angular2 module has no exported member

I was facing same issue and I just started app with new port and everything looks good.

ng serve --port 4201

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

Document has already explain the usage. So I am using SQL to explain these methods

Example:


Assuming there is an Order (orders) has many OrderItem (order_items).

And you have already build the relationship between them.

// App\Models\Order:
public function orderItems() {
    return $this->hasMany('App\Models\OrderItem', 'order_id', 'id');
}

These three methods are all based on a relationship.

With


Result: with() return the model object and its related results.

Advantage: It is eager-loading which can prevent the N+1 problem.

When you are using the following Eloquent Builder:

Order::with('orderItems')->get();

Laravel change this code to only two SQL:

// get all orders:
SELECT * FROM orders; 

// get the order_items based on the orders' id above
SELECT * FROM order_items WHERE order_items.order_id IN (1,2,3,4...);

And then laravel merge the results of the second SQL as different from the results of the first SQL by foreign key. At last return the collection results.

So if you selected columns without the foreign_key in closure, the relationship result will be empty:

Order::with(['orderItems' => function($query) { 
           // $query->sum('quantity');
           $query->select('quantity'); // without `order_id`
       }
])->get();

#=> result:
[{  id: 1,
    code: '00001',
    orderItems: [],    // <== is empty
  },{
    id: 2,
    code: '00002',
    orderItems: [],    // <== is empty
  }...
}]

Has


Has will return the model's object that its relationship is not empty.

Order::has('orderItems')->get();

Laravel change this code to one SQL:

select * from `orders` where exists (
    select * from `order_items` where `order`.`id` = `order_item`.`order_id`
)

whereHas


whereHas and orWhereHas methods to put where conditions on your has queries. These methods allow you to add customized constraints to a relationship constraint.

Order::whereHas('orderItems', function($query) {
   $query->where('status', 1);
})->get();

Laravel change this code to one SQL:

select * from `orders` where exists (
    select * 
    from `order_items` 
    where `orders`.`id` = `order_items`.`order_id` and `status` = 1
)

Pandas: how to change all the values of a column?

You can do a column transformation by using apply

Define a clean function to remove the dollar and commas and convert your data to float.

def clean(x):
    x = x.replace("$", "").replace(",", "").replace(" ", "")
    return float(x)

Next, call it on your column like this.

data['Revenue'] = data['Revenue'].apply(clean)

Send POST request with JSON data using Volley

JsonObjectRequest actually accepts JSONObject as body.

From this blog article,

final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");

new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });

Here is the source code and JavaDoc (@param jsonRequest):

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONObject> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
}

How to create an integer-for-loop in Ruby?

If you're doing this in your erb view (for Rails), be mindful of the <% and <%= differences. What you'd want is:

<% (1..x).each do |i| %>
  Code to display using <%= stuff %> that you want to display    
<% end %>

For plain Ruby, you can refer to: http://www.tutorialspoint.com/ruby/ruby_loops.htm

Loop through an array in JavaScript

The optimized approach is to cache the length of array and using the single variable pattern, initializing all variables with a single var keyword.

var i, max, myStringArray = ["Hello", "World"];
for (i = 0, max = myStringArray.length; i < max; i++) {
    alert(myStringArray[i]);

    // Do something
}

If the order of iteration does not matter then you should try reversed loop. It is the fastest as it reduces overhead condition testing and decrement is in one statement:

var i,myStringArray = ["item1","item2"];
for (i =  myStringArray.length; i--) {
    alert(myStringArray[i]);
}

Or better and cleaner to use a while loop:

var myStringArray = ["item1","item2"],i = myStringArray.length;
while(i--) {
   // Do something with fruits[i]
}

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I don't think that replacing "Require all denied" with "Require all granted" in this directive:

<Directory>

    Options FollowSymLinks
    AllowOverride None
    #Require all denied
    Require all granted
</Directory>

as suggested by Jan Czarny and seonded by user3801675 is the most secure way of solving this problem.

According to the Apache configuration files, that line denies access to the entirety of your server's filesystem. Replacing it might indeed allow access to your virtual host folders but at the price of allowing access to your entire computer as well!

Gev Balyan's approach seems to be the most secure approach here. It was the answer to the "access denied problems" plaguing me after setting up my new Apache server this morning.

Calling another different view from the controller using ASP.NET MVC 4

You can directly return a different view like:

return View("NameOfView", Model);

Or you can make a partial view and can return like:

return PartialView("PartialViewName", Model);

How to make a section of an image a clickable link

If you don't want to make the button a separate image, you can use the <area> tag. This is done by using html similar to this:

<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">

<map name="mapname">
    <area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>

Note 1: The coords=" " attribute must be formatted in this way: coords="x1,y1,x2,y2" where:

x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate

Note 2: The usemap="#mapname" attribute must include the #.

EDIT:

I looked at your code and added in the <map> and <area> tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.

<div class="flexslider">
    <ul class="slides" runat="server" id="Ul">                             
        <li class="flex-active-slide" style="background: url(&quot;images/slider-bg-1.jpg&quot;) no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
            <div class="container">
                <div class="sixteen columns contain"></div>   
                <img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
                <map name="imgmap">
                    <area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
                </map>
                <!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
            </div>
        </li>
    </ul>
</div>
<!-- <ul class="flex-direction-nav">
    <li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
    <li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->

Notes:

  1. The coord="48,341,294,275" is in reference to your screenshot you posted.
  2. The src="./test.png" is the location and name of the screenshot you posted on my computer.
  3. The href="http://www.example.com/" is an example link.

Send form data using ajax

$.ajax({
  url: "target.php",
  type: "post",
  data: "fname="+fname+"&lname="+lname,
}).done(function(data) {
  alert(data);
});

MySQL compare DATE string with string from DATETIME field

You can cast the DATETIME field into DATE as:

SELECT * FROM `calendar` WHERE CAST(startTime AS DATE) = '2010-04-29'

This is very much efficient.

What are the git concepts of HEAD, master, origin?

While this doesn't directly answer the question, there is great book available for free which will help you learn the basics called ProGit. If you would prefer the dead-wood version to a collection of bits you can purchase it from Amazon.

How can I find out the current route in Rails?

Simplest solution I can come up with in 2015 (verified using Rails 4, but should also work using Rails 3)

request.url
# => "http://localhost:3000/lists/7/items"
request.path
# => "/lists/7/items"

How to open SharePoint files in Chrome/Firefox

You can use web-based protocol handlers for the links as per https://sharepoint.stackexchange.com/questions/70178/how-does-sharepoint-2013-enable-editing-of-documents-for-chrome-and-fire-fox

Basically, just prepend ms-word:ofe|u| to the links to your SharePoint hosted Word documents.

What is a Question Mark "?" and Colon ":" Operator Used for?

Thats an if/else statement equilavent to

if(row % 2 == 1){
  System.out.print("<");
}else{
  System.out.print("\r>");
}

Firing events on CSS class changes in jQuery

using latest jquery mutation

var $target = jQuery(".required-entry");
            var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.attributeName === "class") {
                        var attributeValue = jQuery(mutation.target).prop(mutation.attributeName);
                        if (attributeValue.indexOf("search-class") >= 0){
                            // do what you want
                        }
                    }
                });
            });
            observer.observe($target[0],  {
                attributes: true
            });

// any code which update div having class required-entry which is in $target like $target.addClass('search-class');

Is it possible to CONTINUE a loop from an exception?

The CONTINUE statement is a new feature in 11g.

Here is a related question: 'CONTINUE' keyword in Oracle 10g PL/SQL

Convert a list of characters into a string

Use the join method of the empty string to join all of the strings together with the empty string in between, like so:

>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on script tags. Note that for JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results.

http://en.wikipedia.org/wiki/JSONP

Good answer on stackoverflow: jQuery AJAX cross domain

   $.ajax({
        type: "GET",
        url: 'http://www.oxfordlearnersdictionaries.com/search/english/direct/',
        data:{q:idiom},
        async:true,
        dataType : 'jsonp',   //you may use jsonp for cross origin request
        crossDomain:true,
        success: function(data, status, xhr) {
            alert(xhr.getResponseHeader('Location'));
        }
    });

How can I turn a List of Lists into a List in Java 8?

An expansion on Eran's answer that was the top answer, if you have a bunch of layers of lists, you can keep flatmapping them.

This also comes with a handy way of filtering as you go down the layers if needed as well.

So for example:

List<List<List<List<List<List<Object>>>>>> multiLayeredList = ...

List<Object> objectList = multiLayeredList
    .stream()
    .flatmap(someList1 -> someList1
        .stream()
        .filter(...Optional...))
    .flatmap(someList2 -> someList2
        .stream()
        .filter(...Optional...))
    .flatmap(someList3 -> someList3
        .stream()
        .filter(...Optional...))
    ...
    .collect(Collectors.toList())

This is would be similar in SQL to having SELECT statements within SELECT statements.

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.setAttribute("onclick", "removeColumn(#)");
newTH.setAttribute("id", "#");

function removeColumn(#){
// remove column #
}

Replace multiple characters in one replace call

You can also pass a RegExp object to the replace method like

var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");

string.replace(regexHash, "").replace(regexUnderscore, " ");

Javascript RegExp

Why does Node.js' fs.readFile() return a buffer instead of string?

From the docs:

If no encoding is specified, then the raw buffer is returned.

Which might explain the <Buffer ...>. Specify a valid encoding, for example utf-8, as your second parameter after the filename. Such as,

fs.readFile("test.txt", "utf8", function(err, data) {...});

css ellipsis on second line

A requirement for text-overflow: ellipsis; to work is a one-line version of white-space (pre, nowrap etc). Which means the text will never reach the second line.

Ergo. Not possible in pure CSS.

My source when I was looking for the exact same thing just now: http://www.quirksmode.org/css/textoverflow.html (Quirksmode ftw!)

EDIT If the good CSS gods will implement http://www.w3.org/TR/css-overflow-3/#max-lines we can haz this in pure CSS using fragments (new) and max-lines (new). Also some more info on http://css-tricks.com/line-clampin/

EDIT 2 WebKit/Blink has line-clamp: -webkit-line-clamp: 2 will put ellipsis on 2nd line.

How to compare two date values with jQuery

var startDate = $('#start_date').val().replace(/-/g,'/');
var endDate = $('#end_date').val().replace(/-/g,'/');

if(startDate > endDate){
   // do your stuff here...
}

Lotus Notes email as an attachment to another email

Tested vith Notes versions 6.5.x and 7.0.x From your Lotus Notes inbox

  1. Open the message
  2. Click View > Show > Page Source
  3. Copy all the data into a text file and save the file with .eml extension.
  4. Create a new message
  5. Attach the .eml file(s) and send the new message

Hop this helps. I have no client on my current machine but will test from home on 8.5.1

Android, How to read QR code in my application?

Zxing is an excellent library to perform Qr code scanning and generation. The following implementation uses Zxing library to scan the QR code image Don't forget to add following dependency in the build.gradle

implementation 'me.dm7.barcodescanner:zxing:1.9'

Code scanner activity:

    public class QrCodeScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
        private ZXingScannerView mScannerView;

        @Override
        public void onCreate(Bundle state) {
            super.onCreate(state);
            // Programmatically initialize the scanner view
            mScannerView = new ZXingScannerView(this);
            // Set the scanner view as the content view
            setContentView(mScannerView);
        }

        @Override
        public void onResume() {
            super.onResume();
            // Register ourselves as a handler for scan results.
            mScannerView.setResultHandler(this);
            // Start camera on resume
            mScannerView.startCamera();
        }

        @Override
        public void onPause() {
            super.onPause();
            // Stop camera on pause
            mScannerView.stopCamera();
        }

        @Override
        public void handleResult(Result rawResult) {
            // Do something with the result here
            // Prints scan results
            Logger.verbose("result", rawResult.getText());
            // Prints the scan format (qrcode, pdf417 etc.)
            Logger.verbose("result", rawResult.getBarcodeFormat().toString());
            //If you would like to resume scanning, call this method below:
            //mScannerView.resumeCameraPreview(this);
            Intent intent = new Intent();
            intent.putExtra(AppConstants.KEY_QR_CODE, rawResult.getText());
            setResult(RESULT_OK, intent);
            finish();
        }
    }

Getting HTTP code in PHP using curl

curl_exec is necessary. Try CURLOPT_NOBODY to not download the body. That might be faster.

Is it possible to have SSL certificate for IP address, not domain name?

Yep. Cloudflare uses it for its DNS instructions homepage: https://1.1.1.1

How to set the height of an input (text) field in CSS?

You should use font-size for controlling the height, it is widely supported amongst browsers. And in order to add spacing, you should use padding. Forexample,

.inputField{
  font-size: 30px;
  padding-top: 10px;
  padding-bottom: 10px;
}

How to split a string of space separated numbers into integers?

Use str.split():

>>> "42 0".split()  # or .split(" ")
['42', '0']

Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.

Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:

>>> map(int, "42 0".split())
[42, 0]

In Python 3, map will return a lazy object. You can get it into a list with list():

>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]

How can I format a nullable DateTime with ToString()?

As others have stated you need to check for null before invoking ToString but to avoid repeating yourself you could create an extension method that does that, something like:

public static class DateTimeExtensions {

  public static string ToStringOrDefault(this DateTime? source, string format, string defaultValue) {
    if (source != null) {
      return source.Value.ToString(format);
    }
    else {
      return String.IsNullOrEmpty(defaultValue) ?  String.Empty : defaultValue;
    }
  }

  public static string ToStringOrDefault(this DateTime? source, string format) {
       return ToStringOrDefault(source, format, null);
  }

}

Which can be invoked like:

DateTime? dt = DateTime.Now;
dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss");  
dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss", "n/a");
dt = null;
dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss", "n/a")  //outputs 'n/a'

What is the difference between a schema and a table and a database?

This particular posting has been shown to relate to Oracle only and the definition of Schema changes when in the context of another DB.

Probably the kinda thing to just google up but FYI terms do seem to vary in their definitions which is the most annoying thing :)

In Oracle a database is a database. In your head think of this as the data files and the redo logs and the actual physical presence on the disk of the database itself (i.e. not the instance)

A Schema is effectively a user. More specifically it's a set of tables/procs/indexes etc owned by a user. Another user has a different schema (tables he/she owns) however user can also see any schemas they have select priviliedges on. So a database can consist of hundreds of schemas, and each schema hundreds of tables. You can have tables with the same name in different schemas, which are in the same database.

A Table is a table, a set of rows and columns containing data and is contained in schemas.

Definitions may be different in SQL Server for instance. I'm not aware of this.

How do I resolve git saying "Commit your changes or stash them before you can merge"?

WARNING: This will delete untracked files, so it's not a great answer to this question.

In my case, I didn't want to keep the files, so this worked for me:

Git 2.11 and newer:

git clean  -d  -fx .

Older Git:

git clean  -d  -fx ""

Reference: http://www.kernel.org/pub/software/scm/git/docs/git-clean.html

  • -x means ignored files are also removed as well as files unknown to git.

  • -d means remove untracked directories in addition to untracked files.

  • -f is required to force it to run.

What is the correct way to free memory in C#

The .NET garbage collector takes care of all this for you.

It is able to determine when objects are no longer referenced and will (eventually) free the memory that had been allocated to them.

How to use switch statement inside a React component?

Try this, which is way cleaner too: Get that switch out of the render in a function and just call it passing the params you want. For example:

_x000D_
_x000D_
renderSwitch(param) {_x000D_
  switch(param) {_x000D_
    case 'foo':_x000D_
      return 'bar';_x000D_
    default:_x000D_
      return 'foo';_x000D_
  }_x000D_
}_x000D_
_x000D_
render() {_x000D_
  return (_x000D_
    <div>_x000D_
      <div>_x000D_
          // removed for brevity_x000D_
      </div>_x000D_
      {this.renderSwitch(param)}_x000D_
      <div>_x000D_
          // removed for brevity_x000D_
      </div>_x000D_
    </div>_x000D_
  );_x000D_
}
_x000D_
_x000D_
_x000D_

CS0234: Mvc does not exist in the System.Web namespace

I had the same problem and I had solved it with:

1.Right click to solution and click 'Clean Solution'

2.Click 'References' folder in solution explorer and select the problem reference (in your case it seems System.Web.Mvc) and then right click and click 'Properties'.

3.In the properties window, make sure that the 'Copy Local' property is set to 'True'

This worked for me. Hope it works for someone else

Helpful Note: As it has mentioned in comments by @Vlad:

If it is already set to True:

  1. Set it False
  2. Set it True again
  3. Rebuild

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

Getting msbuild.exe without installing Visual Studio

The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/

Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)

See this question for additional information.

Passing a method as a parameter in Ruby

You can pass a method as parameter with method(:function) way. Below is a very simple example:

def double(a)
  return a * 2 
end
=> nil

def method_with_function_as_param( callback, number) 
  callback.call(number) 
end 
=> nil

method_with_function_as_param( method(:double) , 10 ) 
=> 20

Setting selected option in laravel form

To echo some other answers here, the code I just used with 5.6 is this

{{ Form::select('status', ['Draft' => 'Draft', 'Sent' => 'Sent', 'Paid' => 'Paid'], $model->status, ['id' => 'status']) }}

In order to be able to use the Form Helper from LaravelCollective I took a look at https://laravelcollective.com/docs/master/html#drop-down-lists

I also had to composer require the dependency also so that I could use it in my projects

composer require "laravelcollective/html":"^5"

Lastly I altered my config/app.php and added the following in the $aliases array

    'Form' => Collective\Html\FormFacade::class,

https://laravelcollective.com/docs/master/html should be consulted if any of the above ceases to work.

Excel CSV - Number cell format

This works for Microsoft Office 2010, Excel Version 14

I misread the OP's preference "to do something to the file itself." I'm still keeping this for those who want a solution to format the import directly

  1. Open a blank (new) file (File -> New from workbook)
  2. Open the Import Wizard (Data -> From Text)
  3. Select your .csv file and Import
  4. In the dialogue box, choose 'Delimited', and click Next.
  5. Choose your delimiters (uncheck everything but 'comma'), choose your Text qualifiers (likely {None}), click Next
  6. In the Data preview field select the column you want to be text. It should highlight.
  7. In the Column data format field, select 'Text'.
  8. Click finished.

How to create a Calendar table for 100 years in Sql

 declare @date int
 WITH CTE_DatesTable
AS
(
  SELECT CAST('20000101' as date) AS [date]
  UNION ALL
  SELECT   DATEADD(dd, 1, [date])
  FROM CTE_DatesTable
  WHERE DATEADD(dd, 1, [date]) <= '21001231'
)
SELECT [DWDateKey]=[date],[DayDate]=datepart(dd,[date]),[DayOfWeekName]=datename(dw,[date]),[WeekNumber]=DATEPART( WEEK , [date]),[MonthNumber]=DATEPART( MONTH , [date]),[MonthName]=DATENAME( MONTH , [date]),[MonthShortName]=substring(LTRIM( DATENAME(MONTH,[date])),0, 4),[Year]=DATEPART(YY,[date]),[QuarterNumber]=DATENAME(quarter, [date]),[QuarterName]=DATENAME(quarter, [date]) into DimDate   FROM CTE_DatesTable

OPTION (MAXRECURSION 0);

How to delete multiple rows in SQL where id = (x to y)

CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]       
@CODE XML
,@ERRFLAG  CHAR(1) = '0' OUTPUT    

AS        

SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  

DELETE tb_SampleTest
    WHERE 
        CODE IN(
            SELECT Item.value('.', 'VARCHAR(20)')
            FROM  @CODE.nodes('RecordList/ID') AS x(Item)
            )

IF @@ROWCOUNT = 0
    SET @ERRFLAG = 200

SET NOCOUNT OFF

Get string value delete

<RecordList>
    <ID>1</ID>
    <ID>2</ID>
</RecordList>

How does Trello access the user's clipboard?

Daniel LeCheminant's code didn't work for me after converting it from CoffeeScript to JavaScript (js2coffee). It kept bombing out on the _.defer() line.

I assumed this was something to do with jQuery deferreds, so I changed it to $.Deferred() and it's working now. I tested it in Internet Explorer 11, Firefox 35, and Chrome 39 with jQuery 2.1.1. The usage is the same as described in Daniel's post.

var TrelloClipboard;

TrelloClipboard = new ((function () {
    function _Class() {
        this.value = "";
        $(document).keydown((function (_this) {
            return function (e) {
                var _ref, _ref1;
                if (!_this.value || !(e.ctrlKey || e.metaKey)) {
                    return;
                }
                if ($(e.target).is("input:visible,textarea:visible")) {
                    return;
                }
                if (typeof window.getSelection === "function" ? (_ref = window.getSelection()) != null ? _ref.toString() : void 0 : void 0) {
                    return;
                }
                if ((_ref1 = document.selection) != null ? _ref1.createRange().text : void 0) {
                    return;
                }
                return $.Deferred(function () {
                    var $clipboardContainer;
                    $clipboardContainer = $("#clipboard-container");
                    $clipboardContainer.empty().show();
                    return $("<textarea id='clipboard'></textarea>").val(_this.value).appendTo($clipboardContainer).focus().select();
                });
            };
        })(this));

        $(document).keyup(function (e) {
            if ($(e.target).is("#clipboard")) {
                return $("#clipboard-container").empty().hide();
            }
        });
    }

    _Class.prototype.set = function (value) {
        this.value = value;
    };

    return _Class;

})());

How to include bootstrap css and js in reactjs app?

Just in case if you can use yarn which is recommended for React apps,

you can do,

yarn add [email protected] // this is to add bootstrap with a specific  version

This will add the bootstrap as a dependency to your package.json as well.

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "4.1.1", // it will add an entry here
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-scripts": "1.1.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

After that just import bootstrap in your index.js file.

import 'bootstrap/dist/css/bootstrap.css';

How to change screen resolution of Raspberry Pi

After uncommenting disable_overscan=1 follow my lead. In the link, http://elinux.org/RPiconfig when you search for Video options, you'll also get hdmi_group and hdmi_mode. For, hdmi_group choose 1 if you're using you TV as an video output or choose 2 for monitors. Then in hdmi_mode, you can select the resolution you want from the list. I chose :- hdmi_group=2 hdmi_mode=23 And it worked.enter image description here

Setting table column width

Add colgroup after your table tag. Define width and number of column here. and add tbody tag. Put your tr inside of tbody.

<table>
    <colgroup>
       <col span="1" style="width: 30%;">
       <col span="1" style="width: 70%;">
    </colgroup>


    <tbody>
        <tr>
            <td>First column</td>
            <td>Second column</td>
        </tr>
    </tbody>
</table>

Get Category name from Post ID

here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

get_the_category

What is the copy-and-swap idiom?

Assignment, at its heart, is two steps: tearing down the object's old state and building its new state as a copy of some other object's state.

Basically, that's what the destructor and the copy constructor do, so the first idea would be to delegate the work to them. However, since destruction mustn't fail, while construction might, we actually want to do it the other way around: first perform the constructive part and, if that succeeded, then do the destructive part. The copy-and-swap idiom is a way to do just that: It first calls a class' copy constructor to create a temporary object, then swaps its data with the temporary's, and then lets the temporary's destructor destroy the old state.
Since swap() is supposed to never fail, the only part which might fail is the copy-construction. That is performed first, and if it fails, nothing will be changed in the targeted object.

In its refined form, copy-and-swap is implemented by having the copy performed by initializing the (non-reference) parameter of the assignment operator:

T& operator=(T tmp)
{
    this->swap(tmp);
    return *this;
}

Mocha / Chai expect.to.throw not catching thrown errors

I have found a nice way around it:

// The test, BDD style
it ("unsupported site", () => {
    The.function(myFunc)
    .with.arguments({url:"https://www.ebay.com/"})
    .should.throw(/unsupported/);
});


// The function that does the magic: (lang:TypeScript)
export const The = {
    'function': (func:Function) => ({
        'with': ({
            'arguments': function (...args:any) {
                return () => func(...args);
            }
        })
    })
};

It's much more readable then my old version:

it ("unsupported site", () => {
    const args = {url:"https://www.ebay.com/"}; //Arrange
    function check_unsupported_site() { myFunc(args) } //Act
    check_unsupported_site.should.throw(/unsupported/) //Assert
});

How can I ping a server port with PHP?

If you want to send ICMP packets in php you can take a look at this Native-PHP ICMP ping implementation, but I didn't test it.

EDIT:

Maybe the site was hacked because it seems that the files got deleted, there is copy in archive.org but you can't download the tar ball file, there are no contact email only contact form, but this will not work at archive.org, we can only wait until the owner will notice that sit is down.

count of entries in data frame in R

You could use table:

R> x <- read.table(textConnection('
   Believe Age Gender Presents Behaviour
1    FALSE   9   male       25   naughty
2     TRUE   5   male       20      nice
3     TRUE   4 female       30      nice
4     TRUE   4   male       34   naughty'
), header=TRUE)

R> table(x$Believe)

FALSE  TRUE 
    1     3 

How to check if a std::thread is still running?

An easy solution is to have a boolean variable that the thread sets to true on regular intervals, and that is checked and set to false by the thread wanting to know the status. If the variable is false for to long then the thread is no longer considered active.

A more thread-safe way is to have a counter that is increased by the child thread, and the main thread compares the counter to a stored value and if the same after too long time then the child thread is considered not active.

Note however, there is no way in C++11 to actually kill or remove a thread that has hanged.

Edit How to check if a thread has cleanly exited or not: Basically the same technique as described in the first paragraph; Have a boolean variable initialized to false. The last thing the child thread does is set it to true. The main thread can then check that variable, and if true do a join on the child thread without much (if any) blocking.

Edit2 If the thread exits due to an exception, then have two thread "main" functions: The first one have a try-catch inside which it calls the second "real" main thread function. This first main function sets the "have_exited" variable. Something like this:

bool thread_done = false;

void *thread_function(void *arg)
{
    void *res = nullptr;

    try
    {
        res = real_thread_function(arg);
    }
    catch (...)
    {
    }

    thread_done = true;

    return res;
}

SELECT only rows that contain only alphanumeric characters in MySQL

There is also this:

select m from table where not regexp_like(m, '^[0-9]\d+$')

which selects the rows that contains characters from the column you want (which is m in the example but you can change).

Most of the combinations don't work properly in Oracle platforms but this does. Sharing for future reference.

Replace a character at a specific index in a string?

Turn the String into a char[], replace the letter by index, then convert the array back into a String.

String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);

Rename a table in MySQL

ALTER TABLE old_table_name RENAME new_table_name;

or

RENAME TABLE old_table_name TO new_table_name;

How to start automatic download of a file in Internet Explorer?

For those trying to trigger the download using a dynamic link it's tricky to get it working consistently across browsers.

I had trouble in IE10+ downloading a PDF and used @dandavis' download function (https://github.com/rndme/download).

IE10+ needs msSaveBlob.

How to run batch file from network share without "UNC path are not supported" message?

I feel cls is the best answer. It hides the UNC message before anyone can see it. I combined it with a @pushd %~dp0 right after so that it would seem like opening the script and map the location in one step, thus preventing further UNC issues.

cls
@pushd %~dp0
:::::::::::::::::::
:: your script code here
:::::::::::::::::::
@popd

Notes:

pushd will change your working directory to the scripts location in the new mapped drive.

popd at the end, to clean up the mapped drive.

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
    {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
    }
}

Convert NSData to String?

Prior Swift 3.0 :

String(data: yourData, encoding: NSUTF8StringEncoding)

For Swift 4.0:

String(data: yourData, encoding: .utf8)

How can I restore the MySQL root user’s full privileges?

If you are using WAMP on you local computer (mysql version 5.7.14) Step 1: open my.ini file Step 2: un-comment this line 'skip-grant-tables' by removing the semi-colon step 3: restart mysql server step 4: launch mySQL console step 5:

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;

Step 6: Problem solved!!!!

What's the difference between git clone --mirror and git clone --bare

A nuanced explanation from the GitHub documentation on Duplicating a Repository:

As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references will be overwritten each time you fetch, so it will always be the same as the original repository.

How to print full stack trace in exception?

I usually use the .ToString() method on exceptions to present the full exception information (including the inner stack trace) in text:

catch (MyCustomException ex)
{
    Debug.WriteLine(ex.ToString());
}

Sample output:

ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes!
   at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14
   --- End of inner exception stack trace ---
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18
   at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23
   at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

Where Sticky Notes are saved in Windows 10 1607

It appears Microsoft now stores them in a SQLite database file called plum.sqlite located here:

C:\Users\%username%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite

What data type to use for hashed password field and what length?

As a fixed length string (VARCHAR(n) or however MySQL calls it). A hash has always a fixed length of for example 12 characters (depending on the hash algorithm you use). So a 20 char password would be reduced to a 12 char hash, and a 4 char password would also yield a 12 char hash.

Java Set retain order?

Set is just an interface. In order to retain order, you have to use a specific implementation of that interface and the sub-interface SortedSet, for example TreeSet or LinkedHashSet. You can wrap your Set this way:

Set myOrderedSet = new LinkedHashSet(mySet);

How can I split a delimited string into an array in PHP?

The Best choice is to use the function "explode()".

$content = "dad,fger,fgferf,fewf";
$delimiters =",";
$explodes = explode($delimiters, $content);

foreach($exploade as $explode) {
    echo "This is a exploded String: ". $explode;
}

If you want a faster approach you can use a delimiter tool like Delimiters.co There are many websites like this. But I prefer a simple PHP code.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

Many time this error is caused when you update a product in your custom module's observer as shown below.

class [NAMESPACE]_[MODULE NAME]_Model_Observer
{
    /**
     * Flag to stop observer executing more than once
     *
     * @var static bool
     */
    static protected $_singletonFlag = false;

    public function saveProductData(Varien_Event_Observer $observer)
    {
        if (!self::$_singletonFlag) {
            self::$_singletonFlag = true;

            $product = $observer->getEvent()->getProduct();
             //do stuff to the $product object
            // $product->save();  // commenting out this line prevents the error
            $product->getResource()->save($product);
    }
} 

Hence whenever you save your product after updating some properties in your module's observer use $product->getResource()->save($product) instead of $product->save()

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

The data-toggle attributes in Twitter Bootstrap

So many answers have been given, but they don't get to the point. Let's fix this.

http://www.w3schools.com/bootstrap/bootstrap_ref_js_collapse.asp

To the point

  1. Any attribute starting with data- is not parsed by the HTML5 parser.
  2. Bootstrap uses the data-toggle attribute to create collapse functionality.

How to use: Only 2 Steps

  1. Add class="collapse" to the element #A you want to collapse.
  2. Add data-target="#A" and data-toggle="collapse".

Purpose: the data-toggle attribute allows us to create a control to collapse/expand a div (block) if we use Bootstrap.

How to add an image in Tkinter?

It's a Python version problem. If you are using the latest, then your old syntax won't work and give you this error. Please follow @Josav09's code and you will be fine.

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

You don't need to change the compliance level here, or rather, you should but that's not the issue.

The code compliance ensures your code is compatible with a given Java version.

For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).

The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.

Instead, you should check the JDK/JRE you're using to build.

In Eclipse, open the project properties and check the selected JRE in the Java build path.

If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.

How to convert int[] into List<Integer> in Java?

Here is a generic way to convert array to ArrayList

<T> ArrayList<T> toArrayList(Object o, Class<T> type){
    ArrayList<T> objects = new ArrayList<>();
    for (int i = 0; i < Array.getLength(o); i++) {
        //noinspection unchecked
        objects.add((T) Array.get(o, i));
    }
    return objects;
}

Usage

ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);

How can I center an image in Bootstrap?

Three ways to align img in the center of its parent.

  1. img is an inline element, text-center aligns inline elements in the center of its container should the container be a block element.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col text-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. mx-auto centers block elements. In order to so, change display of the img from inline to block with d-block class.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Use d-flex and justify-content-center on its parent.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col d-flex justify-content-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Regular expression for checking if capital letters are found consecutively in a string?

If you want to get all Employee name in mysql which having at least one uppercase letter than apply this query.

SELECT * FROM registration WHERE `name` REGEXP BINARY '[A-Z]';

Get records of current month

This query should work for you:

SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())

Using DISTINCT and COUNT together in a MySQL Query

You were close :-)

select count(distinct productId) from table_name where keyword='$keyword'

How to clear PermGen space Error in tomcat

I tried the same on Intellij Ideav11.

It was not picking up the settings after checking the process using grep. In case it does not, give the mem settings for JAVA_OPTS in catalina.sh instead.

How do I make an asynchronous GET request in PHP?

Here's an adaptation of the accepted answer for performing a simple GET request.

One thing to note if the server does any url rewriting, this will not work. You'll need to use a more full featured http client.

  /**
   * Performs an async get request (doesn't wait for response)
   * Note: One limitation of this approach is it will not work if server does any URL rewriting
   */
  function async_get($url)
  {
      $parts=parse_url($url);

      $fp = fsockopen($parts['host'],
          isset($parts['port'])?$parts['port']:80,
          $errno, $errstr, 30);

      $out = "GET ".$parts['path']." HTTP/1.1\r\n";
      $out.= "Host: ".$parts['host']."\r\n";
      $out.= "Connection: Close\r\n\r\n";
      fwrite($fp, $out);
      fclose($fp);
  }

How to print exact sql query in zend framework ?

$db->getProfiler()->setEnabled(true);

// your code    
$this->update('table', $data, $where);    
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQuery());    
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQueryParams());    
$db->getProfiler()->setEnabled(false);

jQuery get values of checked checkboxes into array

You need to add .toArray() to the end of your .map() function

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).val();
    }).toArray();
    console.log(searchIDs);
});

Demo: http://jsfiddle.net/sZQtL/