Programs & Examples On #Http content length

The Content-Length header specifies the length (in bytes) of the content, both for requests and responses.

Generate a range of dates using SQL

Another simple way to get 365 days from today would be:

SELECT (TRUNC(sysdate) + (LEVEL-366)) AS DATE_ID
FROM DUAL connect by level <=( (sysdate)-(sysdate-366));

How to replace unicode characters in string with something else python?

  1. Decode the string to Unicode. Assuming it's UTF-8-encoded:

    str.decode("utf-8")
    
  2. Call the replace method and be sure to pass it a Unicode string as its first argument:

    str.decode("utf-8").replace(u"\u2022", "*")
    
  3. Encode back to UTF-8, if needed:

    str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
    

(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str shadows the built-in type str.)

Jquery DatePicker Set default date

To create the datepicker and set the date.

$('.next_date').datepicker({ dateFormat: 'dd-mm-yy'}).datepicker("setDate", new Date());

VBA: Conditional - Is Nothing

Based on your comment to Issun:

Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>

You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.

I did test several common objects and found that an instantiated Collection with no items added shows <No Variables> in the watch window. If your object is indeed a collection, you can check for the <No Variables> condition using the .Count property:

Sub TestObj()
Dim Obj As Object
    Set Obj = New Collection
    If Obj Is Nothing Then
        Debug.Print "Object not instantiated"
    Else
        If Obj.Count = 0 Then
            Debug.Print "<No Variables> (ie, no items added to the collection)"
        Else
            Debug.Print "Object instantiated and at least one item added"
        End If
    End If
End Sub

It is also worth noting that if you declare any object As New then the Is Nothing check becomes useless. The reason is that when you declare an object As New then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!

Dim MyObject As New Collection
If MyObject Is Nothing Then  ' <--- This check always returns False

This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.

Query Mongodb on month, day, year... of a datetime

Use the $expr operator which allows the use of aggregation expressions within the query language. This will give you the power to use the Date Aggregation Operators in your query as follows:

month = 11
db.mydatabase.mycollection.find({ 
    "$expr": { 
        "$eq": [ { "$month": "$date" }, month ] 
    } 
})

or

day = 17
db.mydatabase.mycollection.find({ 
    "$expr": { 
        "$eq": [ { "$dayOfMonth": "$date" }, day ] 
    } 
})

You could also run an aggregate operation with the aggregate() function that takes in a $redact pipeline:

month = 11
db.mydatabase.mycollection.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$eq": [ { "$month": "$date" }, month ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

For the other request

day = 17
db.mydatabase.mycollection.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$eq": [ { "$dayOfMonth": "$date" }, day ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

Using OR

month = 11
day = 17
db.mydatabase.mycollection.aggregate([
    {
        "$redact": {
            "$cond": [
                { 
                    "$or": [ 
                        { "$eq": [ { "$month": "$date" }, month ] },
                        { "$eq": [ { "$dayOfMonth": "$date" }, day ] }
                    ] 
                },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

Using AND

var month = 11,
    day = 17;
db.collection.aggregate([
    {
        "$redact": {
            "$cond": [
                { 
                    "$and": [ 
                        { "$eq": [ { "$month": "$createdAt" }, month ] },
                        { "$eq": [ { "$dayOfMonth": "$createdAt" }, day ] }
                    ] 
                },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

The $redact operator incorporates the functionality of $project and $match pipeline and will return all documents match the condition using $$KEEP and discard from the pipeline those that don't match using the $$PRUNE variable.

Execute JavaScript code stored as a string

Using both eval and creating a new Function to execute javascript comes with a lot of security risks.

const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);

I prefer this method to execute the Javascript I receive as a string.

Postgres: INSERT if does not exist already

INSERT .. WHERE NOT EXISTS is good approach. And race conditions can be avoided by transaction "envelope":

BEGIN;
LOCK TABLE hundred IN SHARE ROW EXCLUSIVE MODE;
INSERT ... ;
COMMIT;

Token based authentication in Web API without any user interface

ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

All you have to do is to post URL encoded username and password inside query string.

/Token/userName=johndoe%40example.com&password=1234&grant_type=password

If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.

Dart SDK is not configured

It normally happens when you are download projects from the github. normally dark sdk contains inside flutter.

you can solve this issue following these few steps

  1. go to the setting using (Ctrl + Shift + s)
  2. go the the Languages & Framework
  3. go to Dart
  4. Enable Dark support for the project
  5. Change the dark sdk path C:\flutter\bin\cache\dart-sdk
  6. Apply

Replace first occurrence of pattern in a string

I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

document.body.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
  event.preventDefault();
  console.log('clicked ;)');
}
});

DEMO

https://jsfiddle.net/muratkezli/51rnc9ug/6/

How to download Google Play Services in an Android emulator?

Go to https://university.xamarin.com/resources/working-with-android-emulators . Scroll down to the "Installing Google Play Services" section. Step by step walk through there.

Directly plagarized from xamarin here so I don't get dinged for linking and not including solution. Posting this as I found the hit in stack before I found the solution that worked across the board on the xamarin page.

  1. Start the Xamarin Android Player and run one of the supplied images, the following assumes you have started the KitKat Nexus 4 image. Download the proper Google Play Services .zip file from www.teamandroid.com/gapps/ . Make sure to download the image appropriate for your version of Android.
  2. Drag the .zip file onto the running emulator and drop it to install the component, here we show it on Mac OS X, but the same mechanism is used in Windows. You will get a prompt to install the package onto the emulator which indicates the image will be restarted
  3. Once it restarts, you will get a notification that installation is completed, and the image will now have Google Maps, Google+ and support for the Google Play store. Note that some things do not work correctly and you may get a few errors from some of the services, but you can safely dismiss these and continue the instructions.
  4. Next, you will need to associate a Google account so that you can update the services using the Google Play store. It should prompt you for this, but if it does not, you can go into the Google Settings and add a new account. Once you've added the account, you can then update the Google apps by opening the Google Play store application and going into settings from the side bar menu.
  5. Select Settings and then scroll down to the Build Version number information and double-tap on it until it tells you it is either up-to-date, or that it will download and install a new version.
  6. Power off the device (press and hold the power button in the toolbar on the right) and restart it. Once it restarts, it should indicate that it needs to update the Google Play services, tapping the notification will open the Google Play Store and install the latest version

Now you can run applications that depend on Google Maps in the Xamarin Android Player.

text box input height

You can define a class or id for input fields.

Or

input {
    line-height: 20px;
}

Hope this helps you.

How can I run a windows batch file but hide the command window?

If you write an unmanaged program and use CreateProcess API then you should initialize lpStartupInfo parameter of the type STARTUPINFO so that wShowWindow field of the struct is SW_HIDE and not forget to use STARTF_USESHOWWINDOW flag in the dwFlags field of STARTUPINFO. Another method is to use CREATE_NO_WINDOW flag of dwCreationFlags parameter. The same trick work also with ShellExecute and ShellExecuteEx functions.

If you write a managed application you should follows advices from http://blogs.msdn.com/b/jmstall/archive/2006/09/28/createnowindow.aspx: initialize ProcessStartInfo with CreateNoWindow = true and UseShellExecute = false and then use as a parameter of . Exactly like in case of you can set property WindowStyle of ProcessStartInfo to ProcessWindowStyle.Hidden instead or together with CreateNoWindow = true.

You can use a VBS script which you start with wcsript.exe. Inside the script you can use CreateObject("WScript.Shell") and then Run with 0 as the second (intWindowStyle) parameter. See http://www.robvanderwoude.com/files/runnhide_vbs.txt as an example. I can continue with Kix, PowerShell and so on.

If you don't want to write any program you can use any existing utility like CMDOW /RUN /HID "c:\SomeDir\MyBatch.cmd", hstart /NOWINDOW /D=c:\scripts "c:\scripts\mybatch.bat", hstart /NOCONSOLE "batch_file_1.bat" which do exactly the same. I am sure that you will find much more such kind of free utilities.

In some scenario (for example starting from UNC path) it is important to set also a working directory to some local path (%SystemRoot%\system32 work always). This can be important for usage any from above listed variants of starting hidden batch.

List<T> or IList<T>

You would because defining an IList or an ICollection would open up for other implementations of your interfaces.

You might want to have an IOrderRepository that defines a collection of orders in either a IList or ICollection. You could then have different kinds of implementations to provide a list of orders as long as they conform to "rules" defined by your IList or ICollection.

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

In our case we finally found out the root cause of StaleStateException.

In fact we were deleting the row twice in a single hibernate session. Earlier we were using ojdbc6 lib, and this was ok in this version.

But when we upgraded to odjc7 or ojdbc8, deleting records twice was throwing exception. There was bug in our code where we were deleting twice, but that was not evident in ojdbc6.

We were able to reproduce with this piece of code:

Detail detail = getDetail(Long.valueOf(1396451));
session.delete(detail);
session.flush();
session.delete(detail);
session.flush();

On first flush hibernate goes and makes changes in database. During 2nd flush hibernate compares session's object with actual table's record, but could not find one, hence the exception.

How can I override the OnBeforeUnload dialog and replace it with my own?

 <script type="text/javascript">
        window.onbeforeunload = function(evt) {
            var message = 'Are you sure you want to leave?';
            if (typeof evt == 'undefined') {
                evt = window.event;
            }       
            if (evt) {
                evt.returnValue = message;
            }
            return message;
        } 
    </script>

refer from http://www.codeprojectdownload.com

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

How can I dismiss the on screen keyboard?

The example implementation of .unfocus() to auto hide keyboard when scrolling a list

FocusScope.of(context).unfocus();

you can find at

https://github.com/flutter/flutter/issues/36869#issuecomment-518118441

Thanks to szotp

How to preserve insertion order in HashMap?

HashMap is unordered per the second line of the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. This link can help you find the most appropriate collection to use.

How can I adjust DIV width to contents

EDIT2- Yea auto fills the DOM SOZ!

#img_box{        
    width:90%;
    height:90%;
    min-width: 400px;
    min-height: 400px;
}

check out this fiddle

http://jsfiddle.net/ppumkin/4qjXv/2/

http://jsfiddle.net/ppumkin/4qjXv/3/

and this page

http://www.webmasterworld.com/css/3828593.htm

Removed original answer because it was wrong.

The width is ok- but the height resets to 0

so

 min-height: 400px;

Multiple conditions in WHILE loop

You need to change || to && so that both conditions must be true to enter the loop.

while(myChar != 'n' && myChar != 'N')

ExecuteReader: Connection property has not been initialized

As mentioned you should assign the connection and you should preferably also use sql parameters instead, so your command assignment would read:

    // 3. Pass the connection to a command object
    SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn); // ", conn)" added
    cmd.Parameters.Add("project", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
    cmd.Parameters.Add("iteration", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;

    //
    // 4. Use the connection
    //

By using parameters you avoid SQL injection and other problematic typos (project names like "myproject's" is an example).

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

I had this due to a simple ordering mistake on my end. I called

[WRONG] docker run <image> <arguments> <command>

When I should have used

docker run <arguments> <image> <command>

Same resolution on similar question: https://stackoverflow.com/a/50762266/6278

Why am I getting this error Premature end of file?

I resolved the issue by converting the source feed from http://www.news18.com/rss/politics.xml to https://www.news18.com/rss/politics.xml

with http below code was creating an empty file which was causing the issue down the line

    String feedUrl = "https://www.news18.com/rss/politics.xml"; 
    File feedXmlFile = null;

    try {
    feedXmlFile =new File("C://opinionpoll/newsFeed.xml");
    FileUtils.copyURLToFile(new URL(feedUrl),feedXmlFile);


          DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
          Document doc = dBuilder.parse(feedXmlFile);

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

Set and Get Methods in java?

It looks like you trying to do something similar to C# if you want setAge create method
setAge(int age){ this.age = age;}

Fragment Inside Fragment

you can use getChildFragmentManager() function.

example:

Parent fragment :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.parent_fragment, container,
            false);


    }

    //child fragment 
    FragmentManager childFragMan = getChildFragmentManager();
    FragmentTransaction childFragTrans = childFragMan.beginTransaction();
    ChildFragment fragB = new ChildFragment ();
    childFragTrans.add(R.id.FRAGMENT_PLACEHOLDER, fragB);
    childFragTrans.addToBackStack("B");
    childFragTrans.commit();        


    return rootView;
}

Parent layout (parent_fragment.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">



    <FrameLayout
        android:id="@+id/FRAGMENT_PLACEHOLDER"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>




</LinearLayout>

Child Fragment:

public class ChildFragment extends Fragment implements View.OnClickListener{

    View v ;
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View rootView = inflater.inflate(R.layout.child_fragment, container, false);


        v = rootView;


        return rootView;
    }



    @Override
    public void onClick(View view) {


    }


} 

Is there more to an interface than having the correct methods

Interfaces allow statically typed languages to support polymorphism. An Object Oriented purist would insist that a language should provide inheritance, encapsulation, modularity and polymorphism in order to be a fully-featured Object Oriented language. In dynamically-typed - or duck typed - languages (like Smalltalk,) polymorphism is trivial; however, in statically typed languages (like Java or C#,) polymorphism is far from trivial (in fact, on the surface it seems to be at odds with the notion of strong typing.)

Let me demonstrate:

In a dynamically-typed (or duck typed) language (like Smalltalk), all variables are references to objects (nothing less and nothing more.) So, in Smalltalk, I can do this:

|anAnimal|    
anAnimal := Pig new.
anAnimal makeNoise.

anAnimal := Cow new.
anAnimal makeNoise.

That code:

  1. Declares a local variable called anAnimal (note that we DO NOT specify the TYPE of the variable - all variables are references to an object, no more and no less.)
  2. Creates a new instance of the class named "Pig"
  3. Assigns that new instance of Pig to the variable anAnimal.
  4. Sends the message makeNoise to the pig.
  5. Repeats the whole thing using a cow, but assigning it to the same exact variable as the Pig.

The same Java code would look something like this (making the assumption that Duck and Cow are subclasses of Animal:

Animal anAnimal = new Pig();
duck.makeNoise();

anAnimal = new Cow();
cow.makeNoise();

That's all well and good, until we introduce class Vegetable. Vegetables have some of the same behavior as Animal, but not all. For example, both Animal and Vegetable might be able to grow, but clearly vegetables don't make noise and animals cannot be harvested.

In Smalltalk, we can write this:

|aFarmObject|
aFarmObject := Cow new.
aFarmObject grow.
aFarmObject makeNoise.

aFarmObject := Corn new.
aFarmObject grow.
aFarmObject harvest.

This works perfectly well in Smalltalk because it is duck-typed (if it walks like a duck, and quacks like a duck - it is a duck.) In this case, when a message is sent to an object, a lookup is performed on the receiver's method list, and if a matching method is found, it is called. If not, some kind of NoSuchMethodError exception is thrown - but it's all done at runtime.

But in Java, a statically typed language, what type can we assign to our variable? Corn needs to inherit from Vegetable, to support grow, but cannot inherit from Animal, because it does not make noise. Cow needs to inherit from Animal to support makeNoise, but cannot inherit from Vegetable because it should not implement harvest. It looks like we need multiple inheritance - the ability to inherit from more than one class. But that turns out to be a pretty difficult language feature because of all the edge cases that pop up (what happens when more than one parallel superclass implement the same method?, etc.)

Along come interfaces...

If we make Animal and Vegetable classes, with each implementing Growable, we can declare that our Cow is Animal and our Corn is Vegetable. We can also declare that both Animal and Vegetable are Growable. That lets us write this to grow everything:

List<Growable> list = new ArrayList<Growable>();
list.add(new Cow());
list.add(new Corn());
list.add(new Pig());

for(Growable g : list) {
   g.grow();
}

And it lets us do this, to make animal noises:

List<Animal> list = new ArrayList<Animal>();
list.add(new Cow());
list.add(new Pig());
for(Animal a : list) {
  a.makeNoise();
}

The advantage to the duck-typed language is that you get really nice polymorphism: all a class has to do to provide behavior is provide the method. As long as everyone plays nice, and only sends messages that match defined methods, all is good. The downside is that the kind of error below isn't caught until runtime:

|aFarmObject|
aFarmObject := Corn new.
aFarmObject makeNoise. // No compiler error - not checked until runtime.

Statically-typed languages provide much better "programming by contract," because they will catch the two kinds of error below at compile-time:

// Compiler error: Corn cannot be cast to Animal.
Animal farmObject = new Corn();  
farmObject makeNoise();

--

// Compiler error: Animal doesn't have the harvest message.
Animal farmObject = new Cow();
farmObject.harvest(); 

So....to summarize:

  1. Interface implementation allows you to specify what kinds of things objects can do (interaction) and Class inheritance lets you specify how things should be done (implementation).

  2. Interfaces give us many of the benefits of "true" polymorphism, without sacrificing compiler type checking.

How do you clear the focus in javascript?

.focus() and then .blur() something else arbitrary on your page. Since only one element can have the focus, it is transferred to that element and then removed.

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

iPad WebApp Full Screen in Safari

Looks like most of the answers on this thread have not kept up. iOS Safari on iPads have fullscreen support now and it's very easy to implement using javascript.

Here's my full article on how to implement fullscreen capability on your web app.

How to remove only 0 (Zero) values from column in excel 2010

Some of the other answers are great for removing zeros from existing data, but if you have a working sheet that is constantly changed and want to prevent zeros from ever appearing, I find it's easiest to use conditional formatting to make them invisible. Just select the range of cells you want to apply it to > conditional formatting > new rule.

Change the rule type to "format only cells that contain" Cell value > equal to > 0.

Under "Format" change the text colour to white or whatever your background happens to be, and all cells which contain exactly zero will disappear.

Obviously this also works with any other value you want to make disappear.

How to float a div over Google Maps?

Try this:

<style>
   #wrapper { position: relative; }
   #over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }
</style>

<div id="wrapper">
   <div id="google_map">

   </div>

   <div id="over_map">

   </div>
</div>

The zip() function in Python 3

The zip() function in Python 3 returns an iterator. That is the reason why when you print test1 you get - <zip object at 0x1007a06c8>. From documentation -

Make an iterator that aggregates elements from each of the iterables.

But once you do - list(test1) - you have exhausted the iterator. So after that anytime you do list(test1) would only result in empty list.

In case of test2, you have already created the list once, test2 is a list, and hence it will always be that list.

How to discard all changes made to a branch?

Note: You CANNOT UNDO this.

Try git checkout -f this will discard any local changes which are not committed in ALL branches and master.

Remove leading zeros from a number in Javascript

We can use four methods for this conversion

  1. parseInt with radix 10
  2. Number Constructor
  3. Unary Plus Operator
  4. Using mathematical functions (subtraction)

_x000D_
_x000D_
const numString = "065";_x000D_
_x000D_
//parseInt with radix=10_x000D_
let number = parseInt(numString, 10);_x000D_
console.log(number);_x000D_
_x000D_
// Number constructor_x000D_
number = Number(numString);_x000D_
console.log(number);_x000D_
_x000D_
// unary plus operator_x000D_
number = +numString;_x000D_
console.log(number);_x000D_
_x000D_
// conversion using mathematical function (subtraction)_x000D_
number = numString - 0;_x000D_
console.log(number);
_x000D_
_x000D_
_x000D_


Update(based on comments): Why doesn't this work on "large numbers"?

For the primitive type Number, the safest max value is 253-1(Number.MAX_SAFE_INTEGER).

_x000D_
_x000D_
console.log(Number.MAX_SAFE_INTEGER);
_x000D_
_x000D_
_x000D_

Now, lets consider the number string '099999999999999999999' and try to convert it using the above methods

_x000D_
_x000D_
const numString = '099999999999999999999';_x000D_
_x000D_
let parsedNumber = parseInt(numString, 10);_x000D_
console.log(`parseInt(radix=10) result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = Number(numString);_x000D_
console.log(`Number conversion result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = +numString;_x000D_
console.log(`Appending Unary plus operator result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = numString - 0;_x000D_
console.log(`Subtracting zero conversion result: ${parsedNumber}`);
_x000D_
_x000D_
_x000D_

All results will be incorrect.

That's because, when converted, the numString value is greater than Number.MAX_SAFE_INTEGER. i.e.,

99999999999999999999 > 9007199254740991

This means all operation performed with the assumption that the stringcan be converted to number type fails.

For numbers greater than 253, primitive BigInt has been added recently. Check browser compatibility of BigInthere.

The conversion code will be like this.

const numString = '099999999999999999999';
const number = BigInt(numString);

P.S: Why radix is important for parseInt?

If radix is undefined or 0 (or absent), JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal)
  • If the input string begins with any other value, the radix is 10 (decimal)

Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.

For this reason, always specify a radix when using parseInt

Shortest distance between a point and a line segment

One line solution using arctangents:

The idea is to move A to (0, 0) and rotate triangle clockwise to make C lay on X axis, when this happen, By will be the distance.

  1. a angle = Atan(Cy - Ay, Cx - Ax);
  2. b angle = Atan(By - Ay, Bx - Ax);
  3. AB length = Sqrt( (Bx - Ax)^2 + (By - Ay)^2 )
  4. By = Sin ( bAngle - aAngle) * ABLength

C#

public double Distance(Point a, Point b, Point c)
{
    // normalize points
    Point cn = new Point(c.X - a.X, c.Y - a.Y);
    Point bn = new Point(b.X - a.X, b.Y - a.Y);

    double angle = Math.Atan2(bn.Y, bn.X) - Math.Atan2(cn.Y, cn.X);
    double abLength = Math.Sqrt(bn.X*bn.X + bn.Y*bn.Y);

    return Math.Sin(angle)*abLength;
}

One line C# (to be converted to SQL)

double distance = Math.Sin(Math.Atan2(b.Y - a.Y, b.X - a.X) - Math.Atan2(c.Y - a.Y, c.X - a.X)) * Math.Sqrt((b.X - a.X) * (b.X - a.X) + (b.Y - a.Y) * (b.Y - a.Y))

Overriding css style?

You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important.

#zoomTarget .slikezamenjanje img {
    max-height: auto;
    padding-right: 0px;
}

Hatting

I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.

For example, all CSS height and width attributes default to auto.

Can't connect to localhost on SQL Server Express 2012 / 2016

Try changing the User that owns the service to Local System or use your admin account.

Under services, I changed the Service SQL Server (MSSQLSERVER) Log On from NT Service\Sql... To Local System. Right click the service and go to the Log On Tab and select the radio button Local System Account. You could also force another User to run it too if that fits better.

Inserting multiple rows in a single SQL query?

NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.

You can use INSERT with SELECT UNION ALL:

INSERT INTO MyTable  (FirstCol, SecondCol)
    SELECT  'First' ,1
    UNION ALL
SELECT  'Second' ,2
    UNION ALL
SELECT  'Third' ,3
...

Only for small datasets though, which should be fine for your 4 records.

Releasing memory in Python

First, you may want to install glances:

sudo apt-get install python-pip build-essential python-dev lm-sensors 
sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
sudo pip install glances

Then run it in the terminal!

glances

In your Python code, add at the begin of the file, the following:

import os
import gc # Garbage Collector

After using the "Big" variable (for example: myBigVar) for which, you would like to release memory, write in your python code the following:

del myBigVar
gc.collect()

In another terminal, run your python code and observe in the "glances" terminal, how the memory is managed in your system!

Good luck!

P.S. I assume you are working on a Debian or Ubuntu system

Laravel Eloquent LEFT JOIN WHERE NULL

use Illuminate\Database\Eloquent\Builder;

$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
     $query = $query->where('orders.customer_id', 'NULL') 
});
    $query = $query->get();

How to add chmod permissions to file in Git?

According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index sub-command.

To set the flag, use following command:

git update-index --chmod=+x path/to/file

To remove it, use:

git update-index --chmod=-x path/to/file

Under the hood

While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:

  • 100644 for regular files
  • 100755 for executable ones

You can visualize it using ls-file subcommand, with --stage option:

$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0       .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0       my_executable_script.sh

By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode option to false:

git config core.fileMode false

Troubleshooting

If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:

git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file

Bonus

Starting with Git 2.9, you can stage a file AND set the flag in one command:

git add --chmod=+x path/to/file

React - How to force a function component to render?

The accepted answer is good. Just to make it easier to understand.

Example component:

export default function MyComponent(props) {

    const [updateView, setUpdateView] = useState(0);

    return (
        <>
            <span style={{ display: "none" }}>{updateView}</span>
        </>
    );
}

To force re-rendering call the code below:

setUpdateView((updateView) => ++updateView);

How might I extract the property values of a JavaScript object into an array?

Using the accepted answer and knowing that Object.values() is proposed in ECMAScript 2017 Draft you can extend Object with method:

if(Object.values == null) {
    Object.values = function(obj) {
        var arr, o;
        arr = new Array();
        for(o in obj) { arr.push(obj[o]); }
        return arr;
    }
}

What causes HttpHostConnectException?

A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.

If this is happening intermittently, then the most likely explanations are (IMO):

  • the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
  • there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.

Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.

It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.


1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.

LINQ Orderby Descending Query

You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending

like:

.OrderByDescending(x => x.Delivery.SubmissionDate);

Really, though the first version of your LINQ statement should work. Is t.Delivery.SubmissionDate actually populated with valid dates?

HTTP Error 404 when running Tomcat from Eclipse

Check the server configuration and folders' routes:

  1. Open servers view (Window -> Open view... -> Others... -> Search for 'servers'.

  2. Right click on server (mine is Tomcat v6.0) -> properties -> Click on 'Swicth Location' (check that location's like /servers...

  3. Double click on the server. This will open a new servers page. In the 'Servers Locations' area, check the 'Use Tomcat Installation (takes control of Tomcat Installation)' option.

  4. Restart your server.

  5. Enjoy!

Keyboard shortcut to comment lines in Sublime Text 3

I'm under Linux too. For me, it only works when I press CTRL+SHIFT+/, and it's like a single comment, not a block comment. The reason is to acceed the / character, I have to press SHIFT, if I do not, sublime text detects that I pressed CTRL + :.

Here it is my solution to get back normal preferences. Write in Key Bindings - User :

{ "keys": ["ctrl+:"], "command": "toggle_comment", "args": { "block": false } }, { "keys": ["ctrl+shift+:"], "command": "toggle_comment", "args": { "block": true } }

What's a simple way to get a text input popup dialog box on an iPhone

Building on John Riselvato's answer, to retrieve the string back from the UIAlertView...

alert.addAction(UIAlertAction(title: "Submit", style: UIAlertAction.Style.default) { (action : UIAlertAction) in
            guard let message = alert.textFields?.first?.text else {
                return
            }
            // Text Field Response Handling Here
        })

Adding onClick event dynamically using jQuery

$("#bfCaptchaEntry").click(function(){
    myFunction();
});

Which @NotNull Java annotation should I use?

If you are building your application using Spring Framework I would suggest using javax.validation.constraints.NotNull comming from Beans Validation packaged in following dependency:

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>

The main advantage of this annotation is that Spring provides support for both method parameters and class fields annotated with javax.validation.constraints.NotNull. All you need to do to enable support is:

  1. supply the api jar for beans validation and jar with implementation of validator of jsr-303/jsr-349 annotations (which comes with Hibernate Validator 5.x dependency):

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    
  2. provide MethodValidationPostProcessor to spring's context

      @Configuration
      @ValidationConfig
      public class ValidationConfig implements MyService {
    
            @Bean
            public MethodValidationPostProcessor providePostProcessor() {
                  return new MethodValidationPostProcessor()
            }
      }
    
  3. finally you annotate your classes with Spring's org.springframework.validation.annotation.Validated and validation will be automatically handled by Spring.

Example:

@Service
@Validated
public class MyServiceImpl implements MyService {

  @Override
  public Something doSomething(@NotNull String myParameter) {
        // No need to do something like assert myParameter != null  
  }
}

When you try calling method doSomething and pass null as the parameter value, spring (by means of HibernateValidator) will throw ConstraintViolationException. No need for manuall work here.

You can also validate return values.

Another important benefit of javax.validation.constraints.NotNull comming for Beans Validation Framework is that at the moment it is still developed and new features are planned for new version 2.0.

What about @Nullable? There is nothing like that in Beans Validation 1.1. Well, I could arguee that if you decide to use @NotNull than everything which is NOT annotated with @NonNull is effectively "nullable", so the @Nullable annotation is useless.

What's the difference between window.location and document.location in JavaScript?

According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location rather than document.location.

See: http://www.w3.org/TR/html/browsers.html#dom-location

Activating Anaconda Environment in VsCode

Find a note here: https://code.visualstudio.com/docs/python/environments#_conda-environments

As noted earlier, the Python extension automatically detects existing conda environments provided that the environment contains a Python interpreter. For example, the following command creates a conda environment with the Python 3.4 interpreter and several libraries, which VS Code then shows in the list of available interpreters:

 conda create -n env-01 python=3.4 scipy=0.15.0 astroid babel 

In contrast, if you fail to specify an interpreter, as with conda create --name env-00, the environment won't appear in the list.

In where shall I use isset() and !empty()

isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.

So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:

$var = "";
var_dump(isset($var));

The type comparison tables in PHP’s manual is quite handy for such questions.

isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)

Convert True/False value read from file to boolean

bool('True') and bool('False') always return True because strings 'True' and 'False' are not empty.

To quote a great man (and Python documentation):

5.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].

All other values are considered true — so objects of many types are always true.

The built-in bool function uses the standard truth testing procedure. That's why you're always getting True.

To convert a string to boolean you need to do something like this:

def str_to_bool(s):
    if s == 'True':
         return True
    elif s == 'False':
         return False
    else:
         raise ValueError # evil ValueError that doesn't tell you what the wrong value was

How to change text color of simple list item

I realize this question is a bit old but here's a really simple solution that was missing. You don't need to create a custom ListView or even a custom layout.

Just create an anonymous subclass of ArrayAdapter and override getView(). Let super.getView() handle all the heavy lifting. Since simple_list_item_1 is just a text view you can customize it (e.g. set textColor) and then return it.

Here's an example from one of my apps. I'm displaying a list of recent locations and I want all occurrences of "Current Location" to be blue and the rest white.

ListView listView = (ListView) this.findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MobileMuni.getBookmarkStore().getRecentLocations()) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = (TextView) super.getView(position, convertView, parent);

        String currentLocation = RouteFinderBookmarksActivity.this.getResources().getString(R.string.Current_Location);
        int textColor = textView.getText().toString().equals(currentLocation) ? R.color.holo_blue : R.color.text_color_btn_holo_dark;
        textView.setTextColor(RouteFinderBookmarksActivity.this.getResources().getColor(textColor));

        return textView;
    }
});

Statically rotate font-awesome icons

This works perfectly

<i class="fa fa-power-off text-gray" style="transform: rotate(90deg);"></i>

OnClick in Excel VBA

I don't think so. But you can create a shape object ( or wordart or something similiar ) hook Click event and place the object to position of the specified cell.

How to create a GUID in Excel?

=CONCATENATE(
    DEC2HEX(RANDBETWEEN(0;4294967295);8);"-";
    DEC2HEX(RANDBETWEEN(0;42949);4);"-";
    DEC2HEX(RANDBETWEEN(0;42949);4);"-";
    DEC2HEX(RANDBETWEEN(0;42949);4);"-";
    DEC2HEX(RANDBETWEEN(0;4294967295);8);
    DEC2HEX(RANDBETWEEN(0;42949);4)
)

C compile : collect2: error: ld returned 1 exit status

install this

sudo apt install libgl-dev libglu-dev libglib2.0-dev libsm-dev libxrender-dev libfontconfig1-dev libxext-dev

http://www.qtcentre.org/threads/69625-collect2-error-ld-returned-1-exit-status

builder for HashMap

Since Java 9 Map interface contains:

  • Map.of(k1,v1, k2,v2, ..)
  • Map.ofEntries(Map.entry(k1,v1), Map.entry(k2,v2), ..).

Limitations of those factory methods are that they:

  • can't hold nulls as keys and/or values (if you need to store nulls take a look at other answers)
  • produce immutable maps

If we need mutable map (like HashMap) we can use its copy-constructor and let it copy content of map created via Map.of(..)

Map<Integer, String> map = new HashMap<>( Map.of(1,"a", 2,"b", 3,"c") );

onclick="javascript:history.go(-1)" not working in Chrome

Try this:

<a href="www.mypage.com" onclick="history.go(-1); return false;"> Link </a>

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

How do I ignore ampersands in a SQL script running from SQL Plus?

I had a CASE statement with WHEN column = 'sometext & more text' THEN ....

I replaced it with WHEN column = 'sometext ' || CHR(38) || ' more text' THEN ...

you could also use WHEN column LIKE 'sometext _ more text' THEN ...

(_ is the wildcard for a single character)

How to catch a unique constraint error in a PL/SQL block?

EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         UPDATE

Get User's Current Location / Coordinates

Import library like:

import CoreLocation

set Delegate:

CLLocationManagerDelegate

Take variable like:

var locationManager:CLLocationManager!

On viewDidLoad() write this pretty code:

 locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled(){
        locationManager.startUpdatingLocation()
    }

Write CLLocation delegate methods:

    //MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation :CLLocation = locations[0] as CLLocation

    print("user latitude = \(userLocation.coordinate.latitude)")
    print("user longitude = \(userLocation.coordinate.longitude)")

    self.labelLat.text = "\(userLocation.coordinate.latitude)"
    self.labelLongi.text = "\(userLocation.coordinate.longitude)"

    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
        if (error != nil){
            print("error in reverseGeocode")
        }
        let placemark = placemarks! as [CLPlacemark]
        if placemark.count>0{
            let placemark = placemarks![0]
            print(placemark.locality!)
            print(placemark.administrativeArea!)
            print(placemark.country!)

            self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
        }
    }

}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Error \(error)")
}

Now set permission for access the location, so add these key value into your info.plist file

 <key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>

enter image description here

100% working without any issue. TESTED

How to remove the last element added into the List?

You can use List<T>.RemoveAt method:

rows.RemoveAt(rows.Count -1);

How do I move a redis database from one server to another?

First, create a dump on server A.

A$ redis-cli
127.0.0.1:6379> CONFIG GET dir
1) "dir"
2) "/var/lib/redis/"
127.0.0.1:6379> SAVE
OK

This ensures dump.rdb is completely up-to-date, and shows us where it is stored (/var/lib/redis/dump.rdb in this case). dump.rdb is also periodically written to disk automatically.

Next, copy it to server B:

A$ scp /var/lib/redis/dump.rdb myuser@B:/tmp/dump.rdb

Stop the Redis server on B, copy dump.rdb (ensuring permissions are the same as before), then start.

B$ sudo service redis-server stop
B$ sudo cp /tmp/dump.rdb /var/lib/redis/dump.rdb
B$ sudo chown redis: /var/lib/redis/dump.rdb
B$ sudo service redis-server start

The version of Redis on B must be greater or equal than that of A, or you may hit compatibility issues.

Deprecated meaning?

Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.

How to filter rows in pandas by regex

Thanks for the great answer @user3136169, here is an example of how that might be done also removing NoneType values.

def regex_filter(val):
    if val:
        mo = re.search(regex,val)
        if mo:
            return True
        else:
            return False
    else:
        return False

df_filtered = df[df['col'].apply(regex_filter)]

Also you can also add regex as an arg:

def regex_filter(val,myregex):
    ...

df_filtered = df[df['col'].apply(res_regex_filter,regex=myregex)]

How to select all the columns of a table except one column?

I just wanted to echo @Luann's comment as I use this approach always.

Just right click on the table > Script table as > Select to > New Query window.

You will see the select query. Just take out the column you want to exclude and you have your preferred select query. enter image description here

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

Using the fileProvider is the way to go. But you can use this simple workaround:

WARNING: It will be fixed in next Android release - https://issuetracker.google.com/issues/37122890#comment4

replace:

startActivity(intent);

by

startActivity(Intent.createChooser(intent, "Your title"));

How to emulate GPS location in the Android Emulator?

If you're using Eclipse, go to Window->Open Perspective->DDMS, then type one in Location Controls and hit Send.

Converting ArrayList to HashMap

[edited]

using your comment about productCode (and assuming product code is a String) as reference...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }

Binding a WPF ComboBox to a custom list

You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.

Have you set the DataContext to your ConnectionViewModel object?

I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.

Here is my XAML content:

<Window x:Class="WpfApplication6.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
<Grid>
    <StackPanel>
        <Button Click="Button_Click">asdf</Button>
        <ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
                  DisplayMemberPath="Name"
                  SelectedValuePath="Name"
                  SelectedValue="{Binding Path=PhonebookEntry}" />
    </StackPanel>
</Grid>
</Window>

And here is my code-behind:

namespace WpfApplication6
{

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            ConnectionViewModel vm = new ConnectionViewModel();
            DataContext = vm;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((ConnectionViewModel)DataContext).PhonebookEntry = "test";
        }
    }

    public class PhoneBookEntry
    {
        public string Name { get; set; }

        public PhoneBookEntry(string name)
        {
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

    public class ConnectionViewModel : INotifyPropertyChanged
    {
        public ConnectionViewModel()
        {
            IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
            list.Add(new PhoneBookEntry("test"));
            list.Add(new PhoneBookEntry("test2"));
            _phonebookEntries = new CollectionView(list);
        }

        private readonly CollectionView _phonebookEntries;
        private string _phonebookEntry;

        public CollectionView PhonebookEntries
        {
            get { return _phonebookEntries; }
        }

        public string PhonebookEntry
        {
            get { return _phonebookEntry; }
            set
            {
                if (_phonebookEntry == value) return;
                _phonebookEntry = value;
                OnPropertyChanged("PhonebookEntry");
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.

Maybe there is an issue with the CollectionView? I noticed a warning in the output console:

System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.

Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.

warning: implicit declaration of function

You need to declare the desired function before your main function:

#include <stdio.h>
int yourfunc(void);

int main(void) {

   yourfunc();
 }

Metadata file '.dll' could not be found

If you have a space in your solution name, this will also cause the issue. Removing the space from your solution name, so path doesn't contain %20 will solve this.

Python read next()

When you do : f.readlines() you already read all the file so f.tell() will show you that you are in the end of the file, and doing f.next() will result in a StopIteration error.

Alternative of what you want to do is:

filne = "D:/testtube/testdkanimfilternode.txt"

with open(filne, 'r+') as f:
    for line in f:
        if line.startswith("anim "):
            print f.next() 
            # Or use next(f, '') to return <empty string> instead of raising a  
            # StopIteration if the last line is also a match.
            break

Java generics - ArrayList initialization

The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

ArrayList<A> a = new ArrayList<A>();

Here a is a reference to an instance of a specific type - exactly an array list of As. More explicitly, a is a reference to an array list that will accept As and will produce As. new ArrayList<A>() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

ArrayList<Integer> a = new ArrayList<Number>(); 

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers. It cannot point to an array list of Numbers. That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

ArrayList<Number> a = new ArrayList<Integer>(); 

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers. It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

ArrayList<? extends Object> a= new ArrayList<Object>();

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object. (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

ArrayList<? super Integer> a = new ArrayList<Number>();

Again, a is a reference to a family of types (rather than a single specific type). Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer. However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

ArrayList<ArrayList<?>> a

An array list that holds references to any list that is a member of a family of array lists types.

= new ArrayList<ArrayList<?>>(); // correct

An instance of an array list that holds references to any list that is a member of a family of array lists types.

ArrayList<?> a

An reference to any array list (a member of the family of array list types).

= new ArrayList<?>()

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.


See also How can I add to List<? extends Number> data structures?

python NameError: global name '__file__' is not defined

If you're exec'ing a file via command line, you can use this hack

import traceback

def get_this_filename():
    try:
        raise NotImplementedError("No error")
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        filename = traceback.extract_tb(exc_traceback)[-1].filename
    return filename

This worked for me in the UnrealEnginePython console, calling py.exec myfile.py

PHP - add 1 day to date format mm-dd-yyyy

The format you've used is not recognized by strtotime(). Replace

$date = "04-15-2013";

by

$date = "04/15/2013";

Or if you want to use - then use the following line with the year in front:

$date = "2013-04-15";

How to comment a block in Eclipse?

For JAVA :

Single line comment:

               // this is a single line comment

To comment: Ctrl + Shift + C

To uncomment: Press again Ctrl + Shift + C

Multiple line comment:

         /* .........
            .........
            ......... */ 

First, select all the lines that you want to comment/uncomment then,

To comment: Ctrl + Shift + C

To uncomment: Press again Ctrl + Shift + C

I hope, this will work for you!

How to see my Eclipse version?

I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.

  1. Open Installation Details:

    • Go to Help => About => Installation Details.
    • Or to Help => Install New Software... => click What is already installed? link.
  2. Choose Plug-ins tab => type org.eclipse.platform => check Version column.

  3. You can match version code and version name on https://wiki.eclipse.org/Older_Versions_Of_Eclipse

For example, check out GitEye (Git GUI client) GitEye Installation Details

Or checkout DBBeaver (DB manager):

enter image description here

MySQL DROP all tables, ignoring foreign keys

Drop all the tables from database with a single line from command line:

mysqldump -u [user_name] -p[password] -h [host_name] --add-drop-table --no-data [database_name] | grep ^DROP | mysql -u [user_name] -p[password] -h [host_name] [database_name]

Where [user_name], [password], [host_name] and [database_name] have to be replaced with a real data (user, password, host name, database name).

PHP Remove elements from associative array

for single array Item use reset($item)

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

I had a problem where it did not allow me to insert it even after setting the IDENTITY_INSERT ON.

The problem was that i did not specify the column names and for some reason it did not like it.

INSERT INTO tbl Values(vals)

So basically do the full INSERT INTO tbl(cols) Values(vals)

Should I use window.navigate or document.location in JavaScript?

window.location also affects to the frame,

the best form i found is:

parent.window.location.href

And the worse is:

parent.document.URL 

I did a massive browser test, and some rare IE with several plugins get undefined with the second form.

What is :: (double colon) in Python when subscripting sequences?

TL;DR

This visual example will show you how to a neatly select elements in a NumPy Matrix (2 dimensional array) in a pretty entertaining way (I promise). Step 2 below illustrate the usage of that "double colons" :: in question.

(Caution: this is a NumPy array specific example with the aim of illustrating the a use case of "double colons" :: for jumping of elements in multiple axes. This example does not cover native Python data structures like List).

One concrete example to rule them all...

Say we have a NumPy matrix that looks like this:

In [1]: import numpy as np

In [2]: X = np.arange(100).reshape(10,10)

In [3]: X
Out[3]:
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
       [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
       [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
       [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
       [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])

Say for some reason, your boss wants you to select the following elements:

enter image description here

"But How???"... Read on! (We can do this in a 2-step approach)

Step 1 - Obtain subset

Specify the "start index" and "end index" in both row-wise and column-wise directions.

enter image description here

In code:

In [5]: X2 = X[2:9,3:8]

In [6]: X2
Out[6]:
array([[23, 24, 25, 26, 27],
       [33, 34, 35, 36, 37],
       [43, 44, 45, 46, 47],
       [53, 54, 55, 56, 57],
       [63, 64, 65, 66, 67],
       [73, 74, 75, 76, 77],
       [83, 84, 85, 86, 87]])

Notice now we've just obtained our subset, with the use of simple start and end indexing technique. Next up, how to do that "jumping"... (read on!)

Step 2 - Select elements (with the "jump step" argument)

We can now specify the "jump steps" in both row-wise and column-wise directions (to select elements in a "jumping" way) like this:

enter image description here

In code (note the double colons):

In [7]: X3 = X2[::3, ::2]

In [8]: X3
Out[8]:
array([[23, 25, 27],
       [53, 55, 57],
       [83, 85, 87]])

We have just selected all the elements as required! :)

 Consolidate Step 1 (start and end) and Step 2 ("jumping")

Now we know the concept, we can easily combine step 1 and step 2 into one consolidated step - for compactness:

In [9]: X4 = X[2:9,3:8][::3,::2]

    In [10]: X4
    Out[10]:
    array([[23, 25, 27],
           [53, 55, 57],
           [83, 85, 87]])

Done!

How to convert a byte to its binary string representation

Use Integer#toBinaryString():

byte b1 = (byte) 129;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
System.out.println(s1); // 10000001

byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println(s2); // 00000010

DEMO.

PHP - Check if the page run on Mobile or Desktop browser

I used Robert Lee`s answer and it works great! Just writing down the complete function i'm using:

function isMobileDevice(){
    $aMobileUA = array(
        '/iphone/i' => 'iPhone', 
        '/ipod/i' => 'iPod', 
        '/ipad/i' => 'iPad', 
        '/android/i' => 'Android', 
        '/blackberry/i' => 'BlackBerry', 
        '/webos/i' => 'Mobile'
    );

    //Return true if Mobile User Agent is detected
    foreach($aMobileUA as $sMobileKey => $sMobileOS){
        if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){
            return true;
        }
    }
    //Otherwise return false..  
    return false;
}

How to specify Memory & CPU limit in docker compose version 3

deploy:
  resources:
    limits:
      cpus: '0.001'
      memory: 50M
    reservations:
      cpus: '0.0001'
      memory: 20M

More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources

In you specific case:

version: "3"
services:
  node:
    image: USER/Your-Pre-Built-Image
    environment:
      - VIRTUAL_HOST=localhost
    volumes:
      - logs:/app/out/
    command: ["npm","start"]
    cap_drop:
      - NET_ADMIN
      - SYS_ADMIN
    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M
        reservations:
          cpus: '0.0001'
          memory: 20M

volumes:
  - logs

networks:
  default:
    driver: overlay

Note:

  • Expose is not necessary, it will be exposed per default on your stack network.
  • Images have to be pre-built. Build within v3 is not possible
  • "Restart" is also deprecated. You can use restart under deploy with on-failure action
  • You can use a standalone one node "swarm", v3 most improvements (if not all) are for swarm

Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:

ports:
  - 80:80

Laravel migration: unique key is too long, even if specified

If someone having this problem even after doing, above mentioned changes. For an example, in my case I did below changes,

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
  /**
   * Register any application services.
   *
   * @return void
   */
   public function register()
   {
      //
   }

   public function boot()
   {
     Schema::defaultStringLength(191);
   }
}

But it wouldn't work right away for two reasons. One is if you are using lumen instead of laravel, you may have to uncomment this line in your app.php file first.

$app->register(App\Providers\AppServiceProvider::class);

And then you have to create the migration script again with the artisan command,

php artisan make:migration <your_table_name>

Since now only the changes you made to ServiceProvider will work.

rebase in progress. Cannot commit. How to proceed or stop (abort)?

Mine was an error that popped up from BitBucket. Ran git am --skip fixed it.

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

This is the full step-by-step procedure to resync a master-slave replication from scratch:

At the master:

RESET MASTER;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;

And copy the values of the result of the last command somewhere.

Without closing the connection to the client (because it would release the read lock) issue the command to get a dump of the master:

mysqldump -u root -p --all-databases > /a/path/mysqldump.sql

Now you can release the lock, even if the dump hasn't ended yet. To do it, perform the following command in the MySQL client:

UNLOCK TABLES;

Now copy the dump file to the slave using scp or your preferred tool.

At the slave:

Open a connection to mysql and type:

STOP SLAVE;

Load master's data dump with this console command:

mysql -uroot -p < mysqldump.sql

Sync slave and master logs:

RESET SLAVE;
CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=98;

Where the values of the above fields are the ones you copied before.

Finally, type:

START SLAVE;

To check that everything is working again, after typing:

SHOW SLAVE STATUS;

you should see:

Slave_IO_Running: Yes
Slave_SQL_Running: Yes

That's it!

How to use the priority queue STL for objects?

You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement

bool operator<(const Person& lhs, const Person& rhs); 

it should work without any further changes. The implementation could be

bool operator<(const Person& lhs, const Person& rhs)
{
  return lhs.age < rhs.age;
}

If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,

struct LessThanByAge
{
  bool operator()(const Person& lhs, const Person& rhs) const
  {
    return lhs.age < rhs.age;
  }
};

then instantiate the queue like this:

std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;

Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

Like it's written up there, you forget to type #include <sstream>

#include <sstream>
using namespace std;

QString Stats_Manager::convertInt(int num)
{
   stringstream ss;
   ss << num;
   return ss.str();
}

You can also use some other ways to convert int to string, like

char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

check this!

How can I use JQuery to post JSON data?

Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.

var DoPost = function(url, body) {
    try {
        body = JSON.stringify(body);
    } catch (error) {
        return reject(error);
    }
    return new Promise((resolve, reject) => {
        $.ajax({
                type: 'POST',
                url: url,
                data: body,
                contentType: "application/json",
                dataType: 'json'
            })
            .done(function(data) {
                return resolve(data);
            })
            .fail(function(error) {
                console.error(error);
                return reject(error);
            })
            .always(function() {
                // called after done or fail
            });
    });
}

Linux: command to open URL in default browser

On distributions that come with the open command,

$ open http://www.google.com

How to create a simple map using JavaScript/JQuery

Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

//map[myKey1] == get(myKey1);

How to remove newlines from beginning and end of a string?

For anyone else looking for answer to the question when dealing with different linebreaks:

string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", "");          // Java 8

This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

This passes these tests:

// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));

// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));

// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));

Allow Access-Control-Allow-Origin header using HTML5 fetch API

This worked for me :

npm install -g local-cors-proxy

API endpoint that we want to request that has CORS issues:

https://www.yourdomain.com/test/list

Start Proxy:

lcp --proxyUrl https://www.yourdomain.com

 Proxy Active 

 Proxy Url: http://www.yourdomain.com:28080
 Proxy Partial: proxy
 PORT: 8010

Then in your client code, new API endpoint:

http://localhost:8010/proxy/test/list

End result will be a request to https://www.yourdomain.ie/test/list without the CORS issues!

How to change the name of a Django app?

In many cases, I believe @allcaps's answer works well.

However, sometimes it is necessary to actually rename an app, e.g. to improve code readability or prevent confusion.

Most of the other answers involve either manual database manipulation or tinkering with existing migrations, which I do not like very much.

As an alternative, I like to create a new app with the desired name, copy everything over, make sure it works, then remove the original app:

  1. Start a new app with the desired name, and copy all code from the original app into that. Make sure you fix the namespaced stuff, in the newly copied code, to match the new app name.

  2. makemigrations and migrate

  3. Create a data migration that copies the relevant data from the original app's tables into the new app's tables, and migrate again.

At this point, everything still works, because the original app and its data are still in place.

  1. Now you can refactor all the dependent code, so it only makes use of the new app. See other answers for examples of what to look out for.

  2. Once you are certain that everything works, you can remove the original app.

This has the advantage that every step uses the normal Django migration mechanism, without manual database manipulation, and we can track everything in source control. In addition, we keep the original app and its data in place until we are sure everything works.

XAMPP permissions on Mac OS X?

This Solved WordPress Filesystem Permissions in Bitnami XAMPP

By changing the file permissions in apps/wordpress folder mounted on MAC XAMPP-VM shown in the below screenshot.

enter image description here

sudo chown -R bitnami:daemon TARGET # [ Replace "TARGET" with your file/folder path ]
find TARGET -type d -print0 | xargs -0 chmod 775
find TARGET -type f -print0 | xargs -0 chmod 664
chmod 640 TARGET/wp-config.php

Source: bitnami

TARGET - Replace placeholder for your mounted filesystem wordpress path eg: '1.1.1.1/lampp/apps/wordpress'

Now you can edit your themes in VS-Code or any developer editor of your choice.

NOTE: This should be done only in your development environment. Production build permissions are different & above doesn't apply

Difference between no-cache and must-revalidate

I believe that must-revalidate means :

Once the cache expires, refuse to return stale responses to the user even if they say that stale responses are acceptable.

Whereas no-cache implies :

must-revalidate plus the fact the response becomes stale right away.

If a response is cacheable for 10 seconds, then must-revalidate kicks in after 10 seconds, whereas no-cache implies must-revalidate after 0 seconds.

At least, that's my interpretation.

Markdown `native` text alignment

I was trying to center an image and none of the techniques suggested in answers here worked. A regular HTML <img> with inline CSS worked for me...

<img style="display: block; margin: auto;" alt="photo" src="{{ site.baseurl }}/images/image.jpg">

This is for a Jekyll blog hosted on GitHub

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

I tried doing several ways for removing duplicates from a list of java objects
Some of them are
1. Override equals and hashCode methods and Converting the list to a set by passing the list to the set class constructor and do remove and add all
2. Run 2 pointers and remove the duplicates manually by running 2 for loops one inside the other like we used to do in C language for arrays
3.Write a anonymous Comparator class for the bean and do a Collections.sort and then run 2 pointers to remove in forward direction.



And more over my requirement was to remove almost 1 million duplicates from almost 5 million objects.
So after so many trials I ended up with third option which I feel is the most efficient and effective way and it turned out to be evaluating within seconds where as other 2 options are almost taking 10 to 15 mins.
First and Second options are very ineffective because when my objects increase the time taken to remove the duplicates increase in exponential way.

So Finally third option is the best.

Check if inputs form are empty jQuery

var empty = true;
$('input[type="text"]').each(function() {
   if ($(this).val() != "") {
      empty = false;
      return false;
   }
});

This should look all the input and set the empty var to false, if at least one is not empty.

EDIT:

To match the OP edit request, this can be used to filter input based on name substring.

$('input[name*="denominationcomune_"]').each(...

How to get access to raw resources that I put in res folder?

This worked for for me: getResources().openRawResource(R.raw.certificate)

Invalid attempt to read when no data is present

I was having 2 values which could contain null values.

while(dr.Read())
 {
    Id = dr["Id"] as int? ?? default(int?);
    Alt =  dr["Alt"].ToString() as string ?? default(string);
    Name = dr["Name"].ToString()
 }

resolved the issue

Summing elements in a list

You can also use reduce method:

>>> myList = [3, 5, 4, 9]
>>> myTotal = reduce(lambda x,y: x+y, myList)
>>> myTotal
21

Furthermore, you can modify the lambda function to do other operations on your list.

Electron: jQuery is not defined

Just install Jquery with following command.

npm install --save jquery

After that Please put belew line in js file which you want to use Jquery

let $ = require('jquery')

ToList()-- does it create a new list?

ToList will always create a new list, which will not reflect any subsequent changes to the collection.

However, it will reflect changes to the objects themselves (Unless they're mutable structs).

In other words, if you replace an object in the original list with a different object, the ToList will still contain the first object.
However, if you modify one of the objects in the original list, the ToList will still contain the same (modified) object.

Changing default encoding of Python?

This is a quick hack for anyone who is (1) On a Windows platform (2) running Python 2.7 and (3) annoyed because a nice piece of software (i.e., not written by you so not immediately a candidate for encode/decode printing maneuvers) won't display the "pretty unicode characters" in the IDLE environment (Pythonwin prints unicode fine), For example, the neat First Order Logic symbols that Stephan Boyer uses in the output from his pedagogic prover at First Order Logic Prover.

I didn't like the idea of forcing a sys reload and I couldn't get the system to cooperate with setting environment variables like PYTHONIOENCODING (tried direct Windows environment variable and also dropping that in a sitecustomize.py in site-packages as a one liner ='utf-8').

So, if you are willing to hack your way to success, go to your IDLE directory, typically: "C:\Python27\Lib\idlelib" Locate the file IOBinding.py. Make a copy of that file and store it somewhere else so you can revert to original behavior when you choose. Open the file in the idlelib with an editor (e.g., IDLE). Go to this code area:

# Encoding for file names
filesystemencoding = sys.getfilesystemencoding()

encoding = "ascii"
if sys.platform == 'win32':
    # On Windows, we could use "mbcs". However, to give the user
    # a portable encoding name, we need to find the code page 
    try:
        # --> 6/5/17 hack to force IDLE to display utf-8 rather than cp1252
        # --> encoding = locale.getdefaultlocale()[1]
        encoding = 'utf-8'
        codecs.lookup(encoding)
    except LookupError:
        pass

In other words, comment out the original code line following the 'try' that was making the encoding variable equal to locale.getdefaultlocale (because that will give you cp1252 which you don't want) and instead brute force it to 'utf-8' (by adding the line 'encoding = 'utf-8' as shown).

I believe this only affects IDLE display to stdout and not the encoding used for file names etc. (that is obtained in the filesystemencoding prior). If you have a problem with any other code you run in IDLE later, just replace the IOBinding.py file with the original unmodified file.

What happened to Lodash _.pluck?

There isn't a need for _.map or _.pluck since ES6 has taken off.

Here's an alternative using ES6 JavaScript:

clips.map(clip => clip.id)

The module was expected to contain an assembly manifest

I found that, I am using a different InstallUtil from my target .NET Framework. I am building a .NET Framework 4.5, meanwhile the error occured if I am using the .NET Framework 2.0 release. Having use the right InstallUtil for my target .NET Framework, solved this problem!

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

How to replace a whole line with sed?

You can also use sed's change line to accomplish this:

sed -i "/aaa=/c\aaa=xxx" your_file_here

This will go through and find any lines that pass the aaa= test, which means that the line contains the letters aaa=. Then it replaces the entire line with aaa=xxx. You can add a ^ at the beginning of the test to make sure you only get the lines that start with aaa= but that's up to you.

Replacing from match to end-of-line

This should do what you want:

sed 's/two.*/BLAH/'

$ echo "   one  two  three  five
>    four two  five five six
>    six  one  two seven four" | sed 's/two.*/BLAH/'
   one  BLAH
   four BLAH
   six  one  BLAH

The $ is unnecessary because the .* will finish at the end of the line anyways, and the g at the end is unnecessary because your first match will be the first two to the end of the line.

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

I realise that WayneM has stated he knows that money is specific to SQL Server. However, he is asking if there are any reasons to use money over decimal or vice versa and I think one obvious reason still ought to be stated and that is using decimal means it's one less thing to worry about if you ever have to change your DBMS - which can happen.

Make your systems as flexible as possible!

Binding multiple events to a listener (without JQuery)?

ES2015:

let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));

What is the difference between map and flatMap and a good use case for each?

The difference can be seen from below sample pyspark code:

rdd = sc.parallelize([2, 3, 4])
rdd.flatMap(lambda x: range(1, x)).collect()
Output:
[1, 1, 2, 1, 2, 3]


rdd.map(lambda x: range(1, x)).collect()
Output:
[[1], [1, 2], [1, 2, 3]]

How to change the icon of .bat file programmatically?

You can just create a shortcut and then right click on it -> properties -> change icon, and just browse for your desired icon. Hope this help.

To set an icon of a shortcut programmatically, see this article using SetIconLocation:

How Can I Change the Icon for an Existing Shortcut?:

https://devblogs.microsoft.com/scripting/how-can-i-change-the-icon-for-an-existing-shortcut/

Const DESKTOP = &H10&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(DESKTOP)
Set objFolderItem = objFolder.ParseName("Test Shortcut.lnk")
Set objShortcut = objFolderItem.GetLink
objShortcut.SetIconLocation "C:\Windows\System32\SHELL32.dll", 13
objShortcut.Save

What difference is there between WebClient and HTTPWebRequest classes in .NET?

Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.

Workaround for that problem is here https://stackoverflow.com/a/3052637/1303422

Unable to import path from django.urls

Use url instead of path.

from django.conf.urls import url

urlpatterns = [
    url('', views.homepageview, name='home')
]

How to grant remote access to MySQL for a whole subnet?

It looks like you can also use a netmask, e.g.

GRANT ... TO 'user'@'192.168.0.0/255.255.255.0' IDENTIFIED BY ...

What is the size of a pointer?

On 32-bit machine sizeof pointer is 32 bits ( 4 bytes), while on 64 bit machine it's 8 byte. Regardless of what data type they are pointing to, they have fixed size.

Changing MongoDB data store directory

In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)

This is a bit of a hack, but adding these to the script made it start correctly:

add:

DBDIR=/database/mongodb

change:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}

to:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}

In Objective-C, how do I test the object type?

You can make use of the following code incase you want to check the types of primitive data types.

// Returns 0 if the object type is equal to double
strcmp([myNumber objCType], @encode(double)) 

How to change the window title of a MATLAB plotting figure?

It can also be done this way:

figure(xx);
set(gcf, 'name', 'Name goes here')

gcf gets the current figure handle.

What is the 'override' keyword in C++ used for?

The override keyword serves two purposes:

  1. It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."
  2. The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.

To explain the latter:

class base
{
  public:
    virtual int foo(float x) = 0; 
};


class derived: public base
{
   public:
     int foo(float x) override { ... } // OK
}

class derived2: public base
{
   public:
     int foo(int x) override { ... } // ERROR
};

In derived2 the compiler will issue an error for "changing the type". Without override, at most the compiler would give a warning for "you are hiding virtual method by same name".

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

TypeError: 'module' object is not callable

Short answer: You are calling a file/directory as a function instead of real function

Read on:

This kind of error happens when you import module thinking it as function and call it. So in python module is a .py file. Packages(directories) can also be considered as modules. Let's say I have a create.py file. In that file I have a function like this:

#inside create.py
def create():
  pass

Now, in another code file if I do like this:

#inside main.py file
import create
create() #here create refers to create.py , so create.create() would work here

It gives this error as am calling the create.py file as a function. so I gotta do this:

from create import create
create() #now it works.

Hope that helps! Happy Coding!

POST an array from an HTML form without javascript

check this one out.

<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">

<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">

<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">

<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">

it should end up like this in the $_POST[] array (PHP format for easy visualization)

$_POST[] = array(
    'firstname'=>'value',
    'lastname'=>'value',
    'email'=>'value',
    'address'=>'value',
    'tree' => array(
        'tree1'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree2'=>array(
            'fruit'=>'value',
            'height'=>'value'
        ),
        'tree3'=>array(
            'fruit'=>'value',
            'height'=>'value'
        )
    )
)

HTML - Display image after selecting filename

Here You Go:

HTML

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

Script:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

Live Demo

RAW POST using cURL in PHP

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

Returning http status code from Web Api controller

public HttpResponseMessage Post(Article article)
{
    HttpResponseMessage response = Request.CreateResponse<Article>(HttpStatusCode.Created, article);

    string uriToTheCreatedItem = Url.Route(null, new { id = article.Id });
    response.Headers.Location = new Uri(Request.RequestUri, uriToTheCreatedItem);

    return response;
}

Android screen size HDPI, LDPI, MDPI

The documentation is quite sketchy as far as definitive resolutions go. After some research, here's the solution I came to: Android splash screen image sizes to fit all devices

It's basically guided towards splash screens, but it's perfectly applicable to images that should occupy full screen.

Simple dictionary in C++

Until I was really concerned about performance, I would use a function, that takes a base and returns its match:

char base_pair(char base)
{
    switch(base) {
        case 'T': return 'A';
        ... etc
        default: // handle error
    }
}

If I was concerned about performance, I would define a base as one fourth of a byte. 0 would represent A, 1 would represent G, 2 would represent C, and 3 would represent T. Then I would pack 4 bases into a byte, and to get their pairs, I would simply take the complement.

How can I extract a good quality JPEG image from a video file with ffmpeg?

Output the images in a lossless format such as PNG:

ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png

Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).

I have since found that -vsync 0 is simpler than -r 10 because it avoids needing to know the frame rate.

This is something like what I currently use:

mkdir stills
ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png

To extract only the key frames (which are likely to be of higher quality post-edit):

ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png

Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.

It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1 and outputting as JPEG directly from ffmpeg.

Using app.config in .Net Core

To get started with dotnet core, SqlServer and EF core the below DBContextOptionsBuilder would sufice and you do not need to create App.config file. Do not forget to change the sever address and database name in the below code.

protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=TestDB;Trusted_Connection=True;");

To use the EF core SqlServer provider and compile the above code install the EF SqlServer package

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

After compilation before running the code do the following for the first time

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update

To run the code

dotnet run

How to check whether an array is empty using PHP?

Some decent answers, but just thought I'd expand a bit to explain more clearly when PHP determines if an array is empty.


Main Notes:

An array with a key (or keys) will be determined as NOT empty by PHP.

As array values need keys to exist, having values or not in an array doesn't determine if it's empty, only if there are no keys (AND therefore no values).

So checking an array with empty() doesn't simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.


So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name="array[]").
A non empty array will be produced for each field as there will be auto incremented key values for each form field's array.

Take these arrays for example:

/* Assigning some arrays */

// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");

// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";

// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';

If you echo out the array keys and values for the above arrays, you get the following:

ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]

ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]

ARRAY THREE:
[0] => []
[1] => []

And testing the above arrays with empty() returns the following results:

ARRAY ONE:
$ArrayOne is not empty

ARRAY TWO:
$ArrayTwo is not empty

ARRAY THREE:
$ArrayThree is not empty

An array will always be empty when you assign an array but don't use it thereafter, such as:

$ArrayFour = array();

This will be empty, ie PHP will return TRUE when using if empty() on the above.

So if your array has keys - either by eg a form's input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty().

In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.

However it is not the best method if you simply need to know "if values exist" returns TRUE or FALSE. There are various methods to determine if an array has any values when it's know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).


Here's an approach which uses very little code to check if an array has values:

Using array_filter():
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

$EmptyTestArray = array_filter($ArrayOne);

if (!empty($EmptyTestArray))
  {
    // do some tests on the values in $ArrayOne
  }
else
  {
    // Likely not to need an else, 
    // but could return message to user "you entered nothing" etc etc
  }

Running array_filter() on all three example arrays (created in the first code block in this answer) results in the following:

ARRAY ONE:
$arrayone is not empty

ARRAY TWO:
$arraytwo is not empty

ARRAY THREE:
$arraythree is empty

So when there are no values, whether there are keys or not, using array_filter() to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don't need to loop through it for any other reason, then this is the simplest in terms of code needed.


I'm not experienced in checking overheads, but it would be good to know the differences between using array_filter() and foreach checking if a value is found.

Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.

Datepicker: How to popup datepicker when click on edittext

editText1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DatePickerDialog.OnDateSetListener dpd = new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                                      int dayOfMonth) {

                    int s = monthOfYear + 1;
                    String a = dayOfMonth + "/" + s + "/" + year;
                    editText1.setText(a);
                }
            };

            Time date = new Time();
            DatePickerDialog d = new DatePickerDialog(UpdateStore.this, dpd, date.year, date.month, date.monthDay);
            d.show();

        }
    });

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

SyntaxError: Unexpected token function - Async Await Nodejs

node v6.6.0

If you just use in development. You can do this:

npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev

the package.json would be like this:

"devDependencies": {
   "babel-cli": "^6.18.0",
   "babel-plugin-transform-async-to-generator": "^6.16.0",
   "babel-polyfill": "^6.20.0"
}

create .babelrc file and write this:

{
  "plugins": ["transform-async-to-generator"]
}

and then, run your async/await script like this:

./node_modules/.bin/babel-node script.js

How to correctly dismiss a DialogFragment?

You should dismiss you Dialog in onPause() so override it.

Also before dismissing you can check for null and is showing like below snippet:

@Override
protected void onPause() {
    super.onPause();
    if (dialog != null && dialog.isShowing()) {
        dialog.dismiss();
    }
}

What is ADT? (Abstract Data Type)

Before defining abstract data types, let us considers the different view of system-defined data types. We all know that by default all primitive data types (int, float, etc.) support basic operations such as addition and subtraction. The system provides the implementations for the primitive data types. For user-defined data types, we also need to define operations. The implementation for these operations can be done when we want to actually use them. That means in general, user-defined data types are defined along with their operations.

To simplify the process of solving problems, we combine the data structures with their operations and we call this "Abstract Data Type". (ADT's).

Commonly used ADT'S include: Linked List, Stacks, Queues, Binary Tree, Dictionaries, Disjoint Sets (Union and find), Hash Tables and many others.

ADT's consist of two types:

1. Declaration of data.

2. Declaration of operation.

Add to integers in a list

fooList = [1,3,348,2]
fooList.append(3)
fooList.append(2734)
print(fooList) # [1,3,348,2,3,2734]

How to split a long array into smaller arrays, with JavaScript

More compact:

_x000D_
_x000D_
const chunk = (xs, size) =>_x000D_
  xs.map((_, i) =>_x000D_
    (i % size === 0 ? xs.slice(i, i + size) : null)).filter(Boolean);_x000D_
    _x000D_
// Usage:_x000D_
const sampleArray = new Array(33).fill(undefined).map((_, i) => i);_x000D_
_x000D_
console.log(chunk(sampleArray, 5));
_x000D_
_x000D_
_x000D_

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

For those who need the input file to open directly the camera, you just have to declare capture parameter to the input file, like this :

<input type="file" accept="image/*" capture>

PHP: Split string into array, like explode with no delimiter

$array = str_split("$string");

will actuall work pretty fine, BUT if you want to preserve the special characters in that string, and you want to do some manipulation with them, THAN I would use

do {
    $array[] = mb_substr( $string, 0, 1, 'utf-8' );
} while ( $string = mb_substr( $string, 1, mb_strlen( $string ), 'utf-8' ) );

because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters

How to bind Close command to a button

One option that I've found to work is to set this function up as a Behavior.

The Behavior:

    public class WindowCloseBehavior : Behavior<Window>
{
    public bool Close
    {
        get { return (bool) GetValue(CloseTriggerProperty); }
        set { SetValue(CloseTriggerProperty, value); }
    }

    public static readonly DependencyProperty CloseTriggerProperty =
        DependencyProperty.Register("Close", typeof(bool), typeof(WindowCloseBehavior),
            new PropertyMetadata(false, OnCloseTriggerChanged));

    private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = d as WindowCloseBehavior;

        if (behavior != null)
        {
            behavior.OnCloseTriggerChanged();
        }
    }

    private void OnCloseTriggerChanged()
    {
        // when closetrigger is true, close the window
        if (this.Close)
        {
            this.AssociatedObject.Close();
        }
    }
}

On the XAML Window, you set up a reference to it and bind the Behavior's Close property to a Boolean "Close" property on your ViewModel:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<i:Interaction.Behaviors>
    <behavior:WindowCloseBehavior Close="{Binding Close}" />
</i:Interaction.Behaviors>

So, from the View assign an ICommand to change the Close property on the ViewModel which is bound to the Behavior's Close property. When the PropertyChanged event is fired the Behavior fires the OnCloseTriggerChanged event and closes the AssociatedObject... which is the Window.

Variables declared outside function

The local names for a function are decided when the function is defined:

>>> x = 1
>>> def inc():
...     x += 5
...     
>>> inc.__code__.co_varnames
('x',)

In this case, x exists in the local namespace. Execution of x += 5 requires a pre-existing value for x (for integers, it's like x = x + 5), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError is named as such.

Compare the other version, where x is not a local variable, so it can be resolved at the global scope instead:

>>> def incg():
...    print(x)
...    
>>> incg.__code__.co_varnames
()

Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

Troubleshooting "Illegal mix of collations" error in mysql

I had a similar problem, was trying to use the FIND_IN_SET procedure with a string variable.

SET @my_var = 'string1,string2';
SELECT * from my_table WHERE FIND_IN_SET(column_name,@my_var);

and was receiving the error

Error Code: 1267. Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation 'find_in_set'

Short answer:

No need to change any collation_YYYY variables, just add the correct collation next to your variable declaration, i.e.

SET @my_var = 'string1,string2' COLLATE utf8_unicode_ci;
SELECT * from my_table WHERE FIND_IN_SET(column_name,@my_var);

Long answer:

I first checked the collation variables:

mysql> SHOW VARIABLES LIKE 'collation%';
    +----------------------+-----------------+
    | Variable_name        | Value           |
    +----------------------+-----------------+
    | collation_connection | utf8_general_ci |
    +----------------------+-----------------+
    | collation_database   | utf8_general_ci |
    +----------------------+-----------------+
    | collation_server     | utf8_general_ci |
    +----------------------+-----------------+

Then I checked the table collation:

mysql> SHOW CREATE TABLE my_table;

CREATE TABLE `my_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `column_name` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=125 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

This means that my variable was configured with the default collation of utf8_general_ci while my table was configured as utf8_unicode_ci.

By adding the COLLATE command next to the variable declaration, the variable collation matched the collation configured for the table.

Wait for shell command to complete

Add the following Sub:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
VBA.CreateObject("WScript.Shell").Run Cmd, WindowStyle, True
End Sub

If you add a reference to C:\Windows\system32\wshom.ocx you can also use:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
Static wsh As New WshShell
wsh.Run Cmd, WindowStyle, True
End Sub

This version should be more efficient.

Cleaning `Inf` values from an R dataframe

Here is a dplyr/tidyverse solution using the na_if() function:

dat %>% mutate_if(is.numeric, list(~na_if(., Inf)))

Note that this only replaces positive infinity with NA. Need to repeat if negative infinity values also need to be replaced.

dat %>% mutate_if(is.numeric, list(~na_if(., Inf))) %>% 
  mutate_if(is.numeric, list(~na_if(., -Inf)))

API Gateway CORS: no 'Access-Control-Allow-Origin' header

For Googlers:

Here is why:

  • Simple request, or, GET/POST with no cookies do not trigger preflight
  • When you configure CORS for a path, API Gateway will only create an OPTIONS method for that path, then send Allow-Origin headers using mock responses when user calls OPTIONS, but GET / POST will not get Allow-Origin automatically
  • If you try to send simple requests with CORS mode on, you will get an error because that response has no Allow-Origin header
  • You may adhere to best practice, simple requests are not meant to send response to user, send authentication/cookie along with your requests to make it "not simple" and preflight will trigger
  • Still, you will have to send CORS headers by yourself for the request following OPTIONS

To sum it up:

  • Only harmless OPTIONS will be generated by API Gateway automatically
  • OPTIONS are only used by browser as a precautious measure to check possibility of CORS on a path
  • Whether CORS is accepted depend on the actual method e.g. GET / POST
  • You have to manually send appropriate headers in your response

Clear the cache in JavaScript

window.parent.caches.delete("call")

close and open the browser after executing the code in console.

Get class list for element with jQuery

Try This. This will get you the names of all the classes from all the elements of document.

$(document).ready(function() {
var currentHtml="";
$('*').each(function() {
    if ($(this).hasClass('') === false) {
        var class_name = $(this).attr('class');
        if (class_name.match(/\s/g)){
            var newClasses= class_name.split(' ');
            for (var i = 0; i <= newClasses.length - 1; i++) {
                if (currentHtml.indexOf(newClasses[i]) <0) {
                    currentHtml += "."+newClasses[i]+"<br>{<br><br>}<br>"
                }
            }
        }
        else
        {
            if (currentHtml.indexOf(class_name) <0) {
                currentHtml += "."+class_name+"<br>{<br><br>}<br>"
            }
        }
    }
    else
    {
        console.log("none");
    }
});
$("#Test").html(currentHtml);

});

Here is the working example: https://jsfiddle.net/raju_sumit/2xu1ujoy/3/

Upgrading Node.js to latest version

just try this on your terminal :

nvm install node --reinstall-packages-from=node

it should do the trick.

later, run node --version to check the version that you have.

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

Reading output of a command into an array in Bash

Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;

my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length

Or, you can iterate over this array by adding the following script:

for element in "${my_array[@]}"
do
   echo "${element}"
done

Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).

.gitignore for Visual Studio Projects and Solutions

I prefer to exclude things on an as-needed basis. You don't want to shotgun exclude everything with the string "bin" or "obj" in the name. At least be sure to follow those with a slash.

Here's what I start with on a VS2010 project:

bin/
obj/
*.suo
*.user

And only because I use ReSharper, also this:

_ReSharper*

How to count number of unique values of a field in a tab-delimited text file?

Here is a bash script that fully answers the (revised) original question. That is, given any .tsv file, it provides the synopsis for each of the columns in turn. Apart from bash itself, it only uses standard *ix/Mac tools: sed tr wc cut sort uniq.

#!/bin/bash
# Syntax: $0 filename   
# The input is assumed to be a .tsv file

FILE="$1"

cols=$(sed -n 1p $FILE | tr -cd '\t' | wc -c)
cols=$((cols + 2 ))
i=0
for ((i=1; i < $cols; i++))
do
  echo Column $i ::
  cut -f $i < "$FILE" | sort | uniq -c
  echo
done

"Series objects are mutable and cannot be hashed" error

gene_name = no_headers.iloc[1:,[1]]

This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:

gene_name[x]

you now have a Series object with a single value. You can't hash the Series.

The solution is to create Series from the start.

gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]

Also, where you have orph_dict[gene_name[x]] =+ 1, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1 to increment the counter.

Enable Hibernate logging

Hibernate logging has to be also enabled in hibernate configuration.

Add lines

hibernate.show_sql=true
hibernate.format_sql=true

either to

server\default\deployers\ejb3.deployer\META-INF\jpa-deployers-jboss-beans.xml

or to application's persistence.xml in <persistence-unit><properties> tag.

Anyway hibernate logging won't include (in useful form) info on actual prepared statements' parameters.

There is an alternative way of using log4jdbc for any kind of sql logging.

The above answer assumes that you run the code that uses hibernate on JBoss, not in IDE. In this case you should configure logging also on JBoss in server\default\deploy\jboss-logging.xml, not in local IDE classpath.

Note that JBoss 6 doesn't use log4j by default. So adding log4j.properties to ear won't help. Just try to add to jboss-logging.xml:

   <logger category="org.hibernate">
     <level name="DEBUG"/>
   </logger>

Then change threshold for root logger. See SLF4J logger.debug() does not get logged in JBoss 6.

If you manage to debug hibernate queries right from IDE (without deployment), then you should have log4j.properties, log4j, slf4j-api and slf4j-log4j12 jars on classpath. See http://www.mkyong.com/hibernate/how-to-configure-log4j-in-hibernate-project/.

What is a wrapper class?

There are several design patterns that can be called wrapper classes.

See my answer to "How do the Proxy, Decorator, Adaptor, and Bridge Patterns differ?"

MongoDB: How to query for records where field is null or not set?

You can also try this:

db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()

How to create a box when mouse over text in pure CSS?

This is a small tweak on the other answers. If you have nested divs you can include more exciting content such as H1s in your popup.

CSS

div.appear {
    width: 250px; 
    border: #000 2px solid;
    background:#F8F8F8;
    position: relative;
    top: 5px;
    left:15px;
    display:none;
    padding: 0 20px 20px 20px;
    z-index: 1000000;
}
div.hover  {
    cursor:pointer;
    width: 5px;
}
div.hover:hover div.appear {
    display:block;
}

HTML

<div class="hover">
<img src="questionmark.png"/>
    <div class="appear">
       <h1>My popup</h1>Hitherto and whenceforth.
    </div>
</div>

The problem with these solutions is that everything after this in the page gets shifted when the popup is displayed, ie, the rest of the page jumps downwards to 'make space'. The only way I could fix this was by making position:absolute and removing the top and left CSS tags.

Regex for Mobile Number Validation

Try this regex:

^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$

Explanation of the regex using Perl's YAPE is as below:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  (                        group and capture to \1 (optional
                           (matching the most amount possible)):
----------------------------------------------------------------------
    \+?                      '+' (optional (matching the most amount
                             possible))
----------------------------------------------------------------------
    \d{1,4}                  digits (0-9) (between 1 and 4 times
                             (matching the most amount possible))
----------------------------------------------------------------------
    [\s-]                    any character of: whitespace (\n, \r,
                             \t, \f, and " "), '-'
----------------------------------------------------------------------
  )?                       end of \1 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \1)
----------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
----------------------------------------------------------------------
    0+                       '0' (1 or more times (matching the most
                             amount possible))
----------------------------------------------------------------------
    \s+                      whitespace (\n, \r, \t, \f, and " ") (1
                             or more times (matching the most amount
                             possible))
----------------------------------------------------------------------
    ,?                       ',' (optional (matching the most amount
                             possible))
----------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  \d{10}                   digits (0-9) (10 times)
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  ,?                       ',' (optional (matching the most amount
                           possible))
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

Check Ayende post on the topic: Combating the Select N + 1 Problem In NHibernate.

Basically, when using an ORM like NHibernate or EntityFramework, if you have a one-to-many (master-detail) relationship, and want to list all the details per each master record, you have to make N + 1 query calls to the database, "N" being the number of master records: 1 query to get all the master records, and N queries, one per master record, to get all the details per master record.

More database query calls ? more latency time ? decreased application/database performance.

However, ORMs have options to avoid this problem, mainly using JOINs.

Why is January month 0 in Java Calendar?

Probably because C's "struct tm" does the same.

Show percent % instead of counts in charts of categorical variables

Note that if your variable is continuous, you will have to use geom_histogram(), as the function will group the variable by "bins".

df <- data.frame(V1 = rnorm(100))

ggplot(df, aes(x = V1)) +  
  geom_histogram(aes(y = 100*(..count..)/sum(..count..))) 

# if you use geom_bar(), with factor(V1), each value of V1 will be treated as a
# different category. In this case this does not make sense, as the variable is 
# really continuous. With the hp variable of the mtcars (see previous answer), it 
# worked well since hp was not really continuous (check unique(mtcars$hp)), and one 
# can want to see each value of this variable, and not to group it in bins.
ggplot(df, aes(x = factor(V1))) +  
  geom_bar(aes(y = (..count..)/sum(..count..))) 

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

You select data like this:

$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator

You insert in the same way:

$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));

I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:

$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

How to call external url in jquery?

Follow the below simple steps you will able to get the result

Step 1- Create one internal function getDetailFromExternal in your back end. step 2- In that function call the external url by using cUrl like below function

 function getDetailFromExternal($p1,$p2) {

        $url = "http://request url with parameters";
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true            
        ));

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        echo $output;
        exit;
    }

Step 3- Call that internal function from your front end by using javascript/jquery Ajax.

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...

...create an NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                       forKeys:keys];

...iterate over it

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

...make it mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Note: historic version before 2010: [[dictionary mutableCopy] autorelease]

...and alter it

[mutableDict setObject:@"value3" forKey:@"key3"];

...then store it to a file

[mutableDict writeToFile:@"path/to/file" atomically:YES];

...and read it back again

NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];

...read a value

NSString *x = [anotherDict objectForKey:@"key1"];

...check if a key exists

if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");

...use scary futuristic syntax

From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]

How to convert numbers to words without using num2word library?

Your first statement logic is incorrect. Unless Number is 1 or smaller, that statement is always True; 200 is greater than 1 as well.

Use and instead, and include 1 in the acceptable values:

if (Number >= 1) and (Number <= 19):

You could use chaining as well:

if 1 <= Number <= 19:

For numbers of 20 or larger, use divmod() to get both the number of tens and the remainder:

tens, remainder = divmod(Number, 10)

Demo:

>>> divmod(42, 10)
(4, 2)

then use those values to build your number from the parts:

return num2words2[tens - 2] + '-' + num2words1[below_ten]

Don't forget to account for cases when the number is above 20 and doesn't have a remainder from the divmod operation:

return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]

All put together:

def number(Number):
    if 0 <= Number <= 19:
        return num2words1[Number]
    elif 20 <= Number <= 99:
        tens, remainder = divmod(Number, 10)
        return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]
    else:
        print('Number out of implemented range of numbers.')

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

if you have integrated firebase messaging push notification then,

Add new/update firebase messaging dependencies for android O (Android 8.0), due to Background Execution Limits.

compile 'com.google.firebase:firebase-messaging:11.4.0'

upgrade google play services and google repositories if needed.

Update:

 compile 'com.google.firebase:firebase-messaging:11.4.2'

SQL Update to the SUM of its joined values

How about this:

UPDATE p
SET p.extrasPrice = t.sumPrice
FROM BookingPitches AS p
INNER JOIN
    (
        SELECT PitchID, SUM(Price) sumPrice
        FROM BookingPitchExtras
        WHERE [required] = 1
        GROUP BY PitchID 
    ) t
    ON t.PitchID = p.ID
WHERE p.bookingID = 1

How do I draw a circle in iOS Swift?

If you want to use a UIView to draw it, then you need to make the radius / of the height or width.

so just change:

block.layer.cornerRadius = 9

to:

block.layer.cornerRadius = block.frame.width / 2

You'll need to make the height and width the same however. If you'd like to use coregraphics, then you'll want to do something like this:

CGContextRef ctx= UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];

CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;
CGContextSaveGState(ctx);

CGContextSetLineWidth(ctx,5);
CGContextSetRGBStrokeColor(ctx,0.8,0.8,0.8,1.0);
CGContextAddArc(ctx,locationOfTouch.x,locationOfTouch.y,30,0.0,M_PI*2,YES);
CGContextStrokePath(ctx);

Docker Error bind: address already in use

In some cases it is critical to perform a more in-depth debugging to the problem before stopping a container or killing a process.

Consider following the checklist below:

1) Check you current docker compose environment
Run docker-compose ps.
If port is in use by another container, stop it with docker-compose stop <service-name-in-compose-file> or remove it by replacing stop with rm.

2) Check the containers running outside your current workspace
Run docker ps to see list of all containers running under your host.
If you find the port is in use by another container, you can stop it with docker stop <container-id>.
(*) Because you're not under the scope of the origin compose environment - it is a good practice first to use docker inspect to gather more information about the container that you're about to stop.

3) Check if port is used by other processes running on the host
For example if the port is 6379 run:

$ sudo netstat -ltnp | grep ':6379'
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      915/redis-server 12 
tcp6       0      0 ::1:6379                :::*                    LISTEN      915/redis-server 12

(*) You can also use the lsof command which is mainly used to retrieve information about files that are opened by various processes (I suggest running netstat before that).

So, In case of the output above the PID is 915. Now you can run:

$ ps j 915
 PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
    1   915   915   915 ?           -1 Ssl    123   0:11 /usr/bin/redis-server 127.0.0.1:6379

And see the ID of the parent process (PPID) and the execution command.
You can also run: $ pstree -s <PID> to a visual display of the process and its related processes.

In our case we can see that the process probably is a daemon (PPID is 1) - In that case consider running:
A) $ cat /proc/<PID>/status in order to get a more in-depth information about the process like the number of threads spawned by the process, its capabilities, etc'.
B) $ systemctl status <PID> in order to see the unit that caused the creation of a specific process. If the service is not critical - you can stop and disable the service.

4) Restart Docker service
Run: sudo service docker restart.

5) You reached this point and..
Only if its not placing your system at risk - consider restarting the server.

How can I determine the URL that a local Git repository was originally cloned from?

You can try:

git remote -v

It will print all your remotes' fetch/push URLs.

Dots in URL causes 404 with ASP.NET mvc and IIS

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    [RoutePrefix("File")]
    [Route("{action=index}")]
    public class FileController : Controller
    {
        // GET: File
        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        [Route("Image/{extension?}/{filename}")]
        public ActionResult Image(string extension, string filename)
        {
            var dir = Server.MapPath("/app_data/images");

            var path = Path.Combine(dir, filename+"."+ (extension!=null?    extension:"jpg"));
           // var extension = filename.Substring(0,filename.LastIndexOf("."));

            return base.File(path, "image/jpeg");
        }
    }
}

What is the best way to remove the first element from an array?

You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:

  1. Shift every element up one, then set the last element to null.
  2. Create a new array, then copy it.

You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.

If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).

Integer division: How do you produce a double?

Best way to do this is

int i = 3;
Double d = i * 1.0;

d is 3.0 now.

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

Here's an alternate way of finding height. Add an additional attribute to your node called height:

class Node
{
data value; //data is a custom data type
node right;
node left;
int height;
}

Now, we'll do a simple breadth-first traversal of the tree, and keep updating the height value for each node:

int height (Node root)
{
Queue<Node> q = Queue<Node>();
Node lastnode;
//reset height
root.height = 0;

q.Enqueue(root);
while(q.Count > 0)
{
   lastnode = q.Dequeue();
   if (lastnode.left != null){
      lastnode.left.height = lastnode.height + 1; 
      q.Enqueue(lastnode.left);
   }

   if (lastnode.right != null){
      lastnode.right.height = lastnode.height + 1;
      q.Enqueue(lastnode.right);
   }
}
return lastnode.height; //this will return a 0-based height, so just a root has a height of 0
}

Cheers,

Ruby/Rails: converting a Date to a UNIX timestamp

The suggested options of using to_utc or utc to fix the local time offset does not work. For me I found using Time.utc() worked correctly and the code involves less steps:

> Time.utc(2016, 12, 25).to_i
=> 1482624000 # correct

vs

> Date.new(2016, 12, 25).to_time.utc.to_i
=> 1482584400 # incorrect

Here is what happens when you call utc after using Date....

> Date.new(2016, 12, 25).to_time
=> 2016-12-25 00:00:00 +1100 # This will use your system's time offset
> Date.new(2016, 12, 25).to_time.utc
=> 2016-12-24 13:00:00 UTC

...so clearly calling to_i is going to give the wrong timestamp.

Same font except its weight seems different on different browsers

In order to best standardise your @font-face embedded fonts across browsers try including the below inside your @font-face declaration or on your body font styling:

speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;

At present there looks to be no universal fix across all platforms and browser builds. As stated frequently all browsers/OS have different text rendering engines.

How to add a button dynamically using jquery

Working plunk here.

To add the new input just once, use the following code:

$(document).ready(function()
{
  $("#insertAfterBtn").one("click", function(e)
  {
    var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" });

    $("body").append(r);
  });
});

[... source stripped here ...]

<body>
    <button id="insertAfterBtn">Insert after</button>
</body>

[... source stripped here ...]

To make it work in w3 editor, copy/paste the code below into 'source code' section inside w3 editor and then hit 'Submit Code':

<!DOCTYPE html>
<html>

  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  </head>

  <body>
    <button id="insertAfterBtn">Insert only one button after</button>
    <div class="myClass"></div>
    <div id="myId"></div>
  </body>

<script type="text/javascript">
$(document).ready(function()
{
  // when dom is ready, call this method to add an input to 'body' tag.
  addInputTo($("body"));

  // when dom is ready, call this method to add an input to a div with class=myClass
  addInputTo($(".myClass"));

  // when dom is ready, call this method to add an input to a div with id=myId
  addInputTo($("#myId"));

  $("#insertAfterBtn").one("click", function(e)
  {
    var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" });

    $("body").append(r);
  });
});

function addInputTo(container)
{
  var inputToAdd = $("<input/>", { type: "button", id: "field", value: "I was added on page load" });

  container.append(inputToAdd);
}
</script>

</html>

Set default time in bootstrap-datetimepicker

use this after initialisation

$('.form_datetime').datetimepicker('update', new Date());