Programs & Examples On #Smart tags

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

You can get this error if you use wrong mode when opening the file. For example:

    with open(output, 'wb') as output_file:
        print output_file.read()

In that code, I want to read the file, but I use mode wb instead of r or r+

bootstrap 3 - how do I place the brand in the center of the navbar?

Another option is to use nav-justified..

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav nav-justified">
      <li><a href="#" class="navbar-brand">Brand</a></li>
    </ul>
  </div>
</nav>

CSS

.navbar-brand {
    float:none;
}

Bootply

Alternate example

What is console.log?

A point of confusion sometimes is that to log a text message along with the contents of one of your objects using console.log, you have to pass each one of the two as a different argument. This means that you have to separate them by commas because if you were to use the + operator to concatenate the outputs, this would implicitly call the .toString() method of your object. This in most cases is not explicitly overriden and the default implementation inherited by Object doesn't provide any useful information.

Example to try in console:

>>> var myObj = {foo: 'bar'}
undefined
>>> console.log('myObj is: ', myObj);
myObj is: Object { foo= "bar"}

whereas if you tried to concatenate the informative text message along with the object's contents you'd get:

>>> console.log('myObj is: ' + myObj);
myObj is: [object Object]

So keep in mind that console.log in fact takes as many arguments as you like.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

Here is an Online Tool for fixing a corrupted serialized string.

I'd like to add that this mostly happens due to a search and replace done on the DB and the serialization data(specially the key length) doesn't get updated as per the replace and that causes the "corruption".

Nonetheless, The above tool uses the following logic to fix the serialization data (Copied From Here).

function error_correction_serialise($string){
    // at first, check if "fixing" is really needed at all. After that, security checkup.
    if ( unserialize($string) !== true &&  preg_match('/^[aOs]:/', $string) ) {
         $string = preg_replace_callback( '/s\:(\d+)\:\"(.*?)\";/s',    function($matches){return 's:'.strlen($matches[2]).':"'.$matches[2].'";'; },   $string );
    }
    return $string;
} 

Prevent WebView from displaying "web page not available"

First create your own error page in HTML and put it in your assets folder, Let's call it myerrorpage.html Then with onReceivedError:

mWebView.setWebViewClient(new WebViewClient() {
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        mWebView.loadUrl("file:///android_asset/myerrorpage.html");

    }
});

How do I view the SQL generated by the Entity Framework?

Well, I am using Express profiler for that purpose at the moment, the drawback is that it only works for MS SQL Server. You can find this tool here: https://expressprofiler.codeplex.com/

How to fluently build JSON in Java?

You can use one of Java template engines. I love this method because you are separating your logic from the view.

Java 8+:

<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.9.6</version>
</dependency>

Java 6/7:

<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.8.18</version>
</dependency>

Example template file:

{{#items}}
Name: {{name}}
Price: {{price}}
  {{#features}}
  Feature: {{description}}
  {{/features}}
{{/items}}

Might be powered by some backing code:

public class Context {
  List<Item> items() {
    return Arrays.asList(
      new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
      new Item("Item 2", "$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly.")))
    );
  }

  static class Item {
    Item(String name, String price, List<Feature> features) {
      this.name = name;
      this.price = price;
      this.features = features;
    }
    String name, price;
    List<Feature> features;
  }

  static class Feature {
    Feature(String description) {
       this.description = description;
    }
    String description;
  }
}

And would result in:

Name: Item 1
Price: $19.99
  Feature: New!
  Feature: Awesome!
Name: Item 2
Price: $29.99
  Feature: Old.
  Feature: Ugly.

In Maven how to exclude resources from the generated jar?

By convention, the directory src/main/resources contains the resources that will be used by the application. So Maven will include them in the final JAR.

Thus in your application, you will access them using the getResourceAsStream() method, as the resources are loaded in the classpath.

If you need to have them outside your application, do not store them in src/main/resources as they will be bundled by Maven. Of course, you can exclude them (using the link given by chkal) but it is better to create another directory (for example src/main/external-resources) in order to keep the conventions regarding the src/main/resources directory.

In the latter case, you will have to deliver the resources independently as your JAR file (this can be achieved by using the Assembly plugin). If you need to access them in your Eclipse environment, go to the Properties of your project, then in Java Build Path in Sources tab, add the folder (for example src/main/external-resources). Eclipse will then add this directory in the classpath.

How do I use WPF bindings with RelativeSource?

I created a library to simplify the binding syntax of WPF including making it easier to use RelativeSource. Here are some examples. Before:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
{Binding Path=Text, ElementName=MyTextBox}

After:

{BindTo PathToProperty}
{BindTo Ancestor.typeOfAncestor.PathToProperty}
{BindTo Template.PathToProperty}
{BindTo #MyTextBox.Text}

Here is an example of how method binding is simplified. Before:

// C# code
private ICommand _saveCommand;
public ICommand SaveCommand {
 get {
  if (_saveCommand == null) {
   _saveCommand = new RelayCommand(x => this.SaveObject());
  }
  return _saveCommand;
 }
}

private void SaveObject() {
 // do something
}

// XAML
{Binding Path=SaveCommand}

After:

// C# code
private void SaveObject() {
 // do something
}

// XAML
{BindTo SaveObject()}

You can find the library here: http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html

Note in the 'BEFORE' example that I use for method binding that code was already optimized by using RelayCommand which last I checked is not a native part of WPF. Without that the 'BEFORE' example would have been even longer.

Java error - "invalid method declaration; return type required"

Every method (other than a constructor) must have a return type.

public double diameter(){...

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

I changed the following dependencies in my project to make it work .

build.gradle (app):

implementation 'com.google.firebase:firebase-core:16.0.1'

to

implementation 'com.google.firebase:firebase-core:16.0.8'

build.gradle (app) :

classpath 'com.google.gms:google-services:4.0.1'

to

classpath 'com.google.gms:google-services:4.2.0'

****Note :

Use the following link for updated use of libraries that have dependencies https://firebase.google.com/docs/android/setup

iPhone viewWillAppear not firing

I'm not 100% sure on this, but I think that adding a view to the view hierarchy directly means calling -addSubview: on the view controller's view (e.g., [viewController.view addSubview:anotherViewController.view]) instead of pushing a new view controller onto the navigation controller's stack.

How can I catch all the exceptions that will be thrown through reading and writing a file?

While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.

try{
    // IO code
} catch (Exception e){
    if(e instanceof IOException){
        // handle this exception type
    } else if (e instanceof AnotherExceptionType){
        //handle this one
    } else {
        // We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
        throw e;
    }
}

However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable

try{
    // IO code
} catch (Throwable t){
    if(t instanceof Exception){
        if(t instanceof IOException){
            // handle this exception type
        } else if (t instanceof AnotherExceptionType){
            //handle this one
        } else {
            // We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else if (t instanceof Error){
        if(t instanceof IOError){
            // handle this Error
        } else if (t instanceof AnotherError){
            //handle different Error
        } else {
            // We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else {
        // This should never be reached, unless you have subclassed Throwable for your own purposes.
        throw t;
    }
}

How do I loop through a date range?

@jacob-sobus and @mquander and @Yogurt not exactly correct.. If I need the next day I wait 00:00 time mostly

    public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
    {
        for (var day = from.Date; day.Date <= thru.Date; day = day.NextDay())
            yield return day;
    }

    public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
    {
        for (var month = from.Date; month.Date <= thru.Date || month.Year == thru.Year && month.Month == thru.Month; month = month.NextMonth())
            yield return month;
    }

    public static IEnumerable<DateTime> EachYear(DateTime from, DateTime thru)
    {
        for (var year = from.Date; year.Date <= thru.Date || year.Year == thru.Year; year = year.NextYear())
            yield return year;
    }

    public static DateTime NextDay(this DateTime date)
    {
        return date.AddTicks(TimeSpan.TicksPerDay - date.TimeOfDay.Ticks);
    }

    public static DateTime NextMonth(this DateTime date)
    {
        return date.AddTicks(TimeSpan.TicksPerDay * DateTime.DaysInMonth(date.Year, date.Month) - (date.TimeOfDay.Ticks + TimeSpan.TicksPerDay * (date.Day - 1)));
    }

    public static DateTime NextYear(this DateTime date)
    {
        var yearTicks = (new DateTime(date.Year + 1, 1, 1) - new DateTime(date.Year, 1, 1)).Ticks;
        var ticks = (date - new DateTime(date.Year, 1, 1)).Ticks;
        return date.AddTicks(yearTicks - ticks);
    }

    public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
    {
        return EachDay(dateFrom, dateTo);
    }

    public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
    {
        return EachMonth(dateFrom, dateTo);
    }

    public static IEnumerable<DateTime> EachYearTo(this DateTime dateFrom, DateTime dateTo)
    {
        return EachYear(dateFrom, dateTo);
    }

How do I create a circle or square with just CSS - with a hollow center?

To my knowledge there is no cross-browser compatible way to make a circle with CSS & HTML only.

For the square I guess you could make a div with a border and a z-index higher than what you are putting it over. I don't understand why you would need to do this, when you could just put a border on the image or "something" itself.

If anyone else knows how to make a circle that is cross browser compatible with CSS & HTML only, I would love to hear about it!

@Caspar Kleijne border-radius does not work in IE8 or below, not sure about 9.

How to capture the "virtual keyboard show/hide" event in Android?

Nebojsa Tomcic's answer wasn't helpful for me. I have RelativeLayout with TextView and AutoCompleteTextView inside it. I need to scroll the TextView to the bottom when the keyboard is showed and when it's hidden. To accomplish this I overrode onLayout method and it works fine for me.

public class ExtendedLayout extends RelativeLayout
{
    public ExtendedLayout(Context context, AttributeSet attributeSet)
    {
        super(context, attributeSet);
        LayoutInflater inflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.main, this);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        super.onLayout(changed, l, t, r, b);

        if (changed)
        {
            int scrollEnd = (textView.getLineCount() - textView.getHeight() /
                textView.getLineHeight()) * textView.getLineHeight();
            textView.scrollTo(0, scrollEnd);
        }
    }
}

Click toggle with jQuery

This is easily done by flipping the current 'checked' state of the checkbox upon each click. Examples:

 $(".offer").on("click", function () { 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.attr('checked', !$checkbox.attr('checked'));
 });

or:

 $(".offer").on("click", function () { 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.attr('checked', !$checkbox.is(':checked'));
 });

or, by directly manipulating the DOM 'checked' property (i.e. not using attr() to fetch the current state of the clicked checkbox):

 $(".offer").on("click", function () { 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.attr('checked', !$checkbox[0].checked);
 });

...and so on.

Note: since jQuery 1.6, checkboxes should be set using prop not attr:

 $(".offer").on("click", function () { 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.prop('checked', !$checkbox[0].checked);
 });

How do I clear my Jenkins/Hudson build history?

Go to "Manage Jenkins" > "Script Console"

Run below:

def jobName = "build_name"  
def job = Jenkins.instance.getItem(jobName)  
job.getBuilds().each { it.delete() }  
job.save()

Why is HttpClient BaseAddress not working?

Ran into a issue with the HTTPClient, even with the suggestions still could not get it to authenticate. Turns out I needed a trailing '/' in my relative path.

i.e.

var result = await _client.GetStringAsync(_awxUrl + "api/v2/inventories/?name=" + inventoryName);
var result = await _client.PostAsJsonAsync(_awxUrl + "api/v2/job_templates/" + templateId+"/launch/" , new {
                inventory = inventoryId
            });

Ideal way to cancel an executing AsyncTask

The only way to do it is by checking the value of the isCancelled() method and stopping playback when it returns true.

ROW_NUMBER() in MySQL

A bit late but may also help to someone who looks for answers...

Between rows/row_number example - recursive query that may be used in any SQL:

WITH data(row_num, some_val) AS 
(
 SELECT 1 row_num, 1 some_val FROM any_table --dual in Oracle
  UNION ALL
 SELECT row_num+1, some_val+row_num FROM data WHERE row_num < 20 -- any number
)
SELECT * FROM data
 WHERE row_num BETWEEN 5 AND 10
/

ROW_NUM    SOME_VAL
-------------------
5           11
6           16
7           22
8           29
9           37
10          46

Java, How to implement a Shift Cipher (Caesar Cipher)

Java Shift Caesar Cipher by shift spaces.

Restrictions:

  1. Only works with a positive number in the shift parameter.
  2. Only works with shift less than 26.
  3. Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
  4. Does a cast number to character, so it will fail with anything but ascii letters.
  5. Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
  6. Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.

Pseudocode:

  1. Loop through each character in the string.
  2. Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
  3. If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
  4. Append the character onto a new string. Return the string.

Function:

String cipher(String msg, int shift){
    String s = "";
    int len = msg.length();
    for(int x = 0; x < len; x++){
        char c = (char)(msg.charAt(x) + shift);
        if (c > 'z')
            s += (char)(msg.charAt(x) - (26-shift));
        else
            s += (char)(msg.charAt(x) + shift);
    }
    return s;
}

How to invoke it:

System.out.println(cipher("abc", 3));  //prints def
System.out.println(cipher("xyz", 3));  //prints abc

Selector on background color of TextView

The problem here is that you cannot define the background color using a color selector, you need a drawable selector. So, the necessary changes would look like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@drawable/selected_state" />
</selector>

You would also need to move that resource to the drawable directory where it would make more sense since it's not a color selector per se.

Then you would have to create the res/drawable/selected_state.xml file like this:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <solid android:color="@color/semitransparent_white" />
</shape>

and finally, you would use it like this:

android:background="@drawable/selector"

Note: the reason why the OP was getting an image resource drawn is probably because he tried to just reference his resource that was still in the color directory but using @drawable so he ended up with an ID collision, selecting the wrong resource.

Hope this can still help someone even if the OP probably has, I hope, solved his problem by now.

Why did I get the compile error "Use of unassigned local variable"?

IEnumerable<DateTime?> _getCurrentHolidayList; //this will not initailize

Assign value(_getCurrentHolidayList) inside the loop

foreach (HolidaySummaryList _holidayItem in _holidayDetailsList)
{
                            if (_holidayItem.CountryId == Countryid)
                                _getCurrentHolidayList = _holidayItem.Holiday;                                                   
}

After your are passing the local varibale to another method like below. It throw error(use of unassigned variable). eventhough nullable mentioned in time of decalration.

var cancelRescheduleCondition = GetHolidayDays(_item.ServiceDateFrom, _getCurrentHolidayList);

if you mentioned like below, It will not throw any error.

IEnumerable<DateTime?> _getCurrentHolidayList =null;

Simple line plots using seaborn

Yes, you can do the same in Seaborn directly. This is done with tsplot() which allows either a single array as input, or two arrays where the other is 'time' i.e. x-axis.

import seaborn as sns

data =  [1,5,3,2,6] * 20
time = range(100)

sns.tsplot(data, time)

enter image description here

Testing two JSON objects for equality ignoring child order in Java

You could try using json-lib's JSONAssert class:

JSONAssert.assertEquals(
  "{foo: 'bar', baz: 'qux'}",
  JSONObject.fromObject("{foo: 'bar', baz: 'xyzzy'}")
);

Gives:

junit.framework.ComparisonFailure: objects differed at key [baz]; expected:<[qux]> but was:<[xyzzy]>

Why does the Google Play store say my Android app is incompatible with my own device?

Typical, found it right after posting this question in despair; the tool I was looking for was:

$ aapt dump badging <my_apk.apk>

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

"Line contains NULL byte" in CSV reader (Python)

A tricky way:

If you develop under Lunux, you can use all the power of sed:

from subprocess import check_call, CalledProcessError

PATH_TO_FILE = '/home/user/some/path/to/file.csv'

try:
    check_call("sed -i -e 's|\\x0||g' {}".format(PATH_TO_FILE), shell=True)
except CalledProcessError as err:
    print(err)    

The most efficient solution for huge files.

Checked for Python3, Kubuntu

Why use multiple columns as primary keys (composite primary key)

Your second question

How many columns can be used together as a primary key in a given table?

is implementation specific: it's defined in the actual DBMS being used.[1],[2],[3] You have to inspect the technical specification of the database system you use. Some are very detailed, some are not. Searching the web about such limitations can be hard because the terminology varies. The term composite primary key should be mandatory ;)

If you cannot find explicit information, try creating a test database to ensure you can expect stable (and specific) handling of the limit violations (which are to be expected). Be careful to get the right information about this: sometimes the limits are accumulated, and you'll see different results with different database layouts.


What's is the difference between train, validation and test set, in neural networks?

Say you train a model on a training set and then measure its performance on a test set. You think that there is still room for improvement and you try tweaking the hyper-parameters ( If the model is a Neural Network - hyper-parameters are the number of layers, or nodes in the layers ). Now you get a slightly better performance. However, when the model is subjected to another data ( not in the testing and training set ) you may not get the same level of accuracy. This is because you introduced some bias while tweaking the hyper-parameters to get better accuracy on the testing set. You basically have adapted the model and hyper-parameters to produce the best model for that particular training set.

A common solution is to split the training set further to create a validation set. Now you have

  • training set
  • testing set
  • validation set

You proceed as before but this time you use the validation set to test the performance and tweak the hyper-parameters. More specifically, you train multiple models with various hyper-parameters on the reduced training set (i.e., the full training set minus the validation set), and you select the model that performs best on the validation set.

Once you've selected the best performing model on the validation set, you train the best model on the full training set (including the valida- tion set), and this gives you the final model.

Lastly, you evaluate this final model on the test set to get an estimate of the generalization error.

Registering for Push Notifications in Xcode 8/Swift 3.0?

In iOS10 instead of your code, you should request an authorization for notification with the following: (Don't forget to add the UserNotifications Framework)

if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { (granted: Bool, error: NSError?) in
            // Do something here
        }
    }

Also, the correct code for you is (use in the else of the previous condition, for example):

let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared().registerUserNotificationSettings(setting)
UIApplication.shared().registerForRemoteNotifications()

Finally, make sure Push Notification is activated under target-> Capabilities -> Push notification. (set it on On)

Change color of Button when Mouse is over

Try this- In this example Original color is green and mouseover color will be DarkGoldenrod

<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="50" Height="50" HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="DarkGoldenrod"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Alternative to Intersect in MySQL

Your query would always return an empty recordset since cut_name= '?????' and cut_name='??' will never evaluate to true.

In general, INTERSECT in MySQL should be emulated like this:

SELECT  *
FROM    mytable m
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    othertable o
        WHERE   (o.col1 = m.col1 OR (m.col1 IS NULL AND o.col1 IS NULL))
                AND (o.col2 = m.col2 OR (m.col2 IS NULL AND o.col2 IS NULL))
                AND (o.col3 = m.col3 OR (m.col3 IS NULL AND o.col3 IS NULL))
        )

If both your tables have columns marked as NOT NULL, you can omit the IS NULL parts and rewrite the query with a slightly more efficient IN:

SELECT  *
FROM    mytable m
WHERE   (col1, col2, col3) IN
        (
        SELECT  col1, col2, col3
        FROM    othertable o
        )

Taskkill /f doesn't kill a process

I faced the same issue where I started a node app in port 3000 and it didn't close correctly and the process kept running even after restart.

None of the taskkill or powershell commands running in Administrator mode worked for me.

I used MS Process Expoler > Properties > Image > Current directory (which was supposed to be the my project directory).

Finally, I had to reboot in SafeMode and rename the project folder and restart. The Node processes which were consuming port 3000 killed itself.

How do I pass multiple parameters into a function in PowerShell?

You can pass parameters in a function like this also:

function FunctionName()
{
    Param ([string]$ParamName);
    # Operations
}

Remove Elements from a HashSet while Iterating

Java 8 Collection has a nice method called removeIf that makes things easier and safer. From the API docs:

default boolean removeIf(Predicate<? super E> filter)
Removes all of the elements of this collection that satisfy the given predicate. 
Errors or runtime exceptions thrown during iteration or by the predicate 
are relayed to the caller.

Interesting note:

The default implementation traverses all elements of the collection using its iterator(). 
Each matching element is removed using Iterator.remove().

From: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-

Sorting options elements alphabetically using jQuery

What I'd do is:

  1. Extract the text and value of each <option> into an array of objects;
  2. Sort the array;
  3. Update the <option> elements with the array contents in order.

To do that with jQuery, you could do this:

var options = $('select.whatever option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
options.each(function(i, o) {
  o.value = arr[i].v;
  $(o).text(arr[i].t);
});

Here is a working jsfiddle.

edit — If you want to sort such that you ignore alphabetic case, you can use the JavaScript .toUpperCase() or .toLowerCase() functions before comparing:

arr.sort(function(o1, o2) {
  var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();

  return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});

Presto SQL - Converting a date string to date format

Converted DateID having date in Int format to date format: Presto Query

Select CAST(date_format(date_parse(cast(dateid as varchar(10)), '%Y%m%d'), '%Y/%m-%d') AS DATE)
from
     Table_Name
limit 10;

What is the difference between Select and Project Operations

The difference come in relational algebra where project affects columns and select affect rows. However in query syntax, select is the word. There is no such query as project. Assuming there is a table named users with hundreds of thousands of records (rows) and the table has 6 fields (userID, Fname,Lname,age,pword,salary). Lets say we want to restrict access to sensitive data (userID,pword and salary) and also restrict amount of data to be accessed. In mysql maria DB we create a view as follows ( Create view user1 as select Fname,Lname, age from users limit 100;) from our view we issue (select Fname from users1;) . This query is both a select and a project

mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

To summarize:

  • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
  • win32: No C++11 multithreading features.

Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

Position Relative vs Absolute?

Absolute CSS Positioning

position: absolute;

Absolute positioning is the easiest to understand. You start with the CSS position property:

position: absolute;

This tells the browser that whatever is going to be positioned should be removed from the normal flow of the document and will be placed in an exact location on the page. It won't affect how the elements before it or after it in the HTML are positioned on the Web page however it will be subject to it's parents' positioning unless you override it.

If you want to position an element 10 pixels from the top of the document window, you would use the top offset to position it there with absolute positioning:

position: absolute;
top: 10px;

This element will then always display 10px from the top of the page regardless of what content passes through, under or over the element (visually).

The four positioning properties are:

  1. top
  2. right
  3. bottom
  4. left

To use them, you need to think of them as offset properties. In other words, an element positioned right: 2px is not moved right 2px. It's right side is offset from the right side of the window (or its position overriding parent) by 2px. The same is true for the other three.

Relative Positioning

position: relative;

Relative positioning uses the same four positioning properties as absolute positioning. But instead of basing the position of the element upon the browser view port, it starts from where the element would be if it were still in the normal flow.

For example, if you have three paragraphs on your Web page, and the third has a position: relative style placed on it, its position will be offset based on its current location-- not from the original sides of the view port.

Paragraph 1.

Paragraph 2.

Paragraph 3.

In the above example, the third paragraph will be positioned 3em from the left side of the container element, but will still be below the first two paragraphs. It would remain in the normal flow of the document, and just be offset slightly. If you changed it to position: absolute;, anything following it would display on top of it, because it would no longer be in the normal flow of the document.

Notes:

  • the default width of an element that is absolutely positioned is the width of the content within it, unlike an element that is relatively positioned where it's default width is 100% of the space it can fill.

  • You can have elements that overlap with absolutely positioned elements, whereas you cannot do this with relatively positioned elements (natively i.e without the use of negative margins/positioning)


lots pulled from: this resource

Allow only numbers and dot in script

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 46 || charCode > 57)) {
        return false;
    }
    return true;
}

you should use this function and write the properties of this element ;

HTML Code:

<input id="deneme" data-mini="true" onKeyPress="return isNumber(event)" type="text"/>`

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<

Very simple question that you can solved it easily ,

Please follow my step : change < to ( and >; to );

Just use: (

     );

enter code here

` CREATE TABLE information (
-> id INT(11) NOT NULL AUTO_INCREMENT,
-> name VARCHAR(30) NOT NULL,
-> age INT(10) NOT NULL,
-> salary INT(100) NOT NULL,
-> address VARCHAR(100) NOT NULL,
-> PRIMARY KEY(id)
-> );`

The representation of if-elseif-else in EL using JSF

One possible solution is:

<h:panelGroup rendered="#{bean.row == 10}">
    <div class="text-success">
        <h:outputText value="#{bean.row}"/>
    </div>
</h:panelGroup>

clear table jquery

  $('#myTable > tr').remove();

Using GroupBy, Count and Sum in LINQ Lambda Expressions

var boxSummary = from b in boxes
                 group b by b.Owner into g
                 let nrBoxes = g.Count()
                 let totalWeight = g.Sum(w => w.Weight)
                 let totalVolume = g.Sum(v => v.Volume)
                 select new { Owner = g.Key, Boxes = nrBoxes,
                              TotalWeight = totalWeight,
                              TotalVolume = totalVolume }

What is a simple command line program or script to backup SQL server databases?

SET NOCOUNT ON;
declare @PATH VARCHAR(200)='D:\MyBackupFolder\'
 -- path where you want to take backups
IF OBJECT_ID('TEMPDB..#back') IS NOT NULL

DROP TABLE #back

CREATE TABLE #back
(
RN INT IDENTITY (1,1),
DatabaseName NVARCHAR(200)

)

INSERT INTO #back 
SELECT       'MyDatabase1'
UNION SELECT 'MyDatabase2'
UNION SELECT 'MyDatabase3'
UNION SELECT 'MyDatabase4'

-- your databases List

DECLARE @COUNT INT =0 ,  @RN INT =1, @SCRIPT NVARCHAR(MAX)='',  @DBNAME VARCHAR(200)

PRINT '---------------------FULL BACKUP SCRIPT-------------------------'+CHAR(10)
SET @COUNT = (SELECT COUNT(*) FROM #back)
PRINT 'USE MASTER'+CHAR(10)
WHILE(@COUNT > = @RN)
BEGIN

SET @DBNAME =(SELECT DatabaseName FROM #back WHERE RN=@RN)
SET @SCRIPT ='BACKUP DATABASE ' +'['+@DBNAME+']'+CHAR(10)+'TO DISK =N'''+@PATH+@DBNAME+ N'_Backup_'
+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.bak'''+CHAR(10)+'WITH COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)
PRINT @SCRIPT
SET @RN=@RN+1
END

 PRINT '---------------------DIFF BACKUP SCRIPT-------------------------'+CHAR(10)

  SET  @COUNT  =0 SET  @RN  =1 SET @SCRIPT ='' SET @DBNAME =''
 SET @COUNT = (SELECT COUNT(*) FROM #back)
PRINT 'USE MASTER'+CHAR(10)
WHILE(@COUNT > = @RN)
BEGIN
SET @DBNAME =(SELECT DatabaseName FROM #back WHERE RN=@RN)
SET @SCRIPT ='BACKUP DATABASE ' +'['+@DBNAME+']'+CHAR(10)+'TO DISK =N'''+@PATH+@DBNAME+ N'_Backup_'
+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.diff'''+CHAR(10)+'WITH DIFFERENTIAL, COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)
PRINT @SCRIPT
SET @RN=@RN+1
END

Find if value in column A contains value from column B?

You can try this. :) simple solution!

=IF(ISNUMBER(MATCH(I1,E:E,0)),"TRUE","")

How do I set the icon for my application in visual studio 2008?

This is how you do it in Visual Studio 2010.

Because it is finicky, this can be quite painful, actually, because you are trying to do something so incredibly simple, but it isn't straight forward and there are many gotchas that Visual Studio doesn't tell you about. If at any point you feel angry or like you want to sink your teeth into a 2 by 4 and scream, by all means, please do so.

Gotchas:

  • You need to use an .ico file. You cannot use a PNG image file for your executable's icon, it will not work. You must use .ico. There are web utilities that convert images to .ico files.
  • The ico used for your exe will be the ico with the LOWEST RESOURCE ID. In order to change the .ico

1) Open VIEW > RESOURCE VIEW (in the middle of the VIEW menu), or press Ctrl+Shift+E to get it to appear.

2) In Resource view, right click the project name and say ADD > RESOURCE...

3) Assuming you have already generated an .ico file yourself, choose Icon from the list of crap that appears, then click IMPORT.

4) At this dialog *.ico files aren't listed, and you can't use a regular PNG or JPG image as an icon, so change the file filter to *.ico using the dropdown. Misleading UI, I know, I know.

5) If you compile your project now, it will automatically stick the .ico with the lowest ID (as listed in resource.h) as the icon of your .exe file.

6) If you load a bunch of ICO files into the project for whatever reason, be sure the .ico you want Visual Studio to use has the lowest id in resource.h. You can edit this file manually with no problems

Eg.

//resource.h
#define IDI_ICON1                       102
#define IDI_ICON2                       103

IDI_ICON1 is used

//resource.h
#define IDI_ICON1                       106
#define IDI_ICON2                       103

Now IDI_ICON2 is used.

How to check if mod_rewrite is enabled in php?

This is my current method of checking if Mod_rewrite enabled for both Apache and IIS

/**
 * --------------------------------------------------------------
 *  MOD REWRITE CHECK
 * --------------------------------------------------------------
 *                                        - By A H Abid
 * Define Constant for MOD REWRITE
 * 
 * Check if server allows MOD REWRITE. Checks for both 
 * Apache and IIS.
 * 
 */
if( function_exists('apache_get_modules') && in_array('mod_rewrite',apache_get_modules()) )
    $mod_rewrite = TRUE;
elseif( isset($_SERVER['IIS_UrlRewriteModule']) )
    $mod_rewrite = TRUE;
else
    $mod_rewrite = FALSE;
define('MOD_REWRITE', $mod_rewrite);

It works in my local machine and also worked in my IIS based webhost. However, on a particular apache server, it didn't worked for Apache as the apache_get_modules() was disabled but the mod_rewrite was enable in that server.

Google Maps API v3: InfoWindow not sizing correctly

This solved my problem completely:

.gm-style-iw {
    overflow: visible !important;
    height: auto !important;
    width: auto !important;
}

Unable to install pyodbc on Linux

I had the same problem on CentOS 5.5

In addition to installing unixODBC-devel I also had to install gcc-c++

yum install gcc-c++

How to set a cookie to expire in 1 hour in Javascript?

Code :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

How to create json by JavaScript for loop?

From what I understand of your request, this should work:

<script>
//  var status  = document.getElementsByID("uniqueID"); // this works too
var status  = document.getElementsByName("status")[0];
var jsonArr = [];

for (var i = 0; i < status.options.length; i++) {
    jsonArr.push({
        id: status.options[i].text,
        optionValue: status.options[i].value
    });
}
</script>

Fatal error: [] operator not supported for strings

I agree with Jeremy Young's comment on Phils answer:

I have found that this can be a problem associated with migrating from php 5 to php 7. php 5 was more tolerant of amibiguity in whether a variable was an array or not than php 7 is. In most cases the solution is to declare the array explicitly, as explained in this answer.

I was just trouble shooting a Wordpress plugin after the migration of php5 to php7. Since the plugin code was relying on user input, and it was intrinsically used in the code either as string, or as array, I added the following code in to prevent a fatal error:

if(is_array($variable_either_string_or_array)){
    // if it's an array, declaration is allowed:
    $variable_either_string_or_array[]=$additionalInfoData[$i];
}else{
    // if it's not an array, declaration it as follows:
    $variable_either_string_or_array=$additionalInfoData[$i];
}

This was the only modification I needed to add to make the plugin php7-proof. Obviously not "best practices", I'd rather read and understand the full code.. but a quick fix was needed.

Determine if an element has a CSS class with jQuery

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}

Can't resolve module (not found) in React.js

The way we usually use import is based on relative path.

. and .. are similar to how we use to navigate in terminal like cd .. to go out of directory and mv ~/file . to move a file to current directory.

my-app/
  node_modules/
  package.json
  src/
    containers/card.js
    components/header.js
    App.js
    index.js

In your case, App.js is in src/ directory while header.js is in src/components. To import you would do import Header from './components/header'. This roughly translate to in my current directory, find the components folder that contain a header file.

Now, if from header.js, you need to import something from card, you would do this. import Card from '../containers/card'. This translate to, move out of my current directory, look for a folder name containers that have a card file.

As for import React, { Component } from 'react', this does not start with a ./ or ../ or / therefore node will start looking for the module in the node_modules in a specific order till react is found. For a more detail understanding, it can be read here.

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

What is function overloading and overriding in php?

Overloading Example

class overload {
    public $name;
    public function __construct($agr) {
        $this->name = $agr;
    }
    public function __call($methodname, $agrument) {
         if($methodname == 'sum2') {

          if(count($agrument) == 2) {
              $this->sum($agrument[0], $agrument[1]);
          }
          if(count($agrument) == 3) {

              echo $this->sum1($agrument[0], $agrument[1], $agrument[2]);
          }
        }
    }
    public function sum($a, $b) {
        return $a + $b;
    }
    public function sum1($a,$b,$c) {

        return $a + $b + $c;
    }
}
$object = new overload('Sum');
echo $object->sum2(1,2,3);

How to make in CSS an overlay over an image?

Putting this answer here as it is the top result in Google.

If you want a quick and simple way:

    filter: brightness(0.2);

*Not compatible with IE

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Get filename from input [type='file'] using jQuery

There is no jQuery function for this. You have to access the DOM element and check the files property.

document.getElementById("image_file").files[0];

Or

$('#image_file')[0].files[0]

How to get label of select option with jQuery?

Hi first give an id to the select as

<select id=theid>
<option value="test">label </option>
</select>

then you can call the selected label like that:

jQuery('#theid option:selected').text()

How to enable Google Play App Signing

When you use Fabric for public beta releases (signed with prod config), DON'T USE Google Play App Signing. You will must after build two signed apks!

When you distribute to more play stores (samsung, amazon, xiaomi, ...) you will must again build two signed apks.

So be really carefull with Google Play App Signing.

It's not possible to revert it :/ and Google Play did not after accept apks signed with production key. After enable Google Play App Signing only upload key is accepted...

It really complicate CI distribution...

Next issues with upgrade: https://issuetracker.google.com/issues/69285256

Paging with Oracle

Try the following:

SELECT *
FROM
  (SELECT FIELDA,
    FIELDB,
    FIELDC,
    ROW_NUMBER() OVER (ORDER BY FIELDC) R
  FROM TABLE_NAME
  WHERE FIELDA = 10
  )
WHERE R >= 10
AND R   <= 15;

via [tecnicume]

How to get Node.JS Express to listen only on localhost?

You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000, 'localhost');
server.on('listening', function() {
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});

This works just fine in nodejs v0.6+ and Express v3.0+.

Why specify @charset "UTF-8"; in your CSS file?

One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.

How can I concatenate a string and a number in Python?

If it worked the way you expected it to (resulting in "abc9"), what would "9" + 9 deliver? 18 or "99"?

To remove this ambiguity, you are required to make explicit what you want to convert in this case:

"abc" + str(9)

HTTPS setup in Amazon EC2

An old question but worth mentioning another option in the answers. In case the DNS system of your domain has been defined in Amazon Route 53, you can use Amazon CloudFront service in front of your EC2 and attach a free Amazon SSL certificate to it. This way you will benefit from both having a CDN for a faster content delivery and also securing you domain with HTTPS protocol.

Python - Move and overwrite files and folders

You can use this to copy directory overwriting existing files:

import shutil
shutil.copytree("src", "dst", dirs_exist_ok=True)

dirs_exist_ok argument was added in Python 3.8.

See docs: https://docs.python.org/3/library/shutil.html#shutil.copytree

Detect whether Office is 32bit or 64bit via the registry

@clatonh: this is the path of the registry on my PC: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Registration{90140000-002A-0000-1000-0000000FF1CE} and it's definitely a 32-bit-installation on a 64-bit OS.

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Logical operators for boolean indexing in Pandas

When you say

(a['x']==1) and (a['y']==10)

You are implicitly asking Python to convert (a['x']==1) and (a['y']==10) to boolean values.

NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise

ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().

when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.

Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.

Instead, you must be explicit, by calling the empty(), all() or any() method to indicate which behavior you desire.

In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the & binary operator performs:

(a['x']==1) & (a['y']==10)

returns a boolean array.


By the way, as alexpmil notes, the parentheses are mandatory since & has a higher operator precedence than ==. Without the parentheses, a['x']==1 & a['y']==10 would be evaluated as a['x'] == (1 & a['y']) == 10 which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10). That is an expression of the form Series and Series. The use of and with two Series would again trigger the same ValueError as above. That's why the parentheses are mandatory.

How can I get the last 7 characters of a PHP string?

For simplicity, if you do not want send a message, try this

$new_string = substr( $dynamicstring, -min( strlen( $dynamicstring ), 7 ) );

Access nested dictionary items via a list of keys?

It seems more pythonic to use a for loop. See the quote from What’s New In Python 3.0.

Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.

def nested_get(dic, keys):    
    for key in keys:
        dic = dic[key]
    return dic

Note that the accepted solution doesn't set non-existing nested keys (it raises KeyError). Using the approach below will create non-existing nodes instead:

def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

The code works in both Python 2 and 3.

How to make a gap between two DIV within the same column

I'm assuming you want the two boxes in the sidebar to be next to each other horizontally, so something like this fiddle? That uses inline-block, or you could achieve the same thing by floating the boxes.

EDIT - I've amended the above fiddle to do what I think you want, though your question could really do with being clearer. Similar to @balexandre's answer, though I've used :nth-child(odd) instead. Both will work, or if support for older browsers is important you'll have to stick with another helper class.

.NET Console Application Exit Event

The application is a server which simply runs until the system shuts down or it receives a Ctrl+C or the console window is closed.

Due to the extraordinary nature of the application, it is not feasible to "gracefully" exit. (It may be that I could code another application which would send a "server shutdown" message but that would be overkill for one application and still insufficient for certain circumstances like when the server (Actual OS) is actually shutting down.)

Because of these circumstances I added a "ConsoleCtrlHandler" where I stop my threads and clean up my COM objects etc...


Public Declare Auto Function SetConsoleCtrlHandler Lib "kernel32.dll" (ByVal Handler As HandlerRoutine, ByVal Add As Boolean) As Boolean

Public Delegate Function HandlerRoutine(ByVal CtrlType As CtrlTypes) As Boolean

Public Enum CtrlTypes
  CTRL_C_EVENT = 0
  CTRL_BREAK_EVENT
  CTRL_CLOSE_EVENT
  CTRL_LOGOFF_EVENT = 5
  CTRL_SHUTDOWN_EVENT
End Enum

Public Function ControlHandler(ByVal ctrlType As CtrlTypes) As Boolean
.
.clean up code here
.
End Function

Public Sub Main()
.
.
.
SetConsoleCtrlHandler(New HandlerRoutine(AddressOf ControlHandler), True)
.
.
End Sub

This setup seems to work out perfectly. Here is a link to some C# code for the same thing.

Installing tensorflow with anaconda in windows

The following command from inside your command window (and preferably, conda environment) will work provided you have an Nvidia graphics card.

conda install tensorflow-gpu 

Converting between datetime, Timestamp and datetime64

This post has been up for 4 years and I still struggled with this conversion problem - so the issue is still active in 2017 in some sense. I was somewhat shocked that the numpy documentation does not readily offer a simple conversion algorithm but that's another story.

I have come across another way to do the conversion that only involves modules numpy and datetime, it does not require pandas to be imported which seems to me to be a lot of code to import for such a simple conversion. I noticed that datetime64.astype(datetime.datetime) will return a datetime.datetime object if the original datetime64 is in micro-second units while other units return an integer timestamp. I use module xarray for data I/O from Netcdf files which uses the datetime64 in nanosecond units making the conversion fail unless you first convert to micro-second units. Here is the example conversion code,

import numpy as np
import datetime

def convert_datetime64_to_datetime( usert: np.datetime64 )->datetime.datetime:
    t = np.datetime64( usert, 'us').astype(datetime.datetime)
return t

Its only tested on my machine, which is Python 3.6 with a recent 2017 Anaconda distribution. I have only looked at scalar conversion and have not checked array based conversions although I'm guessing it will be good. Nor have I looked at the numpy datetime64 source code to see if the operation makes sense or not.

How to get file creation date/time in Bash/Debian?

If you really want to achieve that you can use a file watcher like inotifywait.

You watch a directory and you save information about file creations in separate file outside that directory.

while true; do
  change=$(inotifywait -e close_write,moved_to,create .)
  change=${change#./ * }
  if [ "$change" = ".*" ]; then ./scriptToStoreInfoAboutFile; fi
done

As no creation time is stored, you can build your own system based on inotify.

How can I find out which server hosts LDAP on my windows domain?

AD registers Service Location (SRV) resource records in its DNS server which you can query to get the port and the hostname of the responsible LDAP server in your domain.

Just try this on the command-line:

C:\> nslookup 
> set types=all
> _ldap._tcp.<<your.AD.domain>>
_ldap._tcp.<<your.AD.domain>>  SRV service location:
      priority       = 0
      weight         = 100
      port           = 389
      svr hostname   = <<ldap.hostname>>.<<your.AD.domain>>

(provided that your nameserver is the AD nameserver which should be the case for the AD to function properly)

Please see Active Directory SRV Records and Windows 2000 DNS white paper for more information.

disable Bootstrap's Collapse open/close animation

Bootstrap 2 CSS solution:

.collapse {  transition: height 0.01s; }  

NB: setting transition: none disables the collapse functionnality.


Bootstrap 4 solution:

.collapsing {
  transition: none !important;
}

Fast check for NaN in NumPy

There are two general approaches here:

  • Check each array item for nan and take any.
  • Apply some cumulative operation that preserves nans (like sum) and check its result.

While the first approach is certainly the cleanest, the heavy optimization of some of the cumulative operations (particularly the ones that are executed in BLAS, like dot) can make those quite fast. Note that dot, like some other BLAS operations, are multithreaded under certain conditions. This explains the difference in speed between different machines.

enter image description here

import numpy
import perfplot


def min(a):
    return numpy.isnan(numpy.min(a))


def sum(a):
    return numpy.isnan(numpy.sum(a))


def dot(a):
    return numpy.isnan(numpy.dot(a, a))


def any(a):
    return numpy.any(numpy.isnan(a))


def einsum(a):
    return numpy.isnan(numpy.einsum("i->", a))


perfplot.show(
    setup=lambda n: numpy.random.rand(n),
    kernels=[min, sum, dot, any, einsum],
    n_range=[2 ** k for k in range(20)],
    logx=True,
    logy=True,
    xlabel="len(a)",
)

What is the SQL command to return the field names of a table?

PostgreSQL understands the

select column_name from information_schema.columns where table_name = 'myTable'

syntax. If you're working in the psql shell, you can also use

\d myTable

for a description (columns, and their datatypes and constraints)

Find the similarity metric between two strings

Here's what i thought of:

import string

def match(a,b):
    a,b = a.lower(), b.lower()
    error = 0
    for i in string.ascii_lowercase:
            error += abs(a.count(i) - b.count(i))
    total = len(a) + len(b)
    return (total-error)/total

if __name__ == "__main__":
    print(match("pple inc", "Apple Inc."))

How to Execute SQL Server Stored Procedure in SQL Developer?

You need to do this:

    exec procName 
    @parameter_1_Name = 'parameter_1_Value', 
    @parameter_2_name = 'parameter_2_value',
    @parameter_z_name = 'parameter_z_value'

Subset data to contain only columns whose names match a condition

You can also use starts_with and dplyr's select() like so:

df <- df %>% dplyr:: select(starts_with("ABC"))

Simple way to get element by id within a div tag?

Sample Html code   
 <div id="temp">
        F1 <input type="text" value="111"/><br/>
        F2 <input type="text" value="222"/><br/>
        F3 <input type="text" value="333"/><br/>
        Type <select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        </select>
        <input type="button" value="Go" onclick="getVal()">
    </div>

Javascript

    function  getVal()
    {
        var test = document.getElementById("temp").getElementsByTagName("input");
        alert("Number of Input Elements "+test.length);
        for(var i=0;i<test.length;i++)
        {
          if(test[i].type=="text")
          {
            alert(test[i].value);
          }
       }
      test = document.getElementById("temp").getElementsByTagName("select");
      alert("Select box  "+test[0].options[test[0].selectedIndex].text);
    }

By providing different tag names we can get all the values from the div.

Git cli: get user info from username

git config --list

git config -l

will display your username and email together, along with other info

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

simply use local time as the default:

CREATE TABLE whatever(
     ....
     timestamp DATE DEFAULT (datetime('now','localtime')),
     ...
);

Uses of content-disposition in an HTTP response header

Note that RFC 6266 supersedes the RFCs referenced below. Section 7 outlines some of the related security concerns.

The authority on the content-disposition header is RFC 1806 and RFC 2183. People have also devised content-disposition hacking. It is important to note that the content-disposition header is not part of the HTTP 1.1 standard.

The HTTP 1.1 Standard (RFC 2616) also mentions the possible security side effects of content disposition:

15.5 Content-Disposition Issues

RFC 1806 [35], from which the often implemented Content-Disposition
(see section 19.5.1) header in HTTP is derived, has a number of very
serious security considerations. Content-Disposition is not part of
the HTTP standard, but since it is widely implemented, we are
documenting its use and risks for implementors. See RFC 2183 [49]
(which updates RFC 1806) for details.

How to get hex color value rather than RGB value?

This one looks a bit nicer:

var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var r   = parseInt(rgb[0], 10);
var g   = parseInt(rgb[1], 10);
var b   = parseInt(rgb[2], 10);
var hex = '#'+ r.toString(16) + g.toString(16) + b.toString(16);

a more succinct one-liner:

var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
var hex = '#'+ Number(rgb[0]).toString(16) + Number(rgb[1]).toString(16) + Number(rgb[2]).toString(16);

forcing jQuery to always return hex:

$.cssHooks.backgroundColor = {
    get: function(elem) {
        if (elem.currentStyle)
            var bg = elem.currentStyle["backgroundColor"];
        else if (window.getComputedStyle) {
            var bg = document.defaultView.getComputedStyle(elem,
                null).getPropertyValue("background-color");
        }
        if (bg.search("rgb") == -1) {
            return bg;
        } else {
            bg = bg.match(/\d+/g);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[0]) + hex(bg[1]) + hex(bg[2]);
        }
    }
}

Set transparent background using ImageMagick and commandline prompt

If you want to control the level of transparency you can use rgba. where a is the alpha. 0 for transparent and 1 for opaque. Make sure that final output file must have .png extension for transparency.

convert 
  test.png 
    -channel rgba 
    -matte 
    -fuzz 40% 
    -fill "rgba(255,255,255,0.5)" 
    -opaque "rgb(255,255,255)" 
       semi_transparent.png

Access Google's Traffic Data through a Web Service

Maybe you should have a look at Mapquests Traffic API: http://www.mapquestapi.com/traffic/

The webservice is unfortunately only available for some citys in the US, I think. But probably it solves your problem.

Attaching click event to a JQuery object not yet added to the DOM

I am really surprised that no one has posted this yet

$(document).on('click','#my-butt', function(){
   console.log('document is always there');
}) 

If you are unsure about what elements are going to be on that page at that time just attach it to document.

Note: this is sub-optimal from performance perspective - to get maximum speed one should try to attach to the nearest parent of element that is going to be inserted.

Can I use conditional statements with EJS templates (in JMVC)?

Conditionals work if they're structured correctly, I ran into this issue and figured it out.

For conditionals, the tag before else has to be paired with the end tag of the previous if otherwise the statements will evaluate separately and produce an error.

ERROR!

<% if(true){ %>
   <h1>foo</h1>
<% } %>
<% else{ %>
   <h1>bar</h1>
 <% } %>

Correct

<% if(true){ %>
   <h1>foo</h1>
 <% } else{ %>  
   <h1>bar</h1>
<% } %>

hope this helped.

ElasticSearch: Unassigned Shards, how to fix?

In my case, when I create a new index then the default number_of_replicas is set as 1. And the number of nodes in my cluster was only one so there was no extra node to create the replica, so the health was turning to yellow. So when I created the index with settings property and set the number_of_replicas as 0. Then it worked fine. Hope this helps.

PUT /customer
{
    "settings": {
        "number_of_replicas": 0
    }
}

What is the Ruby <=> (spaceship) operator?

Since this operator reduces comparisons to an integer expression, it provides the most general purpose way to sort ascending or descending based on multiple columns/attributes.

For example, if I have an array of objects I can do things like this:

# `sort!` modifies array in place, avoids duplicating if it's large...

# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }

# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }

# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }

# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
      8 * (a.zip   <=> b.zip) +
     -4 * (a.age   <=> b.age) +
      2 * (a.last  <=> b.last) +
          (a.first <=> b.first)
end

This basic pattern can be generalized to sort by any number of columns, in any permutation of ascending/descending on each.

Error 1053 the service did not respond to the start or control request in a timely fashion

After spending some time on the issue, trying solutions that didn't work, I run into this blog. It suggests to wrap the service initialization code in a try/catch block, like this, and adding EventLog

using System;
using System.Diagnostics;
using System.ServiceProcess;

namespace WindowsService
{
    static class Program
    {
        static void Main()
        {
            try
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new Service1() 
                };
                ServiceBase.Run(ServicesToRun);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);
            }
        }
    }
}

Then, uninstall the old service, redeploy the service with these modifications. Start the service and check out the Event Viewer/Application logs. You'll see what the real problem is, which is the underlying reason for the timeout.

Send and receive messages through NSNotificationCenter in Objective-C?

@implementation TestClass

- (void) dealloc
{
    // If you don't remove yourself as an observer, the Notification Center
    // will continue to try and send notification objects to the deallocated
    // object.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (id) init
{
    self = [super init];
    if (!self) return nil;

    // Add this instance of TestClass as an observer of the TestNotification.
    // We tell the notification center to inform us of "TestNotification"
    // notifications using the receiveTestNotification: selector. By
    // specifying object:nil, we tell the notification center that we are not
    // interested in who posted the notification. If you provided an actual
    // object rather than nil, the notification center will only notify you
    // when the notification was posted by that particular object.

    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(receiveTestNotification:) 
        name:@"TestNotification"
        object:nil];

    return self;
}

- (void) receiveTestNotification:(NSNotification *) notification
{
    // [notification name] should always be @"TestNotification"
    // unless you use this method for observation of other notifications
    // as well.

    if ([[notification name] isEqualToString:@"TestNotification"])
        NSLog (@"Successfully received the test notification!");
}

@end

... somewhere else in another class ...

- (void) someMethod
{

    // All instances of TestClass will be notified
    [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"TestNotification" 
        object:self];

}

Add some word to all or some rows in Excel?

  • Select All cells that want to change.
  • right click and select Format cell.
  • In category select Custom.
  • In Type select General and insert this formol ----> "k"@

How to create a label inside an <input> element?

Here is a simple example, all it does is overlay an image (with whatever wording you want). I saw this technique somewhere. I am using the prototype library so you would need to modify if using something else. With the image loading after window.load it fails gracefully if javascript is disabled.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1;" />
    <meta http-equiv="Expires" content="Fri, Jan 1 1981 08:00:00 GMT" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    <style type="text/css" >

        input.searcher
        {
            background-image: url(/images/search_back.png);
            background-repeat: no-repeat;
            background-attachment: scroll;
            background-x-position: left;
            background-y-position: center;
        }

    </style>

    <script type="text/javascript" src="/logist/include/scripts/js/prototype.js" ></script>
</head>
<body>
    <input type="text" id="q" name="q" value="" />

    <script type="text/javascript" language="JavaScript" >
    //  <![CDATA[
        function f(e){
            $('q').removeClassName('searcher');
        }

        function b(e){
            if ( $F('q') == '' )
            {
                $('q').addClassName('searcher');
            }
        }

        Event.observe( 'q', 'focus', f);
        Event.observe( 'q', 'blur', b);
        Event.observe( window, 'load', b);

    //  ]]>
    </script>
</body>
</html>

ActionBarActivity cannot resolve a symbol

If the same error occurs in ADT/Eclipse

Add Action Bar Sherlock library in your project.

Now, to remove the "import The import android.support.v7 cannot be resolved" error download a jar file named as android-support-v7-appcompat.jar and add it in your project lib folder.

This will surely removes your both errors.

Why does Maven have such a bad rep?

Like Glenn, I don't think Maven has a bad rep, but a mixed rep. I have been working for 6 month exclusively trying to migrate a rather big project project to Maven and it clearly shows the limits of the tool.

In my experience, Maven is good for:

  • external dependency management
  • centralized management of the build (pom inheritance)
  • lots of plugins for lots of things
  • very good integration with continuous integration tools
  • very good reporting capabilities (FindBugs, PMD, Checkstyle, Javadoc, ...)

And it has some problems with:

  • all or nothing approach (hard to migrate slowly to Maven)
  • complexe dependencies, intermodules dependencies
  • cyclic dependencies (I know, bad design, but we can't fix 5 years of dev ...)
  • coherence (version ranges don't work the same everywhere)
  • bugs (again with version ranges)
  • reproducible builds (unless you fix the versions number of all the plugins, you can't be sure you will get the same build in 6 months)
  • lack of documentation (the doc is quite good for the basics, but there aren't a lot of examples of how to handle large projects)

To give some context, there are around 30 developers working on this project, and the project has been around for more than 5 years, so: lot of legacy, lots of process already in place, lots of custom proprietary tools already in place. We decided to try migrating to Maven because the cost of maintaining our proprietary tools was getting too high.

List of strings to one string

If you use .net 4.0 you can use a sorter way:

String.Join<string>(String.Empty, los);

loading json data from local file into React JS

My JSON file name: terrifcalculatordata.json

[
    {
      "id": 1,
      "name": "Vigo",
      "picture": "./static/images/vigo.png",
      "charges": "PKR 100 per excess km"
    },
    {
      "id": 2,
      "name": "Mercedes",
      "picture": "./static/images/Marcedes.jpg",
      "charges": "PKR 200 per excess km"
    },
    {
        "id": 3,
        "name": "Lexus",
        "picture": "./static/images/Lexus.jpg",
        "charges": "PKR 150 per excess km"
      }
]

First , import on top:

import calculatorData from "../static/data/terrifcalculatordata.json";

then after return:

  <div>
  {
    calculatorData.map((calculatedata, index) => {
        return (
            <div key={index}>
                <img
                    src={calculatedata.picture}
                    class="d-block"
                    height="170"
                />
                <p>
                    {calculatedata.charges}
                </p>
            </div>
                  

Testing the type of a DOM element in JavaScript

Although the previous answers work perfectly, I will just add another way where the elements can also be classified using the interface they have implemented.

Refer W3 Org for available interfaces

_x000D_
_x000D_
console.log(document.querySelector("#anchorelem") instanceof HTMLAnchorElement);_x000D_
console.log(document.querySelector("#divelem") instanceof HTMLDivElement);_x000D_
console.log(document.querySelector("#buttonelem") instanceof HTMLButtonElement);_x000D_
console.log(document.querySelector("#inputelem") instanceof HTMLInputElement);
_x000D_
<a id="anchorelem" href="">Anchor element</a>_x000D_
<div id="divelem">Div Element</div>_x000D_
<button id="buttonelem">Button Element</button>_x000D_
<br><input id="inputelem">
_x000D_
_x000D_
_x000D_

The interface check can be made in 2 ways as elem instanceof HTMLAnchorElement or elem.constructor.name == "HTMLAnchorElement", both returns true

Core dump file is not generated

Although this isn't going to be a problem for the person who asked the question, because they ran the program that was to produce the core file in a script with the ulimit command, I'd like to document that the ulimit command is specific to the shell in which you run it (like environment variables). I spent way too much time running ulimit and sysctl and stuff in one shell, and the command that I wanted to dump core in the other shell, and wondering why the core file was not produced.

I will be adding it to my bashrc. The sysctl works for all processes once it is issued, but the ulimit only works for the shell in which it is issued (maybe also the descendents too) - but not for other shells that happen to be running.

Best tool for inspecting PDF files?

The object viewer in Acrobat is good but Windjack Solution's PDF Canopener allows better inspection with an eyedropper for selecting objects on page. Also permits modifications to be made to PDF.

http://www.windjack.com/products/pdfcanopener.html

How to URL encode in Python 3?

You’re looking for urllib.parse.urlencode

import urllib.parse

params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'

Importing CSV with line breaks in Excel 2007

Excel is incredibly broken when dealing with CSVs. LibreOffice does a much better job. So, I found out that:

  • The file must be encoded in UTF-8 with BOM, so consider this for all the points below
  • The best result, by far, is achieved by opening it from File Explorer
  • If you open it from within Excel there are two possible outcomes:
    • If it has only ASCII characters, it will most likely work
    • If it has non-ASCII characters, it will mess your line breaks
  • It seems to be heavily dependent on the decimal separator configured in the OS's regional settings, so you have to select the right one
  • I would bet that it may also behave differently depending on OS and Office version

How to find char in string and get all the indexes?

You could try this

def find(ch,string1):
    for i in range(len(string1)):
        if ch == string1[i]:
            pos.append(i)        

Convert a list of characters into a string

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

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

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Plenty of good ideas on this thread. I have a lot of popups in my page for handling user input. What I use, is a combination of disabling the mousewheel and hiding the scrollbar:

this.disableScrollFn= function(e) { 
    e.preventDefault(); e.stopPropagation() 
};
document.body.style.overflow = 'hidden';
$('body').on('mousewheel', this.disableScrollFn);

Advantage of this is we stop the user from scrolling in any possible way, and without having to change css position and top properties. I'm not concerened about touch events, since touch outside would close the popup.

To disable this, upon closing the popup I do the following.

document.body.style.overflow = 'auto';
$('body').off('mousewheel', this.disableScrollFn);

Note, I store a reference to my disableScrollFn on the existing object (in my case a PopupViewModel), for that gets triggered upon closing the popup to have access to disableScrollFn.

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

Adding a caption to an equation in LaTeX

As in this forum post by Gonzalo Medina, a third way may be:

\documentclass{article}
\usepackage{caption}

\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}

\begin{document}

Some text

\begin{equ}[!ht]
  \begin{equation}
    a=b+c
  \end{equation}
\caption{Caption of the equation}
\end{equ}

Some other text
 
\end{document}

More details of the commands used from package caption: here.

A screenshot of the output of the above code:

screenshot of output

Remove URL parameters without refreshing page

//Joraid code is working but i altered as below. it will work if your URL contain "?" mark or not
//replace URL in browser
if(window.location.href.indexOf("?") > -1) {
    var newUrl = refineUrl();
    window.history.pushState("object or string", "Title", "/"+newUrl );
}

function refineUrl()
{
    //get full url
    var url = window.location.href;
    //get url after/  
    var value = url = url.slice( 0, url.indexOf('?') );
    //get the part after before ?
    value  = value.replace('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]','');  
    return value;     
}

shuffling/permutating a DataFrame in pandas

This might be more useful when you want your index shuffled.

def shuffle(df):
    index = list(df.index)
    random.shuffle(index)
    df = df.ix[index]
    df.reset_index()
    return df

It selects new df using new index, then reset them.

How do I store the select column in a variable?

select @EmpID = ID from dbo.Employee

Or

set @EmpID =(select id from dbo.Employee)

Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..

As table type variable do not exist in Oracle and others, you would have to define it:

DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type: variable_name type_name;

-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

-- Where 'n' is the index value

Android RecyclerView addition & removal of items

Here are some visual supplemental examples. See my fuller answer for examples of adding and removing a range.

Add single item

Add "Pig" at index 2.

Insert single item

String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);

Remove single item

Remove "Pig" from the list.

Remove single item

int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);

How can I create database tables from XSD files?

I use XSLT to do that. Write up your XSD then pass your data models through a hand written XSLT that outputs SQL commands. Writing an XSLT is way faster and reusable than a custom program /script you may write.

At least thats how I do it at work, and thanks to that I got time to hang out on SO :)

Best way to compare two complex objects

Serialize both objects, then calculate Hash Code, then compare.

Selecting a row of pandas series/dataframe by integer index

You can take a look at the source code .

DataFrame has a private function _slice() to slice the DataFrame, and it allows the parameter axis to determine which axis to slice. The __getitem__() for DataFrame doesn't set the axis while invoking _slice(). So the _slice() slice it by default axis 0.

You can take a simple experiment, that might help you:

print df._slice(slice(0, 2))
print df._slice(slice(0, 2), 0)
print df._slice(slice(0, 2), 1)

How to get the entire document HTML as a string?

I believe document.documentElement.outerHTML should return that for you.

According to MDN, outerHTML is supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile. outerHTML is in the DOM Parsing and Serialization specification.

The MSDN page on the outerHTML property notes that it is supported in IE 5+. Colin's answer links to the W3C quirksmode page, which offers a good comparison of cross-browser compatibility (for other DOM features too).

Align text in a table header

In HTML5, the easiest, and fastest, way to center your <th>THcontent</th> is to add a colspan like this:

<th colspan="3">Thcontent</th> 

This will work if your table is three columns. So if you have a four-column table, add a colspan of 4, etc.

You can manage the location furthermore in the CSS file while you have put your colspan in HTML like I said.

th { 
    text-align: center; /* Or right or left */
}

Why the switch statement cannot be applied on strings?

    cout << "\nEnter word to select your choice\n"; 
    cout << "ex to exit program (0)\n";     
    cout << "m     to set month(1)\n";
    cout << "y     to set year(2)\n";
    cout << "rm     to return the month(4)\n";
    cout << "ry     to return year(5)\n";
    cout << "pc     to print the calendar for a month(6)\n";
    cout << "fdc      to print the first day of the month(1)\n";
    cin >> c;
    cout << endl;
    a = c.compare("ex") ?c.compare("m") ?c.compare("y") ? c.compare("rm")?c.compare("ry") ? c.compare("pc") ? c.compare("fdc") ? 7 : 6 :  5  : 4 : 3 : 2 : 1 : 0;
    switch (a)
    {
        case 0:
            return 1;

        case 1:                   ///m
        {
            cout << "enter month\n";
            cin >> c;
            cout << endl;
            myCalendar.setMonth(c);
            break;
        }
        case 2:
            cout << "Enter year(yyyy)\n";
            cin >> y;
            cout << endl;
            myCalendar.setYear(y);
            break;
        case 3:
             myCalendar.getMonth();
            break;
        case 4:
            myCalendar.getYear();
        case 5:
            cout << "Enter month and year\n";
            cin >> c >> y;
            cout << endl;
            myCalendar.almanaq(c,y);
            break;
        case 6:
            break;

    }

Explicit vs implicit SQL joins

As Leigh Caldwell has stated, the query optimizer can produce different query plans based on what functionally looks like the same SQL statement. For further reading on this, have a look at the following two blog postings:-

One posting from the Oracle Optimizer Team

Another posting from the "Structured Data" blog

I hope you find this interesting.

Is it better to use path() or url() in urls.py for django 2.0?

The new django.urls.path() function allows a simpler, more readable URL routing syntax. For example, this example from previous Django releases:

url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive)

could be written as:

path('articles/<int:year>/', views.year_archive)

The django.conf.urls.url() function from previous versions is now available as django.urls.re_path(). The old location remains for backwards compatibility, without an imminent deprecation. The old django.conf.urls.include() function is now importable from django.urls so you can use:

from django.urls import include, path, re_path

in the URLconfs. For further reading django doc

Parsing Query String in node.js

Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:

// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');

// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';

// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
  // Parse the request URL. Relative URLs require an origin explicitly.
  const url = new URL(request.url, serverOrigin);
  // Parse the URL query. The leading '?' has to be removed before this.
  const query = parseQuery(url.search.substr(1));
  response.writeHead(200, { 'Content-Type': 'text/plain' });
  response.end(`Hello, ${query.name}!\n`);
});

// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);

// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);

If you run the script above, you can test the server response like this, for example:

curl -q http://localhost:8000/status?name=ryan
Hello, ryan!

How to post JSON to a server using C#?

WARNING! I have a very strong view on this subject.

.NET’s existing web clients are not developer friendly! WebRequest & WebClient are prime examples of "how to frustrate a developer". They are verbose & complicated to work with; when all you want to do is a simple Post request in C#. HttpClient goes some way in addressing these issues, but it still falls short. On top of that Microsoft’s documentation is bad … really bad; unless you want to sift through pages and pages of technical blurb.

Open-source to the rescue. There are three excellent open-source, free NuGet libraries as alternatives. Thank goodness! These are all well supported, documented and yes, easy - correction…super easy - to work with.

There is not much between them, but I would give ServiceStack.Text the slight edge …

  • Github stars are roughly the same.
  • Open Issues & importantly how quickly any issues closed down? ServiceStack takes the award here for the fastest issue resolution & no open issues.
  • Documentation? All have great documentation; however, ServiceStack takes it to the next level & is known for its ‘Golden standard’ for documentation.

Ok - so what does a Post Request in JSON look like within ServiceStack.Text?

var response = "http://example.org/login"
    .PostJsonToUrl(new Login { Username="admin", Password="mypassword" });

That is one line of code. Concise & easy! Compare the above to .NET’s Http libraries.

How to create file execute mode permissions in Git on Windows?

If the files already have the +x flag set, git update-index --chmod=+x does nothing and git thinks there's nothing to commit, even though the flag isn't being saved into the repo.

You must first remove the flag, run the git command, then put the flag back:

chmod -x <file>
git update-index --chmod=+x <file>
chmod +x <file>

then git sees a change and will allow you to commit the change.

Difference between java HH:mm and hh:mm on SimpleDateFormat

Use the built-in localized formats

If this is for showing a time of day to a user, then in at least 19 out of 20 you don’t need to care about kk, HH nor hh. I suggest that you use something like this:

    DateTimeFormatter defaultTimeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
    System.out.format("%s: %s%n",
            Locale.getDefault(), LocalTime.MIN.format(defaultTimeFormatter));

The point is that it gives different output in different default locales. For example:

en_SS: 12:00 AM
fr_BL: 00:00
ps_AF: 0:00
es_CO: 12:00 a.m.

The localized formats have been designed to conform with the expectations of different cultures. So they generally give the user a better experience and they save you of writing a format pattern string, which is always error-prone.

I furthermore suggest that you don’t use SimpleDateFormat. That class is notoriously troublesome and fortunately long outdated. Instead I use java.time, the modern Java date and time API. It is so much nicer to work with.

Four pattern letters for hour: H, h, k and K

Of course if you need to parse a string with a specified format, and also if you have a very specific formatting requirement, it’s good to use a format pattern string. There are actually four different pattern letters to choose from for hour (quoted from the documentation):

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-day (1-24)    number            24
   H       hour-of-day (0-23)          number            0

In practice H and h are used. As far as I know k and K are not (they may just have been included for the sake of completeness). But let’s just see them all in action:

    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofPattern("hh:mm a  HH:mm  kk:mm  KK:mm a", Locale.ENGLISH);
    System.out.println(LocalTime.of(0, 0).format(timeFormatter));
    System.out.println(LocalTime.of(1, 15).format(timeFormatter));
    System.out.println(LocalTime.of(11, 25).format(timeFormatter));
    System.out.println(LocalTime.of(12, 35).format(timeFormatter));
    System.out.println(LocalTime.of(13, 40).format(timeFormatter));
12:00 AM  00:00  24:00  00:00 AM
01:15 AM  01:15  01:15  01:15 AM
11:25 AM  11:25  11:25  11:25 AM
12:35 PM  12:35  12:35  00:35 PM
01:40 PM  13:40  13:40  01:40 PM

If you don’t want the leading zero, just specify one pattern letter, that is h instead of hh or H instead of HH. It will still accept two digits when parsing, and if a number to be printed is greater than 9, two digits will still be printed.

Links

Modifying local variable from inside lambda

If you are on Java 10, you can use var for that:

var ordinal = new Object() { int value; };
list.forEach(s -> {
    s.setOrdinal(ordinal.value);
    ordinal.value++;
});

How to see which flags -march=native will activate?

To see command-line flags, use:

gcc -march=native -E -v - </dev/null 2>&1 | grep cc1

If you want to see the compiler/precompiler defines set by certain parameters, do this:

echo | gcc -dM -E - -march=native

How do you declare an object array in Java?

It's the other way round:

Vehicle[] car = new Vehicle[N];

This makes more sense, as the number of elements in the array isn't part of the type of car, but it is part of the initialization of the array whose reference you're initially assigning to car. You can then reassign it in another statement:

car = new Vehicle[10]; // Creates a new array

(Note that I've changed the type name to match Java naming conventions.)

For further information about arrays, see section 10 of the Java Language Specification.

json_decode() expects parameter 1 to be string, array given

json_decode() is used to decode a json string to an array/data object. json_encode() creates a json string from an array or data. You are using the wrong function my friend, try json_encode();

Apache - MySQL Service detected with wrong path. / Ports already in use

Set XAMPP controlpanel to run under Administrator priviledges.

In Win 7 1. First make sure XAMPP control panel is not running 2. SHIFT+right click on XAMPP Control Panel 3. Click on properties 4. In properties select tab 'Compatibility' 5. On bottom of the tab under 'Privilege level' check the box "Run this program as an administrator" 6. Click OK

this worked for me

How to append contents of multiple files into one file

if you have a certain output type then do something like this

cat /path/to/files/*.txt >> finalout.txt

while-else-loop

I don't see why there is a encapsulation of a while...

Use

//Use the appropriate start and end...
for(int rowIndex = 0, e = 65536; i < e; ++i){        
    if(rowIndex >= dataColLinker.size()) {
         dataColLinker.add(value);
     } else {
        dataColLinker.set(rowIndex, value);
     }    
}

Oracle: how to UPSERT (update or insert into a table?)

None of the answers given so far is safe in the face of concurrent accesses, as pointed out in Tim Sylvester's comment, and will raise exceptions in case of races. To fix that, the insert/update combo must be wrapped in some kind of loop statement, so that in case of an exception the whole thing is retried.

As an example, here's how Grommit's code can be wrapped in a loop to make it safe when run concurrently:

PROCEDURE MyProc (
 ...
) IS
BEGIN
 LOOP
  BEGIN
    MERGE INTO Employee USING dual ON ( "id"=2097153 )
      WHEN MATCHED THEN UPDATE SET "last"="smith" , "name"="john"
      WHEN NOT MATCHED THEN INSERT ("id","last","name") 
        VALUES ( 2097153,"smith", "john" );
    EXIT; -- success? -> exit loop
  EXCEPTION
    WHEN NO_DATA_FOUND THEN -- the entry was concurrently deleted
      NULL; -- exception? -> no op, i.e. continue looping
    WHEN DUP_VAL_ON_INDEX THEN -- an entry was concurrently inserted
      NULL; -- exception? -> no op, i.e. continue looping
  END;
 END LOOP;
END; 

N.B. In transaction mode SERIALIZABLE, which I don't recommend btw, you might run into ORA-08177: can't serialize access for this transaction exceptions instead.

Java - Convert String to valid URI object

The java.net blog had a class the other day that might have done what you want (but it is down right now so I cannot check).

This code here could probably be modified to do what you want:

http://svn.apache.org/repos/asf/incubator/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/uri/UriBuilder.java

Here is the one I was thinking of from java.net: https://urlencodedquerystring.dev.java.net/

Changing the JFrame title

If your class extends JFrame then use this.setTitle(newTitle.getText());

If not and it contains a JFrame let's say named myFrame, then use myFrame.setTitle(newTitle.getText());

Now that you have posted your program, it is obvious that you need only one JTextField to get the new title. These changes will do the trick:

JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
        hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
        newTitle;

and:

    public void createOptions()
    {
        options = new JPanel();
        options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        newTitle = new JTextField("Some Title");
        newTitle.setBounds(80, 40, 225, 20);
        options.add(newTitle);
//        myTitle = new JTextField("My Title...");
//        myTitle.setBounds(80, 40, 225, 20);
//        myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

and:

private void New_Name()
{
    this.setTitle(newTitle.getText());
}

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

What possibilities can cause "Service Unavailable 503" error?

Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...

  1. Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]

  2. Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.

In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.

What is a Crash (technically)... in ASP.NET and what to do if it happens?

Phone number validation Android

I got best solution for international phone number validation and selecting country code below library is justified me Best library for all custom UI and functionality CountryCodePickerProject

https with WCF error: "Could not find base address that matches scheme https"

I think you are trying to configure your service in a similar way to the following config. There is more information here: Specify a Service with Two Endpoints Using Different Binding Values. Also, other than for development, it's probably not a good idea to have both HTTP & HTTPS endpoints to the same service. It kinda defeats the purpose of HTTPS. Hope this helps!

<service type="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null">
    <endpoint
        address="http://computer:8080/Hello"
        contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
        binding="basicHttpBinding"
        bindingConfiguration="shortTimeout"
    </endpoint>
    <endpoint
        address="http://computer:8080/Hello"
        contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
        binding="basicHttpBinding"
        bindingConfiguration="Secure"
     </endpoint>
</service>
<bindings>
    <basicHttpBinding 
        name="shortTimeout"
        timeout="00:00:00:01" 
     />
     <basicHttpBinding 
        name="Secure">
        <Security mode="Transport" />
     </basicHttpBinding>
</bindings>

Wrapping long text without white space inside of a div

white-space: pre-wrap

is what worked for me for <span> and <div>.

Spring Security exclude url patterns in security annotation configurartion

When you say adding antMatchers doesnt help - what do you mean? antMatchers is exactly how you do it. Something like the following should work (obviously changing your URL appropriately):

@Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/authFailure").permitAll()
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()

If you are still not having any joy, then you will need to provide more details/stacktrace etc.

Details of XML to Java config switch is here

complex if statement in python

I think the most pythonic way to do this for me, will be

elif var in [80,443] + range(1024,65535):

although it could take a little time and memory (it's generating numbers from 1024 to 65535). If there's a problem with that, I'll do:

elif 1024 <= var <= 65535 or var in [80,443]:

Select rows having 2 columns equal value

select t.* from table t
    join (
        select C2, C3, C4
        from table
        group by C2, C3, C4
        having count(*) > 1
    ) t2
    using (C2, C3, C4);

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

Lately I created a chrome extension "eXtract Snippet" for copying the inspected element, html and only the relevant css and media queries from a page. Note that this would give you the actual relevant CSS

https://chrome.google.com/webstore/detail/extract-snippet/bfcjfegkgdoomgmofhcidoiampnpbdao?hl=en

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

Basic Ajax send/receive with node.js

  1. Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true); Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. call http://localhost:8001/?getstring=true) or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.

  2. You are correctly calling listen() but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response using response.write() or response.end(). First, you need to include fs=require('fs') to get access to the filesystem. Then, you need to actually serve the file.

  3. XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now, string will be undefined (or perhaps null), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start here.

Here is a simple implementation that incorporates all of the above:

server.js:

var http = require('http'),
      fs = require('fs'),
     url = require('url'),
 choices = ["hello world", "goodbye world"];

http.createServer(function(request, response){
    var path = url.parse(request.url).pathname;
    if(path=="/getstring"){
        console.log("request recieved");
        var string = choices[Math.floor(Math.random()*choices.length)];
        console.log("string '" + string + "' chosen");
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.end(string);
        console.log("string sent");
    }else{
        fs.readFile('./index.html', function(err, file) {  
            if(err) {  
                // write an error response or nothing here  
                return;  
            }  
            response.writeHead(200, { 'Content-Type': 'text/html' });  
            response.end(file, "utf-8");  
        });
    }
}).listen(8001);
console.log("server initialized");

frontend (part of index.html):

function newGame()
{
   guessCnt=0;
   guess="";
   server();
   displayHash();
   displayGuessStr();
   displayGuessCnt();
}

function server()
{
   xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET","http://localhost:8001/getstring", true);
   xmlhttp.onreadystatechange=function(){
         if (xmlhttp.readyState==4 && xmlhttp.status==200){
           string=xmlhttp.responseText;
         }
   }
   xmlhttp.send();
}

You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.

UPDATE: I have changed response.sendHeader() to the new response.writeHead() in the code above !!!

Loop and get key/value pair for JSON array using jQuery

The following should work for a JSON returned string. It will also work for an associative array of data.

for (var key in data)
     alert(key + ' is ' + data[key]);

How to change value of object which is inside an array using JavaScript or jQuery?

It's easily can be accomplished with underscore/lodash library:

  _.chain(projects)
   .find({value:"jquery-ui"})
   .merge({desc: "new desc"});

Docs:
https://lodash.com/docs#find
https://lodash.com/docs#merge

Centering a background image, using CSS

simply replace

background-image:url(../images/images2.jpg) no-repeat;

with

background:url(../images/images2.jpg)  center;

Subtract days, months, years from a date in JavaScript

I implemented a function similar to the momentjs method subtract.

- If you use Javascript

function addDate(dt, amount, dateType) {
  switch (dateType) {
    case 'days':
      return dt.setDate(dt.getDate() + amount) && dt;
    case 'weeks':
      return dt.setDate(dt.getDate() + (7 * amount)) && dt;
    case 'months':
      return dt.setMonth(dt.getMonth() + amount) && dt;
    case 'years':
      return dt.setFullYear( dt.getFullYear() + amount) && dt;
  }
}

example:

let dt = new Date();
dt = addDate(dt, -1, 'months');// use -1 to subtract 

- If you use Typescript:

export enum dateAmountType {
  DAYS,
  WEEKS,
  MONTHS,
  YEARS,
}

export function addDate(dt: Date, amount: number, dateType: dateAmountType): Date {
  switch (dateType) {
    case dateAmountType.DAYS:
      return dt.setDate(dt.getDate() + amount) && dt;
    case dateAmountType.WEEKS:
      return dt.setDate(dt.getDate() + (7 * amount)) && dt;
    case dateAmountType.MONTHS:
      return dt.setMonth(dt.getMonth() + amount) && dt;
    case dateAmountType.YEARS:
      return dt.setFullYear( dt.getFullYear() + amount) && dt;
  }
}

example:

let dt = new Date();
dt = addDate(dt, -1, 'months'); // use -1 to subtract

Optional (unit-tests)

I also made some unit-tests for this function using Jasmine:

  it('addDate() should works properly', () => {
    for (const test of [
      { amount: 1,  dateType: dateAmountType.DAYS,   expect: '2020-04-13'},
      { amount: -1, dateType: dateAmountType.DAYS,   expect: '2020-04-11'},
      { amount: 1,  dateType: dateAmountType.WEEKS,  expect: '2020-04-19'},
      { amount: -1, dateType: dateAmountType.WEEKS,  expect: '2020-04-05'},
      { amount: 1,  dateType: dateAmountType.MONTHS, expect: '2020-05-12'},
      { amount: -1, dateType: dateAmountType.MONTHS, expect: '2020-03-12'},
      { amount: 1,  dateType: dateAmountType.YEARS,  expect: '2021-04-12'},
      { amount: -1, dateType: dateAmountType.YEARS,  expect: '2019-04-12'},
    ]) {
      expect(formatDate(addDate(new Date('2020-04-12'), test.amount, test.dateType))).toBe(test.expect);
    }

  });

To use this test you need this function:

// get format date as 'YYYY-MM-DD'
export function formatDate(date: Date): string {
  const d     = new Date(date);
  let month   = '' + (d.getMonth() + 1);
  let day     = '' + d.getDate();
  const year  = d.getFullYear();

  if (month.length < 2)  {
    month = '0' + month;
  }
  if (day.length < 2) {
    day = '0' + day;
  }

  return [year, month, day].join('-');
}

How to get the selected item of a combo box to a string variable in c#

Test this

  var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
  MessageBox.Show(selected);

VSCode single to double quote automatic replace

For projects that use .editorconfig file by default. The formatter will ignore the rules in the settings and use the rules in .editorconfig, then you can either:

  • Remove .editorconfig file, and use your VSCode settings.
  • Add quote_type = single to the .editorconfig file regarding your file type. You can also set quote_type value to double or auto.

iOS how to set app icon and launch images

Update: Unless you love resizing icons one by one, check out Schmoudi's answer. It's just a lot easier.

Icon sizes

enter image description here

Above image from Designing for iOS 9. They are the same for iOS 10.

How to Set the App Icon

Click Assets.xcassets in the Project navigator and then choose AppIcon.

enter image description here

This will give you an empty app icon set.

enter image description here

Now just drag the right sized image (in .png format) from Finder onto every blank in the app set. The app icon should be all set up now.

How to create the right sized images

The image at the very top tells the pixels sizes for for each point size that is required in iOS 9. However, even if I don't get this answer updated for future versions of iOS, you can still figure out the correct pixel sizes using the method below.

Look at how many points (pt) each blank on the empty image set is. If the image is 1x then the pixels are the same as the points. For 2x double the points and 3x triple the points. So, for example, in the first blank above (29pt 2x) you would need a 58x58 pixel image.

You can start with a 1024x1024 pixel image and then downsize it to the correct sizes. You can do it yourself or there are also websites and scripts for getting the right sizes. Do a search for "ios app icon generator" or something similar.

I don't think the names matter as long as you get the dimensions right, but the general naming convention is as follows:

Icon-29.png      // 29x29 pixels
[email protected]   // 58x58 pixels
[email protected]   // 87x87 pixels

Launch Image

Although you can use an image for the launch screen, consider using a launch screen storyboard file. This will conveniently resize for every size and orientation. Check out this SO answer or the following documentation for help with this.

Useful documentation

The Xcode images in this post were created with Xcode 7.

Make an html number input always display 2 decimal places

an inline solution combines Groot and Ivaylo suggestions in the format below:

onchange="(function(el){el.value=parseFloat(el.value).toFixed(2);})(this)"

encapsulation vs abstraction real world example

Abstraction : you'll never buy a "device", but always buy something more specific : iPhone, GSII, Nokia 3310... Here, iPhone, GSII and N3310 are concrete things, device is abstract.

Encapsulation : you've got several devices, all of them have got a USB port. You don't know what kind of printed circuit there's back, you just have to know you'll be able to plug a USB cable into it.

Abstraction is a concept, which is allowed by encapsulation. My example wasn't the best one (there's no real link between the two blocks).

You can do encapsulation without using abstraction, but if you wanna use some abstraction in your projects, you'll need encapsulation.

Changing the selected option of an HTML Select element

You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:

document.getElementById('sel').value = 'bike';??????????

DEMO

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

How can I display the current branch and folder path in terminal?

Simple way

Open ~/.bash_profile in your favorite editor and add the following content to the bottom.

Git branch in prompt.

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "

Add Git Branch To Terminal Prompt (Mac)

if statement in ng-click

We can add ng-click event conditionally without using disabled class.

HTML:

  <input ng-click="profileForm.$valid && updateMyProfile()" name="submit" id="submit" value="Save" class="submit" type="submit">

How to do jquery code AFTER page loading?

You can avoid get undefined in '$' this way

window.addEventListener("DOMContentLoaded", function(){
    // Your code
});

EDIT: Using 'DOMContentLoaded' is faster than just 'load' because load wait page fully loaded, imgs included... while DomContentLoaded waits just the structure

How to get input field value using PHP

<form action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
<button type="submit" name="ok">OK</button>
</form>
<?php
if(isset($_POST['ok'])){
echo $_POST['subject'];
}
?>

Use Fieldset Legend with bootstrap

In bootstrap 4 it is much easier to have a border on the fieldset that blends with the legend. You don't need custom css to achieve it, it can be done like this:

<fieldset class="border p-2">
   <legend  class="w-auto">Your Legend</legend>
</fieldset>

which looks like this: bootstrap 4 fieldset and legend

Using Linq to get the last N elements of a collection?

coll.Reverse().Take(N).Reverse().ToList();


public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> coll, int N)
{
    return coll.Reverse().Take(N).Reverse();
}

UPDATE: To address clintp's problem: a) Using the TakeLast() method I defined above solves the problem, but if you really want the do it without the extra method, then you just have to recognize that while Enumerable.Reverse() can be used as an extension method, you aren't required to use it that way:

List<string> mystring = new List<string>() { "one", "two", "three" }; 
mystring = Enumerable.Reverse(mystring).Take(2).Reverse().ToList();

How to prevent line-break in a column of a table cell (not a single cell)?

Just add

style="white-space:nowrap;"

Example:

<table class="blueTable" style="white-space:nowrap;">
   <tr>
      <td>My name is good</td>
    </tr>
 </table>

Making an array of integers in iOS

You can use a plain old C array:

NSInteger myIntegers[40];

for (NSInteger i = 0; i < 40; i++)
    myIntegers[i] = i;

// to get one of them
NSLog (@"The 4th integer is: %d", myIntegers[3]);

Or, you can use an NSArray or NSMutableArray, but here you will need to wrap up each integer inside an NSNumber instance (because NSArray objects are designed to hold class instances).

NSMutableArray *myIntegers = [NSMutableArray array];

for (NSInteger i = 0; i < 40; i++)
    [myIntegers addObject:[NSNumber numberWithInteger:i]];

// to get one of them
NSLog (@"The 4th integer is: %@", [myIntegers objectAtIndex:3]);

// or
NSLog (@"The 4th integer is: %d", [[myIntegers objectAtIndex:3] integerValue]);

How to set border's thickness in percentages?

You can use em for percentage instead of pixels,

Example:

border:10PX dotted #c1a9ff; /* In Pixels */
border:0.75em dotted #c1a9ff; /* Exact same as above in Percentage */

Replacing all non-alphanumeric characters with empty strings

Use [^A-Za-z0-9].

Note: removed the space since that is not typically considered alphanumeric.

Child element click event trigger the parent click event

I faced the same problem and solve it by this method. html :

<div id="parentDiv">
   <div id="childDiv">
     AAA
   </div>
    BBBB
</div>

JS:

$(document).ready(function(){
 $("#parentDiv").click(function(e){
   if(e.target.id=="childDiv"){
     childEvent();
   } else {
     parentEvent();
   }
 });
});

function childEvent(){
    alert("child event");
}

function parentEvent(){
    alert("paren event");
}

Converting string to date in mongodb

In my case I have succeed with the following solution for converting field ClockInTime from ClockTime collection from string to Date type:

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);
    db.ClockTime.save(doc); 
    })

Should we @Override an interface's method implementation?

For the interface, using @Override caused compile error. So, I had to remove it.

Error message went "The method getAllProducts() of type InMemoryProductRepository must override a superclass method".

It also read "One quick fix available: Remove @Override annotation."

It was on Eclipse 4.6.3, JDK 1.8.0_144.

How to change the text color of first select option

If the first item is to be used as a placeholder (empty value) and your select is required then you can use the :invalid pseudo-class to target it.

_x000D_
_x000D_
select {_x000D_
  -webkit-appearance: menulist-button;_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
select:invalid {_x000D_
  color: green;_x000D_
}
_x000D_
<select required>_x000D_
  <option value="">Item1</option>_x000D_
  <option value="Item2">Item2</option>_x000D_
  <option value="Item3">Item3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Git: Merge a Remote branch locally

You can reference those remote tracking branches ~(listed with git branch -r) with the name of their remote.

You need to fetch the remote branch:

git fetch origin aRemoteBranch

If you want to merge one of those remote branches on your local branch:

git checkout master
git merge origin/aRemoteBranch

Note 1: For a large repo with a long history, you will want to add the --depth=1 option when you use git fetch.

Note 2: These commands also work with other remote repos so you can setup an origin and an upstream if you are working on a fork.

Note 3: user3265569 suggests the following alias in the comments:

From aLocalBranch, run git combine remoteBranch
Alias:

combine = !git fetch origin ${1} && git merge origin/${1}

Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:

git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch

The idea here, is to merge "one of your local branch" (here anotherLocalBranch) to a remote branch (origin/aBranch).
For that, you create first "myBranch" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch part.
And then you can merge anotherLocalBranch to it (to myBranch).

How can I make a time delay in Python?

You also can try this:

import time
# The time now
start = time.time() 
while time.time() - start < 10: # Run 1- seconds
    pass
# Do the job

Now the shell will not crash or not react.

Java: How to stop thread?

JavaSun recomendation is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread to terminate.

You can that way kill the other process, and the current one afterwards.

DevTools failed to load SourceMap: Could not load content for chrome-extension

For me, the problem was caused not by the app in development itself but by the Chrome extension: React Developer Tool. I solved partially that by right-clicking the extension icon in the toolbar, clicking "manage extension" (I'm freely translating menu text here since my browser language is in Brazilian Portuguese), then enabling "Allow access to files URLs." But this measure fixed just some of the alerts.

I found issues in the react repo that suggests the cause is a bug in their extension and is planned to be corrected soon - see issues 20091 and 20075.

You can confirm is extension-related by accessing your app in an anonymous tab without any extension enabled.

Why use a ReentrantLock if one can use synchronized(this)?

From oracle documentation page about ReentrantLock:

A reentrant mutual exclusion Lock with the same basic behaviour and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

  1. A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.

  2. The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order.

ReentrantLock key features as per this article

  1. Ability to lock interruptibly.
  2. Ability to timeout while waiting for lock.
  3. Power to create fair lock.
  4. API to get list of waiting thread for lock.
  5. Flexibility to try for lock without blocking.

You can use ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock to further acquire control on granular locking on read and write operations.

Have a look at this article by Benjamen on usage of different type of ReentrantLocks

How to get Maven project version to the bash command line

One alternative would be to parse with yq (https://github.com/kislyuk/yq) like so:

cat pom.xml | xq -r '.project.version'

Notice the executable is xq not yq

To get xq, install yq like so pip install yq

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

Spring Could not Resolve placeholder

enter image description hereI know It is an old message , but i want to add my case.

If you use more than one profile(dev,test,prod...), check your execute profile.

How to extract .war files in java? ZIP vs JAR

Just rename the .war into .jar and unzip it using Winrar (or any other archive manager).

Maximum request length exceeded.

And just in case someone's looking for a way to handle this exception and show a meaningful explanation to the user (something like "You're uploading a file that is too big"):

//Global.asax
private void Application_Error(object sender, EventArgs e)
{
    var ex = Server.GetLastError();
    var httpException = ex as HttpException ?? ex.InnerException as HttpException;
    if(httpException == null) return;

    if (((System.Web.HttpException)httpException.InnerException).WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
    {
        //handle the error
        Response.Write("Too big a file, dude"); //for example
    }
}

(ASP.NET 4 or later required)

show dbs gives "Not Authorized to execute command" error

It was Docker running in the background in my case. If you have Docker installed, you may wanna close it and try again.

Convert Rtf to HTML

If you don't mind getting your hands dirty, it isn't that difficult to write an RTF to HTML converter.

Writing a general purpose RTF->HTML converter would be somewhat complicated because you would need to deal with hundreds of RTF verbs. However, in your case you are only dealing with those verbs used specifically by Crystal Reports. I'll bet the standard RTF coding generated by Crystal doesn't vary much from report to report.

I wrote an RTF to HTML converter in C++, but it only deals with basic formatting like fonts, paragraph alignments, etc. My translator basically strips out any specialized formatting that it isn't prepared to deal with. It took about 400 lines of C++. It basically scans the text for RTF tags and replaces them with equivalent HTML tags. RTF tags that aren't in my list are simply stripped out. A regex function is really helpful when writing such a converter.

How to apply shell command to each line of a command output?

You can use a for loop:

for file in * ; do
   echo "$file"
done

Note that if the command in question accepts multiple arguments, then using xargs is almost always more efficient as it only has to spawn the utility in question once instead of multiple times.

Invoking a static method using reflection

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

How to allow only numbers in textbox in mvc4 razor

function NumValidate(e) {
    var evt = (e) ? e : window.event;
    var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        alert('Only Number ');
        return false;
    }    return true;
}  function NumValidateWithDecimal(e) {

var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;

if (!(charCode == 8 || charCode == 46 || charCode == 110 || charCode == 13 || charCode == 9) && (charCode < 48 || charCode > 57)) {
    alert('Only Number With desimal e.g.: 0.0');
    return false;
}
else {
    return true;
} } function onlyAlphabets(e) {
try {
    if (window.event) {
        var charCode = window.event.keyCode;
    }
    else if (e) {
        var charCode = e.which;
    }
    else { return true; }

    if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 46) || (charCode == 32))
        return true;
    else
        alert("Only text And White Space And . Allow");
    return false;

}
catch (err) {
    alert(err.Description);
}} function checkAlphaNumeric(e) {

if (window.event) {
    var charCode = window.event.keyCode;
}
else if (e) {
    var charCode = e.which;
}
else { return true; }

if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode == 32) || (charCode >= 97 && charCode <= 122)) {
    return true;
} else {
    alert('Only Text And Number');
    return false;
}}

Upload failed You need to use a different version code for your APK because you already have one with version code 2

If you're using Android Studio, you could go:

Build -> Edit Flavors

And change the Version Code and Name from there.

enter image description here

How do function pointers in C work?

Function pointer is usually defined by typedef, and used as param & return value.

Above answers already explained a lot, I just give a full example:

#include <stdio.h>

#define NUM_A 1
#define NUM_B 2

// define a function pointer type
typedef int (*two_num_operation)(int, int);

// an actual standalone function
static int sum(int a, int b) {
    return a + b;
}

// use function pointer as param,
static int sum_via_pointer(int a, int b, two_num_operation funp) {
    return (*funp)(a, b);
}

// use function pointer as return value,
static two_num_operation get_sum_fun() {
    return &sum;
}

// test - use function pointer as variable,
void test_pointer_as_variable() {
    // create a pointer to function,
    two_num_operation sum_p = &sum;
    // call function via pointer
    printf("pointer as variable:\t %d + %d = %d\n", NUM_A, NUM_B, (*sum_p)(NUM_A, NUM_B));
}

// test - use function pointer as param,
void test_pointer_as_param() {
    printf("pointer as param:\t %d + %d = %d\n", NUM_A, NUM_B, sum_via_pointer(NUM_A, NUM_B, &sum));
}

// test - use function pointer as return value,
void test_pointer_as_return_value() {
    printf("pointer as return value:\t %d + %d = %d\n", NUM_A, NUM_B, (*get_sum_fun())(NUM_A, NUM_B));
}

int main() {
    test_pointer_as_variable();
    test_pointer_as_param();
    test_pointer_as_return_value();

    return 0;
}

What is the difference between document.location.href and document.location?

document.location is a synonym for window.location that has been deprecated for almost as long as JavaScript has existed. Don't use it.

location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string. Assigning a string to either is defined to cause the same kind of navigation, so take your pick.

I consider writing to location.href = something to be marginally better as it's slightly more explicit about what it's doing. You generally want to avoid just location = something as it looks misleadingly like a variable assignment. window.location = something is fine though.

How do I rewrite URLs in a proxy response in NGINX

We should first read the documentation on proxy_pass carefully and fully.

The URI passed to upstream server is determined based on whether "proxy_pass" directive is used with URI or not. Trailing slash in proxy_pass directive means that URI is present and equal to /. Absense of trailing slash means hat URI is absent.

Proxy_pass with URI:

location /some_dir/ {
    proxy_pass http://some_server/;
}

With the above, there's the following proxy:

http:// your_server/some_dir/ some_subdir/some_file ->
http:// some_server/          some_subdir/some_file

Basically, /some_dir/ gets replaced by / to change the request path from /some_dir/some_subdir/some_file to /some_subdir/some_file.

Proxy_pass without URI:

location /some_dir/ {
    proxy_pass http://some_server;
}

With the second (no trailing slash): the proxy goes like this:

http:// your_server /some_dir/some_subdir/some_file ->
http:// some_server /some_dir/some_subdir/some_file

Basically, the full original request path gets passed on without changes.


So, in your case, it seems you should just drop the trailing slash to get what you want.


Caveat

Note that automatic rewrite only works if you don't use variables in proxy_pass. If you use variables, you should do rewrite yourself:

location /some_dir/ {
  rewrite    /some_dir/(.*) /$1 break;
  proxy_pass $upstream_server;
}

There are other cases where rewrite wouldn't work, that's why reading documentation is a must.


Edit

Reading your question again, it seems I may have missed that you just want to edit the html output.

For that, you can use the sub_filter directive. Something like ...

location /admin/ {
    proxy_pass http://localhost:8080/;
    sub_filter "http://your_server/" "http://your_server/admin/";
    sub_filter_once off;
}

Basically, the string you want to replace and the replacement string

Set start value for column with autoincrement

From Resetting SQL Server Identity Columns:

Retrieving the identity for the table Employees:

DBCC checkident ('Employees')

Repairing the identity seed (if for some reason the database is inserting duplicate identities):

DBCC checkident ('Employees', reseed)

Changing the identity seed for the table Employees to 1000:

DBCC checkident ('Employees', reseed, 1000)

The next row inserted will begin at 1001.