Programs & Examples On #Gears

Relative frequencies / proportions with dplyr

This answer is based upon Matifou's answer.

First I modified it to ensure that I don't get the freq column returned as a scientific notation column by using the scipen option.

Then I multiple the answer by 100 to get a percent rather than decimal to make the freq column easier to read as a percentage.

getOption("scipen") 
options("scipen"=10) 
mtcars %>%
count(am, gear) %>% 
mutate(freq = (n / sum(n)) * 100)

Disable vertical sync for glxgears

I found a solution that works in the intel card and in the nvidia card using Bumblebee.

> export vblank_mode=0
glxgears
...
optirun glxgears
...
export vblank_mode=1

How to calculate distance from Wifi router using Signal Strength?

K = 32.44
FSPL = Ptx - CLtx + AGtx + AGrx - CLrx - Prx - FM
d = 10 ^ (( FSPL - K - 20 log10( f )) / 20 )

Here:

  • K - constant (32.44, when f in MHz and d in km, change to -27.55 when f in MHz and d in m)
  • FSPL - Free Space Path Loss
  • Ptx - transmitter power, dBm ( up to 20 dBm (100mW) )
  • CLtx, CLrx - cable loss at transmitter and receiver, dB ( 0, if no cables )
  • AGtx, AGrx - antenna gain at transmitter and receiver, dBi
  • Prx - receiver sensitivity, dBm ( down to -100 dBm (0.1pW) )
  • FM - fade margin, dB ( more than 14 dB (normal) or more than 22 dB (good))
  • f - signal frequency, MHz
  • d - distance, m or km (depends on value of K)

Note: there is an error in formulas from TP-Link support site (mising ^).

Substitute Prx with received signal strength to get a distance from WiFi AP.

Example: Ptx = 16 dBm, AGtx = 2 dBi, AGrx = 0, Prx = -51 dBm (received signal strength), CLtx = 0, CLrx = 0, f = 2442 MHz (7'th 802.11bgn channel), FM = 22. Result: FSPL = 47 dB, d = 2.1865 m

Note: FM (fade margin) seems to be irrelevant here, but I'm leaving it because of the original formula.

You should take into acount walls, table http://www.liveport.com/wifi-signal-attenuation may help.

Example: (previous data) + one wooden wall ( 5 dB, from the table ). Result: FSPL = FSPL - 5 dB = 44 dB, d = 1.548 m

Also please note, that antena gain dosn't add power - it describes the shape of radiation pattern (donut in case of omnidirectional antena, zeppelin in case of directional antenna, etc).

None of this takes into account signal reflections (don't have an idea how to do this). Probably noise is also missing. So this math may be good only for rough distance estimation.

Reordering arrays

The syntax of Array.splice is:

yourArray.splice(index, howmany, element1, /*.....,*/ elementX);

Where:

  • index is the position in the array you want to start removing elements from
  • howmany is how many elements you want to remove from index
  • element1, ..., elementX are elements you want inserted from position index.

This means that splice() can be used to remove elements, add elements, or replace elements in an array, depending on the arguments you pass.

Note that it returns an array of the removed elements.

Something nice and generic would be:

Array.prototype.move = function (from, to) {
  this.splice(to, 0, this.splice(from, 1)[0]);
};

Then just use:

var ar = [1,2,3,4,5];
ar.move(0,3);
alert(ar) // 2,3,4,1,5

Diagram:

Algorithm diagram

How does Google calculate my location on a desktop?

I've finally worked it out. The biggest issue is how they managed to work out what Wireless networks were around me and how do they know where these networks are.

It "seems" to be something similar to this:

  1. skyhookwireless.com [or similar] Company has mapped the location of many wireless access points, i assume by similar means that google streetview went around and picked up all the photos.
  2. Using Google gears and my browser, we can report which wireless networks i see and have around me
  3. Compare these wireless points to their geolocation and triangulate my position.

Reference: Slashdot

Is there a good jQuery Drag-and-drop file upload plugin?

Shameless Plug:

Filepicker.io handles uploading for you and returns a url. It supports drag/drop, cross browser. Also, people can upload from Dropbox/Facebook/Gmail which is super handy on a mobile device.

Dynamically set value of a file input

It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.

However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.

Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.

ImageView - have height match width?

For people passing by now, in 2017, the new best way to achieve what you want is by using ConstraintLayout like this:

<ImageView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scaleType="centerCrop"
    app:layout_constraintDimensionRatio="1:1" />

And don't forget to add constraints to all of the four directions as needed by your layout.

Build a Responsive UI with ConstraintLayout

Furthermore, by now, PercentRelativeLayout has been deprecated (see Android documentation).

How to use XPath contains() here?

I already gave my +1 to Jeff Yates' solution.

Here is a quick explanation why your approach does not work. This:

//ul[@class='featureList' and contains(li, 'Model')]

encounters a limitation of the contains() function (or any other string function in XPath, for that matter).

The first argument is supposed to be a string. If you feed it a node list (giving it "li" does that), a conversion to string must take place. But this conversion is done for the first node in the list only.

In your case the first node in the list is <li><b>Type:</b> Clip Fan</li> (converted to a string: "Type: Clip Fan") which means that this:

//ul[@class='featureList' and contains(li, 'Type')]

would actually select a node!

Vue - Deep watching an array of objects and calculating the change?

I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.

Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.

new Vue({
  methods: {
    setValue: function() {
      this.$data.oldPeople = _.cloneDeep(this.$data.people);
    },
  },
  mounted() {
    this.setValue();
  },
  el: '#app',
  data: {
    people: [
      {id: 0, name: 'Bob', age: 27},
      {id: 1, name: 'Frank', age: 32},
      {id: 2, name: 'Joe', age: 38}
    ],
    oldPeople: []
  },
  watch: {
    people: {
      handler: function (after, before) {
        // Return the object that changed
        var vm = this;
        let changed = after.filter( function( p, idx ) {
          return Object.keys(p).some( function( prop ) {
            return p[prop] !== vm.$data.oldPeople[idx][prop];
          })
        })
        // Log it
        vm.setValue();
        console.log(changed)
      },
      deep: true,
    }
  }
})

See the updated codepen

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

find vs find_by vs where

where returns ActiveRecord::Relation

Now take a look at find_by implementation:

def find_by
  where(*args).take
end

As you can see find_by is the same as where but it returns only one record. This method should be used for getting 1 record and where should be used for getting all records with some conditions.

Invalid date in safari

Use the below format, it would work on all the browsers

var year = 2016;
var month = 02;           // month varies from 0-11 (Jan-Dec)
var day = 23;

month = month<10?"0"+month:month;        // to ensure YYYY-MM-DD format
day = day<10?"0"+day:day;

dateObj = new Date(year+"-"+month+"-"+day);

alert(dateObj); 

//Your output would look like this "Wed Mar 23 2016 00:00:00 GMT+0530 (IST)"

//Note this would be in the current timezone in this case denoted by IST, to convert to UTC timezone you can include

alert(dateObj.toUTCSting);

//Your output now would like this "Tue, 22 Mar 2016 18:30:00 GMT"

Note that now the dateObj shows the time in GMT format, also note that the date and time have been changed correspondingly.

The "toUTCSting" function retrieves the corresponding time at the Greenwich meridian. This it accomplishes by establishing the time difference between your current timezone to the Greenwich Meridian timezone.

In the above case the time before conversion was 00:00 hours and minutes on the 23rd of March in the year 2016. And after conversion from GMT+0530 (IST) hours to GMT (it basically subtracts 5.30 hours from the given timestamp in this case) the time reflects 18.30 hours on the 22nd of March in the year 2016 (exactly 5.30 hours behind the first time).

Further to convert any date object to timestamp you can use

alert(dateObj.getTime());

//output would look something similar to this "1458671400000"

This would give you the unique timestamp of the time

Vertical Menu in Bootstrap

The "nav nav-list" class of Twiter Bootstrap 2.0 is handy for building a side bar.

You can see a lot of documentation at http://www.w3resource.com/twitter-bootstrap/nav-tabs-and-pills-tutorial.php

How to include static library in makefile

use

LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Public Function GetRange(ByVal sListName As String) As String

Dim oListObject As ListObject
Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook

For Each ws In wb.Sheets
    For Each oListObject In ws.ListObjects
        If oListObject.Name = sListName Then
            GetRange = "[" & ws.Name & "$" & Replace(oListObject.Range.Address, "$", "") & "]"
        Exit Function
        End If
    Next oListObject
Next ws


End Function

In your SQL use it like this

sSQL = "Select * from " & GetRange("NameOfTable") & ""

Adding form action in html in laravel

For Laravel 2020. Ok, an example:

<form class="modal-content animate" action="{{ url('login_kun')  }}" method="post">
  @csrf   // !!! attention - this string is a must 
....
 </form>

And then in web.php:

Route::post("/login_kun", "LoginController@login");

And one more in new created LoginController:

 public function login(Request $request){
    dd($request->all());
}

and you are done my friend.

How to understand nil vs. empty vs. blank in Ruby

enter image description here

  • Everything that is nil? is blank?
  • Everything that is empty? is blank?
  • Nothing that is empty? is nil?
  • Nothing that is nil? is empty?

tl;dr -- only use blank? & present? unless you want to distinguish between "" and " "

Alarm Manager Example

Alarm Manager:

Add To XML Layout (*init these view on create in main activity)

  <TimePicker
    android:id="@+id/timepicker"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"></TimePicker>

  <Button
    android:id="@+id/btn_start"
    android:text="start Alarm"
    android:onClick="start_alarm_event"
    android:layout_width="match_parent"
    android:layout_height="52dp" />

Add To Manifest (Inside application tag && outside activity)

 <receiver android:name=".AlarmBroadcastManager"
        android:enabled="true"
        android:exported="true"/>

Create AlarmBroadcastManager Class(inherit it from BroadcastReceiver)

 public class AlarmBroadcastManager extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
      MediaPlayer mediaPlayer=MediaPlayer.create(context,Settings.System.DEFAULT_RINGTONE_URI);
      mediaPlayer.start();
    }
 }

In Main Activity (Add these Functions):

 @RequiresApi(api = Build.VERSION_CODES.M)
 public  void start_alarm_event(View view){
    Calendar calendar=Calendar.getInstance();
    calendar.set(
    calendar.get(Calendar.YEAR),
    calendar.get(Calendar.MONTH),
    calendar.get(Calendar.DAY_OF_MONTH),
    timePicker.getHour(),
    timePicker.getMinute(),
    0
    );
    setAlarm(calendar.getTimeInMillis());
 }

 public void setAlarm(long timeInMillis){
    AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent=new Intent(this,AlarmBroadcastManager.class);
    PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,timeInMillis,AlarmManager.INTERVAL_DAY,pendingIntent);
    Toast.makeText(getApplicationContext(),"Alarm is Set",Toast.LENGTH_SHORT).show();


 }

How to style an asp.net menu with CSS

Alright, so there are obviously not a whole lot of people who have tried the .NET 4 menu as of today. Not surprising as the final version was released a couple days ago. I seem to be the first one to ever report on what seems to be a bug. I will report this to MS if I find the time, but given MS track-record of not paying attention to bug reports I'm not rushing this.

Anyway, at this point the least worst solution is to copy and paste the CSS styles generated by the control (check the header) into your own stylesheet and modify it from there. After you're done doing this, don't forget to set IncludeStyleBlock="False" on your menu so as to prevent the automatic generation of the CSS, since we'll be using the copied block from now on. Conceptually this is not correct as your application shouldn't rely on automatically generated code, but that's the only option I can think of.

AngularJS : How to watch service variables?

I came to this question but it turned out my problem was that I was using setInterval when I should have been using the angular $interval provider. This is also the case for setTimeout (use $timeout instead). I know it's not the answer to the OP's question, but it might help some, as it helped me.

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

How to set Spinner default value to null?

Using a custom spinner layout like this:

<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/spinnerTarget"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textSize="14dp"         
          android:textColor="#000000"/>

In the activity:

    // populate the list
    ArrayList<String> dataList = new ArrayList<String>();
    for (int i = 0; i < 4; i++) {
        dataList.add("Item");
    }

    // set custom layout spinner_layout.xml and adapter
    Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerObject.setAdapter(dataAdapter);
    spinnerObject.setOnTouchListener(new View.OnTouchListener() { 

        public boolean onTouch(View v, MotionEvent event) {
            // to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
            TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
            spinnerTarget.setText(spinnerObject.getSelectedItem().toString());

            return false;
        }

    });
    spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                private boolean selectionControl = true;

                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                    // just the first time
                    if(selectionControl){

                        // find TextView in layout 
                        TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
                        // set spinner text empty
                        spinnerTarget.setText("");
                        selectionControl = false;
                    }
                    else{
                        // select object
                    }
                }

                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

Sleep Command in T-SQL?

Here is a very simple piece of C# code to test the CommandTimeout with. It creates a new command which will wait for 2 seconds. Set the CommandTimeout to 1 second and you will see an exception when running it. Setting the CommandTimeout to either 0 or something higher than 2 will run fine. By the way, the default CommandTimeout is 30 seconds.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data.SqlClient;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var builder = new SqlConnectionStringBuilder();
      builder.DataSource = "localhost";
      builder.IntegratedSecurity = true;
      builder.InitialCatalog = "master";

      var connectionString = builder.ConnectionString;

      using (var connection = new SqlConnection(connectionString))
      {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
          command.CommandText = "WAITFOR DELAY '00:00:02'";
          command.CommandTimeout = 1;

          command.ExecuteNonQuery();
        }
      }
    }
  }
}

C# Remove object from list of objects

If ChunkList is List<Chunk>, you can use the RemoveAll method:

ChunkList.RemoveAll(chunk => chunk.UniqueID == ChunkID);

Hadoop "Unable to load native-hadoop library for your platform" warning

Firstly: You can modify the glibc version.CentOS provides safe softwares tranditionally,it also means the version is old such as glibc,protobuf ...

ldd --version
ldd /opt/hadoop/lib/native/libhadoop.so.1.0.0

You can compare the version of current glibc with needed glibc.

Secondly: If the version of current glibc is old,you can update the glibc. DownLoad Glibc

If the version of current glibc id right,you can append word native to your HADOOP_OPTS

export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib"

Wrapping text inside input type="text" element HTML/CSS

Word Break will mimic some of the intent

_x000D_
_x000D_
    input[type=text] {
        word-wrap: break-word;
        word-break: break-all;
        height: 80px;
    }
_x000D_
<input type="text" value="The quick brown fox jumped over the lazy dog" />
_x000D_
_x000D_
_x000D_

As a workaround, this solution lost its effectiveness on some browsers. Please check the demo: http://cssdesk.com/dbCSQ

How do I check if an array includes a value in JavaScript?

Let's say you've defined an array like so:

const array = [1, 2, 3, 4]

Below are three ways of checking whether there is a 3 in there. All of them return either true or false.

Native Array method (since ES2016) (compatibility table)

array.includes(3) // true

As custom Array method (pre ES2016)

// Prefixing the method with '_' to avoid name clashes
Object.defineProperty(Array.prototype, '_includes', { value: function (v) { return this.indexOf(v) !== -1 }})
array._includes(3) // true

Simple function

const includes = (a, v) => a.indexOf(v) !== -1
includes(array, 3) // true

What is the purpose of the single underscore "_" variable in Python?

It's just a variable name, and it's conventional in python to use _ for throwaway variables. It just indicates that the loop variable isn't actually used.

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

Remove row lines in twitter bootstrap

bootstrap.min.css is more specific than your own stylesheet if you just use .table td. So use this instead:

.table>tbody>tr>th, .table>tbody>tr>td {
    border-top: none;
}

How to show code but hide output in RMarkdown?

To hide warnings, you can also do {r, warning=FALSE}

How to convert binary string value to decimal

According to this : 1 we can write this help function :

    public static int convertBinaryToDecimal(String str) {
        int result = 0;
        for (int i = 0; i < str.length(); i++) {
            int value = Character.getNumericValue(str.charAt(i));
            result = result * 2 + value;
        }
        return result;
    }

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

This is LITERALLY 1 google query away, but here goes:

http://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx

Understanding legacy document modes

Use the following value to display the webpage in edge mode, which is the highest standards mode supported by Internet Explorer, from Internet Explorer 6 through IE11.

<meta http-equiv="x-ua-compatible" content="IE=edge"

Note that this is functionally equivalent to using the HTML5 doctype. It places Internet Explorer into the highest supported document mode. Edge most is most useful for regularly maintained websites that are routinely tested for interoperability between multiple browsers, including Internet Explorer.

Note Starting with IE11, edge mode is considered the preferred document mode. (In earlier versions, it was considered experimental.) To learn more, see Document modes are deprecated. Starting with Windows Internet Explorer 8, some web developers used the edge mode meta element to hide the Compatibility View button on the address bar. As of IE11, this is no longer necessary as the button has been removed from the address bar. Because it forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use edge mode for all pages viewed with Internet Explorer. Don't do this, as the X-UA-Compatible header is only supported starting with Internet Explorer 8.

Tip If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration, as shown in the earlier example.

Also among the search results is:

How do I convert ticks to minutes?

The clearest way in my view is to use TimeSpan.FromTicks and then convert that to minutes:

TimeSpan ts = TimeSpan.FromTicks(ticks);
double minutes = ts.TotalMinutes;

git pull remote branch cannot find remote ref

I had this issue when after rebooted and the last copy of VSCode reopened. The above fix did not work, but when I closed and reopened VSCode via explorer it worked. Here are the steps I did:

_x000D_
_x000D_
//received fatal error_x000D_
git remote remove origin_x000D_
git init_x000D_
git remote add origin git@github:<yoursite>/<your project>.git_x000D_
// still received an err _x000D_
//restarted VSCode and folder via IE _x000D_
//updated one char and resaved the index.html  _x000D_
git add ._x000D_
git commit -m "blah"_x000D_
git push origin master
_x000D_
_x000D_
_x000D_

How to select min and max values of a column in a datatable?

var min = dt.AsEnumerable().Min(row => row["AccountLevel"]);
var max = dt.AsEnumerable().Max(row => row["AccountLevel"]);

How do I implement a callback in PHP?

The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a function pointer, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:

$cb1 = 'someGlobalFunction';
$cb2 = ['ClassName', 'someStaticMethod'];
$cb3 = [$object, 'somePublicMethod'];

// this syntax is callable since PHP 5.2.3 but a string containing it
// cannot be called directly
$cb2 = 'ClassName::someStaticMethod';
$cb2(); // fatal error

// legacy syntax for PHP 4
$cb3 = array(&$object, 'somePublicMethod');

This is a safe way to use callable values in general:

if (is_callable($cb2)) {
    // Autoloading will be invoked to load the class "ClassName" if it's not
    // yet defined, and PHP will check that the class has a method
    // "someStaticMethod". Note that is_callable() will NOT verify that the
    // method can safely be executed in static context.

    $returnValue = call_user_func($cb2, $arg1, $arg2);
}

Modern PHP versions allow the first three formats above to be invoked directly as $cb(). call_user_func and call_user_func_array support all the above.

See: http://php.net/manual/en/language.types.callable.php

Notes/Caveats:

  1. If the function/class is namespaced, the string must contain the fully-qualified name. E.g. ['Vendor\Package\Foo', 'method']
  2. call_user_func does not support passing non-objects by reference, so you can either use call_user_func_array or, in later PHP versions, save the callback to a var and use the direct syntax: $cb();
  3. Objects with an __invoke() method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term.
  4. The legacy create_function() creates a global function and returns its name. It's a wrapper for eval() and anonymous functions should be used instead.

How to change the text of a button in jQuery?

This should do the trick:

$("#btnAddProfile").prop('value', 'Save');       
$("#btnAddProfile").button('refresh');

How to delete all data from solr and hbase

The curl examples above all failed for me when I ran them from a cygwin terminal. There were errors like this when i ran the script example.

curl http://192.168.2.20:7773/solr/CORE1/update --data '<delete><query>*:*</query></delete>' -H 'Content-type:text/xml; charset=utf-8'
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">0</int><int name="QTime">1</int></lst>
</response>
<!-- 
     It looks like it deleted stuff, but it did not go away
     maybe because the committing call failed like so 
-->
curl http://192.168.1.2:7773/solr/CORE1/update --data-binary '' -H 'Content-type:text/xml; charset=utf-8'
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">400</int><int name="QTime">2</int></lst><lst name="error"><str name="msg">Unexpected EOF in prolog
 at [row,col {unknown-source}]: [1,0]</str><int name="code">400</int></lst>
</response>

I needed to use the delete in a loop on core names to wipe them all out in a project.

This query below worked for me in the Cygwin terminal script.

curl http://192.168.1.2:7773/hpi/CORE1/update?stream.body=<delete><query>*:*</query></delete>&commit=true
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">0</int><int name="QTime">1</int></lst>
</response>

This one line made the data go away and the change persisted.

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

Develop Android app using C#

Here is a new one (Note: in Tech Preview stage): http://www.dot42.com

It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.

Disclosure: I work for this company


UPDATE: all sources are now on https://github.com/dot42

__init__() got an unexpected keyword argument 'user'

You can't do

LivingRoom.objects.create(user=instance)

because you have an __init__ method that does NOT take user as argument.

You need something like

#signal function: if a user is created, add control livingroom to the user    
def create_control_livingroom(sender, instance, created, **kwargs):
    if created:
        my_room = LivingRoom()
        my_room.user = instance

Update

But, as bruno has already said it, Django's models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields.

So, following better principles, you should probably have something like

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, *args, temp=65, **kwargs):
        self.temp = temp
        return super().__init__(*args, **kwargs)

Note - If you weren't using temp as a keyword argument, e.g. LivingRoom(65), then you'll have to start doing that. LivingRoom(user=instance, temp=66) or if you want the default (65), simply LivingRoom(user=instance) would do.

How to get first/top row of the table in Sqlite via Sql Query

LIMIT 1 is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order clause in an outer query).

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

Yes, they both form the primary key. Especially in tables where you don't have a surrogate key, it may be necessary to specify multiple attributes as the unique identifier for each record (bad example: a table with both a first name and last name might require the combination of them to be unique).

Is it possible to run selenium (Firefox) web driver without a GUI?

Yes. You can use HTMLUnitDriver instead for FirefoxDriver while starting webdriver. This is headless browser setup. Details can be found here.

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

// detect IE8 and above, and Edge
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
    ... do something
}

Explanation:

document.documentMode

An IE only property, first available in IE8.

/Edge/

A regular expression to search for the string 'Edge' - which we then test against the 'navigator.userAgent' property

Update Mar 2020

@Jam comments that the latest version of Edge now reports Edg as the user agent. So the check would be:

if (document.documentMode || /Edge/.test(navigator.userAgent) || /Edg/.test(navigator.userAgent)) {
    ... do something
}

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Followed this.

I have solved it with adding some key in info.plist. The steps I followed are:

  1. Opened my Projects info.plist file

  2. Added a Key called NSAppTransportSecurity as a Dictionary.

  3. Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES as like following image. enter image description here

Clean the Project and Now Everything is Running fine as like before.

Ref Link.

Converting HTML files to PDF

Did you try WKHTMLTOPDF?

It's a simple shell utility, an open source implementation of WebKit. Both are free.

We've set a small tutorial here

EDIT( 2017 ):

If it was to build something today, I wouldn't go that route anymore.
But would use http://pdfkit.org/ instead.
Probably stripping it of all its nodejs dependencies, to run in the browser.

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

Wherever you invoke a generator from within a generator you need a "pump" to re-yield the values: for v in inner_generator: yield v. As the PEP points out there are subtle complexities to this which most people ignore. Non-local flow-control like throw() is one example given in the PEP. The new syntax yield from inner_generator is used wherever you would have written the explicit for loop before. It's not merely syntactic sugar, though: It handles all of the corner cases that are ignored by the for loop. Being "sugary" encourages people to use it and thus get the right behaviors.

This message in the discussion thread talks about these complexities:

With the additional generator features introduced by PEP 342, that is no longer the case: as described in Greg's PEP, simple iteration doesn't support send() and throw() correctly. The gymnastics needed to support send() and throw() actually aren't that complex when you break them down, but they aren't trivial either.

I can't speak to a comparison with micro-threads, other than to observe that generators are a type of paralellism. You can consider the suspended generator to be a thread which sends values via yield to a consumer thread. The actual implementation may be nothing like this (and the actual implementation is obviously of great interest to the Python developers) but this does not concern the users.

The new yield from syntax does not add any additional capability to the language in terms of threading, it just makes it easier to use existing features correctly. Or more precisely it makes it easier for a novice consumer of a complex inner generator written by an expert to pass through that generator without breaking any of its complex features.

Html table tr inside td

Just add a new table in the td you want. Example: http://jsfiddle.net/AbE3Q/

_x000D_
_x000D_
<table border="1">
  <tr>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
  </tr>
  <tr>
    <td>Item1</td>
    <td>Item2</td>
    <td>
      <table border="1">
        <tr>
          <td>qweqwewe</td>
          <td>qweqwewe</td>
        </tr>
        <tr>
          <td>qweqwewe</td>
          <td>qweqwewe</td>
        </tr>
        <tr>
          <td>qweqwewe</td>
          <td>qweqwewe</td>
        </tr>
      </table>
    </td>
    <td>Item3</td>
  </tr>
  <tr>
  </tr>
  <tr>
  </tr>
  <tr>
  </tr>
  <tr>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Remove Android App Title Bar

Just use this

getSupportActionBar().hide();

Can you create nested WITH clauses for Common Table Expressions?

You can do the following, which is referred to as a recursive query:

WITH y
AS
(
  SELECT x, y, z
  FROM MyTable
  WHERE [base_condition]

  UNION ALL

  SELECT x, y, z
  FROM MyTable M
  INNER JOIN y ON M.[some_other_condition] = y.[some_other_condition]
)
SELECT *
FROM y

You may not need this functionality. I've done the following just to organize my queries better:

WITH y 
AS
(
  SELECT * 
  FROM MyTable
  WHERE [base_condition]
),
x
AS
(
  SELECT * 
  FROM y
  WHERE [something_else]
)
SELECT * 
FROM x

Importing csv file into R - numeric values read as characters

In read.table (and its relatives) it is the na.strings argument which specifies which strings are to be interpreted as missing values NA. The default value is na.strings = "NA"

If missing values in an otherwise numeric variable column are coded as something else than "NA", e.g. "." or "N/A", these rows will be interpreted as character, and then the whole column is converted to character.

Thus, if your missing values are some else than "NA", you need to specify them in na.strings.

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

- Another Update -

Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible

It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="fixed">  <!-- we want this div to be fixed width -->
            ...
        </div>
        <div class="hero-unit filler">  <!-- we have removed spanX class -->
            ...
        </div>
    </div>
</div>

CSS

/* CSS for fixed-fluid layout */

.fixed {
    width: 150px;  /* the fixed width required */
    float: left;
}

.fixed + div {
     margin-left: 150px;  /* must match the fixed width in the .fixed class */
     overflow: hidden;
}


/* CSS to ensure sidebar and content are same height (optional) */

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
    position: relative;
}

.filler:after{
    background-color:inherit;
    bottom: 0;
    content: "";
    height: auto;
    min-height: 100%;
    left: 0;
    margin:inherit;
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)


Important

Answer below is fluid-fluid

Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0

To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html and body to 100% and create a new css class called .fill which has a minimum-height of 100%:

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
}

We can then add the .fill class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:

<div class="container-fluid fill">
    ...
</div>

To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after pseudo selector to add a filler element that will give the illusion that the two columns have the same height:

.filler::after {
    background-color: inherit;
    bottom: 0;
    content: "";
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

To make sure that the .filler element is positioned relatively to the .fill element we need to add position: relative to .fill:

.fill { 
    min-height: 100%;
    position: relative;
}

And finally add the .filler style to the HTML:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="span3">
            ...
        </div>
        <div class="span9 hero-unit filler">
            ...
        </div>
    </div>
</div>

Notes

  • If you need the element on the left of the page to be the filler then you need to change right: 0 to left: 0.

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

A lot depends on what kind of project it is. WTP's JSP support either expects the JSP files to be under the same folder that's the parent of the WEB-INF folder (src/web, which it will then treat as "/" to find TLDs), or to have project metadata set up to help it know where that root is (done for you in a Dynamic Web Project through Deployment Assembly). How are you referring to the TLD file, and where is the JSP file located?

And maybe I missed the original post to the Eclipse forums; the one I saw was posted a full day after this one.

catching stdout in realtime from subprocess

Some rules of thumb for subprocess.

  • Never use shell=True. It needlessly invokes an extra shell process to call your program.
  • When calling processes, arguments are passed around as lists. sys.argv in python is a list, and so is argv in C. So you pass a list to Popen to call subprocesses, not a string.
  • Don't redirect stderr to a PIPE when you're not reading it.
  • Don't redirect stdin when you're not writing to it.

Example:

import subprocess, time, os, sys
cmd = ["rsync.exe", "-vaz", "-P", "source/" ,"dest/"]

p = subprocess.Popen(cmd,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)

for line in iter(p.stdout.readline, b''):
    print(">>> " + line.rstrip())

That said, it is probable that rsync buffers its output when it detects that it is connected to a pipe instead of a terminal. This is the default behavior - when connected to a pipe, programs must explicitly flush stdout for realtime results, otherwise standard C library will buffer.

To test for that, try running this instead:

cmd = [sys.executable, 'test_out.py']

and create a test_out.py file with the contents:

import sys
import time
print ("Hello")
sys.stdout.flush()
time.sleep(10)
print ("World")

Executing that subprocess should give you "Hello" and wait 10 seconds before giving "World". If that happens with the python code above and not with rsync, that means rsync itself is buffering output, so you are out of luck.

A solution would be to connect direct to a pty, using something like pexpect.

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

Using File.listFiles with FileNameExtensionFilter

Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter

Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.

Take n rows from a spark dataframe and pass to toPandas()

Try it:

def showDf(df, count=None, percent=None, maxColumns=0):
    if (df == None): return
    import pandas
    from IPython.display import display
    pandas.set_option('display.encoding', 'UTF-8')
    # Pandas dataframe
    dfp = None
    # maxColumns param
    if (maxColumns >= 0):
        if (maxColumns == 0): maxColumns = len(df.columns)
        pandas.set_option('display.max_columns', maxColumns)
    # count param
    if (count == None and percent == None): count = 10 # Default count
    if (count != None):
        count = int(count)
        if (count == 0): count = df.count()
        pandas.set_option('display.max_rows', count)
        dfp = pandas.DataFrame(df.head(count), columns=df.columns)
        display(dfp)
    # percent param
    elif (percent != None):
        percent = float(percent)
        if (percent >=0.0 and percent <= 1.0):
            import datetime
            now = datetime.datetime.now()
            seed = long(now.strftime("%H%M%S"))
            dfs = df.sample(False, percent, seed)
            count = df.count()
            pandas.set_option('display.max_rows', count)
            dfp = dfs.toPandas()    
            display(dfp)

Examples of usages are:

# Shows the ten first rows of the Spark dataframe
showDf(df)
showDf(df, 10)
showDf(df, count=10)

# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15) 

How can I convert a string with dot and comma into a float in Python

s =  "123,456.908"
print float(s.replace(',', ''))

Add image to left of text via css

.create
{
background-image: url('somewhere.jpg');
background-repeat: no-repeat;
padding-left: 30px;  /* width of the image plus a little extra padding */
display: block;  /* may not need this, but I've found I do */
}

Play around with padding and possibly margin until you get your desired result. You can also play with the position of the background image (*nod to Tom Wright) with "background-position" or doing a completely definition of "background" (link to w3).

UML diagram shapes missing on Visio 2013

Software & Database is usually not in the Standard edition of Visio, only the Pro version.

Try looking here for some templates that will work in standard edition

Set up an HTTP proxy to insert a header

You can also install Fiddler (http://www.fiddler2.com/fiddler2/) which is very easy to install (easier than Apache for example).

After launching it, it will register itself as system proxy. Then open the "Rules" menu, and choose "Customize Rules..." to open a JScript file which allow you to customize requests.

To add a custom header, just add a line in the OnBeforeRequest function:

oSession.oRequest.headers.Add("MyHeader", "MyValue");

Finding all possible combinations of numbers to reach a given sum

Perl version (of the leading answer):

use strict;

sub subset_sum {
  my ($numbers, $target, $result, $sum) = @_;

  print 'sum('.join(',', @$result).") = $target\n" if $sum == $target;
  return if $sum >= $target;

  subset_sum([@$numbers[$_ + 1 .. $#$numbers]], $target, 
             [@{$result||[]}, $numbers->[$_]], $sum + $numbers->[$_])
    for (0 .. $#$numbers);
}

subset_sum([3,9,8,4,5,7,10,6], 15);

Result:

sum(3,8,4) = 15
sum(3,5,7) = 15
sum(9,6) = 15
sum(8,7) = 15
sum(4,5,6) = 15
sum(5,10) = 15

Javascript version:

_x000D_
_x000D_
const subsetSum = (numbers, target, partial = [], sum = 0) => {_x000D_
  if (sum < target)_x000D_
    numbers.forEach((num, i) =>_x000D_
      subsetSum(numbers.slice(i + 1), target, partial.concat([num]), sum + num));_x000D_
  else if (sum == target)_x000D_
    console.log('sum(%s) = %s', partial.join(), target);_x000D_
}_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10,6], 15);
_x000D_
_x000D_
_x000D_

Javascript one-liner that actually returns results (instead of printing it):

_x000D_
_x000D_
const subsetSum=(n,t,p=[],s=0,r=[])=>(s<t?n.forEach((l,i)=>subsetSum(n.slice(i+1),t,[...p,l],s+l,r)):s==t?r.push(p):0,r);_x000D_
_x000D_
console.log(subsetSum([3,9,8,4,5,7,10,6], 15));
_x000D_
_x000D_
_x000D_

And my favorite, one-liner with callback:

_x000D_
_x000D_
const subsetSum=(n,t,cb,p=[],s=0)=>s<t?n.forEach((l,i)=>subsetSum(n.slice(i+1),t,cb,[...p,l],s+l)):s==t?cb(p):0;_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10,6], 15, console.log);
_x000D_
_x000D_
_x000D_

Accessing the index in 'for' loops?

If I were to iterate nums = [1, 2, 3, 4, 5] I would do

for i, num in enumerate(nums, start=1):
    print(i, num)

Or get the length as l = len(nums)

for i in range(l):
    print(i+1, nums[i])

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Http Servlet request lose params from POST body after read it once

So this is basically Lathy's answer BUT updated for newer requirements for ServletInputStream.

Namely (for ServletInputStream), one has to implement:

public abstract boolean isFinished();

public abstract boolean isReady();

public abstract void setReadListener(ReadListener var1);

This is the edited Lathy's object

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class RequestWrapper extends HttpServletRequestWrapper {

    private String _body;

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        _body = "";
        BufferedReader bufferedReader = request.getReader();
        String line;
        while ((line = bufferedReader.readLine()) != null){
            _body += line;
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        CustomServletInputStream kid = new CustomServletInputStream(_body.getBytes());
        return kid;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}

and somewhere (??) I found this (which is a first-class class that deals with the "extra" methods.

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class CustomServletInputStream extends ServletInputStream {

    private byte[] myBytes;

    private int lastIndexRetrieved = -1;
    private ReadListener readListener = null;

    public CustomServletInputStream(String s) {
        try {
            this.myBytes = s.getBytes("UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new IllegalStateException("JVM did not support UTF-8", ex);
        }
    }

    public CustomServletInputStream(byte[] inputBytes) {
        this.myBytes = inputBytes;
    }

    @Override
    public boolean isFinished() {
        return (lastIndexRetrieved == myBytes.length - 1);
    }

    @Override
    public boolean isReady() {
        // This implementation will never block
        // We also never need to call the readListener from this method, as this method will never return false
        return isFinished();
    }

    @Override
    public void setReadListener(ReadListener readListener) {
        this.readListener = readListener;
        if (!isFinished()) {
            try {
                readListener.onDataAvailable();
            } catch (IOException e) {
                readListener.onError(e);
            }
        } else {
            try {
                readListener.onAllDataRead();
            } catch (IOException e) {
                readListener.onError(e);
            }
        }
    }

    @Override
    public int read() throws IOException {
        int i;
        if (!isFinished()) {
            i = myBytes[lastIndexRetrieved + 1];
            lastIndexRetrieved++;
            if (isFinished() && (readListener != null)) {
                try {
                    readListener.onAllDataRead();
                } catch (IOException ex) {
                    readListener.onError(ex);
                    throw ex;
                }
            }
            return i;
        } else {
            return -1;
        }
    }
};

Ultimately, I was just trying to log the requests. And the above frankensteined together pieces helped me create the below.

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

//one or the other based on spring version
//import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;

import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.filter.OncePerRequestFilter;


/**
 * A filter which logs web requests that lead to an error in the system.
 */
@Component
public class LogRequestFilter extends OncePerRequestFilter implements Ordered {

    // I tried apache.commons and slf4g loggers.  (one or the other in these next 2 lines of declaration */
    //private final static org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory.getLog(LogRequestFilter.class);
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LogRequestFilter.class);

    // put filter at the end of all other filters to make sure we are processing after all others
    private int order = Ordered.LOWEST_PRECEDENCE - 8;
    private ErrorAttributes errorAttributes;

    @Override
    public int getOrder() {
        return order;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String temp = ""; /* for a breakpoint, remove for production/real code */

        /* change to true for easy way to comment out this code, remove this if-check for production/real code */
        if (false) {
            filterChain.doFilter(request, response);
            return;
        }

        /* make a "copy" to avoid issues with body-can-only-read-once issues */
        RequestWrapper reqWrapper = new RequestWrapper(request);

        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        // pass through filter chain to do the actual request handling
        filterChain.doFilter(reqWrapper, response);
        status = response.getStatus();

        try {
            Map<String, Object> traceMap = getTrace(reqWrapper, status);
            // body can only be read after the actual request handling was done!
            this.getBodyFromTheRequestCopy(reqWrapper, traceMap);
            
            /* now do something with all the pieces of information gatherered */
            this.logTrace(reqWrapper, traceMap);
        } catch (Exception ex) {
            logger.error("LogRequestFilter FAILED: " + ex.getMessage(), ex);
        }
    }

    private void getBodyFromTheRequestCopy(RequestWrapper rw, Map<String, Object> trace) {
        try {
            if (rw != null) {
                byte[] buf = IOUtils.toByteArray(rw.getInputStream());
                //byte[] buf = rw.getInputStream();
                if (buf.length > 0) {
                    String payloadSlimmed;
                    try {
                        String payload = new String(buf, 0, buf.length, rw.getCharacterEncoding());
                        payloadSlimmed = payload.trim().replaceAll(" +", " ");
                    } catch (UnsupportedEncodingException ex) {
                        payloadSlimmed = "[unknown]";
                    }

                    trace.put("body", payloadSlimmed);
                }
            }
        } catch (IOException ioex) {
            trace.put("body", "EXCEPTION: " + ioex.getMessage());
        }
    }

    private void logTrace(HttpServletRequest request, Map<String, Object> trace) {
        Object method = trace.get("method");
        Object path = trace.get("path");
        Object statusCode = trace.get("statusCode");

        logger.info(String.format("%s %s produced an status code '%s'. Trace: '%s'", method, path, statusCode,
                trace));
    }

    protected Map<String, Object> getTrace(HttpServletRequest request, int status) {
        Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");

        Principal principal = request.getUserPrincipal();

        Map<String, Object> trace = new LinkedHashMap<String, Object>();
        trace.put("method", request.getMethod());
        trace.put("path", request.getRequestURI());
        if (null != principal) {
            trace.put("principal", principal.getName());
        }
        trace.put("query", request.getQueryString());
        trace.put("statusCode", status);

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            trace.put("header:" + key, value);
        }

        if (exception != null && this.errorAttributes != null) {
            trace.put("error", this.errorAttributes
                    .getErrorAttributes((WebRequest) new ServletRequestAttributes(request), true));
        }

        return trace;
    }
}

Please take this code with a grain of salt.

The MOST important "test" is if a POST works with a payload. This is what will expose "double read" issues.

pseudo example code

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("myroute")
public class MyController {
    @RequestMapping(method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public String getSomethingExample(@RequestBody MyCustomObject input) {

        String returnValue = "";

        return returnValue;
    }
}

You can replace "MyCustomObject" with plain ole "Object" if you just want to test.

This answer is frankensteined from several different SOF posts and examples..but it took a while to pull it all together so I hope it helps a future reader.

Please upvote Lathy's answer before mine. I could have not gotten this far without it.

Below is one/some of the exceptions I got while working this out.

getReader() has already been called for this request

Looks like some of the places I "borrowed" from are here:

http://slackspace.de/articles/log-request-body-with-spring-boot/

https://github.com/c0nscience/spring-web-logging/blob/master/src/main/java/org/zalando/springframework/web/logging/LoggingFilter.java

https://howtodoinjava.com/servlets/httpservletrequestwrapper-example-read-request-body/

https://www.oodlestechnologies.com/blogs/How-to-create-duplicate-object-of-httpServletRequest-object

https://github.com/c0nscience/spring-web-logging/blob/master/src/main/java/org/zalando/springframework/web/logging/LoggingFilter.java

January 2021 APPEND.

I have learned the hard way that the above code does NOT work for

x-www-form-urlencoded

Consider the example below:

   @CrossOrigin
    @ResponseBody
    @PostMapping(path = "/mypath", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
    public ResponseEntity myMethodName(@RequestParam Map<String, String> parameters
    ) {
        /* DO YOU GET ANY PARAMETERS HERE?  Or are they empty because of logging/auditing filter ?*/
        return new ResponseEntity(HttpStatus.OK);

    }

I had to go through several of the other examples here.

I came up with a "wrapper" that works explicitly for APPLICATION_FORM_URLENCODED_VALUE

import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Makes a "copy" of the HttpRequest so the body can be accessed more than 1 time.
 * WORKS WITH APPLICATION_FORM_URLENCODED_VALUE
 * See : https://stackoverflow.com/questions/44182370/why-do-we-wrap-httpservletrequest-the-api-provides-an-httpservletrequestwrappe/44187955#44187955
 */
public final class AppFormUrlEncodedSpecificContentCachingRequestWrapper extends ContentCachingRequestWrapper {

    public static final String ERROR_MSG_CONTENT_TYPE_NOT_SUPPORTED = "ContentType not supported. (Input ContentType(s)=\"%1$s\", Supported ContentType(s)=\"%2$s\")";

    public static final String ERROR_MSG_PERSISTED_CONTENT_CACHING_REQUEST_WRAPPER_CONSTRUCTOR_FAILED = "AppFormUrlEncodedSpecificContentCachingRequestWrapper constructor failed";

    private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(AppFormUrlEncodedSpecificContentCachingRequestWrapper.class);

    private byte[] body;

    private ServletInputStream inputStream;

    public AppFormUrlEncodedSpecificContentCachingRequestWrapper(HttpServletRequest request) {
        super(request);
        super.getParameterMap(); // init cache in ContentCachingRequestWrapper.  THIS IS THE VITAL CALL so that "@RequestParam Map<String, String> parameters" are populated on the REST Controller.  See https://stackoverflow.com/questions/10210645/http-servlet-request-lose-params-from-post-body-after-read-it-once/64924380#64924380

        String contentType = request.getContentType();
        /* EXPLICTLY check for APPLICATION_FORM_URLENCODED_VALUE and allow nothing else */
        if (null == contentType || !contentType.equalsIgnoreCase(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
            IllegalArgumentException ioex = new IllegalArgumentException(String.format(ERROR_MSG_CONTENT_TYPE_NOT_SUPPORTED, contentType, MediaType.APPLICATION_FORM_URLENCODED_VALUE));
            LOGGER.error(ERROR_MSG_PERSISTED_CONTENT_CACHING_REQUEST_WRAPPER_CONSTRUCTOR_FAILED, ioex);
            throw ioex;
        }

        try {
            loadBody(request);
        } catch (IOException ioex) {
            throw new RuntimeException(ioex);
        }
    }

    private void loadBody(HttpServletRequest request) throws IOException {
        body = IOUtils.toByteArray(request.getInputStream());
        inputStream = new CustomServletInputStream(this.getBody());
    }

    private byte[] getBody() {
        return body;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (inputStream != null) {
            return inputStream;
        }
        return super.getInputStream();
    }
}

Note Andrew Sneck's answer on this same page. It is pretty much this : https://programmersought.com/article/23981013626/

I have not had time to harmonize the two above implementations (my two that is).

So I created a Factory to "choose" from the two:

import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

/**
 * Factory to return different concretes of HttpServletRequestWrapper. APPLICATION_FORM_URLENCODED_VALUE needs a different concrete.
 */
public class HttpServletRequestWrapperFactory {

    public static final String ERROR_MSG_HTTP_SERVLET_REQUEST_WRAPPER_FACTORY_CREATE_HTTP_SERVLET_REQUEST_WRAPPER_FAILED = "HttpServletRequestWrapperFactory createHttpServletRequestWrapper FAILED";

    public static HttpServletRequestWrapper createHttpServletRequestWrapper(final HttpServletRequest request) {
        HttpServletRequestWrapper returnItem = null;

        if (null != request) {
            String contentType = request.getContentType();
            if (null != contentType && contentType.equalsIgnoreCase(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
                returnItem = new AppFormUrlEncodedSpecificContentCachingRequestWrapper(request);
            } else {
                try {
                    returnItem = new PersistedBodyRequestWrapper(request);
                } catch (IOException ioex) {
                    throw new RuntimeException(ERROR_MSG_HTTP_SERVLET_REQUEST_WRAPPER_FACTORY_CREATE_HTTP_SERVLET_REQUEST_WRAPPER_FAILED, ioex);
                }
            }
        }

        return returnItem;
    }

}

Below is the "other" one that works with JSON, etc. It is the other concrete that the Factory can output. I put it here so that my Jan 2021 APPEND is consistent..I don't know if the code below is perfect consistent with my original answer:

import org.springframework.http.MediaType;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Makes a "copy" of the HttpRequest so the body can be accessed more than 1 time.
 * See : https://stackoverflow.com/questions/44182370/why-do-we-wrap-httpservletrequest-the-api-provides-an-httpservletrequestwrappe/44187955#44187955
 * DOES NOT WORK WITH APPLICATION_FORM_URLENCODED_VALUE
 */
public final class PersistedBodyRequestWrapper extends HttpServletRequestWrapper {

    public static final String ERROR_MSG_CONTENT_TYPE_NOT_SUPPORTED = "ContentType not supported. (ContentType=\"%1$s\")";

    public static final String ERROR_MSG_PERSISTED_BODY_REQUEST_WRAPPER_CONSTRUCTOR_FAILED = "PersistedBodyRequestWrapper constructor FAILED";

    private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(PersistedBodyRequestWrapper.class);

    private String persistedBody;

    private final Map<String, String[]> parameterMap;

    public PersistedBodyRequestWrapper(final HttpServletRequest request) throws IOException {
        super(request);

        String contentType = request.getContentType();
        /* Allow everything EXCEPT APPLICATION_FORM_URLENCODED_VALUE */
        if (null != contentType && contentType.equalsIgnoreCase(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
            IllegalArgumentException ioex = new IllegalArgumentException(String.format(ERROR_MSG_CONTENT_TYPE_NOT_SUPPORTED, MediaType.APPLICATION_FORM_URLENCODED_VALUE));
            LOGGER.error(ERROR_MSG_PERSISTED_BODY_REQUEST_WRAPPER_CONSTRUCTOR_FAILED, ioex);
            throw ioex;
        }

        parameterMap = request.getParameterMap();
        this.persistedBody = "";
        BufferedReader bufferedReader = request.getReader();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            this.persistedBody += line;
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        CustomServletInputStream csis = new CustomServletInputStream(this.persistedBody.getBytes(StandardCharsets.UTF_8));
        return csis;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return this.parameterMap;
    }
}

Access all Environment properties as a Map or Properties object

I had the requirement to retrieve all properties whose key starts with a distinct prefix (e.g. all properties starting with "log4j.appender.") and wrote following Code (using streams and lamdas of Java 8).

public static Map<String,Object> getPropertiesStartingWith( ConfigurableEnvironment aEnv,
                                                            String aKeyPrefix )
{
    Map<String,Object> result = new HashMap<>();

    Map<String,Object> map = getAllProperties( aEnv );

    for (Entry<String, Object> entry : map.entrySet())
    {
        String key = entry.getKey();

        if ( key.startsWith( aKeyPrefix ) )
        {
            result.put( key, entry.getValue() );
        }
    }

    return result;
}

public static Map<String,Object> getAllProperties( ConfigurableEnvironment aEnv )
{
    Map<String,Object> result = new HashMap<>();
    aEnv.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
    return result;
}

public static Map<String,Object> getAllProperties( PropertySource<?> aPropSource )
{
    Map<String,Object> result = new HashMap<>();

    if ( aPropSource instanceof CompositePropertySource)
    {
        CompositePropertySource cps = (CompositePropertySource) aPropSource;
        cps.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
        return result;
    }

    if ( aPropSource instanceof EnumerablePropertySource<?> )
    {
        EnumerablePropertySource<?> ps = (EnumerablePropertySource<?>) aPropSource;
        Arrays.asList( ps.getPropertyNames() ).forEach( key -> result.put( key, ps.getProperty( key ) ) );
        return result;
    }

    // note: Most descendants of PropertySource are EnumerablePropertySource. There are some
    // few others like JndiPropertySource or StubPropertySource
    myLog.debug( "Given PropertySource is instanceof " + aPropSource.getClass().getName()
                 + " and cannot be iterated" );

    return result;

}

private static void addAll( Map<String, Object> aBase, Map<String, Object> aToBeAdded )
{
    for (Entry<String, Object> entry : aToBeAdded.entrySet())
    {
        if ( aBase.containsKey( entry.getKey() ) )
        {
            continue;
        }

        aBase.put( entry.getKey(), entry.getValue() );
    }
}

Note that the starting point is the ConfigurableEnvironment which is able to return the embedded PropertySources (the ConfigurableEnvironment is a direct descendant of Environment). You can autowire it by:

@Autowired
private ConfigurableEnvironment  myEnv;

If you not using very special kinds of property sources (like JndiPropertySource, which is usually not used in spring autoconfiguration) you can retrieve all properties held in the environment.

The implementation relies on the iteration order which spring itself provides and takes the first found property, all later found properties with the same name are discarded. This should ensure the same behaviour as if the environment were asked directly for a property (returning the first found one).

Note also that the returned properties are not yet resolved if they contain aliases with the ${...} operator. If you want to have a particular key resolved you have to ask the Environment directly again:

myEnv.getProperty( key );

How to create the pom.xml for a Java project with Eclipse

If you have plugin for Maven in Eclipse, you can do following:

  • right click on your project -> Maven -> Enable Dependency Management

This will convert your project to Maven and creates a pom.xml. Fast and simple...

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

This code works for me:

$rootScope.$$listeners.nameOfYourEvent=[];

Javascript / Chrome - How to copy an object from the webkit inspector as code

If you've sent the object over a request you can copy it from the Chrome -> Network tab.

Request Payload - > View Source

enter image description here

enter image description here

Groovy built-in REST/HTTP client?

HTTPBuilder is it. Very easy to use.

import groovyx.net.http.HTTPBuilder

def http = new HTTPBuilder('https://google.com')
def html = http.get(path : '/search', query : [q:'waffles'])

It is especially useful if you need error handling and generally more functionality than just fetching content with GET.

using extern template (C++11)

If you have used extern for functions before, exactly same philosophy is followed for templates. if not, going though extern for simple functions may help. Also, you may want to put the extern(s) in header file and include the header when you need it.

When do you use varargs in Java?

Varargs is the feature added in java version 1.5.

Why to use this?

  1. What if, you don't know the number of arguments to pass for a method?
  2. What if, you want to pass unlimited number of arguments to a method?

How this works?

It creates an array with the given arguments & passes the array to the method.

Example :

public class Solution {



    public static void main(String[] args) {
        add(5,7);
        add(5,7,9);
    }

    public static void add(int... s){
        System.out.println(s.length);
        int sum=0;
        for(int num:s)
            sum=sum+num;
        System.out.println("sum is "+sum );
    }

}

Output :

2

sum is 12

3

sum is 21

How do I skip an iteration of a `foreach` loop?

Use the continue statement:

foreach(object number in mycollection) {
     if( number < 0 ) {
         continue;
     }
  }

Firebase: how to generate a unique numeric ID for key?

As the docs say, this can be achieved just by using set instead if push.

As the docs say, it is not recommended (due to possible overwrite by other user at the "same" time).

But in some cases it's helpful to have control over the feed's content including keys.

As an example of webapp in js, 193 being your id generated elsewhere, simply:

 firebase.initializeApp(firebaseConfig);
  var data={
      "name":"Prague"
  };
  firebase.database().ref().child('areas').child("193").set(data);

This will overwrite any area labeled 193 or create one if it's not existing yet.

IE prompts to open or save json result from server

Is above javascript code the one you're using in your web application ? If so - i would like to point few errors in it: firstly - it has an additional '{' sign in definition of 'success' callback function secondly - it has no ')' sign after definition of ajax callback. Valid code should look like:

$.ajax({
        type:'POST',
        data: 'args',
        url: '@Url.Action("PostBack")',
        success: function (data, textStatus, jqXHR) {
                alert(data.message);
            }
    });

try using above code - it gave me 'Yay' alert on all 3 IE versions ( 7,8,9 ).

How to know the size of the string in bytes?

System.Text.ASCIIEncoding.Unicode.GetByteCount(yourString);

Or

System.Text.ASCIIEncoding.ASCII.GetByteCount(yourString);

Deep cloning objects

I know that this question and answer sits here for a while and following is not quite answer but rather observation, to which I came across recently when I was checking whether indeed privates are not being cloned (I wouldn't be myself if I have not ;) when I happily copy-pasted @johnc updated answer.

I simply made myself extension method (which is pretty much copy-pasted form aforementioned answer):

public static class CloneThroughJsonExtension
{
    private static readonly JsonSerializerSettings DeserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };

    public static T CloneThroughJson<T>(this T source)
    {
        return ReferenceEquals(source, null) ? default(T) : JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), DeserializeSettings);
    }
}

and dropped naively class like this (in fact there was more of those but they are unrelated):

public class WhatTheHeck
{
    public string PrivateSet { get; private set; } // matches ctor param name

    public string GetOnly { get; } // matches ctor param name

    private readonly string _indirectField;
    public string Indirect => $"Inception of: {_indirectField} "; // matches ctor param name
    public string RealIndirectFieldVaule => _indirectField;

    public WhatTheHeck(string privateSet, string getOnly, string indirect)
    {
        PrivateSet = privateSet;
        GetOnly = getOnly;
        _indirectField = indirect;
    }
}

and code like this:

var clone = new WhatTheHeck("Private-Set-Prop cloned!", "Get-Only-Prop cloned!", "Indirect-Field clonned!").CloneThroughJson();
Console.WriteLine($"1. {clone.PrivateSet}");
Console.WriteLine($"2. {clone.GetOnly}");
Console.WriteLine($"3.1. {clone.Indirect}");
Console.WriteLine($"3.2. {clone.RealIndirectFieldVaule}");

resulted in:

1. Private-Set-Prop cloned!
2. Get-Only-Prop cloned!
3.1. Inception of: Inception of: Indirect-Field cloned!
3.2. Inception of: Indirect-Field cloned!

I was whole like: WHAT THE F... so I grabbed Newtonsoft.Json Github repo and started to dig. What it comes out, is that: while deserializing a type which happens to have only one ctor and its param names match (case insensitive) public property names they will be passed to ctor as those params. Some clues can be found in the code here and here.

Bottom line

I know that it is rather not common case and example code is bit abusive, but hey! It got me by surprise when I was checking whether there is any dragon waiting in the bushes to jump out and bite me in the ass. ;)

svn: E155004: ..(path of resource).. is already locked

Update and clean your working copy.

svn update
svn cleanup

If nothing else works, save your changes as a patch (TortoiseSVNCreate patch... or svn diff > changes.diff), and check out the repository anew. You can then apply the patch to the new working copy (TortoiseSVNApply patch... or svn patch changes.diff).

Easy way to concatenate two byte arrays

For two or multiple arrays, this simple and clean utility method can be used:

/**
 * Append the given byte arrays to one big array
 *
 * @param arrays The arrays to append
 * @return The complete array containing the appended data
 */
public static final byte[] append(final byte[]... arrays) {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (arrays != null) {
        for (final byte[] array : arrays) {
            if (array != null) {
                out.write(array, 0, array.length);
            }
        }
    }
    return out.toByteArray();
}

Where can I find the default timeout settings for all browsers?

For Google Chrome (Tested on ver. 62)

I was trying to keep a socket connection alive from the google chrome's fetch API to a remote express server and found the request headers have to match Node.JS's native <net.socket> connection settings.

I set the headers object on my client-side script with the following options:

/* ----- */
head = new headers();
head.append("Connnection", "keep-alive")
head.append("Keep-Alive", `timeout=${1*60*5}`) //in seconds, not milliseconds
/* apply more definitions to the header */
fetch(url, {
    method: 'OPTIONS',
    credentials: "include",
    body: JSON.stringify(data),
    cors: 'cors',
    headers: head, //could be object literal too
    cache: 'default'
 })
 .then(response=>{
    ....
  }).catch(err=>{...});

And on my express server I setup my router as follows:

 router.head('absolute or regex', (request, response, next)=>{
  req.setTimeout(1000*60*5, ()=>{
     console.info("socket timed out");
   });
  console.info("Proceeding down the middleware chain link...\n\n");
  next();
 });

 /*Keep the socket alive by enabling it on the server, with an optional 
  delay on the last packet sent 
 */
server.on('connection', (socket)=>socket.setKeepAlive(true, 10))

WARNING

Please use common sense and make sure the users you're keeping the socket connection open to is validated and serialized. It works for Firefox as well, but it's really vulnerable if you keep the TCP connection open for longer than 5 minutes.

I'm not sure how some of the lesser known browsers operate, but I'll append to this answer with the Microsoft browser details as well.

How to use default Android drawables

Better to use android.R.drawable because it is public and documented.

Uploading multiple files using formData()

You just have to use fileToUpload[] instead of fileToUpload :

fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[0]);

And it will return an array with multiple names, sizes, etc...

How to check if an element does NOT have a specific class?

Select element (or group of elements) having class "abc", not having class "xyz":

    $('.abc:not(".xyz")')

When selecting regular CSS you can use .abc:not(.xyz).

How to set min-font-size in CSS

No. While you can set a base font size on body using the font-size property, anything after that that specifies a smaller size will override the base rule for that element. In order to do what you are looking to do you will need to use Javascript.

You could iterate through the elements on the page and change the smaller fonts using something like this:

$("*").each( function () {
    var $this = $(this);
    if (parseInt($this.css("fontSize")) < 12) {
        $this.css({ "font-size": "12px" });   
    }
});

Here is a Fiddle where you can see it done: http://jsfiddle.net/mifi79/LfdL8/2/

The connection to adb is down, and a severe error has occurred

I had a similar problem with adb.exe and Eclipse last time I updated ADT plugin. The solution was to run Eclipse as administrator and reinstall ADT.

Getting strings recognized as variable names in R

The basic answer to the question in the title is eval(as.symbol(variable_name_as_string)) as Josh O'Brien uses. e.g.

var.name = "x"
assign(var.name, 5)
eval(as.symbol(var.name)) # outputs 5

Or more simply:

get(var.name) # 5

Is it safe to store a JWT in localStorage with ReactJS?

A way to look at this is to consider the level of risk or harm.

Are you building an app with no users, POC/MVP? Are you a startup who needs to get to market and test your app quickly? If yes, I would probably just implement the simplest solution and maintain focus on finding product-market-fit. Use localStorage as its often easier to implement.

Are you building a v2 of an app with many daily active users or an app that people/businesses are heavily dependent on. Would getting hacked mean little or no room for recovery? If so, I would take a long hard look at your dependencies and consider storing token information in an http-only cookie.

Using both localStorage and cookie/session storage have their own pros and cons.

As stated by first answer: If your application has an XSS vulnerability, neither will protect your user. Since most modern applications have a dozen or more different dependencies, it becomes increasingly difficult to guarantee that one of your application's dependencies is not XSS vulnerable.

If your application does have an XSS vulnerability and a hacker has been able to exploit it, the hacker will be able to perform actions on behalf of your user. The hacker can perform GET/POST requests by retrieving token from localStorage or can perform POST requests if token is stored in a http-only cookie.

The only down-side of the storing your token in local storage is the hacker will be able to read your token.

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

#define GENERAL__GET_BITS_FROM_U8(source,lsb,msb) \
    ((uint8_t)((source) & \
        ((uint8_t)(((uint8_t)(0xFF >> ((uint8_t)(7-((uint8_t)(msb) & 7))))) & \
             ((uint8_t)(0xFF << ((uint8_t)(lsb) & 7)))))))

#define GENERAL__GET_BITS_FROM_U16(source,lsb,msb) \
    ((uint16_t)((source) & \
        ((uint16_t)(((uint16_t)(0xFFFF >> ((uint8_t)(15-((uint8_t)(msb) & 15))))) & \
            ((uint16_t)(0xFFFF << ((uint8_t)(lsb) & 15)))))))

#define GENERAL__GET_BITS_FROM_U32(source,lsb,msb) \
    ((uint32_t)((source) & \
        ((uint32_t)(((uint32_t)(0xFFFFFFFF >> ((uint8_t)(31-((uint8_t)(msb) & 31))))) & \
            ((uint32_t)(0xFFFFFFFF << ((uint8_t)(lsb) & 31)))))))

Convert a double to a QString

You can use arg(), as follow:

double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);

This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision

DNS problem, nslookup works, ping doesn't

I have the same issue with IIS running on my home server, on the client machine a command like ipconfig /flushdns usually solves the problem.

When to use which design pattern?

Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)

if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.

How to set a maximum execution time for a mysql query?

If you're using the mysql native driver (common since php 5.3), and the mysqli extension, you can accomplish this with an asynchronous query:

<?php

// Here's an example query that will take a long time to execute.
$sql = "
    select *
    from information_schema.tables t1
    join information_schema.tables t2
    join information_schema.tables t3
    join information_schema.tables t4
    join information_schema.tables t5
    join information_schema.tables t6
    join information_schema.tables t7
    join information_schema.tables t8
";

$mysqli = mysqli_connect('localhost', 'root', '');
$mysqli->query($sql, MYSQLI_ASYNC | MYSQLI_USE_RESULT);
$links = $errors = $reject = [];
$links[] = $mysqli;

// wait up to 1.5 seconds
$seconds = 1;
$microseconds = 500000;

$timeStart = microtime(true);

if (mysqli_poll($links, $errors, $reject, $seconds, $microseconds) > 0) {
    echo "query finished executing. now we start fetching the data rows over the network...\n";
    $result = $mysqli->reap_async_query();
    if ($result) {
        while ($row = $result->fetch_row()) {
            // print_r($row);
            if (microtime(true) - $timeStart > 1.5) {
                // we exceeded our time limit in the middle of fetching our result set.
                echo "timed out while fetching results\n";
                var_dump($mysqli->close());
                break;
            }
        }
    }
} else {
    echo "timed out while waiting for query to execute\n";
    var_dump($mysqli->close());
}

The flags I'm giving to mysqli_query accomplish important things. It tells the client driver to enable asynchronous mode, while forces us to use more verbose code, but lets us use a timeout(and also issue concurrent queries if you want!). The other flag tells the client not to buffer the entire result set into memory.

By default, php configures its mysql client libraries to fetch the entire result set of your query into memory before it lets your php code start accessing rows in the result. This can take a long time to transfer a large result. We disable it, otherwise we risk that we might time out while waiting for the buffering to complete.

Note that there's two places where we need to check for exceeding a time limit:

  • The actual query execution
  • while fetching the results(data)

You can accomplish similar in the PDO and regular mysql extension. They don't support asynchronous queries, so you can't set a timeout on the query execution time. However, they do support unbuffered result sets, and so you can at least implement a timeout on the fetching of the data.

For many queries, mysql is able to start streaming the results to you almost immediately, and so unbuffered queries alone will allow you to somewhat effectively implement timeouts on certain queries. For example, a

select * from tbl_with_1billion_rows

can start streaming rows right away, but,

select sum(foo) from tbl_with_1billion_rows

needs to process the entire table before it can start returning the first row to you. This latter case is where the timeout on an asynchronous query will save you. It will also save you from plain old deadlocks and other stuff.

ps - I didn't include any timeout logic on the connection itself.

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

Reading the json rfc (http://www.ietf.org/rfc/rfc4627.txt) it is clear that the preferred encoding is utf-8.

FYI, RFC 4627 is no longer the official JSON spec. It was obsoleted in 2014 by RFC 7159, which was then obsoleted in 2017 by RFC 8259, which is the current spec.

RFC 8259 states:

8.1. Character Encoding

JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8 [RFC3629].

Previous specifications of JSON have not required the use of UTF-8 when transmitting JSON text. However, the vast majority of JSON-based software implementations have chosen to use the UTF-8 encoding, to the extent that it is the only encoding that achieves interoperability.

Implementations MUST NOT add a byte order mark (U+FEFF) to the beginning of a networked-transmitted JSON text. In the interests of interoperability, implementations that parse JSON texts MAY ignore the presence of a byte order mark rather than treating it as an error.

How add "or" in switch statements?

Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write

switch(myvar)
{
   case 2:
   case 5:
   {
      //your code
   break;
   }

// etc... }

Math constant PI value in C

I don't know exactly how C calculates PI directly as I'm more familiar with C++ than C; however, you could either have a predefined C macro or const such as:

#define PI 3.14159265359.....
const float PI = 3.14159265359.....
const double PI = 3.14159265359.....
/* If your machine,os & compiler supports the long double */
const long double PI = 3.14159265359..... 

or you could calculate it with either of these two formulas:

#define M_PI acos(-1.0);
#define M_PI (4.0 * atan(1.0)); // tan(pi/4) = 1 or acos(-1)

IMHO I'm not 100% certain but I think atan() is cheaper than acos().

Using RegEX To Prefix And Append In Notepad++

Regular Expression that can be used:

Find: \w.+
Replace: able:"$&"

As, $& will give you the string you search for.

Refer: regexr

Check if list is empty in C#

    If (list.Count==0){
      //you can show your error messages here
    } else {
      //here comes your datagridview databind 
    }

You can make your datagrid visible false and make it visible on the else section.

Fast ceiling of an integer division in C / C++

How about this? (requires y non-negative, so don't use this in the rare case where y is a variable with no non-negativity guarantee)

q = (x > 0)? 1 + (x - 1)/y: (x / y);

I reduced y/y to one, eliminating the term x + y - 1 and with it any chance of overflow.

I avoid x - 1 wrapping around when x is an unsigned type and contains zero.

For signed x, negative and zero still combine into a single case.

Probably not a huge benefit on a modern general-purpose CPU, but this would be far faster in an embedded system than any of the other correct answers.

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

In Python 3 it's quite easy: read the file and rewrite it with utf-8 encoding:

s = open(bom_file, mode='r', encoding='utf-8-sig').read()
open(bom_file, mode='w', encoding='utf-8').write(s)

How to update/modify an XML file in python?

You should read the XML file using specific XML modules. That way you can edit the XML document in memory and rewrite your changed XML document into the file.

Here is a quick start: http://docs.python.org/library/xml.dom.minidom.html

There are a lot of other XML utilities, which one is best depends on the nature of your XML file and in which way you want to edit it.

Can we use join for two different database tables?

You could use Synonyms part in the database.

enter image description here

Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply. enter image description here

Guzzle 6: no more json() method for responses

You switch to:

json_decode($response->getBody(), true)

Instead of the other comment if you want it to work exactly as before in order to get arrays instead of objects.

Should I use Vagrant or Docker for creating an isolated environment?

There is a really informative article in the actual Oracle Java magazine about using Docker in combination with Vagrant (and Puppet):

Conclusion

Docker’s lightweight containers are faster compared with classic VMs and have become popular among developers and as part of CD and DevOps initiatives. If your purpose is isolation, Docker is an excellent choice. Vagrant is a VM manager that enables you to script configurations of individual VMs as well as do the provisioning. However, it is sill a VM dependent on VirtualBox (or another VM manager) with relatively large overhead. It requires you to have a hard drive idle that can be huge, it takes a lot of RAM, and performance can be suboptimal. Docker uses kernel cgroups and namespace isolation via LXC. This means that you are using the same kernel as the host and the same ile system. Vagrant is a level above Docker in terms of abstraction, so they are not really comparable. Configuration management tools such as Puppet are widely used for provisioning target environments. Reusing existing Puppet-based solutions is easy with Docker. You can also slice your solution, so the infrastructure is provisioned with Puppet; the middleware, the business application itself, or both are provisioned with Docker; and Docker is wrapped by Vagrant. With this range of tools, you can do what’s best for your scenario.

How to build, use and orchestrate Docker containers in DevOps http://www.javamagazine.mozaicreader.com/JulyAug2015#&pageSet=34&page=0

Could pandas use column as index?

Yes, with set_index you can make Locality your row index.

data.set_index('Locality', inplace=True)

If inplace=True is not provided, set_index returns the modified dataframe as a result.

Example:

> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                     ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> df
     Locality    2005    2006
0  ABBOTSFORD  427000  448000
1  ABERFELDIE  534000  600000

> df.set_index('Locality', inplace=True)
> df
              2005    2006
Locality                  
ABBOTSFORD  427000  448000
ABERFELDIE  534000  600000

> df.loc['ABBOTSFORD']
2005    427000
2006    448000
Name: ABBOTSFORD, dtype: int64

> df.loc['ABBOTSFORD'][2005]
427000

> df.loc['ABBOTSFORD'].values
array([427000, 448000])

> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]

Excel CSV - Number cell format

Put a single quote before the field. Excel will treat it as text, even if it looks like a number.

...,`005,...

EDIT: This is wrong. The apostrophe trick only works when entering data directly into Excel. When you use it in a CSV file, the apostrophe appears in the field, which you don't want.

http://support.microsoft.com/kb/214233

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.

Using MySQL as an example (if for no other reason because it's most popular), you have DATE, DATETIME, TIME and TIMESTAMP column data types; just as you have CHAR, VARCHAR, FLOAT and INTEGER.

So, you ask, what's the difference? Well, some of them are self-explanatory. DATE only stores a date, TIME only stores a time of day, while DATETIME stores both.

The difference between DATETIME and TIMESTAMP is a bit more subtle: DATETIME is formatted as YYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIME stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP only stores the number of seconds since 1970-01-01, it uses 4 bytes.

You can read more about the differences between time formats in MySQL here.

In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP. Do you only need to store a date? Use DATE. Do you only need to store a time? Use TIME.

Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp and :datetime will default to DATETIME, while :date and :time corresponds to DATE and TIME, respectively.

This means that within Rails, you only have to decide whether you need to store date, time or both.

List View Filter Android

In case anyone are still interested in this subject, I find that the best approach for filtering lists is to create a generic Filter class and use it with some base reflection/generics techniques contained in the Java old school SDK package. Here's what I did:

public class GenericListFilter<T> extends Filter {

    /**
     * Copycat constructor
     * @param list  the original list to be used
     */
    public GenericListFilter (List<T> list, String reflectMethodName, ArrayAdapter<T> adapter) {
        super ();

        mInternalList = new ArrayList<>(list);
        mAdapterUsed  = adapter;

        try {
            ParameterizedType stringListType = (ParameterizedType)
                    getClass().getField("mInternalList").getGenericType();
            mCompairMethod =
                    stringListType.getActualTypeArguments()[0].getClass().getMethod(reflectMethodName);
        }
        catch (Exception ex) {
            Log.w("GenericListFilter", ex.getMessage(), ex);

            try {
                if (mInternalList.size() > 0) {
                    T type = mInternalList.get(0);
                    mCompairMethod = type.getClass().getMethod(reflectMethodName);
                }
            }
            catch (Exception e) {
                Log.e("GenericListFilter", e.getMessage(), e);
            }

        }
    }

    /**
     * Let's filter the data with the given constraint
     * @param constraint
     * @return
     */
    @Override protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        List<T> filteredContents = new ArrayList<>();

        if ( constraint.length() > 0 ) {
            try {
                for (T obj : mInternalList) {
                    String result = (String) mCompairMethod.invoke(obj);
                    if (result.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        filteredContents.add(obj);
                    }
                }
            }
            catch (Exception ex) {
                Log.e("GenericListFilter", ex.getMessage(), ex);
            }
        }
        else {
            filteredContents.addAll(mInternalList);
        }

        results.values = filteredContents;
        results.count  = filteredContents.size();
        return results;
    }

    /**
     * Publish the filtering adapter list
     * @param constraint
     * @param results
     */
    @Override protected void publishResults(CharSequence constraint, FilterResults results) {
        mAdapterUsed.clear();
        mAdapterUsed.addAll((List<T>) results.values);

        if ( results.count == 0 ) {
            mAdapterUsed.notifyDataSetInvalidated();
        }
        else {
            mAdapterUsed.notifyDataSetChanged();
        }
    }

    // class properties
    private ArrayAdapter<T> mAdapterUsed;
    private List<T> mInternalList;
    private Method  mCompairMethod;
}

And afterwards, the only thing you need to do is to create the filter as a member class (possibly within the View's "onCreate") passing your adapter reference, your list, and the method to be called for filtering:

this.mFilter = new GenericFilter<MyObjectBean> (list, "getName", adapter);

The only thing missing now, is to override the "getFilter" method in the adapter class:

@Override public Filter getFilter () {
     return MyViewClass.this.mFilter;
}

All done! You should successfully filter your list - Of course, you should also implement your filter algorithm the best way that describes your need, the code bellow is just an example.. Hope it helped, take care.

How to convert seconds to time format?

If You want nice format like: 0:00:00 use str_pad() as @Gardner.

Using Oracle to_date function for date string with milliseconds

TO_DATE supports conversion to DATE datatype, which doesn't support milliseconds. If you want millisecond support in Oracle, you should look at TIMESTAMP datatype and TO_TIMESTAMP function.

Hope that helps.

How do I restart nginx only after the configuration test was successful on Ubuntu?

You can use signals to control nginx.

According to documentation, you need to send HUP signal to nginx master process.

HUP - changing configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes with a new configuration, graceful shutdown of old worker processes

Check the documentation here: http://nginx.org/en/docs/control.html

You can send the HUP signal to nginx master process PID like this:

kill -HUP $( cat /var/run/nginx.pid )

The command above reads the nginx PID from /var/run/nginx.pid. By default nginx pid is written to /usr/local/nginx/logs/nginx.pid but that can be overridden in config. Check your nginx.config to see where it saves the PID.

Installing lxml module in python

You need to install Python's header files (python-dev package in debian/ubuntu) to compile lxml. As well as libxml2, libxslt, libxml2-dev, and libxslt-dev:

apt-get install python-dev libxml2 libxml2-dev libxslt-dev

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

Try changing the Web Client request authentication part to:

NetworkCredential myCreds = new NetworkCredential(userName, passWord);
client.Credentials = myCreds;

Then make your call, seems to work fine for me.

How to do an Integer.parseInt() for a decimal number?

String s="0.01";
int i = Double.valueOf(s).intValue();

Best programming based games

I got myself addicted to uplink a few months ago. It's not really coding based, more hacking. It's still fun and super geeky.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

Can't comment on Susam Pal's answer but if you're dealing with spaces, I'd surround with quotes:

for f in *.jpg; do mv "$f" "`echo $f | sed s/\ /\-/g`"; done;

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

Should IBOutlets be strong or weak under ARC?

In iOS development NIB loading is a little bit different from Mac development.

In Mac development an IBOutlet is usually a weak reference: if you have a subclass of NSViewController only the top-level view will be retained and when you dealloc the controller all its subviews and outlets are freed automatically.

UiViewController use Key Value Coding to set the outlets using strong references. So when you dealloc your UIViewController, the top view will automatically deallocated, but you must also deallocate all its outlets in the dealloc method.

In this post from the Big Nerd Ranch, they cover this topic and also explain why using a strong reference in IBOutlet is not a good choice (even if it is recommended by Apple in this case).

Get an array of list element contents in jQuery

And in clean javascript:

var texts = [], lis = document.getElementsByTagName("li");
for(var i=0, im=lis.length; im>i; i++)
  texts.push(lis[i].firstChild.nodeValue);

alert(texts);

The number of method references in a .dex file cannot exceed 64k API 17

**

For Unity Game Developers

**

If anyone comes here because this error showed up in their Unity project, Go to File->Build Settings -> Player Settings -> Player. go to Publishing Settings and under the Build tab, enable "Custom Launcher Gradle Template". a path will be shown under that text. go to the path and add multiDexEnabled true like this:

defaultConfig {
    minSdkVersion **MINSDKVERSION**
    targetSdkVersion **TARGETSDKVERSION**
    applicationId '**APPLICATIONID**'
    ndk {
        abiFilters **ABIFILTERS**
    }
    versionCode **VERSIONCODE**
    versionName '**VERSIONNAME**'
    multiDexEnabled true
}

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

How to change line width in ggplot?

If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.

library(ggplot2)
library(tidyr)

x = seq(0,10,0.05)

df <- data.frame(A = 2 * x + 10,
                 B = x**2 - x*6,
                 C = 30 - x**1.5,
                 X = x)


df = gather(df,A,B,C,key="Model",value="Y")


ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
  geom_line()+
  scale_size_manual( values = c(4,2,1) ) +
  scale_color_manual( values = c("orange","red","navy") ) 

How is CountDownLatch used in Java Multithreading?

As mentioned in JavaDoc (https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html), CountDownLatch is a synchronization aid, introduced in Java 5. Here the synchronization does not mean restricting access to a critical section. But rather sequencing actions of different threads. The type of synchronization achieved through CountDownLatch is similar to that of Join. Assume that there is a thread "M" which needs to wait for other worker threads "T1", "T2", "T3" to complete its tasks Prior to Java 1.5, the way this can be done is, M running the following code

    T1.join();
    T2.join();
    T3.join();

The above code makes sure that thread M resumes its work after T1, T2, T3 completes its work. T1, T2, T3 can complete their work in any order. The same can be achieved through CountDownLatch, where T1,T2, T3 and thread M share same CountDownLatch object.
"M" requests : countDownLatch.await();
where as "T1","T2","T3" does countDownLatch.countdown();

One disadvantage with the join method is that M has to know about T1, T2, T3. If there is a new worker thread T4 added later, then M has to be aware of it too. This can be avoided with CountDownLatch. After implementation the sequence of action would be [T1,T2,T3](the order of T1,T2,T3 could be anyway) -> [M]

What are the specific differences between .msi and setup.exe file?

MSI is basically an installer from Microsoft that is built into windows. It associates components with features and contains installation control information. It is not necessary that this file contains actual user required files i.e the application programs which user expects. MSI can contain another setup.exe inside it which the MSI wraps, which actually contains the user required files.

Hope this clears you doubt.

Searching in a ArrayList with custom objects for certain strings

Probably something like:

ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points

//Traversal
for(DataPoint myPoint : myList) {
    if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
        //Process data do whatever you want
        System.out.println("Found it!");
     }
}

setOnItemClickListener on custom ListView

I too had that same problem.. If we think logically little bit we can get the answer.. It worked for me very well.. I hope u will get it..

  1. listviewdemo.xml

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="30dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />
    

  2. listviewcontent.xml - note that TextView - android:id="@+id/txtLstItem"

    <LinearLayout
        android:id="@+id/listviewcontentlayout"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="horizontal">
    
        <ImageView
            android:id="@+id/img1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dp" />
    
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:orientation="vertical">
    
            <TextView
                android:id="@+id/txtLstItem"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:shadowColor="@android:color/black"
                android:shadowRadius="5"
                android:textColor="@android:color/white" />
    
        </LinearLayout>
    
        <ImageView
            android:id="@+id/img2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dp" />
    </LinearLayout>
    

  3. ListViewActivity.java - Note that view.findViewById(R.id.txtLstItem) - as we setting the value to TextView by setText() method we getting text from TextView by View object returned by onItemClick method. OnItemClick() returns the current view.

    TextView v=(TextView) view.findViewById(R.id.txtLstItem);
    Toast.makeText(getApplicationContext(), "selected Item Name is "+v.getText(), Toast.LENGTH_LONG).show();**
    

    Using this simple logic we can get other values like CheckBox, RadioButton, ImageView etc.

    ListView List = (ListView) findViewById(R.id.listview);
    cursor = cr.query(CONTENT_URI,projection,null,null,null);
    adapter = new ListViewCursorAdapter(ListViewActivity.this, R.layout.listviewcontent, cursor, from, to);
    
    cursor.moveToFirst();
    
    // Let activity manage the cursor
    startManagingCursor(cursor);
    
    List.setAdapter(adapter);
    List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick (AdapterView < ? > adapter, View view,int position, long arg){
                // TODO Auto-generated method stub
                TextView v = (TextView) view.findViewById(R.id.txtLstItem);
                Toast.makeText(getApplicationContext(), "selected Item Name is " + v.getText(), Toast.LENGTH_LONG).show();
            }
        }
    );
    

How do I timestamp every ping result?

  1. terminal output:

    ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}'

  2. file output:

    ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' > test.txt

  3. terminal + file output:

    ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' | tee test.txt

  4. file output background:

    nohup ping -i 5 google.com | xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' > test.txt &

How do I add images in laravel view?

normaly is better image store in public folder (because it has write permission already that you can use when I upload images to it)

public
    upload_media
         photos
            image.png


$image  = public_path() . '/upload_media/photos/image.png'; // destination path

view PHP

<img src="<?= $image ?>">

View blade

<img src="{{ $image }}">

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

SDK represents to software development kit, and IDE represents to integrated development environment. The IDE is the software or the program is used to write, compile, run, and debug such as Xcode. The SDK is the underlying engine of the IDE, includes all the platform's libraries an app needs to access. It's more basic than an IDE because it doesn't usually have graphical tools.

HashMap - getting First Key value

You may also try the following in order to get the entire first entry,

Map.Entry<String, String> entry = map.entrySet().stream().findFirst().get();
String key = entry.getKey();
String value = entry.getValue();

The following shows how you may get the key of the first entry,

String key = map.entrySet().stream().map(Map.Entry::getKey).findFirst().get();
// or better
String key = map.keySet().stream().findFirst().get();

The following shows how you may get the value of the first entry,

String value = map.entrySet().stream().map(Map.Entry::getValue).findFirst().get();
// or better
String value = map.values().stream().findFirst().get();

Moreover, in case wish to get the second (same for third etc) item of a map and you have validated that this map contains at least 2 entries, you may use the following.

Map.Entry<String, String> entry = map.entrySet().stream().skip(1).findFirst().get();
String key = map.keySet().stream().skip(1).findFirst().get();
String value = map.values().stream().skip(1).findFirst().get();

How do I create a self-signed certificate for code signing on Windows?

Updated Answer

If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.

If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.

Original Answer

While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:

Creating a self-signed certificate authority (CA)

makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
         -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer

(^ = allow batch command-line to wrap line)

This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).

The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.

Importing the CA certificate

Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:

certutil -user -addstore Root MyCA.cer

Creating a code-signing certificate (SPC)

makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
         -sky signature ^
         -ic MyCA.cer -iv MyCA.pvk ^
         -sv MySPC.pvk MySPC.cer

It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).

We'll also want to convert the certificate and key into a PFX file:

pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx

If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.

Using the certificate for signing code

signtool sign /v /f MySPC.pfx ^
              /t http://timestamp.url MyExecutable.exe

(See why timestamps may matter)

If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:

signtool sign /v /n "Me" /s SPC ^
              /t http://timestamp.url MyExecutable.exe

Some possible timestamp URLs for signtool /t are:

  • http://timestamp.verisign.com/scripts/timstamp.dll
  • http://timestamp.globalsign.com/scripts/timstamp.dll
  • http://timestamp.comodoca.com/authenticode

Full Microsoft documentation

Downloads

For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1). Your mileage may vary.

MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).

Setting a PHP $_SESSION['var'] using jQuery

in (backend.php) be sure to include include

session_start();

-Taylor http://www.hawkessolutions.com

Oracle date function for the previous month

The trunc() function truncates a date to the specified time period; so trunc(sysdate,'mm') would return the beginning of the current month. You can then use the add_months() function to get the beginning of the previous month, something like this:

select count(distinct switch_id)   
  from [email protected]  
 where dealer_name =  'XXXX'    
   and creation_date >= add_months(trunc(sysdate,'mm'),-1) 
   and creation_date < trunc(sysdate, 'mm')

As a little side not you're not explicitly converting to a date in your original query. Always do this, either using a date literal, e.g. DATE 2012-08-31, or the to_date() function, for example to_date('2012-08-31','YYYY-MM-DD'). If you don't then you are bound to get this wrong at some point.

You would not use sysdate - 15 as this would provide the date 15 days before the current date, which does not seem to be what you are after. It would also include a time component as you are not using trunc().


Just as a little demonstration of what trunc(<date>,'mm') does:

select sysdate
     , case when trunc(sysdate,'mm') > to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as gt
     , case when trunc(sysdate,'mm') < to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as lt
     , case when trunc(sysdate,'mm') = to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as eq
  from dual
       ;

SYSDATE                   GT         LT         EQ
----------------- ---------- ---------- ----------
20120911 19:58:51                                1

php form action php self

You can leave action blank or use this code:

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI'];?>">
</form>

How to make an element in XML schema optional?

Set the minOccurs attribute to 0 in the schema like so:

<?xml version="1.0"?>
  <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="request">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="amenity">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="description" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element> </xs:schema>

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Please note instead of

public TomcatEmbeddedServletContainerFactory tomcatFactory()

I had to use the following method signature

public EmbeddedServletContainerFactory embeddedServletContainerFactory() 

PHP Date Time Current Time Add Minutes

$time = strtotime(date('2016-02-03 12:00:00'));
        echo date("H:i:s",strtotime("-30 minutes", $time));

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

Replace and overwrite instead of appending

import os#must import this library
if os.path.exists('TwitterDB.csv'):
        os.remove('TwitterDB.csv') #this deletes the file
else:
        print("The file does not exist")#add this to prevent errors

I had a similar problem, and instead of overwriting my existing file using the different 'modes', I just deleted the file before using it again, so that it would be as if I was appending to a new file on each run of my code.

how to check if a form is valid programmatically using jQuery Validation Plugin

2015 answer: we have this out of the box on modern browsers, just use the HTML5 CheckValidity API from jQuery. I've also made a jquery-html5-validity module to do this:

npm install jquery-html5-validity

Then:

var $ = require('jquery')
require("jquery-html5-validity")($);

then you can run:

$('.some-class').isValid()

true

What is a stored procedure?

Generally, a stored procedure is a "SQL Function." They have:

-- a name
CREATE PROCEDURE spGetPerson
-- parameters
CREATE PROCEDURE spGetPerson(@PersonID int)
-- a body
CREATE PROCEDURE spGetPerson(@PersonID int)
AS
SELECT FirstName, LastName ....
FROM People
WHERE PersonID = @PersonID

This is a T-SQL focused example. Stored procedures can execute most SQL statements, return scalar and table-based values, and are considered to be more secure because they prevent SQL injection attacks.

Difference between string and StringBuilder in C#

Major difference:

String is immutable. It means that you can't modify a string at all; the result of modification is a new string. This is not effective if you plan to append to a string.

StringBuilder is mutable. It can be modified in any way and it doesn't require creation of a new instance. When the work is done, ToString() can be called to get the string.

Strings can participate in interning. It means that strings with same contents may have same addresses. StringBuilder can't be interned.

String is the only class that can have a reference literal.

What is the most efficient way to check if a value exists in a NumPy array?

The most convenient way according to me is:

(Val in X[:, col_num])

where Val is the value that you want to check for and X is the array. In your example, suppose you want to check if the value 8 exists in your the third column. Simply write

(8 in X[:, 2])

This will return True if 8 is there in the third column, else False.

How to redirect from one URL to another URL?

Why javascript?

http://www.instant-web-site-tools.com/html-redirect.html

<html>
<meta http-equiv="REFRESH" content="0;url=http://www.URL2.com"> 
</html>

Unless I'm missunderstanding...

How to print Two-Dimensional Array like table

Iliya,

Sorry for that.

you code is work. but its had some problem with Array row and columns

here i correct your code this work correctly, you can try this ..

public static void printMatrix(int size, int row, int[][] matrix) {

    for (int i = 0; i < 7 * matrix[row].length; i++) {
        System.out.print("-");
    }
    System.out.println("-");

    for (int i = 1; i <= matrix[row].length; i++) {
        System.out.printf("| %4d ", matrix[row][i - 1]);
    }
    System.out.println("|");

    if (row == size - 1) {

        // when we reach the last row,
        // print bottom line "---------"

        for (int i = 0; i < 7 * matrix[row].length; i++) {
            System.out.print("-");
        }
        System.out.println("-");

    }
}

public static void length(int[][] matrix) {

    int rowsLength = matrix.length;

    for (int k = 0; k < rowsLength; k++) {

        printMatrix(rowsLength, k, matrix);

    }

}

public static void main(String[] args) {

    int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }

    };

    length(matrix);

}

and out put look like

----------------------
|    1 |    2 |    5 |
----------------------
|    3 |    4 |    6 |
----------------------
|    7 |    8 |    9 |
----------------------

Most efficient way to get table row count

Following is the most performant way to find the next AUTO_INCREMENT value for a table. This is quick even on databases housing millions of tables, because it does not require querying the potentially large information_schema database.

mysql> SHOW TABLE STATUS LIKE 'table_name';
// Look for the Auto_increment column

However, if you must retrieve this value in a query, then to the information_schema database you must go.

SELECT `AUTO_INCREMENT`
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_SCHEMA = 'DatabaseName'
AND    TABLE_NAME   = 'TableName';

How do I compare two columns for equality in SQL Server?

Regarding David Elizondo's answer, this can give false positives. It also does not give zeroes where the values don't match.

Code

DECLARE @t1 TABLE (
    ColID   int     IDENTITY,
    Col2    int
)

DECLARE @t2 TABLE (
    ColID   int     IDENTITY,
    Col2    int
)

INSERT INTO @t1 (Col2) VALUES (123)
INSERT INTO @t1 (Col2) VALUES (234)
INSERT INTO @t1 (Col2) VALUES (456)
INSERT INTO @t1 (Col2) VALUES (1)

INSERT INTO @t2 (Col2) VALUES (123)
INSERT INTO @t2 (Col2) VALUES (345)
INSERT INTO @t2 (Col2) VALUES (456)
INSERT INTO @t2 (Col2) VALUES (2)

SELECT
    t1.Col2 AS t1Col2,
    t2.Col2 AS t2Col2,
    ISNULL(NULLIF(t1.Col2, t2.Col2), 1) AS MyDesiredResult
FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID

Results

     t1Col2      t2Col2 MyDesiredResult
----------- ----------- ---------------
        123         123               1
        234         345             234 <- Not a zero
        456         456               1
          1           2               1 <- Not a match

Count number of occurrences by month

use count instead of sum in your original formula u will get your result

Original One

=SUM(IF(MONTH('2013'!$A$2:$A$19)=4,'2013'!$D$2:$D$19,0))

Modified One

=COUNT(IF(MONTH('2013'!$A$2:$A$19)=4,'2013'!$D$2:$D$19,0))

AND USE ctrl+shift+enter TO EXECUTE

CURRENT_DATE/CURDATE() not working as default DATE value

According to this documentation, starting in MySQL 8.0.13, you will be able to specify:

CREATE TABLE INVOICE(
    INVOICEDATE DATE DEFAULT (CURRENT_DATE)
)

Unfortunately, as of today, that version is not yet released. You can check here for the latest updates.

jQuery: Load Modal Dialog Contents via Ajax

Check out this blog post from Nemikor, which should do what you want.

http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/

Basically, before calling 'open', you 'load' the content from the other page first.

jQuery('#dialog').load('path to my page').dialog('open'); 

How do I discard unstaged changes in Git?

You could create your own alias which describes how to do it in a descriptive way.

I use the next alias to discard changes.


Discard changes in a (list of) file(s) in working tree

discard = checkout --

Then you can use it as next to discard all changes:

discard .

Or just a file:

discard filename

Otherwise, if you want to discard all changes and also the untracked files, I use a mix of checkout and clean:

Clean and discard changes and untracked files in working tree

cleanout = !git clean -df && git checkout -- .

So the use is simple as next:

cleanout

Now is available in the next Github repo which contains a lot of aliases:

How to fix Warning Illegal string offset in PHP

Please check that your key exists in the array or not, instead of simply trying to access it.

Replace:

$myVar = $someArray['someKey']

With something like:

if (isset($someArray['someKey'])) {
    $myVar = $someArray['someKey']
}

or something like:

if(is_array($someArray['someKey'])) {
    $theme_img = 'recent_works_iso_thumbnail';
}else {
    $theme_img = 'recent_works_iso_thumbnail';
}

jQuery .each() with input elements

You can use:

$(formId).serializeArray();

How do you add multi-line text to a UIButton?

Roll your own button class. It's by far the best solution in the long run. UIButton and other UIKit classes are very restrictive in how you can customize them.

Putting a password to a user in PhpMyAdmin in Wamp

There is a file called config.inc.php in the phpmyadmin folder.

The file path is C:\wamp\apps\phpmyadmin4.0.4

Edit The auth_type 'cookie' to 'config' or 'http'

$cfg['Servers'][$i]['auth_type'] = 'cookie';

$cfg['Servers'][$i]['auth_type'] = 'config';

or

$cfg['Servers'][$i]['auth_type'] = 'http';

When you go to the phpmyadmin site then you will be asked for the username and password. This also secure external people from accessing your phpmyadmin application if you happen to have your web server exposed to outside connections.

file_put_contents - failed to open stream: Permission denied

Realise this is pretty old now, but there's no need to manually write queries to a file like this. MySQL has logging support built in, you just need to enable it within your dev environment.

Take a look at the documentation for the 'general query log':

http://dev.mysql.com/doc/refman/5.1/en/query-log.html

How to cancel a pull request on github?

Super EASY way to close a Pull Request - LATEST!

  1. Navigate to the Original Repository where the pull request has been submitted to.
  2. Select the Pull requests tab
  3. Select your pull request that you wish to remove. This will open it up.
  4. Towards the bottom, just enter a valid comment for closure and press Close Pull Request button

enter image description here

How to force Docker for a clean build of an image

With docker-compose try docker-compose up -d --build --force-recreate

How to programmatically determine the current checked out Git branch

If you are on a detached head (i.e. you've checked out a release) and have an output from git status such as

HEAD detached at v1.7.3.1

And you want the release version, we use the following command...

git status --branch | head -n1 | tr -d 'A-Za-z: '

This returns 1.7.3.1, which we replace in our parameters.yml (Symfony) with

# RevNum=`svn status -u | grep revision | tr -d 'A-Za-z: '`  # the old SVN version
RevNum=`git status --branch | head -n1 | tr -d 'A-Za-z: '` # Git (obvs)

sed -i "/^    app_version:/c\    app_version:$RevNum" app/config/parameters.yml

Hope this helps :) Obviously if you have non-numerics in your branch name, you'll need to alter the arguments to the tr command.

Using for loop inside of a JSP

Do this

    <% for(int i = 0; i < allFestivals.size(); i+=1) { %>
        <tr>      
            <td><%=allFestivals.get(i).getFestivalName()%></td>
        </tr>
    <% } %>

Better way is to use c:foreach see link jstl for each

Reloading submodules in IPython

http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/

To avoid typing those magic function again and again, they could be put in the ipython startup script(Name it with .py suffix under .ipython/profile_default/startup. All python scripts under that folder will be loaded according to lexical order), which looks like the following:

from IPython import get_ipython
ipython = get_ipython()

ipython.magic("pylab")
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")

Setting a windows batch file variable to the day of the week

Another spin on this topic. The below script displays a few days around the current, with day-of-week prefix.

At the core is the standalone :dpack routine that encodes the date into a value whose modulo 7 reveals the day-of-week per ISO 8601 standards (Mon == 0). Also provided is :dunpk which is the inverse function:

@echo off& setlocal enabledelayedexpansion
rem 10/23/2018 daydate.bat: Most recent version at paulhoule.com/daydate
rem Example of date manipulation within a .BAT file.
rem This is accomplished by first packing the date into a single number.
rem This demo .bat displays dates surrounding the current date, prefixed
rem with the day-of-week.

set days=0Mon1Tue2Wed3Thu4Fri5Sat6Sun
call :dgetl y m d
call :dpack p %y% %m% %d%
for /l %%o in (-3,1,3) do (
  set /a od=p+%%o
  call :dunpk y m d !od!
  set /a dow=od%%7
  for %%d in (!dow!) do set day=!days:*%%d=!& set day=!day:~,3!
  echo !day! !y! !m! !d!
)
exit /b


rem gets local date returning year month day as separate variables
rem in: %1 %2 %3=var names for returned year month day
:dgetl
setlocal& set "z="
for /f "skip=1" %%a in ('wmic os get localdatetime') do set z=!z!%%a
set /a y=%z:~0,4%, m=1%z:~4,2% %%100, d=1%z:~6,2% %%100
endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b


rem packs date (y,m,d) into count of days since 1/1/1 (0..n)
rem in: %1=return var name, %2= y (1..n), %3=m (1..12), %4=d (1..31)
rem out: set %1= days since 1/1/1 (modulo 7 is weekday, Mon= 0)
:dpack
setlocal enabledelayedexpansion
set mtb=xxx  0 31 59 90120151181212243273304334& set /a r=%3*3
set /a t=%2-(12-%3)/10, r=365*(%2-1)+%4+!mtb:~%r%,3!+t/4-(t/100-t/400)-1
endlocal& set %1=%r%& exit /b


rem inverse of date packer
rem in: %1 %2 %3=var names for returned year month day
rem %4= packed date (large decimal number, eg 736989)
:dunpk
setlocal& set /a y=%4+366, y+=y/146097*3+(y%%146097-60)/36524
set /a y+=y/1461*3+(y%%1461-60)/365, d=y%%366+1, y/=366
set e=31 60 91 121 152 182 213 244 274 305 335
set m=1& for %%x in (%e%) do if %d% gtr %%x set /a m+=1, d=%d%-%%x
endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b

Removing an item from a select box

To Remove an Item

$("select#mySelect option[value='option1']").remove(); 

To Add an item

$("#mySelect").append('<option value="option1">Option</option>');

To Check for an option

$('#yourSelect option[value=yourValue]').length > 0;

To remove a selected option

$('#mySelect :selected').remove(); 

Where is SQL Server Management Studio 2012?

I've found that the command line is my friend in these situations.

I installed the SQL Server 2012 Enterprise Management Tools, including Management Studio, off the DVD (mounted ISO actually), without installing anything else using this command:

e:\setup.exe /Q /IACCEPTSQLSERVERLICENSETERMS /ACTION=install /FEATURES=Tools

Run the command prompt with elevated privileges. And be patient, as it has to unpack the installation files. Don't try to install the MSI files directly, as you lose the dependency checking packaged with the main installer.

Again, this is to install the full version off the Enterprise or Developer media, if you have it, and do not wish to settle for the free Express edition.

Store List to session

Yes. Which platform are you writing for? ASP.NET C#?

List<string> myList = new List<string>();
Session["var"] = myList;

Then, to retrieve:

myList = (List<string>)Session["var"];

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

in my case, I try tried File>Invalidate Cache/Restart and that works for me.

Where to put default parameter value in C++?

You may do in either (according to standard), but remember, if your code is seeing the declaration without default argument(s) before the definition that contains default argument, then compilation error can come.

For example, if you include header containing function declaration without default argument list, thus compiler will look for that prototype as it is unaware of your default argument values and hence prototype won't match.

If you are putting function with default argument in definition, then include that file but I won't suggest that.

How do implement a breadth first traversal?

Breadth first is a queue, depth first is a stack.

For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.

For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.

Oracle Differences between NVL and Coalesce

Actually I cannot agree to each statement.

"COALESCE expects all arguments to be of same datatype."

This is wrong, see below. Arguments can be different data types, that is also documented: If all occurrences of expr are numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type, then Oracle Database determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type.. Actually this is even in contradiction to common expression "COALESCE stops at first occurrence of a non-Null value", otherwise test case No. 4 should not raise an error.

Also according to test case No. 5 COALESCE does an implicit conversion of arguments.

DECLARE
    int_val INTEGER := 1;
    string_val VARCHAR2(10) := 'foo';
BEGIN

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '1. NVL(int_val,string_val) -> '|| NVL(int_val,string_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('1. NVL(int_val,string_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '2. NVL(string_val, int_val) -> '|| NVL(string_val, int_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('2. NVL(string_val, int_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '3. COALESCE(int_val,string_val) -> '|| COALESCE(int_val,string_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('3. COALESCE(int_val,string_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '4. COALESCE(string_val, int_val) -> '|| COALESCE(string_val, int_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('4. COALESCE(string_val, int_val) -> '||SQLERRM ); 
    END;

    DBMS_OUTPUT.PUT_LINE( '5. COALESCE(SYSDATE,SYSTIMESTAMP) -> '|| COALESCE(SYSDATE,SYSTIMESTAMP) );

END;
Output:

1. NVL(int_val,string_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
2. NVL(string_val, int_val) -> foo
3. COALESCE(int_val,string_val) -> 1
4. COALESCE(string_val, int_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
5. COALESCE(SYSDATE,SYSTIMESTAMP) -> 2016-11-30 09:55:55.000000 +1:0 --> This is a TIMESTAMP value, not a DATE value!

CSS :not(:last-child):after selector

Every things seems correct. You might want to use the following css selector instead of what you used.

ul > li:not(:last-child):after

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

How do you underline a text in Android XML?

There are different ways to achieve underlined text in an Android TextView.

1.<u>This is my underlined text</u> or

I just want to underline <u>this</u> word

2.You can do the same programmatically.

`textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);`

3.It can be done by creating a SpannableString and then setting it as the TextView text property

SpannableString text = new SpannableString("Voglio sottolineare solo questa parola");
text.setSpan(new UnderlineSpan(), 25, 6, 0);
textView.setText(text);

Sharing link on WhatsApp from mobile website (not application) for Android

Just saw it on a website and seems to work on latest Android with latest chrome and whatsapp now too! Give the link a new shot!

<a href="whatsapp://send?text=The text to share!" data-action="share/whatsapp/share">Share via Whatsapp</a>

Rechecked it today (17th April 2015):
Works for me on iOS 8 (iPhone 6, latest versions) Android 5 (Nexus 5, latest versions).

It also works on Windows Phone.

TypeScript static classes

TypeScript is not C#, so you shouldn't expect the same concepts of C# in TypeScript necessarily. The question is why do you want static classes?

In C# a static class is simply a class that cannot be subclassed and must contain only static methods. C# does not allow one to define functions outside of classes. In TypeScript this is possible, however.

If you're looking for a way to put your functions/methods in a namespace (i.e. not global), you could consider using TypeScript's modules, e.g.

module M {
    var s = "hello";
    export function f() {
        return s;
    }
}

So that you can access M.f() externally, but not s, and you cannot extend the module.

See the TypeScript specification for more details.

How to keep an iPhone app running on background fully operational

For running on stock iOS devices, make your app an audio player/recorder or a VOIP app, a legitimate one for submitting to the App store, or a fake one if only for your own use.

Even this won't make an app "fully operational" whatever that is, but restricted to limited APIs.

REST API Authentication

For e.g. when a user has login.Now lets say the user want to create a forum topic, How will I know that the user is already logged in?

Think about it - there must be some handshake that tells your "Create Forum" API that this current request is from an authenticated user. Since REST APIs are typically stateless, the state must be persisted somewhere. Your client consuming the REST APIs is responsible for maintaining that state. Usually, it is in the form of some token that gets passed around since the time the user was logged in. If the token is good, your request is good.

Check how Amazon AWS does authentications. That's a perfect example of "passing the buck" around from one API to another.

*I thought of adding some practical response to my previous answer. Try Apache Shiro (or any authentication/authorization library). Bottom line, try and avoid custom coding. Once you have integrated your favorite library (I use Apache Shiro, btw) you can then do the following:

  1. Create a Login/logout API like: /api/v1/login and api/v1/logout
  2. In these Login and Logout APIs, perform the authentication with your user store
  3. The outcome is a token (usually, JSESSIONID) that is sent back to the client (web, mobile, whatever)
  4. From this point onwards, all subsequent calls made by your client will include this token
  5. Let's say your next call is made to an API called /api/v1/findUser
  6. The first thing this API code will do is to check for the token ("is this user authenticated?")
  7. If the answer comes back as NO, then you throw a HTTP 401 Status back at the client. Let them handle it.
  8. If the answer is YES, then proceed to return the requested User

That's all. Hope this helps.

How do I print bold text in Python?

Install the termcolor module

sudo pip install termcolor

and then try this for colored text

from termcolor import colored
print colored('Hello', 'green')

or this for bold text:

from termcolor import colored
print colored('Hello', attrs=['bold'])

In Python 3 you can alternatively use cprint as a drop-in replacement for the built-in print, with the optional second parameter for colors or the attrs parameter for bold (and other attributes such as underline) in addition to the normal named print arguments such as file or end.

import sys
from termcolor import cprint
cprint('Hello', 'green', attrs=['bold'], file=sys.stderr)

Full disclosure, this answer is heavily based on Olu Smith's answer and was intended as an edit, which would have reduced the noise on this page considerably but because of some reviewers' misguided concept of what an edit is supposed to be, I am now forced to make this a separate answer.

The EntityManager is closed

In controller.

Exception closes the Entity Manager. This makes troubles for bulk insert. To continue, need to redefine it.

/** 
* @var  \Doctrine\ORM\EntityManager
*/
$em = $this->getDoctrine()->getManager();

foreach($to_insert AS $data)
{
    if(!$em->isOpen())
    {
        $this->getDoctrine()->resetManager();
        $em = $this->getDoctrine()->getManager();
    }

  $entity = new \Entity();
  $entity->setUniqueNumber($data['number']);
  $em->persist($entity);

  try
  {
    $em->flush();
    $counter++;
  }
  catch(\Doctrine\DBAL\DBALException $e)
  {
    if($e->getPrevious()->getCode() != '23000')
    {   
      /**
      * if its not the error code for a duplicate key 
      * value then rethrow the exception
      */
      throw $e;
    }
    else
    {
      $duplication++;
    }               
  }                      
}

Filezilla FTP Server Fails to Retrieve Directory Listing

I solved this by going into Site Manager -> selected the connection that Failed to retrieve directory listing -> Switched to tab "Transfer Settings" and set "Transfer Mode" to "Active" instead of "Default". Also check if you are connected via VPN or anything similar, this can also interfere.

Extract a single (unsigned) integer from a string

preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);

The first argument in implode in this specific case says "separate each element in matches[0] with a single space." Implode will not put a space (or whatever your first argument is) before the first number or after the last number.

Something else to note is $matches[0] is where the array of matches (that match this regular expression) found are stored.

For further clarification on what the other indexes in the array are for see: http://php.net/manual/en/function.preg-match-all.php

How to uninstall with msiexec using product id guid without .msi file present

There's no reason for the {} command not to work. The semi-obvious questions are:

  1. You are sure that the product is actually installed! There's something in ARP/Programs&Features.

  2. The original install is in fact visible in the current context. It looks as if it might have been a per-user install, and if you are logged in as somebody else now then it won't know about it - you'd need to log in under the same account as the original install.

  3. If the \windows\installer directory was damaged the cached file would be missing, and that's used to do the uninstall.

Preloading images with JavaScript

The browser will work best using the link tag in the head.

export function preloadImages (imageSources: string[]): void {
  imageSources
    .forEach(i => {
      const linkEl = document.createElement('link');
      linkEl.setAttribute('rel', 'preload');
      linkEl.setAttribute('href', i);
      linkEl.setAttribute('as', 'image');
      document.head.appendChild(linkEl);
    });
}

List all files and directories in a directory + subdirectories

Directory.GetFileSystemEntries exists in .NET 4.0+ and returns both files and directories. Call it like so:

string[] entries = Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories);

Note that it won't cope with attempts to list the contents of subdirectories that you don't have access to (UnauthorizedAccessException), but it may be sufficient for your needs.

Simple If/Else Razor Syntax

A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.

tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }

or

tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}

How to connect to MySQL Database?

 private void Initialize()
    {
        server = "localhost";
        database = "connectcsharptomysql";
        uid = "username";
        password = "password";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" + 
        database + ";" + "U`enter code here`ID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);
    }

Disable ONLY_FULL_GROUP_BY

On MySQL 5.7 and Ubuntu 16.04, edit the file mysql.cnf.

$ sudo nano /etc/mysql/conf.d/mysql.cnf

Include the sql_mode like the following and save the file.

[mysql]
sql_mode=IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

Observe that, in my case, I removed the mode STRICT_TRANS_TABLES and the ONLY_FULL_GROUP_BY.

Doing this, it will save the mode configuration permanently. Differently if you just update the @@sql_mode through MySQL, because it will reset on machine/service restart.

After that, to the modified configuration take in action, restart the mysql service:

$ sudo service mysql restart

Try to access the mysql:

$ mysql -u user_name -p

If you are able to login and access MySQL console, it is ok. Great!

BUT, if like me, you face the error "unknown variable sql_mode", which indicates that sql_mode is an option for mysqld, you will have to go back, edit the file mysql.cnf again and change the [mysql] to [mysqld]. Restart the MySQL service and do a last test trying to login on MySQL console. Here it is!

Programmatically change UITextField Keyboard type

Here are the type of keyboard in Swift 4.2

// UIKeyboardType
//
// Requests that a particular keyboard type be displayed when a text widget
// becomes first responder. 
// Note: Some keyboard/input methods types may not support every variant. 
// In such cases, the input method will make a best effort to find a close 
// match to the requested type (e.g. displaying UIKeyboardTypeNumbersAndPunctuation 
// type if UIKeyboardTypeNumberPad is not supported).
//
public enum UIKeyboardType : Int {


    case `default` // Default type for the current input method.

    case asciiCapable // Displays a keyboard which can enter ASCII characters

    case numbersAndPunctuation // Numbers and assorted punctuation.

    case URL // A type optimized for URL entry (shows . / .com prominently).

    case numberPad // A number pad with locale-appropriate digits (0-9, ?-?, ?-?, etc.). Suitable for PIN entry.

    case phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).

    case namePhonePad // A type optimized for entering a person's name or phone number.

    case emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).

    @available(iOS 4.1, *)
    case decimalPad // A number pad with a decimal point.

    @available(iOS 5.0, *)
    case twitter // A type optimized for twitter text entry (easy access to @ #)

    @available(iOS 7.0, *)
    case webSearch // A default keyboard type with URL-oriented addition (shows space . prominently).

    @available(iOS 10.0, *)
    case asciiCapableNumberPad // A number pad (0-9) that will always be ASCII digits.


    public static var alphabet: UIKeyboardType { get } // Deprecated
}

Python3 project remove __pycache__ folders and .pyc files

I found the answer myself when I mistyped pyclean as pycclean:

    No command 'pycclean' found, did you mean:
     Command 'py3clean' from package 'python3-minimal' (main)
     Command 'pyclean' from package 'python-minimal' (main)
    pycclean: command not found

Running py3clean . cleaned it up very nicely.

How to initialize all members of an array to the same value?

  1. If your array is declared as static or is global, all the elements in the array already have default default value 0.
  2. Some compilers set array's the default to 0 in debug mode.
  3. It is easy to set default to 0 : int array[10] = {0};
  4. However, for other values, you have use memset() or loop;

example: int array[10]; memset(array,-1, 10 *sizeof(int));

How do I make a text go onto the next line if it overflows?

As long as you specify a width on the element, it should wrap itself without needing anything else.

How to display pandas DataFrame of floats using a format string for columns?

As of Pandas 0.17 there is now a styling system which essentially provides formatted views of a DataFrame using Python format strings:

import pandas as pd
import numpy as np

constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C

which displays

enter image description here

This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:

constants.name = ['pie','eek']
C

enter image description here

However it appears to have some limitations:

  • Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn't add row/column labels):

    constants.loc[2] = dict(name='bogus', value=123.456)
    constants['comment'] = ['fee','fie','fo']
    constants
    

enter image description here

which looks ok but:

C

enter image description here

  • Formatting works only for values, not index entries:

    constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
    constants.set_index('name',inplace=True)
    C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
    C
    

enter image description here

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

Rewrite the query into this

SELECT st1.*, st2.relevant_field FROM sometable st1
INNER JOIN sometable st2 ON (st1.relevant_field = st2.relevant_field)
GROUP BY st1.id  /* list a unique sometable field here*/
HAVING COUNT(*) > 1

I think st2.relevant_field must be in the select, because otherwise the having clause will give an error, but I'm not 100% sure

Never use IN with a subquery; this is notoriously slow.
Only ever use IN with a fixed list of values.

More tips

  1. If you want to make queries faster, don't do a SELECT * only select the fields that you really need.
  2. Make sure you have an index on relevant_field to speed up the equi-join.
  3. Make sure to group by on the primary key.
  4. If you are on InnoDB and you only select indexed fields (and things are not too complex) than MySQL will resolve your query using only the indexes, speeding things way up.

General solution for 90% of your IN (select queries

Use this code

SELECT * FROM sometable a WHERE EXISTS (
  SELECT 1 FROM sometable b
  WHERE a.relevant_field = b.relevant_field
  GROUP BY b.relevant_field
  HAVING count(*) > 1) 

How do I lock the orientation to portrait mode in a iPhone Web Application?

I like the idea of telling the user to put his phone back into portrait mode. Like it's mentioned here: http://tech.sarathdr.com/featured/prevent-landscape-orientation-of-iphone-web-apps/ ...but utilising CSS instead of JavaScript.

Using bootstrap with bower

There is a prebuilt bootstrap bower package called bootstrap-css. I think this is what you (and I) were hoping to find.

bower install bootstrap-css

Thanks Nico.

Stop Visual Studio from mixing line endings in files

On the File menu, choose Advanced Save Options, you can control it there.

Edit: Here's the documentation, you should have a file open first.

How do I get and set Environment variables in C#?

This will work for an environment variable that is machine setting. For Users, just change to User instead.

String EnvironmentPath = System.Environment
                .GetEnvironmentVariable("Variable_Name", EnvironmentVariableTarget.Machine);

How to set radio button selected value using jquery

Below script works fine in all browser:

function RadionButtonSelectedValueSet(name, SelectdValue) {
     $('input[name="' + name + '"][value="' + SelectdValue + '"]').attr('checked',true);
}

Adding Permissions in AndroidManifest.xml in Android Studio?

Go to Android Manifest.xml and be sure to add the <uses-permission tag > inside the manifest tag but Outside of all other tags..

<manifest xlmns:android...>

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

This is an example of the permission of using Internet.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

It is simple: if recv() returns 0 bytes; you will not receive any more data on this connection. Ever. You still might be able to send.

It means that your non-blocking socket have to raise an exception (it might be system-dependent) if no data is available but the connection is still alive (the other end may send).