Programs & Examples On #Screen brightness

Using jQuery To Get Size of Viewport

Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.

Xcode source automatic formatting

I also feel xcode should have this function. So I made an extension to do it: Swimat

Simple install by brew cask install swimat preview

You can give it a try, see https://github.com/Jintin/Swimat for more information.

How to execute a stored procedure inside a select query

"Not Possible". You can do this using this query. Initialize here

declare @sql nvarchar(4000)=''

Set Value & exec command of your sp with parameters

SET @sql += ' Exec spName @param'
EXECUTE sp_executesql @sql,  N'@param type', @param = @param

Add CSS to <head> with JavaScript?

If you don't want to rely on a javascript library, you can use document.write() to spit out the required css, wrapped in style tags, straight into the document head:

<head>
  <script type="text/javascript">
    document.write("<style>body { background-color:#000 }</style>");
  </script>
  # other stuff..
</head>

This way you avoid firing an extra HTTP request.

There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!

http://jsbin.com/oqede3/edit

How to get first record in each group using Linq

Use it to achieve what you want. Then decide which properties you want to return.

yourList.OrderBy(l => l.Id).GroupBy(l => new { GroupName = l.F1}).Select(r => r.Key.GroupName)

Copy file remotely with PowerShell

From PowerShell version 5 onwards (included in Windows Server 2016, downloadable as part of WMF 5 for earlier versions), this is possible with remoting. The benefit of this is that it works even if, for whatever reason, you can't access shares.

For this to work, the local session where copying is initiated must have PowerShell 5 or higher installed. The remote session does not need to have PowerShell 5 installed -- it works with PowerShell versions as low as 2, and Windows Server versions as low as 2008 R2.[1]

From server A, create a session to server B:

$b = New-PSSession B

And then, still from A:

Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt

Copying items to B is done with -ToSession. Note that local paths are used in both cases; you have to keep track of what server you're on.


[1]: when copying from or to a remote server that only has PowerShell 2, beware of this bug in PowerShell 5.1, which at the time of writing means recursive file copying doesn't work with -ToSession, an apparently copying doesn't work at all with -FromSession.

clear table jquery

$("#employeeTable td").parent().remove();

This will remove all tr having td as child. i.e all rows except the header will be deleted.

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

select p.name
from   person p
where  instr(p.name,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

Getting all types that implement an interface

I got exceptions in the linq-code so I do it this way (without a complicated extension):

private static IList<Type> loadAllImplementingTypes(Type[] interfaces)
{
    IList<Type> implementingTypes = new List<Type>();

    // find all types
    foreach (var interfaceType in interfaces)
        foreach (var currentAsm in AppDomain.CurrentDomain.GetAssemblies())
            try
            {
                foreach (var currentType in currentAsm.GetTypes())
                    if (interfaceType.IsAssignableFrom(currentType) && currentType.IsClass && !currentType.IsAbstract)
                        implementingTypes.Add(currentType);
            }
            catch { }

    return implementingTypes;
}

How do I setup the dotenv file in Node.js?

My problem was stupid. I created the .env in a text editor, and when I saved it it actually saved as

'.env.txt' 

which was only visible after I did a

'ls -a'

in terminal and saw the file name.

A quick:

mv .env.txt .env

And I was in business

Git: Could not resolve host github.com error while cloning remote repository in git

Just in case future generations stuck in this too: For me what worked (on mac OSX) was to set my DNS with opendns 208.67.222.222 , 208.67.220.220. I get this numbers here: https://www.opendns.com. For some reason, my dns configuration reseted to the default numbers (my local ip I guess), and I was not able to connect to neither github, brew or rubygems. Sorry for the misspelling.

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

This is a total hack, but here's what I did...

So while playing with setting up a DocumentsProvider, I noticed that the sample code (in getDocIdForFile, around line 450) generates a unique id for a selected document based on the file's (unique) path relative to the specified root you give it (that is, what you set mBaseDir to on line 96).

So the URI ends up looking something like:

content://com.example.provider/document/root:path/to/the/file

As the docs say, it's assuming only a single root (in my case that's Environment.getExternalStorageDirectory() but you may use somewhere else... then it takes the file path, starting at the root, and makes it the unique ID, prepending "root:". So I can determine the path by eliminating the "/document/root:" part from uri.getPath(), creating an actual file path by doing something like this:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
// check resultcodes and such, then...
uri = data.getData();
if (uri.getAuthority().equals("com.example.provider"))  {
    String path = Environment.getExternalStorageDirectory(0.toString()
                 .concat("/")
                 .concat(uri.getPath().substring("/document/root:".length())));
    doSomethingWithThePath(path); }
else {
    // another provider (maybe a cloud-based service such as GDrive)
    // created this uri.  So handle it, or don't.  You can allow specific
    // local filesystem providers, filter non-filesystem path results, etc.
}

I know. It's shameful, but it worked. Again, this relies on you using your own documents provider in your app to generate the document ID.

(Also, there's a better way to build the path that don't assume "/" is the path separator, etc. But you get the idea.)

How to set up Automapper in ASP.NET Core

In my Startup.cs (Core 2.2, Automapper 8.1.1)

services.AddAutoMapper(new Type[] { typeof(DAL.MapperProfile) });            

In my data access project

namespace DAL
{
    public class MapperProfile : Profile
    {
        // place holder for AddAutoMapper (to bring in the DAL assembly)
    }
}

In my model definition

namespace DAL.Models
{
    public class PositionProfile : Profile
    {
        public PositionProfile()
        {
            CreateMap<Position, PositionDto_v1>();
        }
    }

    public class Position
    {
        ...
    }

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

C# Copy a file to another location with a different name

Use the File.Copy method instead

eg.

File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt");

You can call it whatever you want in the newFile, and it will rename it accordingly.

Closing Applications

System.Windows.Forms.Application.Exit() - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit() method is typically called from within a message loop, and forces Run() to return. To exit a message loop for the current thread only, call ExitThread(). This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run().

System.Environment.Exit(exitCode) - Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.

I hope it is best to use Application.Exit

See also these links:

C++ Erase vector element by value rather than by position?

You can use std::find to get an iterator to a value:

#include <algorithm>
std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
if (position != myVector.end()) // == myVector.end() means the element was not found
    myVector.erase(position);

httpd-xampp.conf: How to allow access to an external IP besides localhost?

Open for new app "HTTPD" (Apache server) in your Firewall

Take a look at this: https://www.youtube.com/watch?v=eqgUGF3NnuM

How do you underline a text in Android XML?

First of all, go to String.xml file

you can add any HTML attributes like , italic or bold or underline here.

    <resources>
        <string name="your_string_here">This is an <u>underline</u>.</string>
    </resources>

Blocking device rotation on mobile web pages

New API's are developing (and are currently available)!

screen.orientation.lock();   // webkit only

and

screen.lockOrientation("orientation");

Where "orientation" can be any of the following:

portrait-primary - It represents the orientation of the screen when it is in its primary portrait mode. A screen is considered in its primary portrait mode if the device is held in its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held turned by 90° clockwise. The normal position is device dependant.

portrait-secondary - It represents the orientation of the screen when it is in its secondary portrait mode. A screen is considered in its secondary portrait mode if the device is held 180° from its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held is turned by 90° anticlockwise. The normal position is device dependant.

landscape-primary - It represents the orientation of the screen when it is in its primary landscape mode. A screen is considered in its primary landscape mode if the device is held in its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° clockwise. The normal position is device dependant.

landscape-secondary - It represents the orientation of the screen when it is in its secondary landscape mode. A screen is considered in its secondary landscape mode if the device held is 180° from its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° anticlockwise. The normal position is device dependant.

portrait - It represents both portrait-primary and portrait-secondary.

landscape - It represents both landscape-primary and landscape-secondary.

default - It represents either portrait-primary and landscape-primary depends on natural orientation of devices. For example, if the panel resolution is 1280*800, default will make it landscape, if the resolution is 800*1280, default will make it to portrait.

Mozilla recommends adding a lockOrientationUniversal to screen to make it more cross-browser compatible.

screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;

Go here for more info: https://developer.mozilla.org/en-US/docs/Web/API/Screen/lockOrientation

sorting integers in order lowest to highest java

You can put them into a list and then sort them using their natural ordering, like so:

final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list

If the numbers are stored in the same variable, then you'll have to somehow put them into a List and then call sort, like so:

final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...

Collections.sort( list );
// Use the sorted list

Press TAB and then ENTER key in Selenium WebDriver

In javascript (node.js) this works for me:

describe('UI', function() {

describe('gets results from Bing', function() {
    this.timeout(10000);

    it('makes a search', function(done) {
        var driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.chrome()).
        build();


        driver.get('http://bing.com');
        var input = driver.findElement(webdriver.By.name('q'));
        input.sendKeys('something');
        input.sendKeys(webdriver.Key.ENTER);

        driver.wait(function() {
            driver.findElement(webdriver.By.className('sb_count')).
                getText().
                then(function(result) {
                  console.log('result: ', result);
                  done();
            });
        }, 8000);


    });
  });
});

For tab use webdriver.Key.TAB

How can you find out which process is listening on a TCP or UDP port on Windows?

You can also check the reserved ports with the command below. Hyper-V reserve some ports, for instance.

netsh int ipv4 show excludedportrange protocol=tcp

Difference between .on('click') vs .click()

NEW ELEMENTS

As an addendum to the comprehensive answers above to highlight critical points if you want the click to attach to new elements:

  1. elements selected by the first selector eg $("body") must exist at the time the declaration is made otherwise there is nothing to attach to.
  2. you must use the three arguments in the .on() function including the valid selector for your target elements as the second argument.

What rules does software version numbering follow?

The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:

  • Major version numbers change whenever there is some significant change being introduced. For example, a large or potentially backward-incompatible change to a software package.
  • Minor version numbers change when a new, minor feature is introduced or when a set of smaller features is rolled out.
  • Patch numbers change when a new build of the software is released to customers. This is normally for small bug-fixes or the like.

Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.

There are many variants to versioning. It all boils down to personal preference.

For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.

Setting the filter to an OpenFileDialog to allow the typical image formats?

For those who don't want to remember the syntax everytime here is a simple encapsulation:

public class FileDialogFilter : List<string>
{
    public string Explanation { get; }

    public FileDialogFilter(string explanation, params string[] extensions)
    {
        Explanation = explanation;
        AddRange(extensions);
    }

    public string GetFileDialogRepresentation()
    {
        if (!this.Any())
        {
            throw new ArgumentException("No file extension is defined.");
        }

        StringBuilder builder = new StringBuilder();

        builder.Append(Explanation);

        builder.Append(" (");
        builder.Append(String.Join(", ", this));
        builder.Append(")");

        builder.Append("|");
        builder.Append(String.Join(";", this));

        return builder.ToString();
    }
}

public class FileDialogFilterCollection : List<FileDialogFilter>
{
    public string GetFileDialogRepresentation()
    {
        return String.Join("|", this.Select(filter => filter.GetFileDialogRepresentation()));
    }
}

Usage:

FileDialogFilter filterImage = new FileDialogFilter("Image Files", "*.jpeg", "*.bmp");
FileDialogFilter filterOffice = new FileDialogFilter("Office Files", "*.doc", "*.xls", "*.ppt");

FileDialogFilterCollection filters = new FileDialogFilterCollection
{
    filterImage,
    filterOffice
};

OpenFileDialog fileDialog = new OpenFileDialog
{
    Filter = filters.GetFileDialogRepresentation()
};

fileDialog.ShowDialog();

Printing object properties in Powershell

Try this:

Write-Host ($obj | Format-Table | Out-String)

or

Write-Host ($obj | Format-List | Out-String)

Execute a shell function with timeout

This function uses only builtins

  • Maybe consider evaling "$*" instead of running $@ directly depending on your needs

  • It starts a job with the command string specified after the first arg that is the timeout value and monitors the job pid

  • It checks every 1 seconds, bash supports timeouts down to 0.01 so that can be tweaked

  • Also if your script needs stdin, read should rely on a dedicated fd (exec {tofd}<> <(:))

  • Also you might want to tweak the kill signal (the one inside the loop) which is default to -15, you might want -9

## forking is evil
timeout() {
    to=$1; shift
    $@ & local wp=$! start=0
     while kill -0 $wp; do
        read -t 1
        start=$((start+1))
        if [ $start -ge $to ]; then
            kill $wp && break
        fi
    done
}

How to use an existing database with an Android application

If you are having pre built data base than copy it in asset folder and create an new class as DataBaseHelper which implements SQLiteOpenHelper Than use following code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelperClass extends SQLiteOpenHelper{
 //The Android's default system path of your application database.
private static String DB_PATH = "/data/data/package_name/databases/";
// Data Base Name.
private static final String DATABASE_NAME = "DBName.sqlite";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE_Name = "tableName";

public Context context;
static SQLiteDatabase sqliteDataBase;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 * Parameters of super() are    1. Context
 *                              2. Data Base Name.
 *                              3. Cursor Factory.
 *                              4. Data Base Version.
 */
public DataBaseHelperClass(Context context) {       
    super(context, DATABASE_NAME, null ,DATABASE_VERSION);
    this.context = context;
}

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * By calling this method and empty database will be created into the default system path
 * of your application so we are gonna be able to overwrite that database with our database.
 * */
public void createDataBase() throws IOException{
    //check if the database exists
    boolean databaseExist = checkDataBase();

    if(databaseExist){
        // Do Nothing.
    }else{
        this.getWritableDatabase();         
        copyDataBase(); 
    }// end if else dbExist
} // end createDataBase().

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
public boolean checkDataBase(){
    File databaseFile = new File(DB_PATH + DATABASE_NAME);
    return databaseFile.exists();        
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transferring byte stream.
 * */
private void copyDataBase() throws IOException{ 
    //Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DATABASE_NAME); 
    // Path to the just created empty db
    String outFileName = DB_PATH + DATABASE_NAME; 
    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName); 
    //transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close(); 
}

/**
 * This method opens the data base connection.
 * First it create the path up till data base of the device.
 * Then create connection with data base.
 */
public void openDataBase() throws SQLException{      
    //Open the database
    String myPath = DB_PATH + DATABASE_NAME;
    sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  
}

/**
 * This Method is used to close the data base connection.
 */
@Override
public synchronized void close() { 
    if(sqliteDataBase != null)
        sqliteDataBase.close(); 
    super.close(); 
}

/**
* Apply your methods and class to fetch data using raw or queries on data base using 
* following demo example code as:
*/
public String getUserNameFromDB(){
    String query = "select User_First_Name From "+TABLE_USER_DETAILS;
    Cursor cursor = sqliteDataBase.rawQuery(query, null);
    String userName = null;
    if(cursor.getCount()>0){
        if(cursor.moveToFirst()){
    do{
                userName = cursor.getString(0);
            }while (cursor.moveToNext());
        }
    }
    return userName;
}


@Override
public void onCreate(SQLiteDatabase db) {
    // No need to write the create table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // No need to write the update table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.
    // We should not update it as requirements of application.
}   
}

Hope this will help you...

Understanding SQL Server LOCKS on SELECT queries

A SELECT in SQL Server will place a shared lock on a table row - and a second SELECT would also require a shared lock, and those are compatible with one another.

So no - one SELECT cannot block another SELECT.

What the WITH (NOLOCK) query hint is used for is to be able to read data that's in the process of being inserted (by another connection) and that hasn't been committed yet.

Without that query hint, a SELECT might be blocked reading a table by an ongoing INSERT (or UPDATE) statement that places an exclusive lock on rows (or possibly a whole table), until that operation's transaction has been committed (or rolled back).

Problem of the WITH (NOLOCK) hint is: you might be reading data rows that aren't going to be inserted at all, in the end (if the INSERT transaction is rolled back) - so your e.g. report might show data that's never really been committed to the database.

There's another query hint that might be useful - WITH (READPAST). This instructs the SELECT command to just skip any rows that it attempts to read and that are locked exclusively. The SELECT will not block, and it will not read any "dirty" un-committed data - but it might skip some rows, e.g. not show all your rows in the table.

Rails has_many with alias name

If you use has_many through, and want to alias:

has_many :alias_name, through: model_name, source: initial_name

How do I delete files programmatically on Android?

I tested this code on Nougat emulator and it worked:

In manifest add:

<application...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Create empty xml folder in res folder and past in the provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
  </paths>

Then put the next snippet into your code (for instance fragment):

File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(), 
  getActivity().getApplicationContext().getPackageName() +
    ".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);

Generate a unique id

This question seems to be answered, however for completeness, I would add another approach.

You can use a unique ID number generator which is based on Twitter's Snowflake id generator. C# implementation can be found here.

var id64Generator = new Id64Generator();

// ...

public string generateID(string sourceUrl)
{
    return string.Format("{0}_{1}", sourceUrl, id64Generator.GenerateId());
}

Note that one of very nice features of that approach is possibility to have multiple generators on independent nodes (probably something useful for a search engine) generating real time, globally unique identifiers.

// node 0
var id64Generator = new Id64Generator(0);

// node 1
var id64Generator = new Id64Generator(1);

// ... node 10
var id64Generator = new Id64Generator(10);

Android on-screen keyboard auto popping up

Include this where the imports are on top:

import android.view.WindowManager;

Add this code on OnCreate part:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ....
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}

Count the number of times a string appears within a string

Probably not the most efficient, but think it's a neat way to do it.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true"));
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "false"));

    }

    static Int32 CountAllTheTimesThisStringAppearsInThatString(string orig, string find)
    {
        var s2 = orig.Replace(find,"");
        return (orig.Length - s2.Length) / find.Length;
    }
}

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

Recreate the default website in IIS

Other answers are basically right, thanks to them I was able to restore my default web site, they're just missing some more or less important details.

This was the complete process to restore the Default Web Site in my case (IIS 7 on Windows 7 64bit):

  1. open IIS Manager
  2. right click Sites node under your machine in the Connections tree on the left side and click Add Website
  3. enter "Default Web Site" as a Site name
  4. set Application pool back to DefaultAppPool!
  5. set Physical path to %SystemDrive%\inetpub\wwwroot
  6. leave Binding and everything else as is

Possible issues:

  1. If the newly created web site cannot be started with the following message:

    Internet Information Services (IIS) Manager - The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)

    ...it's possible that port 80 is already assigned to another application (Skype in my case :). You can change the binding port to e.g. 8080 by right clicking Default Web Site and selecting Edit Bindings... and Edit.... See Error 0x80070020 when you try to start a Web site in IIS 7.0 for details. Or you can just close the application sitting on the port 80, of course.

  2. Some applications require Default Web Site to have the ID 1. In my case, it got ID 1 after recreation automatically. If it's not your case, see Re-create “default Website” in IIS after accidentally deleting. It's different for IIS 6 and 7.


Note: I had to recreate the Default Web Site, because I wasn't able to even open a project configured to run under IIS in Visual Studio. I had a solution with a couple of projects inside. One of the projects failed to load with the following error message:

The Web Application Project is configured to use IIS. The Web server 'http://localhost:8080/' could not be found.

After I have recreated the Default Web Site in IIS Manager, I was able to reload and open that specific project.

Form Validation With Bootstrap (jQuery)

You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation

They use JQuery validation.

jquery.validate.js

jquery.validate.min.js

jquery-1.7.1.min.js

enter image description here

And you'll get the source code there.

 <form id="registration-form" class="form-horizontal">
 <h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
 <div class="form-control-group">
        <label class="control-label" for="name">Your Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="name" id="name"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">User Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="username" id="username"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">Password</label>
 <div class="controls">
          <input type="password" class="input-xlarge" name="password" id="password">

</div>
</div>
<div class="form-control-group">
            <label class="control-label" for="name"> Retype Password</label>
<div class="controls">
              <input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="email">Email Address</label>
<div class="controls">
              <input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message">Your Address</label>
<div class="controls">
              <textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
             <input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
            <button type="submit" class="btn btn-success btn-large">Register</button>
            <button type="reset" class="btn">Cancel</button></div>
</form>

And The JQuery :

<script src="assets/js/jquery-1.7.1.min.js"></script>

<script src="assets/js/jquery.validate.js"></script>

<script src="script.js"></script>
<script>
            addEventListener('load', prettyPrint, false);
            $(document).ready(function(){
            $('pre').addClass('prettyprint linenums');
                  });

Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/

Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/

happy coding.

Convert timestamp to readable date/time PHP

Use PHP's date() function.

Example:

echo date('m/d/Y', 1299446702);

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

PHP if not statements

You're saying "if it's not set or it's different from add or it's different from delete". You realize that a != x && a != y, with x != y is necessarily false since a cannot be simultaneously two different values.

HttpContext.Current.Request.Url.Host what it returns?

The Host property will return the domain name you used when accessing the site. So, in your development environment, since you're requesting

http://localhost:950/m/pages/Searchresults.aspx?search=knife&filter=kitchen

It's returning localhost. You can break apart your URL like so:

Protocol: http
Host: localhost
Port: 950
PathAndQuery: /m/pages/SearchResults.aspx?search=knight&filter=kitchen

IsNull function in DB2 SQL?

COALESCE function same ISNULL function Note. you must use COALESCE function with same data type of column that you check is null.

SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

The server certificate is invalid, either because it is signed by an invalid CA (internal CA, self signed,...), doesn't match the server's name or because it is expired.

Either way, you need to find how to tell to the Python library that you are using that it must not stop at an invalid certificate if you really want to download files from this server.

C++ Redefinition Header Files (winsock2.h)

#include guards are the standard way of doing this. #pragma once is not, meaning that not all compilers support it.

Windows error 2 occured while loading the Java VM

I got the same problem after upgrading java from 1.8.0_202 to 1.8.0_211

Problem:

Here are directories where new version of 1.8.0_211 of Java installed:

Directory of c:\Program Files\Java\jre1.8.0_211\bin Directory of c:\Program Files (x86)\Common Files\Oracle\Java\javapath

So one is located in 32 bit and second is in 64 bit Program files folder. The one that is specified in the PATH is 32 bit version (c:\Program Files (x86)\Common Files\Oracle\Java\javapath), even though it was 64 bit version of the Java that was installed.

Solution:

Change system environments variable PATH from c:\Program Files (x86)\Common Files\Oracle\Java\javapath to c:\Program Files\Java\jre1.8.0_211\bin

How to extract code of .apk file which is not working?

Any .apk file from market or unsigned

  1. If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card . Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.

  2. Download Dex2Jar zip from this link: SourceForge

  3. Unzip the downloaded zip file.

  4. Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.

    dex2jar targetapp.apk file(./dex2jar app.apk on terminal)

  5. http://jd.benow.ca/ download decompiler from this link.

  6. Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.

jQuery detect if textarea is empty

I know you are long past getting a solution. So, this is for others that come along to see how other people are solving the same common problem-- like me.

The examples in the question and answers indicates the use of jQuery and I am using the .change listener/handler/whatever to see if my textarea changes. This should take care of manual text changes, automated text changes, etc. to trigger the

//pseudocode
$(document).ready(function () {
    $('#textarea').change(function () {
        if ($.trim($('#textarea').val()).length < 1) {

            $('#output').html('Someway your box is being reported as empty... sadness.');

        } else {

            $('#output').html('Your users managed to put something in the box!');
            //No guarantee it isn't mindless gibberish, sorry.

        }
    });
});

Seems to work on all the browsers I use. http://jsfiddle.net/Q3LW6/. Message shows when textarea loses focus.

Newer, more thorough example: https://jsfiddle.net/BradChesney79/tjj6338a/

Uses and reports .change(), .blur(), .keydown(), .keyup(), .mousedown(), .mouseup(), .click(), mouseleave(), and .setInterval().

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

Pandas groupby: How to get a union of strings

a simple solution would be :

>>> df.groupby(['A','B']).c.unique().reset_index()

String Pattern Matching In Java

That's just a matter of String.contains:

if (input.contains("{item}"))

If you need to know where it occurs, you can use indexOf:

int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
    ...
}

That's fine for matching exact strings - if you need real patterns (e.g. "three digits followed by at most 2 letters A-C") then you should look into regular expressions.

EDIT: Okay, it sounds like you do want regular expressions. You might want something like this:

private static final Pattern URL_PATTERN =
    Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");

...

if (URL_PATTERN.matches(input).find())

How to remove leading and trailing white spaces from a given html string?

I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.

I have come up with a solution based on your comment for the output you are looking for:

Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces 

_x000D_
_x000D_
var str = "<p>&nbsp;&nbsp;</p><div>&nbsp;</div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p>&nbsp;&nbsp;</p><div>&nbsp;</div>";_x000D_
console.log(str.trim().replace(/&nbsp;/g, '').replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
_x000D_
_x000D_
_x000D_

.trim() removes leading and trailing whitespace

.replace(/&nbsp;/g, '') removes &nbsp;

.replace(/<[^\/>][^>]*><\/[^>]+>/g, "")); removes empty tags

Xcode 10: A valid provisioning profile for this executable was not found

I had this issue occurring in Xcode 10.3 after I switched over to my XCTest unit test target then back to the project run time target.

Turns out I had a different Teams selected in my provisioning profile for each target.

To fix it :

  • Clean Build Folder

  • Make sure all may targets are using the same Team. See Profile Signing under the general tab.

  • If not using same Team for all targets, clean before switching to a build target with

    different team selected.

Google Maps API v2: How to make markers clickable?

Avoid using Activity implements OnMarkerClickListener, use a local OnMarkerClickListener

// Not a good idea
class MapActivity extends Activity implements OnMarkerClickListener {
}

You will need a map to lookup the original data model linked to the marker

private Map<Marker, Map<String, Object>> markers = new HashMap<>();

You will need a data model

private Map<String, Object> dataModel = new HashMap<>();

Put some data in the data model

dataModel.put("title", "My Spot");
dataModel.put("snipet", "This is my spot!");
dataModel.put("latitude", 20.0f);
dataModel.put("longitude", 100.0f);

When creating a new marker using a data model add both to the maker map

Marker marker = googleMap.addMarker(markerOptions);
markers.put(marker, dataModel);

For on click marker event, use a local OnMarkerClickListener:

@Override
public void onMapReady(GoogleMap googleMap) {
    // grab for laters
    this.googleMap = googleMap;

    googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Map dataModel = (Map)markers.get(marker);
            String title = (String)dataModel.get("title");
            markerOnClick(title);

            return false;
        }
    });

    mapView.onResume();

    showMarkers();

    ZoomAsync zoomAsync = new ZoomAsync();
    zoomAsync.execute();
}

For displaying the info window retrieve the original data model from the marker map:

@Override
public void onMapReady(GoogleMap googleMap) {
    this.googleMap = googleMap;
    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            Map dataModel = (Map)markers.get(marker);
            String title = (String)dataModel.get("title");

            infoWindowOnClick(title);
        }
    });

Remove an item from a dictionary when its key is unknown

a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']

"ImportError: no module named 'requests'" after installing with pip

In Windows it worked for me only after trying the following: 1. Open cmd inside the folder where "requests" is unpacked. (CTRL+SHIFT+right mouse click, choose the appropriate popup menu item) 2. (Here is the path to your pip3.exe)\pip3.exe install requests Done

Moment.js - how do I get the number of years since a date, not rounded up?

I found that it would work to reset the month to January for both dates (the provided date and the present):

> moment("02/26/1978", "MM/DD/YYYY").month(0).from(moment().month(0))
"34 years ago"

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How to create an object property from a variable value in JavaScript?

You cannot use a variable to access a property via dot notation, instead use the array notation.

var obj= {
     'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'

Using .htaccess to make all .html pages to run as .php files?

Running .html files as php stopped working all of a sudden in my .htaccess file.

Godaddy support had me change it to:

AddHandler application/x-httpd-lsphp .html

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

Okku's post worked for me in Edge. In order to get desired result on the iPhone, I had to use:

<thead class="sticky-top">

which didn't effect Edge.

javascript - replace dash (hyphen) with a space

Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.

var str = "This-is---a--news-----item----";

Then to replace all dashes with single spaces, you could do this:

var newStr = str.split('-').filter(function(item) {
  item = item ? item.replace(/-/g, ''): item
  return item;
}).join(' ');

Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:

item = item ? item.replace(/-/g, ''): item

The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.

Then when your string join runs on the filtered elements, you end up with this output:

"This is a news item"

Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.

What's the equivalent of Java's Thread.sleep() in JavaScript?

For Best solution, Use async/await statement for ecma script 2017

await can use only inside of async function

function sleep(time) {
    return new Promise((resolve) => {
        setTimeout(resolve, time || 1000);
    });
}

await sleep(10000); //this method wait for 10 sec.

Note : async / await not actualy stoped thread like Thread.sleep but simulate it

How do I get the value of a textbox using jQuery?

Per Jquery docs

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

In order to retrieve the value store in the text box with id txtEmail, you can use

$("#txtEmail").val()

Specified cast is not valid?

Try this:

public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();                
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }

SQL Server Output Clause into a scalar variable

You need a table variable and it can be this simple.

declare @ID table (ID int)

insert into MyTable2(ID)
output inserted.ID into @ID
values (1)

htaccess redirect if URL contains a certain string

RewriteRule ^(.*)foobar(.*)$ http://www.example.com/index.php [L,R=301]

(No space inside your website)

Calling a function on bootstrap modal open

if somebody still has a problem the only thing working perfectly for me by useing (loaded.bs.modal) :

 $('#editModal').on('loaded.bs.modal', function () {
       console.log('edit modal loaded');

       $('.datepicker').datepicker({
            dateFormat: 'yy-mm-dd',
            clearBtn: true,
            rtl: false,
            todayHighlight: true,
            toggleActive: true,
            changeYear: true,
            changeMonth: true
        });
});

val() vs. text() for textarea

The best way to set/get the value of a textarea is the .val(), .value method.

.text() internally uses the .textContent (or .innerText for IE) method to get the contents of a <textarea>. The following test cases illustrate how text() and .val() relate to each other:

var t = '<textarea>';
console.log($(t).text('test').val());             // Prints test
console.log($(t).val('too').text('test').val());  // Prints too
console.log($(t).val('too').text());              // Prints nothing
console.log($(t).text('test').val('too').val());  // Prints too

console.log($(t).text('test').val('too').text()); // Prints test

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.

ValueError: math domain error

You are trying to do a logarithm of something that is not positive.

Logarithms figure out the base after being given a number and the power it was raised to. log(0) means that something raised to the power of 2 is 0. An exponent can never result in 0*, which means that log(0) has no answer, thus throwing the math domain error

*Note: 0^0 can result in 0, but can also result in 1 at the same time. This problem is heavily argued over.

How do I add an element to array in reducer of React native redux?

push does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:

import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {

    arr:[]
}

export default function userState(state = initialUserState, action){
     console.log(arr);
     switch (action.type){
        case ADD_ITEM :
          return { 
             ...state,
             arr:[...state.arr, action.newItem]
        }

        default:return state
     }
}

jQuery and TinyMCE: textarea value doesn't submit

That's because it's not a textarea any longer. It's replaced with an iframe (and whatnot), and the serialize function only gets data from form fields.

Add a hidden field to the form:

<input type="hidden" id="question_html" name="question_html" />

Before posting the form, get the data from the editor and put in the hidden field:

$('#question_html').val(tinyMCE.get('question_text').getContent());

(The editor would of course take care of this itself if you posted the form normally, but as you are scraping the form and sending the data yourself without using the form, the onsubmit event on the form is never triggered.)

Grouping into interval of 5 minutes within a time range

I came across the same issue.

I found that it is easy to group by any minute interval is just dividing epoch by minutes in amount of seconds and then either rounding or using floor to get ride of the remainder. So if you want to get interval in 5 minutes you would use 300 seconds.

    SELECT COUNT(*) cnt, 
    to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300) 
    AT TIME ZONE 'UTC' as interval_alias
    FROM TABLE_NAME GROUP BY interval_alias
interval_alias       cnt
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:45:00  8
2010-11-16 10:55:00  11 

This will return the data correctly group by the selected minutes interval; however, it will not return the intervals that don't contains any data. In order to get those empty intervals we can use the function generate_series.

    SELECT generate_series(MIN(date_trunc('hour',timestamp_column)),
    max(date_trunc('minute',timestamp_column)),'5m') as interval_alias FROM 
    TABLE_NAME

Result:

interval_alias       
-------------------    
2010-11-16 10:30:00  
2010-11-16 10:35:00
2010-11-16 10:40:00   
2010-11-16 10:45:00
2010-11-16 10:50:00   
2010-11-16 10:55:00   

Now to get the result with interval with zero occurrences we just outer join both result sets.

    SELECT series.minute as interval,  coalesce(cnt.amnt,0) as count from 
       (
       SELECT count(*) amnt,
       to_timestamp(floor((extract('epoch' from timestamp_column) / 300 )) * 300)
       AT TIME ZONE 'UTC' as interval_alias
       from TABLE_NAME  group by interval_alias
       ) cnt
    
    RIGHT JOIN 
       (    
       SELECT generate_series(min(date_trunc('hour',timestamp_column)),
       max(date_trunc('minute',timestamp_column)),'5m') as minute from TABLE_NAME 
       ) series
  on series.minute = cnt.interval_alias

The end result will include the series with all 5 minute intervals even those that have no values.

interval             count
-------------------  ----  
2010-11-16 10:30:00  2
2010-11-16 10:35:00  10
2010-11-16 10:40:00  0
2010-11-16 10:45:00  8
2010-11-16 10:50:00  0 
2010-11-16 10:55:00  11 

The interval can be easily changed by adjusting the last parameter of generate_series. In our case we use '5m' but it could be any interval we want.

How to check a Long for null in java

If it is Long you can check if it's null unless you go for long (as primitive data types cant be null while Long instance is a object)

_x000D_
_x000D_
Long num; _x000D_
_x000D_
if(num == null) return;
_x000D_
_x000D_
_x000D_

For some context, you can also prefer using Optional with it to make it somehow beautiful for some use cases. Refer @RequestParam in Spring MVC handling optional parameters

Python reshape list to ndim array

The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.

You can run a small loop and change the dimension from 1xN to Nx1.

    tmp=[]
    for b in bus:
        tmp.append([b])
    bus=tmp

It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

How to change shape color dynamically?

circle.xml (drawable)

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

<solid
    android:color="#000"/>

<size
    android:width="10dp"
    android:height="10dp"/>
</shape>

layout

<ImageView
      android:id="@+id/circleColor"
      android:layout_width="15dp"
       android:layout_height="15dp"
      android:textSize="12dp"
       android:layout_gravity="center"
       android:layout_marginLeft="10dp"
      android:background="@drawable/circle"/>

in activity

   circleColor = (ImageView) view.findViewById(R.id.circleColor);
   int color = Color.parseColor("#00FFFF");
   ((GradientDrawable)circleColor.getBackground()).setColor(color);

Pip freeze vs. pip list

pip list

List installed packages: show ALL installed packages that even pip installed implictly

pip freeze

List installed packages: - list of packages that are installed using pip command

pip freeze has --all flag to show all the packages.

Other difference is the output it renders, that you can check by running the commands.

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

Had trouble importing standard java libraries such as java.beans.*

Fixed it on my Redhat 7 system by pointing it to the correct JRE path.

File->ProjectStructure->SDKs->1.8 Changed 'JDK home path:' to /usr/lib/jvm/java-1.8.0-openjdk-1.8.0161-2.b14.el7.x86_64 instead of /usr/lib/jvm/java-1.8.0-openjdk-1.8.0161-2.b14.el7_4.x86_64

The former path to jdk(with the _4 difference in path) hardly had anything in it. It was missing many java libraries.

IIS: Idle Timeout vs Recycle

IIS now has

Idle Time-out Action : Suspend setting

Suspending is just freezes the process and it is much more efficient than the destroying the process.

Appending a line break to an output file in a shell script

Try

echo -en "`date` User `whoami` started the script.\n" >> output.log

Try issuing this multiple times. I hope you are looking for the same output.

Server.UrlEncode vs. HttpUtility.UrlEncode

Fast-forward almost 9 years since this was first asked, and in the world of .NET Core and .NET Standard, it seems the most common options we have for URL-encoding are WebUtility.UrlEncode (under System.Net) and Uri.EscapeDataString. Judging by the most popular answer here and elsewhere, Uri.EscapeDataString appears to be preferable. But is it? I did some analysis to understand the differences and here's what I came up with:

  • WebUtility.UrlEncode encodes space as +; Uri.EscapeDataString encodes it as %20.
  • Uri.EscapeDataString percent-encodes !, (, ), and *; WebUtility.UrlEncode does not.
  • WebUtility.UrlEncode percent-encodes ~; Uri.EscapeDataString does not.
  • Uri.EscapeDataString throws a UriFormatException on strings longer than 65,520 characters; WebUtility.UrlEncode does not. (A more common problem than you might think, particularly when dealing with URL-encoded form data.)
  • Uri.EscapeDataString throws a UriFormatException on the high surrogate characters; WebUtility.UrlEncode does not. (That's a UTF-16 thing, probably a lot less common.)

For URL-encoding purposes, characters fit into one of 3 categories: unreserved (legal in a URL); reserved (legal in but has special meaning, so you might want to encode it); and everything else (must always be encoded).

According to the RFC, the reserved characters are: :/?#[]@!$&'()*+,;=

And the unreserved characters are alphanumeric and -._~

The Verdict

Uri.EscapeDataString clearly defines its mission: %-encode all reserved and illegal characters. WebUtility.UrlEncode is more ambiguous in both definition and implementation. Oddly, it encodes some reserved characters but not others (why parentheses and not brackets??), and stranger still it encodes that innocently unreserved ~ character.

Therefore, I concur with the popular advice - use Uri.EscapeDataString when possible, and understand that reserved characters like / and ? will get encoded. If you need to deal with potentially large strings, particularly with URL-encoded form content, you'll need to either fall back on WebUtility.UrlEncode and accept its quirks, or otherwise work around the problem.


EDIT: I've attempted to rectify ALL of the quirks mentioned above in Flurl via the Url.Encode, Url.EncodeIllegalCharacters, and Url.Decode static methods. These are in the core package (which is tiny and doesn't include all the HTTP stuff), or feel free to rip them from the source. I welcome any comments/feedback you have on these.


Here's the code I used to discover which characters are encoded differently:

var diffs =
    from i in Enumerable.Range(0, char.MaxValue + 1)
    let c = (char)i
    where !char.IsHighSurrogate(c)
    let diff = new {
        Original = c,
        UrlEncode = WebUtility.UrlEncode(c.ToString()),
        EscapeDataString = Uri.EscapeDataString(c.ToString()),
    }
    where diff.UrlEncode != diff.EscapeDataString
    select diff;

foreach (var diff in diffs)
    Console.WriteLine($"{diff.Original}\t{diff.UrlEncode}\t{diff.EscapeDataString}");

Can't create handler inside thread that has not called Looper.prepare()

first call Looper.prepare() and then call Toast.makeText().show() last call Looper.loop() like:

Looper.prepare() // to be able to make toast
Toast.makeText(context, "not connected", Toast.LENGTH_LONG).show()
Looper.loop()

Parsing PDF files (especially with tables) with PDFBox

ObjectExtractor oe = new ObjectExtractor(document);

SpreadsheetExtractionAlgorithm sea = new SpreadsheetExtractionAlgorithm(); // Tabula algo.

Page page = oe.extract(1); // extract only the first page

for (int y = 0; y < sea.extract(page).size(); y++) {
  System.out.println("table: " + y);
  Table table = sea.extract(page).get(y);

  for (int i = 0; i < table.getColCount(); i++) {
    for (int x = 0; x < table.getRowCount(); x++) {
      System.out.println("col:" + i + "/lin:x" + x + " >>" + table.getCell(x, i).getText());
    }
  }
}

What's the most efficient way to erase duplicates and sort a vector?

Here's a template to do it for you:

template<typename T>
void removeDuplicates(std::vector<T>& vec)
{
    std::sort(vec.begin(), vec.end());
    vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
}

call it like:

removeDuplicates<int>(vectorname);

Angular ng-if="" with multiple arguments

Just to clarify, be aware bracket placement is important!

These can be added to any HTML tags... span, div, table, p, tr, td etc.

AngularJS

ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

Angular2+

*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.

boolean check1 = Your conditional check here...
...

How to load external webpage in WebView

I used this code that was cool. but have an error. " neterr_cleartext_not_permitted" show when you use this code then you will face this problem..

I got a solution of this.you have to add this in your AndroidManifest.xml near about Application

android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" /> // ignore if you already added. outside of Application.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

How to skip over an element in .map()?

Since 2019, Array.prototype.flatMap is a good option.

images.flatMap(({src}) => src.endsWith('.json') ? [] : src);

From MDN:

flatMap can be used as a way to add and remove items (modify the number of items) during a map. In other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one. In this sense, it works like the opposite of filter. Simply return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item.

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Shuffling is the process by which intermediate data from mappers are transferred to 0,1 or more reducers. Each reducer receives 1 or more keys and its associated values depending on the number of reducers (for a balanced load). Further the values associated with each key are locally sorted.

Is true == 1 and false == 0 in JavaScript?

Use === to equate the variables instead of ==.

== checks if the value of the variables is similar

=== checks if the value of the variables and the type of the variables are similar

Notice how

if(0===false) {
    document.write("oh!!! that's true");
}?

and

if(0==false) {
    document.write("oh!!! that's true");
}?

give different results

Is there a way to 'uniq' by column?

awk -F"," '!_[$1]++' file
  • -F sets the field separator.
  • $1 is the first field.
  • _[val] looks up val in the hash _(a regular variable).
  • ++ increment, and return old value.
  • ! returns logical not.
  • there is an implicit print at the end.

Python 3 string.join() equivalent?

'.'.join() or ".".join().. So any string instance has the method join()

getaddrinfo: nodename nor servname provided, or not known

I was seeing this error unrelated to rails. It turned out my test was trying to use a port that was too high (greater than 65535).

This code will produce the error in question

require 'socket'
Socket.getaddrinfo("127.0.0.1", "65536")

rails generate model

You need to create new rails application first. Run

rails new mebay
cd mebay
bundle install
rails generate model ...

And try to find Rails 3 tutorial, there are a lot of changes since 2.1 Guides (http://guides.rubyonrails.org/getting_started.html) are good start point.

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

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Difference between "include" and "require" in php

<?PHP
echo "Firstline";
include('classes/connection.php');
echo "I will run if include but not on Require";
?>

A very simple Practical example with code. The first echo will be displayed. No matter you use include or require because its runs before include or required.

To check the result, In second line of a code intentionally provide the wrong path to the file or make error in file name. Thus the second echo to be displayed or not will be totally dependent on whether you use require or include.

If you use require the second echo will not execute but if you use include not matter what error comes you will see the result of second echo too.

Rails filtering array of objects by attribute value

If your attachments are

@attachments = Job.find(1).attachments

This will be array of attachment objects

Use select method to filter based on file_type.

@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }

This will not trigger any db query.

How can I insert values into a table, using a subquery with more than one result?

Try this:

INSERT INTO prices (
    group, 
    id,
    price
) 
SELECT
    7,
    articleId,
    1.50
FROM
    article 
WHERE 
    name LIKE 'ABC%';

How can I map True/False to 1/0 in a Pandas DataFrame?

You can use a transformation for your data frame:

df = pd.DataFrame(my_data condition)

transforming True/False in 1/0

df = df*1

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

How to fix missing dependency warning when using useEffect React Hook?

The solution is also given by react, they advice you use useCallback which will return a memoize version of your function :

The 'fetchBusinesses' function makes the dependencies of useEffect Hook (at line NN) change on every render. To fix this, wrap the 'fetchBusinesses' definition into its own useCallback() Hook react-hooks/exhaustive-deps

useCallback is simple to use as it has the same signature as useEffect the difference is that useCallback returns a function. It would look like this :

 const fetchBusinesses = useCallback( () => {
        return fetch("theURL", {method: "GET"}
    )
    .then(() => { /* some stuff */ })
    .catch(() => { /* some error handling */ })
  }, [/* deps */])
  // We have a first effect thant uses fetchBusinesses
  useEffect(() => {
    // do things and then fetchBusinesses
    fetchBusinesses(); 
  }, [fetchBusinesses]);
   // We can have many effect thant uses fetchBusinesses
  useEffect(() => {
    // do other things and then fetchBusinesses
    fetchBusinesses();
  }, [fetchBusinesses]);

Swift convert unix time to date and time

For me: Converting timestamps coming from API to a valid date :

`let date = NSDate.init(fromUnixTimestampNumber: timesTamp /* i.e 1547398524000 */) as Date?`

Uncaught ReferenceError: React is not defined

import React, { Component, PropTypes } from 'react';

This may also work!

var self = this?

Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this value.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

npm behind a proxy fails with status 403

npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080

credit goes to http://jjasonclark.com/how-to-setup-node-behind-web-proxy.

How does one create an InputStream from a String?

InputStream in = new ByteArrayInputStream(yourstring.getBytes());

How to run a Runnable thread in Android at defined intervals?

Kotlin

private lateinit var runnable: Runnable
override fun onCreate(savedInstanceState: Bundle?) {
    val handler = Handler()
    runnable = Runnable {
        // do your work
        handler.postDelayed(runnable, 2000)
    }
    handler.postDelayed(runnable, 2000)
}

Java

Runnable runnable;
Handler handler;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            // do your work
            handler.postDelayed(this, 1000);
        }
    };
    handler.postDelayed(runnable, 1000);
}

Laravel Migration Change to Make a Column Nullable

He're the full migration for Laravel 5:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->unsignedInteger('user_id')->nullable()->change();
    });
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->unsignedInteger('user_id')->nullable(false)->change();
    });
}

The point is, you can remove nullable by passing false as an argument.

Quickly create a large file on a Linux system

You could use https://github.com/flew-software/trash-dump you can create file that is any size and with random data

heres a command you can run after installing trash-dump (creates a 1GB file)

$ trash-dump --filename="huge" --seed=1232 --noBytes=1000000000

BTW I created it

Matplotlib different size subplots

I used pyplot's axes object to manually adjust the sizes without using GridSpec:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02

rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]

fig = plt.figure()

cones = plt.axes(rect_cones)
box = plt.axes(rect_box)

cones.plot(x, y)

box.plot(y, x)

plt.show()

Duplicate Entire MySQL Database

Here's a windows bat file I wrote which combines Vincent and Pauls suggestions. It prompts the user for source and destination names.

Just modify the variables at the top to set the proper paths to your executables / database ports.

:: Creates a copy of a database with a different name.
:: User is prompted for Src and destination name.
:: Fair Warning: passwords are passed in on the cmd line, modify the script with -p instead if security is an issue.
:: Uncomment the rem'd out lines if you want script to prompt for database username, password, etc.

:: See also: http://stackoverflow.com/questions/1887964/duplicate-entire-mysql-database

@set MYSQL_HOME="C:\sugarcrm\mysql\bin"
@set mysqldump_exec=%MYSQL_HOME%\mysqldump
@set mysql_exec=%MYSQL_HOME%\mysql
@set SRC_PORT=3306
@set DEST_PORT=3306
@set USERNAME=TODO_USERNAME
@set PASSWORD=TODO_PASSWORD

:: COMMENT any of the 4 lines below if you don't want to be prompted for these each time and use defaults above.
@SET /p USERNAME=Enter database username: 
@SET /p PASSWORD=Enter database password: 
@SET /p SRC_PORT=Enter SRC database port (usually 3306): 
@SET /p DEST_PORT=Enter DEST database port: 

%MYSQL_HOME%\mysql --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% --execute="show databases;"
@IF NOT "%ERRORLEVEL%" == "0" GOTO ExitScript

@SET /p SRC_DB=What is the name of the SRC Database:  
@SET /p DEST_DB=What is the name for the destination database (that will be created):  

%mysql_exec% --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% --execute="create database %DEST_DB%;"
%mysqldump_exec% --add-drop-table --user=%USERNAME% --password=%PASSWORD% --port=%SRC_PORT% %SRC_DB% | %mysql_exec% --user=%USERNAME% --password=%PASSWORD% --port=%DEST_PORT% %DEST_DB%
@echo SUCCESSFUL!!!
@GOTO ExitSuccess

:ExitScript
@echo "Failed to copy database"
:ExitSuccess

Sample output:

C:\sugarcrm_backups\SCRIPTS>copy_db.bat
Enter database username: root
Enter database password: MyPassword
Enter SRC database port (usually 3306): 3308
Enter DEST database port: 3308

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 --execute="show databases;"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sugarcrm_550_pro   |
| sugarcrm_550_ce    |
| sugarcrm_640_pro   |
| sugarcrm_640_ce    |
+--------------------+
What is the name of the SRC Database:  sugarcrm
What is the name for the destination database (that will be created):  sugarcrm_640_ce

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 --execute="create database sugarcrm_640_ce;"

C:\sugarcrm_backups\SCRIPTS>"C:\sugarcrm\mysql\bin"\mysqldump --add-drop-table --user=root --password=MyPassword --port=3308 sugarcrm   | "C:\sugarcrm\mysql\bin"\mysql --user=root --password=MyPassword --port=3308 sugarcrm_640_ce
SUCCESSFUL!!!

Implement touch using Python?

write_text() from pathlib.Path can be used.

>>> from pathlib import Path
>>> Path('aa.txt').write_text("")
0

Create aar file in Android Studio

Finally got the solution here - https://stackoverflow.com/a/49663101/9640177

implementation files('libs/aar-file.aar')

Edit I had one more complication - I had set minifyEnabled true for the library module.

Using $_POST to get select option value from HTML

<select name="taskOption">
      <option value="first">First</option>
      <option value="second">Second</option>
      <option value="third">Third</option>
</select>

$var = $_POST['taskOption'];

Getting DOM node from React child element

this.props.children should either be a ReactElement or an array of ReactElement, but not components.

To get the DOM nodes of the children elements, you need to clone them and assign them a new ref.

render() {
  return (
    <div>
      {React.Children.map(this.props.children, (element, idx) => {
        return React.cloneElement(element, { ref: idx });
      })}
    </div>
  );
}

You can then access the child components via this.refs[childIdx], and retrieve their DOM nodes via ReactDOM.findDOMNode(this.refs[childIdx]).

Check if a number is odd or even in python

One of the simplest ways is to use de modulus operator %. If n % 2 == 0, then your number is even.

Hope it helps,

jQuery issue - #<an Object> has no method

Ignore me. I'm sorry everyone. I'd mistyped the url of the script. Thanks to Simon Ainley for the prod in the right direction.

Sorry again. Thanks.

What does "control reaches end of non-void function" mean?

Make sure that your code is returning a value of given return-type irrespective of conditional statements

This code snippet was showing the same error

int search(char arr[], int start, int end, char value)
{
    int i;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            return i;
    }
}

This is the working code after little changes

int search(char arr[], int start, int end, char value)
{
    int i;
    int index=-1;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            index=i;
    }
    return index;
}

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

CSS filter: make color image with transparency white

You can use

filter: brightness(0) invert(1);

_x000D_
_x000D_
html {_x000D_
  background: red;_x000D_
}_x000D_
p {_x000D_
  float: left;_x000D_
  max-width: 50%;_x000D_
  text-align: center;_x000D_
}_x000D_
img {_x000D_
  display: block;_x000D_
  max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
  -webkit-filter: brightness(0) invert(1);_x000D_
  filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
  Original:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
  Filter:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

First, brightness(0) makes all image black, except transparent parts, which remain transparent.

Then, invert(1) makes the black parts white.

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

python list by value not by reference

When you do b = a you simply create another pointer to the same memory of a, that's why when you append to b , a changes too.

You need to create copy of a and that's done like this:

b = a[:]

How to do a SOAP wsdl web services call from the command line

On linux command line, you can simply execute:

curl -H "Content-Type: text/xml; charset=utf-8" -H "SOAPAction:"  -d @your_soap_request.xml -X POST https://ws.paymentech.net/PaymentechGateway

HTTP error 403 in Python 3 Web Scraping

Based on the previous answer,

from urllib.request import Request, urlopen       
#specify url
url = 'https://xyz/xyz'
req = Request(url, headers={'User-Agent': 'XYZ/3.0'})
response = urlopen(req, timeout=20).read()

This worked for me by extending the timeout.

Cannot find java. Please use the --jdkhome switch

ATTENTION MAC OS USERS


First, please remember that in a Mac computer the netbeans.conf file is stored at

/Applications/NetBeans/NetBeans 8.2.app/Contents/Resources/NetBeans/etc/netbeans.conf

(if you had used the default installation package.)

Then, also remember that the directory you MUST use on either "netbeans_jdkhome" or "--jdkhome" it's NOT the /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/ but the following one:

/Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home //<-- Please, notice the /Contents/Home at the end. That's the "trick"!

Note: of course, you must change the versions for both NetBeans and JDK you're using.

What's the difference between :: (double colon) and -> (arrow) in PHP?

The difference between static and instantiated methods and properties seem to be one of the biggest obstacles to those just starting out with OOP PHP in PHP 5.

The double colon operator (which is called the Paamayim Nekudotayim from Hebrew - trivia) is used when calling an object or property from a static context. This means an instance of the object has not been created yet.

The arrow operator, conversely, calls methods or properties that from a reference of an instance of the object.

Static methods can be especially useful in object models that are linked to a database for create and delete methods, since you can set the return value to the inserted table id and then use the constructor to instantiate the object by the row id.

Fast and simple String encrypt/decrypt in JAVA

If you are using Android then you can use android.util.Base64 class.

Encode:

passwd = Base64.encodeToString( passwd.getBytes(), Base64.DEFAULT );

Decode:

passwd = new String( Base64.decode( passwd, Base64.DEFAULT ) );

A simple and fast single line solution.

Converting serial port data to TCP/IP in a Linux environment

I stumbled upon this question via a Google search for a very similar one (using the serial port on a server from a Linux client over TCP/IP), so, even though this is not an answer to exact original question, some of the code might be useful to the original poster, I think:

  • Making a Linux box with a serial port listen on the TCP port to share the modem: ser2net
  • Using this "shared" modem from another Linux workstation: remtty

Django database query: How to get object by id?

You can also do:

obj = ClassModel.get_by_id(object_id)

This works, but there may I'm not sure if it's supported in Django 2.

Reverting single file in SVN to a particular revision

If you want to roll back an individual file from a specific revision and be able to commit, then do:

svn merge -c -[OldRev#] [Filename]

ie. svn merge -c -150 myfile.py

Note the negative on the revision number

How can I download a specific Maven artifact in one command line?

You could use the maven dependency plugin which has a nice dependency:get goal since version 2.1. No need for a pom, everything happens on the command line.

To make sure to find the dependency:get goal, you need to explicitly tell maven to use the version 2.1, i.e. you need to use the fully qualified name of the plugin, including the version:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
    -DrepoUrl=url \
    -Dartifact=groupId:artifactId:version

UPDATE: With older versions of Maven (prior to 2.1), it is possible to run dependency:get normally (without using the fully qualified name and version) by forcing your copy of maven to use a given version of a plugin.

This can be done as follows:

1. Add the following line within the <settings> element of your ~/.m2/settings.xml file:

<usePluginRegistry>true</usePluginRegistry>

2. Add the file ~/.m2/plugin-registry.xml with the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<pluginRegistry xsi:schemaLocation="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0 http://maven.apache.org/xsd/plugin-registry-1.0.0.xsd"
xmlns="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <useVersion>2.1</useVersion>
      <rejectedVersions/>
    </plugin>
  </plugins>
</pluginRegistry>

But this doesn't seem to work anymore with maven 2.1/2.2. Actually, according to the Introduction to the Plugin Registry, features of the plugin-registry.xml have been redesigned (for portability) and the plugin registry is currently in a semi-dormant state within Maven 2. So I think we have to use the long name for now (when using the plugin without a pom, which is the idea behind dependency:get).

Dynamically load a function from a DLL

LoadLibrary does not do what you think it does. It loads the DLL into the memory of the current process, but it does not magically import functions defined in it! This wouldn't be possible, as function calls are resolved by the linker at compile time while LoadLibrary is called at runtime (remember that C++ is a statically typed language).

You need a separate WinAPI function to get the address of dynamically loaded functions: GetProcAddress.

Example

#include <windows.h>
#include <iostream>

/* Define a function pointer for our imported
 * function.
 * This reads as "introduce the new type f_funci as the type: 
 *                pointer to a function returning an int and 
 *                taking no arguments.
 *
 * Make sure to use matching calling convention (__cdecl, __stdcall, ...)
 * with the exported function. __stdcall is the convention used by the WinAPI
 */
typedef int (__stdcall *f_funci)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");

  if (!hGetProcIDDLL) {
    std::cout << "could not load the dynamic library" << std::endl;
    return EXIT_FAILURE;
  }

  // resolve function address here
  f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
  if (!funci) {
    std::cout << "could not locate the function" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "funci() returned " << funci() << std::endl;

  return EXIT_SUCCESS;
}

Also, you should export your function from the DLL correctly. This can be done like this:

int __declspec(dllexport) __stdcall funci() {
   // ...
}

As Lundin notes, it's good practice to free the handle to the library if you don't need them it longer. This will cause it to get unloaded if no other process still holds a handle to the same DLL.

Spring MVC: Complex object as GET @RequestParam

You can absolutely do that, just remove the @RequestParam annotation, Spring will cleanly bind your request parameters to your class instance:

public @ResponseBody List<MyObject> myAction(
    @RequestParam(value = "page", required = false) int page,
    MyObject myObject)

Closing Bootstrap modal onclick

Close the modal box using javascript

$('#product-options').modal('hide');

Open the modal box using javascript

$('#product-options').modal('show');

Toggle the modal box using javascript

$('#myModal').modal('toggle');

Means close the modal if it's open and vice versa.

Building a fat jar using maven

You can use the maven-shade-plugin.

After configuring the shade plugin in your build the command mvn package will create one single jar with all dependencies merged into it.

SQL WITH clause example

The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.

Syntax For The SQL WITH Clause

The following is the syntax of the SQL WITH clause when using a single sub-query alias.

WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]

When using multiple sub-query aliases, the syntax is as follows.

WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]

In the syntax documentation above, the occurrences of alias_name is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.

For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx

Is it possible to change the package name of an Android app on Google Play?

Never, you can't do it since package name is the unique name Identifier for your app.....

jQuery - Sticky header that shrinks when scrolling down

Here a CSS animation fork of jezzipin's Solution, to seperate code from styling.

JS:

$(window).on("scroll touchmove", function () {
  $('#header_nav').toggleClass('tiny', $(document).scrollTop() > 0);
});

CSS:

.header {
  width:100%;
  height:100px;
  background: #26b;
  color: #fff;
  position:fixed;
  top:0;
  left:0;
  transition: height 500ms, background 500ms;
}
.header.tiny {
  height:40px;
  background: #aaa;
}

http://jsfiddle.net/sinky/S8Fnq/

On scroll/touchmove the css class "tiny" is set to "#header_nav" if "$(document).scrollTop()" is greater than 0.

CSS transition attribute animates the "height" and "background" attribute nicely.

How To Check If A Key in **kwargs Exists?

You want

if 'errormessage' in kwargs:
    print("found it")

To get the value of errormessage

if 'errormessage' in kwargs:
    print("errormessage equals " + kwargs.get("errormessage"))

In this way, kwargs is just another dict. Your first example, if kwargs['errormessage'], means "get the value associated with the key "errormessage" in kwargs, and then check its bool value". So if there's no such key, you'll get a KeyError.

Your second example, if errormessage in kwargs:, means "if kwargs contains the element named by "errormessage", and unless "errormessage" is the name of a variable, you'll get a NameError.

I should mention that dictionaries also have a method .get() which accepts a default parameter (itself defaulting to None), so that kwargs.get("errormessage") returns the value if that key exists and None otherwise (similarly kwargs.get("errormessage", 17) does what you might think it does). When you don't care about the difference between the key existing and having None as a value or the key not existing, this can be handy.

How do I pull files from remote without overwriting local files?

You can stash your local changes first, then pull, then pop the stash.

git stash
git pull origin master
git stash pop

Anything that overrides changes from remote will have conflicts which you will have to manually resolve.

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

As of R2017b, this is not officially possible. The relevant documentation states that:

Program files can contain multiple functions. If the file contains only function definitions, the first function is the main function, and is the function that MATLAB associates with the file name. Functions that follow the main function or script code are called local functions. Local functions are only available within the file.

However, workarounds suggested in other answers can achieve something similar.

Object Dump JavaScript

function mydump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;

    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";

    if(typeof(arr) == 'object') {  
        for(var item in arr) {
            var value = arr[item];

            if(typeof(value) == 'object') { 
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += mydump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { 
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}

How to Query an NTP Server using C#?

A modified version to compensate network times and calculate with DateTime-Ticks (more precise than milliseconds)

public static DateTime GetNetworkTime()
{
  const string NtpServer = "pool.ntp.org";

  const int DaysTo1900 = 1900 * 365 + 95; // 95 = offset for leap-years etc.
  const long TicksPerSecond = 10000000L;
  const long TicksPerDay = 24 * 60 * 60 * TicksPerSecond;
  const long TicksTo1900 = DaysTo1900 * TicksPerDay;

  var ntpData = new byte[48];
  ntpData[0] = 0x1B; // LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)

  var addresses = Dns.GetHostEntry(NtpServer).AddressList;
  var ipEndPoint = new IPEndPoint(addresses[0], 123);
  long pingDuration = Stopwatch.GetTimestamp(); // temp access (JIT-Compiler need some time at first call)
  using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
  {
    socket.Connect(ipEndPoint);
    socket.ReceiveTimeout = 5000;
    socket.Send(ntpData);
    pingDuration = Stopwatch.GetTimestamp(); // after Send-Method to reduce WinSocket API-Call time

    socket.Receive(ntpData);
    pingDuration = Stopwatch.GetTimestamp() - pingDuration;
  }

  long pingTicks = pingDuration * TicksPerSecond / Stopwatch.Frequency;

  // optional: display response-time
  // Console.WriteLine("{0:N2} ms", new TimeSpan(pingTicks).TotalMilliseconds);

  long intPart = (long)ntpData[40] << 24 | (long)ntpData[41] << 16 | (long)ntpData[42] << 8 | ntpData[43];
  long fractPart = (long)ntpData[44] << 24 | (long)ntpData[45] << 16 | (long)ntpData[46] << 8 | ntpData[47];
  long netTicks = intPart * TicksPerSecond + (fractPart * TicksPerSecond >> 32);

  var networkDateTime = new DateTime(TicksTo1900 + netTicks + pingTicks / 2);

  return networkDateTime.ToLocalTime(); // without ToLocalTime() = faster
}

echo that outputs to stderr

My suggestion:

echo "my errz" >> /proc/self/fd/2

or

echo "my errz" >> /dev/stderr

echo "my errz" > /proc/self/fd/2 will effectively output to stderr because /proc/self is a link to the current process, and /proc/self/fd holds the process opened file descriptors, and then, 0, 1, and 2 stand for stdin, stdout and stderr respectively.

The /proc/self link doesn't work on MacOS, however, /proc/self/fd/* is available on Termux on Android, but not /dev/stderr. How to detect the OS from a Bash script? can help if you need to make your script more portable by determining which variant to use.

Bootstrap 4 datapicker.js not included

Most of bootstrap datepickers as I write this answer are rather buggy when included in Bootstrap 4. In my view the least code adding solution is a jQuery plugin. I used this one https://plugins.jquery.com/datetimepicker/ - you can see its usage here: https://xdsoft.net/jqplugins/datetimepicker/ It sure is not as smooth as the whole BS interface, but it only requires its css and js files along with jQuery which is already included in bootstrap.

Convert an integer to a byte array

What's wrong with converting it to a string?

[]byte(fmt.Sprintf("%d", myint))

How can I solve equations in Python?

Use a different tool. Something like Wolfram Alpha, Maple, R, Octave, Matlab or any other algebra software package.

As a beginner you should probably not attempt to solve such a non-trivial problem.

Detect Route Change with react-router

This is an old question and I don't quite understand the business need of listening for route changes to push a route change; seems roundabout.

BUT if you ended up here because all you wanted was to update the 'page_path' on a react-router route change for google analytics / global site tag / something similar, here's a hook you can now use. I wrote it based on the accepted answer:

useTracking.js

import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'

export const useTracking = (trackingId) => {
  const { listen } = useHistory()

  useEffect(() => {
    const unlisten = listen((location) => {
      // if you pasted the google snippet on your index.html
      // you've declared this function in the global
      if (!window.gtag) return

      window.gtag('config', trackingId, { page_path: location.pathname })
    })

    // remember, hooks that add listeners
    // should have cleanup to remove them
    return unlisten
  }, [trackingId, listen])
}

You should use this hook once in your app, somewhere near the top but still inside a router. I have it on an App.js that looks like this:

App.js

import * as React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'

import Home from './Home/Home'
import About from './About/About'
// this is the file above
import { useTracking } from './useTracking'

export const App = () => {
  useTracking('UA-USE-YOURS-HERE')

  return (
    <Switch>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/">
        <Home />
      </Route>
    </Switch>
  )
}

// I find it handy to have a named export of the App
// and then the default export which wraps it with
// all the providers I need.
// Mostly for testing purposes, but in this case,
// it allows us to use the hook above,
// since you may only use it when inside a Router
export default () => (
  <BrowserRouter>
    <App />
  </BrowserRouter>
)

Check if an element is a child of a parent

In addition to the other answers, you can use this less-known method to grab elements of a certain parent like so,

$('child', 'parent');

In your case, that would be

if ($(event.target, 'div#hello')[0]) console.log(`${event.target.tagName} is an offspring of div#hello`);

Note the use of commas between the child and parent and their separate quotation marks. If they were surrounded by the same quotes

$('child, parent');

you'd have an object containing both objects, regardless of whether they exist in their document trees.

Use multiple css stylesheets in the same html page

You can't and don't.

All CSS rules on page will be applied (the HTML "knows" nothing about this process), and the individual rules with the highest specificity will "stick". Specificity is determined by the selector and by the order they appear in the document. All in all the point is that this is part of the cascading. You should refer to one of the very many CSS tutorials on the net.

how to get login option for phpmyadmin in xampp

Can you set the password to the phpmyadmin here

http://localhost/security/index.php

How do you handle multiple submit buttons in ASP.NET MVC Framework?

Here is a mostly clean attribute-based solution to the multiple submit button issue based heavily on the post and comments from Maarten Balliauw.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
    public string Name { get; set; }
    public string Argument { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        var isValidName = false;
        var keyValue = string.Format("{0}:{1}", Name, Argument);
        var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);

        if (value != null)
        {
            controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
            isValidName = true;
        }

        return isValidName;
    }
}

razor:

<form action="" method="post">
 <input type="submit" value="Save" name="action:Save" />
 <input type="submit" value="Cancel" name="action:Cancel" />
</form>

and controller:

[HttpPost]
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult Save(MessageModel mm) { ... }

[HttpPost]
[MultipleButton(Name = "action", Argument = "Cancel")]
public ActionResult Cancel(MessageModel mm) { ... }

Update: Razor pages looks to provide the same functionality out of the box. For new development, it may be preferable.

How does Go update third-party packages?

Go to path and type

go get -u ./..

It will update all require packages.

Best practice to validate null and empty collection in Java

If you need to check for null, that is the way. However, if you have control on this, just return empty collection, whenever you can, and check only for empty later on.

This thread is about the same thing with C#, but the principles applies equally well to java. Like mentioned there, null should be returned only if

  • null might mean something more specific;
  • your API (contract) might force you to return null.

Java : Sort integer array without using Arrays.sort()

class Sort 
{
    public static void main(String[] args) 
    {
    System.out.println("Enter the range");
    java.util.Scanner sc=new java.util.Scanner(System.in);
    int n=sc.nextInt();
    int arr[]=new int[n];
    System.out.println("Enter the array values");
    for(int i=0;i<=n-1;i++)
    {
        arr[i]=sc.nextInt();

    }
    System.out.println("Before sorting array values are");
     for(int i=0;i<=n-1;i++)
    {
     System.out.println(arr[i]);
       }
    System.out.println();
    for(int pass=1;pass<=n;pass++)
    {
    for(int i=0;i<=n-1;i++)
    {
        if(i==n-1)
        {
            break;
        }
        int temp;
        if(arr[i]>arr[i+1])
        {

            temp=arr[i];
            arr[i]=arr[i+1];
            arr[i+1]=temp;
        }
    }
    }

    System.out.println("After sorting array values are");
       for(int i=0;i<=n-1;i++)
    {
     System.out.println(arr[i]);
       }

}
}    

How do I do logging in C# without using 3rd party libraries?

If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.

github changes not staged for commit

I was having the same problem. I ended up going into the subdirectory that was "not staged for commit" and adding, committing and pushing from there. after that, went up one level to master directory and was able to push correctly.

Inserting image into IPython notebook markdown

I put the IPython notebook in the same folder with the image. I use Windows. The image name is "phuong huong xac dinh.PNG".

In Markdown:

<img src="phuong huong xac dinh.PNG">

Code:

from IPython.display import Image
Image(filename='phuong huong xac dinh.PNG')

How to retrieve the current value of an oracle sequence without increment it?

This is not an answer, really and I would have entered it as a comment had the question not been locked. This answers the question:

Why would you want it?

Assume you have a table with the sequence as the primary key and the sequence is generated by an insert trigger. If you wanted to have the sequence available for subsequent updates to the record, you need to have a way to extract that value.

In order to make sure you get the right one, you might want to wrap the INSERT and RonK's query in a transaction.

RonK's Query:

select MY_SEQ_NAME.currval from DUAL;

In the above scenario, RonK's caveat does not apply since the insert and update would happen in the same session.

How to hide the bar at the top of "youtube" even when mouse hovers over it?

The answer to this question in 2020 is IT DOESN'T WORK AT ALL NOW.

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

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

LocalForward 5901 computer.myHost.edu:5901

How to get Month Name from Calendar?

from the SimpleDateFormat java doc:

*         <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
 *         <td><code>02001.July.04 AD 12:08 PM</code>
 *         <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
 *         <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

How do I find out what version of WordPress is running?

For any wordpress site, you can go to http://example.com/feed and check the following tag in the xml file to see the version number:

<generator>http://wordpress.org/?v=3.7</generator>

Here, 3.7 is the version installed.

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

Print raw string from variable? (not getting the answers)

You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.

Windows shell command to get the full path to the current directory?

As one of the possible codes

    echo off
    for /f "usebackq tokens=* delims= " %%x in (`chdir`) do set var=%var% %%x
    echo The current directory is: "%var:~1%"

Prevent Android activity dialog from closing on outside touch

Here is my solution:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Difficulty Level");
builder.setCancelable(false);

What is the difference between String.slice and String.substring?

Note: if you're in a hurry, and/or looking for short answer scroll to the bottom of the answer, and read the last two lines.if Not in a hurry read the whole thing.


let me start by stating the facts:

Syntax:
string.slice(start,end)
string.substr(start,length)
string.substring(start,end)
Note #1: slice()==substring()

What it does?
The slice() method extracts parts of a string and returns the extracted parts in a new string.
The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
The substring() method extracts parts of a string and returns the extracted parts in a new string.
Note #2:slice()==substring()

Changes the Original String?
slice() Doesn't
substr() Doesn't
substring() Doesn't
Note #3:slice()==substring()

Using Negative Numbers as an Argument:
slice() selects characters starting from the end of the string
substr()selects characters starting from the end of the string
substring() Doesn't Perform
Note #3:slice()==substr()

if the First Argument is Greater than the Second:
slice() Doesn't Perform
substr() since the Second Argument is NOT a position, but length value, it will perform as usual, with no problems
substring() will swap the two arguments, and perform as usual

the First Argument:
slice() Required, indicates: Starting Index
substr() Required, indicates: Starting Index
substring() Required, indicates: Starting Index
Note #4:slice()==substr()==substring()

the Second Argument:
slice() Optional, The position (up to, but not including) where to end the extraction
substr() Optional, The number of characters to extract
substring() Optional, The position (up to, but not including) where to end the extraction
Note #5:slice()==substring()

What if the Second Argument is Omitted?
slice() selects all characters from the start-position to the end of the string
substr() selects all characters from the start-position to the end of the string
substring() selects all characters from the start-position to the end of the string
Note #6:slice()==substr()==substring()

so, you can say that there's a difference between slice() and substr(), while substring() is basically a copy of slice().

in Summary:
if you know the index(the position) on which you'll stop (but NOT include), Use slice()
if you know the length of characters to be extracted use substr().

PadLeft function in T-SQL

This works for strings, integers and numeric:

SELECT CONCAT(REPLICATE('0', 4 - LEN(id)), id)

Where 4 is desired length. Works for numbers with more than 4 digits, returns empty string on NULL value.

Show hide divs on click in HTML and CSS without jQuery

Using label and checkbox input

Keeps the selected item opened and togglable.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="checkbox"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="checkbox">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using label and named radio input

Similar to checkboxes, it just closes the already opened one.
Use name="c1" type="radio" on both inputs.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="radio" name="c1"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="radio" name="c1">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using tabindex and :focus

Similar to radio inputs, additionally you can trigger the states using the Tab key.
Clicking outside of the accordion will close all opened items.

_x000D_
_x000D_
.collapse > a{_x000D_
  background: #cdf;_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
}_x000D_
.collapse:focus{_x000D_
  outline: none;_x000D_
}_x000D_
.collapse > div{_x000D_
  display: none;_x000D_
}_x000D_
.collapse:focus div{_x000D_
  display: block; _x000D_
}
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 1</a>_x000D_
  <div>Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 2</a>_x000D_
  <div>Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using :target

Similar to using radio input, you can additionally use Tab and keys to operate

_x000D_
_x000D_
.collapse a{_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse > div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse > div:target{_x000D_
  display:block; _x000D_
}
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_1">Collapse 1</a>_x000D_
  <div id="targ_1">Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_2">Collapse 2</a>_x000D_
  <div id="targ_2">Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using <detail> and <summary> tags (pure HTML)

You can use HTML5's detail and summary tags to solve this problem without any CSS styling or Javascript. Please note that these tags are not supported by Internet Explorer.

_x000D_
_x000D_
<details>_x000D_
  <summary>Collapse 1</summary>_x000D_
  <p>Content 1...</p>_x000D_
</details>_x000D_
<details>_x000D_
  <summary>Collapse 2</summary>_x000D_
  <p>Content 2...</p>_x000D_
</details>
_x000D_
_x000D_
_x000D_

How can I position my jQuery dialog to center?

Are you running into this in IE only? If so, try adding this to the FIRST line of your page's HEAD tag:

<meta http-equiv="X-UA-Compatible" content="IE=7" />

I had though that all compatibility issues were fixed in later jQueries, but I ran into this one today.

Convert a character digit to the corresponding integer in C

If your digit is, say, '5', in ASCII it is represented as the binary number 0011 0101 (53). Every digit has the highest four bits 0011 and the lowest 4 bits represent the digit in bcd. So you just do

char cdig = '5';
int dig = cdig & 0xf; // dig contains the number 5

to get the lowest 4 bits, or, what its same, the digit. In asm, it uses and operation instead of sub(as in the other answers).

add item to dropdown list in html using javascript

For higher performance, I recommend this:

var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');

//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
    //var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
    option.text = option.value = i;
    options.push(option.outerHTML);
}

select.insertAdjacentHTML('beforeEnd', options.join('\n'));

This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.

Optional for generating the string by hand:

function escapeHTML(str)
{
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:

var docfrag = document.createDocumentFragment();

for (var i = 1900; i < 2012; ++i)
{
     docfrag.appendChild(new Option(i, i));
}

var select = document.getElementById("year");
select.appendChild(docfrag);

What does the [Flags] Enum Attribute mean in C#?

Flags allow you to use bitmasking inside your enumeration. This allows you to combine enumeration values, while retaining which ones are specified.

[Flags]
public enum DashboardItemPresentationProperties : long
{
    None = 0,
    HideCollapse = 1,
    HideDelete = 2,
    HideEdit = 4,
    HideOpenInNewWindow = 8,
    HideResetSource = 16,
    HideMenu = 32
}

Making a Simple Ajax call to controller in asp.net mvc

Use a Razor to dynamically change your URL by calling your action like this:

$.ajax({
    type: "POST",
    url: '@Url.Action("ActionName", "ControllerName")',
    contentType: "application/json; charset=utf-8",
    data: { data: "yourdata" },
    dataType: "json",
    success: function(recData) { alert('Success'); },
    error: function() { alert('A error'); }
});

How to get week number of the month from the date in sql server 2008

WeekMonth = CASE WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 22 THEN '5' 
                 WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 15 THEN '4' 
                 WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 8 THEN '3'
                 WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 1 THEN '2' 
                 ELSE '1'
             END 

jQuery get content between <div> tags

use jquery for that:

$("#divId").html()

How to call gesture tap on UIView programmatically in swift

You need to initialize UITapGestureRecognizer with a target and action, like so:

let tap = UITapGestureRecognizer(target: self, action: "handleTap:")
tap.delegate = self
myView.addGestureRecognizer(tap)

Then, you should implement the handler, which will be called each time when a tap event occurs:

func handleTap(sender: UITapGestureRecognizer) {
  // handling code
}

No signing certificate "iOS Distribution" found

You need to have the private key of the signing certificate in the keychain along with the public key. Have you created the certificate using the same Mac (keychain) ?

Solution #1:

  • Revoke the signing certificate (reset) from apple developer portal
  • Create the signing certificate again on the same mac (keychain). Then you will have the private key for the signing certificate!

Solution #2:

  • Export the signing identities from the origin xCode
  • Import the signing on your xCode

Apple documentation: https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingCertificates/MaintainingCertificates.html

Get ID from URL with jQuery

const url = "http://www.example.com/1234"
const id = url.split('/').pop();

Try this, it is much easier

The output gives 1234

Removing object properties with Lodash

This is my solution to deep remove empty properties with Lodash:

const compactDeep = obj => {
    const emptyFields = [];

    function calculateEmpty(prefix, source) {
        _.each(source, (val, key) => {
           if (_.isObject(val) && !_.isEmpty(val)) {
                calculateEmpty(`${prefix}${key}.`, val);
            } else if ((!_.isBoolean(val) && !_.isNumber(val) && !val) || (_.isObject(val) && _.isEmpty(val))) {
                emptyFields.push(`${prefix}${key}`);
            }
        });
    }

    calculateEmpty('', obj);

    return _.omit(obj, emptyFields);
};

Popup window in PHP?

You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.

How to Check whether Session is Expired or not in asp.net

Here I am checking session values(two values filled in text box on previous page)

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["sessUnit_code"] == null || Session["sessgrcSerial"] == null)
    {
        Response.Write("<Script Language = 'JavaScript'> alert('Go to GRC Tab and fill Unit Code and GRC Serial number first')</script>");
    }
    else
    {

        lblUnit.Text = Session["sessUnit_code"].ToString();
        LblGrcSr.Text = Session["sessgrcSerial"].ToString();
    }
}

Apache default VirtualHost

Obligatory - none of the previous answers worked for me. I inherited a strange combination of IP address-based virtual hosts and * vhosts (not assigned/catch all IP addresses) based virtual hosts in this Apache configuration messed up by ISPConfig.

I wanted Apache to serve not configured hosts with the same page.

I had: not configured hosts went to the first vhost after 000-default.conf. No matter I had *:80 catch all defined as the first vhost, instead of default Apache would load first defined site:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
</VirtualHost>

Although it's not completely valid configuration, what finally worked was adding an IP address-based virtualhost without ServerName/ServerAlias defined:

<VirtualHost 192.168.10.10:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
</VirtualHost>

<VirtualHost 192.168.10.10:443>
  ServerAdmin webmaster@localhost
  DocumentRoot /var/www/html
  SSLEngine On
  ...
</VirtualHost>

$ apachectl -S outputs IP address-based vhosts first, and * based vhosts later, and finally my default site is loaded before real site:

AH00548: NameVirtualHost has no effect and will be removed in the next release /etc/apache2/sites-enabled/000-default.conf:50
192.168.10.10:80        is a NameVirtualHost
         default server server.tld (/etc/apache2/sites-enabled/000-default.conf:34)
         port 80 namevhost server.tld (/etc/apache2/sites-enabled/000-default.conf:34)
         port 80 namevhost some-site.tld (/etc/apache2/sites-enabled/100-some-site.tld.vhost:7)

...

46.23.86.103:443       is a NameVirtualHost
         default server server.tld (/etc/apache2/sites-enabled/000-default.conf:38)
         port 443 namevhost server.tld (/etc/apache2/sites-enabled/000-default.conf:38)
         port 443 namevhost some-site.tld (/etc/apache2/sites-enabled/100-some-site.tld.vhost:182)

...

*:80                   is a NameVirtualHost
         default server server.tld (/etc/apache2/sites-enabled/000-default.conf:1)
         port 80 namevhost server.tld (/etc/apache2/sites-enabled/000-default.conf:1)

Word of notice - in a configuration like this, * vhosts won't work, so you need to apply IP addresses to all vhosts.

How to determine the current iPhone/device model?

I found that a lot all these answers use strings. I decided to change @HAS answer to use an enum:

public enum Devices: String {
    case IPodTouch5
    case IPodTouch6
    case IPhone4
    case IPhone4S
    case IPhone5
    case IPhone5C
    case IPhone5S
    case IPhone6
    case IPhone6Plus
    case IPhone6S
    case IPhone6SPlus
    case IPhone7
    case IPhone7Plus
    case IPhoneSE
    case IPad2
    case IPad3
    case IPad4
    case IPadAir
    case IPadAir2
    case IPadMini
    case IPadMini2
    case IPadMini3
    case IPadMini4
    case IPadPro
    case AppleTV
    case Simulator
    case Other
}

public extension UIDevice {

    public var modelName: Devices {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8 , value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }

        switch identifier {
        case "iPod5,1":                                 return Devices.IPodTouch5
        case "iPod7,1":                                 return Devices.IPodTouch6
        case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return Devices.IPhone4
        case "iPhone4,1":                               return Devices.IPhone4S
        case "iPhone5,1", "iPhone5,2":                  return Devices.IPhone5
        case "iPhone5,3", "iPhone5,4":                  return Devices.IPhone5C
        case "iPhone6,1", "iPhone6,2":                  return Devices.IPhone5S
        case "iPhone7,2":                               return Devices.IPhone6
        case "iPhone7,1":                               return Devices.IPhone6Plus
        case "iPhone8,1":                               return Devices.IPhone6S
        case "iPhone8,2":                               return Devices.IPhone6SPlus
        case "iPhone9,1", "iPhone9,3":                  return Devices.IPhone7
        case "iPhone9,2", "iPhone9,4":                  return Devices.IPhone7Plus
        case "iPhone8,4":                               return Devices.IPhoneSE
        case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return Devices.IPad2
        case "iPad3,1", "iPad3,2", "iPad3,3":           return Devices.IPad3
        case "iPad3,4", "iPad3,5", "iPad3,6":           return Devices.IPad4
        case "iPad4,1", "iPad4,2", "iPad4,3":           return Devices.IPadAir
        case "iPad5,3", "iPad5,4":                      return Devices.IPadAir2
        case "iPad2,5", "iPad2,6", "iPad2,7":           return Devices.IPadMini
        case "iPad4,4", "iPad4,5", "iPad4,6":           return Devices.IPadMini2
        case "iPad4,7", "iPad4,8", "iPad4,9":           return Devices.IPadMini3
        case "iPad5,1", "iPad5,2":                      return Devices.IPadMini4
        case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return Devices.IPadPro
        case "AppleTV5,3":                              return Devices.AppleTV
        case "i386", "x86_64":                          return Devices.Simulator
        default:                                        return Devices.Other
        }
    }

}

How to check if NSString begins with a certain character

Another approach to do it..

May it help someone...

if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}

What's the console.log() of java?

The Log class:

API for sending log output.

Generally, use the Log.v() Log.d() Log.i() Log.w() and Log.e() methods.

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

Outside of Android, System.out.println(String msg) is used.

How to remove element from ArrayList by checking its value?

Snippet to remove a element from any arraylist based on the matching condition is as follows:

List<String> nameList = new ArrayList<>();
        nameList.add("Arafath");
        nameList.add("Anjani");
        nameList.add("Rakesh");

Iterator<String> myItr = nameList.iterator();

    while (myItr.hasNext()) {
        String name = myItr.next();
        System.out.println("Next name is: " + name);
        if (name.equalsIgnoreCase("rakesh")) {
            myItr.remove();
        }
    }

Show Hide div if, if statement is true

<?php
$divStyle=''; // show div

// add condition
if($variable == '1'){
  $divStyle='style="display:none;"'; //hide div
}

print'<div '.$divStyle.'>Div to hide</div>';
?>

How can I remove a trailing newline?

Note that rstrip doesn't act exactly like Perl's chomp() because it doesn't modify the string. That is, in Perl:

$x="a\n";

chomp $x

results in $x being "a".

but in Python:

x="a\n"

x.rstrip()

will mean that the value of x is still "a\n". Even x=x.rstrip() doesn't always give the same result, as it strips all whitespace from the end of the string, not just one newline at most.

Opposite of append in jquery

just had the same problem and ive come across this - which actually does the trick for me:

// $("#the_div").contents().remove();
// or short: 
$("#the_div").empty();
$("#the_div").append("HTML goes in here...");

Bootstrap 4 responsive tables won't take up 100% width

Taking in consideration the other answers I would do something like this, thanks!

.table-responsive {
    @include media-breakpoint-up(md) {
        display: table;
    }
}

Should I use Python 32bit or Python 64bit

In my experience, using the 32-bit version is more trouble-free. Unless you are working on applications that make heavy use of memory (mostly scientific computing, that uses more than 2GB memory), you're better off with 32-bit versions because:

  1. You generally use less memory.
  2. You have less problems using COM (since you are on Windows).
  3. If you have to load DLLs, they most probably are also 32-bit. Python 64-bit can't load 32-bit libraries without some heavy hacks running another Python, this time in 32-bit, and using IPC.
  4. If you have to load DLLs that you compile yourself, you'll have to compile them to 64-bit, which is usually harder to do (specially if using MinGW on Windows).
  5. If you ever use PyInstaller or py2exe, those tools will generate executables with the same bitness of your Python interpreter.

Validate that end date is greater than start date with jQuery

Little late to the party but here is my part

Date.parse(fromDate) > Date.parse(toDate)

Here is the detail:

var from = $("#from").val();
var to = $("#to").val();

if(Date.parse(from) > Date.parse(to)){
   alert("Invalid Date Range");
}
else{
   alert("Valid date Range");
}