Programs & Examples On #Nib

On OS X, a nib file describes the visual elements of your application’s user interface, including windows, views, controls, and many others

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

This can also occur if you change the name of your xib file, and you forget to change all the places it is referenced.

Example: MainWindow.xib is a TabBarController that contains a custom ViewController named FirstViewController with associated xib file FirstView. You change the name to SecondViewController and associated xib file to SecondView.

Solution:

Open MainWindow.xib (that contains the TabBarController):

  • Select the tab that is for the ViewController you changed.
  • On the Identity inspector, Change the Custom Class name to SecondViewController.
  • On the attributes inspector, Change the xib name to SecondView.

Open SecondView.xib (this was copied from FirstView.xib):

  • On the Identity Inspector, change the custom class to SecondViewController.

Optionally you may need to:

  • Right click SecondView.xib, verify that "Identity and Type->Target Membership" is enabled.
  • Make sure "Build Phases -> Copy Bundle Resources" shows your SecondView.xib
  • I also found I occasionally needed to build clean and delete the app from the simulator to get the xib file to actually update. The simulator has an internal cache for xib files that is a little inconsistent.

Output to the same line overwriting previous output?

You can just add '\r' at the end of the string plus a comma at the end of print function. For example:

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),

Unable to Cast from Parent Class to Child Class

A variation on the serialization approach for those using ServiceStack:

var child = baseObject.ConvertTo<ChildType>();

or the more verbose:

var child = baseObject.ToJson().FromJson<ChildType>();

ServiceStack's serialization might be super fast and all, but clearly, this is not a solution for massive conversions in low-latency transfers, nor for highly complex types. That's likely obvious to anyone using ServiceStack, but thought I'd clarify in anticipation of comments.

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

Can I animate absolute positioned element with CSS transition?

You forgot to define the default value for left so it doesn't know how to animate.

.test {
    left: 0;
    transition:left 1s linear;
}

See here: http://jsfiddle.net/shomz/yFy5n/5/

Java: Converting String to and from ByteBuffer and associated problems

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

Is it possible to output a SELECT statement from a PL/SQL block?

For versions below 12c, the plain answer is NO, at least not in the manner it is being done is SQL Server.
You can print the results, you can insert the results into tables, you can return the results as cursors from within function/procedure or return a row set from function -
but you cannot execute SELECT statement, without doing something with the results.


SQL Server

begin
    select 1+1
    select 2+2
    select 3+3
end

/* 3 result sets returned */


Oracle

SQL> begin
  2  select 1+1 from dual;
  3  end;
  4  /
select * from dual;
*
ERROR at line 2:
ORA-06550: line 2, column 1:
PLS-00428: an INTO clause is expected in this SELECT statement

UITableView Cell selected Color?

If you want to add a custom highlighted color to your cell (and your cell contains buttons,labels, images,etc..) I followed the next steps:

For example if you want a selected yellow color:

1) Create a view that fits all the cell with 20% opacity (with yellow color) called for example backgroundselectedView

2) In the cell controller write this:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     self.backgroundselectedView.alpha=1;
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.backgroundselectedView.alpha=0;
    [super touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.backgroundSelectedImage.alpha=0;
    [super touchesCancelled:touches withEvent:event];
}

Getting multiple values with scanf()

You can do this with a single call, like so:

scanf( "%i %i %i %i", &minx, &maxx, &miny, &maxy);

Print content of JavaScript object?

You can use json.js from http://www.json.org/js.html to change json data to string data.

IIS URL Rewrite and Web.config

Just wanted to point out one thing missing in LazyOne's answer (I would have just commented under the answer but don't have enough rep)

In rule #2 for permanent redirect there is thing missing:

redirectType="Permanent"

So rule #2 should look like this:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Edit

For more information on how to use the URL Rewrite Module see this excellent documentation: URL Rewrite Module Configuration Reference

In response to @kneidels question from the comments; To match the url: topic.php?id=39 something like the following could be used:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="SpecificRedirect" stopProcessing="true">
        <match url="^topic.php$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{QUERY_STRING}" pattern="(?:id)=(\d{2})" />
        </conditions>
        <action type="Redirect" url="/newpage/{C:1}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

This will match topic.php?id=ab where a is any number between 0-9 and b is also any number between 0-9. It will then redirect to /newpage/xy where xy comes from the original url. I have not tested this but it should work.

How to get first and last day of the current week in JavaScript

Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.

You can use a third party date library to deal with dates. For example:

var startOfWeek = moment().startOf('week').toDate();
var endOfWeek   = moment().endOf('week').toDate();

EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)

Another popular alternative is date-fns.

'module' has no attribute 'urlencode'

import urllib.parse
urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})

How to have the cp command create any necessary folders for copying a file to a destination

To expand upon Christian's answer, the only reliable way to do this would be to combine mkdir and cp:

mkdir -p /foo/bar && cp myfile "$_"

As an aside, when you only need to create a single directory in an existing hierarchy, rsync can do it in one operation. I'm quite a fan of rsync as a much more versatile cp replacement, in fact:

rsync -a myfile /foo/bar/ # works if /foo exists but /foo/bar doesn't.  bar is created.

Android: remove left margin from actionbar's custom layout

I found an other resolution (reference appcompat-v7 ) that change the toolbarStyle ,following code:

<item name="toolbarStyle">@style/Widget.Toolbar</item>


<style name="Widget.Toolbar" parent="@style/Widget.AppCompat.Toolbar">
<item name="contentInsetStart">0dp</item>
</style>

create unique id with javascript

const uid = function(){
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

This Function generates very unique IDs that are sorted by its generated Date. Also useable for IDs in Databases.

How do I access (read, write) Google Sheets spreadsheets with Python?

The latest google api docs document how to write to a spreadsheet with python but it's a little difficult to navigate to. Here is a link to an example of how to append.

The following code is my first successful attempt at appending to a google spreadsheet.

import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'mail_to_g_app.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def add_todo():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = 'PUT YOUR SPREADSHEET ID HERE'
    rangeName = 'A1:A'

    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values':[['Hello Saturn',],]}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=rangeName,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()

How to install Android SDK Build Tools on the command line?

However, it is too slow on running

Yes, I've had the same problem. Some of the file downloads are extremely slow (or at least they have been in the last couple of days). If you want to download everything there's not a lot you can do about that.

The result is that nothing in folder build-tools, and I want is aapt and apkbuilder, since I want to build apk from command line without ant.

Did you let it run to completion?

One thing you can do is filter the packages that are being downloaded using the -t switch.

For example:

tools/android update sdk --no-ui -t platform-tool

When I tried this the other day I got version 18.0.0 of the build tools installed. For some reason the latest version 18.0.1 is not included by this filter and the only way to get it was to install everything with the --all switch.

What is the difference between an Instance and an Object?

each object said to be an instance of its class but each instance of the class has its own value for each attributes intances shares the attribute name and operation with their intances of class but an object contains an implicit reference to his on class

Angular - ng: command not found

Guess You are running on Windows (To make @jowey's answer more straightforward).

  • Install Angular normally from your bash $ npm install -g @angular/cli@latest Next is to rearrange the PATHS to
  • NPM
  • Nodejs
  • Angular CLI

in System Environment Variables, the picture below shows the arrangement.

enter image description here

MySQL INSERT INTO ... VALUES and SELECT

INSERT INTO table1 (col1, col2)
SELECT "a string", 5, TheNameOfTheFieldInTable2
FROM table2 where ...

&& (AND) and || (OR) in IF statements

Java has 5 different boolean compare operators: &, &&, |, ||, ^

& and && are "and" operators, | and || "or" operators, ^ is "xor"

The single ones will check every parameter, regardless of the values, before checking the values of the parameters. The double ones will first check the left parameter and its value and if true (||) or false (&&) leave the second one untouched. Sound compilcated? An easy example should make it clear:

Given for all examples:

 String aString = null;

AND:

 if (aString != null & aString.equals("lala"))

Both parameters are checked before the evaluation is done and a NullPointerException will be thrown for the second parameter.

 if (aString != null && aString.equals("lala"))

The first parameter is checked and it returns false, so the second paramter won't be checked, because the result is false anyway.

The same for OR:

 if (aString == null | !aString.equals("lala"))

Will raise NullPointerException, too.

 if (aString == null || !aString.equals("lala"))

The first parameter is checked and it returns true, so the second paramter won't be checked, because the result is true anyway.

XOR can't be optimized, because it depends on both parameters.

How can I create objects while adding them into a vector?

I know the thread is already all, but as I was checking through I've come up with a solution (code listed below). Hope it can help.

#include <iostream>
#include <vector>

class Box
{
    public:

    static int BoxesTotal;
    static int BoxesEver;
    int Id;

    Box()
    {
        ++BoxesTotal;
        ++BoxesEver;
        Id = BoxesEver;
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") initialized." << std::endl;
    }

    ~Box()
    {
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") ended." << std::endl;
        --BoxesTotal;
    }

};

int Box::BoxesTotal = 0;
int Box::BoxesEver = 0;

int main(int argc, char* argv[])
{
    std::cout << "Objects (Boxes) example." << std::endl;
    std::cout << "------------------------" << std::endl;

    std::vector <Box*> BoxesTab;

    Box* Indicator;
    for (int i = 1; i<4; ++i)
    {
        std::cout << "i = " << i << ":" << std::endl;
        Box* Indicator = new(Box);
        BoxesTab.push_back(Indicator);
        std::cout << "Adres Blowera: " <<  BoxesTab[i-1] << std::endl;
    }

    std::cout << "Summary" << std::endl;
    std::cout << "-------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Adres Blowera: " <<  BoxesTab[i] << std::endl;
    }

    std::cout << "Deleting" << std::endl;
    std::cout << "--------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Deleting Box: " << i+1 << " (" <<  BoxesTab[i] << ") " << std::endl;
        Indicator = (BoxesTab[i]);
        delete(Indicator);
    }

    return 0;
}

And the result it produces is:

Objects (Boxes) example.
------------------------
i = 1:
Box (1/1/1) initialized.
Adres Blowera: 0xdf8ca0
i = 2:
Box (2/2/2) initialized.
Adres Blowera: 0xdf8ce0
i = 3:
Box (3/3/3) initialized.
Adres Blowera: 0xdf8cc0
Summary
-------
Adres Blowera: 0xdf8ca0
Adres Blowera: 0xdf8ce0
Adres Blowera: 0xdf8cc0
Deleting
--------
Deleting Box: 1 (0xdf8ca0) 
Box (1/3/3) ended.
Deleting Box: 2 (0xdf8ce0) 
Box (2/2/3) ended.
Deleting Box: 3 (0xdf8cc0) 
Box (3/1/3) ended.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

To get AM/PM, Check if the hour portion is less than 12, then it is AM, else PM.

To get the hour, do (hour % 12) || 12.

This should do it:

var timeString = "18:00:00";
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;

http://jsfiddle.net/Skwt7/4/

That assumes that AM times are formatted as, eg, 08:00:00. If they are formatted without the leading zero, you would have to test the position of the first colon:

var hourEnd = timeString.indexOf(":");
var H = +timeString.substr(0, hourEnd);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(hourEnd, 3) + ampm;

http://jsfiddle.net/Skwt7/3/

How to use EOF to run through a text file in C?

One possible C loop would be:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        /*
        ** Do something with c, such as check against '\n'
        ** and increment a line counter.
        */
    }
}

For now, I would ignore feof and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.

Pitfall to avoid: using char for the type of c. getchar returns the next character cast to an unsigned char and then to an int. This means that on most [sane] platforms the value of EOF and valid "char" values in c don't overlap so you won't ever accidentally detect EOF for a 'normal' char.

Getting error "The package appears to be corrupt" while installing apk file

In my case, the target phone had the app already installed, but in a "disabled" state. So the user thought it was already uninstalled, but it wasn't. I went to the main app list, clicked on the "disabled" app, uninstalled it, and then the APK would go on.

How to get the bluetooth devices as a list?

package com.sekurtrack.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    private BluetoothAdapter BA;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.devicesList);



        BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

       /* BA = BluetoothAdapter.getDefaultAdapter();
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
        Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
        final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);*/

    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT1", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };
}

Self-reference for cell, column and row in worksheet functions

I don't see the need for Indirect, especially for conditional formatting.

The simplest way to self-reference a cell, row or column is to refer to it normally, e.g., "=A1" in cell A1, and make the reference partly or completely relative. For example, in a conditional formatting formula for checking whether there's a value in the first column of various cells' rows, enter the following with A1 highlighted and copy as necessary. The conditional formatting will always refer to column A for the row of each cell:

= $A1 <> ""

JPA eager fetch does not join

If you use EclipseLink instead of Hibernate you can optimize your queries by "query hints". See this article from the Eclipse Wiki: EclipseLink/Examples/JPA/QueryOptimization.

There is a chapter about "Joined Reading".

Display names of all constraints for a table in Oracle SQL

maybe this can help:

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

cheers

INSERT INTO vs SELECT INTO

The other answers are all great/correct (the main difference is whether the DestTable exists already (INSERT), or doesn't exist yet (SELECT ... INTO))

You may prefer to use INSERT (instead of SELECT ... INTO), if you want to be able to COUNT(*) the rows that have been inserted so far.

Using SELECT COUNT(*) ... WITH NOLOCK is a simple/crude technique that may help you check the "progress" of the INSERT; helpful if it's a long-running insert, as seen in this answer).

[If you use...] INSERT DestTable SELECT ... FROM SrcTable ...then your SELECT COUNT(*) from DestTable WITH (NOLOCK) query would work.

Threading Example in Android

Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.

Android code - Main.java

package test12.tt;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() { 
            public void run(){        
            txt1.setText("Thread!!");
            }
        }).start();

    }    
}

Android application xml - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
    android:id = "@+id/sm"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

</LinearLayout>

PHP PDO: charset, set names?

I think you need an additionally query because the charset option in the DSN is actually ignored. see link posted in the comment of the other answer.

Looking at how Drupal 7 is doing it in http://api.drupal.org/api/drupal/includes--database--mysql--database.inc/function/DatabaseConnection_mysql%3A%3A__construct/7:

// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
  $this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
}
else {
  $this->exec('SET NAMES utf8');
}

How do I call a specific Java method on a click/submit event of a specific button in JSP?

You can try adding action="#{yourBean.function1}" on each button (changing of course the method function2, function3, or whatever you need). If that does not work, you can try the same with the onclick event.

Anyway, it would be easier to help you if you tell us what kind of buttons are you trying to use, a4j:commandButton or whatever you are using.

GridView sorting: SortDirection always Ascending

It's been awhile since I used a GridView, but I think you need to set the grid's SortDirection property to whatever it currently is before leaving the OnSorting method.

So....

List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection();
items.Sort(new Helpers.GenericComparer<V_ReportPeriodStatusEntity>(e.SortExpression, e.SortDirection));
grdHeader.SortDirection = e.SortDirection.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
grdHeader.DataSource = items;
grdHeader.DataBind();

How to set width and height dynamically using jQuery

I tried below code its worked for fine

var modWidth = 250;
var modHeight = 150;

example below :-

$( "#ContainerId .sDashboard li" ).width( modWidth ).height(modHeight);

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

I resolve this is by changing the version no of recyleview to recyclerview-v7:24.2.1. Please check your dependencies and use the proper version number.

Best practices for catching and re-throwing .NET exceptions

I would definitely use:

try
{
    //some code
}
catch
{
    //you should totally do something here, but feel free to rethrow
    //if you need to send the exception up the stack.
    throw;
}

That will preserve your stack.

How to select all and copy in vim?

ggVG 

will select from beginning to end

How to set a timeout on a http.request() in Node?

The Rob Evans anwser works correctly for me but when I use request.abort(), it occurs to throw a socket hang up error which stays unhandled.

I had to add an error handler for the request object :

var options = { ... }
var req = http.request(options, function(res) {
  // Usual stuff: on(data), on(end), chunks, etc...
}

req.on('socket', function (socket) {
    socket.setTimeout(myTimeout);  
    socket.on('timeout', function() {
        req.abort();
    });
}

req.on('error', function(err) {
    if (err.code === "ECONNRESET") {
        console.log("Timeout occurs");
        //specific error treatment
    }
    //other error treatment
});

req.write('something');
req.end();

Find the server name for an Oracle database

The query below demonstrates use of the package and some of the information you can get.

select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual

NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.

Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.

Measuring the distance between two coordinates in PHP

Try this function out to calculate distance between to points of latitude and longitude

function calculateDistanceBetweenTwoPoints($latitudeOne='', $longitudeOne='', $latitudeTwo='', $longitudeTwo='',$distanceUnit ='',$round=false,$decimalPoints='')
    {
        if (empty($decimalPoints)) 
        {
            $decimalPoints = '3';
        }
        if (empty($distanceUnit)) {
            $distanceUnit = 'KM';
        }
        $distanceUnit = strtolower($distanceUnit);
        $pointDifference = $longitudeOne - $longitudeTwo;
        $toSin = (sin(deg2rad($latitudeOne)) * sin(deg2rad($latitudeTwo))) + (cos(deg2rad($latitudeOne)) * cos(deg2rad($latitudeTwo)) * cos(deg2rad($pointDifference)));
        $toAcos = acos($toSin);
        $toRad2Deg = rad2deg($toAcos);

        $toMiles  =  $toRad2Deg * 60 * 1.1515;
        $toKilometers = $toMiles * 1.609344;
        $toNauticalMiles = $toMiles * 0.8684;
        $toMeters = $toKilometers * 1000;
        $toFeets = $toMiles * 5280;
        $toYards = $toFeets / 3;


              switch (strtoupper($distanceUnit)) 
              {
                  case 'ML'://miles
                         $toMiles  = ($round == true ? round($toMiles) : round($toMiles, $decimalPoints));
                         return $toMiles;
                      break;
                  case 'KM'://Kilometers
                        $toKilometers  = ($round == true ? round($toKilometers) : round($toKilometers, $decimalPoints));
                        return $toKilometers;
                      break;
                  case 'MT'://Meters
                        $toMeters  = ($round == true ? round($toMeters) : round($toMeters, $decimalPoints));
                        return $toMeters;
                      break;
                  case 'FT'://feets
                        $toFeets  = ($round == true ? round($toFeets) : round($toFeets, $decimalPoints));
                        return $toFeets;
                      break;
                  case 'YD'://yards
                        $toYards  = ($round == true ? round($toYards) : round($toYards, $decimalPoints));
                        return $toYards;
                      break;
                  case 'NM'://Nautical miles
                        $toNauticalMiles  = ($round == true ? round($toNauticalMiles) : round($toNauticalMiles, $decimalPoints));
                        return $toNauticalMiles;
                      break;
              }


    }

Then use the fucntion as

echo calculateDistanceBetweenTwoPoints('11.657740','77.766270','11.074820','77.002160','ML',true,5);

Hope it helps

Multiple Image Upload PHP form with one input

Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";

        $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
        $lastid= $connection->insert_id;
        foreach ($_FILES["file"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK ){
                $name = $lastid.$_FILES['file']['name'][$key];
                $target_dir = "photo/";
                $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
                move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
            }
        }

And how to fetch

$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());


  if($result->num_rows > 0) {
      while($r = mysqli_fetch_assoc($result)){
        $eventid= $r['id'];
        $sqli="select id,image from photos where eventid='".$eventid."'";
        $resulti=mysqli_query($connection,$sqli);
        $image_json_array = array();
        while($row = mysqli_fetch_assoc($resulti)){
            $image_id = $row['id'];
            $image_name = $row['image'];
            $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
        }
        $msg1[] = array ("imagelist" => $image_json_array);

      }

in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})

How to display special characters in PHP

You can have a mix of PHP and HTML in your PHP files... just do something like this...

<?php
$string = htmlentities("Résumé");
?>

<html>
<head></head>
<body>
<p><?= $string ?></p>
</body>
</html>

That should output Résumé just how you want it to.

If you don't have short tags enabled, replace the <?= $string ?> with <?php echo $string; ?>

A completely free agile software process tool

Try http://www.icescrum.org . It is free to use. And it has lot of cool features. Perfect for scrum teams.

How do I restart my C# WinForm Application?

How about create a bat file, run the batch file before closing, and then close the current instance.

The batch file does this:

  1. wait in a loop to check whether the process has exited.
  2. start the process.

Reading a binary input stream into a single byte array in Java

Max value for array index is Integer.MAX_INT - it's around 2Gb (2^31 / 2 147 483 647). Your input stream can be bigger than 2Gb, so you have to process data in chunks, sorry.

        InputStream is;
        final byte[] buffer = new byte[512 * 1024 * 1024]; // 512Mb
        while(true) {
            final int read = is.read(buffer);
            if ( read < 0 ) {
                break;
            }
            // do processing 
        }

Java ArrayList - Check if list is empty

Good practice nowadays is to use CollectionUtils from either Apache Commons or Spring Framework.

CollectionUtils.isEmpty(list))

How to display Wordpress search results?

Basically, you need to include the Wordpress loop in your search.php template to loop through the search results and show them as part of the template.

Below is a very basic example from The WordPress Theme Search Template and Page Template over at ThemeShaper.

<?php
/**
 * The template for displaying Search Results pages.
 *
 * @package Shape
 * @since Shape 1.0
 */

get_header(); ?>

        <section id="primary" class="content-area">
            <div id="content" class="site-content" role="main">

            <?php if ( have_posts() ) : ?>

                <header class="page-header">
                    <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
                </header><!-- .page-header -->

                <?php shape_content_nav( 'nav-above' ); ?>

                <?php /* Start the Loop */ ?>
                <?php while ( have_posts() ) : the_post(); ?>

                    <?php get_template_part( 'content', 'search' ); ?>

                <?php endwhile; ?>

                <?php shape_content_nav( 'nav-below' ); ?>

            <?php else : ?>

                <?php get_template_part( 'no-results', 'search' ); ?>

            <?php endif; ?>

            </div><!-- #content .site-content -->
        </section><!-- #primary .content-area -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Peak memory usage of a linux/unix process

You can use a tool like Valgrind to do this.

Android ADB devices unauthorized

Delete existing adbkeys

OR

Rename adbkeys

Best practise is to rename the keys because it provides backup.

cd ~/.Android

mv adbkey adbkey2

mv adbkey.pub adbkey.pub2

Next stop & start the server

cd ~/Android/Sdk/platform-tools

Locate the device /Android/Sdk/platform-tools$ ./adb devices

/Android/Sdk/platform-tools$ ./adb kill-server

/Android/Sdk/platform-tools$ ./adb start-server

Then, stop the emulator Open AVD manager, click on the down arrow, then click on wipe data

Restart the emulator. Then everything works fine :)

How can I create download link in HTML?

You can download in the various way you can follow my way. Though files may not download due to 'allow-popups' permission is not set but in your environment, this will work perfectly

_x000D_
_x000D_
<div className="col-6">_x000D_
                    <a  download href="https://www.w3schools.com/images/myw3schoolsimage.jpg" >Test Download </a>_x000D_
                </div>
_x000D_
_x000D_
_x000D_

another one this one will also fail due to 'X-Frame-Options' to 'sameorigin'.

_x000D_
_x000D_
<a href="https://www.w3schools.com/images/myw3schoolsimage.jpg" download>_x000D_
  <img src="https://www.w3schools.com/images/myw3schoolsimage.jpg" alt="W3Schools" width="104" height="142">_x000D_
</a>
_x000D_
_x000D_
_x000D_

Accessing members of items in a JSONArray with Java

Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

If the iteration is only one time, (no need to .collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });

PUT vs. POST in REST

Most of the time, you will use them like this:

  • POST a resource into a collection
  • PUT a resource identified by collection/:id

For example:

  • POST /items
  • PUT /items/1234

In both cases, the request body contains the data for the resource to be created or updated. It should be obvious from the route names that POST is not idempotent (if you call it 3 times it will create 3 objects), but PUT is idempotent (if you call it 3 times the result is the same). PUT is often used for "upsert" operation (create or update), but you can always return a 404 error if you only want to use it to modify.

Note that POST "creates" a new element in the collection, and PUT "replaces" an element at a given URL, but it is a very common practice to use PUT for partial modifications, that is, use it only to update existing resources and only modify the included fields in the body (ignoring the other fields). This is technically incorrect, if you want to be REST-purist, PUT should replace the whole resource and you should use PATCH for the partial update. I personally don't care much as far as the behavior is clear and consistent across all your API endpoints.

Remember, REST is a set of conventions and guidelines to keep your API simple. If you end up with a complicated work-around just to check the "RESTfull" box then you are defeating the purpose ;)

Set default value of javascript object attributes

This seems to me the most simple and readable way of doing so:

let options = {name:"James"}
const default_options = {name:"John", surname:"Doe"}

options = Object.assign({}, default_options, options)

Object.assign() reference

How to make CREATE OR REPLACE VIEW work in SQL Server?

Borrowing from @Khan's answer, I would do:

IF OBJECT_ID('dbo.test_abc_def', 'V') IS NOT NULL
    DROP VIEW dbo.test_abc_def
GO

CREATE VIEW dbo.test_abc_def AS
SELECT 
    VCV.xxxx
    ,VCV.yyyy AS yyyy
    ,VCV.zzzz AS zzzz
FROM TABLE_A

MSDN Reference

How can I get the DateTime for the start of the week?

    namespace DateTimeExample
    {
        using System;

        public static class DateTimeExtension
        {
            public static DateTime GetMonday(this DateTime time)
            {
                if (time.DayOfWeek != DayOfWeek.Monday)
                    return GetMonday(time.AddDays(-1)); //Recursive call

                return time;
            }
        }

        internal class Program
        {
            private static void Main()
            {
                Console.WriteLine(DateTime.Now.GetMonday());
                Console.ReadLine();
            }
        }
    } 

substring index range

The substring starts at, and includes the character at the location of the first number given and goes to, but does not include the character at the last number given.

Whoops, looks like something went wrong. Laravel 5.0

Please, try to find something like:

./website/config/app.php and set 'debug' => env('APP_DEBUG', false) as 'true' 'debug' => env('APP_DEBUG', true)

Convert long/lat to pixel x/y on a given picture

You may have a look at code that used on gheat, it's ported from js to python.

In Python, how do you convert a `datetime` object to seconds?

I tried the standard library's calendar.timegm and it works quite well:

# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
    return int(calendar.timegm(aDateTime.timetuple())*1000)

Ref: https://docs.python.org/2/library/calendar.html#calendar.timegm

Using isKindOfClass with Swift

I would use:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if let touchView = touch.view as? UIPickerView
    {

    }
}

Nullable DateTime conversion

You might want to do it like this:

DateTime? lastPostDate =  (DateTime?)(reader.IsDbNull(3) ? null : reader[3]); 

The problem you are having is that the ternary operator wants a viable cast between the left and right sides. And null can't be cast to DateTime.

Note the above works because both sides of the ternary are object's. The object is explicitly cast to DateTime? which works: as long as reader[3] is in fact a date.

MySQL: How to copy rows, but change a few fields?

This is a solution where you have many fields in your table and don't want to get a finger cramp from typing all the fields, just type the ones needed :)

How to copy some rows into the same table, with some fields having different values:

  1. Create a temporary table with all the rows you want to copy
  2. Update all the rows in the temporary table with the values you want
  3. If you have an auto increment field, you should set it to NULL in the temporary table
  4. Copy all the rows of the temporary table into your original table
  5. Delete the temporary table

Your code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE Event_ID="155";

UPDATE temporary_table SET Event_ID="120";

UPDATE temporary_table SET ID=NULL

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

General scenario code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

UPDATE temporary_table SET <auto_inc_field>=NULL;

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

Simplified/condensed code:

CREATE TEMPORARY TABLE temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <auto_inc_field>=NULL, <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

INSERT INTO original_table SELECT * FROM temporary_table;

As creation of the temporary table uses the TEMPORARY keyword it will be dropped automatically when the session finishes (as @ar34z suggested).

Are PDO prepared statements sufficient to prevent SQL injection?

Prepared statements / parameterized queries are generally sufficient to prevent 1st order injection on that statement*. If you use un-checked dynamic sql anywhere else in your application you are still vulnerable to 2nd order injection.

2nd order injection means data has been cycled through the database once before being included in a query, and is much harder to pull off. AFAIK, you almost never see real engineered 2nd order attacks, as it is usually easier for attackers to social-engineer their way in, but you sometimes have 2nd order bugs crop up because of extra benign ' characters or similar.

You can accomplish a 2nd order injection attack when you can cause a value to be stored in a database that is later used as a literal in a query. As an example, let's say you enter the following information as your new username when creating an account on a web site (assuming MySQL DB for this question):

' + (SELECT UserName + '_' + Password FROM Users LIMIT 1) + '

If there are no other restrictions on the username, a prepared statement would still make sure that the above embedded query doesn't execute at the time of insert, and store the value correctly in the database. However, imagine that later the application retrieves your username from the database, and uses string concatenation to include that value a new query. You might get to see someone else's password. Since the first few names in users table tend to be admins, you may have also just given away the farm. (Also note: this is one more reason not to store passwords in plain text!)

We see, then, that prepared statements are enough for a single query, but by themselves they are not sufficient to protect against sql injection attacks throughout an entire application, because they lack a mechanism to enforce all access to a database within an application uses safe code. However, used as part of good application design — which may include practices such as code review or static analysis, or use of an ORM, data layer, or service layer that limits dynamic sql — prepared statements are the primary tool for solving the Sql Injection problem. If you follow good application design principles, such that your data access is separated from the rest of your program, it becomes easy to enforce or audit that every query correctly uses parameterization. In this case, sql injection (both first and second order) is completely prevented.


*It turns out that MySql/PHP are (okay, were) just dumb about handling parameters when wide characters are involved, and there is still a rare case outlined in the other highly-voted answer here that can allow injection to slip through a parameterized query.

initializing a boolean array in java

The main difference is that Boolean is an object and boolean is an primitive.

  • Object default value is null;
  • boolean default value is false;

CertificateException: No name matching ssl.someUrl.de found

It looks like the certificate of the server you are trying to connect to doesn't match its hostname.

When an HTTPS client connects to a server, it verifies that the hostname in the certificate matches the hostname of the server. It's not enough for a certificate to be trusted, it has to match the server you want to talk to too. (As an analogy, even if you trust a passport to be legitimate, you still have to check that it's the one for the person you want to talk to, not just any passport you would trust to be legitimate.)

In HTTP, this is done by checking that:

  • the certificate contains a DNS subject alternative name (this is a standard extension) entry matching the hostname;

  • failing that, the last CN of your subject distinguished name (this is the main name if you want) matches the hostname. (See RFC 2818.)

It's hard to tell what the subject alternative name is without having the certificate (although, if you connect with your browser and check its content in more details, you should be able to see it.) The subject distinguished name seems to be:

[email protected], CN=plesk, OU=Plesk, O=Parallels, L=Herndon, ST=Virginia, C=US

(It would thus need to be CN=ssl.someUrl.de instead of CN=plesk, if you don't have a subject alternative name with DNS:ssl.someUrl.de already; my guess is that you don't.)

You may be able to bypass the hostname verification using HttpsURLConnection.setHostnameVerifier(..). It shouldn't be too hard to write a custom HostnameVerifier that bybasses the verification, although I would suggest doing it only when the certificate its the one concerned here specifically. You should be able to get that using the SSLSession argument and its getPeerCertificates() method.

(In addition, you don't need to set the javax.net.ssl.* properties the way you've done it, since you're using the default values anyway.)

Alternatively, if you have control over the server you're connecting to and its certificate, you can create a certificate of it that matches the naming rules above (CN should be sufficient, although subject alternative name is an improvement). If a self-signed certificate is good enough for what you name, make sure its common name (CN) is the host name you're trying to talk to (no the full URL, just the hostname).

How to change Java version used by TOMCAT?

When you open catalina.sh / catalina.bat, you can see :

Environment Variable Prequisites

JAVA_HOME Must point at your Java Development Kit installation.

So, set your environment variable JAVA_HOME to point to Java 6. Also make sure JRE_HOME is pointing to the same target, if it is set.

Update: since you are on Windows, see here for how to manage your environment variables

htaccess redirect to https://www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Notes: Make sure you have done the following steps

  1. sudo a2enmod rewrite
  2. sudo service apache2 restart
  3. Add Following in your vhost file, located at /etc/apache2/sites-available/000-default.conf
<Directory /var/www/html>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  allow from all
  Require all granted
</Directory>

Now your .htaccess will work and your site will redirect to http:// to https://www

How to fix "unable to open stdio.h in Turbo C" error?

First check whether the folder name is right or wrong since while you copying to one folder from other accidently it takes other folder address eg it take C instead of F So from OPTION>DIRECTORY change the folder name

Java String - See if a string contains only numbers and not letters

Apache Commons Lang provides org.apache.commons.lang.StringUtils.isNumeric(CharSequence cs), which takes as an argument a String and checks if it consists of purely numeric characters (including numbers from non-Latin scripts). That method returns false if there are characters such as space, minus, plus, and decimal separators such as comma and dot.

Other methods of that class allow for further numeric checks.

Flutter does not find android sdk

Flutter say Sdk build tool version(exp:android toolchain - develop for android devices (android sdk 28.0.3)) version=28.0.3 go to home/username/Android/Sdk/build-tools delete this version(28.0.3) and fixed bug

Finding all positions of substring in a larger string in C#

public List<int> GetPositions(string source, string searchString)
{
    List<int> ret = new List<int>();
    int len = searchString.Length;
    int start = -len;
    while (true)
    {
        start = source.IndexOf(searchString, start + len);
        if (start == -1)
        {
            break;
        }
        else
        {
            ret.Add(start);
        }
    }
    return ret;
}

Call it like this:

List<int> list = GetPositions("bob is a chowder head bob bob sldfjl", "bob");
// list will contain 0, 22, 26

Using IQueryable with Linq

It allows for further querying further down the line. If this was beyond a service boundary say, then the user of this IQueryable object would be allowed to do more with it.

For instance if you were using lazy loading with nhibernate this might result in graph being loaded when/if needed.

What does $_ mean in PowerShell?

I think the easiest way to think about this variable like input parameter in lambda expression in C#. I.e. $_ is similar to x in x => Console.WriteLine(x) anonymous function in C#. Consider following examples:

PowerShell:

1,2,3 | ForEach-Object {Write-Host $_}

Prints:

1
2
3

or

1,2,3 | Where-Object {$_ -gt 1}

Prints:

2
3

And compare this with C# syntax using LINQ:

var list = new List<int> { 1, 2, 3 };
list.ForEach( _ => Console.WriteLine( _ ));

Prints:

1
2
3

or

list.Where( _ => _ > 1)
    .ToList()
    .ForEach(s => Console.WriteLine(s));

Prints:

2
3

Read the current full URL with React?

this.props.location is a react-router feature, you'll have to install if you want to use it.

Note: doesn't return the full url.

Get full query string in C# ASP.NET

This should work fine for you.

Write this code in the Page_Load event of the page.

string ID = Request.QueryString["id"].ToString();
Response.Redirect("http://www.example.com/rendernews.php?id=" + ID);

Java - Best way to print 2D array?

You can print in simple way.

Use below to print 2D array

int[][] array = new int[rows][columns];
System.out.println(Arrays.deepToString(array));

Use below to print 1D array

int[] array = new int[size];
System.out.println(Arrays.toString(array));

Height of an HTML select box (dropdown)

This is not a perfect solution but it sort of does work.

In the select tag, include the following attributes where 'n' is the number of dropdown rows that would be visible.

<select size="1" position="absolute" onclick="size=(size!=1)?n:1;" ...>

There are three problems with this solution. 1) There is a quick flash of all the elements shown during the first mouse click. 2) The position is set to 'absolute' 3) Even if there are less than 'n' items the dropdown box will still be for the size of 'n' items.

How to group by month from Date field using sql

Try this:

select min(closing_date), date_part('month',closing_date) || '-' || date_part('year',closing_date) AS month,
Category, COUNT(Status)TotalCount 
FROM MyTable
where Closing_Date >= '2012-02-01' AND Closing_Date <= '2012-12-31'
AND Defect_Status1 is not null
GROUP BY month, Category,
ORDER BY 1

This way you are grouping by a concatenated date format, joined by a -

Positioning the colorbar

using padding pad

In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()

enter image description here

using an axes divider

One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

using subplots

One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4), 
                  gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

How does one convert a HashMap to a List in Java?

Solution using Java 8 and Stream Api:

private static <K, V>  List<V> createListFromMapEntries (Map<K, V> map){
        return map.values().stream().collect(Collectors.toList());
    }

Usage:

  public static void main (String[] args)
    {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "one");
        map.put(2, "two");
        map.put(3, "three");

        List<String> result = createListFromMapEntries(map);
        result.forEach(System.out :: println);
    }

Where to find Application Loader app in Mac?

As of Xcode 11, "Application Loader is no longer included with Xcode", per the Xcode 11 Release Notes:

Xcode supports uploading apps from the Organizer window or from the command line with xcodebuild or xcrun altool. Application Loader is no longer included with Xcode. (29008875)

The Xcode Help page, Upload an app to App Store Connect, explains how to upload from the Xcode Archives Organizer.

Transporter

In October 2019, Apple announced the Transporter app for macOS, now available in the Mac App Store.

With Transporter you can:

  • Upload your .ipa or .pkg files to App Store Connect.
  • View delivery progress, including validation warnings, errors, and delivery logs, so you can quickly fix any issues.
  • See a history of past deliveries, including date and time.

This was previously a download from iTunes Connect for qualified partners (FAQ)

Notes on Using the Command Line

I've uploaded non-Xcode builds with xcrun altool --upload-app -f path-to-build.ipa -u [email protected]. It won't show any progress, but you can see the network traffic in Activity Monitor. It finishes with No errors uploading 'path-to-build.ipa'.

See xcrun altool --help for usage. If your account has 2FA enabled, first visit https://appleid.apple.com/ and generate an app password.

Python Hexadecimal

Another solution is:

>>> "".join(list(hex(255))[2:])
'ff'

Probably an archaic answer, but functional.

How to make a movie out of images in python

Thanks , but i found an alternative solution using ffmpeg:

def save():
    os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")

But thank you for your help :)

Found 'OR 1=1/* sql injection in my newsletter database

The specific value in your database isn't what you should be focusing on. This is likely the result of an attacker fuzzing your system to see if it is vulnerable to a set of standard attacks, instead of a targeted attack exploiting a known vulnerability.

You should instead focus on ensuring that your application is secure against these types of attacks; OWASP is a good resource for this.

If you're using parameterized queries to access the database, then you're secure against Sql injection, unless you're using dynamic Sql in the backend as well.

If you're not doing this, you're vulnerable and you should resolve this immediately.

Also, you should consider performing some sort of validation of e-mail addresses.

JavaScript - Hide a Div at startup (load)

Barring the CSS solution. The fastest possible way is to hide it immediatly with a script.

<div id="hideme"></div>
<script type="text/javascript">
    $("#hideme").hide();
</script>

In this case I would recommend the CSS solution by Vega. But if you need something more complex (like an animation) you can use this approach.

This has some complications (see comments below). If you want this piece of script to really run as fast as possible you can't use jQuery, use native JS only and defer loading of all other scripts.

How can I get screen resolution in java?

Here's some functional code (Java 8) which returns the x position of the right most edge of the right most screen. If no screens are found, then it returns 0.

  GraphicsDevice devices[];

  devices = GraphicsEnvironment.
     getLocalGraphicsEnvironment().
     getScreenDevices();

  return Stream.
     of(devices).
     map(GraphicsDevice::getDefaultConfiguration).
     map(GraphicsConfiguration::getBounds).
     mapToInt(bounds -> bounds.x + bounds.width).
     max().
     orElse(0);

Here are links to the JavaDoc.

GraphicsEnvironment.getLocalGraphicsEnvironment()
GraphicsEnvironment.getScreenDevices()
GraphicsDevice.getDefaultConfiguration()
GraphicsConfiguration.getBounds()

Max size of an iOS application

4GB's is the maximum size your iOS app can be.

As of January 26, 2017

App Size for iOS (& tvOS) only

Your app’s total uncompressed size must be less than 4GB. Each Mach-O executable file (for example, app_name.app/app_name) must not exceed these limits:

  • For apps whose MinimumOSVersion is less than 7.0: maximum of 80 MB for the total of all __TEXT sections in the binary.
  • For apps whose MinimumOSVersion is 7.x through 8.x: maximum of 60 MB per slice for the __TEXT section of each architecture slice in the binary.
  • For apps whose MinimumOSVersion is 9.0 or greater: maximum of 500 MB for the total of all __TEXT sections in the binary.

However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.

This information can be found at iTunes Connect Developer Guide: Submitting the App to App Review.


As of February 12, 2015

(iOS only) App Size

iOS App binary files can be as large as 4 GB, but each executable file (app_name.app/app_name) must not exceed 60 MB. Additionally, the total uncompressed size of the app must be less than 4 billion bytes. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.

This information can be found on page 77 of the iTunes Connect Developer Guide.


As of December 12, 2013

(iOS only) App Size

iOS App binary files can be as large as 2 GB, but the executable file (app_name.app/app_name) cannot exceed 60MB. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.

This information can be found on page 58 of the iTunes Connect Developer Guide.


As of June 6, 2013

The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 237 of the guide.


As of January 10, 2013

The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 208 of the guide.


As of October 31, 2012

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 206 of the guide. Thanks to comment from Ozair Kafray.


As of July 19, 2012

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 214 of the guide. Thanks to comment from marsbear. In addition, the document has moved here:

http://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/iTunesConnect_Guide.pdf


As of July 13, 2012

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.


As of March 29, 2012 (version 7.4)

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.


As of January 23, 2012 (version 7.3)

The above information is still the same, however, it can be found on page 172 of the guide.


As of October 17, 2011 (version 7.2)

The above information is still the same, however, it can be found on page 180 of the guide. Thanks to comment from Luke for the update.


As of September 22, 2011 (version 7.1)

The above information is still the same, however, it can be found on page 179 of the guide. Thanks to comment from Saxon Druce for the update.

gcc warning" 'will be initialized after'

Class C {
   int a;
   int b;
   C():b(1),a(2){} //warning, should be C():a(2),b(1)
}

the order is important because if a is initialized before b , and a is depend on b. undefined behavior will appear.

How to create Windows EventLog source from command line?

Try PowerShell 2.0's EventLog cmdlets

Throwing this in for PowerShell 2.0 and upwards:

  • Run New-EventLog once to register the event source:

    New-EventLog -LogName Application -Source MyApp
    
  • Then use Write-EventLog to write to the log:

    Write-EventLog 
        -LogName Application 
        -Source MyApp 
        -EntryType Error 
        -Message "Immunity to iocaine powder not detected, dying now" 
        -EventId 1
    

TypeScript static classes

This is one way:

class SomeClass {
    private static myStaticVariable = "whatever";
    private static __static_ctor = (() => { /* do static constructor stuff :) */ })();
}

__static_ctor here is an immediately invoked function expression. Typescript will output code to call it at the end of the generated class.

Update: For generic types in static constructors, which are no longer allowed to be referenced by static members, you will need an extra step now:

class SomeClass<T> {
    static myStaticVariable = "whatever";
    private ___static_ctor = (() => { var someClass:SomeClass<T> ; /* do static constructor stuff :) */ })();
    private static __static_ctor = SomeClass.prototype.___static_ctor();
}

In any case, of course, you could just call the generic type static constructor after the class, such as:

class SomeClass<T> {
    static myStaticVariable = "whatever";
    private __static_ctor = (() => { var example: SomeClass<T>; /* do static constructor stuff :) */ })();
}
SomeClass.prototype.__static_ctor();

Just remember to NEVER use this in __static_ctor above (obviously).

What is difference between sleep() method and yield() method of multi threading?

Yield(): method will stop the currently executing thread and give a chance to another thread of same priority which are waiting in queue. If thier is no thread then current thread will continue to execute. CPU will never be in ideal state.

Sleep(): method will stop the thread for particular time (time will be given in milisecond). If this is single thread which is running then CPU will be in ideal state at that period of time.

Both are static menthod.

How to set the image from drawable dynamically in android?

As of API 22, getResources().getDrawable() is deprecated (see also Android getResources().getDrawable() deprecated API 22). Here is a new way to set the image resource dynamically:

String resourceId = "@drawable/myResourceName"; // where myResourceName is the name of your resource file, minus the file extension
int imageResource = getResources().getIdentifier(resourceId, null, getPackageName());
Drawable drawable = ContextCompat.getDrawable(this, imageResource); // For API 21+, gets a drawable styled for theme of passed Context
imageview = (ImageView) findViewById(R.id.imageView);
imageview.setImageDrawable(drawable);

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The issue with only having these two conditions:

  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />

is that they work only as long as the {REQUEST_FILENAME} exists physically on disk. This means that there can be scenarios where a request for an incorrectly named partial view would return the root page instead of a 404 which would cause angular to be loaded twice (and in certain scenarios it can cause a nasty infinite loop).

Thus, some safe "fallback" rules would be recommended to avoid these hard to troubleshoot issues:

  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.html$" negate="true" />
  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.js$" negate="true" />
  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.css$" negate="true" />

or a condition that matches any file ending:

<conditions>
  <!-- ... -->
  <add input="{REQUEST_FILENAME}" pattern=".*\.[\d\w]+$" negate="true" />
</conditions>

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

You may use Oracle pipelined functions

Basically, when you would like a PLSQL (or java or c) routine to be the «source» of data -- instead of a table -- you would use a pipelined function.

Simple Example - Generating Some Random Data
How could you create N unique random numbers depending on the input argument?

create type array
as table of number;


create function  gen_numbers(n in number default null)
return array
PIPELINED
as
begin
  for i in 1 .. nvl(n,999999999)
  loop
     pipe row(i);
 end loop;
 return;
end;

Suppose we needed three rows for something. We can now do that in one of two ways:

select * from TABLE(gen_numbers(3));

COLUMN_VALUE


       1
       2
       3

or

select * from TABLE(gen_numbers)
 where rownum <= 3;

COLUMN_VALUE


       1
       2
       3

pipelied Functions1 pipelied Functions2

Controlling execution order of unit tests in Visual Studio

As you should know by now, purists say it's forbiden to run ordered tests. That might be true for unit tests. MSTest and other Unit Test frameworks are used to run pure unit test but also UI tests, full integration tests, you name it. Maybe we shouldn't call them Unit Test frameworks, or maybe we should and use them according to our needs. That's what most people do anyway.

I'm running VS2015 and I MUST run tests in a given order because I'm running UI tests (Selenium).

Priority - Doesn't do anything at all This attribute is not used by the test system. It is provided to the user for custom purposes.

orderedtest - it works but I don't recommend it because:

  1. An orderedtest a text file that lists your tests in the order they should be executed. If you change a method name, you must fix the file.
  2. The test execution order is respected inside a class. You can't order which class executes its tests first.
  3. An orderedtest file is bound to a configuration, either Debug or Release
  4. You can have several orderedtest files but a given method can not be repeated in different orderedtest files. So you can't have one orderedtest file for Debug and another for Release.

Other suggestions in this thread are interesting but you loose the ability to follow the test progress on Test Explorer.

You are left with the solution that purist will advise against, but in fact is the solution that works: sort by declaration order.

The MSTest executor uses an interop that manages to get the declaration order and this trick will work until Microsoft changes the test executor code.

This means the test method that is declared in the first place executes before the one that is declared in second place, etc.

To make your life easier, the declaration order should match the alphabetical order that is is shown in the Test Explorer.

  • A010_FirstTest
  • A020_SecondTest
  • etc
  • A100_TenthTest

I strongly suggest some old and tested rules:

  • use a step of 10 because you will need to insert a test method later on
  • avoid the need to renumber your tests by using a generous step between test numbers
  • use 3 digits to number your tests if you are running more than 10 tests
  • use 4 digits to number your tests if you are running more than 100 tests

VERY IMPORTANT

In order to execute the tests by the declaration order, you must use Run All in the Test Explorer.

Say you have 3 test classes (in my case tests for Chrome, Firefox and Edge). If you select a given class and right click Run Selected Tests it usually starts by executing the method declared in the last place.

Again, as I said before, declared order and listed order should match or else you'll in big trouble in no time.

How can I change the image of an ImageView?

Just to go a little bit further in the matter, you can also set a bitmap directly, like this:

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);

Of course, this technique is only useful if you need to change the image.

Bootstrap 3 breakpoints and media queries

Bootstrap does not document the media queries very well. Those variables of @screen-sm, @screen-md, @screen-lg are actually referring to LESS variables and not simple CSS.

When you customize Bootstrap you can change the media query breakpoints and when it compiles the @screen-xx variables are changed to whatever pixel width you defined as screen-xx. This is how a framework like this can be coded once and then customized by the end user to fit their needs.

A similar question on here that might provide more clarity: Bootstrap 3.0 Media queries

In your CSS, you will still have to use traditional media queries to override or add to what Bootstrap is doing.

In regards to your second question, that is not a typo. Once the screen goes below 768px the framework becomes completely fluid and resizes at any device width, removing the need for breakpoints. The breakpoint at 480px exists because there are specific changes that occur to the layout for mobile optimization.

To see this in action, go to this example on their site (http://getbootstrap.com/examples/navbar-fixed-top/), and resize your window to see how it treats the design after 768px.

How do I load the contents of a text file into a javascript variable?

here is how I did it in jquery:

jQuery.get('http://localhost/foo.txt', function(data) {
    alert(data);
});

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

Issue: The Jet OLE DB provider reads a registry key to determine how many rows are to be read to guess the type of the source column. By default, the value for this key is 8. Hence, the provider scans the first 8 rows of the source data to determine the data types for the columns. If any field looks like text and the length of data is more than 255 characters, the column is typed as a memo field. So, if there is no data with a length greater than 255 characters in the first 8 rows of the source, Jet cannot accurately determine the nature of the data type. As the first 8 row length of data in the exported sheet is less than 255 its considering the source length as VARCHAR(255) and unable to read data from the column having more length.

Fix: The solution is just to sort the comment column in descending order. In 2012 onwards we can update the values in Advance tab in the Import wizard.

What is private bytes, virtual bytes, working set?

The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.

Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).

Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.

Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.

So the relationships are:

  • Private Bytes are what your app has actually allocated, but include pagefile usage;
  • Working Set is the non-paged Private Bytes plus memory-mapped files;
  • Virtual Bytes are the Working Set plus paged Private Bytes and standby list.

There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.

Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.

One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.

I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.

Node - how to run app.js?

To run app.js file check "main": "app.js" in your package.json file.

Then run command $ node app.js That should run your app and check.

Command to collapse all sections of code?

To collapse all use:

Ctrl + M and Ctrl+A

All shortcuts for VS 2012/2013/2015 available at http://visualstudioshortcuts.com/2013/

Draw a curve with css

@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.

_x000D_
_x000D_
.box {_x000D_
  width: 500px;_x000D_
  height: 100px;_x000D_
  border: solid 5px #000;_x000D_
  border-color: transparent transparent #000 transparent;_x000D_
  border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

Can I set an unlimited length for maxJsonLength in web.config?

if, after implementing the above addition into your web.config, you get an “Unrecognized configuration section system.web.extensions.” error then try adding this to your web.config in the <ConfigSections> section:

            <sectionGroup name="system.web.extensions" type="System.Web.Extensions">
              <sectionGroup name="scripting" type="System.Web.Extensions">
                    <sectionGroup name="webServices" type="System.Web.Extensions">
                          <section name="jsonSerialization" type="System.Web.Extensions"/>
                    </sectionGroup>
              </sectionGroup>
        </sectionGroup>

Unable to execute dex: Multiple dex files define

For me I deleted android-support-v4.jar from lib folder and also removed from build path.

iFrame src change event detection?

Since version 3.0 of Jquery you might get an error

TypeError: url.indexOf is not a function

Which can be easily fix by doing

$('#iframe').on('load', function() {
    alert('frame has (re)loaded ');
});

TSQL DATETIME ISO 8601

Gosh, NO!!! You're asking for a world of hurt if you store formatted dates in SQL Server. Always store your dates and times and one of the SQL Server "date/time" datatypes (DATETIME, DATE, TIME, DATETIME2, whatever). Let the front end code resolve the method of display and only store formatted dates when you're building a staging table to build a file from. If you absolutely must display ISO date/time formats from SQL Server, only do it at display time. I can't emphasize enough... do NOT store formatted dates/times in SQL Server.

{Edit}. The reasons for this are many but the most obvious are that, even with a nice ISO format (which is sortable), all future date calculations and searches (search for all rows in a given month, for example) will require at least an implicit conversion (which takes extra time) and if the stored formatted date isn't the format that you currently need, you'll need to first convert it to a date and then to the format you want.

The same holds true for front end code. If you store a formatted date (which is text), it requires the same gyrations to display the local date format defined either by windows or the app.

My recommendation is to always store the date/time as a DATETIME or other temporal datatype and only format the date at display time.

Searching for Text within Oracle Stored Procedures

 SELECT * FROM ALL_source WHERE UPPER(text) LIKE '%BLAH%'

EDIT Adding additional info:

 SELECT * FROM DBA_source WHERE UPPER(text) LIKE '%BLAH%'

The difference is dba_source will have the text of all stored objects. All_source will have the text of all stored objects accessible by the user performing the query. Oracle Database Reference 11g Release 2 (11.2)

Another difference is that you may not have access to dba_source.

What does !important mean in CSS?

It is used to influence sorting in the CSS cascade when sorting by origin is done. It has nothing to do with specificity like stated here in other answers.

Here is the priority from lowest to highest:

  1. browser styles
  2. user style sheet declarations (without !important)
  3. author style sheet declarations (without !important)
  4. !important author style sheets
  5. !important user style sheets

After that specificity takes place for the rules still having a finger in the pie.

References:

Extract every nth element of a vector

Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:

foo[ c( rep(FALSE, 5), TRUE ) ]

Redefining the Index in a Pandas DataFrame object

If you don't want 'a' in the index

In :

col = ['a','b','c']

data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

data

Out:

    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In :

data2 = data.set_index('a')

Out:

     b   c
a
1    2   3
10  11  12
20  21  22

In :

data2.index.name = None

Out:

     b   c
 1   2   3
10  11  12
20  21  22

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

Swift - How to hide back button in navigation item?

According to the documentation for UINavigationItem :

self.navigationItem.setHidesBackButton(true, animated: true)

regex error - nothing to repeat

regular expression normally uses * and + in theory of language. I encounter the same bug while executing the line code

re.split("*",text)

to solve it, it needs to include \ before * and +

re.split("\*",text)

Hashing a file in Python

import hashlib
user = input("Enter ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
with open("encrypted.txt","w") as e:
    print(h2,file=e)


with open("encrypted.txt","r") as e:
    p = e.readline().strip()
    print(p)

How to handle windows file upload using Selenium WebDriver?

I made use of sendkeys in shell scripting using a vbsscript file. Below is the code in vbs file,

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "C:\Demo.txt"
WshShell.SendKeys "{ENTER}"

Below is the selenium code line to run this vbs file,

driver.findElement(By.id("uploadname1")).click();
Thread.sleep(1000);
Runtime.getRuntime().exec( "wscript C:/script.vbs" );

How can I get CMake to find my alternative Boost installation?

I ran into a similar problem on a Linux server, where two versions of Boost have been installed. One is the precompiled 1.53.0 version which counts as old in 2018; it's in /usr/include and /usr/lib64. The version I want to use is 1.67.0, as a minimum version of 1.65.1 is required for another C++ library I'm installing; it's in /opt/boost, which has include and lib subdirectories. As suggested in previous answers, I set variables in CMakeLists.txt to specify where to look for Boost 1.67.0 as follows

include_directories(/opt/boost/include/)
include_directories(/opt/boost/lib/)
set(BOOST_ROOT /opt/boost/)
set(BOOST_INCLUDEDIR /opt/boost/include/)
set(BOOST_LIBRARYDIR /opt/boost/lib)
set(Boost_NO_SYSTEM_PATHS TRUE)
set(Boost_NO_BOOST_CMAKE TRUE)

But CMake doesn't honor those changes. Then I found an article online: CMake can use a local Boost, and realized that I need to change the variables in CMakeCache.txt. There I found that the Boost-related variables are still pointing to the default Boost 1.53.0, so no wonder CMake doesn't honor my changes in CMakeLists.txt. Then I set the Boost-related variables in CMakeCache.txt

Boost_DIR:PATH=Boost_DIR-NOTFOUND
Boost_INCLUDE_DIR:PATH=/opt/boost/include/
Boost_LIBRARY_DIR_DEBUG:PATH=/opt/boost/lib
Boost_LIBRARY_DIR_RELEASE:PATH=/opt/boost/lib

I also changed the variables pointing to the non-header, compiled parts of the Boost library to point to the version I want. Then CMake successfully built the library that depends on a recent version of Boost.

How do I decompile a .NET EXE into readable C# source code?

Reflector and its add-in FileDisassembler.

Reflector will allow to see the source code. FileDisassembler will allow you to convert it into a VS solution.

How to set a CMake option() at command line

this works for me:

cmake -D DBUILD_SHARED_LIBS=ON DBUILD_STATIC_LIBS=ON DBUILD_TESTS=ON ..

How to get a JavaScript object's class?

Agree with dfa, that's why i consider the prototye as the class when no named class found

Here is an upgraded function of the one posted by Eli Grey, to match my way of mind

function what(obj){
    if(typeof(obj)==="undefined")return "undefined";
    if(obj===null)return "Null";
    var res = Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
    if(res==="Object"){
        res = obj.constructor.name;
        if(typeof(res)!='string' || res.length==0){
            if(obj instanceof jQuery)return "jQuery";// jQuery build stranges Objects
            if(obj instanceof Array)return "Array";// Array prototype is very sneaky
            return "Object";
        }
    }
    return res;
}

Reset select value to default

If you looking to reset, try this simply:

$('element option').removeAttr('selected');

To set desire value, try like this:

$(element).val('1');

Add directives from directive in AngularJS

A simple solution that could work in some cases is to create and $compile a wrapper and then append your original element to it.

Something like...

link: function(scope, elem, attr){
    var wrapper = angular.element('<div tooltip></div>');
    elem.before(wrapper);
    $compile(wrapper)(scope);
    wrapper.append(elem);
}

This solution has the advantage that it keeps things simple by not recompiling the original element.

This wouldn't work if any of the added directive's require any of the original element's directives or if the original element has absolute positioning.

Unicode character for "X" cancel / close?

This works nicely for me:

<style>
a.closeX {
    position: absolute;
    right: 0px; top: 0px; width:20px;
    background-color: #FFF; color: black;
    margin-top:-15px; margin-right:-15px; border-radius: 20px;
    padding-left: 3px; padding-top: 1px;
    cursor:pointer; z-index: -1;
    font-size:16px; font-weight:bold;
}
</style>
<div id="content">
    <a class="closeX" id="closeX" onclick='$("#content").hide();'>&#10006;</a>
    Click "X" to close this box
</div>

How to map atan2() to degrees 0-360

angle = Math.atan2(x,y)*180/Math.PI;

I have made a Formula for orienting angle into 0 to 360

angle + Math.ceil( -angle / 360 ) * 360;

How do I get the row count of a Pandas DataFrame?

You can do this also:

Let’s say df is your dataframe. Then df.shape gives you the shape of your dataframe i.e (row,col)

Thus, assign the below command to get the required

 row = df.shape[0], col = df.shape[1]

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

After struggling with this thing for WAY too long, here is the super easy solution.

My controller was looking for

@RequestBody List<String> ids

and I had the request body as

{
    "ids": [
        "1234",
        "5678"
     ]
}

and the solution was to change the body simply to

["1234", "5678"]

Yup. Just that easy.

BeanFactory not initialized or already closed - call 'refresh' before

This exception come due to you are providing listener ContextLoaderListener

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

but you are not providing context-param for your spring configuration file. like applicationContext.xml You must provide below snippet for your configuration

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>applicationContext.xml</param-value>
</context-param>

If You are providing the java based spring configuration , means you are not using xml file for spring configuration at that time you must provide below code:

<!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<context-param>
    <param-name>contextClass</param-name>
    <param-value>
    org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    </param-value>
</context-param>

<!-- Configuration locations must consist of one or more comma- or space-delimited
fully-qualified @Configuration classes. Fully-qualified packages may also
be specified for component-scanning -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.nirav.modi.config.SpringAppConfig</param-value>
</context-param>

How do I start Mongo DB from Windows?

Download MongoDB Community Server from the link - https://www.mongodb.com/download-center/community

The installation takes some time. Once done, follow these steps to get your server running-

  1. Go to C drive, make a folder named data and inside that create another folder named db.
  2. Now move to directory where monodb server is installed. Go to C:\Program Files\MongoDB\Server(Version)\bin. Copy this file location.
  3. To make it easier to run server in future, press windows key and type environment variables.
  4. You will see an option 'Edit the system environment variables'.
  5. On the lower right corner, you will see a button 'Environment Variables...'. Click that.
  6. Under System variables, double click on path.
  7. Click on new and paste the file location you copied earlier.
  8. Now open cmd, and type mongod.exe (It's a daemon which hosts the server.)
  9. Open another window of cmd and type mongo.exe The connection will be established and you are good to go now.

Thanks for reading. Hope it helps.

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

If you are using Visual Studio 2017, 2019, you can:

  1. open the main .gitignore (update or remove anothers .gitignore files in others projects in the solution)
  2. paste the below code:
[core]
 autocrlf = false
[filter "lfs"]
 required = true
 clean = git-lfs clean -- %f
 smudge = git-lfs smudge -- %f
 process = git-lfs filter-process

MySQL integer field is returned as string in PHP

I like Chad's answer, especially when the query results will be passed on to javascript in a browser. Javascript deals cleanly with numeric like entities as numbers but requires extra work to deal with numeric like entities as strings. i.e. must use parseInt or parseFloat on them.

Building on Chad's solution I use this and it is often exactly what I need and creates structures that can be JSON encoded for easy dealing with in javascript.

while ($row = $result->fetch_assoc()) {
    // convert numeric looking things to numbers for javascript
    foreach ($row as &$val) {
        if (is_numeric($val))
            $val = $val + 0;
    }
}

Adding a numeric string to 0 produces a numeric type in PHP and correctly identifies the type so floating point numbers will not be truncated into integers.

Escape text for HTML

using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);

"Cannot GET /" with Connect on Node.js

You'll see the message Cannot GET / if you don't specify which page it is that you're trying to get, in other words if your URL is something like http://localhost:8180. Make sure you enter a page name, e.g. http://localhost:8180/index.html.

How to check Django version

Python version supported by Django version

Django version        Python versions
----------------------------------------
1.0                   2.3, 2.4, 2.5, 2.6
1.1                   2.3, 2.4, 2.5, 2.6
1.2                   2.4, 2.5, 2.6, 2.7
1.3                   2.4, 2.5, 2.6, 2.7
1.4                   2.5, 2.6, 2.7
1.5                   2.6.5, 2.7 and 3.2.3, 3.3 (experimental)
1.6                   2.6.5, 2.7 and 3.2.3, 3.3
1.11                  2.7, 3.4, 3.5, 3.6, 3.7 (added in 1.11.17)
2.0                   3.4, 3.5, 3.6, 3.7
2.1, 2.2              3.5, 3.6, 3.7

To verify that Django can be seen by Python, type python from your shell. Then at the Python prompt, try to import Django:

>>> import django
>>> print(django.get_version())
2.1
>>> django.VERSION
(2, 1, 4, 'final', 0)

How do I join two lines in vi?

Another way of joining two lines without placing cursor to that line is:

:6,6s#\n##

Here 6 is the line number to which another line will be join. To display the line number, use :set nu.

If we are on the cursor where the next line should be joined, then:

:s#\n##

In both cases we don't need g like :s#\n##g, because on one line only one \n exist.

How do I parse a string into a number with Dart?

 void main(){
  var x = "4";
  int number = int.parse(x);//STRING to INT

  var y = "4.6";
  double doubleNum = double.parse(y);//STRING to DOUBLE

  var z = 55;
  String myStr = z.toString();//INT to STRING
}

int.parse() and double.parse() can throw an error when it couldn't parse the String

Is it possible to run a .NET 4.5 app on XP?

The Mono project dropped Windows XP support and "forgot" to mention it. Although they still claim Windows XP SP2 is the minimum supported version, it is actually Windows Vista.

The last version of Mono to support Windows XP was 3.2.3.

Access Controller method from another controller in Laravel 5

You can access your controller method like this:

app('App\Http\Controllers\PrintReportController')->getPrintReport();

This will work, but it's bad in terms of code organisation (remember to use the right namespace for your PrintReportController)

You can extend the PrintReportController so SubmitPerformanceController will inherit that method

class SubmitPerformanceController extends PrintReportController {
     // ....
}

But this will also inherit all other methods from PrintReportController.

The best approach will be to create a trait (e.g. in app/Traits), implement the logic there and tell your controllers to use it:

trait PrintReport {

    public function getPrintReport() {
        // .....
    }
}

Tell your controllers to use this trait:

class PrintReportController extends Controller {
     use PrintReport;
}

class SubmitPerformanceController extends Controller {
     use PrintReport;
}

Both solutions make SubmitPerformanceController to have getPrintReport method so you can call it with $this->getPrintReport(); from within the controller or directly as a route (if you mapped it in the routes.php)

You can read more about traits here.

Get a list of checked checkboxes in a div using jQuery

This works for me.

var selecteditems = [];

$("#Div").find("input:checked").each(function (i, ob) { 
    selecteditems.push($(ob).val());
});

Duplicate and rename Xcode project & associated folders

I'm posting this since I have always been struggling when renaming a project in XCode.

Renaming the project is good and simple but this doesn't rename the source folder. Here is a step by step of what I have done that worked great in Xcode 4 and 5 thanks to the links below.

REF links:
Rename Project.
Rename Source Folder and other files.

1- Backup your project.

If you are using git, commit any changes, make a copy of the entire project folder and backup in time machine before making any changes (this step is not required but I highly recommended).

2- Open your project.

3- Slow double click or hit enter on the Project name (blue top icon) and rename it to whatever you like.

NOTE: After you rename the project and press ‘enter’ it will suggest to automatically change all project-name-related entries and will allow you to de-select some of them if you want. Select all of them and click ok.

4- Rename the Scheme

a) Click the menu right next to the stop button and select Manage Schemes.

b) Single-slow-click or hit enter on the old name scheme and rename it to whatever you like.

c) Click ok.

5 - Build and run to make sure it works.

NOTES: At this point all of the important project files should be renamed except the comments in the classes created when the project was created nor the source folder. Next we will rename the folder in the file system.

6- Close the project.

7- Rename the main and the source folder.

8- Right click the project bundle .xcodeproj file and select “Show Package Contents” from the context menu. Open the .pbxproj file with any text editor.

9- Search and replace any occurrence of the original folder name with the new folder name.

10- Save the file.

11- Open XCode project, test it.

12- Done.

EDIT 10/11/19:

There is a tool to rename projects in Xcode I haven't tried it enough to comment on it. https://github.com/appculture/xcode-project-renamer

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

Why does CSS not support negative padding?

You asked WHY, not how to cheat it:

Usually because of laziness of programmers of the initial implementation, because they HAVE already put way more effort in other features, delivering more odd side-effects like floats, because they were more requested by designers back then and yet they haven't taken the time to allow this so we can use the FOUR properties to push/pull an element against its neighbors (now we only have four to push, and only 2 to pull).

When html was designed, magazines loved text reflown around images back then, now hated because today we have touch trends, and love squary things with lots of space and nothing to read. That's why they put more pressure on floats than on centering, or they could have designed something like margin-top: fill; or margin: average 0; to simply align the content to the bottom, or distribute its extra space around.

In this case I think it hasn't been implemented because of the same reason that makes CSS to lack of a :parent pseudo-selector: To prevent looping evaluations.

Without being an engineer, I can see that CSS right now is made to paint elements once, remember some properties for future elements to be painted, but NEVER going back to already-painted elements.

That's why (I guess) padding is calculated on the width, because that's the value that was available at the time of starting to paint it.

If you had a negative value for padding, it would affect the outer limits, which has ALREADY been defined when the margin has already been set. I know, nothing has been painted yet, but when you read how the painting process goes, created by geniuses with 90's technology, I feel like I am asking dumb questions and just say "thanks" hehe.

One of the requirements of web pages is that they are quickly available, unlike an app that can take its time and eat the computer resources to get everything correct before displaying it, web pages need to use little resources (so they are fit in every device possible) and be scrolled in a breeze.

If you see applications with complex reflowing and positioning, like InDesign, you can't scroll that fast! It takes a big effort both from processors and graphic card to jump to next pages!

So painting and calculating forward and forgetting about an element once drawn, for now it seems to be a MUST.

How to save select query results within temporary table?

select *
into #TempTable
from SomeTale

select *
from #TempTable

How to install the JDK on Ubuntu Linux

In case you have already downloaded the ZIP file follow these steps.

Run the following command to unzip your file.

tar -xvf ~/Downloads/jdk-7u3-linux-i586.tar.gz
sudo mkdir -p /usr/lib/jvm/jdk1.7.0
sudo mv jdk1.7.0_03/* /usr/lib/jvm/jdk1.7.0/
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1

After installation is complete, set environment variables as follows.

Edit the system path in file /etc/profile:

sudo gedit /etc/profile

Add the following lines at the end.

JAVA_HOME=/usr/lib/jvm/jdk1.7.0
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export PATH

Source: http://javaandme.com/

htaccess redirect if URL contains a certain string

If url contains a certen string, redirect to index.php . You need to match against the %{REQUEST_URI} variable to check if the url contains a certen string.

To redirect example.com/foo/bar to /index.php if the uri contains bar anywhere in the uri string , you can use this :

RewriteEngine on

RewriteCond %{REQUEST_URI} bar
RewriteRule ^ /index.php [L,R]

Possible to iterate backwards through a foreach?

I have used this code which worked

                if (element.HasAttributes) {

                    foreach(var attr in element.Attributes().Reverse())
                    {

                        if (depth > 1)
                        {
                            elements_upper_hierarchy_text = "";
                            foreach (var ancest  in element.Ancestors().Reverse())
                            {
                                elements_upper_hierarchy_text += ancest.Name + "_";
                            }// foreach(var ancest  in element.Ancestors())

                        }//if (depth > 1)
                        xml_taglist_report += " " + depth  + " " + elements_upper_hierarchy_text+ element.Name + "_" + attr.Name +"(" + attr.Name +")" + "   =   " + attr.Value + "\r\n";
                    }// foreach(var attr in element.Attributes().Reverse())

                }// if (element.HasAttributes) {

Change one value based on another value in pandas

One option is to use Python's slicing and indexing features to logically evaluate the places where your condition holds and overwrite the data there.

Assuming you can load your data directly into pandas with pandas.read_csv then the following code might be helpful for you.

import pandas
df = pandas.read_csv("test.csv")
df.loc[df.ID == 103, 'FirstName'] = "Matt"
df.loc[df.ID == 103, 'LastName'] = "Jones"

As mentioned in the comments, you can also do the assignment to both columns in one shot:

df.loc[df.ID == 103, ['FirstName', 'LastName']] = 'Matt', 'Jones'

Note that you'll need pandas version 0.11 or newer to make use of loc for overwrite assignment operations.


Another way to do it is to use what is called chained assignment. The behavior of this is less stable and so it is not considered the best solution (it is explicitly discouraged in the docs), but it is useful to know about:

import pandas
df = pandas.read_csv("test.csv")
df['FirstName'][df.ID == 103] = "Matt"
df['LastName'][df.ID == 103] = "Jones"

fatal: Not a valid object name: 'master'

You need to commit at least one time on master before creating a new branch.

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

In addition to the missing @Injectable() decorator

Missing @Injectable() decorator in abstract class produced the Can't resolve all parameters for service: (?) The decorator needs be present in MyService as well as in the derived class BaseService

//abstract class
@Injectable()
abstract class BaseService { ... }

//MyService    
@Injectable()
export class MyService extends BaseService {
.....
}

Getting around the Max String size in a vba function?

This works and shows more than 255 characters in the message box.

Sub TestStrLength()
    Dim s As String
    Dim i As Integer

    s = ""
    For i = 1 To 500
        s = s & "1234567890"
    Next i

    MsgBox s
End Sub

The message box truncates the string to 1023 characters, but the string itself can be very large.

I would also recommend that instead of using fixed variables names with numbers (e.g. Var1, Var2, Var3, ... Var255) that you use an array. This is much shorter declaration and easier to use - loops.

Here's an example:

Sub StrArray()
Dim var(256) As Integer
Dim i As Integer
Dim s As String

For i = 1 To 256
    var(i) = i
Next i

s = "Tims_pet_Robot"
For i = 1 To 256
    s = s & " """ & var(i) & """"
Next i

    SecondSub (s)
End Sub

Sub SecondSub(s As String)
    MsgBox "String length = " & Len(s)
End Sub

Updated this to show that a string can be longer than 255 characters and used in a subroutine/function as a parameter that way. This shows that the string length is 1443 characters. The actual limit in VBA is 2GB per string.

Perhaps there is instead a problem with the API that you are using and that has a limit to the string (such as a fixed length string). The issue is not with VBA itself.

Ok, I see the problem is specifically with the Application.OnTime method itself. It is behaving like Excel functions in that they only accept strings that are up to 255 characters in length. VBA procedures and functions though do not have this limit as I have shown. Perhaps then this limit is imposed for any built-in Excel object method.


Update:
changed ...longer than 256 characters... to ...longer than 255 characters...

Changing Fonts Size in Matlab Plots

Jonas's answer does not change the font size of the axes. Sergeyf's answer does not work when there are multiple subplots.

Here is a modification of their answers that works for me when I have multiple subplots:

set(findall(gcf,'type','axes'),'fontsize',30)
set(findall(gcf,'type','text'),'fontSize',30) 

When to use IMG vs. CSS background-image?

Foreground = img.

Background = CSS background.

How to get the last row of an Oracle a table

You can do it like this:

SELECT * FROM (SELECT your_table.your_field, versions_starttime
               FROM your_table
               VERSIONS BETWEEN TIMESTAMP MINVALUE AND MAXVALUE)
WHERE ROWNUM = 1;

Or:

SELECT your_field,ora_rowscn,scn_to_timestamp(ora_rowscn) from your_table WHERE ROWNUM = 1;

Bootstrap: Open Another Modal in Modal

data-dismiss makes the current modal window force close

data-toggle opens up a new modal with the href content inside it

<a data-dismiss="modal" data-toggle="modal" href="#lost">Click</a>

or

<a data-dismiss="modal" onclick="call the new div here">Click</a>

do let us know if it works.

How to pass parameters to maven build using pom.xml?

We can Supply parameter in different way after some search I found some useful

<plugin>
  <artifactId>${release.artifactId}</artifactId>
  <version>${release.version}-${release.svm.version}</version>...

...

Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .

While Running build we need supply value for those parameter as follows.

RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74

Here I am supplying

release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74

It worked for me. Thanks

How to send HTTP request in java?

Apache HttpComponents. The examples for the two modules - HttpCore and HttpClient will get you started right away.

Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away. I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code. By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc.

Using async/await with a forEach loop

The p-iteration module on npm implements the Array iteration methods so they can be used in a very straightforward way with async/await.

An example with your case:

const { forEach } = require('p-iteration');
const fs = require('fs-promise');

(async function printFiles () {
  const files = await getFilePaths();

  await forEach(files, async (file) => {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  });
})();

Parse usable Street Address, City, State, Zip from a string

This won't solve your problem, but if you only needed lat/long data for these addresses, the Google Maps API will parse non-formatted addresses pretty well.

Good suggestion, alternatively you can execute a CURL request for each address to Google Maps and it will return the properly formatted address. From that, you can regex to your heart's content.

mysql_fetch_array() expects parameter 1 to be resource problem

Make sure that your query ran successfully and you got the results. You can check like this:

$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']) or die(mysql_error());


if (is_resource($result))
{
   // your while loop and fetch array function here....
}

AngularJS - Animate ng-view transitions

I'm not sure about a way to do it directly with AngularJS but you could set the display to none for both welcome and login and animate the opacity with an directive once they are loaded.

I would do it some way like so. 2 Directives for fading in the content and fading it out when a link is clicked. The directive for fadeouts could simply animate a element with an unique ID or call a service which broadcasts the fadeout

Template:

<div class="tmplWrapper" onLoadFadeIn>
    <a href="somewhere/else" fadeOut>
</div>

Directives:

angular
  .directive('onLoadFadeIn', ['Fading', function('Fading') {
    return function(scope, element, attrs) {
      $(element).animate(...);
      scope.$on('fading', function() {
    $(element).animate(...);
      });
    }
  }])
  .directive('fadeOut', function() {
    return function(scope, element, attrs) {
      element.bind('fadeOut', function(e) {
    Fading.fadeOut(e.target);
  });
    }
  });

Service:

angular.factory('Fading', function() {
  var news;
  news.setActiveUnit = function() {
    $rootScope.$broadcast('fadeOut');
  };
  return news;
})

I just have put together this code quickly so there may be some bugs :)

Correct way to use get_or_create?

Following @Tobu answer and @mipadi comment, in a more pythonic way, if not interested in the created flag, I would use:

customer.source, _ = Source.objects.get_or_create(name="Website")

Calculate age given the birth date in the format YYYYMMDD

With momentjs "fromNow" method, This allows you to work with formatted date, ie: 03/15/1968

var dob = document.getElementByID("dob"); var age = moment(dob.value).fromNow(true).replace(" years", "");

//fromNow(true) => suffix "ago" is not displayed //but we still have to get rid of "years";

As a prototype version

String.prototype.getAge = function() {
return moment(this.valueOf()).fromNow(true).replace(" years", "");

}

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

Importing modules from parent folder

same sort of style as the past answer - but in fewer lines :P

import os,sys
parentdir = os.path.dirname(__file__)
sys.path.insert(0,parentdir)

file returns the location you are working in

Entity Framework Timeouts

For Entity framework 6 I use this annotation and works fine.

  public partial class MyDbContext : DbContext
  {
      private const int TimeoutDuration = 300;

      public MyDbContext ()
          : base("name=Model1")
      {
          this.Database.CommandTimeout = TimeoutDuration;
      }
       // Some other codes
    }

The CommandTimeout parameter is a nullable integer that set timeout values as seconds, if you set null or don't set it will use default value of provider you use.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I was face same problem when I am going to delete my record than some issue was occur , for this issue solution is that when you are going to delete your record than you missing some thing before deleting header/master record you must write to code for delete its detail before header/Master I hope you issue will be resolve.

Why do I get access denied to data folder when using adb?

This works if your Android device is rooted by any means (not sure if it works for non-rooted).

  1. adb shell - access the shell
  2. su - become the superuser.

You can now read all files in all directories.

What is the simplest C# function to parse a JSON string into an object?

I think this is what you want:

JavaScriptSerializer JSS = new JavaScriptSerializer();
T obj = JSS.Deserialize<T>(String);

How to save a BufferedImage as a File

  1. Download and add imgscalr-lib-x.x.jar and imgscalr-lib-x.x-javadoc.jar to your Projects Libraries.
  2. In your code:

    import static org.imgscalr.Scalr.*;
    
    public static BufferedImage resizeBufferedImage(BufferedImage image, Scalr.Method scalrMethod, Scalr.Mode scalrMode, int width, int height)  {
        BufferedImage bi = image;
        bi = resize( image, scalrMethod, scalrMode, width, height);
    return bi;
    }
    
    // Save image:
    ImageIO.write(Scalr.resize(etotBImage, 150), "jpg", new File(myDir));
    

How to write an XPath query to match two attributes?

Sample XML:

<X>
<Y ATTRIB1=attrib1_value ATTRIB2=attrib2_value/>
</X>

string xPath="/" + X + "/" + Y +
"[@" + ATTRIB1 + "='" + attrib1_value + "']" +
"[@" + ATTRIB2 + "='" + attrib2_value + "']"

XPath Testbed: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

Preprocessing in scikit learn - single sample - Depreciation warning

I faced the same issue and got the same deprecation warning. I was using a numpy array of [23, 276] when I got the message. I tried reshaping it as per the warning and end up in nowhere. Then I select each row from the numpy array (as I was iterating over it anyway) and assigned it to a list variable. It worked then without any warning.

array = []
array.append(temp[0])

Then you can use the python list object (here 'array') as an input to sk-learn functions. Not the most efficient solution, but worked for me.

Gradients on UIView and UILabels On iPhone

You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).

Add multiple items to a list

Code check:

This is offtopic here but the people over at CodeReview are more than happy to help you.

I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.

Lists:

As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List.

Lists are very straightforward to use but take a look at the related documentation anyway.

A very simple example to keep multiple bikes in a list:

List<Motorbike> bikes = new List<Motorbike>();

bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });

And to iterate over the list you can use the foreach statement:

foreach(var bike in bikes) {
     Console.WriteLine(bike.make);
}

Convert file: Uri to File in Android

After searching for a long time this is what worked for me:

File file = new File(getPath(uri));


public String getPath(Uri uri) 
    {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) return null;
        int column_index =             cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String s=cursor.getString(column_index);
        cursor.close();
        return s;
    }

Unable to use Intellij with a generated sources folder

I'm using Maven (SpringBoot application) solution is:

  1. Right click project folder
  2. Select Maven
  3. Select Generate Sources And Update Folders

Then, Intellij automatically import generated sources to project.

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

How to run Gradle from the command line on Mac bash

./gradlew

Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

Concatenate String in String Objective-c

Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:

@"first" @"second"

And it will result in:

@"firstsecond"

You can not use it with NSString objects, only with literals, but it can be useful in some cases.

How do I select an element in jQuery by using a variable for the ID?

Doing $('body').find(); is not necessary when looking up by ID; there is no performance gain.

Please also note that having an ID that starts with a number is not valid HTML:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Disposing WPF User Controls

An UserControl has a Destructor, why don't you use that?

~MyWpfControl()
    {
        // Dispose of any Disposable items here
    }

How do I print out the contents of a vector?

Here is a working library, presented as a complete working program, that I just hacked together:

#include <set>
#include <vector>
#include <iostream>

#include <boost/utility/enable_if.hpp>

// Default delimiters
template <class C> struct Delims { static const char *delim[3]; };
template <class C> const char *Delims<C>::delim[3]={"[", ", ", "]"};
// Special delimiters for sets.                                                                                                             
template <typename T> struct Delims< std::set<T> > { static const char *delim[3]; };
template <typename T> const char *Delims< std::set<T> >::delim[3]={"{", ", ", "}"};

template <class C> struct IsContainer { enum { value = false }; };
template <typename T> struct IsContainer< std::vector<T> > { enum { value = true }; };
template <typename T> struct IsContainer< std::set<T>    > { enum { value = true }; };

template <class C>
typename boost::enable_if<IsContainer<C>, std::ostream&>::type
operator<<(std::ostream & o, const C & x)
{
  o << Delims<C>::delim[0];
  for (typename C::const_iterator i = x.begin(); i != x.end(); ++i)
    {
      if (i != x.begin()) o << Delims<C>::delim[1];
      o << *i;
    }
  o << Delims<C>::delim[2];
  return o;
}

template <typename T> struct IsChar { enum { value = false }; };
template <> struct IsChar<char> { enum { value = true }; };

template <typename T, int N>
typename boost::disable_if<IsChar<T>, std::ostream&>::type
operator<<(std::ostream & o, const T (&x)[N])
{
  o << "[";
  for (int i = 0; i != N; ++i)
    {
      if (i) o << ",";
      o << x[i];
    }
  o << "]";
  return o;
}

int main()
{
  std::vector<int> i;
  i.push_back(23);
  i.push_back(34);

  std::set<std::string> j;
  j.insert("hello");
  j.insert("world");

  double k[] = { 1.1, 2.2, M_PI, -1.0/123.0 };

  std::cout << i << "\n" << j << "\n" << k << "\n";
}

It currently only works with vector and set, but can be made to work with most containers, just by expanding on the IsContainer specializations. I haven't thought much about whether this code is minimal, but I can't immediately think of anything I could strip out as redundant.

EDIT: Just for kicks, I included a version that handles arrays. I had to exclude char arrays to avoid further ambiguities; it might still get into trouble with wchar_t[].

how to get selected row value in the KendoUI

One way is to use the Grid's select() and dataItem() methods.

In single selection case, select() will return a single row which can be passed to dataItem()

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
// selectedItem has EntityVersionId and the rest of your model

For multiple row selection select() will return an array of rows. You can then iterate through the array and the individual rows can be passed into the grid's dataItem().

var entityGrid = $("#EntitesGrid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function(index, row) {
  var selectedItem = entityGrid.dataItem(row);
  // selectedItem has EntityVersionId and the rest of your model
});

IIS7 Permissions Overview - ApplicationPoolIdentity

ApplicationPoolIdentity is actually the best practice to use in IIS7+. It is a dynamically created, unprivileged account. To add file system security for a particular application pool see IIS.net's "Application Pool Identities". The quick version:

If the application pool is named "DefaultAppPool" (just replace this text below if it is named differently)

  1. Open Windows Explorer
  2. Select a file or directory.
  3. Right click the file and select "Properties"
  4. Select the "Security" tab
  5. Click the "Edit" and then "Add" button
  6. Click the "Locations" button and make sure you select the local machine. (Not the Windows domain if the server belongs to one.)
  7. Enter "IIS AppPool\DefaultAppPool" in the "Enter the object names to select:" text box. (Don't forget to change "DefaultAppPool" here to whatever you named your application pool.)
  8. Click the "Check Names" button and click "OK".

Docker is in volume in use, but there aren't any Docker containers

Currently you can use what docker offers now for a general and more complete cleaning:

docker system prune

To additionally remove any stopped containers and all unused images (not just dangling images), add the -a flag to the command:

docker system prune -a

Converting between java.time.LocalDateTime and java.util.Date

Much more convenient way if you are sure you need a default timezone :

Date d = java.sql.Timestamp.valueOf( myLocalDateTime );

Jquery, checking if a value exists in array or not

If you want to do it using .map() or just want to know how it works you can do it like this:

var added=false;
$.map(arr, function(elementOfArray, indexInArray) {
 if (elementOfArray.id == productID) {
   elementOfArray.price = productPrice;
   added = true;
 }
}
if (!added) {
  arr.push({id: productID, price: productPrice})
}

The function handles each element separately. The .inArray() proposed in other answers is probably the more efficient way to do it.

Returning value from Thread

If you want the value from the calling method, then it should wait for the thread to finish, which makes using threads a bit pointless.

To directly answer you question, the value can be stored in any mutable object both the calling method and the thread both have a reference to. You could use the outer this, but that isn't going to be particularly useful other than for trivial examples.

A little note on the code in the question: Extending Thread is usually poor style. Indeed extending classes unnecessarily is a bad idea. I notice you run method is synchronised for some reason. Now as the object in this case is the Thread you may interfere with whatever Thread uses its lock for (in the reference implementation, something to do with join, IIRC).

Split Java String by New Line

In JDK11 the String class has a lines() method:

Returning a stream of lines extracted from this string, separated by line terminators.

Further, the documentation goes on to say:

A line terminator is one of the following: a line feed character "\n" (U+000A), a carriage return character "\r" (U+000D), or a carriage return followed immediately by a line feed "\r\n" (U+000D U+000A). A line is either a sequence of zero or more characters followed by a line terminator, or it is a sequence of one or more characters followed by the end of the string. A line does not include the line terminator.

With this one can simply do:

Stream<String> stream = str.lines();

then if you want an array:

String[] array = str.lines().toArray(String[]::new);

Given this method returns a Stream it upon up a lot of options for you as it enables one to write concise and declarative expression of possibly-parallel operations.

VS 2017 Git Local Commit DB.lock error on every commit

VS 2017 Git Local Commit DB.lock error on every commit

This issue must have been caused by a corrupt .ignore file.

If your IDE is Visual Studio please follow these steps to resolve this issue:

  1. Delete the .gitignore file from your project folder
  2. Go to Team Explorer
  3. Go to Home in Team Explorer
  4. Go to Settings
  5. Under GIT, Click Repository Settings
  6. Under - Ignore & Attributes Files - Under Ignore File - Click Add. You should see a notification that the Ignore File has been successfully created
  7. Build your solution. It will take a little while and create a new .ignore file once build is successful
  8. You should now be able to Commit and Push without any further issue

NB: Bear in mind that your version of visual studio might place these options differently. I am using Visual Studio 2019 Community Edition.

docker error - 'name is already in use by container'

Ok, so I didn't understand either, then I left my pc, went to do other things, and upon my return, it clicked :D

  1. You download a docker image file. docker pull *image-name* will just pull the image from docker hub without running it.

  2. Now, you use docker run, and give it a name (e.g. newWebServer).

    docker run -d -p 8080:8080 -v volume --name newWebServer image-name/version

You perhaps only need docker run --name *name* *image*, but the other stuff will become useful quickly.

-d (detached) - means the container will exit when the root process used to run the container exits.

-p (port) - specify the container port and the host port. Kind of the internal and external port. The internal one being the port the container uses, and the external one is the port you use outside of it and probably the one you need to put in your web browser if that's how you access your app.

--name (what you want to call this instance of the container) - you could have several instances of the same container all with different names, which is useful when you're trying to test something.

image-name/version is the actual image you want to create the container from. You can see a list of all the images on your system with docker images -a. You may have more than one version, so make sure you choose the correct one/tag.

-v (volume) - perhaps not needed initially, but soon you'll want to persist data after your container exits.

OK. So now, docker run just created a container from your image. If it isn't running, you can now start it with it's name:

docker start newWebServer

You can check all your containers (they may or may not be running) with

docker ps -a

You can stop and start them (or pause them) with their name or the container id (or just the first few characters of it) from the CONTAINER ID column e.g:

docker stop newWebServer

docker start c3028a89462c

And list all your images, with

docker images -a

In a nutshell, download an image; docker run creates a container from it; start it with docker start (name or container id); stop it with docker stop (name or container id).

Renaming part of a filename

Something like this will do it. The for loop may need to be modified depending on which filenames you wish to capture.

for fspec1 in DET01-ABC-5_50-*.dat ; do
    fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
    mv ${fspec1} ${fspec2}
done

You should always test these scripts on copies of your data, by the way, and in totally different directories.

Get values from other sheet using VBA

That will be (for you very specific example)

ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value=someval

OR

someVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value

So get a F1 click and read about Worksheets collection, which contains Worksheet objects, which in turn has a Cells collection, holding Cell objects...

cannot convert data (type interface {}) to type string: need type assertion

As asked for by @??s???? an explanation can be found at https://golang.org/pkg/fmt/#Sprint. Related explanations can be found at https://stackoverflow.com/a/44027953/12817546 and at https://stackoverflow.com/a/42302709/12817546. Here is @Yuanbo's answer in full.

package main

import "fmt"

func main() {
    var data interface{} = 2
    str := fmt.Sprint(data)
    fmt.Println(str)
}

Text overflow ellipsis on two lines

It seems more elegant combining two classes. You can drop two-lines class if only one row need see:

_x000D_
_x000D_
.ellipse {_x000D_
          white-space: nowrap;_x000D_
          display:inline-block;_x000D_
          overflow: hidden;_x000D_
          text-overflow: ellipsis;_x000D_
       }_x000D_
      .two-lines {_x000D_
          -webkit-line-clamp: 2;_x000D_
          display: -webkit-box;_x000D_
          -webkit-box-orient: vertical;_x000D_
          white-space: normal;_x000D_
      }_x000D_
      .width{_x000D_
          width:100px;_x000D_
          border:1px solid hotpink;_x000D_
      }
_x000D_
        <span class='width ellipse'>_x000D_
          some texts some texts some texts some texts some texts some texts some texts_x000D_
       </span>_x000D_
_x000D_
       <span class='width ellipse two-lines'>_x000D_
          some texts some texts some texts some texts some texts some texts some texts_x000D_
       </span>
_x000D_
_x000D_
_x000D_