Programs & Examples On #Dasblog

Quicker way to get all unique values of a column in VBA?

Try this

Option Explicit

Sub UniqueValues()
Dim ws As Worksheet
Dim uniqueRng As Range
Dim myCol As Long

myCol = 5 '<== set it as per your needs
Set ws = ThisWorkbook.Worksheets("unique") '<== set it as per your needs

Set uniqueRng = GetUniqueValues(ws, myCol)

End Sub


Function GetUniqueValues(ws As Worksheet, col As Long) As Range
Dim firstRow As Long

With ws
    .Columns(col).RemoveDuplicates Columns:=Array(1), header:=xlNo

    firstRow = 1
    If IsEmpty(.Cells(1, col)) Then firstRow = .Cells(1, col).End(xlDown).row

    Set GetUniqueValues = Range(.Cells(firstRow, col), .Cells(.Rows.Count, col).End(xlUp))
End With

End Function

it should be quite fast and without the drawback NeepNeepNeep told about

Get SSID when WIFI is connected

Android 9 SSID showing NULL values use this code..

ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            wifiInfo.getSSID();
            String name = networkInfo.getExtraInfo();
            String ssid = wifiInfo.getSSID();
            return ssid.replaceAll("^\"|\"$", "");
        }

git rebase fatal: Needed a single revision

Check that you spelled the branch name correctly. I was rebasing a story branch (i.e. branch_name) and forgot the story part. (i.e. story/branch_name) and then git spit this error at me which didn't make much sense in this context.

When to use single quotes, double quotes, and backticks in MySQL

If table cols and values are variables then there are two ways:

With double quotes "" the complete query:

$query = "INSERT INTO $table_name (id, $col1, $col2)
                 VALUES (NULL, '$val1', '$val2')";

Or

 $query = "INSERT INTO ".$table_name." (id, ".$col1.", ".$col2.")
               VALUES (NULL, '".$val1."', '".$val2."')";

With single quotes '':

$query = 'INSERT INTO '.$table_name.' (id, '.$col1.', '.$col2.')
             VALUES (NULL, '.$val1.', '.$val2.')';

Use back ticks `` when a column/value name is similar to a MySQL reserved keyword.

Note: If you are denoting a column name with a table name then use back ticks like this:

`table_name`. `column_name` <-- Note: exclude . from back ticks.

Passing data between controllers in Angular JS?

From the description, seems as though you should be using a service. Check out http://egghead.io/lessons/angularjs-sharing-data-between-controllers and AngularJS Service Passing Data Between Controllers to see some examples.

You could define your product service (as a factory) as such:

app.factory('productService', function() {
  var productList = [];

  var addProduct = function(newObj) {
      productList.push(newObj);
  };

  var getProducts = function(){
      return productList;
  };

  return {
    addProduct: addProduct,
    getProducts: getProducts
  };

});

Dependency inject the service into both controllers.

In your ProductController, define some action that adds the selected object to the array:

app.controller('ProductController', function($scope, productService) {
    $scope.callToAddToProductList = function(currObj){
        productService.addProduct(currObj);
    };
});

In your CartController, get the products from the service:

app.controller('CartController', function($scope, productService) {
    $scope.products = productService.getProducts();
});

set environment variable in python script

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))

Is there any kind of hash code function in JavaScript?

My solution introduces a static function for the global Object object.

(function() {
    var lastStorageId = 0;

    this.Object.hash = function(object) {
        var hash = object.__id;

        if (!hash)
             hash = object.__id = lastStorageId++;

        return '#' + hash;
    };
}());

I think this is more convenient with other object manipulating functions in JavaScript.

Getting unix timestamp from Date()

To get a timestamp from Date(), you'll need to divide getTime() by 1000, i.e. :

Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691

or simply:

long unixTime = System.currentTimeMillis() / 1000L;

How to find foreign key dependencies in SQL Server?

SELECT  obj.name AS FK_NAME,
    sch.name AS [schema_name],
    tab1.name AS [table],
    col1.name AS [column],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id

It will give you:

The FK itself Schema that the FK belongs to

  • The "referencing table" or the table that has the FK
  • The "referencing column" or the column inside referencing table that points to the FK
  • The "referenced table" or the table that has the key column that your FK is pointing to
  • The "referenced column" or the column that is the key that your FK is pointing to

Http Post With Body

You can use HttpClient and HttpPost to build and send the request.

HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));

request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);

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

nil? is a standard Ruby method that can be called on all objects and returns true if the object is nil:

b = nil
b.nil? # => true

empty? is a standard Ruby method that can be called on some objects such as Strings, Arrays and Hashes and returns true if these objects contain no element:

a = []
a.empty? # => true

b = ["2","4"]
b.empty? # => false

empty? cannot be called on nil objects.

blank? is a Rails method that can be called on nil objects as well as empty objects.

What is the difference between a .cpp file and a .h file?

A good rule of thumb is ".h files should have declarations [potentially] used by multiple source files, but no code that gets run."

Android TextView Justify Text

You can use justificationMode as inter_word in xml. You have to remember that this attribute is available for api level 26 and higher. For that you can assign targetApi as o. The full code is given bellow

<com.google.android.material.textview.MaterialTextView
            ...
            android:justificationMode="inter_word"
            tools:targetApi="o" />

How to set response header in JAX-RS so that user sees download popup for Excel?

I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.

package local.test.servlet;

import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;

@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        try {

            URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
            //   /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
            System.out.println(templateFileUrl.getPath());
            String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
            String outputFileDir = "MasatoExcelHorizontalOutput";

            ReportProcessor reportProcessor = new ReportProcessor();
            ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);

            ReportSheet outputSheet = new ReportSheet("MySheet");
            outputBook.addReportSheet(outputSheet);

            reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
            System.out.println("wtf???");
            reportProcessor.process(outputBook);


            System.out.println("done!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }

    } //end doGet()

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}//end class



class OutputStreamExporter extends ReportBookExporter {

    private HttpServletResponse response;

    public OutputStreamExporter(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public String getExtention() {
        return null;
    }

    @Override
    public String getFormatType() {
        return ExcelExporter.FORMAT_TYPE;
    }

    @Override
    public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {

        System.out.println(book.getFirstVisibleTab());
        System.out.println(book.getSheetName(0));

        //TODO write to stream
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
            book.write(response.getOutputStream());
            response.getOutputStream().close();
            System.out.println("booya!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}//end class

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Background

Invariant's answer is a good resource for how everything was started and what was the state of JavaFX on embedded and mobile in beginning of 2014. But, a lot has changed since then and the users who stumble on this thread do not get the updated information.

Most of my points are related to Invariant's answer, so I would suggest to go through it first.

Current Status of JavaFX on Mobile / Embedded

UPDATE

JavaFXPorts has been deprecated. Gluon Mobile now uses GraalVM underneath. There are multiple advantages of using GraalVM. Please check this blogpost from Gluon. The IDE plugins have been updated to use Gluon Client plugins which leverages GraalVM to AOT compile applications for Android/iOS.

Old answer with JavaFXPorts

Some bad news first:

Now, some good news:

  • JavaFX still runs on Android, iOS and most of the Embedded devices
  • JavaFXPorts SDK for android, iOS and embedded devices can be downloaded from here
  • JavaFXPorts project is still thriving and it is easier than ever to run JavaFX on mobile devices, all thanks to the IDE plugins that is built on top of these SDKs and gets you started in a few minutes without the hassle of installing any SDK
  • JavaFX 3D is now supported on mobile devices
  • GluonVM to replace RoboVM enabling Java 9 support for mobile developers. Yes, you heard it right.
  • Mobile Project has been launched by Oracle to support JDK on all major mobile platforms. It should support JavaFX as well ;)

How to get started

If you are not the DIY kind, I would suggest to install the IDE plugin on your favourite IDE and get started.

Most of the documentation on how to get started can be found here and some of the samples can be found here.

Single line if statement with 2 actions

You can write that in single line, but it's not something that someone would be able to read. Keep it like you already wrote it, it's already beautiful by itself.

If you have too much if/else constructs, you may think about using of different datastructures, like Dictionaries (to look up keys) or Collection (to run conditional LINQ queries on it)

Split string into string array of single characters

Strings in C# already have a char indexer

string test = "this is a test";
Console.WriteLine(test[0]);

And...

if(test[0] == 't')
  Console.WriteLine("The first letter is 't'");

This works too...

Console.WriteLine("this is a test"[0]);

And this...

foreach (char c in "this is a test")
  Console.WriteLine(c);

EDIT:

I noticed the question was updated with regards to char[] arrays. If you must have a string[] array, here's how you split a string at each character in c#:

string[] test = Regex.Split("this is a test", string.Empty);

foreach (string s in test)
{
  Console.WriteLine(s);
}

How to generate UL Li list from string array using jquery?

Other variation of Abhishek Bhalani: You can use Array.map() instead of $.each()

var items = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist');
items.map( (item,i ) => {
      var li = $('<li/>')
        .addClass('ui-menu-item')
        .attr('role', 'menuitem')
        .appendTo(cList);
      $('<a class="ui-all">'+ i + ': ' + item.name + '<a/>')
        .appendTo(li);
    });

Select DataFrame rows between two dates

I feel the best option will be to use the direct checks rather than using loc function:

df = df[(df['date'] > '2000-6-1') & (df['date'] <= '2000-6-10')]

It works for me.

Major issue with loc function with a slice is that the limits should be present in the actual values, if not this will result in KeyError.

How to select clear table contents without destroying the table?

There is a condition that most of these solutions do not address. I revised Patrick Honorez's solution to handle it. I felt I had to share this because I was pulling my hair out when the original function was occasionally clearing more data that I expected.

The situation happens when the table only has one column and the .SpecialCells(xlCellTypeConstants).ClearContents attempts to clear the contents of the top row. In this situation, only one cell is selected (the top row of the table that only has one column) and the SpecialCells command applies to the entire sheet instead of the selected range. What was happening to me was other cells on the sheet that were outside of my table were also getting cleared.

I did some digging and found this advice from Mathieu Guindon: Range SpecialCells ClearContents clears whole sheet

Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.

Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.

If the list/table only has one column (in row 1), this revision will check to see if the cell has a formula and if not, it will only clear the contents of that one cell.

Public Sub ClearList(lst As ListObject)
'Clears a listObject while leaving 1 empty row + formula
' https://stackoverflow.com/a/53856079/1898524
'
'With special help from this post to handle a single column table.
'   Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
'   Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
' https://stackoverflow.com/questions/40537537/range-specialcells-clearcontents-clears-whole-sheet-instead

    On Error Resume Next
    
    With lst
        '.Range.Worksheet.Activate ' Enable this if you are debugging 
    
        If .ShowAutoFilter Then .AutoFilter.ShowAllData
        If .DataBodyRange.Rows.Count = 1 Then Exit Sub ' Table is already clear
        .DataBodyRange.Offset(1).Rows.Clear
        
        If .DataBodyRange.Columns.Count > 1 Then ' Check to see if SpecialCells is going to evaluate just one cell.
            .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
        ElseIf Not .Range.HasFormula Then
            ' Only one cell in range and it does not contain a formula.
            .DataBodyRange.Rows(1).ClearContents
        End If

        .Resize .Range.Rows("1:2")
        
        .HeaderRowRange.Offset(1).Select

        ' Reset used range on the sheet
        Dim X
        X = .Range.Worksheet.UsedRange.Rows.Count 'see J-Walkenbach tip 73

    End With

End Sub

A final step I included is a tip that is attributed to John Walkenbach, sometimes noted as J-Walkenbach tip 73 Automatically Resetting The Last Cell

Submit form using AJAX and jQuery

There is a nice form plugin that allows you to send an HTML form asynchroniously.

$(document).ready(function() { 
    $('#myForm1').ajaxForm(); 
});

or

$("select").change(function(){
    $('#myForm1').ajaxSubmit();
});

to submit the form immediately

how to use JSON.stringify and json_decode() properly

None of the other answers worked in my case, most likely because the JSON array contained special characters. What fixed it for me:

Javascript (added encodeURIComponent)

var JSONstr = encodeURIComponent(JSON.stringify(fullInfoArray));
document.getElementById('JSONfullInfoArray').value = JSONstr;

PHP (unchanged from the question)

$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);

echo($_POST["JSONfullInfoArray"]);

Both echo and var_dump have been verified to work fine on a sample of more than 2000 user-entered datasets that included a URL field and a long text field, and that were returning NULL on var_dump for a subset that included URLs with the characters ?&#.

How to fix git error: RPC failed; curl 56 GnuTLS

I had a similar fault:

error: RPC failed; curl 56 GnuTLS recv error (-9): A TLS packet with unexpected length was received.

when trying to clone a repository from Github.

After trying most of the solutions posted here, none of which worked, it turned out to be the parental controls on our home network. Turning these parental controls off solved the problem.

python: get directory two levels up

(pathlib.Path('../../') ).resolve()

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had this issue after converting my Write-Host cmdlets to Write-Information and I was missing quotes and parens around the parameters. The cmdlet signatures are evidently not the same.

Write-Host this is a good idea $here
Write-Information this is a good idea $here <=BAD

This is the cmdlet signature that corrected after spending 20-30 minutes digging down the function stack...

Write-Information ("this is a good idea $here") <=GOOD

Get enum values as List of String in Java 8

You can do (pre-Java 8):

List<Enum> enumValues = Arrays.asList(Enum.values());

or

List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));

Using Java 8 features, you can map each constant to its name:

List<String> enumNames = Stream.of(Enum.values())
                               .map(Enum::name)
                               .collect(Collectors.toList());

GDB: Listing all mapped memory regions for a crashed process

I have just seen the following:

set mem inaccessible-by-default [on|off]

here

It might allow you to search without regard if the memory is accessible.

A formula to copy the values from a formula to another column

you can use those functions together with iferror as a work around.

try =IFERROR(VALUE(A4),(CONCATENATE(A4)))

How to delete all instances of a character in a string in python?

I suggest split (not saying that the other answers are invalid, this is just another way to do it):

def findreplace(char, string):
   return ''.join(string.split(char))

Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below

In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'

And the speed...

In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204

Not as fast as replace or translate, but ok.

show validation error messages on submit in angularjs

I found this fiddle http://jsfiddle.net/thomporter/ANxmv/2/ which does a nifty trick to cause control validation.

Basically it declares a scope member submitted and sets it true when you click submit. The model error binding use this extra expression to show the error message like

submitted && form.email.$error.required

UPDATE

As pointed out in @Hafez's comment (give him some upvotes!), the Angular 1.3+ solution is simply:

form.$submitted && form.email.$error.required

What are invalid characters in XML

For XSL (on really lazy days) I use:

capture="&amp;(?!amp;)" capturereplace="&amp;amp;"

to translate all &-signs that aren't follwed på amp; to proper ones.

We have cases where the input is in CDATA but the system which uses the XML doesn't take it into account. It's a sloppy fix, beware...

Is it possible to put a ConstraintLayout inside a ScrollView?

Try giving some padding bottom to your constraint layout like below

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/top"
        android:fillViewport="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="100dp">
        </android.support.constraint.ConstraintLayout>

    </ScrollView>

Error: could not find function "%>%"

The benefit is that the output of previous function is used. You do not need to repeat where the data source comes from, for example.

What does @@variable mean in Ruby?

@@ denotes a class variable, i.e. it can be inherited.

This means that if you create a subclass of that class, it will inherit the variable. So if you have a class Vehicle with the class variable @@number_of_wheels then if you create a class Car < Vehicle then it too will have the class variable @@number_of_wheels

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Jaqen H'ghar is spot-on. A third way is to:

  1. Go to Manage NuGet Packages
  2. Install Microsoft.jQuery.Unobtrusive.Validation
  3. Open Global.asax.cs file and add this code inside the Application_Start method

Code that runs on application startup:

ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition {
    Path = "~/Scripts/jquery.validate.unobtrusive.min.js",
    DebugPath = "~/Scripts/jquery.validate.unobtrusive.min.js"
});

How can I decrypt MySQL passwords

Hashing is a one-way process but using a password-list you can regenerate the hashes and compare to the stored hash to 'crack' the password.

This site https://crackstation.net/ attempts to do this for you - run through passwords lists and tell you the cleartext password based on your hash.

Creating threads - Task.Factory.StartNew vs new Thread()

There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.

If you have a long running background work you should specify this by using the correct Task Option.

You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.

Loading another html page from javascript

Yes. In the javascript code:

window.location.href = "http://new.website.com/that/you/want_to_go_to.html";

Logarithmic returns in pandas dataframe

@poulter7: I cannot comment on the other answers, so I post it as new answer: be careful with

np.log(df.price).diff() 

as this will fail for indices which can become negative as well as risk factors e.g. negative interest rates. In these cases

np.log(df.price/df.price.shift(1)).dropna()

is preferred and based on my experience generally the safer approach. It also evaluates the logarithm only once.

Whether you use +1 or -1 depends on the ordering of your time series. Use -1 for descending and +1 for ascending dates - in both cases the shift provides the preceding date's value.

Simple check for SELECT query empty result

well there is a way to do it a little more code but really effective

_x000D_
_x000D_
$sql = "SELECT * FROM messages";  //your query_x000D_
$result=$connvar->query($sql);    //$connvar is the connection variable_x000D_
$flag=0;_x000D_
     while($rows2=mysqli_fetch_assoc($result2))_x000D_
    { $flag++;}_x000D_
    _x000D_
if($flag==0){no rows selected;}_x000D_
else{_x000D_
echo $flag." "."rows are selected"_x000D_
}
_x000D_
_x000D_
_x000D_

Git asks for username every time I push

Add new SSH keys as described in this article on GitHub.

If Git still asks you for username & password, try changing https://github.com/ to [email protected]: in remote URL:

$ git config remote.origin.url 
https://github.com/dir/repo.git

$ git config remote.origin.url "[email protected]:dir/repo.git"

How do I make a splash screen?

Abdullah's answer is great. But i want to add some more details to it with my answer.

Implementing a Splash Screen

Implementing a splash screen the right way is a little different than you might imagine. The splash view that you see has to be ready immediately, even before you can inflate a layout file in your splash activity.

So you will not use a layout file. Instead, specify your splash screen’s background as the activity’s theme background. To do this, first create an XML drawable in res/drawable.

background_splash.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/gray"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>

It just a layerlist with logo in center background color with it.

Now open styles.xml and add this style

<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/background_splash</item>
</style>

This theme will have to actionbar and with background that we just created above.

And in manifest you need to set SplashTheme to activity that you want to use as splash.

<activity
android:name=".SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Then inside your activity code navigate user to the specific screen after splash using intent.

public class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}

That's the right way to do. I used these references for answer.

  1. https://material.google.com/patterns/launch-screens.html
  2. https://www.bignerdranch.com/blog/splash-screens-the-right-way/ Thanks to these guys for pushing me into right direction. I want to help others because accepted answer isn't a recommended to do splash screen.

window.close() doesn't work - Scripts may close only the windows that were opened by it

You can't close a current window or any window or page that is opened using '_self' But you can do this

var customWindow = window.open('', '_blank', '');
    customWindow.close();

How to change the text on the action bar

We can change the ActionBar title in one of two ways:

  1. In the Manifest: in the manifest file, set the label of each Activity.

    android:label="@string/TitleWhichYouWantToDisplay"
    
  2. In code: in code, call the setTitle() method with a String or the id of String as the argument.

    public class MainActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
    
            setTitle(R.string.TitleWhichYouWantToDisplay);
            // OR You can also use the line below
            // setTitle("MyTitle")
            setContentView(R.layout.activity_main);
    
        }
    }
    

Update TextView Every Second

You can also use TimerTask for that.

Here is an method

private void setTimerTask() {
    long delay = 3000;
    long periodToRepeat = 60 * 1000; /* 1 mint */
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                 //   do your stuff here.
                }
            });
        }
    }, 3000, 3000);
}

What is setBounds and how do I use it?

This is a method of the java.awt.Component class. It is used to set the position and size of a component:

setBounds

public void setBounds(int x,
                  int y,
                  int width,
                  int height) 

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. Parameters:

  • x - the new x-coordinate of this component
  • y - the new y-coordinate of this component
  • width - the new width of this component
  • height - the new height of this component

x and y as above correspond to the upper left corner in most (all?) cases.

It is a shortcut for setLocation and setSize.

This generally only works if the layout/layout manager are non-existent, i.e. null.

How do I check if a Sql server string is null or empty

SELECT              
    COALESCE(listing.OfferText, 'company.OfferText') AS Offer_Text,         
FROM 
    tbl_directorylisting listing  
    INNER JOIN tbl_companymaster company ON listing.company_id= company.company_id

Send email using java

Following code worked for me.

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendMail {

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "yourpassword";

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

Why is Thread.Sleep so harmful

I agree with many here, but I also think it depends.

Recently I did this code:

private void animate(FlowLayoutPanel element, int start, int end)
{
    bool asc = end > start;
    element.Show();
    while (start != end) {
        start += asc ? 1 : -1;
        element.Height = start;
        Thread.Sleep(1);
    }
    if (!asc)
    {
        element.Hide();
    }
    element.Focus();
}

It was a simple animate-function, and I used Thread.Sleep on it.

My conclusion, if it does the job, use it.

Math operations from string

Warning: this way is not a safe way, but is very easy to use. Use it wisely.

Use the eval function.

print eval('2 + 4')

Output:

6

You can even use variables or regular python code.

a = 5
print eval('a + 4')

Output:

9

You also can get return values:

d = eval('4 + 5')
print d

Output:

9

Or call functions:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

a = 20
b = 10    
print eval('add(a, b)')
print eval('subtract(a, b)')

Output:

30
10

In case you want to write a parser, maybe instead you can built a python code generator if that is easier and use eval to run the code. With eval you can execute any Python evalution.

Why eval is unsafe?

Since you can put literally anything in the eval, e.g. if the input argument is:

os.system(‘rm -rf /’)

It will remove all files on your system (at least on Linux/Unix). So only use eval when you trust the input.

node and Error: EMFILE, too many open files

With bagpipe, you just need change

FS.readFile(filename, onRealRead);

=>

var bagpipe = new Bagpipe(10);

bagpipe.push(FS.readFile, filename, onRealRead))

The bagpipe help you limit the parallel. more details: https://github.com/JacksonTian/bagpipe

How can I delay a :hover effect in CSS?

div {
     background: #dbdbdb;
    -webkit-transition: .5s all;   
    -webkit-transition-delay: 5s; 
    -moz-transition: .5s all;   
    -moz-transition-delay: 5s; 
    -ms-transition: .5s all;   
    -ms-transition-delay: 5s; 
    -o-transition: .5s all;   
    -o-transition-delay: 5s; 
    transition: .5s all;   
    transition-delay: 5s; 
}

div:hover {
    background:#5AC900;
    -webkit-transition-delay: 0s;
    -moz-transition-delay: 0s;
    -ms-transition-delay: 0s;
    -o-transition-delay: 0s;
    transition-delay: 0s;
}

This will add a transition delay, which will be applicable to almost every browser..

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

Ajax passing data to php script

Try sending the data like this:

var data = {};
data.album = this.title;

Then you can access it like

$_POST['album']

Notice not a 'GET'

Hide all elements with class using plain Javascript

Assuming you are dealing with a single class per element:

function swapCssClass(a,b) {
    while (document.querySelector('.' + a)) {
        document.querySelector('.' + a).className = b;
    }
}

and then call simply call it with

swapCssClass('x_visible','x_hidden');

Android: Color To Int conversion

I think it should be R.color.black

Also take a look at Converting android color string in runtime into int

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

In your cshtml,

<tr ng-repeat="value in Results">                
 <td>{{value.FileReceivedOn | mydate | date : 'dd-MM-yyyy'}} </td>
</tr>

In Your JS File, maybe app.js,

Outside of app.controller, add the below filter.

Here the "mydate" is the function which you are calling for parsing the date. Here the "app" is the variable which contains the angular.module

app.filter("mydate", function () {
    var re = /\/Date\(([0-9]*)\)\//;
    return function (x) {
        var m = x.match(re);
        if (m) return new Date(parseInt(m[1]));
        else return null;
    };
});

String concatenation of two pandas columns

df['bar'] = df.bar.map(str) + " is " + df.foo.

How to import an existing project from GitHub into Android Studio

You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.

The github repo will be created as a new project in android studio.

How to pass arguments to Shell Script through docker run

There are a few things interacting here:

  1. docker run your_image arg1 arg2 will replace the value of CMD with arg1 arg2. That's a full replacement of the CMD, not appending more values to it. This is why you often see docker run some_image /bin/bash to run a bash shell in the container.

  2. When you have both an ENTRYPOINT and a CMD value defined, docker starts the container by concatenating the two and running that concatenated command. So if you define your entrypoint to be file.sh, you can now run the container with additional args that will be passed as args to file.sh.

  3. Entrypoints and Commands in docker have two syntaxes, a string syntax that will launch a shell, and a json syntax that will perform an exec. The shell is useful to handle things like IO redirection, chaining multiple commands together (with things like &&), variable substitution, etc. However, that shell gets in the way with signal handling (if you've ever seen a 10 second delay to stop a container, this is often the cause) and with concatenating an entrypoint and command together. If you define your entrypoint as a string, it would run /bin/sh -c "file.sh", which alone is fine. But if you have a command defined as a string too, you'll see something like /bin/sh -c "file.sh" /bin/sh -c "arg1 arg2" as the command being launched inside your container, not so good. See the table here for more on how these two options interact

  4. The shell -c option only takes a single argument. Everything after that would get passed as $1, $2, etc, to that single argument, but not into an embedded shell script unless you explicitly passed the args. I.e. /bin/sh -c "file.sh $1 $2" "arg1" "arg2" would work, but /bin/sh -c "file.sh" "arg1" "arg2" would not since file.sh would be called with no args.

Putting that all together, the common design is:

FROM ubuntu:14.04
COPY ./file.sh /
RUN chmod 755 /file.sh
# Note the json syntax on this next line is strict, double quotes, and any syntax
# error will result in a shell being used to run the line.
ENTRYPOINT ["file.sh"]

And you then run that with:

docker run your_image arg1 arg2

There's a fair bit more detail on this at:

SQL SELECT everything after a certain character

Try this in MySQL.

right(field,((CHAR_LENGTH(field))-(InStr(field,','))))

How to close <img> tag properly?

<img src='stackoverflow.png' />

Works fine and closes the tag properly. Best to add the alt attribute for people that are visually impaired.

Detect if user is scrolling

this works:

window.onscroll = function (e) {  
// called when the window is scrolled.  
} 

edit:

you said this is a function in a TimeInterval..
Try doing it like so:

userHasScrolled = false;
window.onscroll = function (e)
{
    userHasScrolled = true;
}

then inside your Interval insert this:

if(userHasScrolled)
{
//do your code here
userHasScrolled = false;
}

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Send request to curl with post data sourced from a file

You're looking for the --data-binary argument:

curl -i -X POST host:port/post-file \
  -H "Content-Type: text/xml" \
  --data-binary "@path/to/file"

In the example above, -i prints out all the headers so that you can see what's going on, and -X POST makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @ symbol, so curl knows to read from a file.

what does numpy ndarray shape do?

.shape() gives the actual shape of your array in terms of no of elements in it, No of rows/No of Columns. The answer you get is in the form of tuples.

For Example: 1D ARRAY:

d=np.array([1,2,3,4])
print(d)
(1,)

Output: (4,) ie the number4 denotes the no of elements in the 1D Array.

2D Array:

e=np.array([[1,2,3],[4,5,6]])   
print(e)
(2,3)

Output: (2,3) ie the number of rows and the number of columns.

The number of elements in the final output will depend on the number of rows in the Array....it goes on increasing gradually.

.NET Format a string with fixed spaces

Here's a VB.NET version I created, inspired by Joel Coehoorn's answer, Oliver's edit, and shaunmartin's comment:

    <Extension()>
Public Function PadCenter(ByVal [string] As String, ByVal width As Integer, ByVal c As Char) As String

    If [string] Is Nothing Then [string] = String.Empty
    If (width <= [string].Length) Then Return [string]

    Dim padding = width - [string].Length
    Return [string].PadLeft([string].Length + (padding \ 2), c).PadRight(width, c)

End Function

<Extension()>
Public Function PadCenter(ByVal [string] As String, ByVal width As Integer) As String

    If [string] Is Nothing Then [string] = String.Empty
    If (width <= [string].Length) Then Return [string]

    Dim padding = width - [string].Length
    Return [string].PadLeft([string].Length + (padding \ 2)).PadRight(width)

End Function

This is set up as a string extension, inside a Public Module (the way you do Extensions in VB.NET, a bit different than C#). My slight change is that it treats a null string as an empty string, and it pads an empty string with the width value (meets my particular needs). Hopefully this will convert easily to C# for anyone who needs it. If there's a better way to reference the answers, edits, and comments I mentioned above, which inspired my post, please let me know and I'll do it - I'm relatively new to posting, and I couldn't figure out to leave a comment (might not have enough rep yet).

Regex for string contains?

Assuming regular PCRE-style regex flavors:

If you want to check for it as a single, full word, it's \bTest\b, with appropriate flags for case insensitivity if desired and delimiters for your programming language. \b represents a "word boundary", that is, a point between characters where a word can be considered to start or end. For example, since spaces are used to separate words, there will be a word boundary on either side of a space.

If you want to check for it as part of the word, it's just Test, again with appropriate flags for case insensitivity. Note that usually, dedicated "substring" methods tend to be faster in this case, because it removes the overhead of parsing the regex.

Pointer-to-pointer dynamic two-dimensional array

The first method cannot be used to create dynamic 2D arrays because by doing:

int *board[4];

you essentially allocated an array of 4 pointers to int on stack. Therefore, if you now populate each of these 4 pointers with a dynamic array:

for (int i = 0; i < 4; ++i) {
  board[i] = new int[10];
}

what you end-up with is a 2D array with static number of rows (in this case 4) and dynamic number of columns (in this case 10). So it is not fully dynamic because when you allocate an array on stack you should specify a constant size, i.e. known at compile-time. Dynamic array is called dynamic because its size is not necessary to be known at compile-time, but can rather be determined by some variable in runtime.

Once again, when you do:

int *board[4];

or:

const int x = 4; // <--- `const` qualifier is absolutely needed in this case!
int *board[x];

you supply a constant known at compile-time (in this case 4 or x) so that compiler can now pre-allocate this memory for your array, and when your program is loaded into the memory it would already have this amount of memory for the board array, that's why it is called static, i.e. because the size is hard-coded and cannot be changed dynamically (in runtime).

On the other hand, when you do:

int **board;
board = new int*[10];

or:

int x = 10; // <--- Notice that it does not have to be `const` anymore!
int **board;
board = new int*[x];

the compiler does not know how much memory board array will require, and therefore it does not pre-allocate anything. But when you start your program, the size of array would be determined by the value of x variable (in runtime) and the corresponding space for board array would be allocated on so-called heap - the area of memory where all programs running on your computer can allocate unknown beforehand (at compile-time) amounts memory for personal usage.

As a result, to truly create dynamic 2D array you have to go with the second method:

int **board;
board = new int*[10]; // dynamic array (size 10) of pointers to int

for (int i = 0; i < 10; ++i) {
  board[i] = new int[10];
  // each i-th pointer is now pointing to dynamic array (size 10) of actual int values
}

We've just created an square 2D array with 10 by 10 dimensions. To traverse it and populate it with actual values, for example 1, we could use nested loops:

for (int i = 0; i < 10; ++i) {   // for each row
  for (int j = 0; j < 10; ++j) { // for each column
    board[i][j] = 1;
  }
}

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

Make sure, following jar file included in your class path and lib folder.

spring-core-3.0.5.RELEASE.jar

enter image description here

if you are using maven, make sure you have included dependency for spring-core-3xxxxx.jar file

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${org.springframework.version}</version>
</dependency>

Note : Replace ${org.springframework.version} with version number.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

I was having the same problem. Turns out in my case, I was missing the comma after the last column. 30 minutes of my life wasted, I will never get back!

enter image description here

REST API Authentication

I've been using the JWT authentication. Works just fine in my application.

There is an authentication method that will require the user credentials. This method validates the credentials and returns an access token in case of success.

This token must be sent to every other method in my Web API in the header of the request.

It's pretty easy to implement, and very easy to test.

How to put a jar in classpath in Eclipse?

First copy your jar file and paste into you Android project's libs folder.

Now right click on newly added (Pasted) jar file and select option

Build Path -> Add to build path

Now you added jar file will get displayed under Referenced Libraries. Again right click on it and select option

Build Path -> Configure Build path

A new window will get appeared. Select Java Build Path from left menu panel and then select Order and export Enable check on added jar file.

Now run your project.

More details @ Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)

Using Oracle to_date function for date string with milliseconds

You can try this format SS.FF for milliseconds:

to_timestamp(table_1.date_col,'DD-Mon-RR HH24:MI:SS.FF')

For more details:
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions193.htm

How to execute Python scripts in Windows?

Additionally, if you want to be able to run your python scripts without typing the .py (or .pyw) on the end of the file name, you need to add .PY (or .PY;.PYW) to the list of extensions in the PATHEXT environment variable.

In Windows 7:

right-click on Computer
left-click Properties
left-click Advanced system settings
left-click the Advanced tab
left-click Environment Variables...
under "system variables" scroll down until you see PATHEXT
left-click on PATHEXT to highlight it
left-click Edit...
Edit "Variable value" so that it contains ;.PY (the End key will skip to the end)
left-click OK
left-click OK
left-click OK

Note #1: command-prompt windows won't see the change w/o being closed and reopened.

Note #2: the difference between the .py and .pyw extensions is that the former opens a command prompt when run, and the latter doesn't.

On my computer, I added ;.PY;.PYW as the last (lowest-priority) extensions, so the "before" and "after" values of PATHEXT were:

before: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

after .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW

Here are some instructive commands:

C:\>echo %pathext%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Python32\python.exe" "%1" %*

C:\>assoc .pyw
.pyw=Python.NoConFile

C:\>ftype Python.NoConFile
Python.NoConFile="C:\Python32\pythonw.exe" "%1" %*

C:\>type c:\windows\helloworld.py
print("Hello, world!")  # always use a comma for direct address

C:\>helloworld
Hello, world!

C:\>

How to run a Command Prompt command with Visual Basic code?

Here is an example:

Process.Start("CMD", "/C Pause")


/C  Carries out the command specified by string and then terminates
/K  Carries out the command specified by string but remains

And here is a extended function: (Notice the comment-lines using CMD commands.)

#Region " Run Process Function "

' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe")) 
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")

Private Function Run_Process(ByVal Process_Name As String, _
                             Optional Process_Arguments As String = Nothing, _
                             Optional Read_Output As Boolean = False, _
                             Optional Process_Hide As Boolean = False, _
                             Optional Process_TimeOut As Integer = 999999999)

    ' Returns True if "Read_Output" argument is False and Process was finished OK
    ' Returns False if ExitCode is not "0"
    ' Returns Nothing if process can't be found or can't be started
    ' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.

    Try

        Dim My_Process As New Process()
        Dim My_Process_Info As New ProcessStartInfo()

        My_Process_Info.FileName = Process_Name ' Process filename
        My_Process_Info.Arguments = Process_Arguments ' Process arguments
        My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
        My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
        My_Process_Info.RedirectStandardOutput = Read_Output '  Redirect (1) Output
        My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
        My_Process.EnableRaisingEvents = True ' Raise events
        My_Process.StartInfo = My_Process_Info
        My_Process.Start() ' Run the process NOW

        My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)

        Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
        If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0

        If Read_Output = True Then
            Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
            Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
            ' Return output by priority
            If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
            If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
        End If

    Catch ex As Exception
        'MsgBox(ex.Message)
        Return Nothing ' Returns nothing if the process can't be found or started.
    End Try

    Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.

End Function

#End Region

Usage of sys.stdout.flush() method

Consider the following simple Python script:

import time
import sys

for i in range(5):
    print(i),
    #sys.stdout.flush()
    time.sleep(1)

This is designed to print one number every second for five seconds, but if you run it as it is now (depending on your default system buffering) you may not see any output until the script completes, and then all at once you will see 0 1 2 3 4 printed to the screen.

This is because the output is being buffered, and unless you flush sys.stdout after each print you won't see the output immediately. Remove the comment from the sys.stdout.flush() line to see the difference.

c++ compile error: ISO C++ forbids comparison between pointer and integer

You must remember to use single quotes for char constants. So use

if (answer == 'y') return true;

Rather than

if (answer == "y") return true;

I tested this and it works

Specific Time Range Query in SQL Server

I'm assuming you want all three of those as part of the selection criteria. You'll need a few statements in your where but they will be similar to the link your question contained.

SELECT *
  FROM MyTable
  WHERE [dateColumn] > '3/1/2009' AND [dateColumn] <= DATEADD(day,1,'3/31/2009') 
        --make it inclusive for a datetime type
    AND DATEPART(hh,[dateColumn]) >= 6 AND DATEPART(hh,[dateColumn]) <= 22 
        -- gets the hour of the day from the datetime
    AND DATEPART(dw,[dateColumn]) >= 3 AND DATEPART(dw,[dateColumn]) <= 5 
        -- gets the day of the week from the datetime

Hope this helps.

What's the canonical way to check for type in Python?

After the question was asked and answered, type hints were added to Python. Type hints in Python allow types to be checked but in a very different way from statically typed languages. Type hints in Python associate the expected types of arguments with functions as runtime accessible data associated with functions and this allows for types to be checked. Example of type hint syntax:

def foo(i: int):
    return i

foo(5)
foo('oops')

In this case we want an error to be triggered for foo('oops') since the annotated type of the argument is int. The added type hint does not cause an error to occur when the script is run normally. However, it adds attributes to the function describing the expected types that other programs can query and use to check for type errors.

One of these other programs that can be used to find the type error is mypy:

mypy script.py
script.py:12: error: Argument 1 to "foo" has incompatible type "str"; expected "int"

(You might need to install mypy from your package manager. I don't think it comes with CPython but seems to have some level of "officialness".)

Type checking this way is different from type checking in statically typed compiled languages. Because types are dynamic in Python, type checking must be done at runtime, which imposes a cost -- even on correct programs -- if we insist that it happen at every chance. Explicit type checks may also be more restrictive than needed and cause unnecessary errors (e.g. does the argument really need to be of exactly list type or is anything iterable sufficient?).

The upside of explicit type checking is that it can catch errors earlier and give clearer error messages than duck typing. The exact requirements of a duck type can only be expressed with external documentation (hopefully it's thorough and accurate) and errors from incompatible types can occur far from where they originate.

Python's type hints are meant to offer a compromise where types can be specified and checked but there is no additional cost during usual code execution.

The typing package offers type variables that can be used in type hints to express needed behaviors without requiring particular types. For example, it includes variables such as Iterable and Callable for hints to specify the need for any type with those behaviors.

While type hints are the most Pythonic way to check types, it's often even more Pythonic to not check types at all and rely on duck typing. Type hints are relatively new and the jury is still out on when they're the most Pythonic solution. A relatively uncontroversial but very general comparison: Type hints provide a form of documentation that can be enforced, allow code to generate earlier and easier to understand errors, can catch errors that duck typing can't, and can be checked statically (in an unusual sense but it's still outside of runtime). On the other hand, duck typing has been the Pythonic way for a long time, doesn't impose the cognitive overhead of static typing, is less verbose, and will accept all viable types and then some.

Avoid web.config inheritance in child web application using inheritInChildApplications

We're getting errors about duplicate configuration directives on the one of our apps. After investigation it looks like it's because of this issue.

In brief, our root website is ASP.NET 3.5 (which is 2.0 with specific libraries added), and we have a subapplication that is ASP.NET 4.0.

web.config inheritance causes the ASP.NET 4.0 sub-application to inherit the web.config file of the parent ASP.NET 3.5 application.

However, the ASP.NET 4.0 application's global (or "root") web.config, which resides at C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config and C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config (depending on your bitness), already contains these config sections.

The ASP.NET 4.0 app then tries to merge together the root ASP.NET 4.0 web.config, and the parent web.config (the one for an ASP.NET 3.5 app), and runs into duplicates in the node.

The only solution I've been able to find is to remove the config sections from the parent web.config, and then either

  1. Determine that you didn't need them in your root application, or if you do
  2. Upgrade the parent app to ASP.NET 4.0 (so it gains access to the root web.config's configSections)

Execute a shell function with timeout

I have a slight modification of @Tiago Lopo's answer that can handle commands with multiple arguments. I've also tested TauPan's solution, but it does not work if you use it multiple times in a script, while Tiago's does.

function timeout_cmd { 
  local arr
  local cmd
  local timeout

  arr=( "$@" )

  # timeout: first arg
  # cmd: the other args
  timeout="${arr[0]}"
  cmd=( "${arr[@]:1}" )

  ( 
    eval "${cmd[@]}" &
    child=$!

    echo "child: $child"
    trap -- "" SIGTERM 
    (       
      sleep "$timeout"
      kill "$child" 2> /dev/null 
    ) &     
    wait "$child"
  )
}

Here's a fully functional script thant you can use to test the function above:

$ ./test_timeout.sh -h
Usage:
  test_timeout.sh [-n] [-r REPEAT] [-s SLEEP_TIME] [-t TIMEOUT]
  test_timeout.sh -h

Test timeout_cmd function.

Options:
  -n              Dry run, do not actually sleep. 
  -r REPEAT       Reapeat everything multiple times [default: 1].
  -s SLEEP_TIME   Sleep for SLEEP_TIME seconds [default: 5].
  -t TIMEOUT      Timeout after TIMEOUT seconds [default: no timeout].

For example you cnal launch like this:

$ ./test_timeout.sh -r 2 -s 5 -t 3
Try no: 1
  - Set timeout to: 3
child: 2540
    -> retval: 143
    -> The command timed out
Try no: 2
  - Set timeout to: 3
child: 2593
    -> retval: 143
    -> The command timed out
Done!
#!/usr/bin/env bash

#shellcheck disable=SC2128
SOURCED=false && [ "$0" = "$BASH_SOURCE" ] || SOURCED=true

if ! $SOURCED; then
  set -euo pipefail
  IFS=$'\n\t'
fi

#################### helpers
function check_posint() {
  local re='^[0-9]+$'
  local mynum="$1"
  local option="$2"

  if ! [[ "$mynum" =~ $re ]] ; then
     (echo -n "Error in option '$option': " >&2)
     (echo "must be a positive integer, got $mynum." >&2)
     exit 1
  fi

  if ! [ "$mynum" -gt 0 ] ; then
     (echo "Error in option '$option': must be positive, got $mynum." >&2)
     exit 1
  fi
}
#################### end: helpers

#################### usage
function short_usage() {
  (>&2 echo \
"Usage:
  test_timeout.sh [-n] [-r REPEAT] [-s SLEEP_TIME] [-t TIMEOUT]
  test_timeout.sh -h"
  )
}

function usage() {
  (>&2 short_usage )
  (>&2 echo \
"
Test timeout_cmd function.

Options:
  -n              Dry run, do not actually sleep. 
  -r REPEAT       Reapeat everything multiple times [default: 1].
  -s SLEEP_TIME   Sleep for SLEEP_TIME seconds [default: 5].
  -t TIMEOUT      Timeout after TIMEOUT seconds [default: no timeout].
")
}
#################### end: usage

help_flag=false
dryrun_flag=false
SLEEP_TIME=5
TIMEOUT=-1
REPEAT=1

while getopts ":hnr:s:t:" opt; do
  case $opt in
    h)
      help_flag=true
      ;;    
    n)
      dryrun_flag=true
      ;;
    r)
      check_posint "$OPTARG" '-r'

      REPEAT="$OPTARG"
      ;;
    s)
      check_posint "$OPTARG" '-s'

      SLEEP_TIME="$OPTARG"
      ;;
    t)
      check_posint "$OPTARG" '-t'

      TIMEOUT="$OPTARG"
      ;;
    \?)
      (>&2 echo "Error. Invalid option: -$OPTARG.")
      (>&2 echo "Try -h to get help")
      short_usage
      exit 1
      ;;
    :)
      (>&2 echo "Error.Option -$OPTARG requires an argument.")
      (>&2 echo "Try -h to get help")
      short_usage
      exit 1
      ;;
  esac
done

if $help_flag; then
  usage
  exit 0
fi

#################### utils
if $dryrun_flag; then
  function wrap_run() {
    ( echo -en "[dry run]\\t" )
    ( echo "$@" )
  }
else
  function wrap_run() { "$@"; }
fi

# Execute a shell function with timeout
# https://stackoverflow.com/a/24416732/2377454
function timeout_cmd { 
  local arr
  local cmd
  local timeout

  arr=( "$@" )

  # timeout: first arg
  # cmd: the other args
  timeout="${arr[0]}"
  cmd=( "${arr[@]:1}" )

  ( 
    eval "${cmd[@]}" &
    child=$!

    echo "child: $child"
    trap -- "" SIGTERM 
    (       
      sleep "$timeout"
      kill "$child" 2> /dev/null 
    ) &     
    wait "$child"
  )
}
####################

function sleep_func() {
  local secs
  local waitsec

  waitsec=1
  secs=$(($1))
  while [ "$secs" -gt 0 ]; do
   echo -ne "$secs\033[0K\r"
   sleep "$waitsec"
   secs=$((secs-waitsec))
  done

}

command=("wrap_run" \
         "sleep_func" "${SLEEP_TIME}"
         )

for i in $(seq 1 "$REPEAT"); do
  echo "Try no: $i"

  if [ "$TIMEOUT" -gt 0 ]; then
    echo "  - Set timeout to: $TIMEOUT"
    set +e
    timeout_cmd "$TIMEOUT" "${command[@]}"
    retval="$?"
    set -e

    echo "    -> retval: $retval"
    # check if (retval % 128) == SIGTERM (== 15)
    if [[ "$((retval % 128))" -eq 15 ]]; then
      echo "    -> The command timed out"
    fi
  else
    echo "  - No timeout"
    "${command[@]}"
    retval="$?"
  fi
done

echo "Done!"

exit 0

Anchor links in Angularjs?

You can also Navigate to HTML id from inside controller

$location.hash('id_in_html');

How to automatically reload a page after a given period of inactivity

With on page confirmation text instead of alert

Since this is another method to auto load if inactive I give it a second answer. This one is more simple and easier to understand.

With reload confirmation on the page

<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5100; // 5,1 seconds
var warnPeriod = 5000; // 5 seconds
// Warning period should always be a bit shorter then time period

function promptForClose() {
autoCloseDiv.style.display = 'block';
autoCloseTimer = setTimeout("definitelyClose()", warnPeriod);
}


function autoClose() {
autoCloseDiv.style.display = 'block'; //shows message on page
autoCloseTimer = setTimeout("definitelyClose()", timePeriod); //starts countdown to closure
}

function cancelClose() {
clearTimeout(autoCloseTimer); //stops auto-close timer
autoCloseDiv.style.display = 'none'; //hides message
}

function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("promptForClose()", timePeriod); //restarts timer from 0
}


function definitelyClose() {

// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or  this: window.open('http://www.YourPageAdress.com', '_self');

// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');

window.top.location=self.location;
}
-->
</script>

Confirmation box when using with on page confirmation

<div class="leftcolNon">
<div id='autoCloseDiv' style="display:none">
<center>
<b>Inactivity warning!</b><br />
This page will Reloads automatically unless you hit 'Cancel.'</p>
<input type='button' value='Load' onclick='definitelyClose();' />
<input type='button' value='Cancel' onclick='cancelClose();' />
</center>
</div>
</div>

Body codes for both are the SAME

<body onmousedown="resetTimeout();" onmouseup="resetTimeout();" onmousemove="resetTimeout();" onkeydown="resetTimeout();" onload="timeoutObject=setTimeout('promptForClose()',timePeriod);">

NOTE: If you do not want to have the on page confirmation, use Without confirmation

<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5000; // 5 seconds

function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("definitelyClose()", timePeriod); //restarts timer from 0
}

function definitelyClose() {

// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or  this: window.open('http://www.YourPageAdress.com', '_self');

// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');

window.top.location=self.location;
}
-->
</script>

nodejs module.js:340 error: cannot find module

EDIT: This answer is outdated. With things like Yarn and NPM 5's lockfiles it is now easier to ensure you're dependencies are correct on platforms like Heroku

I had a similar issue related to node_modules being modified somehow locally but the change was not reflect on Heroku, causing my app to crash. It's relatively easy fix if this is your issue:

# Remove node_modules
rm -fr node_modules

# Reinstall packages
npm i

# Commit changes
git add node_modules
git commit -m 'Fix node_modules dependencies.'
git push heroku master

Hope that helps for others with a similar issue.

LINQ - Left Join, Group By, and Count

While the idea behind LINQ syntax is to emulate the SQL syntax, you shouldn't always think of directly translating your SQL code into LINQ. In this particular case, we don't need to do group into since join into is a group join itself.

Here's my solution:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
select new { ParentId = p.ParentId, Count = joined.Count() }

Unlike the mostly voted solution here, we don't need j1, j2 and null checking in Count(t => t.ChildId != null)

Mapping many-to-many association table with extra column(s)

Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.

You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.

If you make the relationships bidirectional, you should thus have

class User {
    @OneToMany(mappedBy = "user")
    private Set<UserService> userServices = new HashSet<UserService>();
}

class UserService {
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "service_code")
    private Service service;

    @Column(name = "blocked")
    private boolean blocked;
}

class Service {
    @OneToMany(mappedBy = "service")
    private Set<UserService> userServices = new HashSet<UserService>();
}

If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.

User user = new User();
Service service = new Service();
UserService userService = new UserService();

user.addUserService(userService);
userService.setUser(user);

service.addUserService(userService);
userService.setService(service);

session.save(user);
session.save(service);
session.save(userService);

How to decode a QR-code image in (preferably pure) Python?

I'm answering only the part of the question about zbar installation.

I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:

PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.

PS2: I just tested pyzbar with pip install pyzbar and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.

How to create a md5 hash of a string in C?

Here's a complete example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(__APPLE__)
#  define COMMON_DIGEST_FOR_OPENSSL
#  include <CommonCrypto/CommonDigest.h>
#  define SHA1 CC_SHA1
#else
#  include <openssl/md5.h>
#endif

char *str2md5(const char *str, int length) {
    int n;
    MD5_CTX c;
    unsigned char digest[16];
    char *out = (char*)malloc(33);

    MD5_Init(&c);

    while (length > 0) {
        if (length > 512) {
            MD5_Update(&c, str, 512);
        } else {
            MD5_Update(&c, str, length);
        }
        length -= 512;
        str += 512;
    }

    MD5_Final(digest, &c);

    for (n = 0; n < 16; ++n) {
        snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
    }

    return out;
}

    int main(int argc, char **argv) {
        char *output = str2md5("hello", strlen("hello"));
        printf("%s\n", output);
        free(output);
        return 0;
    }

How do you get the string length in a batch file?

You can try this code. Fast, you can also include special characters

@echo off
set "str=[string]"
echo %str% > "%tmp%\STR"
for %%P in ("%TMP%\STR") do (set /a strlen=%%~zP-3)
echo String lenght: %strlen%

How to capture no file for fs.readFileSync()?

The JavaScript try…catch mechanism cannot be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use throw inside an error-first callback:

// THIS WILL NOT WORK:
const fs = require('fs');

try {
  fs.readFile('/some/file/that/does-not-exist', (err, data) => {
    // Mistaken assumption: throwing here...
    if (err) {
      throw err;
    }
  });
} catch (err) {
  // This will not catch the throw!
  console.error(err);
}

This will not work because the callback function passed to fs.readFile() is called asynchronously. By the time the callback has been called, the surrounding code, including the try…catch block, will have already exited. Throwing an error inside the callback can crash the Node.js process in most cases. If domains are enabled, or a handler has been registered with process.on('uncaughtException'), such errors can be intercepted.

reference: https://nodejs.org/api/errors.html

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I'm not sure how efficient this is but you can use range() to slice in both axis

 x=np.arange(16).reshape((4,4))
 x[range(1,3), :][:,range(1,3)] 

#1062 - Duplicate entry for key 'PRIMARY'

Probably this is not the best of solution but doing the following will solve the problem

Step 1: Take a database dump using the following command

mysqldump -u root -p databaseName > databaseName.db

find the line

ENGINE=InnoDB AUTO_INCREMENT="*****" DEFAULT CHARSET=utf8;

Step 2: Change ******* to max id of your mysql table id. Save this value.

Step 3: again use

mysql -u root -p databaseName < databaseName.db

In my case i got this error when i added a manual entry to use to enter data into some other table. some how we have to set the value AUTO_INCREMENT to max id using mysql command

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

How to run DOS/CMD/Command Prompt commands from VB.NET?

I was inspired by Steve's answer but thought I'd add a bit of flare to it. I like to do the work up front of writing extension methods so later I have less work to do calling the method.

For example with the modified version of Steve's answer below, instead of making this call...

MyUtilities.RunCommandCom("DIR", "/W", true)

I can actually just type out the command and call it from my strings like this...

Directly in code.

Call "CD %APPDATA% & TREE".RunCMD()

OR

From a variable.

Dim MyCommand = "CD %APPDATA% & TREE"
MyCommand.RunCMD()

OR

From a textbox.

textbox.text.RunCMD(WaitForProcessComplete:=True)


Extension methods will need to be placed in a Public Module and carry the <Extension> attribute over the sub. You will also want to add Imports System.Runtime.CompilerServices to the top of your code file.

There's plenty of info on SO about Extension Methods if you need further help.


Extension Method

Public Module Extensions
''' <summary>
''' Extension method to run string as CMD command.
''' </summary>
''' <param name="command">[String] Command to run.</param>
''' <param name="ShowWindow">[Boolean](Default:False) Option to show CMD window.</param>
''' <param name="WaitForProcessComplete">[Boolean](Default:False) Option to wait for CMD process to complete before exiting sub.</param>
''' <param name="permanent">[Boolean](Default:False) Option to keep window visible after command has finished. Ignored if ShowWindow is False.</param>
<Extension>
Public Sub RunCMD(command As String, Optional ShowWindow As Boolean = False, Optional WaitForProcessComplete As Boolean = False, Optional permanent As Boolean = False)
    Dim p As Process = New Process()
    Dim pi As ProcessStartInfo = New ProcessStartInfo()
    pi.Arguments = " " + If(ShowWindow AndAlso permanent, "/K", "/C") + " " + command
    pi.FileName = "cmd.exe"
    pi.CreateNoWindow = Not ShowWindow
    If ShowWindow Then
        pi.WindowStyle = ProcessWindowStyle.Normal
    Else
        pi.WindowStyle = ProcessWindowStyle.Hidden
    End If
    p.StartInfo = pi
    p.Start()
    If WaitForProcessComplete Then Do Until p.HasExited : Loop
End Sub
End Module

Prefer composition over inheritance?

A rule of thumb I have heard is inheritance should be used when its a "is-a" relationship and composition when its a "has-a". Even with that I feel that you should always lean towards composition because it eliminates a lot of complexity.

What is the difference between dynamic and static polymorphism in Java?

method overloading is an example of compile time/static polymorphism because method binding between method call and method definition happens at compile time and it depends on the reference of the class (reference created at compile time and goes to stack).

method overriding is an example of run time/dynamic polymorphism because method binding between method call and method definition happens at run time and it depends on the object of the class (object created at runtime and goes to the heap).

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

Launch Bootstrap Modal on page load

Update 2020 - Bootstrap 5

Building on the excellent responses from previous answers, in Bootstrap 5 with no jQuery, this has worked;

document.querySelector('[data-target="#exampleModal"]').click();

Full snippet:

_x000D_
_x000D_
window.onload = () => {
  document.querySelector('[data-target="#exampleModal"]').click();
}
_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" rel="stylesheet" />


<div class="container py-3">

  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

</div>
_x000D_
_x000D_
_x000D_

Printing all variables value from a class

Generic toString() one-liner, using reflection and style customization:

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
...
public String toString()
{
  return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}

What is the difference between a generative and a discriminative algorithm?

In practice, the models are used as follows.

In discriminative models, to predict the label y from the training example x, you must evaluate:

enter image description here

which merely chooses what is the most likely class y considering x. It's like we were trying to model the decision boundary between the classes. This behavior is very clear in neural networks, where the computed weights can be seen as a complexly shaped curve isolating the elements of a class in the space.

Now, using Bayes' rule, let's replace the enter image description here in the equation by enter image description here. Since you are just interested in the arg max, you can wipe out the denominator, that will be the same for every y. So, you are left with

enter image description here

which is the equation you use in generative models.

While in the first case you had the conditional probability distribution p(y|x), which modeled the boundary between classes, in the second you had the joint probability distribution p(x, y), since p(x | y) p(y) = p(x, y), which explicitly models the actual distribution of each class.

With the joint probability distribution function, given a y, you can calculate ("generate") its respective x. For this reason, they are called "generative" models.

How to create a trie in Python

Here is a list of python packages that implement Trie:

  • marisa-trie - a C++ based implementation.
  • python-trie - a simple pure python implementation.
  • PyTrie - a more advanced pure python implementation.
  • pygtrie - a pure python implementation by Google.
  • datrie - a double array trie implementation based on libdatrie.

Clone Object without reference javascript

A and B reference the same object, so A.a and B.a reference the same property of the same object.

Edit

Here's a "copy" function that may do the job, it can do both shallow and deep clones. Note the caveats. It copies all enumerable properties of an object (not inherited properties), including those with falsey values (I don't understand why other approaches ignore them), it also doesn't copy non–existent properties of sparse arrays.

There is no general copy or clone function because there are many different ideas on what a copy or clone should do in every case. Most rule out host objects, or anything other than Objects or Arrays. This one also copies primitives. What should happen with functions?

So have a look at the following, it's a slightly different approach to others.

/* Only works for native objects, host objects are not
** included. Copies Objects, Arrays, Functions and primitives.
** Any other type of object (Number, String, etc.) will likely give 
** unexpected results, e.g. copy(new Number(5)) ==> 0 since the value
** is stored in a non-enumerable property.
**
** Expects that objects have a properly set *constructor* property.
*/
function copy(source, deep) {
   var o, prop, type;

  if (typeof source != 'object' || source === null) {
    // What do to with functions, throw an error?
    o = source;
    return o;
  }

  o = new source.constructor();

  for (prop in source) {

    if (source.hasOwnProperty(prop)) {
      type = typeof source[prop];

      if (deep && type == 'object' && source[prop] !== null) {
        o[prop] = copy(source[prop]);

      } else {
        o[prop] = source[prop];
      }
    }
  }
  return o;
}

Force uninstall of Visual Studio

I was running in to the same issue, but have just managed a full uninstall by means of trusty old CMD:

D:\vs_ultimate.exe /uninstall /force

Where D: is the location of your installation media (mounted iso, etc).

You could also pass /passive (no user input required - just progress displayed) or /quiet to the above command line.

EDIT: Adding link below to MSDN article mentioning that this forcibly removes ALL installed components.

http://blogs.msdn.com/b/heaths/archive/2015/07/17/removing-visual-studio-components-left-behind-after-an-uninstall.aspx

Also, to ensure link rot doesn't invalidate this, adding brief text below from original article.

Starting with Visual Studio 2013, you can forcibly remove almost all components. A few core components – like the .NET Framework and VC runtimes – are left behind because of their ubiquity, though you can remove those separately from Programs and Features if you really want.

Warning: This will remove all components regardless of whether other products require them. This may cause other products to function incorrectly or not function at all.

Good luck!

Tools for creating Class Diagrams

Just discovered GenMyModel, an awesome UML modeler to design class diagram online

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

use the .not() method and check for an attribute:

$('p').not('[class]');

Check it here: http://jsfiddle.net/AWb79/

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

Include path of jar (jdbc driver) in classpath.

Pass parameters in setInterval function

You can use an anonymous function;

setInterval(function() { funca(10,3); },500);

How to format a number as percentage in R?

You can use the scales package just for this operation (without loading it with require or library)

scales::percent(m)

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

Use TO_TIMESTAMP function

TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')

Group by with multiple columns using lambda

Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.

return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
                .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
                .SelectMany(a => a)
                .ToList();

Where CustomerGroupingKey takes the group keys:

    private class CustomerGroupingKey
    {
        public CustomerGroupingKey(string country, string gender)
        {
            Country = country;
            Gender = gender;
        }

        public string Country { get; }

        public string Gender { get; }
    }

What is the fastest way to create a checksum for large files in C#

You can have a look to XxHash.Net ( https://github.com/wilhelmliao/xxHash.NET )
The xxHash algorythm seems to be faster than all other.
Some benchmark on the xxHash site : https://github.com/Cyan4973/xxHash

PS: I've not yet used it.

JavaScript math, round to two decimal places

try using discount.toFixed(2);

Add Twitter Bootstrap icon to Input box

Bootstrap 4.x

With Bootstrap 4 (and Font Awesome), we still can use the input-group wrapper around our form-control element, and now we can use an input-group-append (or input-group-prepend) wrapper with an input-group-text to get the job done:

<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="Search" aria-label="Search" aria-describedby="my-search">
  <div class="input-group-append">
    <span class="input-group-text" id="my-search"><i class="fas fa-filter"></i></span>
  </div>
</div>

It will look something like this (thanks to KyleMit for the screenshot):

enter image description here

Learn more by visiting the Input group documentation.

Using <style> tags in the <body> with other HTML

When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.

Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.

If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.

Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.

The executable gets signed with invalid entitlements in Xcode

I simply went to apple dev portal, downloaded the appropriate provisioning profile and reinstalled it (xcode 10.1)

Iterating over every two elements in a list

I need to divide a list by a number and fixed like this.

l = [1,2,3,4,5,6]

def divideByN(data, n):
        return [data[i*n : (i+1)*n] for i in range(len(data)//n)]  

>>> print(divideByN(l,2))
[[1, 2], [3, 4], [5, 6]]

>>> print(divideByN(l,3))
[[1, 2, 3], [4, 5, 6]]

How to check if cursor exists (open status)

You can use the CURSOR_STATUS function to determine its state.

IF CURSOR_STATUS('global','myCursor')>=-1
BEGIN
 DEALLOCATE myCursor
END

Excel date to Unix timestamp

Here is a mapping for reference, assuming UTC for spreadsheet systems like Microsoft Excel:

                         Unix  Excel Mac    Excel    Human Date  Human Time
Excel Epoch       -2209075200      -1462        0    1900/01/00* 00:00:00 (local)
Excel = 2011 Mac† -2082758400          0     1462    1904/12/31  00:00:00 (local)
Unix Epoch                  0      24107    25569    1970/01/01  00:00:00 UTC
Example Below      1234567890      38395.6  39857.6  2009/02/13  23:31:30 UTC
Signed Int Max     2147483648      51886    50424    2038/01/19  03:14:08 UTC

One Second                  1       0.0000115740…             —  00:00:01
One Hour                 3600       0.0416666666…             -  01:00:00
One Day                 86400          1        1             -  24:00:00

*  “Jan Zero, 1900” is 1899/12/31; see the Bug section below. Excel 2011 for Mac (and older) use the 1904 date system.

 

As I often use awk to process CSV and space-delimited content, I developed a way to convert UNIX epoch to timezone/DST-appropriate Excel date format:

echo 1234567890 |awk '{ 
  # tries GNU date, tries BSD date on failure
  cmd = sprintf("date -d@%d +%%z 2>/dev/null || date -jf %%s %d +%%z", $1, $1)
  cmd |getline tz                                # read in time-specific offset
  hours = substr(tz, 2, 2) + substr(tz, 4) / 60  # hours + minutes (hi, India)
  if (tz ~ /^-/) hours *= -1                     # offset direction (east/west)
  excel = $1/86400 + hours/24 + 25569            # as days, plus offset
  printf "%.9f\n", excel
}'

I used echo for this example, but you can pipe a file where the first column (for the first cell in .csv format, call it as awk -F,) is a UNIX epoch. Alter $1 to represent your desired column/cell number or use a variable instead.

This makes a system call to date. If you will reliably have the GNU version, you can remove the 2>/dev/null || date … +%%z and the second , $1. Given how common GNU is, I wouldn't recommend assuming BSD's version.

The getline reads the time zone offset outputted by date +%z into tz, which is then translated into hours. The format will be like -0700 (PDT) or +0530 (IST), so the first substring extracted is 07 or 05, the second is 00 or 30 (then divided by 60 to be expressed in hours), and the third use of tz sees whether our offset is negative and alters hours if needed.

The formula given in all of the other answers on this page is used to set excel, with the addition of the daylight-savings-aware time zone adjustment as hours/24.

If you're on an older version of Excel for Mac, you'll need to use 24107 in place of 25569 (see the mapping above).

To convert any arbitrary non-epoch time to Excel-friendly times with GNU date:

echo "last thursday" |awk '{ 
  cmd = sprintf("date -d \"%s\" +\"%%s %%z\"", $0)
  cmd |getline
  hours = substr($2, 2, 2) + substr($2, 4) / 60
  if ($2 ~ /^-/) hours *= -1
  excel = $1/86400 + hours/24 + 25569
  printf "%.9f\n", excel
}'

This is basically the same code, but the date -d no longer has an @ to represent unix epoch (given how capable the string parser is, I'm actually surprised the @ is mandatory; what other date format has 9-10 digits?) and it's now asked for two outputs: the epoch and the time zone offset. You could therefore use e.g. @1234567890 as an input.

Bug

Lotus 1-2-3 (the original spreadsheet software) intentionally treated 1900 as a leap year despite the fact that it was not (this reduced the codebase at a time when every byte counted). Microsoft Excel retained this bug for compatibility, skipping day 60 (the fictitious 1900/02/29), retaining Lotus 1-2-3's mapping of day 59 to 1900/02/28. LibreOffice instead assigned day 60 to 1900/02/28 and pushed all previous days back one.

Any date before 1900/03/01 could be as much as a day off:

Day        Excel   LibreOffice
-1            -1    1899/12/29
 0    1900/01/00*   1899/12/30
 1    1900/01/01    1899/12/31
 2    1900/01/02    1900/01/01
 …
59    1900/02/28    1900/02/27
60    1900/02/29(!) 1900/02/28
61    1900/03/01    1900/03/01

Excel doesn't acknowledge negative dates and has a special definition of the Zeroth of January (1899/12/31) for day zero. Internally, Excel does indeed handle negative dates (they're just numbers after all), but it displays them as numbers since it doesn't know how to display them as dates (nor can it convert older dates into negative numbers). Feb 29 1900, a day that never happened, is recognized by Excel but not LibreOffice.

NodeJs : TypeError: require(...) is not a function

I've faced to something like this too. in your routes file , export the function as an object like this :

 module.exports = {
     hbd: handlebar
 }

and in your app file , you can have access to the function by .hbd and there is no ptoblem ....!

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

I was facing the similar problem with Spring-boot-2 applications with Java 9 library.

Adding the following dependency in my pom.xml solved the issue for me:

    <dependency>
        <groupId>com.googlecode.slf4j-maven-plugin-log</groupId>
        <artifactId>slf4j-maven-plugin-log</artifactId>
        <version>1.0.0</version>
    </dependency>

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

C Macro definition to determine big endian or little endian machine?

If you want to only rely on the preprocessor, you have to figure out the list of predefined symbols. Preprocessor arithmetics has no concept of addressing.

GCC on Mac defines __LITTLE_ENDIAN__ or __BIG_ENDIAN__

$ gcc -E -dM - < /dev/null |grep ENDIAN
#define __LITTLE_ENDIAN__ 1

Then, you can add more preprocessor conditional directives based on platform detection like #ifdef _WIN32 etc.

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

Remove NA values from a vector

The na.omit function is what a lot of the regression routines use internally:

vec <- 1:1000
vec[runif(200, 1, 1000)] <- NA
max(vec)
#[1] NA
max( na.omit(vec) )
#[1] 1000

Set value for particular cell in pandas DataFrame with iloc

Extending Jianxun's answer, using set_value mehtod in pandas. It sets value for a column at given index.

From pandas documentations:

DataFrame.set_value(index, col, value)

To set value at particular index for a column, do:

df.set_value(index, 'COL_NAME', x)

Hope it helps.

JQuery - Storing ajax response into global variable

IMO you can store this data in global variable. But it will be better to use some more unique name or use namespace:

MyCompany = {};

...
MyCompany.cachedData = data;

And also it's better to use json for these purposes, data in json format is usually much smaller than the same data in xml format.

Getting Image from URL (Java)

Directly calling a URL to get an image may concern with major security issues. You need to ensure that you have sufficient rights to access that resource. However You can use ByteOutputStream to read image file. This is an example (Its just an example, you need to do necessary changes as per your requirement.)

ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] bytebuff = new byte[4096]; 
  int n;

  while ( (n = is.read(bytebuff)) > 0 ) {
    bis.write(bytebuff, 0, n);
  }
}

How can I get the current page name in WordPress?

The WordPress global variable $pagename should be available for you. I have just tried with the same setup you specified.

$pagename is defined in the file wp-includes/theme.php, inside the function get_page_template(), which is of course is called before your page theme files are parsed, so it is available at any point inside your templates for pages.

  • Although it doesn't appear to be documented, the $pagename var is only set if you use permalinks. I guess this is because if you don't use them, WordPress doesn't need the page slug, so it doesn't set it up.

  • $pagename is not set if you use the page as a static front page.

  • This is the code inside /wp-includes/theme.php, which uses the solution you pointed out when $pagename can't be set:

--

if ( !$pagename && $id > 0 ) {
  // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
  $post = $wp_query->get_queried_object();
  $pagename = $post->post_name;
}

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Thanks Friend, i got an answer. This is only possible because of your help. you all give me a ray of hope towards resolving this problem.

Here is the code:

package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Facebook {
    public static void main(String args[]){
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.facebook.com");
        WebElement email= driver.findElement(By.id("email"));
        Actions builder = new Actions(driver);
        Actions seriesOfActions = builder.moveToElement(email).click().sendKeys(email, "[email protected]");
        seriesOfActions.perform();
        WebElement pass = driver.findElement(By.id("pass"));
        WebElement login =driver.findElement(By.id("u_0_b"));
        Actions seriesOfAction = builder.moveToElement(pass).click().sendKeys(pass, "naveench").click(login);
        seriesOfAction.perform();
        driver.
    }    
}

ImageView - have height match width?

Update: Sep 14 2017

According to a comment below, the percent support library is deprecated as of Android Support Library 26.0.0. This is the new way to do it:

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

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

</android.support.constraint.ConstraintLayout>

See here

Deprecated:

According to this post by Android Developers, all you need to do now is to wrap whatever you want within a PercentRelativeLayout or a PercentFrameLayout, and then specify its ratios, like so

<android.support.percent.PercentRelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        app:layout_widthPercent="100%"
        app:layout_aspectRatio="100%"/>

</android.support.percent.PercentRelativeLayout>

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

Just as normal, using data-original-title:

Html:

<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>

Javascript:

$("[rel=tooltip]").tooltip({html:true});

The html parameter specifies how the tooltip text should be turned into DOM elements. By default Html code is escaped in tooltips to prevent XSS attacks. Say you display a username on your site and you show a small bio in a tooltip. If the html code isn't escaped and the user can edit the bio themselves they could inject malicious code.

How to insert element as a first child?

Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).

ParentNode.insertBefore(<your element>, ParentNode.firstChild);

using stored procedure in entity framework

// Add some tenants to context so we have something for the procedure to return! AddTenentsToContext(Context);

    // ACT
    // Get the results by calling the stored procedure from the context extention method 
    var results = Context.ExecuteStoredProcedure(procedure);

    // ASSERT
    Assert.AreEqual(expectedCount, results.Count);
}

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

Can I add color to bootstrap icons only using CSS?

I thought that I might add this snippet to this old post. This is what I had done in the past, before the icons were fonts:

<i class="social-icon linkedin small" style="border-radius:7.5px;height:15px;width:15px;background-color:white;></i>
<i class="social-icon facebook small" style="border-radius:7.5px;height:15px;width:15px;background-color:white;></i>

This is very similar to @frbl 's sneaky answer, yet it does not use another image. Instead, this sets the background-color of the <i> element to white and uses the CSS property border-radius to make the entire <i> element "rounded." If you noticed, the value of the border-radius (7.5px) is exactly half that of the width and height property (both 15px, making the icon square), making the <i> element circular.

Infinite Recursion with Jackson JSON and Hibernate JPA issue

This worked perfectly fine for me. Add the annotation @JsonIgnore on the child class where you mention the reference to the parent class.

@ManyToOne
@JoinColumn(name = "ID", nullable = false, updatable = false)
@JsonIgnore
private Member member;

Get unicode value of a character

I found this nice code on web.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Unicode {

public static void main(String[] args) {
System.out.println("Use CTRL+C to quite to program.");

// Create the reader for reading in the text typed in the console. 
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

try {
  String line = null;
  while ((line = bufferedReader.readLine()).length() > 0) {
    for (int index = 0; index < line.length(); index++) {

      // Convert the integer to a hexadecimal code.
      String hexCode = Integer.toHexString(line.codePointAt(index)).toUpperCase();


      // but the it must be a four number value.
      String hexCodeWithAllLeadingZeros = "0000" + hexCode;
      String hexCodeWithLeadingZeros = hexCodeWithAllLeadingZeros.substring(hexCodeWithAllLeadingZeros.length()-4);

      System.out.println("\\u" + hexCodeWithLeadingZeros);
    }

  }
} catch (IOException ioException) {
       ioException.printStackTrace();
  }
 }
}

Original Article

How to convert datetime to integer in python

I think I have a shortcut for that:

# Importing datetime.
from datetime import datetime

# Creating a datetime object so we can test.
a = datetime.now()

# Converting a to string in the desired format (YYYYMMDD) using strftime
# and then to int.
a = int(a.strftime('%Y%m%d'))

Method List in Visual Studio Code

In VSCode 1.24 you can do that.

Right click on EXPLORER on the side bar and checked Outline.

How do I view cookies in Internet Explorer 11 using Developer Tools

How about typing document.cookie into the console? It just shows the values, but it's something.

enter image description here

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

You can just put // in front of $yourUrl in href:

<a href="//<?=$yourUrl?>"></a>

How to remove a variable from a PHP session array

Is the $_SESSION['name'] variable an array? If you want to delete a specific key from within an array, you have to refer to that exact key in the unset() call, otherwise you delete the entire array, e.g.

$name = array(0 => 'a', 1 => 'b', 2 => 'c');
unset($name); // deletes the entire array
unset($name[1]); // deletes only the 'b' entry

Another minor problem with your snippet: You're mixing GET query parameters in with a POST form. Is there any reason why you can't do the forms with 'name' being passed in a hidden field? It's best to not mix get and post variables, especially if you use $_REQUEST elsewhere. You can run into all kinds of fun trying to figure out why $_GET['name'] isn't showing up the same as $_POST['name'], because the server's got a differnt EGPCS order set in the 'variables_order' .ini setting.

<form blah blah blah method="post">
  <input type="hidden" name="name" value="<?= htmlspecialchars($list1) ?>" />
  <input type="submit" name="add" value="Add />
</form>

And note the htmlspecialchars() call. If either $list1 or $list2 contain a double quote ("), it'll break your HTML

How can I disable inherited css styles?

If you control both the HTML and CSS, I'd suggest switching to using ID's on all the divs needed for the rounded corner.

CSS

#d1 {
    background: #CFFEB6 url('tr.gif') no-repeat top right;
}
#d2 {
    background: url('br.gif') no-repeat bottom right;
}
#d3 {
    background: url('bl.gif') no-repeat bottom left;
}
#d4 {
    padding: 10px;
}

HTML

<div id="d1"><div id="d2"><div id="d3"><div id="d4">
    <div class='button'><a href='#'>Test</a></div>
</div></div></div></div>

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

How to run test methods in specific order in JUnit4?

The (as yet unreleased) change https://github.com/junit-team/junit/pull/386 introduces a @SortMethodsWith. https://github.com/junit-team/junit/pull/293 at least made the order predictable without that (in Java 7 it can be quite random).

Loading DLLs at runtime in C#

It's not so difficult.

You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.

Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.

This is pretty simple stuff.

Omitting one Setter/Getter in Lombok

If you have setter and getter as private it will come up in PMD checks.

@RequestParam in Spring MVC handling optional parameters

You need to give required = false for name and password request parameters as well. That's because, when you provide just the logout parameter, it actually expects for name and password as well as they are still mandatory.

It worked when you just gave name and password because logout wasn't a mandatory parameter thanks to required = false already given for logout.

JavaScript replace/regex

You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):

  "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")

Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).

Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.

How can I mark a foreign key constraint using Hibernate annotations?

@JoinColumn(name="reference_column_name") annotation can be used above that property or field of class that is being referenced from some other entity.

How to remove/ignore :hover css style on touch devices

Pointer adaptation to the rescue!

Since this hasn't been touched in awhile, you can use:

a:link, a:visited {
   color: red;
}

a:hover {
   color:blue;
}

@media (hover: none) {
   a:link, a:visited {
      color: red;
   }
}

See this demo in both your desktop browser and your phone browser. Supported by modern touch devices.

Note: Keep in mind that since a Surface PC's primary input (capability) is a mouse, it will end up being a blue link, even if it's a detached (tablet) screen. Browsers will (should) always default to the most precise input's capability.

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

It's definitely an issue with some of the projects being built for x86 compatibility instead of any CPU. If I had to guess I would say that some of the references between your projects are probably referencing the dll's in some of the bin\debug folders instead of being project references.

When a project is compiled for x86 instead of 'Any CPU' the dll's go into the bin\x86\debug folder instead of bin\debug (which is probably where your references are looking).

But in any case, you should be using project references between your projects.

How to configure PostgreSQL to accept all incoming connections

Addition to above great answers, if you want some range of IPs to be authorized, you could edit /var/lib/pgsql/{VERSION}/data file and put something like

host all all 172.0.0.0/8 trust

It will accept incoming connections from any host of the above range. Source: http://www.linuxtopia.org/online_books/database_guides/Practical_PostgreSQL_database/c15679_002.htm

How to create custom spinner like border around the spinner with down triangle on the right side?

You can achieve the following by using a single line in your spinner declaration in XML: enter image description here

Just add this: style="@android:style/Widget.Holo.Light.Spinner"

This is a default generated style in android. It doesn't contain borders around it though. For that you'd better search something on google.

Hope this helps.

UPDATE: AFter a lot of digging I got something which works well for introducing border around spinner.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="8dp"
        android:top="8dp">
        <shape>
            <solid android:color="@android:color/white" />
            <corners android:radius="4dp" />
            <stroke
                android:width="2dp"
                android:color="#9E9E9E" />
            <padding
                android:bottom="16dp"
                android:left="8dp"
                android:right="16dp"
                android:top="16dp" />
        </shape>
    </item>
</layer-list>

Place this in the drawable folder and use it as a background for spinner. Like this:

<RelativeLayout
        android:id="@+id/speaker_relative_layout"
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:background="@drawable/spinner_style"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <Spinner
            android:id="@+id/select_speaker_spinner"
            style="@style/Widget.AppCompat.DropDownItem.Spinner"
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:entries="@array/select_speaker_spinner_array"
            android:spinnerMode="dialog" />

    </RelativeLayout>

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

According to Javax's persistence documentation:

Whether the column is included in SQL UPDATE statements generated by the persistence provider.

It would be best to understand from the official documentation here.

Android replace the current fragment with another fragment

Latest Stuff

Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.

Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.

  1. Add Kotlin extension for Fragments to your project.

In your app level build.gradle file add the following,

dependencies {
    def fragment_version = "1.2.5"

    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
  1. Then simple code to replace the fragment,

In your activity

supportFragmentManager.commit {
    replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
    addToBackStack(null)
}

References

Check latest version of Fragment extension

More on Fragments

Firebase FCM force onTokenRefresh() to be called

This answer does not destroy instance id, instead it is able to get current one. It also store refreshed one in Shared preferences.

Strings.xml

<string name="pref_firebase_instance_id_key">pref_firebase_instance_id</string>
<string name="pref_firebase_instance_id_default_key">default</string>

Utility.java (any class where you want to set/get preferences)

public static void setFirebaseInstanceId(Context context, String InstanceId) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor;
    editor = sharedPreferences.edit();
    editor.putString(context.getString(R.string.pref_firebase_instance_id_key),InstanceId);
    editor.apply();
}

public static String getFirebaseInstanceId(Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String key = context.getString(R.string.pref_firebase_instance_id_key);
    String default_value = context.getString(R.string.pref_firebase_instance_id_default_key);
    return sharedPreferences.getString(key, default_value);
}

MyFirebaseInstanceIdService.java (extends FirebaseInstanceIdService)

@Override
public void onCreate()
{
    String CurrentToken = FirebaseInstanceId.getInstance().getToken();

    //Log.d(this.getClass().getSimpleName(),"Inside Instance on onCreate");
    String savedToken = Utility.getFirebaseInstanceId(getApplicationContext());
    String defaultToken = getApplication().getString(R.string.pref_firebase_instance_id_default_key);

    if(CurrentToken != null && !savedToken.equalsIgnoreCase(defaultToken))
    //currentToken is null when app is first installed and token is not available
    //also skip if token is already saved in preferences...
    {
        Utility.setFirebaseInstanceId(getApplicationContext(),CurrentToken);
    }
    super.onCreate();
}

@Override
public void onTokenRefresh() {
     .... prev code
      Utility.setFirebaseInstanceId(getApplicationContext(),refreshedToken);
     ....

}

Android 2.0 and above onCreate of service is not invoked when started automatically (source). Instead onStartCommand is overridden and used. But in actual FirebaseInstanceIdService it is declared as final and can't be overridden. However, when we start service using startService(), if service is already running, its original instance is used (which is good). Our onCreate() (defined above) also got invoked!.

Use this in begining of MainActivity or at whichever point you think you need instance id.

MyFirebaseInstanceIdService myFirebaseInstanceIdService = new MyFirebaseInstanceIdService();
Intent intent= new Intent(getApplicationContext(),myFirebaseInstanceIdService.getClass());
//Log.d(this.getClass().getSimpleName(),"Starting MyFirebaseInstanceIdService");
startService(intent); //invoke onCreate

And Finally,

Utility.getFirebaseInstanceId(getApplicationContext())

Note, you can futher enhance this by trying to move startservice() code to getFirebaseInstanceId method.

Getting a list of associative array keys

Try this:

var keys = [];
for (var key in dictionary) {
  if (dictionary.hasOwnProperty(key)) {
    keys.push(key);
  }
}

hasOwnProperty is needed because it's possible to insert keys into the prototype object of dictionary. But you typically don't want those keys included in your list.

For example, if you do this:

Object.prototype.c = 3;
var dictionary = {a: 1, b: 2};

and then do a for...in loop over dictionary, you'll get a and b, but you'll also get c.

How to get datetime in JavaScript?

If the format is "fixed" meaning you don't have to use other format you can have pure JavaScript instead of using whole library to format the date:

_x000D_
_x000D_
//Pad given value to the left with "0"_x000D_
function AddZero(num) {_x000D_
    return (num >= 0 && num < 10) ? "0" + num : num + "";_x000D_
}_x000D_
_x000D_
window.onload = function() {_x000D_
    var now = new Date();_x000D_
    var strDateTime = [[AddZero(now.getDate()), _x000D_
        AddZero(now.getMonth() + 1), _x000D_
        now.getFullYear()].join("/"), _x000D_
        [AddZero(now.getHours()), _x000D_
        AddZero(now.getMinutes())].join(":"), _x000D_
        now.getHours() >= 12 ? "PM" : "AM"].join(" ");_x000D_
    document.getElementById("Console").innerHTML = "Now: " + strDateTime;_x000D_
};
_x000D_
<div id="Console"></div>
_x000D_
_x000D_
_x000D_

The variable strDateTime will hold the date/time in the format you desire and you should be able to tweak it pretty easily if you need.

I'm using join as good practice, nothing more, it's better than adding strings together.

Possible to iterate backwards through a foreach?

No. ForEach just iterates through collection for each item and order depends whether it uses IEnumerable or GetEnumerator().

How to get the name of a class without the package?

The following function will work in JDK version 1.5 and above.

public String getSimpleName()

How to get value by key from JObject?

You can also get the value of an item in the jObject like this:

JToken value;
if (json.TryGetValue(key, out value))
{
   DoSomething(value);
}

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

VB6: Listview1.selecteditem

VB10: Listview1.FocusedItem.Text

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

I came across the same issue but a little bit different error message is

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at "xxx"

MAC & ReactNative

Add local.properties

  1. Find your Android SDK location

    /Users/yourMacUserName/Library/Android/sdk
    
  2. Create local.properties under rootProject/android/local.properties.

  3. Add sdk path into it

    sdk.dir = /Users/yourMacUserName/Library/Android/sdk
    

This normally works, but if you are working in a team with other team members, then yourMacUserName is different.

OR

Set ANDROID_SDK_ROOT variable

  1. Edit your ~/.zshrc or ~/.bashrc or ...
  2. Add SDK path:

    export ANDROID_SDK_ROOT=$HOME/Library/Android/sdk
    
  3. Open a new terminal tab or source ~/.zshrc
  4. echo $ANDROID_SDK_ROOT to test the print correct SDK path.

Alternatively, you also can add your path export PATH=${PATH}:$ANDROID_SDK_ROOT/tools:$ANDROID_SDK_ROOT/platform-tools to use some useful commands.

How to get element by innerText

You could use xpath to accomplish this

var xpath = "//a[text()='SearchingText']";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

You can also search of an element containing some text using this xpath:

var xpath = "//a[contains(text(),'Searching')]";

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

How to increase the gap between text and underlining in CSS

This is what i use:

html:

<h6><span class="horizontal-line">GET IN</span> TOUCH</h6>

css:

.horizontal-line { border-bottom: 2px solid  #FF0000; padding-bottom: 5px; }

Typescript: How to extend two classes?

There is a little known feature in TypeScript that allows you to use Mixins to create re-usable small objects. You can compose these into larger objects using multiple inheritance (multiple inheritance is not allowed for classes, but it is allowed for mixins - which are like interfaces with an associated implenentation).

More information on TypeScript Mixins

I think you could use this technique to share common components between many classes in your game and to re-use many of these components from a single class in your game:

Here is a quick Mixins demo... first, the flavours that you want to mix:

class CanEat {
    public eat() {
        alert('Munch Munch.');
    }
}

class CanSleep {
    sleep() {
        alert('Zzzzzzz.');
    }
}

Then the magic method for Mixin creation (you only need this once somewhere in your program...)

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
             if (name !== 'constructor') {
                derivedCtor.prototype[name] = baseCtor.prototype[name];
            }
        });
    }); 
}

And then you can create classes with multiple inheritance from mixin flavours:

class Being implements CanEat, CanSleep {
        eat: () => void;
        sleep: () => void;
}
applyMixins (Being, [CanEat, CanSleep]);

Note that there is no actual implementation in this class - just enough to make it pass the requirements of the "interfaces". But when we use this class - it all works.

var being = new Being();

// Zzzzzzz...
being.sleep();

Convert Python ElementTree to string

Non-Latin Answer Extension

Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.

Input

xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???")  # Read Note about Python 2

NOTE: In Python 2, when calling the toString(...) code, assigning xml with ElementTree.Element("Person", Name="???")will raise an error...

UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)

Output

ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="&#53356;&#47532;&#49828;" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />


ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" />             <-------- Python 3
# Python 3 (John): <Person Name="John" />

# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="???" />             <-------- Python 2
# Python 2 (John): <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 3 (John): <Person Name="John" />

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />

How do I correctly upgrade angular 2 (npm) to the latest version?

Alternative approach using npm-upgrade:

  1. npm i -g npm-upgrade

Go to your project folder

  1. npm-upgrade check

It will ask you if you wish to upgrade the package, select Yes

That's simple

The identity used to sign the executable is no longer valid

Same happened to me, In my case I just needed to approve apple's ne terms of service over: https://developer.apple.com/membercenter

Android Studio - Auto complete and other features not working

I had a similar problem where none of the other solutions worked.

Closing Android Studio and then deleting the .idea and build folders resolved the issue.

CASE .. WHEN expression in Oracle SQL

Following syntax would work :

....
where x.p_NBR =to_number(substr(y.k_str,11,5))
and x.q_nbr = 
 (case 
 when instr(substr(y.m_str,11,9),'_') = 6   then  to_number(substr(y.m_str,11,5))
 when instr(substr(y.m_str,11,9),'_') = 0   then  to_number(substr(y.m_str,11,9))
  else 
       1
  end
)

Get next / previous element using JavaScript?

Tested it and it worked for me. The element finding me change as per the document structure that you have.

<html>
    <head>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <form method="post" id = "formId" action="action.php" onsubmit="return false;">
            <table>
                <tr>
                    <td>
                        <label class="standard_text">E-mail</label>
                    </td>
                    <td><input class="textarea"  name="mail" id="mail" placeholder="E-mail"></label></td>
                    <td><input class="textarea"  name="name" id="name" placeholder="E-mail">   </label></td>
                    <td><input class="textarea"  name="myname" id="myname" placeholder="E-mail"></label></td>
                    <td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
                    <td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
                    <td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
                </tr>
            </table>
            <input class="button_submit" type="submit" name="send_form" value="Register"/>
        </form>
    </body>
</html>

 

var inputs;
document.addEventListener("DOMContentLoaded", function(event) {
    var form = document.getElementById('formId');
    inputs = form.getElementsByTagName("input");
    for(var i = 0 ; i < inputs.length;i++) {
        inputs[i].addEventListener('keydown', function(e){
            if(e.keyCode == 13) {
                var currentIndex = findElement(e.target)
                if(currentIndex > -1 && currentIndex < inputs.length) {
                    inputs[currentIndex+1].focus();
                }
            }   
        });
    }
});

function findElement(element) {
    var index = -1;
    for(var i = 0; i < inputs.length; i++) {
        if(inputs[i] == element) {
            return i;
        }
    }
    return index;
}

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

Try this on the PowerShell command line:

. .\MyFunctions.ps1
A1

The dot operator is used for script include.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

In my case it is Asp.Net Core 3.1 API. I changed the HTTP GET method from public ActionResult GetValidationRulesForField( GetValidationRulesForFieldDto getValidationRulesForFieldDto) to public ActionResult GetValidationRulesForField([FromQuery] GetValidationRulesForFieldDto getValidationRulesForFieldDto) and its working.

Detect changes in the DOM

The following example was adapted from Mozilla Hacks' blog post and is using MutationObserver.

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

Browser support: Chrome 18+, Firefox 14+, IE 11+, Safari 6+

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.

int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();

Hope this answers the question.

Div show/hide media query

I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media can be used for hiding elements in the screen width basis. See some example:

<div id="my-content"></div>

...and:

@media screen and (min-width: 0px) and (max-width: 400px) {
  #my-content { display: block; }  /* show it on small screens */
}

@media screen and (min-width: 401px) and (max-width: 1024px) {
  #my-content { display: none; }   /* hide it elsewhere */
}

Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.

CSS:Defining Styles for input elements inside a div

You can define style rules which only apply to specific elements inside your div with id divContainer like this:

#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */

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

If you don't mind dipping into Rx as part of the monad, you can use TakeLast:

IEnumerable<int> source = Enumerable.Range(1, 10000);

IEnumerable<int> lastThree = source.AsObservable().TakeLast(3).AsEnumerable();

Where to get "UTF-8" string literal in Java?

There are none (at least in the standard Java library). Character sets vary from platform to platform so there isn't a standard list of them in Java.

There are some 3rd party libraries which contain these constants though. One of these is Guava (Google core libraries): http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Charsets.html

Finding median of list in Python

You can try the quickselect algorithm if faster average-case running times are needed. Quickselect has average (and best) case performance O(n), although it can end up O(n²) on a bad day.

Here's an implementation with a randomly chosen pivot:

import random

def select_nth(n, items):
    pivot = random.choice(items)

    lesser = [item for item in items if item < pivot]
    if len(lesser) > n:
        return select_nth(n, lesser)
    n -= len(lesser)

    numequal = items.count(pivot)
    if numequal > n:
        return pivot
    n -= numequal

    greater = [item for item in items if item > pivot]
    return select_nth(n, greater)

You can trivially turn this into a method to find medians:

def median(items):
    if len(items) % 2:
        return select_nth(len(items)//2, items)

    else:
        left  = select_nth((len(items)-1) // 2, items)
        right = select_nth((len(items)+1) // 2, items)

        return (left + right) / 2

This is very unoptimised, but it's not likely that even an optimised version will outperform Tim Sort (CPython's built-in sort) because that's really fast. I've tried before and I lost.

How to play a sound using Swift?

Game style:

file Sfx.swift

import AVFoundation

public let sfx = Sfx.shared
public final class Sfx: NSObject {
    
    static let shared = Sfx()
    
    var apCheer: AVAudioPlayer? = nil
    
    private override init() {
        guard let s = Bundle.main.path(forResource: "cheer", ofType: "mp3") else {
            return  print("Sfx woe")
        }
        do {
            apComment = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: s))
        } catch {
            return  print("Sfx woe")
        }
    }
    
    func cheer() { apCheer?.play() }
    func plonk() { apPlonk?.play() }
    func crack() { apCrack?.play() } .. etc
}

Anywhere at all in code

sfx.explosion()
sfx.cheer()

Check if a string contains a string in C++

Starting from C++23 you can use std::string::contains

#include <string>

const auto haystack = std::string("haystack with needles");
const auto needle = std::string("needle");

if (haystack.contains(needle))
{
    // found!
}

Strip last two characters of a column in MySQL

To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING and CHAR_LENGTH functions together:

SELECT col
     , /* ANSI Syntax  */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
     , /* MySQL Syntax */ SUBSTRING(col,     1,    CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl

To remove a specific substring from the end of string, use the TRIM function:

SELECT col
     , TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.txt remains index.txt

Remove HTML tags from a String

I know this is old, but I was just working on a project that required me to filter HTML and this worked fine:

noHTMLString.replaceAll("\\&.*?\\;", "");

instead of this:

html = html.replaceAll("&nbsp;","");
html = html.replaceAll("&amp;"."");

csv.Error: iterator should return strings, not bytes

I had this error when running an old python script developped with Python 2.6.4

When updating to 3.6.2, I had to remove all 'rb' parameters from open calls in order to fix this csv reading error.

Using OR & AND in COUNTIFS

There is probably a more efficient solution to your question, but following formula should do the trick:

=SUM(COUNTIFS(J1:J196,"agree",A1:A196,"yes"),COUNTIFS(J1:J196,"agree",A1:A196,"no"))

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

Based on the acceptable answer in an object paradigm

class ISO8601Format
{
    let format: ISO8601DateFormatter

    init() {
        let format = ISO8601DateFormatter()
        format.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
        format.timeZone = TimeZone(secondsFromGMT: 0)!
        self.format = format
    }

    func date(from string: String) -> Date {
        guard let date = format.date(from: string) else { fatalError() }
        return date
    }

    func string(from date: Date) -> String { return format.string(from: date) }
}


class ISO8601Time
{
    let date: Date
    let format = ISO8601Format() //FIXME: Duplication

    required init(date: Date) { self.date = date }

    convenience init(string: String) {
        let format = ISO8601Format() //FIXME: Duplication
        let date = format.date(from: string)
        self.init(date: date)
    }

    func concise() -> String { return format.string(from: date) }

    func description() -> String { return date.description(with: .current) }
}

callsite

let now = Date()
let time1 = ISO8601Time(date: now)
print("time1.concise(): \(time1.concise())")
print("time1: \(time1.description())")


let time2 = ISO8601Time(string: "2020-03-24T23:16:17.661Z")
print("time2.concise(): \(time2.concise())")
print("time2: \(time2.description())")

How do I create a folder in a GitHub repository?

Click on new file in github repo online. Then write file name as myfolder/myfilename then give file contents and commit. Then file will be created within that new folder.

How to apply font anti-alias effects in CSS?

Short answer: You can't.

CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.

Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.

There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.

There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.

How do I put two increment statements in a C++ 'for' loop?

Try not to do it!

From http://www.research.att.com/~bs/JSF-AV-rules.pdf:

AV Rule 199
The increment expression in a for loop will perform no action other than to change a single loop parameter to the next value for the loop.

Rationale: Readability.

jQuery count number of divs with a certain class?

You can use the jquery .length property

var numItems = $('.item').length;

Curly braces in string in PHP

I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.

$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
    $this->{'value_'.$period}=1;
}

This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.

You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.

class timevalues
{
                             // Database table values:
    public $value_hour;      // maps to values.value_hour
    public $value_day;       // maps to values.value_day
    public $value_month;     // maps to values.value_month
    public $values=array();

    public function __construct()
    {
        $this->value_hour=0;
        $this->value_day=0;
        $this->value_month=0;
        $this->values=array(
            'hour'=>$this->value_hour,
            'day'=>$this->value_day,
            'month'=>$this->value_month,
        );
    }
}

Sorting data based on second column of a file

Use sort.

sort ... -k 2,2 ...