Programs & Examples On #Stringio

Retrieving the output of subprocess.call()

I recently just figured out how to do this, and here's some example code from a current project of mine:

#Getting the random picture.
#First find all pictures:
import shlex, subprocess
cmd = 'find ../Pictures/ -regex ".*\(JPG\|NEF\|jpg\)" '
#cmd = raw_input("shell:")
args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
#Another way to get output
#output = subprocess.Popen(args,stdout = subprocess.PIPE).stdout
ber = raw_input("search complete, display results?")
print output
#... and on to the selection process ...

You now have the output of the command stored in the variable "output". "stdout = subprocess.PIPE" tells the class to create a file object named 'stdout' from within Popen. The communicate() method, from what I can tell, just acts as a convenient way to return a tuple of the output and the errors from the process you've run. Also, the process is run when instantiating Popen.

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

How to render html with AngularJS templates

In angular 4+ we can use innerHTML property instead of ng-bind-html.

In my case, it's working and I am using angular 5.

<div class="chart-body" [innerHTML]="htmlContent"></div>

In.ts file

let htmlContent = 'This is the `<b>Bold</b>` text.';

How do I test axios in Jest?

I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';

describe('Chatbot', () => {
    it('returns data when sendMessage is called', done => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

        chatbot.sendMessage(0, 'any').then(response => {
            expect(response).toEqual(data);
            done();
        });
    });
});

You can see it the whole example here:

Service: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js

Test: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js

How do I install Python 3 on an AWS EC2 instance?

On Debian derivatives such as Ubuntu, use apt. Check the apt repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo apt-get install python3

On Red Hat and derivatives, use yum. Check the yum repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo yum install python36

On SUSE and derivatives, use zypper. Check the repository for the versions of Python available to you. Then. run a command similar to the following, substituting the correct package name:

sudo zypper install python3

Jquery UI tooltip does not support html content

As long as we're using jQuery (> v1.8), we can parse the incoming string with $.parseHTML().

$('.tooltip').tooltip({
    content: function () {
        var tooltipContent = $('<div />').html( $.parseHTML( $(this).attr('title') ) );
        return tooltipContent;
    },
}); 

We'll parse the incoming string's attribute for unpleasant things, then convert it back to jQuery-readable HTML. The beauty of this is that by the time it hits the parser the strings are already concatenates, so it doesn't matter if someone is trying to split the script tag into separate strings. If you're stuck using jQuery's tooltips, this appears to be a solid solution.

Getting a count of objects in a queryset in django

Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:

Item.objects.values("contest").annotate(Count("id"))

I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.

How do you upload a file to a document library in sharepoint?

As an alternative to the webservices, you can use the put document call from the FrontPage RPC API. This has the additional benefit of enabling you to provide meta-data (columns) in the same request as the file data. The obvious drawback is that the protocol is a bit more obscure (compared to the very well documented webservices).

For a reference application that explains the use of Frontpage RPC, see the SharePad project on CodePlex.

Plotting a list of (x, y) coordinates in python matplotlib

If you want to plot a single line connecting all the points in the list

plt.plot(li[:])

plt.show()

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.

How can I select checkboxes using the Selenium Java WebDriver?

Selecting a checkbox is similar to clicking a button.

driver.findElement(By.id("idOfTheElement")).click();

will do.

However, you can also see whether the checkbox is already checked. The following snippet checks whether the checkbox is selected or not. If it is not selected, then it selects.

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
     driver.findElement(By.id("idOfTheElement")).click();
}

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

This Error mainly came when the SQL Service is stopped.You need to Restart the service.To go to this window you have to search the Services like this- enter image description here

Then Search for SQLSERVER(MSSQLSERVER) and Restart the service.

enter image description here

Hope this will work.

Make <body> fill entire screen?

I had to apply 100% to both html and body.

MySQL Select Date Equal to Today

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE DATE(signup_date) = CURDATE()

How to print current date on python3?

The following seems to work:

import datetime
print (datetime.datetime.now().strftime("%y"))

The datetime.data object that it wants is on the "left" of the dot rather than the right. You need an instance of the datetime to call the method on, which you get through now()

What’s the best way to check if a file exists in C++? (cross platform)

Another possibility consists in using the good() function in the stream:

#include <fstream>     
bool checkExistence(const char* filename)
{
     ifstream Infield(filename);
     return Infield.good();
}

How to call two methods on button's onclick method in HTML or JavaScript?

  1. Try this:

    <input type="button" onclick="function1();function2();" value="Call2Functions" />
    
  2. Or, call second function at the end of first function:

       function func1(){
         //--- some logic
         func2();
       }
    
       function func2(){
        //--- some logic
       }
    

    ...and call func1() onclick of button:

    <input type="button" onclick="func1();" value="Call2Functions" />
    

EOFException - how to handle?

While reading from the file, your are not terminating your loop. So its read all the values and correctly throws EOFException on the next iteration of the read at line below:

 price = in.readDouble();

If you read the documentation, it says:

Throws:

EOFException - if this input stream reaches the end before reading eight bytes.

IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.

Put a proper termination condition in your while loop to resolve the issue e.g. below:

     while(in.available() > 0)  <--- if there are still bytes to read

How to escape braces (curly brackets) in a format string in .NET

Almost there! The escape sequence for a brace is {{ or }} so for your example you would use:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

Understanding dict.copy() - shallow or deep?

"new" and "original" are different dicts, that's why you can update just one of them.. The items are shallow-copied, not the dict itself.

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

UPDATE:
Starting from CLI v6 you can just run ng update in order to get your dependencies updated automatically to a new version.

With ng update sometimes you might want to add --force flag. If you do so make sure that the version of typescript you got installed this way is supported by your current angular version, otherwise you might need to downgrade the typescript version.

Also checkout this guide Updating your Angular projects


For bash users only

If you are on are on Mac/Linux or running bash on Windows(that wont work in default Windows CMD) you can run that oneliner:

npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router,compiler-cli}@4.4.5 --save

yarn add @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router,compiler-cli}@4.4.5

Just specify version you wan't e.g @4.4.5 or put @latest to get the latest

Check your package.json just to make sure you are updating all @angular/* packages that you app is relying on

  • To see exact @angular version in your project run:
    npm ls @angular/compiler or yarn list @angular/compiler
  • To check the latest stable @angular version available on npm run:
    npm show @angular/compiler version

How do I get the YouTube video ID from a URL?

Late to the game here, but I've mashed up two excellent responses from mantish and j-w. First, the modified regex:

const youtube_regex = /^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/

Here's the test code (I've added mantish's original test cases to j-w's nastier ones):

 var urls = [
      'http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
      'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o',
      'http://www.youtube.com/v/0zM3nApSvMg?fs=1&amp;hl=en_US&amp;rel=0',
      'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
      'http://www.youtube.com/embed/0zM3nApSvMg?rel=0',
      'http://www.youtube.com/watch?v=0zM3nApSvMg',
      'http://youtu.be/0zM3nApSvMg',
      '//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
      'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
      'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
      'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
      'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
      'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
      'http://youtu.be/6dwqZw0j_jY',
      'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
      'http://youtu.be/afa-5HQHiAs',
      'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
      'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
      'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
      'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
      'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
      'http://www.youtube.com/watch?v=peFZbP64dsU',
      'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
      'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
      'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
  ];

  var failures = 0;
  urls.forEach(url => {
    const parsed = url.match(youtube_regex);
    if (parsed && parsed[2]) {
      console.log(parsed[2]);
    } else {
      failures++;
      console.error(url, parsed);
    }
  });
  if (failures) {
    console.error(failures, 'failed');
  }

Experimental version to handle the m.youtube urls mentioned in comments:

const youtube_regex = /^.*((m\.)?youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/

It requires parsed[2] to be changed to parsed[3] in two places in the tests (which it then passes with m.youtube urls added to the tests). Let me know if you see problems.

Query for documents where array size is greater than 1

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

you can use $gt and $lt in query.

Split a large pandas dataframe

I also experienced np.array_split not working with Pandas DataFrame my solution was to only split the index of the DataFrame and then introduce a new column with the "group" label:

indexes = np.array_split(df.index,N, axis=0)
for i,index in enumerate(indexes):
   df.loc[index,'group'] = i

This makes grouby operations very convenient for instance calculation of mean value of each group:

df.groupby(by='group').mean()

Replace Line Breaks in a String C#

If you want to replace only the newlines:

var input = @"sdfhlu \r\n sdkuidfs\r\ndfgdgfd";
var match = @"[\\ ]+";
var replaceWith = " ";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input.Replace(@"\n", replaceWith).Replace(@"\r", replaceWith), match, replaceWith);
Console.WriteLine("output: " + x);

If you want to replace newlines, tabs and white spaces:

var input = @"sdfhlusdkuidfs\r\ndfgdgfd";
var match = @"[\\s]+";
var replaceWith = "";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input, match, replaceWith);
Console.WriteLine("output: " + x);

Fragment MyFragment not attached to Activity

The problem with your code is the way the you are using the AsyncTask, because when you rotate the screen during your sleep thread:

Thread.sleep(2000) 

the AsyncTask is still working, it is because you didn't cancel the AsyncTask instance properly in onDestroy() before the fragment rebuilds (when you rotate) and when this same AsyncTask instance (after rotate) runs onPostExecute(), this tries to find the resources with getResources() with the old fragment instance(an invalid instance):

getResources().getString(R.string.app_name)

which is equivalent to:

MyFragment.this.getResources().getString(R.string.app_name)

So the final solution is manage the AsyncTask instance (to cancel if this is still working) before the fragment rebuilds when you rotate the screen, and if canceled during the transition, restart the AsyncTask after reconstruction by the aid of a boolean flag:

public class MyFragment extends SherlockFragment {

    private MyAsyncTask myAsyncTask = null;
    private boolean myAsyncTaskIsRunning = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState!=null) {
            myAsyncTaskIsRunning = savedInstanceState.getBoolean("myAsyncTaskIsRunning");
        }
        if(myAsyncTaskIsRunning) {
            myAsyncTask = new MyAsyncTask();
            myAsyncTask.execute();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("myAsyncTaskIsRunning",myAsyncTaskIsRunning);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(myAsyncTask!=null) myAsyncTask.cancel(true);
        myAsyncTask = null;

    }

    public class MyAsyncTask extends AsyncTask<Void, Void, Void>() {

        public MyAsyncTask(){}

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            myAsyncTaskIsRunning = true;
        }
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {}
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            getResources().getString(R.string.app_name);
            myAsyncTaskIsRunning = false;
            myAsyncTask = null;
        }

    }
}

Android Studio - Failed to apply plugin [id 'com.android.application']

Feb 25th 2021:

For me, after over 8 hours of trials and errors, it was the re-ordering of the repositories sources in the project-level build.gradle file that solved the issue for me. So, instead of:

buildscript {
  ...
  repositories {
        google()
        mavenCentral()
        maven { url "https://plugins.gradle.org/m2/" }
  }
  ...
}

I moved google() to the bottom:

buildscript {
  ...
  repositories {
        mavenCentral()
        maven { url "https://plugins.gradle.org/m2/" }
        google()
  }
  ...
}

Of course, be sure to update the gradle android plugin and the matching gradle-wrapper distribution versions too.

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Creating folders inside a GitHub repository without using Git

You can also just enter the website and:

  1. Choose a repository you have write access to (example URL)
  2. Click "Upload files"
  3. Drag and drop a folder with files into the "Drag files here to add them to your repository" area.

The same limitation applies here: the folder must contain at least one file inside it.

Char array declaration and initialization in C

This is another C example of where the same syntax has different meanings (in different places). While one might be able to argue that the syntax should be different for these two cases, it is what it is. The idea is that not that it is "not allowed" but that the second thing means something different (it means "pointer assignment").

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Mac OS X doesn't have apt-get. There is a package manager called Homebrew that is used instead.

This command would be:

brew install python

Use Homebrew to install packages that you would otherwise use apt-get for.

The page I linked to has an up-to-date way of installing homebrew, but at present, you can install Homebrew as follows:

Type the following in your Mac OS X terminal:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

After that, usage of Homebrew is brew install <package>.

One of the prerequisites for Homebrew are the XCode command line tools.

  1. Install XCode from the App Store.
  2. Follow the directions in this Stack Overflow answer to install the XCode Command Line Tools.

Background

A package manager (like apt-get or brew) just gives your system an easy and automated way to install packages or libraries. Different systems use different programs. apt and its derivatives are used on Debian based linux systems. Red Hat-ish Linux systems use rpm (or at least they did many, many, years ago). yum is also a package manager for RedHat based systems.

Alpine based systems use apk.

Warning

As of 25 April 2016, homebrew opts the user in to sending analytics by default. This can be opted out of in two ways:

Setting an environment variable:

  1. Open your favorite environment variable editor.
  2. Set the following: HOMEBREW_NO_ANALYTICS=1 in whereever you keep your environment variables (typically something like ~/.bash_profile)
  3. Close the file, and either restart the terminal or source ~/.bash_profile.

Running the following command:

brew analytics off

the analytics status can then be checked with the command:

brew analytics

jQuery UI: Datepicker set year range dropdown to 100 years

I wanted to implement the datepicker to select the birthdate and I had troubles changing the yearRange as it doesn't seemed to work with my version (1.5). I updated to the newest jquery-ui datepicker version here: https://github.com/uxsolutions/bootstrap-datepicker.

Then I found out they provide this very helpful on-the-fly tool, so you can config your whole datepicker and see what settings you have to use.

That's how I found out that the option

defaultViewDate

is the option I was looking for and I didn't find any results searching the web.

So for other users: If you also want to provide the datepicker to change the birthdate, I suggest to use this code options:

$('#birthdate').datepicker({
    startView: 2,
    maxViewMode: 2,
    daysOfWeekHighlighted: "1,2",
    defaultViewDate: { year: new Date().getFullYear()-20, month: 01, day: 01 }
});

When opening the datepicker you will start with the view to select the years, 20 years ago relative to the current year.

How to change credentials for SVN repository in Eclipse?

In windows :

  1. Open run type %APPDATA%\Subversion\auth\svn.simple
  2. This will open svn.simple folder
  3. you will find a file e.g. Big Alpha Numeric file
  4. Delete that file.
  5. Restart eclipse.
  6. Try to edit file from project and commit it
  7. you can see dialog asking userName password

It worked for me.... ;)

Twitter Bootstrap 3, vertically center content

You can use display:inline-block instead of float and vertical-align:middle with this CSS:

.col-lg-4, .col-lg-8 {
    float:none;
    display:inline-block;
    vertical-align:middle;
    margin-right:-4px;
}

The demo http://bootply.com/94402

append multiple values for one key in a dictionary

Here is an alternative way of doing this using the not in operator:

# define an empty dict
years_dict = dict()

for line in list:
    # here define what key is, for example,
    key = line[0]
    # check if key is already present in dict
    if key not in years_dict:
        years_dict[key] = []
    # append some value 
    years_dict[key].append(some.value)

How to Alter a table for Identity Specification is identity SQL Server

You can't alter the existing columns for identity.

You have 2 options,

Create a new table with identity & drop the existing table

Create a new column with identity & drop the existing column

Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.

CREATE TABLE dbo.Tmp_Names
    (
      Id int NOT NULL
             IDENTITY(1, 1),
      Name varchar(50) NULL
    )
ON  [PRIMARY]
go

SET IDENTITY_INSERT dbo.Tmp_Names ON
go

IF EXISTS ( SELECT  *
            FROM    dbo.Names ) 
    INSERT  INTO dbo.Tmp_Names ( Id, Name )
            SELECT  Id,
                    Name
            FROM    dbo.Names TABLOCKX
go

SET IDENTITY_INSERT dbo.Tmp_Names OFF
go

DROP TABLE dbo.Names
go

Exec sp_rename 'Tmp_Names', 'Names'

Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.

Alter Table Names
Add Id_new Int Identity(1, 1)
Go

Alter Table Names Drop Column ID
Go

Exec sp_rename 'Names.Id_new', 'ID', 'Column'

See the following Microsoft SQL Server Forum post for more details:

http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/04d69ee6-d4f5-4f8f-a115-d89f7bcbc032

Why does ++[[]][+[]]+[+[]] return the string "10"?

  1. Unary plus given string converts to number
  2. Increment operator given string converts and increments by 1
  3. [] == ''. Empty String
  4. +'' or +[] evaluates 0.

    ++[[]][+[]]+[+[]] = 10 
    ++[''][0] + [0] : First part is gives zeroth element of the array which is empty string 
    1+0 
    10
    

Concatenate String in String Objective-c

Yes, do

NSString *str = [NSString stringWithFormat: @"first part %@ second part", varyingString];

For concatenation you can use stringByAppendingString

NSString *str = @"hello ";
str = [str stringByAppendingString:@"world"]; //str is now "hello world"

For multiple strings

NSString *varyingString1 = @"hello";
NSString *varyingString2 = @"world";
NSString *str = [NSString stringWithFormat: @"%@ %@", varyingString1, varyingString2];
//str is now "hello world"

Multi-threading in VBA

I was looking for something similar and the official answer is no. However, I was able to find an interesting concept by Daniel at ExcelHero.com.

Basically, you need to create worker vbscripts to execute the various things you want and have it report back to excel. For what I am doing, retrieving HTML data from various website, it works great!

Take a look:

http://www.excelhero.com/blog/2010/05/multi-threaded-vba.html

How to pass credentials to the Send-MailMessage command for sending emails

PSH> $cred = Get-Credential

PSH> $cred | Export-CliXml c:\temp\cred.clixml

PSH> $cred2 = Import-CliXml c:\temp\cred.clixml

That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.

How to retrieve unique count of a field using Kibana + Elastic Search

For Kibana 4 go to this answer

This is easy to do with a terms panel:

Adding a terms panel to Kibana

If you want to select the count of distinct IP that are in your logs, you should specify in the field clientip, you should put a big enough number in length (otherwise, it will join different IP under the same group) and specify in the style table. After adding the panel, you will have a table with IP, and the count of that IP:

Table with IP and count

How to run python script in webpage

As others have pointed out, there are many web frameworks for Python.

But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:

  1. Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.

  2. Add these 2 lines in the beginning of the file:

#!/usr/bin/python   
print('Content-type: text/html\r\n\r')

After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.

Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.

Ajax Upload image

first in your ajax call include success & error function and then check if it gives you error or what?

your code should be like this

$(document).ready(function (e) {
    $('#imageUploadForm').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

    $("#ImageBrowse").on("change", function() {
        $("#imageUploadForm").submit();
    });
});

DataGridView - Focus a specific cell

in event form_load (object sender, EventArgs e) try this

dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count1].Cells[0];

this code make focus on last row and 1st cell

ImageMagick security policy 'PDF' blocking conversion

Well, I added

  <policy domain="coder" rights="read | write" pattern="PDF" />

just before </policymap> in /etc/ImageMagick-7/policy.xml and that makes it work again, but not sure about the security implications of that.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

adding this worked for me.

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

/bin/sh: pushd: not found

Your shell (/bin/sh) is trying to find 'pushd'. But it can't find it because 'pushd','popd' and other commands like that are build in bash.

Launch you script using Bash (/bin/bash) instead of Sh like you are doing now, and it will work

What are the differences between normal and slim package of jquery?

I found a difference when creating a Form Contact: slim (recommended by boostrap 4.5):

  • After sending an email the global variables get stuck, and that makes if the user gives f5 (reload page) it is sent again. min:
  • The previous error will be solved. how i suffered!

How to remove provisioning profiles from Xcode

Provisioning profiles are stored under settings > accounts. Just press the "View details..." for the developer account you want and the provisioning profiles will be listed there.

Testing javascript with Mocha - how can I use console.log to debug a test?

Use the debug lib.

import debug from 'debug'
const log = debug('server');

Use it:

log('holi')

then run:

DEBUG=server npm test

And that's it!

Check if enum exists in Java

Most of the answers suggest either using a loop with equals to check if the enum exists or using try/catch with enum.valueOf(). I wanted to know which method is faster and tried it. I am not very good at benchmarking, so please correct me if I made any mistakes.

Heres the code of my main class:

    package enumtest;

public class TestMain {

    static long timeCatch, timeIterate;
    static String checkFor;
    static int corrects;

    public static void main(String[] args) {
        timeCatch = 0;
        timeIterate = 0;
        TestingEnum[] enumVals = TestingEnum.values();
        String[] testingStrings = new String[enumVals.length * 5];
        for (int j = 0; j < 10000; j++) {
            for (int i = 0; i < testingStrings.length; i++) {
                if (i % 5 == 0) {
                    testingStrings[i] = enumVals[i / 5].toString();
                } else {
                    testingStrings[i] = "DOES_NOT_EXIST" + i;
                }
            }

            for (String s : testingStrings) {
                checkFor = s;
                if (tryCatch()) {
                    ++corrects;
                }
                if (iterate()) {
                    ++corrects;
                }
            }
        }

        System.out.println(timeCatch / 1000 + "us for try catch");
        System.out.println(timeIterate / 1000 + "us for iterate");
        System.out.println(corrects);
    }

    static boolean tryCatch() {
        long timeStart, timeEnd;
        timeStart = System.nanoTime();
        try {
            TestingEnum.valueOf(checkFor);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        } finally {
            timeEnd = System.nanoTime();
            timeCatch += timeEnd - timeStart;
        }

    }

    static boolean iterate() {
        long timeStart, timeEnd;
        timeStart = System.nanoTime();
        TestingEnum[] values = TestingEnum.values();
        for (TestingEnum v : values) {
            if (v.toString().equals(checkFor)) {
                timeEnd = System.nanoTime();
                timeIterate += timeEnd - timeStart;
                return true;
            }
        }
        timeEnd = System.nanoTime();
        timeIterate += timeEnd - timeStart;
        return false;
    }
}

This means, each methods run 50000 times the lenght of the enum I ran this test multiple times, with 10, 20, 50 and 100 enum constants. Here are the results:

  • 10: try/catch: 760ms | iteration: 62ms
  • 20: try/catch: 1671ms | iteration: 177ms
  • 50: try/catch: 3113ms | iteration: 488ms
  • 100: try/catch: 6834ms | iteration: 1760ms

These results were not exact. When executing it again, there is up to 10% difference in the results, but they are enough to show, that the try/catch method is far less efficient, especially with small enums.

How to change Windows 10 interface language on Single Language version

Worked for me:

  1. Download package (see links below), name it lp.cab and place it to your C: drive

  2. Run the following commands as Administrator:

2.1 installing new language

dism /Online /Add-Package /PackagePath:C:\lp.cab

2.2 get installed packages

dism /Online /Get-Packages

2.3 remove original package

dism /Online /Remove-Package /PackageName:Microsoft-Windows-Client-LanguagePack-Package~31bf3856ad364e35~amd64~ru-RU~10.0.10240.16384

If you don't know which is your original package you can check your installed packages with this line

dism /Online /Get-Packages | findstr /c:"LanguagePack"

  1. Enjoy your new system language

List of MUI for Windows 10:

For LPs for Windows 10 version 1607 build 14393, follow this link.

Windows 10 x64 (Build 10240):

zh-CN: Chinese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_9949b0581789e2fc205f0eb005606ad1df12745b.cab

hr-HR: Croatian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_c3bde55e2405874ec8eeaf6dc15a295c183b071f.cab

cs-CZ: Czech download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_d0b2a69faa33d1ea1edc0789fdbb581f5a35ce2d.cab

da-DK: Danish download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_15e50641cef50330959c89c2629de30ef8fd2ef6.cab

nl-NL: Dutch download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_8658b909525f49ab9f3ea9386a0914563ffc762d.cab

en-us: English download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_75d67444a5fc444dbef8ace5fed4cfa4fb3602f0.cab

fr-FR: French download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_206d29867210e84c4ea1ff4d2a2c3851b91b7274.cab

de-DE: German download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_3bb20dd5abc8df218b4146db73f21da05678cf44.cab

hi-IN: Hindi download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_e9deaa6a8d8f9dfab3cb90986d320ff24ab7431f.cab

it-IT: Italian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_42c622dc6957875eab4be9d57f25e20e297227d1.cab

ja-JP: Japanese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_adc2ec900dd1c5e94fc0dbd8e010f9baabae665f.cab

kk-KZ: Kazakh download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_a03ed475983edadd3eb73069c4873966c6b65daf.cab

ko-KR: Korean download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_24411100afa82ede1521337a07485c65d1a14c1d.cab

pt-BR: Portuguese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_894199ed72fdf98e4564833f117380e45b31d19f.cab

ru-RU: Russian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_d85bb9f00b5ee0b1ea3256b6e05c9ec4029398f0.cab

es-ES: Spanish download.windowsupdate.com/c/msdownload/update/software/updt/2015/07/lp_7b21648a1df6476b39e02476c2319d21fb708c7d.cab

uk-UA: Ukrainian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_131991188afe0ef668d77c8a9a568cb71b57f09f.cab

Windows 10 x86 (Build 10240):

zh-CN: Chinese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_e7d13432345bcf589877cd3f0b0dad4479785f60.cab

hr-HR: Croatian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_60856d8b4d643835b30d8524f467d4d352395204.cab

cs-CZ: Czech download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_dfa71b93a76b4500578b67fd3bf6b9f10bf5beaa.cab

da-DK: Danish download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_af0ea4318f43d9cb30bcfa5ce7279647f10bc3b3.cab

nl-NL: Dutch download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_cbcdf4818eac2a15cfda81e37595f8ffeb037fd7.cab

en-us: English download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_41877260829bb5f57a52d3310e326c6828d8ce8f.cab

fr-FR: French download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_80fa697f051a3a949258797a0635a4313a448c29.cab

de-DE: German download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_7ea2648033099f99f87642e47e6d959172c6cab8.cab

hi-IN: Hindi download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_78a11997f4e4bf73bbdb1da8011ebfb218bd1bac.cab

it-IT: Italian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_9e62d9a8b141e0eb6434af5a44c4f9468b60a075.cab

ja-JP: Japanese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_79bd099ac811cb1771e6d9b03d640e5eca636b23.cab

kk-KZ: Kazakh download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_59e690df497799cacb96ab579a706250e5a0c8b6.cab

ko-KR: Korean download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_a88379b0461479ab8b5b47f65c4c3241ef048c04.cab

pt-BR: Portuguese download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_bb9f192068fe42fde8787591197a53c174dce880.cab

ru-RU: Russian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_280bf97bbe34cec1b0da620fa1b2dfe5bdb3ea07.cab

es-ES: Spanish download.windowsupdate.com/c/msdownload/update/software/updt/2015/07/lp_31400c38ffea2f0a44bb2dfbd80086aa3cad54a9.cab

uk-UA: Ukrainian download.windowsupdate.com/d/msdownload/update/software/updt/2015/07/lp_41cd48aa22d21f09fbcedc69197609c1f05f433d.cab

How to specify 64 bit integers in c

How to specify 64 bit integers in c

Going against the usual good idea to appending LL.

Appending LL to a integer constant will insure the type is at least as wide as long long. If the integer constant is octal or hex, the constant will become unsigned long long if needed.

If ones does not care to specify too wide a type, then LL is OK. else, read on.

long long may be wider than 64-bit.

Today, it is rare that long long is not 64-bit, yet C specifies long long to be at least 64-bit. So by using LL, in the future, code may be specifying, say, a 128-bit number.

C has Macros for integer constants which in the below case will be type int_least64_t

#include <stdint.h>
#include <inttypes.h>

int main(void) {
  int64_t big = INT64_C(9223372036854775807);
  printf("%" PRId64 "\n", big);
  uint64_t jenny = INT64_C(0x08675309) << 32;  // shift was done on at least 64-bit type 
  printf("0x%" PRIX64 "\n", jenny);
}

output

9223372036854775807
0x867530900000000

SQL Server : Transpose rows to columns

One way to do it if tagID values are known upfront is to use conditional aggregation

SELECT TimeSeconds,
       COALESCE(MAX(CASE WHEN TagID = 'A1' THEN Value END), 'n/a') A1,
       COALESCE(MAX(CASE WHEN TagID = 'A2' THEN Value END), 'n/a') A2,
       COALESCE(MAX(CASE WHEN TagID = 'A3' THEN Value END), 'n/a') A3,
       COALESCE(MAX(CASE WHEN TagID = 'A4' THEN Value END), 'n/a') A4
  FROM table1
 GROUP BY TimeSeconds

or if you're OK with NULL values instead of 'n/a'

SELECT TimeSeconds,
       MAX(CASE WHEN TagID = 'A1' THEN Value END) A1,
       MAX(CASE WHEN TagID = 'A2' THEN Value END) A2,
       MAX(CASE WHEN TagID = 'A3' THEN Value END) A3,
       MAX(CASE WHEN TagID = 'A4' THEN Value END) A4
  FROM table1
 GROUP BY TimeSeconds

or with PIVOT

SELECT TimeSeconds, A1, A2, A3, A4
  FROM
(
  SELECT TimeSeconds, TagID, Value
    FROM table1
) s
PIVOT
(
  MAX(Value) FOR TagID IN (A1, A2, A3, A4)
) p

Output (with NULLs):

TimeSeconds A1      A2     A3    A4
----------- ------- ------ ----- -----
1378700244  3.75    NULL   NULL  NULL
1378700245  30.00   NULL   NULL  NULL
1378700304  1.20    NULL   NULL  NULL
1378700305  NULL    56.00  NULL  NULL
1378700344  NULL    11.00  NULL  NULL
1378700345  NULL    NULL   0.53  NULL
1378700364  4.00    NULL   NULL  NULL
1378700365  14.50   NULL   NULL  NULL
1378700384  144.00  NULL   NULL  10.00

If you have to figure TagID values out dynamically then use dynamic SQL

DECLARE @cols NVARCHAR(MAX), @sql NVARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(TagID)
            FROM Table1
            ORDER BY 1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')

SET @sql = 'SELECT TimeSeconds, ' + @cols + '
              FROM
            (
              SELECT TimeSeconds, TagID, Value
                FROM table1
            ) s
            PIVOT
            (
              MAX(Value) FOR TagID IN (' + @cols + ')
            ) p'

EXECUTE(@sql)

PHP - If variable is not empty, echo some html code

Simply use if ($web). This is true if the variable has any truthy value.

You don't need isset or empty since you know the variable exists, since you have just set it in the previous line.

What is the standard way to add N seconds to datetime.time in Python?

Try adding a datetime.datetime to a datetime.timedelta. If you only want the time portion, you can call the time() method on the resultant datetime.datetime object to get it.

How to get current instance name from T-SQL

Just found the answer, in this SO question (literally, inside the question, not any answer):

SELECT @@servername

returns servername\instance as far as this is not the default instance

SELECT @@servicename

returns instance name, even if this is the default (MSSQLSERVER)

How to use youtube-dl from a python program?

It's not difficult and actually documented:

import youtube_dl

ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})

with ydl:
    result = ydl.extract_info(
        'http://www.youtube.com/watch?v=BaW_jenozKc',
        download=False # We just want to extract the info
    )

if 'entries' in result:
    # Can be a playlist or a list of videos
    video = result['entries'][0]
else:
    # Just a video
    video = result

print(video)
video_url = video['url']
print(video_url)

Format XML string to print friendly XML string

You will have to parse the content somehow ... I find using LINQ the most easy way to do it. Again, it all depends on your exact scenario. Here's a working example using LINQ to format an input XML string.

string FormatXml(string xml)
{
     try
     {
         XDocument doc = XDocument.Parse(xml);
         return doc.ToString();
     }
     catch (Exception)
     {
         // Handle and throw if fatal exception here; don't just ignore them
         return xml;
     }
 }

[using statements are ommitted for brevity]

How to start anonymous thread class

Add: now you can use lambda to simplify your syntax. Requirement: Java 8+

public class A {
    public static void main(String[] arg)
    {
        Thread th = new Thread(() -> {System.out.println("blah");});
        th.start();
    }
}

Resource interpreted as Document but transferred with MIME type application/zip

This issue was re-appeared at Chrome 61 version. But it seems it is fixed at Chrome 62.

I have a RewriteRule like below

RewriteRule ^/ShowGuide/?$ https://<website>/help.pdf [L,NC,R,QSA]

With Chrome 61, the PDF was not opening, in console it was showing the message

"Resource interpreted as Document but transferred with MIME type application/pdf: "

We tried to add mime type in the rewrite rule as below but it didn't help.

RewriteRule ^/ShowGuide/?$ https://<website>/help.pdf [L,NC,R,QSA, t:application/pdf]

I have updated my Chrome to latest 62 version and it started to showing the PDF again. But the message is still there in the console.

With all other browsers, it was/is working fine.

Open fancybox from function

The answers seems a bit over complicated. I hope I didn't misunderstand the question.

If you simply want to open a fancy box from a click to an "A" tag. Just set your html to

<a id="my_fancybox" href="#contentdiv">click me</a>

The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:

$('#my_fancybox').fancybox({
    'autoScale': true,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 500,
    'speedOut': 300,
    'autoDimensions': true,
    'centerOnScroll': true,
});

This will show a fancybox containing "contentdiv" when your anchor tag is clicked.

Difference between Select Unique and Select Distinct

Only In Oracle =>

SELECT DISTINCT and SELECT UNIQUE behave the same way. While DISTINCT is ANSI SQL standard, UNIQUE is an Oracle specific statement.

In other databases (like sql-server in your case) =>

SELECT UNIQUE is invalid syntax. UNIQUE is keyword for adding unique constraint on the column.

SELECT DISTINCT

Converting two lists into a matrix

Assuming lengths of portfolio and index are the same:

matrix = []
for i in range(len(portfolio)):
    matrix.append([portfolio[i], index[i]])

Or a one-liner using list comprehension:

matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]

How do I mock an autowired @Value field in Spring with Mockito?

I'd like to suggest a related solution, which is to pass the @Value-annotated fields as parameters to the constructor, instead of using the ReflectionTestUtils class.

Instead of this:

public class Foo {

    @Value("${foo}")
    private String foo;
}

and

public class FooTest {

    @InjectMocks
    private Foo foo;

    @Before
    public void setUp() {
        ReflectionTestUtils.setField(Foo.class, "foo", "foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Do this:

public class Foo {

    private String foo;

    public Foo(@Value("${foo}") String foo) {
        this.foo = foo;
    }
}

and

public class FooTest {

    private Foo foo;

    @Before
    public void setUp() {
        foo = new Foo("foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Benefits of this approach: 1) we can instantiate the Foo class without a dependency container (it's just a constructor), and 2) we're not coupling our test to our implementation details (reflection ties us to the field name using a string, which could cause a problem if we change the field name).

Creating a thumbnail from an uploaded image

function getExtension($str) 
    {

          $i = strrpos($str,".");
         if (!$i) { return ""; } 

         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
    }

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
    {
        $name = $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];

        if(strlen($name))
            {
                 $ext = getExtension($name);
                if(in_array($ext,$valid_formats))
                {
                if($size<(1024*1024))
                    {
                        $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                        $tmp = $_FILES['photoimg']['tmp_name'];
                        if(move_uploaded_file($tmp, $path.$actual_image_name))
                            {


                            mysql_query("INSERT INTO users (uid, profile_image) VALUES ('$session_id' , '$actual_image_name')");

                                echo "<img src='uploads/".$actual_image_name."'  class='preview'>";
                            }
                        else
                            echo "Fail upload folder with read access.";
                    }
                    else
                    echo "Image file size max 1 MB";                    
                    }
                    else
                    echo "Invalid file format..";   
            }

        else
            echo "Please select image..!";

        exit;
    }

Remove element of a regular array

If you don't want to use List:

var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();

You could try this extension method that I haven't actually tested:

public static T[] RemoveAt<T>(this T[] source, int index)
{
    T[] dest = new T[source.Length - 1];
    if( index > 0 )
        Array.Copy(source, 0, dest, 0, index);

    if( index < source.Length - 1 )
        Array.Copy(source, index + 1, dest, index, source.Length - index - 1);

    return dest;
}

And use it like:

Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);

What is the meaning of "this" in Java?

To be complete, this can also be used to refer to the outer object

class Outer {
    class Inner {
        void foo() {
            Outer o = Outer.this;
    }
  }
}

Bind failed: Address already in use

As mentioned above the port is in use already. This could be due to several reasons

  1. some other application is already using it.
  2. The port is in close_wait state when your program is waiting for the other end to close the program.refer (https://unix.stackexchange.com/questions/10106/orphaned-connections-in-close-wait-state).
  3. The program might be in time_wait state. you can wait or use socket option SO_REUSEADDR as mentioned in another post.

Do netstat -a | grep <portno> to check the port state.

How to find out whether a file is at its `eof`?

Although I would personally use a with statement to handle opening and closing a file, in the case where you have to read from stdin and need to track an EOF exception, do something like this:

Use a try-catch with EOFError as the exception:

try:
    input_lines = ''
    for line in sys.stdin.readlines():
        input_lines += line             
except EOFError as e:
    print e

How to build x86 and/or x64 on Windows from command line with CMAKE?

This cannot be done with CMake. You have to generate two separate build folders. One for the x86 NMake build and one for the x64 NMake build. You cannot generate a single Visual Studio project covering both architectures with CMake, either.

To build Visual Studio projects from the command line for both 32-bit and 64-bit without starting a Visual Studio command prompt, use the regular Visual Studio generators.

For CMake 3.13 or newer, run the following commands:

cmake -G "Visual Studio 16 2019" -A Win32 -S \path_to_source\ -B "build32"
cmake -G "Visual Studio 16 2019" -A x64 -S \path_to_source\ -B "build64"
cmake --build build32 --config Release
cmake --build build64 --config Release

For earlier versions of CMake, run the following commands:

mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" \path_to_source\
popd
mkdir build64 & pushd build64
cmake -G "Visual Studio 15 2017 Win64" \path_to_source\
popd
cmake --build build32 --config Release
cmake --build build64 --config Release

CMake generated projects that use one of the Visual Studio generators can be built from the command line with using the option --build followed by the build directory. The --config option specifies the build configuration.

AngularJS open modal on button click

I am not sure,how you are opening popup or say model in your code. But you can try something like this..

<html ng-app="MyApp">
<head>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" />

<script type="text/javascript">
    var myApp = angular.module("MyApp", []);
    myApp.controller('MyController', function ($scope) {
      $scope.open = function(){
        var modalInstance = $modal.open({
                        templateUrl: '/assets/yourOpupTemplatename.html',
                        backdrop:'static',
                        keyboard:false,
                        controller: function($scope, $modalInstance) {
                            $scope.cancel = function() {
                                $modalInstance.dismiss('cancel');
                            };
                            $scope.ok = function () {
                              $modalInstance.close();
                            };
                        }
                    });
      }
    });
</script>
</head>
<body ng-controller="MyController">

    <button class="btn btn-primary" ng-click="open()">Test Modal</button>

    <!-- Confirmation Dialog -->
    <div class="modal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="modal-title">Delete confirmation</h4>
          </div>
          <div class="modal-body">
            <p>Are you sure?</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" ng-click="cancel()">No</button>
            <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
          </div>
        </div>
      </div>
    </div>
    <!-- End of Confirmation Dialog -->

 </body>
 </html>

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I had to add an older jdk on my project.

Right button on Project folder > Properties > Java Build Path > Libraries > Add Library > JRE System Library

enter image description here

enter image description here

In case you don't have the package for jdk8, download the jdk that some user mentioned above (http://download.oracle.com/otn-pub/java/jdk/8u172-b11/a58eab1ec242421181065cdc37240b08/jdk-8u172-windows-x64.exe) and click on "Installed JREs" and search for the directory you downloaded the jdk8.

enter image description here

Then click on Finish.

Remove the apache server and add again.

The magic is done ;)

Define css class in django Forms

Expanding on the method pointed to at docs.djangoproject.com:

class MyForm(forms.Form): 
    comment = forms.CharField(
            widget=forms.TextInput(attrs={'size':'40'}))

I thought it was troublesome to have to know the native widget type for every field, and thought it funny to override the default just to put a class name on a form field. This seems to work for me:

class MyForm(forms.Form): 
    #This instantiates the field w/ the default widget
    comment = forms.CharField()

    #We only override the part we care about
    comment.widget.attrs['size'] = '40'

This seems a little cleaner to me.

Remove Object from Array using JavaScript

Here is an example with map and splice

_x000D_
_x000D_
const arrayObject = [
  { name: "name1", value: "value1" },
  { name: "name2", value: "value2" },
  { name: "name3", value: "value3" },
];

let index = arrayObject.map((item) => item.name).indexOf("name1");
if (index > -1) {
  
  arrayObject.splice(index, 1);
  console.log("Result", arrayObject);
  

}
_x000D_
_x000D_
_x000D_

Eclipse : Maven search dependencies doesn't work

I have the same problem. None of the options suggested above worked for me. However I find, that if I lets say manually add groupid/artifact/version for org.springframework.spring-core version 4.3.4.RELEASE and save the pom.xml, the dependencies download automatically and the search works for the jars already present in the repository. However if I now search for org.springframework.spring-context , which isnt in the current dependencies, this search still doesn't work.

run main class of Maven project

Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec

Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec, as I have ~/bin in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...

Launch it from the root of your project, where you can see src and target dirs.

The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)

$ mvnexec 
 1) org.jmeld.ui.JMeldComponent
 2) org.jmeld.ui.text.FileDocument
 3) org.jmeld.JMeld
 4) org.jmeld.util.UIDefaultsPrint
 5) org.jmeld.util.PrintProperties
 6) org.jmeld.util.file.DirectoryDiff
 7) org.jmeld.util.file.VersionControlDiff
 8) org.jmeld.vc.svn.InfoCmd
 9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#? 

If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P)

By default it compiles project every run. but you can avoid that using mvnexec -B

It allows to search only in test classes -M or --no-main, or only in main classes -T or --no-test. also has a filter by name option -f <whatever>

Hope this could save you some time, for me it does.

How to calculate UILabel height dynamically?

if you want the label to take dynamic lines you may use this

label.numberOfLines = 0; // allows label to have as many lines as needed
label.text = @"some long text ";
[label sizeToFit];
NSLog(@"Label's frame is: %@", NSStringFromCGRect(label.frame));

Displaying a Table in Django from Database

The easiest way is to use a for loop template tag.

Given the view:

def MyView(request):
    ...
    query_results = YourModel.objects.all()
    ...
    #return a response to your template and add query_results to the context

You can add a snippet like this your template...

<table>
    <tr>
        <th>Field 1</th>
        ...
        <th>Field N</th>
    </tr>
    {% for item in query_results %}
    <tr> 
        <td>{{ item.field1 }}</td>
        ...
        <td>{{ item.fieldN }}</td>
    </tr>
    {% endfor %}
</table>

This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.

Lambda function in list comprehensions

The other answers are correct, but if you are trying to make a list of functions, each with a different parameter, that can be executed later, the following code will do that:

import functools
a = [functools.partial(lambda x: x*x, x) for x in range(10)]

b = []
for i in a:
    b.append(i())

In [26]: b
Out[26]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

While the example is contrived, I found it useful when I wanted a list of functions that each print something different, i.e.

import functools
a = [functools.partial(lambda x: print(x), x) for x in range(10)]

for i in a:
    i()

Shared-memory objects in multiprocessing

If you use an operating system that uses copy-on-write fork() semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).

The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy or array), place that in shared memory, wrap it with multiprocessing.Array, and pass that to your functions. This answer shows how to do that.

If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).

The Manager approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.

There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.

How do I PHP-unserialize a jQuery-serialized form?

In HTML page:

<script>
function insert_tag()
{
    $.ajax({
        url: "aaa.php",
        type: "POST",
        data: {
            ssd: "yes",
            data: $("#form_insert").serialize()
        },
        dataType: "JSON",
        success: function (jsonStr) {
            $("#result1").html(jsonStr['back_message']);
        }
    });
}
</script>

<form id="form_insert">
    <input type="text" name="f1" value="a"/>
    <input type="text" name="f2" value="b"/>
    <input type="text" name="f3" value="c"/>
    <input type="text" name="f4" value="d"/>
    <div onclick="insert_tag();"><b>OK</b></div>
    <div id="result1">...</div>
</form>

on PHP page:

<?php
if(isset($_POST['data']))
{
    parse_str($_POST['data'], $searcharray);
    $data = array(
        "back_message"   => $searcharray['f1']
    );
    echo json_encode($data);
}
?>

on this php code, return f1 field.

Add JsonArray to JsonObject

here is simple code

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
        array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
    obj.put("result", array);
} catch (JSONException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());

uncaught syntaxerror unexpected token U JSON

That error is normally seen when the value given to JSON.parse is actually undefined. So, I would check the code that is trying to parse this - most likely you are not parsing the actual string shown here.

Convert UTC datetime string to local datetime

See the datetime documentation on tzinfo objects. You have to implement the timezones you want to support yourself. The are examples at the bottom of the documentation.

Here's a simple example:

from datetime import datetime,tzinfo,timedelta

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst
        self.name = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
            return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):
         return self.name

GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')

print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z')

t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print t
print t.astimezone(EST)

Output

01/22/2011 21:52:09 
01/22/2011 21:52:09 GMT
01/22/2011 16:52:09 EST
2011-01-21 02:37:21+00:00
2011-01-20 21:37:21-05:00a

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

The best solution ¹for a mathematician is to use Python.

C++ operator overloading has little to do with it. You can't overload operators for built-in types. What you want is simply a function. Of course you can use C++ templating to implement that function for all relevant types with just 1 piece of code.

The standard C library provides fmod, if I recall the name correctly, for floating point types.

For integers you can define a C++ function template that always returns non-negative remainder (corresponding to Euclidian division) as ...

#include <stdlib.h>  // abs

template< class Integer >
auto mod( Integer a, Integer b )
    -> Integer
{
    Integer const r = a%b;
    return (r < 0? r + abs( b ) : r);
}

... and just write mod(a, b) instead of a%b.

Here the type Integer needs to be a signed integer type.

If you want the common math behavior where the sign of the remainder is the same as the sign of the divisor, then you can do e.g.

template< class Integer >
auto floor_div( Integer const a, Integer const b )
    -> Integer
{
    bool const a_is_negative = (a < 0);
    bool const b_is_negative = (b < 0);
    bool const change_sign  = (a_is_negative != b_is_negative);

    Integer const abs_b         = abs( b );
    Integer const abs_a_plus    = abs( a ) + (change_sign? abs_b - 1 : 0);

    Integer const quot = abs_a_plus / abs_b;
    return (change_sign? -quot : quot);
}

template< class Integer >
auto floor_mod( Integer const a, Integer const b )
    -> Integer
{ return a - b*floor_div( a, b ); }

… with the same constraint on Integer, that it's a signed type.


¹ Because Python's integer division rounds towards negative infinity.

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

Find kth smallest element in a binary search tree in Optimum way

Solution for complete BST case :-

Node kSmallest(Node root, int k) {
  int i = root.size(); // 2^height - 1, single node is height = 1;
  Node result = root;
  while (i - 1 > k) {
    i = (i-1)/2;  // size of left subtree
    if (k < i) {
      result = result.left;
    } else {
      result = result.right;
      k -= i;
    }  
  }
  return i-1==k ? result: null;
}

Can I use wget to check , but not download

If you want to check quietly via $? without the hassle of grep'ing wget's output you can use:

wget -q "http://blah.meh.com/my/path" -O /dev/null

Works even on URLs with just a path but has the disadvantage that something's really downloaded so this is not recommended when checking big files for existence.

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

build.gradle (Project)

buildScript {
    ...
    dependencies {
        ...
        classpath 'com.android.tools.build:gradle:4.0.0-rc01'
    }
} 

gradle/wrapper/gradle-wrapper.properties

...
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip

Some libraries require the updated gradle. Such as:

androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines"

GL

Python 3.4.0 with MySQL database

I solved it this way: download the zipped package from here and follow this set of instructions:

unzip  /path/to/downloads/folder/mysql-connector-python-VER.zip  

In case u got a .gz u can use ->

tar xzf mysql-connector-python-VER.tar.gz 

And then:

cd mysql-connector-python-VER  # move into the directory

sudo python3 setup.py install # NOTICE I USED PYTHON3 INSTEAD OF PYTHON

You can read about it here

Bootstrap dropdown sub menu missing

I bumped with this issue a few days ago. I tried many solutions and none really worked for me on the end i ended up creating an extenion/override of the dropdown code of bootstrap. It is a copy of the original code with changes to the closeMenus function.

I think it is a good solution since it doesn't affects the core classes of bootstrap js.

You can check it out on gihub: https://github.com/djokodonev/bootstrap-multilevel-dropdown

Adding CSRFToken to Ajax request

I had this problem in a list of post in a blog, the post are in a view inside a foreach, then is difficult select it in javascript, and the problem of post method and token also exists.

This the code for javascript at the end of the view, I generate the token in javascript functión inside the view and not in a external js file, then is easy use php lavarel to generate it with csrf_token() function, and send the "delete" method directly in params. You can see that I don´t use in var route: {{ route('post.destroy', $post->id}} because I don´t know the id I want delete until someone click in destroy button, if you don´t have this problem you can use {{ route('post.destroy', $post->id}} or other like this.

  $(function(){
    $(".destroy").on("click", function(){
         var vid = $(this).attr("id");
         var v_token = "{{csrf_token()}}";
         var params = {_method: 'DELETE', _token: v_token};
         var route = "http://imagica.app/posts/" + vid + "";
    $.ajax({
         type: "POST",
         url: route,
         data: params
    });
   });
  });

and this the code of content in view (inside foreach there are more forms and the data of each post but is not inportant by this example), you can see I add a class "delete" to button and I call class in javascript.

      @foreach($posts as $post)
          <form method="POST">
            <button id="{{$post->id}}" class="btn btn-danger btn-sm pull-right destroy" type="button" >eliminar</button>
          </form>
      @endforeach

Shell Script Syntax Error: Unexpected End of File

It can also be caused by piping out of a pair of curly braces on a line.

This fails:

{ /usr/local/bin/mycommand ; outputstatus=$? } >> /var/log/mycommand.log 2>&1h
do_something
#Get NOW that saved output status for the following $? invocation
sh -c "exit $outputstatus"
do_something_more

while this is allowed:

{
   /usr/local/bin/mycommand
   outputstatus=$?
} >> /var/log/mycommand.log 2>&1h
do_something
#Get NOW that saved output status for the following $? invocation
sh -c "exit $outputstatus"
do_something_more

How to use OR condition in a JavaScript IF statement?

One can use regular expressions, too:

_x000D_
_x000D_
var thingToTest = "B";_x000D_
if (/A|B/.test(thingToTest)) alert("Do something!")
_x000D_
_x000D_
_x000D_

Here's an example of regular expressions in general:

_x000D_
_x000D_
var myString = "This is my search subject"_x000D_
if (/my/.test(myString)) alert("Do something here!")
_x000D_
_x000D_
_x000D_

This will look for "my" within the variable "myString". You can substitute a string directly in place of the "myString" variable.

As an added bonus you can add the case insensitive "i" and the global "g" to the search as well.

_x000D_
_x000D_
var myString = "This is my search subject"_x000D_
if (/my/ig.test(myString)) alert("Do something here");
_x000D_
_x000D_
_x000D_

How can I disable HREF if onclick is executed?

    yes_js_login = function() {
         // Your code here
         return false;
    }

If you return false it should prevent the default action (going to the href).

Edit: Sorry that doesn't seem to work, you can do the following instead:

<a href="http://example.com/no-js-login" onclick="yes_js_login(); return false;">Link</a>

Align div right in Bootstrap 3

Add offset8 to your class, for example:

<div class="offset8">aligns to the right</div>

Add space between <li> elements

#access a {
    border-bottom: 2px solid #fff;
    color: #eee;
    display: block;
    line-height: 3.333em;
    padding: 0 10px 0 20px;
    text-decoration: none;
}

I see that you had used line-height but you gave it to <a> tag instead of <ul> Try this:

#access ul {line-height:3.333em;}

You wouldn't need to play with margins then.

Get Absolute Position of element within the window in wpf

To get the absolute position of an UI element within the window you can use:

Point position = desiredElement.PointToScreen(new Point(0d, 0d));

If you are within an User Control, and simply want relative position of the UI element within that control, simply use:

Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));

position.X -= controlPosition.X;
position.Y -= controlPosition.Y;

Sort JavaScript object by key

Sorts keys recursively while preserving references.

function sortKeys(o){
    if(o && o.constructor === Array)
        o.forEach(i=>sortKeys(i));
    else if(o && o.constructor === Object)
        Object.entries(o).sort((a,b)=>a[0]>b[0]?1:-1).forEach(e=>{
            sortKeys(e[1]);
            delete o[e[0]];
            o[e[0]] = e[1];
        });
}

Example:

let x = {d:3, c:{g:20, a:[3,2,{s:200, a:100}]}, a:1};
let y = x.c;
let z = x.c.a[2];
sortKeys(x);
console.log(x); // {a: 1, c: {a: [3, 2, {a: 1, s: 2}], g: 2}, d: 3}
console.log(y); // {a: [3, 2, {a: 100, s: 200}}, g: 20}
console.log(z); // {a: 100, s: 200}

Installation of SQL Server Business Intelligence Development Studio

It sounds like you have installed SQL Server 2005 Express Edition, which does not include SSIS or the Business Intelligence Development Studio.

BIDS is only provided with the (not free) Standard, Enterprise and Developer Editions.

EDIT

This information was correct for SQL Server 2005. Since SQL Server 2014, Developer Edition has been free. BIDS has been replaced by SQL Server Data Tools, a free plugin for Visual Studio (including the free Visual Studio Community Edition).

Can the Unix list command 'ls' output numerical chmod permissions?

You can use the following command

stat -c "%a %n" *

Also you can use any filename or directoryname instead of * to get a specific result.

On Mac, you can use

stat -f '%A %N' *

VS 2017 Metadata file '.dll could not be found

In my case, I had to open the .csproj file and add the reference by hand, like this (Microsoft.Extensions.Identity.Stores.dll was missing):

<Reference Include="Microsoft.Extensions.Identity.Stores">
  <HintPath>..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.extensions.identity.stores\2.0.1\lib\netstandard2.0\Microsoft.Extensions.Identity.Stores.dll</HintPath>
</Reference>

How to find elements with 'value=x'?

Use the following selector.

$('#attached_docs [value=123]').remove();

Reading an Excel file in python using pandas

I think this should satisfy your need:

import pandas as pd

# Read the excel sheet to pandas dataframe
df = pd.read_excel("PATH\FileName.xlsx", sheetname=0)

How to sort a file in-place

Do you want to sort all files in a folder and subfolder overriding them?

Use this:

find . -type f -exec sort {} -o {} \;

Is there a naming convention for MySQL?

Simple Answer: NO

Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html

About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.

By personal experience, I would recommed this:

  • Use lower case. This almost ensures interoperability when you migrate your databases from one server to another. Sometimes the lower_case_table_names is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).
  • Short names. Simple and clear. The most easy and fast is identify your table or columns, the better. Trust me, when you make a lot of different queries in a short amount of time is better having all simple to write (and read).
  • Avoid prefixes. Unless you are using the same database for tables of different applications, don't use prefixes. This only add more verbosity to your queries. There are situations when this could be useful, for example, when you want to indentify primary keys and foreign keys, that usually table names are used as prefix for id columns.
  • Use underscores for separating words. If you still want to use more than one word for naming a table, column, etc., so use underscores for separating_the_words, this helps for legibility (your eyes and your stressed brain are going to thank you).
  • Be consistent. Once you have your own standard, follow it. Don´t be the person that create the rules and is the first who breaking them, that is shameful.

And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.

Node.js: socket.io close client connection

I'm trying to close users connection in version 1.0 and found this method:

socket.conn.close()

The difference between this method and disconnect() is that the client will keep trying to reconnect to the server.

Testing the type of a DOM element in JavaScript

I have another way of testing the same.

_x000D_
_x000D_
Element.prototype.typeof = "element";_x000D_
var element = document.body; // any dom element_x000D_
if (element && element.typeof == "element"){_x000D_
   return true; _x000D_
   // this is a dom element_x000D_
}_x000D_
else{_x000D_
  return false; _x000D_
  // this isn't a dom element_x000D_
}
_x000D_
_x000D_
_x000D_

What is correct media query for IPad Pro?

/* Landscape*/

@media only screen and (min-device-width: 1366px) and (max-device-height: 1024px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: landscape)  {}

/* Portrait*/
@media only screen and (min-device-width: 1024px) and (max-device-height: 1366px) and (-webkit-min-device-pixel-ratio: 2)  and (orientation: portrait)  {}

Portrait medias query for iPad Pro should be fine as it is.

Landscape media query for iPad Pro (min-device-width) should be 1366px and (max device-height) should be 1024px.

Hope this helps.

Create a jTDS connection string

SQLServer runs the default instance over port 1433. If you specify the port as port 1433, SQLServer will only look for the default instance. The name of the default instance was created at setup and usually is SQLEXPRESSxxx_xx_ENU.

The instance name also matches the folder name created in Program Files -> Microsoft SQL Server. So if you look there and see one folder named SQLEXPRESSxxx_xx_ENU it is the default instance.

Folders named MSSQL12.myInstanceName (for SQLServer 2012) are named instances in SQL Server and are not accessed via port 1433.

So if your program is accessing a default instance in the database, specify port 1433, and you may not need to specify the instance name.

If your program is accessing a named instance (not the default instance) in the database DO NOT specify the port but you must specify the instance name.

I hope this clarifies some of the confusion emanating from the errors above.

How to concatenate string variables in Bash

The simplest way with quotation marks:

B=Bar
b=bar
var="$B""$b""a"
echo "Hello ""$var"

Measuring execution time of a function in C++

#include <iostream>
#include <chrono>

void function()
{
    // code here;
}

int main()
{
    auto t1 = std::chrono::high_resolution_clock::now();
    function();
    auto t2 = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << duration<<"/n";
    return 0;
}

This Worked for me.


Note:

The high_resolution_clock is not implemented consistently across different standard library implementations, and its use should be avoided. It is often just an alias for std::chrono::steady_clock or std::chrono::system_clock, but which one it is depends on the library or configuration. When it is a system_clock, it is not monotonic (e.g., the time can go backwards).

For example, for gcc's libstdc++ it is system_clock, for MSVC it is steady_clock, and for clang's libc++ it depends on configuration.

Generally one should just use std::chrono::steady_clock or std::chrono::system_clock directly instead of std::chrono::high_resolution_clock: use steady_clock for duration measurements, and system_clock for wall-clock time.

How do you stylize a font in Swift?

Xamarin

Label.Font = UIFont.FromName("Copperplate", 10.0f);

Swift

text.font = UIFont.init(name: "Poppins-Regular", size: 14)

To get the list of font family Github/IOS-UIFont-Names

Batchfile to create backup and rename with timestamp

try this:

ren "File 1-1" "File 1 - %date:/=-% %time::=-%"

How do I make a JSON object with multiple arrays?

A good book I'm reading: Professional JavaScript for Web Developers by Nicholas C. Zakas 3rd Edition has the following information regarding JSON Syntax:

"JSON Syntax allows the representation of three types of values".

Regarding the one you're interested in, Arrays it says:

"Arrays are represented in JSON using array literal notation from JavaScript. For example, this is an array in JavaScript:

var values = [25, "hi", true];

You can represent this same array in JSON using a similar syntax:

[25, "hi", true]

Note the absence of a variable or a semicolon. Arrays and objects can be used together to represent more complex collections of data, such as:

{
    "books":
              [
                {
                    "title": "Professional JavaScript",
                    "authors": [
                        "Nicholas C. Zakas"
                    ],
                    "edition": 3,
                    "year": 2011
                },
                {
                    "title": "Professional JavaScript",
                    "authors": [
                        "Nicholas C.Zakas"
                    ],
                    "edition": 2,
                    "year": 2009
                },
                {
                    "title": "Professional Ajax",
                    "authors": [
                        "Nicholas C. Zakas",
                        "Jeremy McPeak",
                        "Joe Fawcett"
                    ],
                    "edition": 2,
                    "year": 2008
                }
              ]
}

This Array contains a number of objects representing books, Each object has several keys, one of which is "authors", which is another array. Objects and arrays are typically top-level parts of a JSON data structure (even though this is not required) and can be used to create a large number of data structures."

To serialize (convert) a JavaScript object into a JSON string you can use the JSON object stringify() method. For the example from Mark Linus answer:

var cars = [{
    color: 'gray',
    model: '1',
    nOfDoors: 4
    },
    {
    color: 'yellow',
    model: '2',
    nOfDoors: 4
}];

cars is now a JavaScript object. To convert it into a JSON object you could do:

var jsonCars = JSON.stringify(cars);

Which yields:

"[{"color":"gray","model":"1","nOfDoors":4},{"color":"yellow","model":"2","nOfDoors":4}]"

To do the opposite, convert a JSON object into a JavaScript object (this is called parsing), you would use the parse() method. Search for those terms if you need more information... or get the book, it has many examples.

Specify a Root Path of your HTML directory for script links?

Use two periods before /, example:

../style.css

ipad safari: disable scrolling, and bounce effect?

improved answer @Ben Bos and commented by @Tim

This css will help prevent scrolling and performance issue with css re-render because position changed / little lagging without width and height

body,
html {
  position: fixed;
  width: 100%; 
  height: 100%
}

How to upload files to server using JSP/Servlet?

Sending multiple file for file we have to use enctype="multipart/form-data"
and to send multiple file use multiple="multiple" in input tag

<form action="upload" method="post" enctype="multipart/form-data">
 <input type="file" name="fileattachments"  multiple="multiple"/>
 <input type="submit" />
</form>

Eclipse hangs on loading workbench

I solved deleting *.snap from the workspace dir (and all subdirectories):

metadata\.plugins\*.snap

Convert float to double without losing precision

A simple solution that works well, is to parse the double from the string representation of the float:

double val = Double.valueOf(String.valueOf(yourFloat));

Not super efficient, but it works!

How to select a div element in the code-behind page?

If you want to find the control from code behind you have to use runat="server" attribute on control. And then you can use Control.FindControl.

<div class="tab-pane active" id="portlet_tab1" runat="server">

Control myControl1 = FindControl("portlet_tab1");
if(myControl1!=null)
{
    //do stuff
}

If you use runat server and your control is inside the ContentPlaceHolder you have to know the ctrl name would not be portlet_tab1 anymore. It will render with the ctrl00 format.

Something like: #ctl00_ContentPlaceHolderMain_portlet_tab1. You will have to modify name if you use jquery.

You can also do it using jQuery on client side without using the runat-server attribute:

<script type='text/javascript'>

    $("#portlet_tab1").removeClass("Active");

</script>

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Ctrl + . shows the menu. I find this easier to type than the alternative, Alt + Shift + F10.

This can be re-bound to something more familiar by going to Tools > Options > Environment > Keyboard > Visual C# > View.QuickActions

Reading an integer from user input

Try this it will not throw exception and user can try again:

        Console.WriteLine("1. Add account.");
        Console.WriteLine("Enter choice: ");
        int choice = 0;
        while (!Int32.TryParse(Console.ReadLine(), out choice))
        {
            Console.WriteLine("Wrong input! Enter choice number again:");
        }

How to update MySql timestamp column to current timestamp on PHP?

Use this query:

UPDATE `table` SET date_date=now();

Sample code can be:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("UPDATE `table` SET date_date=now()");

mysql_close($con);
?>

Full Page <iframe>

Put this in your CSS.

iframe {
  width: 100%;
  height: 100vh;
}

AngularJS - Any way for $http.post to send request parameters instead of JSON?

Syntax for AngularJS v1.4.8 + (v1.5.0)

       $http.post(url, data, config)
            .then(
                    function (response) {
                        // success callback
                    },
                    function (response) {
                        // failure callback
                    }
            );

Eg:

    var url = "http://example.com";

    var data = {
        "param1": "value1",
        "param2": "value2",
        "param3": "value3"
    };

    var config = {
        headers: {
            'Content-Type': "application/json"
        }
    };

    $http.post(url, data, config)
            .then(
                    function (response) {
                        // success callback
                    },
                    function (response) {
                        // failure callback
                    }
            );

Filter by Dates in SQL

WHERE dates BETWEEN (convert(datetime, '2012-12-12',110) AND (convert(datetime, '2012-12-12',110))

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

You can't multiply string and float.instead of you try as below.it works fine

totalAmount = salesAmount * float(salesTax)

Loop in Jade (currently known as "Pug") template engine

You could also speed things up with a while loop (see here: http://jsperf.com/javascript-while-vs-for-loops). Also much more terse and legible IMHO:

i = 10
while(i--)
    //- iterate here
    div= i

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Tks Ramon Gil Moreno. Pasting in Terminal and then restarting R Studio did the trick:
write org.rstudio.RStudio force.LANG en_US.UTF-8

Environment: MAC OS High Sierra 10.13.1 // RStudio version 3.4.2 (2017-09-28) -- "Short Summer"

Ennio De Leon

MySQL stored procedure vs function, which would I use when?

Stored procedure can be called recursively but stored function can not

spark submit add multiple jars in classpath

I was trying to connect to mysql from the python code that was executed using spark-submit.

I was using HDP sandbox that was using Ambari. Tried lot of options such as --jars, --driver-class-path, etc, but none worked.

Solution

Copy the jar in /usr/local/miniconda/lib/python2.7/site-packages/pyspark/jars/

As of now I'm not sure if it's a solution or a quick hack, but since I'm working on POC so it kind of works for me.

Select Specific Columns from Spark DataFrame

Let's say our parent Dataframe has 'n' columns

we can create 'x' child DataFrames( Lets consider 2 in our case).

The columns for the child Dataframe can be chosen as per desire from any of the parent Dataframe columns.

Consider source has 10 columns and we want to split into 2 DataFrames that contains columns referenced from the parent Dataframe.

The columns for the child Dataframe can be decided using the select Dataframe API

val parentDF = spark.read.format("csv").load("/path of the CSV file")

val Child1_DF = parentDF.select("col1","col2","col3","col9","col10").show()

val child2_DF = parentDF.select("col5", "col6","col7","col8","col1","col2").show()

Notice that the column count in the child dataframes can differ in length and will be less than the parent dataframe column count.

we can also refer to the column names without mentioning the real names using the positional indexes of the desired column from the parent dataframe

Import spark implicits first which acts as a helper class for usage of $-notation to access the columns using the positional indexes

import spark.implicits._
import org.apache.spark.sql.functions._

val child3_DF  = parentDF.select("_c0","_c1","_c2","_c8","_c9").show()

we can also select column basing on certain conditions. Lets say we want only even numbered columns to be selected in the child dataframe. By even we refer to even indexed columns and index being starting from '0'

val parentColumns = parentDF.columns.toList


res0: List[String] = List(_c0, _c1, _c2, _c3, _c4, _c5, _c6, _c7,_c8,_c9)

val evenParentColumns =  res0.zipWithIndex.filter(_._2 % 2 == 0).map( _._1).toSeq

res1: scala.collection.immutable.Seq[String] = List(_c0, _c2, _c4, _c6,_c8)

Now feed these columns to be selected from the parentDF.Note that the select API need seq type arguments.So we converted the "evenParentColumns" to Seq collection

val child4_DF = parentDF.select(res1.head, res1.tail:_*).show()

This will show the even indexed columns from the parent Dataframe.


| _c0 | _c2 | _c4 |_c6 |_c8 |


|ITE00100554|TMAX|null| E| 1 |

|TE00100554 |TMIN|null| E| 4 |

|GM000010962|PRCP|null| E| 7 |

So Now we are left with the even numbered columns in the dataframe

Similarly we can also apply other operations to the Dataframe column like shown below

val child5_DF = parentDF.select($"_c0", $"_c8" + 1).show()

So by many ways as mentioned we can select the columns in the Dataframe.

Java 8 stream reverse order

In all this I don't see the answer I would go to first.

This isn't exactly a direct answer to the question, but it's a potential solution to the problem.

Just build the list backwards in the first place. If you can, use a LinkedList instead of an ArrayList and when you add items use "Push" instead of add. The list will be built in the reverse order and will then stream correctly without any manipulation.

This won't fit cases where you are dealing with primitive arrays or lists that are already used in various ways but does work well in a surprising number of cases.

Preventing twitter bootstrap carousel from auto sliding on page load

  • Use data-interval="false" to stop automatic slide
  • Use data-wrap="false" to stop circular slide

If Cell Starts with Text String... Formula

I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.

I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"s","l","m"}, {-1,1,0})

and it started working when I did this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"l","m","s"}, {1,0,-1})

I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.

Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.

#1071 - Specified key was too long; max key length is 767 bytes

When you hit the limit. Set the following.

  • INNODB utf8 VARCHAR(255)
  • INNODB utf8mb4 VARCHAR(191)

How to connect android wifi to adhoc wifi?

I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)

However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:

    public class MainActivity extends Activity {

private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
    final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
    final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
    final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
    final TextView textIp = (TextView) findViewById(R.id.Ip);

    final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.BSSID = CHIPKIT_BSSID;
    wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;

    myWifiManager.setWifiEnabled(true);

    int netID = myWifiManager.addNetwork(wifiConfiguration);

    myWifiManager.enableNetwork(netID, true);

    textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n' 
            + myWifiManager.getWifiState() + "\n\n");

    btnDoSomething.setOnClickListener(new View.OnClickListener() {          
        public void onClick(View v) {
            clearTextViews(textWifiManager, textIp);                
        }           
    });

    btnNewScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getNewScan(myWifiManager, textWifiManager, textIp);
        }
    });     
}

private void clearTextViews(TextView...tv) {
    for(int i = 0; i<tv.length; i++){
        tv[i].setText("");
    }       
}

public void getNewScan(WifiManager wm, TextView...textViews) {
    wm.startScan();

    List<ScanResult> scanResult = wm.getScanResults();

    String scan = "";

    for (int i = 0; i < scanResult.size(); i++) {
        scan += (scanResult.get(i).toString() + "\n\n");
    }

    textViews[0].setText(scan);
    textViews[1].setText(wm.toString());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...

and my manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

Hope that helps!

How to get a list column names and datatypes of a table in PostgreSQL?

To get information about the table's column, you can use:

\dt+ [tablename]

To get information about the datatype in the table, you can use:

\dT+ [datatype]

When do you use Java's @Override annotation and why?

Its best to use it for every method intended as an override, and Java 6+, every method intended as an implementation of an interface.

First, it catches misspellings like "hashcode()" instead of "hashCode()" at compile-time. It can be baffling to debug why the result of your method doesn't seem to match your code when the real cause is that your code is never invoked.

Also, if a superclass changes a method signature, overrides of the older signature can be "orphaned", left behind as confusing dead code. The @Override annotation will help you identify these orphans so that they can be modified to match the new signature.

Callback to a Fragment from a DialogFragment

You should define an interface in your fragment class and implement that interface in its parent activity. The details are outlined here http://developer.android.com/guide/components/fragments.html#EventCallbacks . The code would look similar to:

Fragment:

public static class FragmentA extends DialogFragment {

    OnArticleSelectedListener mListener;

    // Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
}

Activity:

public class MyActivity extends Activity implements OnArticleSelectedListener{

    ...
    @Override
    public void onArticleSelected(Uri articleUri){

    }
    ...
}

Can I force a page break in HTML printing?

Add a CSS class called "pagebreak" (or "pb"), like so:

@media print {
    .pagebreak { page-break-before: always; } /* page-break-after works, as well */
}

Then add an empty DIV tag (or any block element that generates a box) where you want the page break.

<div class="pagebreak"> </div>

It won't show up on the page, but will break up the page when printing.

P.S. Perhaps this only applies when using -after (and also what else you might be doing with other <div>s on the page), but I found that I had to augment the CSS class as follows:

@media print {
    .pagebreak {
        clear: both;
        page-break-after: always;
    }
}

JavaScript URL Decode function

Here is a complete function (taken from PHPJS):

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

How exactly does the python any() function work?

Simply saying, any() does this work : according to the condition even if it encounters one fulfilling value in the list, it returns true, else it returns false.

list = [2,-3,-4,5,6]

a = any(x>0 for x in lst)

print a:
True


list = [2,3,4,5,6,7]

a = any(x<0 for x in lst)

print a:
False

Send parameter to Bootstrap modal window?

I found the solution at: Passing data to a bootstrap modal

So simply use:

 $(e.relatedTarget).data('book-id'); 

with 'book-id' is a attribute of modal with pre-fix 'data-'

Correct format specifier to print pointer or address?

Use %p, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u expects an unsigned int, but what if void* has a different size or alignment requirement than unsigned int?)

*) [See Jonathan's fine answer!] Alternatively to %p, you can use pointer-specific macros from <inttypes.h>, added in C99.

All object pointers are implicitly convertible to void* in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):

printf("x lives at %p.\n", (void*)&x);

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

From the community documentation:

hibernate.hbm2ddl.auto Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

e.g. validate | update | create | create-drop

So the list of possible options are,

  • validate: validate the schema, makes no changes to the database.
  • update: update the schema.
  • create: creates the schema, destroying previous data.
  • create-drop: drop the schema when the SessionFactory is closed explicitly, typically when the application is stopped.
  • none: does nothing with the schema, makes no changes to the database

These options seem intended to be developers tools and not to facilitate any production level databases, you may want to have a look at the following question; Hibernate: hbm2ddl.auto=update in production?

How to change maven logging level to display only warning and errors?

you can achieve this by using below in the commandline itself

_x000D_
_x000D_
 -e for error_x000D_
-X for debug_x000D_
-q for only error
_x000D_
_x000D_
_x000D_

e.g :

_x000D_
_x000D_
mvn test -X -DsomeProperties='SomeValue' [For Debug level Logs]_x000D_
mvn test -e -DsomeProperties='SomeValue' [For Error level Logs]_x000D_
mvn test -q -DsomeProperties='SomeValue' [For Only Error Logs]
_x000D_
_x000D_
_x000D_

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

In your INSERT statements:

INSERT INTO employee(hans,germany) values(?,?)

You've got your values where your field names belong. Change it to be:

INSERT INTO employee(emp_name,emp_address) values(?,?)

If you were to run that statement from a SQL prompt, it would look like this:

INSERT INTO employee(emp_name,emp_address) values('hans','germany');

Note that you'd need to put single quotes around the string/varchar values.

Additionally, you are also not adding any parameters to your prepared statement. That is what's actually causing the error you're seeing. Try this:

PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.execute();

Also (according to Oracle), you can use "execute" for any SQL statement. Using "executeUpdate" would also be valid in this situation, which would return an integer to indicate the number of rows affected.

How do I run Visual Studio as an administrator by default?

image showing how to run visual studio as adminstrator by mhamri step 1 to 3

1- either from start menu or when visual studio is open in the task bar, right click on the VS icon

2- in the context menu, right click again on the visual studio icon

3- left click on prorperties

image showing how to run visual studio as adminstrator by mhamri step 4

4- choose advanced

image showing how to run visual studio as adminstrator by mhamri step 5

5- choose Run as Administrator

click ok all the windows, close the visual studio and reopen again.

How to convert image file data in a byte array to a Bitmap?

The answer of Uttam didnt work for me. I just got null when I do:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:

//Create bitmap with width, height, and 4 bytes color (RGBA)    
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options

What is 'PermSize' in Java?

A quick definition of the "permanent generation":

"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]

In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space if an application loads a large number of classes and/or on redeployment).

Note that PermSize is additional to the -Xmx value set by the user on the JVM options. But MaxPermSize allows for the JVM to be able to grow the PermSize to the amount specified. Initially when the VM is loaded, the MaxPermSize will still be the default value (32mb for -client and 64mb for -server) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize and MaxPermSize to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx setting.

JPA & Criteria API - Select only specific columns

One of the JPA ways for getting only particular columns is to ask for a Tuple object.

In your case you would need to write something like this:

CriteriaQuery<Tuple> cq = builder.createTupleQuery();
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<Tuple> tupleResult = em.createQuery(cq).getResultList();
for (Tuple t : tupleResult) {
    Long id = (Long) t.get(0);
    Long version = (Long) t.get(1);
}

Another approach is possible if you have a class representing the result, like T in your case. T doesn't need to be an Entity class. If T has a constructor like:

public T(Long id, Long version)

then you can use T directly in your CriteriaQuery constructor:

CriteriaQuery<T> cq = builder.createQuery(T.class);
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<T> result = em.createQuery(cq).getResultList();

See this link for further reference.

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

How can I verify a Google authentication API access token?

Here's an example using Guzzle:

/**
 * @param string $accessToken JSON-encoded access token as returned by \Google_Client->getAccessToken() or raw access token
 * @return array|false False if token is invalid or array in the form
 * 
 * array (
 *   'issued_to' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
 *   'audience' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
 *   'scope' => 'https://www.googleapis.com/auth/calendar',
 *   'expires_in' => 3350,
 *   'access_type' => 'offline',
 * )
 */
public static function tokenInfo($accessToken) {
    if(!strlen($accessToken)) {
        return false;
    }

    if($accessToken[0] === '{') {
        $accessToken = json_decode($accessToken)->access_token;
    }

    $guzzle = new \GuzzleHttp\Client();

    try {
        $resp = $guzzle->get('https://www.googleapis.com/oauth2/v1/tokeninfo', [
            'query' => ['access_token' => $accessToken],
        ]);
    } catch(ClientException $ex) {
        return false;
    }

    return $resp->json();
}

Efficient way to determine number of digits in an integer

See Bit Twiddling Hacks for a much shorter version of the answer you accepted. It also has the benefit of finding the answer sooner if your input is normally distributed, by checking the big constants first. (v >= 1000000000) catches 76% of the values, so checking that first will on average be faster.

What MIME type should I use for CSV?

You should use "text/csv" according to RFC 4180.

How to get the next auto-increment id in mysql

For me it works, and looks simple:

 $auto_inc_db = mysql_query("SELECT * FROM my_table_name  ORDER BY  id  ASC ");
 while($auto_inc_result = mysql_fetch_array($auto_inc_db))
 {
 $last_id = $auto_inc_result['id'];
 }
 $next_id = ($last_id+1);


 echo $next_id;//this is the new id, if auto increment is on

What is aria-label and how should I use it?

If you wants to know how aria-label helps you practically .. then follow the steps ... you will get it by your own ..

Create a html page having below code

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
</head>
<body>
    <button title="Close"> X </button>
    <br />
    <br />
    <br />
    <br />
    <button aria-label="Back to the page" title="Close" > X </button>
</body>
</html>

Now, you need a virtual screen reader emulator which will run on browser to observe the difference. So, chrome browser users can install chromevox extension and mozilla users can go with fangs screen reader addin

Once done with installation, put headphones in your ears, open the html page and make focus on both button(by pressing tab) one-by-one .. and you can hear .. focusing on first x button .. will tell you only x button .. but in case of second x button .. you will hear back to the page button only..

i hope you got it well now!!

jQuery Change event on an <input> element - any way to retain previous value?

Every DOM element has an attribute called defaultValue. You can use that to get the default value if you just want to compare the first changing of data.

How to bring an activity to foreground (top of stack)?

I think a combination of Intent flags should do the trick. In particular, Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK.

Add these flags to your intent before calling startActvity.

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

Class file for com.google.android.gms.internal.zzaja not found

If you use different version of play services libraries, you will get this error.

For example, below entries in build.gradle file cause the error as versions are different.

implementation 'com.google.android.gms:play-services-maps:11.4.2'
implementation 'com.google.android.gms:play-services-location:11.6.0'

To fix the issue use same versions.

implementation 'com.google.android.gms:play-services-maps:11.6.0'
implementation 'com.google.android.gms:play-services-location:11.6.0'

Multiple types were found that match the controller named 'Home'

Another solution is to register a default namespace with ControllerBuilder. Since we had lots of routes in our main application and only a single generic route in our areas (where we were already specifying a namespace), we found this to be the easiest solution:

ControllerBuilder.Current
     .DefaultNamespaces.Add("YourApp.Controllers");

How to Decrease Image Brightness in CSS

If you have a background-image, you can do this : Set a rgba() gradient on the background-image.

_x000D_
_x000D_
.img_container {_x000D_
  float: left;_x000D_
  width: 300px;_x000D_
  height: 300px;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  border : 1px solid #fff;_x000D_
}_x000D_
_x000D_
.image_original {_x000D_
  background: url(https://i.ibb.co/GkDXWYW/demo-img.jpg);_x000D_
}_x000D_
_x000D_
.image_brighness {_x000D_
  background: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), /* the gradient on top, adjust color and opacity to your taste */_x000D_
  url(https://i.ibb.co/GkDXWYW/demo-img.jpg);_x000D_
}_x000D_
_x000D_
.img_container p {_x000D_
  color: #fff;_x000D_
  font-size: 28px;_x000D_
}
_x000D_
<div class="img_container image_original">_x000D_
  <p>normal</p>_x000D_
</div>_x000D_
<div class="img_container image_brighness ">_x000D_
  <p>less brightness</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Receiving "Attempted import error:" in react app

i had the same issue, but I just typed export on top and erased the default one on the bottom. Scroll down and check the comments.

import React, { Component } from "react";

export class Counter extends Component { // type this  
export default Counter; // this is eliminated  

angularjs getting previous route path

This alternative also provides a back function.

The template:

<a ng-click='back()'>Back</a>

The module:

myModule.run(function ($rootScope, $location) {

    var history = [];

    $rootScope.$on('$routeChangeSuccess', function() {
        history.push($location.$$path);
    });

    $rootScope.back = function () {
        var prevUrl = history.length > 1 ? history.splice(-2)[0] : "/";
        $location.path(prevUrl);
    };

});

How can I convert byte size into a human-readable format in Java?

FileUtils.byteCountToDisplaySize(long size) would work if your project can depend on org.apache.commons.io.

JavaDoc for this method

string.split - by multiple character delimiter

More fast way using directly a no-string array but a string:

string[] StringSplit(string StringToSplit, string Delimitator)
{
    return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}

StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/

CSS opacity only to background color, not the text on it?

For Less users only:

If you don't like to set your colors using RGBA, but rather using HEX, there are solutions.

You could use a mixin like:

.transparentBackgroundColorMixin(@alpha,@color) {
  background-color: rgba(red(@color), green(@color), blue(@color), @alpha);
}

And use it like:

.myClass {
    .transparentBackgroundColorMixin(0.6,#FFFFFF);
}

Actually this is what a built-in Less function also provide:

.myClass {
    background-color: fade(#FFFFFF, 50%);
}

See How do I convert a hexadecimal color to rgba with the Less compiler?

How to run a program in Atom Editor?

You can go settings, select packages and type atom-runner there if your browser can't open this link.

To run your code do Alt+R if you're using Windows in Atom.

How can I share Jupyter notebooks with non-programmers?

Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.

Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing:

!ipython nbconvert <notebook name>.ipynb --to html

EDIT: With Jupyter/IPython's Big Split, you'll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html now.

Copy a file list as text from Windows Explorer

In Windows 7 and later, this will do the trick for you

  • Select the file/files.
  • Hold the shift key and then right-click on the selected file/files.
  • You will see Copy as Path. Click that.
  • Open a Notepad file and paste and you will be good to go.

The menu item Copy as Path is not available in Windows XP.

C++ callback using class member

Instead of having static methods and passing around a pointer to the class instance, you could use functionality in the new C++11 standard: std::function and std::bind:

#include <functional>
class EventHandler
{
    public:
        void addHandler(std::function<void(int)> callback)
        {
            cout << "Handler added..." << endl;
            // Let's pretend an event just occured
            callback(1);
        }
};

The addHandler method now accepts a std::function argument, and this "function object" have no return value and takes an integer as argument.

To bind it to a specific function, you use std::bind:

class MyClass
{
    public:
        MyClass();

        // Note: No longer marked `static`, and only takes the actual argument
        void Callback(int x);
    private:
        int private_x;
};

MyClass::MyClass()
{
    using namespace std::placeholders; // for `_1`

    private_x = 5;
    handler->addHandler(std::bind(&MyClass::Callback, this, _1));
}

void MyClass::Callback(int x)
{
    // No longer needs an explicit `instance` argument,
    // as `this` is set up properly
    cout << x + private_x << endl;
}

You need to use std::bind when adding the handler, as you explicitly needs to specify the otherwise implicit this pointer as an argument. If you have a free-standing function, you don't have to use std::bind:

void freeStandingCallback(int x)
{
    // ...
}

int main()
{
    // ...
    handler->addHandler(freeStandingCallback);
}

Having the event handler use std::function objects, also makes it possible to use the new C++11 lambda functions:

handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });

How to set up default schema name in JPA configuration?

I had to set the value in '' and ""

spring:
   jpa:
     properties:
       hibernate:
          default_schema: '"schema"'

Rename column SQL Server 2008

Run Query:

    SP_RENAME '[TableName].[ColumnName]','NewNameForColumn'

jquery json to string?

I use

$.param(jsonObj)

which gets me the string.

How to get last key in an array?

You can use this:

$array = array("one" => "apple", "two" => "orange", "three" => "pear");
end($array); 
echo key($array);

Another Solution is to create a function and use it:

function endKey($array){
end($array);
return key($array);
}

$array = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($array);

Wait .5 seconds before continuing code VB.net

The problem with Threading.Thread.SLeep(2000) is that it executes first in my VB.Net program. This

Imports VB = Microsoft.VisualBasic

Public Sub wait(ByVal seconds As Single)
    Static start As Single
    start = VB.Timer()
    Do While VB.Timer() < start + seconds
        System.Windows.Forms.Application.DoEvents()
    Loop
End Sub

worked flawlessly.

writing a batch file that opens a chrome URL

start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 2"

start "webpage name" "http://someurl.com/"

start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 3"

start "webpage name" "http://someurl.com/"

Android Studio does not show layout preview

I used the Debug "app" button enter image description here
and my problem was solved

Matplotlib different size subplots

Another way is to use the subplots function and pass the width ratio with gridspec_kw:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)

f.tight_layout()
f.savefig('grid_figure.pdf')

Hashing a string with Sha256

public static string ComputeSHA256Hash(string text)
{
    using (var sha256 = new SHA256Managed())
    {
        return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "");
    }                
}

The reason why you get different results is because you don't use the same string encoding. The link you put for the on-line web site that computes SHA256 uses UTF8 Encoding, while in your example you used Unicode Encoding. They are two different encodings, so you don't get the same result. With the example above you get the same SHA256 hash of the linked web site. You need to use the same encoding also in PHP.

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/

Windows Forms - Enter keypress activates submit button?

private void textBox_KeyDown(object sender, KeyEventArgs e) 
{
    if (e.KeyCode == Keys.Enter)
        button.PerformClick();
}

Is it possible to hide the cursor in a webpage using CSS or Javascript?

With CSS:

selector { cursor: none; }

An example:

_x000D_
_x000D_
<div class="nocursor">_x000D_
   Some stuff_x000D_
</div>_x000D_
<style type="text/css">_x000D_
    .nocursor { cursor:none; }_x000D_
</style>
_x000D_
_x000D_
_x000D_

To set this on an element in Javascript, you can use the style property:

<div id="nocursor"><!-- some stuff --></div>
<script type="text/javascript">
    document.getElementById('nocursor').style.cursor = 'none';
</script>

If you want to set this on the whole body:

<script type="text/javascript">
    document.body.style.cursor = 'none';
</script>

Make sure you really want to hide the cursor, though. It can really annoy people.

Exception: There is already an open DataReader associated with this Connection which must be closed first

You are trying to to an Insert (with ExecuteNonQuery()) on a SQL connection that is used by this reader already:

while (myReader.Read())

Either read all the values in a list first, close the reader and then do the insert, or use a new SQL connection.

Variable declaration in a header file

The key is to keep the declarations of the variable in the header file and source file the same.

I use this trick

------sample.c------
#define sample_c
#include sample.h

(rest of sample .c)

------sample.h------
#ifdef sample_c
#define EXTERN
#else
#define EXTERN extern
#endif

EXTERN int x;

Sample.c is only compiled once and it defines the variables. Any file that includes sample.h is only given the "extern" of the variable; it does allocate space for that variable.

When you change the type of x, it will change for everybody. You won't need to remember to change it in the source file and the header file.

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

how to reset <input type = "file">

In case you have the following:

<input type="file" id="fileControl">

then just do:

$("#fileControl").val('');

to reset the file control.

How should I log while using multiprocessing in Python?

There is this great package

Package: https://pypi.python.org/pypi/multiprocessing-logging/

code: https://github.com/jruere/multiprocessing-logging

Install:

pip install multiprocessing-logging

Then add:

import multiprocessing_logging

# This enables logs inside process
multiprocessing_logging.install_mp_handler()

How can you profile a Python script?

Ever want to know what the hell that python script is doing? Enter the Inspect Shell. Inspect Shell lets you print/alter globals and run functions without interrupting the running script. Now with auto-complete and command history (only on linux).

Inspect Shell is not a pdb-style debugger.

https://github.com/amoffat/Inspect-Shell

You could use that (and your wristwatch).

Centering a background image, using CSS

Had the same problem. Used display and margin properties and it worked.

.background-image {
  background: url('yourimage.jpg') no-repeat;
  display: block;
  margin-left: auto;
  margin-right: auto;
  height: whateveryouwantpx;
  width: whateveryouwantpx;
}

Convert time fields to strings in Excel

The below worked for me

  • First copy the content say "1:00:15" in notepad
  • Then select a new column where you need to copy the text from notepad.
  • Then right click and select format cell option and in that select numbers tab and in that tab select the option "Text".
  • Now copy the content from notepad and paste in this Excel column. it will be text but in format "1:00:15".

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

Are PostgreSQL column names case-sensitive?

if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:

select
    psat.schemaname,
    psat.relname,
    pa.attname,
    psat.relid
from
    pg_catalog.pg_stat_all_tables psat,
    pg_catalog.pg_attribute pa
where
    psat.relid = pa.attrelid

change schema name:

ALTER SCHEMA "XXXXX" RENAME TO xxxxx;

change table names:

ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;

change column names:

ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;

How To Accept a File POST

I used Mike Wasson's answer before I updated all the NuGets in my webapi mvc4 project. Once I did, I had to re-write the file upload action:

    public Task<HttpResponseMessage> Upload(int id)
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
            {
                FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);

                string guid = Guid.NewGuid().ToString();

                File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));

                return new HttpResponseMessage()
                {
                    Content = new StringContent("File uploaded.")
                };
            }
        );
        return task;
    }

Apparently BodyPartFileNames is no longer available within the MultipartFormDataStreamProvider.

Read pdf files with php

There is a php library (pdfparser) that does exactly what you want.

project website

http://www.pdfparser.org/

github

https://github.com/smalot/pdfparser

Demo page/api

http://www.pdfparser.org/demo

After including pdfparser in your project you can get all text from mypdf.pdf like so:

<?php
$parser = new \installpath\PdfParser\Parser();
$pdf    = $parser->parseFile('mypdf.pdf');  
$text = $pdf->getText();
echo $text;//all text from mypdf.pdf

?>

Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).

How to access accelerometer/gyroscope data from Javascript?

Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation

function orientationhandler(evt){


  // For FF3.6+
  if (!evt.gamma && !evt.beta) {
    evt.gamma = -(evt.x * (180 / Math.PI));
    evt.beta = -(evt.y * (180 / Math.PI));
  }

  // use evt.gamma, evt.beta, and evt.alpha 
  // according to dev.w3.org/geo/api/spec-source-orientation


}

window.addEventListener('deviceorientation',  orientationhandler, false);
window.addEventListener('MozOrientation',     orientationhandler, false);

Throwing exceptions in a PHP Try Catch block

throw $e->getMessage();

You try to throw a string

As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data

JavaScript get clipboard data on paste event (Cross browser)

You can do this in this way:

use this jQuery plugin for pre & post paste events:

$.fn.pasteEvents = function( delay ) {
    if (delay == undefined) delay = 20;
    return $(this).each(function() {
        var $el = $(this);
        $el.on("paste", function() {
            $el.trigger("prepaste");
            setTimeout(function() { $el.trigger("postpaste"); }, delay);
        });
    });
};

Now you can use this plugin;:

$('#txt').on("prepaste", function() { 

    $(this).find("*").each(function(){

        var tmp=new Date.getTime();
        $(this).data("uid",tmp);
    });


}).pasteEvents();

$('#txt').on("postpaste", function() { 


  $(this).find("*").each(function(){

     if(!$(this).data("uid")){
        $(this).removeClass();
          $(this).removeAttr("style id");
      }
    });
}).pasteEvents();

Explaination

First set a uid for all existing elements as data attribute.

Then compare all nodes POST PASTE event. So by comparing you can identify the newly inserted one because they will have a uid, then just remove style/class/id attribute from newly created elements, so that you can keep your older formatting.