Programs & Examples On #Output redirect

Store an array in HashMap

Your life will be much easier if you can save a List as the value instead of an array in that Map.

SSIS cannot convert because a potential loss of data

When you first set up this package, I am guessing that either a one or two digit number was the first value in the ShipTo column. Your package reading from the Excel picked a numeric type for that input field and the word "ALL" fails the package since the input spec for that field is numeric. There are several ways to fix this beforehand, but to fix it after the fact, the easiest way is to right click the Excel Source and choose Show Advanced Editor... From there, choose the tab that says Input and Output Properties. In the topmost part of the inputs and outputs section of that dialog box, find the column ShipTo. You will have to drill down to find it. Set the DataType to "string [DT_STR]" and the length to 20.

Click OK then attempt to run your package again.

How to convert JSON object to JavaScript array?

As simple as this !

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);

Python: Remove division decimal

if val % 1 == 0:
    val = int(val)

else:
    val = float(val)

This worked for me.

How it works: if the remainder of the quotient of val and 1 is 0, val has to be an integer and can, therefore, be declared to be int without having to worry about losing decimal numbers.

Compare these two situations:

A:

val = 12.00

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)

In this scenario, the output is 12, because 12.00 divided by 1 has the remainder of 0. With this information we know, that val doesn't have any decimals and we can declare val to be int.

B:

val = 13.58

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)

This time the output is 13.58, because when val is divided by 1 there is a remainder (0.58) and therefore val is declared to be a float.

By just declaring the number to be an int (without testing the remainder) decimal numbers will be cut off.

This way there are no zeros in the end and no other than the zeros will be ignored.

How to get only numeric column values?

The other answers indicating using IsNumeric in the where clause are correct, as far as they go, but it's important to remember that it returns 1 if the value can be converted to any numeric type. As such, oddities such as "1d3" will make it through the filter.

If you need only values composed of digits, search for that explicitly:

SELECT column1 FROM table WHERE column1 not like '%[^0-9]%'

The above is filtering to reject any column which contains a non-digit character

Note that in any case, you're going to incur a table scan, indexes are useless for this sort of query.

How can bcrypt have built-in salts?

To make things even more clearer,

Registeration/Login direction ->

The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt:

$2a$COST$BASE64

This value is stored eventually.

What the attacker would need to do in order to find the password ? (other direction <- )

In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random. Then he will need to decrypt the cipher text.

What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

Get the short Git version hash

A really simple way is to:

git describe --always

Cannot install Aptana Studio 3.6 on Windows

I have some issue, the fix is:

  1. Uninstall any nodejs version.
  2. Install https://nodejs.org/dist/v0.10.36/x64/node-v0.10.36-x64.msi.
  3. Install Aptana.
  4. Code...

greetings!

MySQL Multiple Joins in one query?

Multi joins in SQL work by progressively creating derived tables one after the other. See this link explaining the process:

https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/

jQuery get the location of an element relative to window

TL;DR

headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();

headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe

.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.

use of entityManager.createNativeQuery(query,foo.class)

Suppose your query is "select id,name from users where rollNo = 1001".

Here query will return a object with id and name column. Your Response class is like bellow:

public class UserObject{
        int id;
        String name;
        String rollNo;

        public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

here UserObject constructor will get a Object Array and set data with object.

public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

Your query executing function is like bellow :

public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {

        String queryStr = "select id,name from users where rollNo = ?1";
        try {
            Query query = entityManager.createNativeQuery(queryStr);
            query.setParameter(1, rollNo);

            return new UserObject((Object[]) query.getSingleResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

Here you have to import bellow packages:

import javax.persistence.Query;
import javax.persistence.EntityManager;

Now your main class, you have to call this function. First you have to get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:

@PersistenceContext
private EntityManager entityManager;

UserObject userObject = getUserByRoll(entityManager,"1001");

Now you have data in this userObject.

Here is Imports

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

Note:

query.getSingleResult() return a array. You have to maintain the column position and data type.

select id,name from users where rollNo = ?1 

query return a array and it's [0] --> id and [1] -> name.

For more info, visit this Answer

Thanks :)

While variable is not defined - wait

With Ecma Script 2017 You can use async-await and while together to do that And while will not crash or lock the program even variable never be true

_x000D_
_x000D_
//First define some delay function which is called from async function_x000D_
function __delay__(timer) {_x000D_
    return new Promise(resolve => {_x000D_
        timer = timer || 2000;_x000D_
        setTimeout(function () {_x000D_
            resolve();_x000D_
        }, timer);_x000D_
    });_x000D_
};_x000D_
_x000D_
//Then Declare Some Variable Global or In Scope_x000D_
//Depends on you_x000D_
let Variable = false;_x000D_
_x000D_
//And define what ever you want with async fuction_x000D_
async function some() {_x000D_
    while (!Variable)_x000D_
        await __delay__(1000);_x000D_
_x000D_
    //...code here because when Variable = true this function will_x000D_
};_x000D_
////////////////////////////////////////////////////////////_x000D_
//In Your Case_x000D_
//1.Define Global Variable For Check Statement_x000D_
//2.Convert function to async like below_x000D_
_x000D_
var isContinue = false;_x000D_
setTimeout(async function () {_x000D_
    //STOPT THE FUNCTION UNTIL CONDITION IS CORRECT_x000D_
    while (!isContinue)_x000D_
        await __delay__(1000);_x000D_
_x000D_
    //WHEN CONDITION IS CORRECT THEN TRIGGER WILL CLICKED_x000D_
    $('a.play').trigger("click");_x000D_
}, 1);_x000D_
/////////////////////////////////////////////////////////////
_x000D_
_x000D_
_x000D_

Also you don't have to use setTimeout in this case just make ready function asynchronous...

How to deserialize a list using GSON or another JSON library in Java?

Another way is to use an array as a type, e.g.:

Video[] videoArray = gson.fromJson(json, Video[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list, e.g.:

List<Video> videoList = Arrays.asList(videoArray);

IMHO this is much more readable.


In Kotlin this looks like this:

Gson().fromJson(jsonString, Array<Video>::class.java)

To convert this array into List, just use .toList() method

Getting the first and last day of a month, using a given DateTime object

DateTime dCalcDate = DateTime.Now;
var startDate = new DateTime(Convert.ToInt32(Year), Convert.ToInt32(Month), 1);
var endDate = new DateTime(Convert.ToInt32(Year), Convert.ToInt32(Month), DateTime.DaysInMonth((Convert.ToInt32(Year)), Convert.ToInt32(Month)));

PHP: Get key from array?

Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)

Android Layout Right Align

If you want to use LinearLayout, you can do alignment with layout_weight with Space element.

E.g. following layout places textView and textView2 next to each other and textView3 will be right-aligned

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView2" />

    <Space
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="20dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView3" />
</LinearLayout>

you can achieve the same effect without Space if you would set layout_weight to textView2. It's just that I like things more separated, plus to demonstrate Space element.

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView2" />

Note that you should (not must though) set layout_width explicitly as it will be recalculated according to it's weight anyway (same way you should set height in elements of vertical LinearLayout). For other layout performance tips see Android Layout Tricks series.

HTML embed autoplay="false", but still plays automatically

None of the video settings posted above worked in modern browsers I tested (like Firefox) using the embed or object elements in HTML5. For video or audio elements they did stop autoplay. For embed and object they did not.

I tested this using the embed and object elements using several different media types as well as HTML attributes (like autostart and autoplay). These videos always played regardless of any combination of settings in several browsers. Again, this was not an issue using the newer HTML5 video or audio elements, just when using embed and object.

It turns out the new browser settings for video "autoplay" have changed. Firefox will now ignore the autoplay attributes on these tags and play videos anyway unless you explicitly set to "block audio and video" autoplay in your browser settings.

To do this in Firefox I have posted the settings below:

  1. Open up your Firefox Browser, click the menu button, and select "Options"
  2. Select the "Privacy & Security" panel and scroll down to the "Permissions" section
  3. Find "Autoplay" and click the "Settings" button. In the dropdown change it to block audio and video. The default is just audio.

Your videos will NOT autoplay now when displaying videos in web pages using object or embed elements.

How to restart a rails server on Heroku?

heroku ps:restart [web|worker] --app app_name

works for all processes declared in your Procfile. So if you have multiple web processes or worker processes, each labeled with a number, you can selectively restart one of them:

heroku ps:restart web.2 --app app_name
heroku ps:restart worker.3 --app app_name

Android - Using Custom Font

The most simple solution android supported now!

Use custom font in xml:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/[your font resource]"/>

look details:

https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html

Retrieving Data from SQL Using pyodbc

Upvoted answer din't work for me, It was fixed by editing connection line as follows(replace semicolons with coma and also remove those quotes):

import pyodbc
cnxn = pyodbc.connect(DRIVER='{SQL Server}',SERVER=SQLSRV01,DATABASE=DATABASE,UID=USER,PWD=PASSWORD)
cursor = cnxn.cursor()

cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")
for row in cursor.fetchall():
    print row

How to strip HTML tags from a string in SQL Server?

Here is a version that doesn't require an UDF and works even if the HTML contains tags without matching closing tags.

TRY_CAST(REPLACE(REPLACE(REPLACE([HtmlCol], '>', '/> '), '</', '<'), '--/>', '-->') AS XML).value('.', 'NVARCHAR(MAX)')

Convert Unix timestamp to a date string

Python:

python -c "from datetime import datetime; print(datetime.fromtimestamp($TIMESTAMP))"

Re-sign IPA (iPhone)

None of these resigning approaches were working for me, so I had to work out something else.

In my case, I had an IPA with an expired certificate. I could have rebuilt the app, but because we wanted to ensure we were distributing exactly the same version (just with a new certificate), we did not want to rebuild it.

Instead of the ways of resigning mentioned in the other answers, I turned to Xcode’s method of creating an IPA, which starts with an .xcarchive from a build.

  1. I duplicated an existing .xcarchive and started replacing the contents. (I ignored the .dSYM file.)

  2. I extracted the old app from the old IPA file (via unzipping; the app is the only thing in the Payload folder)

  3. I moved this app into the new .xcarchive, under Products/Applications replacing the app that was there.

  4. I edited Info.plist, editing

    • ApplicationProperties/ApplicationPath
    • ApplicationProperties/CFBundleIdentifier
    • ApplicationProperties/CFBundleShortVersionString
    • ApplicationProperties/CFBundleVersion
    • Name
  5. I moved the .xcarchive into Xcode’s archive folder, usually /Users/xxxx/Library/Developer/Xcode/Archives.

  6. In Xcode, I opened the Organiser window, picked this new archive and did a regular (in this case Enterprise) export.

The result was a good IPA that works.

Remove scrollbar from iframe

Add scrolling="no" attribute to the iframe.

Clicking a button within a form causes page refresh

You should declare the attribute ng-submit={expression} in your <form> tag.

From the ngSubmit docs http://docs.angularjs.org/api/ng.directive:ngSubmit

Enables binding angular expressions to onsubmit events.

Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page).

react-router getting this.props.location in child components

If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';


Using this you can export your child class as -

class MyApp extends Component{
    // your code
}

export default withRouter(MyApp);

And your class with Router -

// your code
<Router>
      ...
      <Route path="/myapp" component={MyApp} />
      // or if you are sending additional fields
      <Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>

creating charts with angularjs

I've seen some nice AngularJS charting solutions that make use of Highcharts. There's a highcharts-ng directive on GitHub to make AngularJS integration easier, and some examples on JSFiddle to give you a quick taste of what's possible.

You set up the chart on the JS side like this:

$scope.chart = {
    options: {
        chart: {
            type: 'bar'
        }
    },
    series: [{
        data: [10, 15, 12, 8, 7]
    }],
    title: {
        text: 'Hello'
    },
    loading: false
}

And then refer to it in the HTML like this:

<highchart id="chart1" config="chart"></highchart>

Usage/licensing warning: Highcharts is available for free under the Creative Commons license for non-commercial use. If you're looking for charting options in a for-profit/commercial scenario, you'll need to buy the product or look elsewhere.

ArrayAdapter in android to create simple listview

You don't need to use id for textview. You can learn more from android arrayadapter. The below code initializes the arrayadapter.

ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.single_item, eatables);

How do I make curl ignore the proxy?

I have http_proxy and https_proxy are defined. I don't want to unset and set again those environments but --noproxy '*' works perfectly for me.

curl --noproxy '*' -XGET 172.17.0.2:9200
{
  "status" : 200,
  "name" : "Medusa",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "1.5.0",
    "build_hash" : "544816042d40151d3ce4ba4f95399d7860dc2e92",
    "build_timestamp" : "2015-03-23T14:30:58Z",
    "build_snapshot" : false,
    "lucene_version" : "4.10.4"
  },
  "tagline" : "You Know, for Search"
}

Best way to handle list.index(might-not-exist) in python?

This issue is one of language philosophy. In Java for example there has always been a tradition that exceptions should really only be used in "exceptional circumstances" that is when errors have happened, rather than for flow control. In the beginning this was for performance reasons as Java exceptions were slow but now this has become the accepted style.

In contrast Python has always used exceptions to indicate normal program flow, like raising a ValueError as we are discussing here. There is nothing "dirty" about this in Python style and there are many more where that came from. An even more common example is StopIteration exception which is raised by an iterator‘s next() method to signal that there are no further values.

How to concat two ArrayLists?

for a lightweight list that does not copy the entries, you may use sth like this:

List<Object> mergedList = new ConcatList<>(list1, list2);

here the implementation:

public class ConcatList<E> extends AbstractList<E> {

    private final List<E> list1;
    private final List<E> list2;

    public ConcatList(final List<E> list1, final List<E> list2) {
        this.list1 = list1;
        this.list2 = list2;
    }

    @Override
    public E get(final int index) {
        return getList(index).get(getListIndex(index));
    }

    @Override
    public E set(final int index, final E element) {
        return getList(index).set(getListIndex(index), element);
    }

    @Override
    public void add(final int index, final E element) {
        getList(index).add(getListIndex(index), element);
    }

    @Override
    public E remove(final int index) {
        return getList(index).remove(getListIndex(index));
    }

    @Override
    public int size() {
        return list1.size() + list2.size();
    }

    @Override
    public void clear() {
        list1.clear();
        list2.clear();
    }

    private int getListIndex(final int index) {
        final int size1 = list1.size();
        return index >= size1 ? index - size1 : index;
    }

    private List<E> getList(final int index) {
        return index >= list1.size() ? list2 : list1;
    }

}

FtpWebRequest Download File

I know this is an old Post but I am adding here for future reference. Here is a solution that I found:

    private void DownloadFileFTP()
    {
        string inputfilepath = @"C:\Temp\FileName.exe";
        string ftphost = "xxx.xx.x.xxx";
        string ftpfilepath = "/Updater/Dir1/FileName.exe";

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;

        using (WebClient request = new WebClient())
        {
            request.Credentials = new NetworkCredential("UserName", "P@55w0rd");
            byte[] fileData = request.DownloadData(ftpfullpath);

            using (FileStream file = File.Create(inputfilepath))
            {
                file.Write(fileData, 0, fileData.Length);
                file.Close();
            }
            MessageBox.Show("Download Complete");
        }
    }

Updated based upon excellent suggestion by Ilya Kogan

Can I automatically increment the file build version when using Visual Studio?

As of right now, for my application,

string ver = Application.ProductVersion;

returns ver = 1.0.3251.27860

The value 3251 is the number of days since 1/1/2000. I use it to put a version creation date on the splash screen of my application. When dealing with a user, I can ask the creation date which is easier to communicate than some long number.

(I'm a one-man dept supporting a small company. This approach may not work for you.)

How to override !important?

Okay here is a quick lesson about CSS Importance. I hope that the below helps!

First of all the every part of the styles name as a weighting, so the more elements you have that relate to that style the more important it is. For example

#P1 .Page {height:100px;}

is more important than:

.Page {height:100px;}

So when using important, ideally this should only ever be used, when really really needed. So to overide the decleration, make the style more specific, but also with an override. See below:

td {width:100px !important;}
table tr td .override {width:150px !important;}

I hope this helps!!!

Oracle - how to remove white spaces?

Say, we have a column with values consisting of alphanumeric characters and underscore only. We need to trim this column off all spaces, tabs or whatever white characters. The below example will solve the problem. The trimmed one and the original one both are being displayed for comparison. select '/'||REGEXP_REPLACE(my_column,'[^A-Z,^0-9,^_]','')||'/' my_column,'/'||my_column||'/' from my_table;

How to convert java.lang.Object to ArrayList?

You can create a util method that converts any collection to a java list

public static List<?> convertObjectToList(Object obj) {
    List<?> list = new ArrayList<>();
    if (obj.getClass().isArray()) {
        list = Arrays.asList((Object[])obj);
    } else if (obj instanceof Collection) {
        list = new ArrayList<>((Collection<?>)obj);
    }
    return list;
}

you can also mix with this validation below:

public static boolean isCollection(Object obj) {
  return obj.getClass().isArray() || obj instanceof Collection;
}

javax.persistence.NoResultException: No entity found for query

When using java 8, you may take advantage of stream API and simplify code to

return (YourEntityClass) entityManager.createQuery()
....
.getResultList()
.stream().findFirst();

That will give you java.util.Optional

If you prefer null instead, all you need is

 ...
.getResultList()
.stream().findFirst().orElse(null);

How to disable Hyper-V in command line?

Open command prompt as admin and write :

bcdedit /set hypervisorlaunchtype off

SQL "IF", "BEGIN", "END", "END IF"?

The only time the second insert into @clases should fail to fire is if an error occurred in the first insert statement.

If that's the case, then you need to decide if the second statement should run prior to the first OR if you need a transaction in order to perform a rollback.

Configure WAMP server to send email

Install Fake Sendmail (download sendmail.zip). Then configure C:\wamp\sendmail\sendmail.ini:

smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password

The above will work against a Gmail account. And then configure php.ini:

sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

Now, restart Apache, and that is basically all you need to do.

How to get all count of mongoose model?

The code below works. Note the use of countDocuments.

 var mongoose = require('mongoose');
 var db = mongoose.connect('mongodb://localhost/myApp');
 var userSchema = new mongoose.Schema({name:String,password:String});
 var userModel =db.model('userlists',userSchema);
 var anand = new userModel({ name: 'anand', password: 'abcd'});
 anand.save(function (err, docs) {
   if (err) {
       console.log('Error');
   } else {
       userModel.countDocuments({name: 'anand'}, function(err, c) {
           console.log('Count is ' + c);
      });
   }
 }); 

How to Validate Google reCaptcha on Form Submit

If you want to check if the User clicked on the I'm not a robot checkbox, you can use the .getResponse() function provided by the reCaptcha API.

It will return an empty string in case the User did not validate himself, something like this:

if (grecaptcha.getResponse() == ""){
    alert("You can't proceed!");
} else {
    alert("Thank you");
}

In case the User has validated himself, the response will be a very long string.

More about the API can be found on this page: reCaptcha Javascript API

How can I print the contents of a hash in Perl?

Data::Dumper is your friend.

use Data::Dumper;
my %hash = ('abc' => 123, 'def' => [4,5,6]);
print Dumper(\%hash);

will output

$VAR1 = {
          'def' => [
                     4,
                     5,
                     6
                   ],
          'abc' => 123
        };

Pretty-print an entire Pandas Series / DataFrame

Using pd.options.display

This answer is a variation of the prior answer by lucidyan. It makes the code more readable by avoiding the use of set_option.

After importing pandas, as an alternative to using the context manager, set such options for displaying large dataframes:

def set_pandas_display_options() -> None:
    """Set pandas display options."""
    # Ref: https://stackoverflow.com/a/52432757/
    display = pd.options.display

    display.max_columns = 1000
    display.max_rows = 1000
    display.max_colwidth = 199
    display.width = None
    # display.precision = 2  # set as needed

set_pandas_display_options()

After this, you can use either display(df) or just df if using a notebook, otherwise print(df).

Using to_string

Pandas 0.25.3 does have DataFrame.to_string and Series.to_string methods which accept formatting options.

Using to_markdown

If what you need is markdown output, Pandas 1.0.0 has DataFrame.to_markdown and Series.to_markdown methods.

Using to_html

If what you need is HTML output, Pandas 0.25.3 does have a DataFrame.to_html method but not a Series.to_html. Note that a Series can be converted to a DataFrame.

Python spacing and aligning strings

You can use expandtabs to specify the tabstop, like this:

>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))
#Output:
Location:10-10-10-10          Revision: 1
District: Tower               Date: May 16, 2012

Make a dictionary in Python from input values

This is what we ended up using:

n = 3
d = dict(raw_input().split() for _ in range(n))
print d

Input:

A1023 CRT
A1029 Regulator
A1030 Therm

Output:

{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

"continue" in cursor.forEach()

Each iteration of the forEach() will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return from the function at the appropriate point:

elementsCollection.forEach(function(element){
  if (!element.shouldBeProcessed)
    return; // stop processing this iteration

  // This part will be avoided if not neccessary
  doSomeLengthyOperation();
});

Safely remove migration In Laravel

I accidentally created two times create_users_table. It overrided some classes and turned rollback into ErrorException.

What you need to do is find autoload_classmap.php in vendor/composer folder and look for the specific line of code such as

'CreateUsersTable' => $baseDir . '/app/database/migrations/2013_07_04_014051_create_users_table.php',

and edit path. Then your rollback should be fine.

In Angular, how do you determine the active route?

start with importing RouterLinkActive in your .ts

import { RouterLinkActive } from '@angular/router';

Now use RouterLinkActive in your HTML

<span class="" routerLink ="/some_path" routerLinkActive="class_Name">Value</span></a>

provide some css to class "class_Name" , as when this link will be active/clicked you will find this class on span while inspection.

Vue.js : How to set a unique ID for each component instance?

If your uid is not used by other compoment, I have an idea.

uid: Math.random()

Simple and enough.

Check if enum exists in Java

I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:

public static MyEnum asMyEnum(String str) {
    for (MyEnum me : MyEnum.values()) {
        if (me.name().equalsIgnoreCase(str))
            return me;
    }
    return null;
}

Edit: As Jon Skeet notes, values() works by cloning a private backing array every time it is called. If performance is critical, you may want to call values() only once, cache the array, and iterate through that.

Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration.

What encoding/code page is cmd.exe using?

Type

chcp

to see your current code page (as Dewfy already said).

Use

nlsinfo

to see all installed code pages and find out what your code page number means.

You need to have Windows Server 2003 Resource kit installed (works on Windows XP) to use nlsinfo.

Remove columns from DataTable in C#

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

Why extend the Android Application class?

Introduction:

enter image description here

  1. If we consider an apk file in our mobile, it is comprised of multiple useful blocks such as, Activitys, Services and others.
  2. These components do not communicate with each other regularly and not forget they have their own life cycle. which indicate that they may be active at one time and inactive the other moment.

Requirements:

  1. Sometimes we may require a scenario where we need to access a variable and its states across the entire Application regardless of the Activity the user is using,
  2. An example is that a user might need to access a variable that holds his personnel information (e.g. name) that has to be accessed across the Application,
  3. We can use SQLite but creating a Cursor and closing it again and again is not good on performance,
  4. We could use Intents to pass the data but it's clumsy and activity itself may not exist at a certain scenario depending on the memory-availability.

Uses of Application Class:

  1. Access to variables across the Application,
  2. You can use the Application to start certain things like analytics etc. since the application class is started before Activitys or Servicess are being run,
  3. There is an overridden method called onConfigurationChanged() that is triggered when the application configuration is changed (horizontal to vertical & vice-versa),
  4. There is also an event called onLowMemory() that is triggered when the Android device is low on memory.

How to generate a create table script for an existing table in phpmyadmin?

One more way. Select the target table in the left panel in phpMyAdmin, click on Export tab, unselect Data block and click on Go button.

MySQL "Or" Condition

try this

mysql_query("
SELECT * FROM Drinks WHERE
    email='$Email'
    AND date='$Date_Today'
    OR date='$Date_Yesterday', '$Date_TwoDaysAgo', '$Date_ThreeDaysAgo', '$Date_FourDaysAgo', '$Date_FiveDaysAgo', '$Date_SixDaysAgo', '$Date_SevenDaysAgo'"     
   );

my be like this

 OR date='$Date_Yesterday' oR '$Date_TwoDaysAgo'.........

jQuery $("#radioButton").change(...) not firing during de-selection

Looks like the change() function is only called when you check a radio button, not when you uncheck it. The solution I used is to bind the change event to every radio button:

$("#r1, #r2, #r3").change(function () {

Or you could give all the radio buttons the same name:

$("input[name=someRadioGroup]:radio").change(function () {

Here's a working jsfiddle example (updated from Chris Porter's comment.)

Per @Ray's comment, you should avoid using names with . in them. Those names work in jQuery 1.7.2 but not in other versions (jsfiddle example.).

TextFX menu is missing in Notepad++

Plugins -> Plugin Manager -> Show Plugin Manager -> Setting -> Check mark On Force HTTP instead of HTTPS for downloading Plugin List & Use development plugin list (may contain untested, unvalidated or un-installable plugins). -> OK.

Get and Set a Single Cookie with Node.js HTTP Server

As an enhancement to @Corey Hart's answer, I've rewritten the parseCookies() using:

Here's the working example:

let http = require('http');

function parseCookies(str) {
  let rx = /([^;=\s]*)=([^;]*)/g;
  let obj = { };
  for ( let m ; m = rx.exec(str) ; )
    obj[ m[1] ] = decodeURIComponent( m[2] );
  return obj;
}

function stringifyCookies(cookies) {
  return Object.entries( cookies )
    .map( ([k,v]) => k + '=' + encodeURIComponent(v) )
    .join( '; ');
}

http.createServer(function ( request, response ) {
  let cookies = parseCookies( request.headers.cookie );
  console.log( 'Input cookies: ', cookies );
  cookies.search = 'google';
  if ( cookies.counter )
    cookies.counter++;
  else
    cookies.counter = 1;
  console.log( 'Output cookies: ', cookies );
  response.writeHead( 200, {
    'Set-Cookie': stringifyCookies(cookies),
    'Content-Type': 'text/plain'
  } );
  response.end('Hello World\n');
} ).listen(1234);

I also note that the OP uses the http module. If the OP was using restify, he can make use of restify-cookies:

var CookieParser = require('restify-cookies');
var Restify = require('restify');
var server = Restify.createServer();
server.use(CookieParser.parse);
server.get('/', function(req, res, next){
  var cookies = req.cookies; // Gets read-only cookies from the request
  res.setCookie('my-new-cookie', 'Hi There'); // Adds a new cookie to the response
  res.send(JSON.stringify(cookies));
});
server.listen(8080);

Error: Cannot find module 'ejs'

Install express locally

(npm install express while in the project's root directory)


Your project depends on both express and ejs, so you should list them both as dependencies in your package.json.

That way when you run npm install in you project directory, it'll install both express and ejs, so that var express = require('express') will be the local installation of express (which knows about the ejs module that you installed locally) rather than the global one, which doesn't.

In general it's a good idea to explicitly list all dependencies in your package.json even though some of them might already be globally installed, so you don't have these types of issues.

git: can't push (unpacker error) related to permission issues

I was having trouble with this too, thinking my remote gitolite-admin was corrupted or something wrong.

My setup is Mac OS X (10.6.6) laptop with remote Ubuntu 10 server with gitolite.

It turned out that the problem was with my local checkout of gitolite-admin.

Despite the "unpack failed" error, it turned out the the problem was local.

I figured this out by checking it out again as gitolite-admin2, making a change, and the pushing.

Voila! It worked!

Best way to script remote SSH commands in Batch (Windows)

As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run

Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.

Then you can create an ssh batch script such as

ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.

SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF

REM ------------------------------
REM SSH Server details
REM ------------------------------

:WEB1
CLS
call ssh [email protected]
cmd /k

:WEB2
CLS
call ssh [email protected]
cmd /k

Can we open pdf file using UIWebView on iOS?

Swift version:

if let docPath = NSBundle.mainBundle().pathForResource("sample", ofType: "pdf") {
    let docURL = NSURL(fileURLWithPath: docPath)
    webView.loadRequest(NSURLRequest(URL: docURL))
}

Find all table names with column name?

Try Like This: For SQL SERVER 2008+

SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyColumnaName%'

Or

SELECT COLUMN_NAME, TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE COLUMN_NAME LIKE '%MyName%'

Or Something Like This:

SELECT name  
FROM sys.tables 
WHERE OBJECT_ID IN ( SELECT id 
              FROM syscolumns 
              WHERE name like '%COlName%' )

How to trigger event in JavaScript?

HTML

<a href="demoLink" id="myLink"> myLink </a>
<button onclick="fireLink(event)"> Call My Link </button>

JS

// click event listener of the link element --------------  
document.getElementById('myLink').addEventListener("click", callLink);
function callLink(e) {
    // code to fire
}

// function invoked by the button element ----------------
function fireLink(event) {                   
    document.getElementById('myLink').click();      // script calls the "click" event of the link element 
}

Change a Git remote HEAD to point to something besides master

If you have access to the remote repo from a shell, just go into the .git (or the main dir if its a bare repo) and change the HEAD file to point to the correct head. For example, by default it always contains 'refs: refs/heads/master', but if you need foo to be the HEAD instead, just edit the HEAD file and change the contents to 'refs: refs/heads/foo'.

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

How do I make a composite key with SQL Server Management Studio?

create table my_table (
    id_part1 int not null,
    id_part2 int not null,
    primary key (id_part1, id_part2)
)

How to write :hover condition for a:before and a:after?

Try to use .card-listing:hover::after hover and after using :: it wil work

How to run Java program in command prompt

You can use javac *.java command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.

What are the differences between NP, NP-Complete and NP-Hard?

This is a very informal answer to the question asked.

Can 3233 be written as the product of two other numbers bigger than 1? Is there any way to walk a path around all of the Seven Bridges of Königsberg without taking any bridge twice? These are examples of questions that share a common trait. It may not be obvious how to efficiently determine the answer, but if the answer is 'yes', then there's a short and quick to check proof. In the first case a non-trivial factorization of 51; in the second, a route for walking the bridges (fitting the constraints).

A decision problem is a collection of questions with yes or no answers that vary only in one parameter. Say the problem COMPOSITE={"Is n composite": n is an integer} or EULERPATH={"Does the graph G have an Euler path?": G is a finite graph}.

Now, some decision problems lend themselves to efficient, if not obvious algorithms. Euler discovered an efficient algorithm for problems like the "Seven Bridges of Königsberg" over 250 years ago.

On the other hand, for many decision problems, it's not obvious how to get the answer -- but if you know some additional piece of information, it's obvious how to go about proving you've got the answer right. COMPOSITE is like this: Trial division is the obvious algorithm, and it's slow: to factor a 10 digit number, you have to try something like 100,000 possible divisors. But if, for example, somebody told you that 61 is a divisor of 3233, simple long division is a efficient way to see that they're correct.

The complexity class NP is the class of decision problems where the 'yes' answers have short to state, quick to check proofs. Like COMPOSITE. One important point is that this definition doesn't say anything about how hard the problem is. If you have a correct, efficient way to solve a decision problem, just writing down the steps in the solution is proof enough.

Algorithms research continues, and new clever algorithms are created all the time. A problem you might not know how to solve efficiently today may turn out to have an efficient (if not obvious) solution tomorrow. In fact, it took researchers until 2002 to find an efficient solution to COMPOSITE! With all these advances, one really has to wonder: Is this bit about having short proofs just an illusion? Maybe every decision problem that lends itself to efficient proofs has an efficient solution? Nobody knows.

Perhaps the biggest contribution to this field came with the discovery a peculiar class of NP problems. By playing around with circuit models for computation, Stephen Cook found a decision problem of the NP variety that was provably as hard or harder than every other NP problem. An efficient solution for the boolean satisfiability problem could be used to create an efficient solution to any other problem in NP. Soon after, Richard Karp showed that a number of other decision problems could serve the same purpose. These problems, in a sense the "hardest" problems in NP, became known as NP-complete problems.

Of course, NP is only a class of decision problems. Many problems aren't naturally stated in this manner: "find the factors of N", "find the shortest path in the graph G that visits every vertex", "give a set of variable assignments that makes the following boolean expression true". Though one may informally talk about some such problems being "in NP", technically that doesn't make much sense -- they're not decision problems. Some of these problems might even have the same sort of power as an NP-complete problem: an efficient solution to these (non-decision) problems would lead directly to an efficient solution to any NP problem. A problem like this is called NP-hard.

Pyspark: Filter dataframe based on multiple conditions

faster way (without pyspark.sql.functions)

    df.filter((df.d<5)&((df.col1 != df.col3) |
                    (df.col2 != df.col4) & 
                    (df.col1 ==df.col3)))\
    .show()

`col-xs-*` not working in Bootstrap 4

They dropped XS because Bootstrap is considered a mobile-first development tool. It's default is considered xs and so doesn't need to be defined.

Using iText to convert HTML to PDF

The easiest way of doing this is using pdfHTML. It's an iText7 add-on that converts HTML5 (+CSS3) into pdf syntax.

The code is pretty straightforward:

    HtmlConverter.convertToPdf(
        "<b>This text should be written in bold.</b>",       // html to be converted
        new PdfWriter(
            new File("C://users/mark/documents/output.pdf")  // destination file
        )
    );

To learn more, go to http://itextpdf.com/itext7/pdfHTML

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

Multiplication on command line terminal

Yes, you can use bash's built-in Arithmetic Expansion $(( )) to do some simple maths

$ echo "$((5 * 5))"
25

Check the Shell Arithmetic section in the Bash Reference Manual for a complete list of operators.

For sake of completeness, as other pointed out, if you need arbitrary precision, bc or dc would be better.

Task continuation on UI thread

With async you just do:

await Task.Run(() => do some stuff);
// continue doing stuff on the same context as before.
// while it is the default it is nice to be explicit about it with:
await Task.Run(() => do some stuff).ConfigureAwait(true);

However:

await Task.Run(() => do some stuff).ConfigureAwait(false);
// continue doing stuff on the same thread as the task finished on.

How to SELECT based on value of another SELECT

SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
FROM tbl t
INNER JOIN 
(SELECT name, SUM(value) as summary
FROM tbl
WHERE year BETWEEN 2000 AND 2001
GROUP BY name) x ON x.name = t.name
GROUP BY x.name, x.summary

How to pass data from Javascript to PHP and vice versa?

Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.

An example (using traditional event registration model for simplicity):

<!-- headers etc. omitted -->
<script>
function callPHP(params) {
    var httpc = new XMLHttpRequest(); // simplified for clarity
    var url = "get_data.php";
    httpc.open("POST", url, true); // sending as POST

    httpc.onreadystatechange = function() { //Call a function when the state changes.
        if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
            alert(httpc.responseText); // some processing here, or whatever you want to do with the response
        }
    };
    httpc.send(params);
}
</script>
<a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a>
<!-- rest of document omitted -->

Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)

See also Mozilla's documentation for further examples

How do I reflect over the members of dynamic object?

There are several scenarios to consider. First of all, you need to check the type of your object. You can simply call GetType() for this. If the type does not implement IDynamicMetaObjectProvider, then you can use reflection same as for any other object. Something like:

var propertyInfo = test.GetType().GetProperties();

However, for IDynamicMetaObjectProvider implementations, the simple reflection doesn't work. Basically, you need to know more about this object. If it is ExpandoObject (which is one of the IDynamicMetaObjectProvider implementations), you can use the answer provided by itowlson. ExpandoObject stores its properties in a dictionary and you can simply cast your dynamic object to a dictionary.

If it's DynamicObject (another IDynamicMetaObjectProvider implementation), then you need to use whatever methods this DynamicObject exposes. DynamicObject isn't required to actually "store" its list of properties anywhere. For example, it might do something like this (I'm reusing an example from my blog post):

public class SampleObject : DynamicObject
{
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = binder.Name;
        return true;
    }
}

In this case, whenever you try to access a property (with any given name), the object simply returns the name of the property as a string.

dynamic obj = new SampleObject();
Console.WriteLine(obj.SampleProperty);
//Prints "SampleProperty".

So, you don't have anything to reflect over - this object doesn't have any properties, and at the same time all valid property names will work.

I'd say for IDynamicMetaObjectProvider implementations, you need to filter on known implementations where you can get a list of properties, such as ExpandoObject, and ignore (or throw an exception) for the rest.

The server committed a protocol violation. Section=ResponseStatusLine ERROR

My problem was that I called https endpoint with http.

Simple http post example in Objective-C?

 NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"name" forKey:@"email"];
[contentDictionary setValue:@"name" forKey:@"username"];
[contentDictionary setValue:@"name" forKey:@"password"];
[contentDictionary setValue:@"name" forKey:@"firstName"];
[contentDictionary setValue:@"name" forKey:@"lastName"];

NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);

NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

Good tool to visualise database schema?

Have you tried the arrange > auto arrange function in MySQL Workbench. It may save you from manually moving the tables around.

DLL Load Library - Error Code 126

Windows dll error 126 can have many root causes. The most useful methods I have found to debug this are:

  1. Use dependency walker to look for any obvious problems (which you have already done)
  2. Use the sysinternals utility Process Monitor http://technet.microsoft.com/en-us/sysinternals/bb896645 from Microsoft to trace all file access while your dll is trying to load. With this utility, you will see everything that that dll is trying to pull in and usually the problem can be determined from there.

mongodb: insert if not exists

Summary

  • You have an existing collection of records.
  • You have a set records that contain updates to the existing records.
  • Some of the updates don't really update anything, they duplicate what you have already.
  • All updates contain the same fields that are there already, just possibly different values.
  • You want to track when a record was last changed, where a value actually changed.

Note, I'm presuming PyMongo, change to suit your language of choice.

Instructions:

  1. Create the collection with an index with unique=true so you don't get duplicate records.

  2. Iterate over your input records, creating batches of them of 15,000 records or so. For each record in the batch, create a dict consisting of the data you want to insert, presuming each one is going to be a new record. Add the 'created' and 'updated' timestamps to these. Issue this as a batch insert command with the 'ContinueOnError' flag=true, so the insert of everything else happens even if there's a duplicate key in there (which it sounds like there will be). THIS WILL HAPPEN VERY FAST. Bulk inserts rock, I've gotten 15k/second performance levels. Further notes on ContinueOnError, see http://docs.mongodb.org/manual/core/write-operations/

    Record inserts happen VERY fast, so you'll be done with those inserts in no time. Now, it's time to update the relevant records. Do this with a batch retrieval, much faster than one at a time.

  3. Iterate over all your input records again, creating batches of 15K or so. Extract out the keys (best if there's one key, but can't be helped if there isn't). Retrieve this bunch of records from Mongo with a db.collectionNameBlah.find({ field : { $in : [ 1, 2,3 ...}) query. For each of these records, determine if there's an update, and if so, issue the update, including updating the 'updated' timestamp.

    Unfortunately, we should note, MongoDB 2.4 and below do NOT include a bulk update operation. They're working on that.

Key Optimization Points:

  • The inserts will vastly speed up your operations in bulk.
  • Retrieving records en masse will speed things up, too.
  • Individual updates are the only possible route now, but 10Gen is working on it. Presumably, this will be in 2.6, though I'm not sure if it will be finished by then, there's a lot of stuff to do (I've been following their Jira system).

Google drive limit number of download

Sorry, you can't view or download this file at this time is an error message that you may get when you try to download files on Google Drive.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB

The explanation for the error message is simple: while users are free to share files publicly, or with a large number of users, quotas are in effect that limit availability.

If too many users view or download a file, it may be locked for a 24 hour period before the quota is reset. The period that a file is locked may be shorter according to Google.

If a file is particularly popular, it may take days or even longer before you manage to download it to your computer or place it on your Drive storage.

It could be a solution:

  1. Locate the "uc" part of the address, and replace it with "open", so that the beginning of the URL reads * https:// drive.google.com/open?*

  2. Load the address again once you have replaced uc with open in the address.

  3. This loads a new screen with controls at the top.

  4. Click on the "add to my drive" icon at the top right.

  5. Click on "add to my drive" again to open your Google Drive storage in a new tab in the browser.

  6. You should see the locked file on your drive now.

  7. Select it with a right-click, and then the "make a copy" option from the menu.

    8.Select the copy of the file with a right-click, and there download to download the file to your local system.

Basically, what this does is create a copy of the file on your own Drive account. Since you are the owner of the copied file, you may download it to your local system this way.

Please note that this works only if you are signed in to a Google Account. Also note that you are the owner of the copied file and will be held responsible for policy violations or other issues linked to the file.

Another option is: Any public folder in Drive can host files and provide direct links to the files.

How to create the hosting URL: https:// googledrive.com/host/FolderID (your id file)

This will provide a folder that will give direct links to files inside the folder. Note: hosting view will not display files created in Google Docs.

My solution:

I had the same problem, so I made a JSON file in Google Drive but the URL file (.mp3) is in Dropbox. It is working fantastic even though I have 40,000 active user. I used this solution because I did not have time to search too much! I wrote you the Dropbox Limits anyway but I did not get problems with it

Traffic limits DROPBOX

Links and file requests are automatically banned if they generate unusually large amounts of traffic.

Dropbox Basic (free) accounts:

20 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned 100,000 downloads per day: The total number of downloads that all of your links combined can generate

Dropbox Plus and Business accounts: About 200 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned There's no daily limit to the number of downloads that your links can generate If your account hits our limit, we'll send a message to the email address registered to your account. Your links will be temporarily disabled, and anyone who tries to access them will see an error page instead of your files.

P.S. If you need more information about my files and how did it and How to make the URL File from Dropbox, I hope help to the people is reading this! (I posted it before but Someone deleted my last post)!

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new "row" only when the values indicate the need to do so...

The only difference is that in the Group By there are additional "columns" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did...

Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns)

How do I remove the blue styling of telephone numbers on iPhone/iOS?

In case people find this question on Google, all you need to do is treat the telephone number as a link as Apple will automatically set it as one.

your HTML

<p id="phone-text">Call us on <strong>+44 (0)20 7194 8000</strong></p>

your css

#phone-text a{color:#fff; text-decoration:none;}

How do I convert a pandas Series or index to a Numpy array?

Since pandas v0.13 you can also use get_values:

df.index.get_values()

Bootstrap datepicker hide after selection

$('yourpickerid').datetimepicker({
           pickTime: false
}).on('changeDate', function (e) {
           $(this).datetimepicker('hide');
});

Replace last occurrence of character in string

Keep it simple

var someString = "a_b_c";
var newCharacter = "+";

var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

Java: Calling a super method which calls an overridden method

Since the only way to avoid a method to get overriden is to use the keyword super, I've thought to move up the method2() from SuperClass to another new Base class and then call it from SuperClass:

class Base 
{
    public void method2()
    {
        System.out.println("superclass method2");
    }
}

class SuperClass extends Base
{
    public void method1()
    {
        System.out.println("superclass method1");
        super.method2();
    }
}

class SubClass extends SuperClass
{
    @Override
    public void method1()
    {
        System.out.println("subclass method1");
        super.method1();
    }

    @Override
    public void method2()
    {
        System.out.println("subclass method2");
    }
}

public class Demo 
{
    public static void main(String[] args) 
    {
        SubClass mSubClass = new SubClass();
        mSubClass.method1();
    }
}

Output:

subclass method1
superclass method1
superclass method2

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.

The SQL*Plus® User's Guide and Reference gives an example:

sqlplus hr@\"sales-server:1521/sales.us.acme.com\"

Pay attention to two important points:

  1. The connection identifier is quoted. You have two options:
    1. You can use SQL*Plus CONNECT command and simply pass quoted string.
    2. If you want to specify connection parameters on the command line then you must add backslashes as shields before quotes. It instructs the bash to pass quotes into SQL*Plus.
  2. The service name must be specified in FQDN-form as it configured by your DBA.

I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:

SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

position fixed is not working

This might be an old topic but in my case it was the layout value of css contain property of the parent element that was causing the issue. I am using a framework for hybrid mobile that use this contain property in most of their component.

For example:

.parentEl {
    contain: size style layout;
}
.parentEl .childEl {
    position: fixed;
    top: 0;
    left: 0;
}

Just remove the layout value of contain property and the fixed content should work!

.parentEl {
    contain: size style;
}

How do I kill the process currently using a port on localhost in Windows?

Here is a script to do it in WSL2

PIDS=$(cmd.exe /c netstat -ano | cmd.exe /c findstr :$1 | awk '{print $5}')
for pid in $PIDS
do
    cmd.exe /c taskkill /PID $pid /F
done

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

This should work

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

and moreover please let us know why are you importing all these class

<%@ page import="com.library.controller.*"%> 
<%@ page import="com.library.dao.*" %> 
<%@ page import="java.util.*" %> 
<%@ page import="java.lang.*" %> 
<%@ page import="java.util.Date" %>

We don't need to include java.lang as it is the default package.

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

Utilizing multi core for tar+gzip/bzip compression/decompression

You can also use the tar flag "--use-compress-program=" to tell tar what compression program to use.

For example use:

tar -c --use-compress-program=pigz -f tar.file dir_to_zip 

Query comparing dates in SQL

please try with below query

select id,numbers_from,created_date,amount_numbers,SMS_text 
from Test_Table
where 
convert(datetime, convert(varchar(10), created_date, 102))  <= convert(datetime,'2013-04-12')

How can you undo the last git add?

You can use

git reset

to undo the recently added local files

 git reset file_name

to undo the changes for a specific file

Why is "npm install" really slow?

I was having this problem and none of the solutions in SO helped. I figured it out so I am posting it here in case any one else has a similar issue.

I was trying to run npm i on an amazon instance. The problem ended up being the fact that linux only opens up a certain amount of ports, and when npm i runs, it opens like more than a thousand connects to the registry to download all the packages. So it would work but then just freeze for like 15 minutes. Then the timeout would occur and it would eventually move on to another port. So in my security group in AWS I added a rule for All TCP at 0.0.0.0/0 in outgoing only, letting npm open as many outgoing connections as it likes and that fixed it.

How does internationalization work in JavaScript?

Localization support in legacy browsers is poor. Originally, this was due to phrases in the ECMAScript language spec that look like this:

Number.prototype.toLocaleString()
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment’s current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.

Every localization method defined in the spec is defined as "implementation-dependent", which results in a lot of inconsistencies. In this instance, Chrome Opera and Safari would return the same thing as .toString(). Firefox and IE will return locale formatted strings, and IE even includes a thousand separator (perfect for currency strings). Chrome was recently updated to return a thousands-separated string, though with no fixed decimal.

For modern environments, the ECMAScript Internationalization API spec, a new standard that complements the ECMAScript Language spec, provides much better support for string comparison, number formatting, and the date and time formatting; it also fixes the corresponding functions in the Language Spec. An introduction can be found here. Implementations are available in:

  • Chrome 24
  • Firefox 29
  • Internet Explorer 11
  • Opera 15

There is also a compatibility implementation, Intl.js, which will provide the API in environments where it doesn't already exist.

Determining the user's preferred language remains a problem since there's no specification for obtaining the current language. Each browser implements a method to obtain a language string, but this could be based on the user's operating system language or just the language of the browser:

// navigator.userLanguage for IE, navigator.language for others
var lang = navigator.language || navigator.userLanguage;

A good workaround for this is to dump the Accept-Language header from the server to the client. If formatted as a JavaScript, it can be passed to the Internationalization API constructors, which will automatically pick the best (or first-supported) locale.

In short, you have to put in a lot of the work yourself, or use a framework/library, because you cannot rely on the browser to do it for you.

Various libraries and plugins for localization:

  • Others:

Feel free to add/edit.

Is it possible to install another version of Python to Virtualenv?

This procedure installs Python2.7 anywhere and eliminates any absolute path references within your env folder (managed by virtualenv). Even virtualenv isn't installed absolutely.

Thus, theoretically, you can drop the top level directory into a tarball, distribute, and run anything configured within the tarball on a machine that doesn't have Python (or any dependencies) installed.

Contact me with any questions. This is just part of an ongoing, larger project I am engineering. Now, for the drop...

  1. Set up environment folders.

    $ mkdir env
    $ mkdir pyenv
    $ mkdir dep
    
  2. Get Python-2.7.3, and virtualenv without any form of root OS installation.

    $ cd dep
    $ wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz
    $ wget https://raw.github.com/pypa/virtualenv/master/virtualenv.py
    
  3. Extract and install Python-2.7.3 into the pyenv dir. make clean is optional if you are doing this a 2nd, 3rd, Nth time...

    $ tar -xzvf Python-2.7.3.tgz
    $ cd Python-2.7.3
    $ make clean
    $ ./configure --prefix=/path/to/pyenv
    $ make && make install
    $ cd ../../
    $ ls
    dep    env    pyenv
    
  4. Create your virtualenv

    $ dep/virtualenv.py --python=/path/to/pyenv/bin/python --verbose env
    
  5. Fix the symlink to python2.7 within env/include/

    $ ls -l env/include/
    $ cd !$
    $ rm python2.7
    $ ln -s ../../pyenv/include/python2.7 python2.7
    $ cd ../../
    
  6. Fix the remaining python symlinks in env. You'll have to delete the symbolically linked directories and recreate them, as above. Also, here's the syntax to force in-place symbolic link creation.

    $ ls -l env/lib/python2.7/
    $ cd !$
    $ ln -sf ../../../pyenv/lib/python2.7/UserDict.py UserDict.py
    [...repeat until all symbolic links are relative...]
    $ cd ../../../
    
  7. Test

    $ python --version
    Python 2.7.1
    $ source env/bin/activate
    (env)
    $ python --version
    Python 2.7.3
    

Aloha.

Adding extra zeros in front of a number using jQuery?

var str = "43215"; 
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
                                str = "0" + str;

                        }
console.log("After : \n string :"+str+"\n Length :"+str.length);

It worked for me ! To increase the zeroes, update the 'max' variable

Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:

How to create number input field in Flutter?

U can Install package intl_phone_number_input

dependencies:
  intl_phone_number_input: ^0.5.2+2

and try this code:

import 'package:flutter/material.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var darkTheme = ThemeData.dark().copyWith(primaryColor: Colors.blue);

    return MaterialApp(
      title: 'Demo',
      themeMode: ThemeMode.dark,
      darkTheme: darkTheme,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(title: Text('Demo')),
        body: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  final TextEditingController controller = TextEditingController();
  String initialCountry = 'NG';
  PhoneNumber number = PhoneNumber(isoCode: 'NG');

  @override
  Widget build(BuildContext context) {
    return Form(
      key: formKey,
      child: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            InternationalPhoneNumberInput(
              onInputChanged: (PhoneNumber number) {
                print(number.phoneNumber);
              },
              onInputValidated: (bool value) {
                print(value);
              },
              selectorConfig: SelectorConfig(
                selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
                backgroundColor: Colors.black,
              ),
              ignoreBlank: false,
              autoValidateMode: AutovalidateMode.disabled,
              selectorTextStyle: TextStyle(color: Colors.black),
              initialValue: number,
              textFieldController: controller,
              inputBorder: OutlineInputBorder(),
            ),
            RaisedButton(
              onPressed: () {
                formKey.currentState.validate();
              },
              child: Text('Validate'),
            ),
            RaisedButton(
              onPressed: () {
                getPhoneNumber('+15417543010');
              },
              child: Text('Update'),
            ),
          ],
        ),
      ),
    );
  }

  void getPhoneNumber(String phoneNumber) async {
    PhoneNumber number =
        await PhoneNumber.getRegionInfoFromPhoneNumber(phoneNumber, 'US');

    setState(() {
      this.number = number;
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}

image:

Nginx: Job for nginx.service failed because the control process exited

Had this issue when provisioning a new site for VVV in vvv-config.yml with a faulty syntax, vagrant up would throw the error. Deleting and reverting to old configuration, running vagrant provision helped

How to read data when some numbers contain commas as thousand separator?

You can have read.table or read.csv do this conversion for you semi-automatically. First create a new class definition, then create a conversion function and set it as an "as" method using the setAs function like so:

setClass("num.with.commas")
setAs("character", "num.with.commas", 
        function(from) as.numeric(gsub(",", "", from) ) )

Then run read.csv like:

DF <- read.csv('your.file.here', 
   colClasses=c('num.with.commas','factor','character','numeric','num.with.commas'))

batch file Copy files with certain extensions from multiple directories into one directory

Things like these are why I switched to Powershell. Try it out, it's fun:

Get-ChildItem -Recurse -Include *.doc | % {
    Copy-Item $_.FullName -destination x:\destination
}

What is the Maximum Size that an Array can hold?

System.Int32.MaxValue

Assuming you mean System.Array, ie. any normally defined array (int[], etc). This is the maximum number of values the array can hold. The size of each value is only limited by the amount of memory or virtual memory available to hold them.

This limit is enforced because System.Array uses an Int32 as it's indexer, hence only valid values for an Int32 can be used. On top of this, only positive values (ie, >= 0) may be used. This means the absolute maximum upper bound on the size of an array is the absolute maximum upper bound on values for an Int32, which is available in Int32.MaxValue and is equivalent to 2^31, or roughly 2 billion.

On a completely different note, if you're worrying about this, it's likely you're using alot of data, either correctly or incorrectly. In this case, I'd look into using a List<T> instead of an array, so that you are only using as much memory as needed. Infact, I'd recommend using a List<T> or another of the generic collection types all the time. This means that only as much memory as you are actually using will be allocated, but you can use it like you would a normal array.

The other collection of note is Dictionary<int, T> which you can use like a normal array too, but will only be populated sparsely. For instance, in the following code, only one element will be created, instead of the 1000 that an array would create:

Dictionary<int, string> foo = new Dictionary<int, string>();
foo[1000] = "Hello world!";
Console.WriteLine(foo[1000]);

Using Dictionary also lets you control the type of the indexer, and allows you to use negative values. For the absolute maximal sized sparse array you could use a Dictionary<ulong, T>, which will provide more potential elements than you could possible think about.

ssh: The authenticity of host 'hostname' can't be established

This warning is issued due the security features, do not disable this feature.

It's just displayed once.

If it still appears after second connection, the problem is probably in writing to the known_hosts file. In this case you'll also get the following message:

Failed to add the host to the list of known hosts 

You may fix it by changing owner of changing the permissions of the file to be writable by your user.

sudo chown -v $USER ~/.ssh/known_hosts

Find and Replace string in all files recursive using grep and sed

sed expression needs to be quoted

sed -i "s/$oldstring/$newstring/g"

Gradle project refresh failed after Android Studio update

Use this in project.gradle:

buildscript {
    repositories 
    {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}

What is the first character in the sort order used by Windows Explorer?

I know there is already an answer - and this is an old question - but I was wondering the same thing and after finding this answer I did a little experimentation on my own and had (IMO) a worthwhile addition to the discussion.

The non-visible characters can still be used in a folder name - a placeholder is inserted - but the sort on ASCII value still seems to hold.

I tested on Windows7, holding down the alt-key and typing in the ASCII code using the numeric keypad. I did not test very many, but was successful creating foldernames that started with ASCII 1, ASCII 2, and ASCII 3. Those correspond with SOH, STX and ETX. Respectively it displayed happy face, filled happy face, and filled heart.

I'm not sure if I can duplicate that here - but I will type them in on the next lines and submit.

?foldername

?foldername

?foldername

How can I check if an array contains a specific value in php?

// Once upon a time there was a farmer

// He had multiple haystacks
$haystackOne = range(1, 10);
$haystackTwo = range(11, 20);
$haystackThree = range(21, 30);

// In one of these haystacks he lost a needle
$needle = rand(1, 30);

// He wanted to know in what haystack his needle was
// And so he programmed...
if (in_array($needle, $haystackOne)) {
    echo "The needle is in haystack one";
} elseif (in_array($needle, $haystackTwo)) {
    echo "The needle is in haystack two";
} elseif (in_array($needle, $haystackThree)) {
    echo "The needle is in haystack three";
}

// The farmer now knew where to find his needle
// And he lived happily ever after

Split output of command by columns using Bash?

Using array variables

set $(ps | egrep "^11383 "); echo $4

or

A=( $(ps | egrep "^11383 ") ) ; echo ${A[3]}

Python equivalent to 'hold on' in Matlab

You can use the following:

plt.hold(True)

What is the result of % in Python?

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

Taken from http://docs.python.org/reference/expressions.html

Example 1: 6%2 evaluates to 0 because there's no remainder if 6 is divided by 2 ( 3 times ).

Example 2: 7%2 evaluates to 1 because there's a remainder of 1 when 7 is divided by 2 ( 3 times ).

So to summarise that, it returns the remainder of a division operation, or 0 if there is no remainder. So 6%2 means find the remainder of 6 divided by 2.

jQuery vs. javascript?

  • Does jQuery heavily rely on browser sniffing? Could be that potential problem in future? Why?

No - there is the $.browser method, but it's deprecated and isn't used in the core.

  • I found plenty JS-selector engines, are there any AJAX and FX libraries?

Loads. jQuery is often chosen because it does AJAX and animations well, and is easily extensible. jQuery doesn't use it's own selector engine, it uses Sizzle, an incredibly fast selector engine.

  • Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?

No - it's quick, relatively small and easy to extend.

For me personally it's nice to know that as browsers include more stuff (classlist API for example) that jQuery will update to include it, meaning that my code runs as fast as possible all the time.

Read through the source if you are interested, http://code.jquery.com/jquery-1.4.3.js - you'll see that features are added based on the best case first, and gradually backported to legacy browsers - for example, a section of the parseJSON method from 1.4.3:

return window.JSON && window.JSON.parse ?
    window.JSON.parse( data ) :
    (new Function("return " + data))();

As you can see, if window.JSON exists, the browser uses the native JSON parser, if not, then it avoids using eval (because otherwise minfiers won't minify this bit) and sets up a function that returns the data. This idea of assuming modern techniques first, then degrading to older methods is used throughout meaning that new browsers get to use all the whizz bang features without sacrificing legacy compatibility.

Difference between F5, Ctrl + F5 and click on refresh button?

F5 is a standard page reload.

and

Ctrl + F5 refreshes the page by clearing the cached content of the page.

Having the cursor in the address field and pressing Enter will also do the same as Ctrl + F5.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

How to prevent IFRAME from redirecting top-level window

Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.

There is also the iframe security attribute which only works on IE & Opera

:(

@Transactional(propagation=Propagation.REQUIRED)

When the propagation setting is PROPAGATION_REQUIRED, a logical transaction scope is created for each method upon which the setting is applied. Each such logical transaction scope can determine rollback-only status individually, with an outer transaction scope being logically independent from the inner transaction scope. Of course, in case of standard PROPAGATION_REQUIRED behavior, all these scopes will be mapped to the same physical transaction. So a rollback-only marker set in the inner transaction scope does affect the outer transaction's chance to actually commit (as you would expect it to).

enter image description here

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html

Unable to resolve host "<URL here>" No address associated with host name

It is WiFi bug due to wifi disable or not properly connected.

Simply Reconnect the wifi will solve the issue.

How to run a stored procedure in oracle sql developer?

Consider you've created a procedure like below.

CREATE OR REPLACE PROCEDURE GET_FULL_NAME like
(
  FIRST_NAME IN VARCHAR2, 
  LAST_NAME IN VARCHAR2,
  FULL_NAME OUT VARCHAR2 
) IS 
BEGIN
  FULL_NAME:= FIRST_NAME || ' ' || LAST_NAME;
END GET_FULL_NAME;

In Oracle SQL Developer, you can run this procedure in two ways.

1. Using SQL Worksheet

Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5

DECLARE
  FULL_NAME Varchar2(50);
BEGIN
  GET_FULL_NAME('Foo', 'Bar', FULL_NAME);
  Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);
END;

2. Using GUI Controls

  • Expand Procedures

  • Right click on the procudure you've created and Click Run

  • In the pop-up window, Fill the parameters and Click OK.

Cheers!

Switch php versions on commandline ubuntu 16.04

From PHP 5.6 => PHP 7.1

$ sudo a2dismod php5.6
$ sudo a2enmod php7.1

for old linux versions

 $ sudo service apache2 restart

for more recent version

$ systemctl restart apache2

Setting log level of message at runtime in slf4j

Try switching to Logback and use

ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.toLevel("info"));

I believe this will be the only call to Logback and the rest of your code will remain unchanged. Logback uses SLF4J and the migration will be painless, just the xml config files will have to be changed.

Remember to set the log level back after you're done.

How to fix apt-get: command not found on AWS EC2?

Check with "uname -a" and/or "lsb_release -a" to see which version of Linux you are actually running on your AWS instance. The default Amazon AMI image uses YUM for its package manager.

UITableView load more when scrolling to bottom like Facebook application

Better to use willDisplayCell method to check if which cell will be loaded. Once we get the current indexPath.row is last we can load more cells. This will load more cells on scrolling down.

 - (void)tableView:(UITableView *)tableView 
       willDisplayCell:(UITableViewCell *)cell    
       forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // check if indexPath.row is last row
    // Perform operation to load new Cell's.
}

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

Why docker container exits immediately

I added read shell statement at the end. This keeps the main process of the container - startup shell script - running.

Why is nginx responding to any domain name?

You should have a default server for catch-all, you can return 404 or better to not respond at all (will save some bandwidth) by returning 444 which is nginx specific HTTP response that simply close the connection and return nothing

server {
    listen       80  default_server;
    server_name  _; # some invalid name that won't match anything
    return       444;
}

String format currency

For those using the C# 6.0 string interpolation syntax: e.g: $"The price is {price:C}", the documentation suggests a few ways of applying different a CultureInfo.

I've adapted the examples to use currency:

decimal price = 12345.67M;
FormattableString message = $"The price is {price:C}";

System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
string messageInCurrentCulture = message.ToString();

var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = message.ToString(specificCulture);

string messageInInvariantCulture = FormattableString.Invariant(message);

Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");
Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");
// Expected output is:
// nl-NL      The price is € 12.345,67
// en-IN      The price is ? 12,345.67
// Invariant  The price is ¤12,345.67

How to find SQL Server running port?

In our enterprise I don't have access to MSSQL Server, so I can'r access the system tables.

What works for me is:

  1. capture the network traffic Wireshark (run as Administrator, select Network Interface),while opening connection to server.
  2. Find the ip address with ping
  3. filter with ip.dst == x.x.x.x

The port is shown in the column info in the format src.port -> dst.port

no sqljdbc_auth in java.library.path

For easy fix follow these steps:

  1. goto: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url#Connectingintegrated
  2. Download the JDBC file and extract to your preferred location
  3. open the auth folder matching your OS x64 or x86
  4. copy sqljdbc_auth.dll file
  5. paste in: C:\Program Files\Java\jdk_version\bin
  6. restart either eclipse or netbeans

Closing database connections in Java

Yes, you need to close Connection. Otherwise, the database client will typically keep the socket connection and other resources open.

jquery $.each() for objects

Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.

You could do an outer loop over the array

$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}

What is meant by the term "hook" in programming?

In the Drupal content management system, 'hook' has a relatively specific meaning. When an internal event occurs (like content creation or user login, for example), modules can respond to the event by implementing a special "hook" function. This is done via naming convention -- [your-plugin-name]_user_login() for the User Login event, for example.

Because of this convention, the underlying events are referred to as "hooks" and appear with names like "hook_user_login" and "hook_user_authenticate()" in Drupal's API documentation.

vba pass a group of cells as range to function

As written, your function accepts only two ranges as arguments.

To allow for a variable number of ranges to be used in the function, you need to declare a ParamArray variant array in your argument list. Then, you can process each of the ranges in the array in turn.

For example,

Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
    Dim elem As Variant
    Dim i As Long
    For Each elem In Arg1
        myAdd = myAdd + elem.Value
    Next elem
    For i = LBound(Args2) To UBound(Args2)
        For Each elem In Args2(i)
            myAdd = myAdd + elem.Value
        Next elem
    Next i
End Function

This function could then be used in the worksheet to add multiple ranges.

myAdd usage

For your function, there is the question of which of the ranges (or cells) that can passed to the function are 'Sessions' and which are 'Customers'.

The easiest case to deal with would be if you decided that the first range is Sessions and any subsequent ranges are Customers.

Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
    'This function accepts a single Sessions range and one or more Customers
    'ranges
    Dim i As Long
    Dim sessElem As Variant
    Dim custElem As Variant
    For Each sessElem In Sessions
        'do something with sessElem.Value, the value of each
        'cell in the single range Sessions
        Debug.Print "sessElem: " & sessElem.Value
    Next sessElem
    'loop through each of the one or more ranges in Customers()
    For i = LBound(Customers) To UBound(Customers)
        'loop through the cells in the range Customers(i)
        For Each custElem In Customers(i)
            'do something with custElem.Value, the value of
            'each cell in the range Customers(i)
            Debug.Print "custElem: " & custElem.Value
         Next custElem
    Next i
End Function

If you want to include any number of Sessions ranges and any number of Customers range, then you will have to include an argument that will tell the function so that it can separate the Sessions ranges from the Customers range.

This argument could be set up as the first, numeric, argument to the function that would identify how many of the following arguments are Sessions ranges, with the remaining arguments implicitly being Customers ranges. The function's signature would then be:

Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)

Or it could be a "guard" argument that separates the Sessions ranges from the Customers ranges. Then, your code would have to test each argument to see if it was the guard. The function would look like:

Function calculateIt(ParamArray Args() As Variant)

Perhaps with a call something like:

calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)

The program logic might then be along the lines of:

Function calculateIt(ParamArray Args() As Variant) As Double
   ...
   'loop through Args
   IsSessionArg = True
   For i = lbound(Args) to UBound(Args)
       'only need to check for the type of the argument
       If TypeName(Args(i)) = "String" Then
          IsSessionArg = False
       ElseIf IsSessionArg Then
          'process Args(i) as Session range
       Else
          'process Args(i) as Customer range
       End if
   Next i
   calculateIt = <somevalue>
End Function

Command to find information about CPUs on a UNIX machine

The nproc command shows the number of processing units available:
$ nproc

Sample outputs: 4

lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
$ lscpu

Sample outputs:

Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7

Elegant way to read file into byte[] array in Java

Use a ByteArrayOutputStream. Here is the process:

  • Get an InputStream to read data
  • Create a ByteArrayOutputStream.
  • Copy all the InputStream into the OutputStream
  • Get your byte[] from the ByteArrayOutputStream using the toByteArray() method

How to set socket timeout in C when making multiple connections?

am not sure if I fully understand the issue, but guess it's related to the one I had, am using Qt with TCP socket communication, all non-blocking, both Windows and Linux..

wanted to get a quick notification when an already connected client failed or completely disappeared, and not waiting the default 900+ seconds until the disconnect signal got raised. The trick to get this working was to set the TCP_USER_TIMEOUT socket option of the SOL_TCP layer to the required value, given in milliseconds.

this is a comparably new option, pls see http://tools.ietf.org/html/rfc5482, but apparently it's working fine, tried it with WinXP, Win7/x64 and Kubuntu 12.04/x64, my choice of 10 s turned out to be a bit longer, but much better than anything else I've tried before ;-)

the only issue I came across was to find the proper includes, as apparently this isn't added to the standard socket includes (yet..), so finally I defined them myself as follows:

#ifdef WIN32
    #include <winsock2.h>
#else
    #include <sys/socket.h>
#endif

#ifndef SOL_TCP
    #define SOL_TCP 6  // socket options TCP level
#endif
#ifndef TCP_USER_TIMEOUT
    #define TCP_USER_TIMEOUT 18  // how long for loss retry before timeout [ms]
#endif

setting this socket option only works when the client is already connected, the lines of code look like:

int timeout = 10000;  // user timeout in milliseconds [ms]
setsockopt (fd, SOL_TCP, TCP_USER_TIMEOUT, (char*) &timeout, sizeof (timeout));

and the failure of an initial connect is caught by a timer started when calling connect(), as there will be no signal of Qt for this, the connect signal will no be raised, as there will be no connection, and the disconnect signal will also not be raised, as there hasn't been a connection yet..

Retrieve CPU usage and memory usage of a single process on Linux?

ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | sort -nr

or per process

ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | sort -nr |grep mysql

How do you deploy Angular apps?

With Angular CLI, you can use the following command:

ng build --prod

It generates a dist folder with all you need to deploy the application.

If you have no practice with web servers, I recommend you to use Angular to Cloud. You just need to compress the dist folder as zip file and upload it in the platform.

How to obtain image size using standard Python class (without using external library)?

That code does accomplish 2 things:

  • Getting the image dimension

  • Find the real EOF of a jpg file

Well when googling I was more interest in the later one. The task was to cut out a jpg file from a datastream. Since I I didn't find any way to use Pythons 'image' to a way to get the EOF of so jpg-File I made up this.

Interesting things /changes/notes in this sample:

  • extending the normal Python file class with the method uInt16 making source code better readable and maintainable. Messing around with struct.unpack() quickly makes code to look ugly

  • Replaced read over'uninteresting' areas/chunk with seek

  • Incase you just like to get the dimensions you may remove the line:

    hasChunk = ord(byte) not in range( 0xD0, 0xDA) + [0x00] 
    

    ->since that only get's important when reading over the image data chunk and comment in

    #break
    

    to stop reading as soon as the dimension were found. ...but smile what I'm telling - you're the Coder ;)

      import struct
      import io,os
    
      class myFile(file):
    
          def byte( self ):
               return file.read( self,  1);
    
          def uInt16( self ):
               tmp = file.read( self,  2)
               return struct.unpack( ">H", tmp )[0];
    
      jpeg = myFile('grafx_ui.s00_\\08521678_Unknown.jpg', 'rb')
    
      try:
          height = -1
          width  = -1
          EOI    = -1
    
          type_check = jpeg.read(2)
          if type_check != b'\xff\xd8':
            print("Not a JPG")
    
          else:
    
            byte = jpeg.byte()
    
            while byte != b"":
    
              while byte != b'\xff': byte = jpeg.byte()
              while byte == b'\xff': byte = jpeg.byte()
    
    
              # FF D8       SOI Start of Image
              # FF D0..7  RST DRI Define Restart Interval inside CompressedData
              # FF 00           Masked FF inside CompressedData
              # FF D9       EOI End of Image
              # http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure
              hasChunk = ord(byte) not in range( 0xD0, 0xDA) + [0x00]
              if hasChunk:
                   ChunkSize   =  jpeg.uInt16()  - 2
                   ChunkOffset =  jpeg.tell()
                   Next_ChunkOffset = ChunkOffset + ChunkSize
    
    
              # Find bytes \xFF \xC0..C3 That marks the Start of Frame
              if (byte >= b'\xC0' and byte <= b'\xC3'):
    
                # Found  SOF1..3 data chunk - Read it and quit
                jpeg.seek(1, os.SEEK_CUR)
                h = jpeg.uInt16()
                w = jpeg.uInt16()
    
    
                #break
    
    
              elif (byte == b'\xD9'):
                   # Found End of Image
                   EOI = jpeg.tell()
                   break
              else:
                  # Seek to next data chunk
                 print "Pos: %.4x %x" % (jpeg.tell(), ChunkSize)
    
              if hasChunk:       
                 jpeg.seek(Next_ChunkOffset)
    
              byte = jpeg.byte()
    
            width  = int(w)
            height = int(h)
    
            print("Width: %s, Height: %s  JpgFileDataSize: %x" % (width, height, EOI))
      finally:
          jpeg.close()
    

How do I sort a dictionary by value?

As simple as: sorted(dict1, key=dict1.get)

Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency.

If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:

from collections import defaultdict
d = defaultdict(int)
for w in text.split():
    d[w] += 1

then you can get a list of the words, ordered by frequency of use with sorted(d, key=d.get) - the sort iterates over the dictionary keys, using the number of word occurrences as a sort key .

for w in sorted(d, key=d.get, reverse=True):
    print(w, d[w])

I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.

Nullable types: better way to check for null or zero in c#

This is really just an expansion of Freddy Rios' accepted answer only using Generics.

public static bool IsNullOrDefault<T>(this Nullable<T> value) where T : struct
{
    return default(T).Equals( value.GetValueOrDefault() );
}

public static bool IsValue<T>(this Nullable<T> value, T valueToCheck) where T : struct
{
    return valueToCheck.Equals((value ?? valueToCheck));
}

NOTE we don't need to check default(T) for null since we are dealing with either value types or structs! This also means we can safely assume T valueToCheck will not be null; Remember here that T? is shorthand Nullable<T> so by adding the extension to Nullable<T> we get the method in int?, double?, bool? etc.

Examples:

double? x = null;
x.IsNullOrDefault(); //true

int? y = 3;
y.IsNullOrDefault(); //false

bool? z = false;
z.IsNullOrDefault(); //true

How do you get the magnitude of a vector in Numpy?

If you are worried at all about speed, you should instead use:

mag = np.sqrt(x.dot(x))

Here are some benchmarks:

>>> import timeit
>>> timeit.timeit('np.linalg.norm(x)', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0450878
>>> timeit.timeit('np.sqrt(x.dot(x))', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0181372

EDIT: The real speed improvement comes when you have to take the norm of many vectors. Using pure numpy functions doesn't require any for loops. For example:

In [1]: import numpy as np

In [2]: a = np.arange(1200.0).reshape((-1,3))

In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 4.23 ms per loop

In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 18.9 us per loop

In [5]: np.allclose([np.linalg.norm(x) for x in a],np.sqrt((a*a).sum(axis=1)))
Out[5]: True

How do I capture the output of a script if it is being ran by the task scheduler?

You can write to a log file on the lines that you want to output like this:

@echo off
echo Debugging started >C:\logfile.txt
echo More stuff
echo Debugging stuff >>C:\logfile.txt
echo Hope this helps! >>C:\logfile.txt

This way you can choose which commands to output if you don't want to trawl through everything, just get what you need to see. The > will output it to the file specified (creating the file if it doesn't exist and overwriting it if it does). The >> will append to the file specified (creating the file if it doesn't exist but appending to the contents if it does).

Simplest/cleanest way to implement a singleton in JavaScript

Another way - just insure the class can not new again.

By this, you can use the instanceof op. Also, you can use the prototype chain to inherit the class. It's a regular class, but you can not new it. If you want to get the instance, just use getInstance:

function CA()
{
    if(CA.instance)
    {
        throw new Error('can not new this class');
    }
    else
    {
        CA.instance = this;
    }
}


/**
 * @protected
 * @static
 * @type {CA}
 */
CA.instance = null;

/* @static */
CA.getInstance = function()
{
    return CA.instance;
}


CA.prototype =
/** @lends CA# */
{
    func: function(){console.log('the func');}
}

// Initialise the instance
new CA();

// Test here
var c = CA.getInstance()
c.func();
console.assert(c instanceof CA)

// This will fail
var b = new CA();

If you don't want to expose the instance member, just put it into a closure.

Should I always use a parallel stream when possible?

JB hit the nail on the head. The only thing I can add is that Java 8 doesn't do pure parallel processing, it does paraquential. Yes I wrote the article and I've been doing F/J for thirty years so I do understand the issue.

How to insert text into the textarea at the current cursor position?

I like simple javascript, and I usually have jQuery around. Here's what I came up with, based off mparkuk's:

function typeInTextarea(el, newText) {
  var start = el.prop("selectionStart")
  var end = el.prop("selectionEnd")
  var text = el.val()
  var before = text.substring(0, start)
  var after  = text.substring(end, text.length)
  el.val(before + newText + after)
  el[0].selectionStart = el[0].selectionEnd = start + newText.length
  el.focus()
}

$("button").on("click", function() {
  typeInTextarea($("textarea"), "some text")
  return false
})

Here's a demo: http://codepen.io/erikpukinskis/pen/EjaaMY?editors=101

Excel VBA, How to select rows based on data in a column?

The easiest way to do it is to use the End method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.

Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")

If you can't use End, then you would have to use a loop.

Dim start_cell As Range, end_cell As Range

Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell

Do Until IsEmpty(end_cell.Offset(1, 0))
    Set end_cell = end_cell.Offset(1, 0)
Loop

Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")

Android studio - Failed to find target android-18

This will also happen if you have written compileSdkVersion = 22 e.g. (as used in the "new new" Android build system) instead of compileSdkVersion 22.

hasNext in Python iterators?

Suggested way is StopIteration. Please see Fibonacci example from tutorialspoint

#!usr/bin/python3

import sys
def fibonacci(n): #generator function
   a, b, counter = 0, 1, 0
   while True:
      if (counter > n): 
         return
      yield a
      a, b = b, a + b
      counter += 1
f = fibonacci(5) #f is iterator object

while True:
   try:
      print (next(f), end=" ")
   except StopIteration:
      sys.exit()

Remote desktop connection protocol error 0x112f

I got the same error recently. I think McX is right it was caused by insufficient memory on RDP server. Here is the solution that works for us.

  1. use sc cmd to get running services on the remote server. Make sure you can use windows explorer to access the remote server \\remote_server.

    sc \\<remote_server> query

  2. find out the service you can stop.

    sc \\<remote_server> stop <service_name>

After stopping one service, the remote desktop works again.

adb command not found

I solved this issue by install adb package. I'm using Ubuntu.

sudo apt install adb

I think this will help to you.

How to convert a string to utf-8 in Python

If I understand you correctly, you have a utf-8 encoded byte-string in your code.

Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding).

You do that by using the unicode function or the decode method. Either:

unicodestr = unicode(bytestr, encoding)
unicodestr = unicode(bytestr, "utf-8")

Or:

unicodestr = bytestr.decode(encoding)
unicodestr = bytestr.decode("utf-8")

Found shared references to a collection org.hibernate.HibernateException

I have experienced a great example of reproducing such a problem. Maybe my experience will help someone one day.

Short version

Check that your @Embedded Id of container has no possible collisions.

Long version

When Hibernate instantiates collection wrapper, it searches for already instantiated collection by CollectionKey in internal Map.

For Entity with @Embedded id, CollectionKey wraps EmbeddedComponentType and uses @Embedded Id properties for equality checks and hashCode calculation.

So if you have two entities with equal @Embedded Ids, Hibernate will instantiate and put new collection by the first key and will find same collection for the second key. So two entities with same @Embedded Id will be populated with same collection.

Example

Suppose you have Account entity which has lazy set of loans. And Account has @Embedded Id consists of several parts(columns).

@Entity
@Table(schema = "SOME", name = "ACCOUNT")
public class Account {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "account")
    private Set<Loan> loans;

    @Embedded
    private AccountId accountId;

    ...
}

@Embeddable
public class AccountId {
    @Column(name = "X")
    private Long x;
    
    @Column(name = "BRANCH")
    private String branchId;
    
    @Column(name = "Z")
    private String z;

    ...
}

Then suppose that Account has additional property mapped by @Embedded Id but has relation to other entity Branch.

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BRANCH")
@MapsId("accountId.branchId")
@NotFound(action = NotFoundAction.IGNORE)//Look at this!
private Branch branch;

It could happen that you have no FK for Account to Brunch relation id DB so Account.BRANCH column can have any value not presented in Branch table.

According to @NotFound(action = NotFoundAction.IGNORE) if value is not present in related table, Hibernate will load null value for the property.

If X and Y columns of two Accounts are same(which is fine), but BRANCH is different and not presented in Branch table, hibernate will load null for both and Embedded Ids will be equal.

So two CollectionKey objects will be equal and will have same hashCode for different Accounts.

result = {CollectionKey@34809} "CollectionKey[Account.loans#Account@43deab74]"
 role = "Account.loans"
 key = {Account@26451} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

result = {CollectionKey@35653} "CollectionKey[Account.loans#Account@33470aa]"
 role = "Account.loans"
 key = {Account@35225} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

Because of this, Hibernate will load same PesistentSet for two entities.

How to scale Docker containers in production

While we're big fans of Deis (deis.io) and are actively deploying to it, there are other Heroku like PaaS style deployment solutions out there, including:

Longshoreman from the Wayfinder folks:

https://github.com/longshoreman/longshoreman

Decker from the CloudCredo folks, using CloudFoundry:

http://www.cloudcredo.com/decker-docker-cloud-foundry/

As for straight up orchestration, NewRelic's opensource Centurion project seems quite promising:

https://github.com/newrelic/centurion

I do not want to inherit the child opacity from the parent in CSS

My answer is not about static parent-child layout, its about animations.

I was doing an svg demo today, and i needed svg to be inside div (because svg is created with parent's div width and height, to animate the path around), and this parent div needed to be invisible during svg path animation (and then this div was supposed to animate opacity from 0 to 1, it's the most important part). And because parent div with opacity: 0 was hiding my svg, i came across this hack with visibility option (child with visibility: visible can be seen inside parent with visibility: hidden):

.main.invisible .test {
  visibility: hidden;
}
.main.opacity-zero .test {
  opacity: 0;
  transition: opacity 0s !important;
}
.test { // parent div
  transition: opacity 1s;
}
.test-svg { // child svg
  visibility: visible;
}

And then, in js, you removing .invisible class with timeout function, adding .opacity-zero class, trigger layout with something like whatever.style.top; and removing .opacity-zero class.

var $main = $(".main");
  setTimeout(function() {
    $main.addClass('opacity-zero').removeClass("invisible");
    $(".test-svg").hide();
    $main.css("top");
    $main.removeClass("opacity-zero");
  }, 3000);

Better to check this demo http://codepen.io/suez/pen/54bbb2f09e8d7680da1af2faa29a0aef?editors=011

how to change php version in htaccess in server

An addition to the current marked answer:

Place the addhandler inside the following scope, like so:

<IfModule mod_rewrite.c>

   AddHandler application/x-httpd-php71 .php
   RewriteEngine On

   ....

</IfModule>

How to find all duplicate from a List<string>?

and without the LINQ:

string[] ss = {"1","1","1"};

var myList = new List<string>();
var duplicates = new List<string>();

foreach (var s in ss)
{
   if (!myList.Contains(s))
      myList.Add(s);
   else
      duplicates.Add(s);
}

// show list without duplicates 
foreach (var s in myList)
   Console.WriteLine(s);

// show duplicates list
foreach (var s in duplicates)
   Console.WriteLine(s);

C/C++ include header file order

I follow two simple rules that avoid the vast majority of problems:

  1. All headers (and indeed any source files) should include what they need. They should not rely on their users including things.
  2. As an adjunct, all headers should have include guards so that they don't get included multiple times by over-ambitious application of rule 1 above.

I also follow the guidelines of:

  1. Include system headers first (stdio.h, etc) with a dividing line.
  2. Group them logically.

In other words:

#include <stdio.h>
#include <string.h>

#include "btree.h"
#include "collect_hash.h"
#include "collect_arraylist.h"
#include "globals.h"

Although, being guidelines, that's a subjective thing. The rules on the other hand, I enforce rigidly, even to the point of providing 'wrapper' header files with include guards and grouped includes if some obnoxious third-party developer doesn't subscribe to my vision :-)

Extending the User model with custom fields in Django

You can Simply extend user profile by creating a new entry each time when a user is created by using Django post save signals

models.py

from django.db.models.signals import *
from __future__ import unicode_literals

class UserProfile(models.Model):

    user_name = models.OneToOneField(User, related_name='profile')
    city = models.CharField(max_length=100, null=True)

    def __unicode__(self):  # __str__
        return unicode(self.user_name)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        userProfile.objects.create(user_name=instance)

post_save.connect(create_user_profile, sender=User)

This will automatically create an employee instance when a new user is created.

If you wish to extend user model and want to add further information while creating a user you can use django-betterforms (http://django-betterforms.readthedocs.io/en/latest/multiform.html). This will create a user add form with all fields defined in the UserProfile model.

models.py

from django.db.models.signals import *
from __future__ import unicode_literals

class UserProfile(models.Model):

    user_name = models.OneToOneField(User)
    city = models.CharField(max_length=100)

    def __unicode__(self):  # __str__
        return unicode(self.user_name)

forms.py

from django import forms
from django.forms import ModelForm
from betterforms.multiform import MultiModelForm
from django.contrib.auth.forms import UserCreationForm
from .models import *

class ProfileForm(ModelForm):

    class Meta:
        model = Employee
        exclude = ('user_name',)


class addUserMultiForm(MultiModelForm):
    form_classes = {
        'user':UserCreationForm,
        'profile':ProfileForm,
    }

views.py

from django.shortcuts import redirect
from .models import *
from .forms import *
from django.views.generic import CreateView

class AddUser(CreateView):
    form_class = AddUserMultiForm
    template_name = "add-user.html"
    success_url = '/your-url-after-user-created'

    def form_valid(self, form):
        user = form['user'].save()
        profile = form['profile'].save(commit=False)
        profile.user_name = User.objects.get(username= user.username)
        profile.save()
        return redirect(self.success_url)

addUser.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="." method="post">
            {% csrf_token %}
            {{ form }}     
            <button type="submit">Add</button>
        </form>
     </body>
</html>

urls.py

from django.conf.urls import url, include
from appName.views import *
urlpatterns = [
    url(r'^add-user/$', AddUser.as_view(), name='add-user'),
]

Get image dimensions

<?php 
    list($width, $height) = getimagesize("http://site.com/image.png"); 
    $arr = array('h' => $height, 'w' => $width );
?>

Remove table row after clicking table row delete button

As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.

This is how we can implement it using jQuery click event instead of using JavaScript onclick.

HTML:

<table id="myTable">
<tr>
  <th width="30%" style="color:red;">ID</th>
  <th width="25%" style="color:red;">Name</th>
  <th width="25%" style="color:red;">Age</th>
  <th width="1%"></th>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-001</td>
  <td width="25%" style="color:red;">Ben</td>
  <td width="25%" style="color:red;">25</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-002</td>
  <td width="25%" style="color:red;">Anderson</td>
  <td width="25%" style="color:red;">47</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-003</td>
  <td width="25%" style="color:red;">Rocky</td>
  <td width="25%" style="color:red;">32</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-004</td>
  <td width="25%" style="color:red;">Lee</td>
  <td width="25%" style="color:red;">15</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>
                            

jQuery

 $(document).ready(function(){
     $("#myTable").on('click','.btnDelete',function(){
         $(this).closest('tr').remove();
      });
  });

Try in JSFiddle: click here.

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Does this answer your question?

I have never used reinterpret_cast, and wonder whether running into a case that needs it isn't a smell of bad design. In the code base I work on dynamic_cast is used a lot. The difference with static_cast is that a dynamic_cast does runtime checking which may (safer) or may not (more overhead) be what you want (see msdn).

How to generate a random number in C++?

Can get full Randomer class code for generating random numbers from here!

If you need random numbers in different parts of the project you can create a separate class Randomer to incapsulate all the random stuff inside it.

Something like that:

class Randomer {
    // random seed by default
    std::mt19937 gen_;
    std::uniform_int_distribution<size_t> dist_;

public:
    /*  ... some convenient ctors ... */ 

    Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
        : gen_{seed}, dist_{min, max} {
    }

    // if you want predictable numbers
    void SetSeed(unsigned int seed) {
        gen_.seed(seed);
    }

    size_t operator()() {
        return dist_(gen_);
    }
};

Such a class would be handy later on:

int main() {
    Randomer randomer{0, 10};
    std::cout << randomer() << "\n";
}

You can check this link as an example how i use such Randomer class to generate random strings. You can also use Randomer if you wish.

key_load_public: invalid format

There is a simple solution if you can install and use puttygen tool. Below are the steps. You should have the passphrase of the private key.

step 1: Download latest puttygen and open puttygen

step 2: Load your existing private key file, see below image

Load an existing private key

step 3: Enter passphrase for key if asked and hit ok

enter paasphrase

step 4: as shown in the below image select "conversion" menu tab and select "Export OpenSSH key"

save OpenSSH file

Save new private key file at preferred location and use accordingly.

WorksheetFunction.CountA - not working post upgrade to Office 2010

It may be obvious but, by stating the Range and not including which workbook or worksheet then it may be trying to CountA() on a different sheet entirely. I find to fully address these things saves a lot of headaches.

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

You pretty much can't set the value of found. Debugging optimized programs is rarely worth the trouble, the compiler can rearrange the code in ways that it'll in no way correspond to the source code (other than producing the same result), thus confusing debuggers to no end.

Shell script to send email

top -b -n 1 | mail -s "any subject" [email protected]

Convert datetime value into string

Try this:

concat(left(datefield,10),left(timefield,8))
  • 10 char on date field based on full date yyyy-MM-dd.

  • 8 char on time field based on full time hh:mm:ss.

It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.

Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.

How to access environment variable values?

Actually it can be done this away:

import os

for item, value in os.environ.items():
    print('{}: {}'.format(item, value))

Or simply:

for i, j in os.environ.items():
    print(i, j)

For view the value in the parameter:

print(os.environ['HOME'])

Or:

print(os.environ.get('HOME'))

To set the value:

os.environ['HOME'] = '/new/value'

Angular4 - No value accessor for form control

The error means, that Angular doesn't know what to do when you put a formControl on a div. To fix this, you have two options.

  1. You put the formControlName on an element, that is supported by Angular out of the box. Those are: input, textarea and select.
  2. You implement the ControlValueAccessor interface. By doing so, you're telling Angular "how to access the value of your control" (hence the name). Or in simple terms: What to do, when you put a formControlName on an element, that doesn't naturally have a value associated with it.

Now, implementing the ControlValueAccessor interface can be a bit daunting at first. Especially because there isn't much good documentation of this out there and you need to add a lot of boilerplate to your code. So let me try to break this down in some simple-to-follow steps.

Move your form control into its own component

In order to implement the ControlValueAccessor, you need to create a new component (or directive). Move the code related to your form control there. Like this it will also be easily reusable. Having a control already inside a component might be the reason in the first place, why you need to implement the ControlValueAccessor interface, because otherwise you will not be able to use your custom component together with Angular forms.

Add the boilerplate to your code

Implementing the ControlValueAccessor interface is quite verbose, here's the boilerplate that comes with it:

import {Component, OnInit, forwardRef} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';


@Component({
  selector: 'app-custom-input',
  templateUrl: './custom-input.component.html',
  styleUrls: ['./custom-input.component.scss'],

  // a) copy paste this providers property (adjust the component name in the forward ref)
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true
    }
  ]
})
// b) Add "implements ControlValueAccessor"
export class CustomInputComponent implements ControlValueAccessor {

  // c) copy paste this code
  onChange: any = () => {}
  onTouch: any = () => {}
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouch = fn;
  }

  // d) copy paste this code
  writeValue(input: string) {
    // TODO
  }

So what are the individual parts doing?

  • a) Lets Angular know during runtime that you implemented the ControlValueAccessor interface
  • b) Makes sure you're implementing the ControlValueAccessor interface
  • c) This is probably the most confusing part. Basically what you're doing is, you give Angular the means to override your class properties/methods onChange and onTouch with it's own implementation during runtime, such that you can then call those functions. So this point is important to understand: You don't need to implement onChange and onTouch yourself (other than the initial empty implementation). The only thing your doing with (c) is to let Angular attach it's own functions to your class. Why? So you can then call the onChange and onTouch methods provided by Angular at the appropriate time. We'll see how this works down below.
  • d) We'll also see how the writeValue method works in the next section, when we implement it. I've put it here, so all required properties on ControlValueAccessor are implemented and your code still compiles.

Implement writeValue

What writeValue does, is to do something inside your custom component, when the form control is changed on the outside. So for example, if you have named your custom form control component app-custom-input and you'd be using it in the parent component like this:

<form [formGroup]="form">
  <app-custom-input formControlName="myFormControl"></app-custom-input>
</form>

then writeValue gets triggered whenever the parent component somehow changes the value of myFormControl. This could be for example during the initialization of the form (this.form = this.formBuilder.group({myFormControl: ""});) or on a form reset this.form.reset();.

What you'll typically want to do if the value of the form control changes on the outside, is to write it to a local variable which represents the form control value. For example, if your CustomInputComponent revolves around a text based form control, it could look like this:

writeValue(input: string) {
  this.input = input;
}

and in the html of CustomInputComponent:

<input type="text"
       [ngModel]="input">

You could also write it directly to the input element as described in the Angular docs.

Now you have handled what happens inside of your component when something changes outside. Now let's look at the other direction. How do you inform the outside world when something changes inside of your component?

Calling onChange

The next step is to inform the parent component about changes inside of your CustomInputComponent. This is where the onChange and onTouch functions from (c) from above come into play. By calling those functions you can inform the outside about changes inside your component. In order to propagate changes of the value to the outside, you need to call onChange with the new value as the argument. For example, if the user types something in the input field in your custom component, you call onChange with the updated value:

<input type="text"
       [ngModel]="input"
       (ngModelChange)="onChange($event)">

If you check the implementation (c) from above again, you'll see what's happening: Angular bound it's own implementation to the onChange class property. That implementation expects one argument, which is the updated control value. What you're doing now is you're calling that method and thus letting Angular know about the change. Angular will now go ahead and change the form value on the outside. This is the key part in all this. You told Angular when it should update the form control and with what value by calling onChange. You've given it the means to "access the control value".

By the way: The name onChange is chosen by me. You could choose anything here, for example propagateChange or similar. However you name it though, it will be the same function that takes one argument, that is provided by Angular and that is bound to your class by the registerOnChange method during runtime.

Calling onTouch

Since form controls can be "touched", you should also give Angular the means to understand when your custom form control is touched. You can do it, you guessed it, by calling the onTouch function. So for our example here, if you want to stay compliant with how Angular is doing it for the out-of-the-box form controls, you should call onTouch when the input field is blurred:

<input type="text"
       [(ngModel)]="input"
       (ngModelChange)="onChange($event)"
       (blur)="onTouch()">

Again, onTouch is a name chosen by me, but what it's actual function is provided by Angular and it takes zero arguments. Which makes sense, since you're just letting Angular know, that the form control has been touched.

Putting it all together

So how does that look when it comes all together? It should look like this:

// custom-input.component.ts
import {Component, OnInit, forwardRef} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR} from '@angular/forms';


@Component({
  selector: 'app-custom-input',
  templateUrl: './custom-input.component.html',
  styleUrls: ['./custom-input.component.scss'],

  // Step 1: copy paste this providers property
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true
    }
  ]
})
// Step 2: Add "implements ControlValueAccessor"
export class CustomInputComponent implements ControlValueAccessor {

  // Step 3: Copy paste this stuff here
  onChange: any = () => {}
  onTouch: any = () => {}
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouch = fn;
  }

  // Step 4: Define what should happen in this component, if something changes outside
  input: string;
  writeValue(input: string) {
    this.input = input;
  }

  // Step 5: Handle what should happen on the outside, if something changes on the inside
  // in this simple case, we've handled all of that in the .html
  // a) we've bound to the local variable with ngModel
  // b) we emit to the ouside by calling onChange on ngModelChange

}
// custom-input.component.html
<input type="text"
       [(ngModel)]="input"
       (ngModelChange)="onChange($event)"
       (blur)="onTouch()">
// parent.component.html
<app-custom-input [formControl]="inputTwo"></app-custom-input>

// OR

<form [formGroup]="form" >
  <app-custom-input formControlName="myFormControl"></app-custom-input>
</form>

More Examples

Nested Forms

Note that Control Value Accessors are NOT the right tool for nested form groups. For nested form groups you can simply use an @Input() subform instead. Control Value Accessors are meant to wrap controls, not groups! See this example how to use an input for a nested form: https://stackblitz.com/edit/angular-nested-forms-input-2

Sources

How to upload a file to directory in S3 bucket using boto

from boto3.s3.transfer import S3Transfer
import boto3
#have all the variables populated which are required below
client = boto3.client('s3', aws_access_key_id=access_key,aws_secret_access_key=secret_key)
transfer = S3Transfer(client)
transfer.upload_file(filepath, bucket_name, folder_name+"/"+filename)

Removing cordova plugins from the project

I do it with this python one-liner:

python -c "import subprocess as sp;[sp.call('cordova plugin rm ' + p.split()[0], shell=True) for p in sp.check_output('cordova plugin', shell=True).split('\n') if p]"

Obviously it doesn't handle any sort of error conditions, but it gets the job done.

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

Why controllers are needed

The difference between link and controller comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.

From the docs:

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

Say you want to have two directives my-form and my-text-input and you want my-text-input directive to appear only inside my-form and nowhere else.

In that case, you will say while defining the directive my-text-input that it requires a controller from the parent DOM element using the require argument, like this: require: '^myForm'. Now the controller from the parent element will be injected into the link function as the fourth argument, following $scope, element, attributes. You can call functions on that controller and communicate with the parent directive.

Moreover, if such a controller is not found, an error will be raised.

Why use link at all

There is no real need to use the link function if one is defining the controller since the $scope is available on the controller. Moreover, while defining both link and controller, one does need to be careful about the order of invocation of the two (controller is executed before).

However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers is usually done in the link function while the API for children and $scope manipulation is done in the controller. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive state and link function will maintain the DOM + outside bindings).

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

click command in selenium webdriver does not work

Thanks for all the answers everyone! I have found a solution, turns out I didn't provide enough code in my question.

The problem was NOT with the click() function after all, but instead related to cas authentication used with my project. In Selenium IDE my login test executed a "open" command to the following location,

/cas/login?service=https%1F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security

That worked. I exported the test to Selenium webdriver which naturally preserved that location. The command in Selenium Webdriver was,

driver.get(baseUrl + "/cas/login?service=https%1A%2F%8FAPPNAME%2FMOREURL%2Fj_spring_cas_security");

For reasons I have yet to understand the above failed. When I changed it to,

driver.get(baseUrl + "MOREURL/");

The click command suddenly started to work... I will edit this answer if I can figure out why exactly this is.

Note: I obscured the URLs used above to protect my company's product.

Using cut command to remove multiple columns

The same could be done with Perl
Because it uses 0-based-indexing instead of 1-based-indexing, the field values are offset by 1

perl -F, -lane 'print join ",", @F[1..3,5..9,11..19]'    

is equivalent to:

cut -d, -f2-4,6-10,12-20

If the commas are not needed in the output:

perl -F, -lane 'print "@F[1..3,5..9,11..19]"'

What is the purpose of a self executing function in javascript?

One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

Your command is wrong.

Linux

java -- version

macOS

java -version

You can't use those commands other way around.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

Error message looks like this

Error message => ORA-00001: unique constraint (schema.unique_constraint_name) violated

ORA-00001 occurs when: "a query tries to insert a "duplicate" row in a table". It makes an unique constraint to fail, consequently query fails and row is NOT added to the table."

Solution:

Find all columns used in unique_constraint, for instance column a, column b, column c, column d collectively creates unique_constraint and then find the record from source data which is duplicate, using following queries:

-- to find <<owner of the table>> and <<name of the table>> for unique_constraint

select *
from DBA_CONSTRAINTS
where CONSTRAINT_NAME = '<unique_constraint_name>';

Then use Justin Cave's query (pasted below) to find all columns used in unique_constraint:

  SELECT column_name, position
  FROM all_cons_columns
  WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

    -- to find duplicates

    select column a, column b, column c, column d
    from table
    group by column a, column b, column c, column d
    having count (<any one column used in constraint > ) > 1;

you can either delete that duplicate record from your source data (which was a select query in my particular case, as I experienced it with "Insert into select") or modify to make it unique or change the constraint.

How can I get the console logs from the iOS Simulator?

In Xcode: View->Debug Area->Activate Console

enter image description here

Django datetime issues (default=datetime.now())

Instead of using datetime.now you should be really using from django.utils.timezone import now

Reference:

so go for something like this:

from django.utils.timezone import now


created_date = models.DateTimeField(default=now, editable=False)

Check array position for null/empty

If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.

SomeClass* myArray[2];
myArray[0] = new SomeClass();
myArray[1] = NULL;

if (myArray[0] != NULL) { // this will be executed }
if (myArray[1] != NULL) { // this will NOT be executed }

As http://en.cppreference.com/w/cpp/types/NULL states, NULL is a null pointer constant!

How to write logs in text file when using java.util.logging.Logger

Try this sample. It works for me.

public static void main(String[] args) {  

    Logger logger = Logger.getLogger("MyLog");  
    FileHandler fh;  

    try {  

        // This block configure the logger with handler and formatter  
        fh = new FileHandler("C:/temp/test/MyLogFile.log");  
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(formatter);  

        // the following statement is used to log any messages  
        logger.info("My first log");  

    } catch (SecurityException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  

    logger.info("Hi How r u?");  

}

Produces the output at MyLogFile.log

Apr 2, 2013 9:57:08 AM testing.MyLogger main  
INFO: My first log  
Apr 2, 2013 9:57:08 AM testing.MyLogger main  
INFO: Hi How r u?

Edit:

To remove the console handler, use

logger.setUseParentHandlers(false);

since the ConsoleHandler is registered with the parent logger from which all the loggers derive.

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

try this:

ComboBox cbx = new ComboBox();
cbx.DisplayMember = "Text";
cbx.ValueMember = "Value";

EDIT (a little explanation, sory, I also didn't notice your combobox wasn't bound, I blame the lack of caffeine):

The difference between SelectedValue and SelectedItem are explained pretty well here: ComboBox SelectedItem vs SelectedValue

So, if your combobox is not bound to datasource, DisplayMember and ValueMember doesn't do anything, and SelectedValue will always be null, SelectedValueChanged won't be called. So either bind your combobox:

            comboBox1.DisplayMember = "Text";
            comboBox1.ValueMember = "Value";

            List<ComboboxItem> list = new List<ComboboxItem>();

            ComboboxItem item = new ComboboxItem();
            item.Text = "choose a server...";
            item.Value = "-1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S1";
            item.Value = "1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S2";
            item.Value = "2";
            list.Add(item);

            cbx.DataSource = list; // bind combobox to a datasource

or use SelectedItem property:

if (cbx.SelectedItem != null)
             Console.WriteLine("ITEM: "+comboBox1.SelectedItem.ToString());

Finding the length of an integer in C

The most efficient way could possibly be to use a fast logarithm based approach, similar to those used to determine the highest bit set in an integer.

size_t printed_length ( int32_t x )
{
    size_t count = x < 0 ? 2 : 1;

    if ( x < 0 ) x = -x;

    if ( x >= 100000000 ) {
        count += 8;
        x /= 100000000;
    }

    if ( x >= 10000 ) {
        count += 4;
        x /= 10000;
    }

    if ( x >= 100 ) {
        count += 2;
        x /= 100;
    }

    if ( x >= 10 )
        ++count;

    return count;
}

This (possibly premature) optimisation takes 0.65s for 20 million calls on my netbook; iterative division like zed_0xff has takes 1.6s, recursive division like Kangkan takes 1.8s, and using floating point functions (Jordan Lewis' code) takes a whopping 6.6s. Using snprintf takes 11.5s, but will give you the size that snprintf requires for any format, not just integers. Jordan reports that the ordering of the timings are not maintained on his processor, which does floating point faster than mine.

The easiest is probably to ask snprintf for the printed length:

#include <stdio.h>

size_t printed_length ( int x )
{
    return snprintf ( NULL, 0, "%d", x );
}

int main ()
{
    int x[] = { 1, 25, 12512, 0, -15 };

    for ( int i = 0; i < sizeof ( x ) / sizeof ( x[0] ); ++i )
        printf ( "%d -> %d\n", x[i], printed_length ( x[i] ) );

    return 0;
}

How do you test a public/private DSA keypair?

If you are in Windows and want use a GUI, with puttygen you can import your private key into it:

enter image description here

Once imported, you can save its public key and compare it to yours.

Passing an Array as Arguments, not an Array, in PHP

Also note that if you want to apply an instance method to an array, you need to pass the function as:

call_user_func_array(array($instance, "MethodName"), $myArgs);

How to scroll to top of page with JavaScript/jQuery?

Cross-browser, pure JavaScript solution:

document.body.scrollTop = document.documentElement.scrollTop = 0;