Programs & Examples On #Intrinsics

Intrinsics functions are used in compiled languages to use specific CPU instructions outside the scope of the language.

Why Maven uses JDK 1.6 but my java -version is 1.7

add the following to your ~/.mavenrc:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/{jdk-version}/Contents/Home

Second Solution:

echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile

Reading content from URL with Node.js

HTTP and HTTPS:

const getScript = (url) => {
    return new Promise((resolve, reject) => {
        const http      = require('http'),
              https     = require('https');

        let client = http;

        if (url.toString().indexOf("https") === 0) {
            client = https;
        }

        client.get(url, (resp) => {
            let data = '';

            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            });

            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(data);
            });

        }).on("error", (err) => {
            reject(err);
        });
    });
};

(async (url) => {
    console.log(await getScript(url));
})('https://sidanmor.com/');

When to use HashMap over LinkedList or ArrayList and vice-versa

I will put here some real case examples and scenarios when to use one or another, it might be of help for somebody else:

HashMap

When you have to use cache in your application. Redis and membase are some type of extended HashMap. (Doesn't matter the order of the elements, you need quick ( O(1) ) read access (a value), using a key).

LinkedList

When the order is important (they are ordered as they were added to the LinkedList), the number of elements are unknown (don't waste memory allocation) and you require quick insertion time ( O(1) ). A list of to-do items that can be listed sequentially as they are added is a good example.

Exporting results of a Mysql query to excel?

Good Example can be when incase of writing it after the end of your query if you have joins or where close :

 select 'idPago','fecha','lead','idAlumno','idTipoPago','idGpo'
 union all
(select id_control_pagos, fecha, lead, id_alumno, id_concepto_pago, id_Gpo,id_Taller,
id_docente, Pagoimporte, NoFactura, FacturaImporte, Mensualidad_No, FormaPago,
Observaciones from control_pagos
into outfile 'c:\\data.csv' 
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n');

Android lollipop change navigation bar color

You can add the following line in the values-v21/style.xml folder:

<item name="android:navigationBarColor">@color/theme_color</item>

How to use makefiles in Visual Studio?

Makefiles and build files are about automating your build. If you use a script like MSBuild or NAnt, you can build your project or solution directly from command line. This in turn makes it possible to automate the build, have it run by a build server.

Besides building your solution it is typical that a build script includes task to run unit tests, report code coverage and complexity and more.

How to import CSV file data into a PostgreSQL table?

IMHO, the most convenient way is to follow "Import CSV data into postgresql, the comfortable way ;-)", using csvsql from csvkit, which is a python package installable via pip.

How can I limit the visible options in an HTML <select> dropdown?

You can use the size attribute to make the <select> appear as a box instead of a dropdown. The number you use in the size attribute defines how many options are visible in the box without scrolling.

<select size="5">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
    <option>11</option>
    <option>12</option>
</select>

You can’t apply this to a <select> and have it still appear as a drop-down list though. The browser/operating system will decide how many options should be displayed for drop-down lists, unless you use HTML, CSS and JavaScript to create a fake dropdown list.

Android device does not show up in adb list

I had a similar issue and solved with the following steps after connecting the device via USB:

  1. turn on developer options on the android device.
  2. enable check box for stay awake.
  3. enable check box for USB debugging.
  4. open cmd
  5. got to platform tools adt tools here https://developer.android.com/studio.
  6. adb kill-server
  7. adb start-server
  8. adb devices

Now we can see attached devices.

C++ STL Vectors: Get iterator from index?

Also; auto it = std::next(v.begin(), index);

Update: Needs a C++11x compliant compiler

How to share data between different threads In C# using AOP?

You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.

Read up on the lock statement.

lock

EDIT

Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.

public class Queue<T>
{
    /// <summary>Used as a lock target to ensure thread safety.</summary>
    private readonly Locker _Locker = new Locker();

    private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();

    /// <summary></summary>
    public void Enqueue(T item)
    {
        lock (_Locker)
        {
            _Queue.Enqueue(item);
        }
    }

    /// <summary>Enqueues a collection of items into this queue.</summary>
    public virtual void EnqueueRange(IEnumerable<T> items)
    {
        lock (_Locker)
        {
            if (items == null)
            {
                return;
            }

            foreach (T item in items)
            {
                _Queue.Enqueue(item);
            }
        }
    }

    /// <summary></summary>
    public T Dequeue()
    {
        lock (_Locker)
        {
            return _Queue.Dequeue();
        }
    }

    /// <summary></summary>
    public void Clear()
    {
        lock (_Locker)
        {
            _Queue.Clear();
        }
    }

    /// <summary></summary>
    public Int32 Count
    {
        get
        {
            lock (_Locker)
            {
                return _Queue.Count;
            }
        }
    }

    /// <summary></summary>
    public Boolean TryDequeue(out T item)
    {
        lock (_Locker)
        {
            if (_Queue.Count > 0)
            {
                item = _Queue.Dequeue();
                return true;
            }
            else
            {
                item = default(T);
                return false;
            }
        }
    }
}

EDIT 2

I hope this example helps. Remember this is bare bones. Using these basic ideas you can safely harness the power of threads.

public class WorkState
{
    private readonly Object _Lock = new Object();
    private Int32 _State;

    public Int32 GetState()
    {
        lock (_Lock)
        {
            return _State;
        }
    }

    public void UpdateState()
    {
        lock (_Lock)
        {
            _State++;   
        }   
    }
}

public class Worker
{
    private readonly WorkState _State;
    private readonly Thread _Thread;
    private volatile Boolean _KeepWorking;

    public Worker(WorkState state)
    {
        _State = state;
        _Thread = new Thread(DoWork);
        _KeepWorking = true;                
    }

    public void DoWork()
    {
        while (_KeepWorking)
        {
            _State.UpdateState();                   
        }
    }

    public void StartWorking()
    {
        _Thread.Start();
    }

    public void StopWorking()
    {
        _KeepWorking = false;
    }
}



private void Execute()
{
    WorkState state = new WorkState();
    Worker worker = new Worker(state);

    worker.StartWorking();

    while (true)
    {
        if (state.GetState() > 100)
        {
            worker.StopWorking();
            break;
        }
    }                   
}

Open files in 'rt' and 'wt' modes

The 'r' is for reading, 'w' for writing and 'a' is for appending.

The 't' represents text mode as apposed to binary mode.

Several times here on SO I've seen people using rt and wt modes for reading and writing files.

Edit: Are you sure you saw rt and not rb?

These functions generally wrap the fopen function which is described here:

http://www.cplusplus.com/reference/cstdio/fopen/

As you can see it mentions the use of b to open the file in binary mode.

The document link you provided also makes reference to this b mode:

Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.

How to capitalize the first letter in a String in Ruby

Unfortunately, it is impossible for a machine to upcase/downcase/capitalize properly. It needs way too much contextual information for a computer to understand.

That's why Ruby's String class only supports capitalization for ASCII characters, because there it's at least somewhat well-defined.

What do I mean by "contextual information"?

For example, to capitalize i properly, you need to know which language the text is in. English, for example, has only two is: capital I without a dot and small i with a dot. But Turkish has four is: capital I without a dot, capital I with a dot, small i without a dot, small i with a dot. So, in English 'i'.upcase # => 'I' and in Turkish 'i'.upcase # => 'I'. In other words: since 'i'.upcase can return two different results, depending on the language, it is obviously impossible to correctly capitalize a word without knowing its language.

But Ruby doesn't know the language, it only knows the encoding. Therefore it is impossible to properly capitalize a string with Ruby's built-in functionality.

It gets worse: even with knowing the language, it is sometimes impossible to do capitalization properly. For example, in German, 'Maße'.upcase # => 'MASSE' (Maße is the plural of Maß meaning measurement). However, 'Masse'.upcase # => 'MASSE' (meaning mass). So, what is 'MASSE'.capitalize? In other words: correctly capitalizing requires a full-blown Artificial Intelligence.

So, instead of sometimes giving the wrong answer, Ruby chooses to sometimes give no answer at all, which is why non-ASCII characters simply get ignored in downcase/upcase/capitalize operations. (Which of course also reads to wrong results, but at least it's easy to check.)

Remove Item in Dictionary based on Value

Loop through the dictionary to find the index and then remove it.

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

Check your TLS version:

python2 -c "import urllib2,json; print(json.loads(urllib2.urlopen('https://www.howsmyssl.com/a/check').read())['tls_version'])"

If your TLS version is less than 1.2 you have to upgrade it since the PyPI repository is on a brownout period of deprecating early TLS.

Source - Time To Upgrade Your Python: TLS v1.2 Will Soon Be Mandatory

You can upgrade the TLS version using the following command:

sudo apt-get update && sudo apt-get install openssl libssl-dev

This should fix your problem. Good luck!

EDIT: You can download packages using your own private python package repository regardless of TLS version. Private Python Package Repository

Simple URL GET/POST function in Python

Even easier: via the requests module.

import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)

To send data that is not form-encoded, send it serialised as a string (example taken from the documentation):

import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)

Tuples( or arrays ) as Dictionary keys in C#

Here is the .NET tuple for reference:

[Serializable] 
public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {

    private readonly T1 m_Item1; 
    private readonly T2 m_Item2;
    private readonly T3 m_Item3; 

    public T1 Item1 { get { return m_Item1; } }
    public T2 Item2 { get { return m_Item2; } }
    public T3 Item3 { get { return m_Item3; } } 

    public Tuple(T1 item1, T2 item2, T3 item3) { 
        m_Item1 = item1; 
        m_Item2 = item2;
        m_Item3 = item3; 
    }

    public override Boolean Equals(Object obj) {
        return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);; 
    }

    Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { 
        if (other == null) return false;

        Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;

        if (objTuple == null) {
            return false; 
        }

        return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3); 
    }

    Int32 IComparable.CompareTo(Object obj) {
        return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
    }

    Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
        if (other == null) return 1; 

        Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;

        if (objTuple == null) {
            throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
        }

        int c = 0;

        c = comparer.Compare(m_Item1, objTuple.m_Item1); 

        if (c != 0) return c; 

        c = comparer.Compare(m_Item2, objTuple.m_Item2);

        if (c != 0) return c; 

        return comparer.Compare(m_Item3, objTuple.m_Item3); 
    } 

    public override int GetHashCode() { 
        return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
    }

    Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { 
        return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3));
    } 

    Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
        return ((IStructuralEquatable) this).GetHashCode(comparer); 
    }
    public override string ToString() {
        StringBuilder sb = new StringBuilder();
        sb.Append("("); 
        return ((ITuple)this).ToString(sb);
    } 

    string ITuple.ToString(StringBuilder sb) {
        sb.Append(m_Item1); 
        sb.Append(", ");
        sb.Append(m_Item2);
        sb.Append(", ");
        sb.Append(m_Item3); 
        sb.Append(")");
        return sb.ToString(); 
    } 

    int ITuple.Size { 
        get {
            return 3;
        }
    } 
}

How to convert a String to Bytearray

You don't need underscore, just use built-in map:

_x000D_
_x000D_
var string = 'Hello World!';_x000D_
_x000D_
document.write(string.split('').map(function(c) { return c.charCodeAt(); }));
_x000D_
_x000D_
_x000D_

Get login username in java

inspired by @newacct's answer, a code that can be compiled in any platform:

String osName = System.getProperty( "os.name" ).toLowerCase();
String className = null;
String methodName = "getUsername";

if( osName.contains( "windows" ) ){
    className = "com.sun.security.auth.module.NTSystem";
    methodName = "getName";
}
else if( osName.contains( "linux" ) ){
    className = "com.sun.security.auth.module.UnixSystem";
}
else if( osName.contains( "solaris" ) || osName.contains( "sunos" ) ){
    className = "com.sun.security.auth.module.SolarisSystem";
}

if( className != null ){
    Class<?> c = Class.forName( className );
    Method method = c.getDeclaredMethod( methodName );
    Object o = c.newInstance();
    System.out.println( method.invoke( o ) );
}

CSS: image link, change on hover

That could be done with <a> only:

#twitterbird {
 display: block; /* 'convert' <a> to <div> */
 margin-bottom: 10px;
 background-position: center top;
 background-repeat: no-repeat;
 width: 160px;
 height: 160px;
 background-image: url('twitterbird.png');
}
#twitterbird:hover {
 background-image: url('twitterbird_hover.png');
}

wget: unable to resolve host address `http'

I figured out what went wrong. In the proxy configuration of my box, an extra http:// got prefixed to "proxy server with http".

Example..

http://http://proxy.mycollege.com

and that has created problems. Corrected that, and it works perfectly.

Thanks @WhiteCoffee and @ChrisBint for your suggestions!

How do I set GIT_SSL_NO_VERIFY for specific repos only?

You can do

git config http.sslVerify "false"

in your specific repo to disable SSL certificate checking for that repo only.

How to increase request timeout in IIS?

In IIS Manager, right click on the site and go to Manage Web Site -> Advanced Settings. Under Connection Limits option, you should see Connection Time-out.

How to use goto statement correctly

goto is an unused reserved word in the language. So there is no goto. But, if you want absurdist theater you could coax one out of a language feature of labeling. But, rather than label a for loop which is sometimes useful you label a code block. You can, within that code block, call break on the label, spitting you to the end of the code block which is basically a goto, that only jumps forward in code.

    System.out.println("1");
    System.out.println("2");
    System.out.println("3");
    my_goto:
    {
        System.out.println("4");
        System.out.println("5");
        if (true) break my_goto;
        System.out.println("6");
    } //goto end location.
    System.out.println("7");
    System.out.println("8");

This will print 1, 2, 3, 4, 5, 7, 8. As the breaking the code block jumped to just after the code block. You can move the my_goto: { and if (true) break my_goto; and } //goto end location. statements. The important thing is just the break must be within the labeled code block.

This is even uglier than a real goto. Never actually do this.

But, it is sometimes useful to use labels and break and it is actually useful to know that if you label the code block and not the loop when you break you jump forward. So if you break the code block from within the loop, you not only abort the loop but you jump over the code between the end of the loop and the codeblock.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

The accounts property is defined like this:

"accounts":{"github":"sergiotapia"}

Your POCO states this:

public List<Account> Accounts { get; set; }

Try using this Json:

"accounts":[{"github":"sergiotapia"}]

An array of items (which is going to be mapped to the list) is always enclosed in square brackets.

Edit: The Account Poco will be something like this:

class Account {
    public string github { get; set; }
}

and maybe other properties.

Edit 2: To not have an array use the property as follows:

public Account Accounts { get; set; }

with something like the sample class I've posted in the first edit.

Sum values in a column based on date

Use pivot tables, it will definitely save you time. If you are using excel 2007+ use tables (structured references) to keep your table dynamic. However if you insist on using functions, go with Smandoli's suggestion. Again, if you are on 2007+ use SUMIFS, it's faster compared to SUMIF.

How to close activity and go back to previous activity in android

Finish closes the whole application, this is is something i hate in Android development not finish that is fine but that they do not keep up wit ok syntax they have

startActivity(intent)

Why not

closeActivity(intent) ?

AngularJS: Can't I set a variable value on ng-click?

If you are using latest versions of Angular (2/5/6) :

In your component.ts

//x.component.ts
prefs = false;

hidePrefs(){
   this.prefs = true;
}

How to check if a subclass is an instance of a class at runtime?

Maybe I'm missing something, but wouldn't this suffice:

if (view instanceof B) {
    // this view is an instance of B
}

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

For myself, I had to do:

yum remove mysql*

rm -rf /var/lib/mysql/
cp /etc/my.cnf ~/my.cnf.bkup

yum install -y mysql-server mysql-client

mysql_install_db

chown -R mysql:mysql /var/lib/mysql
chown -R mysql:mysql /var/log/mysql

service mysql start

Then I was able to get back into my databases and configure them again after I nuked them the first go around.

How to display table data more clearly in oracle sqlplus

You can set the line size as per the width of the window and set wrap off using the following command.

set linesize 160;
set wrap off;

I have used 160 as per my preference you can set it to somewhere between 100 - 200 and setting wrap will not your data and it will display the data properly.

How to check for a valid Base64 encoded string

It's pretty easy to recognize a Base64 string, as it will only be composed of characters 'A'..'Z', 'a'..'z', '0'..'9', '+', '/' and it is often padded at the end with up to three '=', to make the length a multiple of 4. But instead of comparing these, you'd be better off ignoring the exception, if it occurs.

cannot make a static reference to the non-static field

main is a static method. It cannot refer to balance, which is an attribute (non-static variable). balance has meaning only when it is referred through an object reference (such as myAccount.balance or yourAccount.balance). But it doesn't have any meaning when it is referred through class (such as Account.balance (whose balance is that?))

I made some changes to your code so that it compiles.

public static void main(String[] args) {
    Account account = new Account(1122, 20000, 4.5);
    account.withdraw(2500);
    account.deposit(3000);

and:

public void withdraw(double withdrawAmount) {
    balance -= withdrawAmount;
}

public void deposit(double depositAmount) {
    balance += depositAmount;
}   

how to increase the limit for max.print in R

Use the options command, e.g. options(max.print=1000000).

See ?options:

 ‘max.print’: integer, defaulting to ‘99999’.  ‘print’ or ‘show’
      methods can make use of this option, to limit the amount of
      information that is printed, to something in the order of
      (and typically slightly less than) ‘max.print’ _entries_.

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

You can wrap all tasks which can fail in block, and use ignore_errors: yes with that block.

tasks:
  - name: ls
    command: ls -la
  - name: pwd
    command: pwd

  - block:
    - name: ls non-existing txt file
      command: ls -la no_file.txt
    - name: ls non-existing pic
      command: ls -la no_pic.jpg
    ignore_errors: yes 

Read more about error handling in blocks here.

TensorFlow not found using pip

Nothing here worked for me on Windows 10. Perhaps an updated solution below that did work for me.

python -m pip install --upgrade tensorflow.

This is using Python 3.6 and tensorflow 1.5 on Windows 10

are there dictionaries in javascript like python?

I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

var dict = new Map();
dict.set("foo", "bar");

//returns "bar"
dict.get("foo");

Unlike javascript's normal objects, it allows any object as a key:

var foo = {};
var bar = {};
var dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");

//returns "Bar"
dict.get(bar);

//returns "Foo"
dict.get(foo);

//returns undefined, as {} !== foo and {} !== bar
dict.get({});

Cant get text of a DropDownList in code - can get value but not text

Have a look here, this has a proof-of-concept page and demo you can use to get anything from the drop-down: asp:DropDownList Control Tutorial Page

How do I exit from a function?

There are two ways to exit a method early (without quitting the program):

i) Use the return keyword.
ii) Throw an exception.

Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.

If your method returns void then you can write return without a value:

return;

What's the difference between "&nbsp;" and " "?

As already mentioned, you will not receive a line break where there is a "no-break space".

Also be wary, that elements containing only a " " may show up incorrectly, where &nbsp; will work. In i.e. 6 at least (as far as I remember, IE7 has the same issue), if you have an empty table element, it will not apply styling, for example borders, to the element, if there is no content, or only white space. So the following will not be rendered with borders:

<td></td>
<td> <td>

Whereas the borders will show up in this example:

<td>& nbsp;</td>

Hmm -had to put in a dummy space to get it to render correctly here

Trigger an event on `click` and `enter`

Use keypress event on usersSearch textbox and look for Enter button. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.

$('document').ready(function(){
    $('#searchButton').click(function(){
        var search = $('#usersSearch').val();
        $.post('../searchusers.php',{search: search},function(response){
            $('#userSearchResultsTable').html(response);
        });
    })
    $('#usersSearch').keypress(function(e){
        if(e.which == 13){//Enter key pressed
            $('#searchButton').click();//Trigger search button click event
        }
    });

});

Demo

ERROR 2003 (HY000): Can't connect to MySQL server (111)

if the system you use is CentOS/RedHat, and rpm is the way you install MySQL, there is no my.cnf in /etc/ folder, you could use: #whereis mysql #cd /usr/share/mysql/ cp -f /usr/share/mysql/my-medium.cnf /etc/my.cnf

get an element's id

Yes you can simply say:


function getID(oObject) 
{
    var id = oObject.id;
    alert("This object's ID attribute is set to \"" + id + "\"."); 
}

Check this out: ID Attribute | id Property

Retrieve filename from file descriptor in C

In Windows, with GetFileInformationByHandleEx, passing FileNameInfo, you can retrieve the file name.

C# : changing listbox row color?

You will need to draw the item yourself. Change the DrawMode to OwnerDrawFixed and handle the DrawItem event.

/// <summary>
/// Handles the DrawItem event of the listBox1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.DrawItemEventArgs"/> instance containing the event data.</param>
private void listBox1_DrawItem( object sender, DrawItemEventArgs e )
{
   e.DrawBackground();
   Graphics g = e.Graphics;

    // draw the background color you want
    // mine is set to olive, change it to whatever you want
    g.FillRectangle( new SolidBrush( Color.Olive), e.Bounds );

    // draw the text of the list item, not doing this will only show
    // the background color
    // you will need to get the text of item to display
    g.DrawString( THE_LIST_ITEM_TEXT , e.Font, new SolidBrush( e.ForeColor ), new PointF( e.Bounds.X, e.Bounds.Y) );

    e.DrawFocusRectangle();
}

Using PHP to upload file and add the path to MySQL database

mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

These are deprecated use the following..

 // Connects to your Database
            $link = mysqli_connect("localhost", "root", "", "");

and to insert data use the following

 $sql = "INSERT INTO  Table-Name (Column-Name)
VALUES ('$filename')" ;

How to format number of decimal places in wpf using style/template?

You should use the StringFormat on the Binding. You can use either standard string formats, or custom string formats:

<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />

Note that the StringFormat only works when the target property is of type string. If you are trying to set something like a Content property (typeof(object)), you will need to use a custom StringFormatConverter (like here), and pass your format string as the ConverterParameter.

Edit for updated question

So, if your ViewModel defines the precision, I'd recommend doing this as a MultiBinding, and creating your own IMultiValueConverter. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format.

However, for things like a ContentControl, you can much more easily do this with a Style:

<Style TargetType="{x:Type ContentControl}">
    <Setter Property="ContentStringFormat" 
            Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>

Any control that exposes a ContentStringFormat can be used like this. Unfortunately, TextBox doesn't have anything like that.

ORACLE convert number to string

Using the FM format model modifier to get close, as you won't get the trailing zeros after the decimal separator; but you will still get the separator itself, e.g. 50.. You can use rtrim to get rid of that:

select to_char(a, '99D90'),
    to_char(a, '90D90'),
    to_char(a, 'FM90D99'),
    rtrim(to_char(a, 'FM90D99'), to_char(0, 'D'))
from (
    select 50 a from dual
    union all select 50.57 from dual
    union all select 5.57 from dual
    union all select 0.35 from dual
    union all select 0.4 from dual
)
order by a;

TO_CHA TO_CHA TO_CHA RTRIM(
------ ------ ------ ------
   .35   0.35 0.35   0.35
   .40   0.40 0.4    0.4
  5.57   5.57 5.57   5.57
 50.00  50.00 50.    50
 50.57  50.57 50.57  50.57

Note that I'm using to_char(0, 'D') to generate the character to trim, to match the decimal separator - so it looks for the same character, , or ., as the first to_char adds.

The slight downside is that you lose the alignment. If this is being used elsewhere it might not matter, but it does then you can also wrap it in an lpad, which starts to make it look a bit complicated:

...
lpad(rtrim(to_char(a, 'FM90D99'), to_char(0, 'D')), 6)
...

TO_CHA TO_CHA TO_CHA RTRIM( LPAD(RTRIM(TO_CHAR(A,'FM
------ ------ ------ ------ ------------------------
   .35   0.35 0.35   0.35     0.35
   .40   0.40 0.4    0.4       0.4
  5.57   5.57 5.57   5.57     5.57
 50.00  50.00 50.    50         50
 50.57  50.57 50.57  50.57   50.57

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

Java2D: Increase the line width

You should use setStroke to set a stroke of the Graphics2D object.

The example at http://www.java2s.com gives you some code examples.

The following code produces the image below:

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(10));
                g2.draw(new Line2D.Float(30, 20, 80, 90));
            }
        });
        jf.setSize(300, 200);
        jf.setVisible(true);
    }
}

enter image description here

(Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


This post has been rewritten as an article here.

How to open a new file in vim in a new window

I'm using the following, though it's hardcoded for gnome-terminal. It also changes the CWD and buffer for vim to be the same as your current buffer and it's directory.

:silent execute '!gnome-terminal -- zsh -i -c "cd ' shellescape(expand("%:h")) '; vim' shellescape(expand("%:p")) '; zsh -i"' <cr>

Space between two rows in a table?

The correct way to give spacing for tables is to use cellpadding and cellspacing e.g.

<table cellpadding="4">

Change class on mouseover in directive

This is my solution for my scenario:

<div class="btn-group btn-group-justified">
    <a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
        {{ song.name }}
    </a>
    <a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
        <i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
        {{ match.name }}
    </a>
</div>

default state: enter image description here

on hover: enter image description here

Best practice: PHP Magic Methods __set and __get

I vote for a third solution. I use this in my projects and Symfony uses something like this too:

public function __call($val, $x) {
    if(substr($val, 0, 3) == 'get') {
        $varname = strtolower(substr($val, 3));
    }
    else {
        throw new Exception('Bad method.', 500);
    }
    if(property_exists('Yourclass', $varname)) {
        return $this->$varname;
    } else {
        throw new Exception('Property does not exist: '.$varname, 500);
    }
}

This way you have automated getters (you can write setters too), and you only have to write new methods if there is a special case for a member variable.

How to convert DateTime? to DateTime

You want to use the null-coalescing operator, which is designed for exactly this purpose.

Using it you end up with this code.

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;

Change URL parameters

No library, using URL() WebAPI (https://developer.mozilla.org/en-US/docs/Web/API/URL)

function setURLParameter(url, parameter, value) {
    let url = new URL(url);
    if (url.searchParams.get(parameter) === value) {
        return url;
    }
    url.searchParams.set(parameter, value);
    return url.href;
}

This doesn't work on IE: https://developer.mozilla.org/en-US/docs/Web/API/URL#Browser_compatibility

Remove non-numeric characters (except periods and commas) from a string

I'm surprised there's been no mention of filter_var here for this being such an old question...

PHP has a built in method of doing this using sanitization filters. Specifically, the one to use in this situation is FILTER_SANITIZE_NUMBER_FLOAT with the FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND flags. Like so:

$numeric_filtered = filter_var("AR3,373.31", FILTER_SANITIZE_NUMBER_FLOAT,
    FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
echo $numeric_filtered; // Will print "3,373.31"

It might also be worthwhile to note that because it's built-in to PHP, it's slightly faster than using regex with PHP's current libraries (albeit literally in nanoseconds).

Why are interface variables static and final by default?

An Interface is contract between two parties that is invariant, carved in the stone, hence final. See Design by Contract.

How to get the size of a varchar[n] field in one SQL statement?

For SQL Server (2008 and above):

SELECT COLUMNPROPERTY(OBJECT_ID('mytable'), 'Remarks', 'PRECISION');

COLUMNPROPERTY returns information for a column or parameter (id, column/parameter, property). The PRECISION property returns the length of the data type of the column or parameter.

COLUMNPROPERTY documentation

How to display 3 buttons on the same line in css

Do something like this,

HTML :

<div style="width:500px;">
    <button type="submit" class="msgBtn" onClick="return false;" >Save</button>
    <button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
    <button class="msgBtnBack">Back</button>
</div>

CSS :

div button{
    display:inline-block;
}

Fiddle Demo

Or

HTML :

<div style="width:500px;" id="container">
    <div><button type="submit" class="msgBtn" onClick="return false;" >Save</button></div>
    <div><button type="submit" class="msgBtn2" onClick="return false;">Publish</button></div>
    <div><button class="msgBtnBack">Back</button></div>
</div>

CSS :

#container div{
    display:inline-block;
    width:130px;
}

Fiddle Demo

Android : Check whether the phone is dual SIM

I am able to read both the IMEI's from OnePlus 2 Phone

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                TelephonyManager manager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
                Log.i(TAG, "Single or Dual Sim " + manager.getPhoneCount());
                Log.i(TAG, "Default device ID " + manager.getDeviceId());
                Log.i(TAG, "Single 1 " + manager.getDeviceId(0));
                Log.i(TAG, "Single 2 " + manager.getDeviceId(1));
            }

How to get/generate the create statement for an existing hive table?

Describe Formatted/Extended will show the data definition of the table in hive

hive> describe Formatted dbname.tablename;

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

CSS last-child(-1)

You can use :nth-last-child(); in fact, besides :nth-last-of-type() I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.

ul li:nth-last-child(2)

How to restart VScode after editing extension's config?

You can do the following

  1. Click on extensions
  2. Type Reload
  3. Then install

It will add a reload button on your right hand at the bottom of the vs code.

Node.js Generate html

You can use jsdom

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;

or, take a look at cheerio, it may more suitable in your case.

How to revert multiple git commits?

Expanding what I wrote in a comment

The general rule is that you should not rewrite (change) history that you have published, because somebody might have based their work on it. If you rewrite (change) history, you would make problems with merging their changes and with updating for them.

So the solution is to create a new commit which reverts changes that you want to get rid of. You can do this using git revert command.

You have the following situation:

A <-- B  <-- C <-- D                                  <-- master <-- HEAD

(arrows here refers to the direction of the pointer: the "parent" reference in the case of commits, the top commit in the case of branch head (branch ref), and the name of branch in the case of HEAD reference).

What you need to create is the following:

A <-- B  <-- C <-- D <-- [(BCD)-1]                   <-- master <-- HEAD

where [(BCD)^-1] means the commit that reverts changes in commits B, C, D. Mathematics tells us that (BCD)-1 = D-1 C-1 B-1, so you can get the required situation using the following commands:

$ git revert --no-commit D
$ git revert --no-commit C
$ git revert --no-commit B
$ git commit -m "the commit message for all of them"

Works for everything except merge commits.


Alternate solution would be to checkout contents of commit A, and commit this state. Also works with merge commits. Added files will not be deleted, however. If you have any local changes git stash them first:

$ git checkout -f A -- . # checkout that revision over the top of local files
$ git commit -a

Then you would have the following situation:

A <-- B  <-- C <-- D <-- A'                       <-- master <-- HEAD

The commit A' has the same contents as commit A, but is a different commit (commit message, parents, commit date).


Alternate solution by Jeff Ferland, modified by Charles Bailey builds upon the same idea, but uses git reset. Here it is slightly modified, this way WORKS FOR EVERYTHING:

$ git reset --hard A
$ git reset --soft D # (or ORIG_HEAD or @{1} [previous location of HEAD]), all of which are D
$ git commit

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Adding following property to your persistence.xml may solve your problem temporarily

<property name="hibernate.enable_lazy_load_no_trans" value="true" />

As @vlad-mihalcea said it's an antipattern and does not solve lazy initialization issue completely, initialize your associations before closing transaction and use DTOs instead.

Most efficient way to see if an ArrayList contains an object in Java

You could use a Comparator with Java's built-in methods for sorting and binary search. Suppose you have a class like this, where a and b are the fields you want to use for sorting:

class Thing { String a, b, c, d; }

You would define your Comparator:

Comparator<Thing> comparator = new Comparator<Thing>() {
  public int compare(Thing o1, Thing o2) {
    if (o1.a.equals(o2.a)) {
      return o1.b.compareTo(o2.b);
    }
    return o1.a.compareTo(o2.a);
  }
};

Then sort your list:

Collections.sort(list, comparator);

And finally do the binary search:

int i = Collections.binarySearch(list, thingToFind, comparator);

sed: print only matching group

grep is the right tool for extracting.

using your example and your regex:

kent$  echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4

How to connect Android app to MySQL database?

Use android vollley, it is very fast and you can betterm manipulate requests. Send post request using Volley and receive in PHP

Basically, you will create a map with key-value params for the php request(POST/GET), the php will do the desired processing and you will return the data as JSON(json_encode()). Then you can either parse the JSON as needed or use GSON from Google to let it do the parsing.

jQuery get an element by its data-id

Yes, you can find out element by data attribute.

element = $('a[data-item-id="stand-out"]');

Print <div id="printarea"></div> only?

You can use this: http://vikku.info/codesnippets/javascript/print-div-content-print-only-the-content-of-an-html-element-and-not-the-whole-document/

Or use visibility:visible and visibility:hidden css property together with @media print{}

'display:none' will hide all nested 'display:block'. That is not solution.

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

How to convert URL parameters to a JavaScript object?

I needed to also deal with + in the query part of the URL (decodeURIComponent doesn't), so I adapted Wolfgang's code to become:

var search = location.search.substring(1);
search = search?JSON.parse('{"' + search.replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)}):{};

In my case, I'm using jQuery to get URL-ready form parameters, then this trick to build an object out of it and I can then easily update parameters on the object and rebuild the query URL, e.g.:

var objForm = JSON.parse('{"' + $myForm.serialize().replace(/\+/g, ' ').replace(/&/g, '","').replace(/=/g,'":"') + '"}',
             function(key, value) { return key===""?value:decodeURIComponent(value)});
objForm.anyParam += stringToAddToTheParam;
var serializedForm = $.param(objForm);

Log4net does not write the log in the log file

Make sure the following line code should be there in AssemblyInfo.cs file.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]

and also check for this line in Application_start() method.

log4net.Config.XmlConfigurator.Configure();

git pull error "The requested URL returned error: 503 while accessing"

As in "CocoaPods - pod setup http request failed", a 503 error on accessing (cloning) a public repository is likely to be the result of a GitHub glitch (availability issue)

Retrying later usually works.

How to accept Date params in a GET request to Spring MVC Controller?

... or you can do it the right way and have a coherent rule for serialisation/deserialisation of dates all across your application. put this in application.properties:

spring.mvc.date-format=yyyy-MM-dd

Can you use Microsoft Entity Framework with Oracle?

Oracle have announced a "statement of direction" for ODP.net and the Entity Framework:

In summary, ODP.Net beta around the end of 2010, production sometime in 2011.

Eclipse java debugging: source not found

In eclipse photon try to turn off "Window->Preferences->Java->Debug->Use advanced source lookup"

Edit: There is a related bug in this version of eclipse which leads to a "source not found" message while debugging Java applications. See bug report bugs.eclipse.org/bugs/show_bug.cgi?id=537699 for more details

How to install lxml on Ubuntu

Since you're on Ubuntu, don't bother with those source packages. Just install those development packages using apt-get.

apt-get install libxml2-dev libxslt1-dev python-dev

If you're happy with a possibly older version of lxml altogether though, you could try

apt-get install python-lxml

and be done with it. :)

What is the most efficient way to store a list in the Django models?

If you are using Django >= 1.9 with Postgres you can make use of ArrayField advantages

A field for storing lists of data. Most field types can be used, you simply pass another field instance as the base_field. You may also specify a size. ArrayField can be nested to store multi-dimensional arrays.

It is also possible to nest array fields:

from django.contrib.postgres.fields import ArrayField
from django.db import models

class ChessBoard(models.Model):
    board = ArrayField(
        ArrayField(
            models.CharField(max_length=10, blank=True),
            size=8,
        ),
        size=8,
    )

As @thane-brimhall mentioned it is also possible to query elements directly. Documentation reference

adb command not found in linux environment

Ubuntu 18.04

This worked for me:

  1. Find out and copy platform-tools path, in my case is '/home/daniel/Android/Sdk/platform-tools'
  2. Open bashrc nano ~/.bashrc
  3. Save platform-tools path export PATH="${PATH}:/home/daniel/Android/Sdk/platform-tools"
  4. Reset bash_profile source .bash_profile
  5. adb devices is now working

java.net.BindException: Address already in use: JVM_Bind <null>:80

Use the following command to find if your tomcat port is already in use,

netstat -a -b

netstat -a -o | findstr :port

For example

netstat -a -o | findstr :8080

Exception: java.net.BindException: Address already in use: JVM_Bind:80

means that port 80 is configured by your Tomcat server and it is already used by some other application running on your computer. Please quit Skype if open or change the default port in Skype or other application's port to something other than 80. Or change the tomcat port to something else than 80(e.g. 8080 or 9090) in the server.xml file under the config folder of your tomcat installation directory.

Exception: java.net.BindException: Address already in use: JVM_Bind

means you din't stop the tomcat server properly and you are trying to start the server again. In Eclipse, the solution for me was to remove the project from the servers tab and right click and run the project as Run on server. This added the project back to the Tomcat 7 and I din't get the BindException error. This was due to closing eclipse the last time you used without stopping the Tomcat server.

How can I ping a server port with PHP?

Test different ports:

$wait = 1; // wait Timeout In Seconds
$host = 'example.com';
$ports = [
    'http'  => 80,
    'https' => 443,
    'ftp'   => 21,
];

foreach ($ports as $key => $port) {
    $fp = @fsockopen($host, $port, $errCode, $errStr, $wait);
    echo "Ping $host:$port ($key) ==> ";
    if ($fp) {
        echo 'SUCCESS';
        fclose($fp);
    } else {
        echo "ERROR: $errCode - $errStr";
    }
    echo PHP_EOL;
}


// Ping example.com:80 (http) ==> SUCCESS
// Ping example.com:443 (https) ==> SUCCESS
// Ping example.com:21 (ftp) ==> ERROR: 110 - Connection timed out

Ant error when trying to build file, can't find tools.jar?

Just set your java_home property with java home (eg:C:\Program Files\Java\jdk1.7.0_25) directory. Close command prompt and reopen it. Then error relating to tools.jar will be solved. For the second one("build.xml not found ") you should have to ensure your command line also at the directory where your build.xml file resides.

Recover unsaved SQL query scripts

SSMSBoost add-in (currently free)

  • keeps track on all executed statements (saves them do disk)
  • regulary saves snapshot of SQL Editor contents. You keep history of the modifications of your script. Sometimes "the best" version is not the last and you want to restore the intermediate state.
  • keeps track of opened tabs and allows to restore them after restart. Unsaved tabs are also restored.

+tons of other features. (I am the developer of the add-in)

Access 2013 - Cannot open a database created with a previous version of your application

In case you just need to dump the data you can use this clever script http://youaccess.sourceforge.net . In case you are under linux / wine you can try my procedure

How do I programmatically set device orientation in iOS 7?

  1. Add this statement into AppDelegate.h

    //whether to allow cross screen marker 
    @property (nonatomic, assign) allowRotation BOOL;
    
  2. Write down this section of code into AppDelegate.m

    - (UIInterfaceOrientationMask) application: (UIApplication *) supportedInterfaceOrientationsForWindow: application (UIWindow *) window {
        If (self.allowRotation) {
            UIInterfaceOrientationMaskAll return;
        }
        UIInterfaceOrientationMaskPortrait return;
    }
    
  3. Change the allowRotation property of delegate app

How to hide a div after some time period?

_x000D_
_x000D_
$().ready(function(){_x000D_
_x000D_
  $('div.alert').delay(1500);_x000D_
   $('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
_x000D_
_x000D_

How to show soft-keyboard when edittext is focused

Worked for me after adding this lines.

globalSearchBarMainActivity.setEnabled(true);
globalSearchBarMainActivity.requestFocus();

As my auto complete text view method was hidden i.e. VISIBLE: GONE

So needed to add above two line

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(globalSearchBarMainActivity, InputMethodManager.SHOW_IMPLICIT);

How to put sshpass command inside a bash script?

This worked for me:

#!/bin/bash

#Variables
FILELOCAL=/var/www/folder/$(date +'%Y%m%d_%H-%M-%S').csv    
SFTPHOSTNAME="myHost.com"
SFTPUSERNAME="myUser"
SFTPPASSWORD="myPass"
FOLDER="myFolderIfNeeded"
FILEREMOTE="fileNameRemote"

#SFTP CONNECTION
sshpass -p $SFTPPASSWORD sftp $SFTPUSERNAME@$SFTPHOSTNAME << !
    cd $FOLDER
    get $FILEREMOTE $FILELOCAL
    ls
   bye
!

Probably you have to install sshpass:

sudo apt-get install sshpass

DATEDIFF function in Oracle

In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a select statement without a from clause. One way around this is to use the builtin dummy table, dual:

SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -  
       TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM   dual

Where does the iPhone Simulator store its data?

I have no affiliation with this program, but if you are looking to open any of this in the finder SimPholders makes it incredibly easy.

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

Based on different answers but mainly on this, this works for what I need:

UIImage *image1 = ...; // The image from where you want a pixel data
int pixelX = ...; // The X coordinate of the pixel you want to retrieve
int pixelY = ...; // The Y coordinate of the pixel you want to retrieve

uint32_t pixel1; // Where the pixel data is to be stored
CGContextRef context1 = CGBitmapContextCreate(&pixel1, 1, 1, 8, 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
CGContextDrawImage(context1, CGRectMake(-pixelX, -pixelY, CGImageGetWidth(image1.CGImage), CGImageGetHeight(image1.CGImage)), image1.CGImage);
CGContextRelease(context1);

As a result of this lines, you will have a pixel in AARRGGBB format with alpha always set to FF in the 4 byte unsigned integer pixel1.

Read input from console in Ruby?

There are many ways to take input from the users. I personally like using the method gets. When you use gets, it gets the string that you typed, and that includes the ENTER key that you pressed to end your input.

name = gets
"mukesh\n"

You can see this in irb; type this and you will see the \n, which is the “newline” character that the ENTER key produces: Type name = gets you will see somethings like "mukesh\n" You can get rid of pesky newline character using chomp method.

The chomp method gives you back the string, but without the terminating newline. Beautiful chomp method life saviour.

name = gets.chomp
"mukesh"

You can also use terminal to read the input. ARGV is a constant defined in the Object class. It is an instance of the Array class and has access to all the array methods. Since it’s an array, even though it’s a constant, its elements can be modified and cleared with no trouble. By default, Ruby captures all the command line arguments passed to a Ruby program (split by spaces) when the command-line binary is invoked and stores them as strings in the ARGV array.

When written inside your Ruby program, ARGV will take take a command line command that looks like this:

test.rb hi my name is mukesh

and create an array that looks like this:

["hi", "my", "name", "is", "mukesh"]

But, if I want to passed limited input then we can use something like this.

test.rb 12 23

and use those input like this in your program:

a = ARGV[0]
b = ARGV[1]

shorthand c++ if else statement

Depending on how often you use this in your code you could consider the following:

macro

#define SIGN(x) ( (x) >= 0 )

Inline function

inline int sign(int x)
{
    return x >= 0;
}

Then you would just go:

bigInt.sign = sign(number); 

How do I perform the SQL Join equivalent in MongoDB?

MongoDB does not allow joins, but you can use plugins to handle that. Check the mongo-join plugin. It's the best and I have already used it. You can install it using npm directly like this npm install mongo-join. You can check out the full documentation with examples.

(++) really helpful tool when we need to join (N) collections

(--) we can apply conditions just on the top level of the query

Example

var Join = require('mongo-join').Join, mongodb = require('mongodb'), Db = mongodb.Db, Server = mongodb.Server;
db.open(function (err, Database) {
    Database.collection('Appoint', function (err, Appoints) {

        /* we can put conditions just on the top level */
        Appoints.find({_id_Doctor: id_doctor ,full_date :{ $gte: start_date },
            full_date :{ $lte: end_date }}, function (err, cursor) {
            var join = new Join(Database).on({
                field: '_id_Doctor', // <- field in Appoints document
                to: '_id',         // <- field in User doc. treated as ObjectID automatically.
                from: 'User'  // <- collection name for User doc
            }).on({
                field: '_id_Patient', // <- field in Appoints doc
                to: '_id',         // <- field in User doc. treated as ObjectID automatically.
                from: 'User'  // <- collection name for User doc
            })
            join.toArray(cursor, function (err, joinedDocs) {

                /* do what ever you want here */
                /* you can fetch the table and apply your own conditions */
                .....
                .....
                .....


                resp.status(200);
                resp.json({
                    "status": 200,
                    "message": "success",
                    "Appoints_Range": joinedDocs,


                });
                return resp;


            });

    });

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Visual Studio Code terminal (Ctrl + `)
  2. Write the Git clone command. For example,

    git clone https://github.com/angular/angular-phonecat.git
    
  3. Open the folder you have just cloned (menu FileOpen Folder)

    Enter image description here

How to print a int64_t type in C

With C99 the %j length modifier can also be used with the printf family of functions to print values of type int64_t and uint64_t:

#include <stdio.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
    int64_t  a = 1LL << 63;
    uint64_t b = 1ULL << 63;

    printf("a=%jd (0x%jx)\n", a, a);
    printf("b=%ju (0x%jx)\n", b, b);

    return 0;
}

Compiling this code with gcc -Wall -pedantic -std=c99 produces no warnings, and the program prints the expected output:

a=-9223372036854775808 (0x8000000000000000)
b=9223372036854775808 (0x8000000000000000)

This is according to printf(3) on my Linux system (the man page specifically says that j is used to indicate a conversion to an intmax_t or uintmax_t; in my stdint.h, both int64_t and intmax_t are typedef'd in exactly the same way, and similarly for uint64_t). I'm not sure if this is perfectly portable to other systems.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

A ClusterIP exposes the following:

  • spec.clusterIp:spec.ports[*].port

You can only access this service while inside the cluster. It is accessible from its spec.clusterIp port. If a spec.ports[*].targetPort is set it will route from the port to the targetPort. The CLUSTER-IP you get when calling kubectl get services is the IP assigned to this service within the cluster internally.

A NodePort exposes the following:

  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

If you access this service on a nodePort from the node's external IP, it will route the request to spec.clusterIp:spec.ports[*].port, which will in turn route it to your spec.ports[*].targetPort, if set. This service can also be accessed in the same way as ClusterIP.

Your NodeIPs are the external IP addresses of the nodes. You cannot access your service from spec.clusterIp:spec.ports[*].nodePort.

A LoadBalancer exposes the following:

  • spec.loadBalancerIp:spec.ports[*].port
  • <NodeIP>:spec.ports[*].nodePort
  • spec.clusterIp:spec.ports[*].port

You can access this service from your load balancer's IP address, which routes your request to a nodePort, which in turn routes the request to the clusterIP port. You can access this service as you would a NodePort or a ClusterIP service as well.

Can I call a base class's virtual function if I'm overriding it?

Yes,

class Bar : public Foo
{
    ...

    void printStuff()
    {
        Foo::printStuff();
    }
};

It is the same as super in Java, except it allows calling implementations from different bases when you have multiple inheritance.

class Foo {
public:
    virtual void foo() {
        ...
    }
};

class Baz {
public:
    virtual void foo() {
        ...
    }
};

class Bar : public Foo, public Baz {
public:
    virtual void foo() {
        // Choose one, or even call both if you need to.
        Foo::foo();
        Baz::foo();
    }
};

How to remove package using Angular CLI?

npm uninstal @angular/material

and also clear file custom-theme.scss

Where is the default log location for SharePoint/MOSS?

For SharePoint 2016

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs

For SharePoint 2013

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs

For SharePoint 2010

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\14\Logs

For SharePoint 2007

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\12\Logs

Note: The sharePoint Trace log path can be changed by opening Central Administration > Monitoring > Reporting > Configure Diagnostic Logs

For more details check SHAREPOINT ULS VIEWER

SQLite error 'attempt to write a readonly database' during insert?

I used:

echo exec('whoami');

to find out who is running the script (say username), and then gave the user permissions to the entire application directory, like:

sudo chown -R :username /var/www/html/myapp

Hope this helps someone out there.

how to cancel/abort ajax request in axios

Using useEffect hook:

useEffect(() => {
  const ourRequest = Axios.CancelToken.source() // <-- 1st step

  const fetchPost = async () => {
    try {
      const response = await Axios.get(`endpointURL`, {
        cancelToken: ourRequest.token, // <-- 2nd step
      })
      console.log(response.data)
      setPost(response.data)
      setIsLoading(false)
    } catch (err) {
      console.log('There was a problem or request was cancelled.')
    }
  }
  fetchPost()

  return () => {
    ourRequest.cancel() // <-- 3rd step
  }
}, [])

Note: For POST request, pass cancelToken as 3rd argument

Axios.post(`endpointURL`, {data}, {
 cancelToken: ourRequest.token, // 2nd step
})

How to increase MySQL connections(max_connections)?

From Increase MySQL connection limit:-

MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:

For MySQL 3.x:

# vi /etc/my.cnf
set-variable = max_connections = 250

For MySQL 4.x and 5.x:

# vi /etc/my.cnf
max_connections = 250

Restart MySQL once you’ve made the changes and verify with:

echo "show variables like 'max_connections';" | mysql

EDIT:-(From comments)

The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

Same question : how-to-update-the-gui-from-another-thread-in-c

Two Ways:

  1. Return value in e.result and use it to set yout textbox value in backgroundWorker_RunWorkerCompleted event

  2. Declare some variable to hold these kind of values in a separate class (which will work as data holder) . Create static instance of this class adn you can access it over any thread.

Example:

public  class data_holder_for_controls
{
    //it will hold value for your label
    public  string status = string.Empty;
}

class Demo
{
    public static  data_holder_for_controls d1 = new data_holder_for_controls();
    static void Main(string[] args)
    {
        ThreadStart ts = new ThreadStart(perform_logic);
        Thread t1 = new Thread(ts);
        t1.Start();
        t1.Join();
        //your_label.Text=d1.status; --- can access it from any thread 
    }

    public static void perform_logic()
    {
        //put some code here in this function
        for (int i = 0; i < 10; i++)
        {
            //statements here
        }
        //set result in status variable
        d1.status = "Task done";
    }
}

How do I select a sibling element using jQuery?

Here is a link which is useful to learn about select a siblings element in Jquery.

How do I select a sibling element using jQuery

$("selector").nextAll(); 
$("selector").prev(); 

you can also find an element using Jquery selector

$("h2").siblings('table').find('tr'); 

For more information, refer this link next(), nextAll(), prev(), prevAll(), find() and siblings in JQuery

How to auto-reload files in Node.js?

Use this:

function reload_config(file) {
  if (!(this instanceof reload_config))
    return new reload_config(file);
  var self = this;

  self.path = path.resolve(file);

  fs.watchFile(file, function(curr, prev) {
    delete require.cache[self.path];
    _.extend(self, require(file));
  });

  _.extend(self, require(file));
}

All you have to do now is:

var config = reload_config("./config");

And config will automatically get reloaded :)

Why do multiple-table joins produce duplicate rows?

When you have related tables you often have one-to-many or many-to-many relationships. So when you join to TableB each record in TableA many have multiple records in TableB. This is normal and expected.

Now at times you only need certain columns and those are all the same for all the records, then you would need to do some sort of group by or distinct to remove the duplicates. Let's look at an example:

TableA
Id Field1
1  test
2  another test

TableB
ID Field2 field3
1  Test1  something
1  test1  More something
2  Test2  Anything

So when you join them and select all the files you get:

select * 
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1        b.id   b.field2  b.field3
1    test            1      Test1     something
1    test            1      Test1     More something
2    another test 2  2      Test2     Anything

These are not duplicates because the values of Field3 are different even though there are repeated values in the earlier fields. Now when you only select certain columns the same number of records are being joined together but since the columns with the different information is not being displayed they look like duplicates.

select a.Id, a.Field1,  b.field2
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1       b.field2  
1    test           Test1     
1    test           Test1 
2    another test   Test2

This appears to be duplicates but it is not because of the multiple records in TableB.

You normally fix this by using aggregates and group by, by using distinct or by filtering in the where clause to remove duplicates. How you solve this depends on exactly what your business rule is and how your database is designed and what kind of data is in there.

Unable to open a file with fopen()

Try using an absolute path for the filename. And if you are using Windows, use getlasterror() to see the actual error message.

How do I make Java register a string input with spaces?

Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.

Class Scanner

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.

Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;

System.out.println("Please input question:");
question = in.next();

// TODO do something with your input such as removing spaces...

if (question.equalsIgnoreCase("howdoyoulikeschool?") )
    /* it seems strings do not allow for spaces */
    System.out.println("CLOSED!!");
else
    System.out.println("Que?");

Laravel: Get Object From Collection By Attribute

Since I don't need to loop entire collection, I think it is better to have helper function like this

/**
 * Check if there is a item in a collection by given key and value
 * @param Illuminate\Support\Collection $collection collection in which search is to be made
 * @param string $key name of key to be checked
 * @param string $value value of key to be checkied
 * @return boolean|object false if not found, object if it is found
 */
function findInCollection(Illuminate\Support\Collection $collection, $key, $value) {
    foreach ($collection as $item) {
        if (isset($item->$key) && $item->$key == $value) {
            return $item;
        }
    }
    return FALSE;
}

How to find the nearest parent of a Git branch?

I have a solution to your overall problem (determine if feature is descended from the tip of develop), but it doesn't work using the method you outlined.

You can use git branch --contains to list all the branches descended from the tip of develop, then use grep to make sure feature is among them.

git branch --contains develop | grep "^ *feature$"

If it is among them, it will print " feature" to standard output and have a return code of 0. Otherwise, it will print nothing and have a return code of 1.

How can building a heap be O(n) time complexity?

@bcorso has already demonstrated the proof of the complexity analysis. But for the sake of those still learning complexity analysis, I have this to add:

The basis of your original mistake is due to a misinterpretation of the meaning of the statement, "insertion into a heap takes O(log n) time". Insertion into a heap is indeed O(log n), but you have to recognise that n is the size of the heap during the insertion.

In the context of inserting n objects into a heap, the complexity of the ith insertion is O(log n_i) where n_i is the size of the heap as at insertion i. Only the last insertion has a complexity of O (log n).

Strangest language feature

In Python:

abs((10+5j)-(25+-5j))

Returns ~18.03, which is the distance between the points (10,5) and (25,5) by the Pythagoras theorem. This fact happens because Python has native language support to complex numbers in the form of 2+2j for example. Since the absolute value of a complex number in form of a+bj = sqrt(a^2+b^2), we get the distance while subtracting one complex number from another and then apply the abs (absolute) function over it.

How do I use an image as a submit button?

<form id='formName' name='formName' onsubmit='redirect();return false;'>
        <div class="style7">
    <input type='text' id='userInput' name='userInput' value=''>
    <img src="BUTTON1.JPG" onclick="document.forms['formName'].submit();">
</div>
</form>

How to Consolidate Data from Multiple Excel Columns All into One Column

Save your workbook. If this code doesn't do what you want, the only way to go back is to close without saving and reopen.

Select the data you want to list in one column. Must be contiguous columns. May contain blank cells.

Press Alt+F11 to open the VBE

Press Control+R to view the Project Explorer

Navigate to the project for your workbook and choose Insert - Module

Paste this code in the code pane

Sub MakeOneColumn()

    Dim vaCells As Variant
    Dim vOutput() As Variant
    Dim i As Long, j As Long
    Dim lRow As Long

    If TypeName(Selection) = "Range" Then
        If Selection.Count > 1 Then
            If Selection.Count <= Selection.Parent.Rows.Count Then
                vaCells = Selection.Value

                ReDim vOutput(1 To UBound(vaCells, 1) * UBound(vaCells, 2), 1 To 1)

                For j = LBound(vaCells, 2) To UBound(vaCells, 2)
                    For i = LBound(vaCells, 1) To UBound(vaCells, 1)
                        If Len(vaCells(i, j)) > 0 Then
                            lRow = lRow + 1
                            vOutput(lRow, 1) = vaCells(i, j)
                        End If
                    Next i
                Next j

                Selection.ClearContents
                Selection.Cells(1).Resize(lRow).Value = vOutput
            End If
        End If
    End If

End Sub

Press F5 to run the code

How to convert DataSet to DataTable

A DataSet already contains DataTables. You can just use:

DataTable firstTable = dataSet.Tables[0];

or by name:

DataTable customerTable = dataSet.Tables["Customer"];

Note that you should have using statements for your SQL code, to ensure the connection is disposed properly:

using (SqlConnection conn = ...)
{
    // Code here...
}

What is the instanceof operator in JavaScript?

instanceof is just syntactic sugar for isPrototypeOf:

function Ctor() {}
var o = new Ctor();

o instanceof Ctor; // true
Ctor.prototype.isPrototypeOf(o); // true

o instanceof Ctor === Ctor.prototype.isPrototypeOf(o); // equivalent

instanceof just depends on the prototype of a constructor of an object.

A constructor is just a normal function. Strictly speaking it is a function object, since everything is an object in Javascript. And this function object has a prototype, because every function has a prototype.

A prototype is just a normal object, which is located within the prototype chain of another object. That means being in the prototype chain of another object makes an object to a prototype:

function f() {} //  ordinary function
var o = {}, // ordinary object
 p;

f.prototype = o; // oops, o is a prototype now
p = new f(); // oops, f is a constructor now

o.isPrototypeOf(p); // true
p instanceof f; // true

The instanceof operator should be avoided because it fakes classes, which do not exist in Javascript. Despite the class keyword not in ES2015 either, since class is again just syntactic sugar for...but that's another story.

Java math function to convert positive int to negative and negative to positive?

What about x *= -1; ? Do you really want a library function for this?

What is the $$hashKey added to my JSON.stringify result

https://www.timcosta.io/angular-js-object-comparisons/

Angular is pretty magical the first time people see it. Automatic DOM updates when you update a variable in your JS, and the same variable will update in your JS file when someone updates its value in the DOM. This same functionality works across page elements, and across controllers.

The key to all of this is the $$hashKey Angular attaches to objects and arrays used in ng-repeats.

This $$hashKey causes a lot of confusion for people who are sending full objects to an API that doesn't strip extra data. The API will return a 400 for all of your requests, but that $$hashKey just wont go away from your objects.

Angular uses the $$hashKey to keep track of which elements in the DOM belong to which item in an array that is being looped through in an ng-repeat. Without the $$hashKey Angular would have no way to apply changes the occur in the JavaScript or DOM to their counterpart, which is one of the main uses for Angular.

Consider this array:

users = [  
    {
         first_name: "Tim"
         last_name: "Costa"
         email: "[email protected]"
    }
]

If we rendered that into a list using ng-repeat="user in users", each object in it would receive a $$hashKey for tracking purposes from Angular. Here are two ways to avoid this $$hashKey.

Check if string contains a value in array

I came up with this function which works for me, hope this will help somebody

$word_list = 'word1, word2, word3, word4';
$str = 'This string contains word1 in it';

function checkStringAgainstList($str, $word_list)
{
  $word_list = explode(', ', $word_list);
  $str = explode(' ', $str);

  foreach ($str as $word):
    if (in_array(strtolower($word), $word_list)) {
        return TRUE;
    }
  endforeach;

  return false;
}

Also, note that answers with strpos() will return true if the matching word is a part of other word. For example if word list contains 'st' and if your string contains 'street', strpos() will return true

Difference between map, applymap and apply methods in Pandas

Comparing map, applymap and apply: Context Matters

First major difference: DEFINITION

  • map is defined on Series ONLY
  • applymap is defined on DataFrames ONLY
  • apply is defined on BOTH

Second major difference: INPUT ARGUMENT

  • map accepts dicts, Series, or callable
  • applymap and apply accept callables only

Third major difference: BEHAVIOR

  • map is elementwise for Series
  • applymap is elementwise for DataFrames
  • apply also works elementwise but is suited to more complex operations and aggregation. The behaviour and return value depends on the function.

Fourth major difference (the most important one): USE CASE

  • map is meant for mapping values from one domain to another, so is optimised for performance (e.g., df['A'].map({1:'a', 2:'b', 3:'c'}))
  • applymap is good for elementwise transformations across multiple rows/columns (e.g., df[['A', 'B', 'C']].applymap(str.strip))
  • apply is for applying any function that cannot be vectorised (e.g., df['sentences'].apply(nltk.sent_tokenize))

Summarising

enter image description here

Footnotes

  1. map when passed a dictionary/Series will map elements based on the keys in that dictionary/Series. Missing values will be recorded as NaN in the output.
  2. applymap in more recent versions has been optimised for some operations. You will find applymap slightly faster than apply in some cases. My suggestion is to test them both and use whatever works better.

  3. map is optimised for elementwise mappings and transformation. Operations that involve dictionaries or Series will enable pandas to use faster code paths for better performance.

  4. Series.apply returns a scalar for aggregating operations, Series otherwise. Similarly for DataFrame.apply. Note that apply also has fastpaths when called with certain NumPy functions such as mean, sum, etc.

TypeError: unsupported operand type(s) for /: 'str' and 'str'

By turning them into integers instead:

percent = (int(pyc) / int(tpy)) * 100;

In python 3, the input() function returns a string. Always. This is a change from Python 2; the raw_input() function was renamed to input().

Adding a newline character within a cell (CSV)

This question was answered well at Can you encode CR/LF in into CSV files?.

Consider also reverse engineering multiple lines in Excel. To embed a newline in an Excel cell, press Alt+Enter. Then save the file as a .csv. You'll see that the double-quotes start on one line and each new line in the file is considered an embedded newline in the cell.

Different class for the last element in ng-repeat

It's easier and cleaner to do it with CSS.

HTML:

<div ng-repeat="file in files" class="file">
  {{ file.name }}
</div>

CSS:

.file:last-of-type {
    color: #800;
}

The :last-of-type selector is currently supported by 98% of browsers

ASP.NET MVC 404 Error Handling

What I can recomend is to look on FilterAttribute. For example MVC already has HandleErrorAttribute. You can customize it to handle only 404. Reply if you are interesed I will look example.

BTW

Solution(with last route) that you have accepted in previous question does not work in much of the situations. Second solution with HandleUnknownAction will work but require to make this change in each controller or to have single base controller.

My choice is a solution with HandleUnknownAction.

How to use a variable from a cursor in the select statement of another cursor in pl/sql

Use alter session set current_schema = <username>, in your case as an execute immediate.

See Oracle's documentation for further information.

In your case, that would probably boil down to (untested)

DECLARE

   CURSOR client_cur IS
     SELECT  distinct username 
       from all_users 
      where length(username) = 3;

   -- client cursor 
   CURSOR emails_cur IS
   SELECT id, name 
     FROM org;

BEGIN

   FOR client IN client_cur LOOP

   -- ****
      execute immediate 
     'alter session set current_schema = ' || client.username;
   -- ****

      FOR email_rec in client_cur LOOP

         dbms_output.put_line(
             'Org id is ' || email_rec.id || 
             ' org nam '  || email_rec.name);

      END LOOP;

  END LOOP;
END;
/

Persistent invalid graphics state error when using ggplot2

try to get out grafics with x11() or win.graph() and solve this trouble.

How to convert float value to integer in php?

There is always intval() - Not sure if this is what you were looking for...

example: -

$floatValue = 4.5;
echo intval($floatValue);    // Returns 4

It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.

Here is some documentation for this: - http://php.net/manual/en/function.intval.php

JFrame Maximize window

Something like this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);

import java.awt.*;
import javax.swing.*;

public class Test extends JFrame
{
    public Test()
    {
        GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
        this.setMaximizedBounds(env.getMaximumWindowBounds());
        this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);
    }

    public static void main(String[] args)
    {
        JFrame.setDefaultLookAndFeelDecorated(true);

        Test t = new Test();
        t.setVisible(true);
    }
}

javascript if number greater than number

You should convert them to number before compare.

Try:

if (+x > +y) {
  //...
}

or

if (Number(x) > Number(y)) {
  // ...
}

Note: parseFloat and pareseInt(for compare integer, and you need to specify the radix) will give you NaN for an empty string, compare with NaN will always be false, If you don't want to treat empty string be 0, then you could use them.

How can I get a file's size in C++?

#include <stdio.h>

#define MAXNUMBER 1024

int main()
{
    int i;
    char a[MAXNUMBER];

    FILE *fp = popen("du -b  /bin/bash", "r");

    while((a[i++] = getc(fp))!= 9)
        ;

    a[i] ='\0';

    printf(" a is %s\n", a);

    pclose(fp);
    return 0;
}  

HTH

Is it possible to disable scrolling on a ViewPager

There is an easy fix for this one:

When you want to disable the viewpager scrolling then:

mViewPager.setOnTouchListener(new OnTouchListener() {

   public boolean onTouch(View arg0, MotionEvent arg1) {
      return true;
   }
}); 

And when you want to re-enable it then:

mViewPager.setOnTouchListener(null);

That will do the trick.

Python pandas: fill a dataframe row by row

This is a simpler version

import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
   df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`

What is the difference between an IntentService and a Service?

In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.

From the docs:

Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

IntentService Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

Refer this doc - http://developer.android.com/reference/android/app/IntentService.html

Regex for quoted string with escaping quotes

If it is searched from the beginning, maybe this can work?

\"((\\\")|[^\\])*\"

Get table column names in MySQL?

$col = $db->query("SHOW COLUMNS FROM category");

while ($fildss = $col->fetch_array())
{             
    $filds[] = '"{'.$fildss['Field'].'}"';
    $values[] = '$rows->'.$fildss['Field'].'';
}

if($type == 'value')
{
    return $values = implode(',', $values);
}
else {
     return $filds = implode(',', $filds);
}

Checking character length in ruby

You could take any of the answers above that use the string.length method and replace it with string.size.

They both work the same way.

if string.size <= 25
  puts "No problem here!"
else
  puts "Sorry too long!"
end

https://ruby-doc.org/core-2.4.0/String.html#method-i-size

How do I get values from a SQL database into textboxes using C#?

using (SqlConnection connection =  new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True"))
{
    SqlCommand command =
    new SqlCommand("select * from Pending_Tasks WHERE CustomerId=...", connection);
    connection.Open();

    SqlDataReader read= command.ExecuteReader();

    while (read.Read())
    {
        CustID.Text = (read["Customer_ID"].ToString());
        CustName.Text = (read["Customer_Name"].ToString());
        Add1.Text = (read["Address_1"].ToString());
        Add2.Text = (read["Address_2"].ToString());
        PostBox.Text = (read["Postcode"].ToString());
        PassBox.Text = (read["Password"].ToString());
        DatBox.Text = (read["Data_Important"].ToString());
        LanNumb.Text = (read["Landline"].ToString());
        MobNumber.Text = (read["Mobile"].ToString());
        FaultRep.Text = (read["Fault_Report"].ToString());
    }
    read.Close();
}

Make sure you have data in the query : select * from Pending_Tasks and you are using "using System.Data.SqlClient;"

How do I make WRAP_CONTENT work on a RecyclerView

Try this (It's a nasty solution but It may work): In the onCreate method of your Activity or in the onViewCreated method of your fragment. Set a callback ready to be triggered when the RecyclerView first render, like this:

vRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                calculeRecyclerViewFullHeight();
            }
        });

In the calculeRecyclerViewFullHeight calculate the RecyclerView full height based in the height of its children.

protected void calculateSwipeRefreshFullHeight() {
        int height = 0;
        for (int idx = 0; idx < getRecyclerView().getChildCount(); idx++ ) {
            View v = getRecyclerView().getChildAt(idx);
            height += v.getHeight();
        }
        SwipeRefreshLayout.LayoutParams params = getSwipeRefresh().getLayoutParams();
        params.height = height;
        getSwipeRefresh().setLayoutParams(params);
    }

In my case my RecyclerView is contain in a SwipeRefreshLayout for that reason I'm setting the height to the SwipeRefreshView and not to the RecyclerView but if you don't have any SwipeRefreshView then you can set the height to the RecyclerView instead.

Let me know if this helped you or not.

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

Solve Cross Origin Resource Sharing with Flask

Might as well make this an answer. I had the same issue today and it was more of a non-issue than expected. After adding the CORS functionality, you must restart your Flask server (ctrl + c -> python manage.py runserver, or whichever method you use)) in order for the change to take effect, even if the code is correct. Otherwise the CORS will not work in the active instance.

Here's how it looks like for me and it works (Python 3.6.1, Flask 0.12):

factory.py:

from flask import Flask
from flask_cors import CORS  # This is the magic


def create_app(register_stuffs=True):
    """Configure the app and views"""
    app = Flask(__name__)
    CORS(app)  # This makes the CORS feature cover all routes in the app

    if register_stuffs:
        register_views(app)
    return app


def register_views(app):
    """Setup the base routes for various features."""
    from backend.apps.api.views import ApiView
    ApiView.register(app, route_base="/api/v1.0/")

views.py:

from flask import jsonify
from flask_classy import FlaskView, route


class ApiView(FlaskView):
    @route("/", methods=["GET"])
    def index(self):
        return "API v1.0"

    @route("/stuff", methods=["GET", "POST"])
    def news(self):
        return jsonify({
            "stuff": "Here be stuff"
        })

In my React app console.log:

Sending request:
GET /stuff
With parameters:
null
bundle.js:17316 Received data from Api:
{"stuff": "Here be stuff"}

Could not find or load main class

Here is my working env path variables after much troubleshooting

CLASSPATH

.;C:\Program Files (x86)\Java\jre7\lib\ext\QTJava.zip;C:\Program Files (x86)\Java\jdk1.6.0_27\bin

PATH <---sometimes this PATH fills up with too many paths and you can't add a path(which was my case!)

bunchofpaths;C:\Program Files (x86)\Java\jdk1.6.0_27\bin

Additionally, when you try to use the cmd to execute the file...make sure your in the local directory as the file your trying to execute (which you did.)

Just a little checklist for people that have this problem still.

Post form data using HttpWebRequest

Use this code:

internal void SomeFunction() {
    Dictionary<string, string> formField = new Dictionary<string, string>();
    
    formField.Add("Name", "Henry");
    formField.Add("Age", "21");
    
    string body = GetBodyStringFromDictionary(formField);
    // output : Name=Henry&Age=21
}

internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
    string body = string.Empty;
    foreach (var pair in formField)
    {
        body += $"{pair.Key}={pair.Value}&";   
    }

    // delete last "&"
    body = body.Substring(0, body.Length - 1);

    return body;
}

Preloading @font-face fonts?

Via Google's webfontloader

var fontDownloadCount = 0;
WebFont.load({
    custom: {
        families: ['fontfamily1', 'fontfamily2']
    },
    fontinactive: function() {
        fontDownloadCount++;
        if (fontDownloadCount == 2) {
            // all fonts have been loaded and now you can do what you want
        }
    }
});

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

This is due to the series df[cat] containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna operation.

In other words

pandas data type 'Object' indicates mixed types rather than str type

so using the following line:

df[cat] = le.fit_transform(df[cat].astype(str))


should help

How to make picturebox transparent?

Just use the Form Paint method and draw every Picturebox on it, it allows transparency :

    private void frmGame_Paint(object sender, PaintEventArgs e)
    {
        DoubleBuffered = true;
        for (int i = 0; i < Controls.Count; i++)
            if (Controls[i].GetType() == typeof(PictureBox))
            {
                var p = Controls[i] as PictureBox;
                p.Visible = false;
                e.Graphics.DrawImage(p.Image, p.Left, p.Top, p.Width, p.Height);
            }
    }

Match two strings in one line with grep

And as people suggested perl and python, and convoluted shell scripts, here a simple awk approach:

awk '/string1/ && /string2/' filename

Having looked at the comments to the accepted answer: no, this doesn't do multi-line; but then that's also not what the author of the question asked for.

Refresh a page using JavaScript or HTML

You can also use

<input type="button" value = "Refresh" onclick="history.go(0)" />

It works fine for me.

Git - Pushing code to two remotes

In recent versions of Git you can add multiple pushurls for a given remote. Use the following to add two pushurls to your origin:

git remote set-url --add --push origin git://original/repo.git
git remote set-url --add --push origin git://another/repo.git

So when you push to origin, it will push to both repositories.

UPDATE 1: Git 1.8.0.1 and 1.8.1 (and possibly other versions) seem to have a bug that causes --add to replace the original URL the first time you use it, so you need to re-add the original URL using the same command. Doing git remote -v should reveal the current URLs for each remote.

UPDATE 2: Junio C. Hamano, the Git maintainer, explained it's how it was designed. Doing git remote set-url --add --push <remote_name> <url> adds a pushurl for a given remote, which overrides the default URL for pushes. However, you may add multiple pushurls for a given remote, which then allows you to push to multiple remotes using a single git push. You can verify this behavior below:

$ git clone git://original/repo.git
$ git remote -v
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.'
remote.origin.url=git://original/repo.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*

Now, if you want to push to two or more repositories using a single command, you may create a new remote named all (as suggested by @Adam Nelson in comments), or keep using the origin, though the latter name is less descriptive for this purpose. If you still want to use origin, skip the following step, and use origin instead of all in all other steps.

So let's add a new remote called all that we'll reference later when pushing to multiple repositories:

$ git remote add all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)               <-- ADDED
all git://original/repo.git (push)                <-- ADDED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git            <-- ADDED
remote.all.fetch=+refs/heads/*:refs/remotes/all/* <-- ADDED

Then let's add a pushurl to the all remote, pointing to another repository:

$ git remote set-url --add --push all git://another/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)                 <-- CHANGED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git         <-- ADDED

Here git remote -v shows the new pushurl for push, so if you do git push all master, it will push the master branch to git://another/repo.git only. This shows how pushurl overrides the default url (remote.all.url).

Now let's add another pushurl pointing to the original repository:

$ git remote set-url --add --push all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)
all git://original/repo.git (push)                <-- ADDED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git
remote.all.pushurl=git://original/repo.git        <-- ADDED

You see both pushurls we added are kept. Now a single git push all master will push the master branch to both git://another/repo.git and git://original/repo.git.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json")
               .Build();
            var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
            optionsBuilder.UseSqlServer(connectionString);
        }
    }

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

On apache you need to edit security.conf:

nano /etc/apache2/conf-enabled/security.conf

and set:

Header set X-Frame-Options: "sameorigin"

Then enable mod_headers:

cd /etc/apache2/mods-enabled

ln -s ../mods-available/headers.load headers.load

And restart Apache:

service apache2 restart

And voila!

How to change the text on the action bar

ActionBar ab = getActionBar();
TextView tv = new TextView(getApplicationContext());

LayoutParams lp = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, // Width of TextView
        LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
tv.setTextColor(Color.RED);
ab.setCustomView(tv);

For more information check this link :

http://android--code.blogspot.in/2015/09/android-how-to-change-actionbar-title_21.html

How to get Device Information in Android

Try this:

// Code For IMEI AND IMSI NUMBER

String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
String IMEI,IMSI;
IMEI = m_telephonyManager.getDeviceId();
IMSI = m_telephonyManager.getSubscriberId();

Get week number (in the year) from a date PHP

Becomes more difficult when you need year and week.
Try to find out which week is 01.01.2017.
(It is the 52nd week of 2016, which is from Mon 26.12.2016 - Sun 01.01.2017).

After a longer search I found

strftime('%G-%V',strtotime("2017-01-01"))

Result: 2016-52


https://www.php.net/manual/de/function.strftime.php
ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week. (01 through 53)


The equivalent in mysql is DATE_FORMAT(date, '%x-%v') https://www.w3schools.com/sql/func_mysql_date_format.asp
Week where Monday is the first day of the week (01 to 53).


Could not find a corresponding solution with date() or DateTime.
At least not without solutions like "+1day, last monday".

How can I get the current page name in WordPress?

<?php wp_title(''); ?>

This worked for me.

If I understand correctly, you want to get the page name on a page that has post entries.

Set default syntax to different filetype in Sublime Text 2

You can turn on syntax highlighting based on the contents of the file.

For example, my Makefiles regardless of their extension the first line as follows:

#-*-Makefile-*- vim:syntax=make

This is typical practice for other editors such as vim.

However, for this to work you need to modify the Makefile.tmLanguage file.

  1. Find the file (for Sublime Text 3 in Ubuntu) at:

    /opt/sublime_text/Packages/Makefile.sublime-package
    

Note, that is really a zip file. Copy it, rename with .zip at the end, and extract the Makefile.tmLanguage file from it.

  1. Edit the new Makefile.tmLanguage by adding the "firstLineMatch" key and string after the "fileTypes" section. In the example below, the last two lines are new (should be added by you). The <string> section holds the regular expression, that will enable syntax highlighting for the files that match the first line. This expression recognizes two patterns: "-*-Makefile-*-" and "vim:syntax=make".

    ...
    <key>fileTypes</key>
    <array>
        <string>GNUmakefile</string>
        <string>makefile</string>
        <string>Makefile</string>
        <string>OCamlMakefile</string>
        <string>make</string>
    </array>
    
    <key>firstLineMatch</key>
    <string>^#\s*-\*-Makefile-\*-|^#.*\s*vim:syntax=make</string>
    
  2. Place the modified Makefile.tmLanguage in the User settings directory:

    ~/.config/sublime-text-3/Packages/User/Makefile.tmLanguage
    

All the files matching the first line rule should turn the syntax highlighting on when opened.

How to trap the backspace key using jQuery?

Working on the same idea as above , but generalizing a bit . Since the backspace should work fine on the input elements , but should not work if the focus is a paragraph or something , since it is there where the page tends to go back to the previous page in history .

$('html').on('keydown' , function(event) {

        if(! $(event.target).is('input')) {
            console.log(event.which);
           //event.preventDefault();
           if(event.which == 8) {
            //  alert('backspace pressed');
            return false;
         }
        }
});

returning false => both event.preventDefault and event.stopPropagation are in effect .

How to backup a local Git repository?

Both answers to this questions are correct, but I was still missing a complete, short solution to backup a Github repository into a local file. The gist is available here, feel free to fork or adapt to your needs.

backup.sh:

#!/bin/bash
# Backup the repositories indicated in the command line
# Example:
# bin/backup user1/repo1 user1/repo2
set -e
for i in $@; do
  FILENAME=$(echo $i | sed 's/\//-/g')
  echo "== Backing up $i to $FILENAME.bak"
  git clone [email protected]:$i $FILENAME.git --mirror
  cd "$FILENAME.git"
  git bundle create ../$FILENAME.bak --all
  cd ..
  rm -rf $i.git
  echo "== Repository saved as $FILENAME.bak"
done

restore.sh:

#!/bin/bash
# Restore the repository indicated in the command line
# Example:
# bin/restore filename.bak
set -e

FOLDER_NAME=$(echo $1 | sed 's/.bak//')
git clone --bare $1 $FOLDER_NAME.git

Is HTML considered a programming language?

The 'M' stands for a 'Markup'. It's a 'Markup Language' not a programming language. Some people will disagree with this, but my opinion is that if it lacks logical constructs (conditional branching, iteration, etc) its not really a programming language.

As for the resume, I would suggest putting HTML and XML under a section like 'Technologies'. I usually have a section like this where I list things like version control software, OS's I've developed for, build systems, etc.

How to loop and render elements in React-native?

You would usually use map for that kind of thing.

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button>
);

(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)

As a side, I would use an object instead of an array. I find it looks nicer:

initialArr = [
  {
    id: 1,
    color: "blue",
    text: "text1"
  },
  {
    id: 2,
    color: "red",
    text: "text2"
  },
];

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo.id}>{buttonInfo.text}</Button>
);

String to byte array in php

PHP has no explicit byte type, but its string is already the equivalent of Java's byte array. You can safely write fputs($connection, "The quick brown fox …"). The only thing you must be aware of is character encoding, they must be the same on both sides. Use mb_convert_encoding() when in doubt.

Decoding JSON String in Java

Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to your package.

To add the jar file to your project in Eclipse, do the following:

  1. Right click on your project, click Build Path > Configure Build Path
  2. Goto Libraries tab > Add External JARs
  3. Locate the JAR file and add

How to save the contents of a div as a image?

There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

The offending lines are the following:

MaxConnections=90
InitialConnections=80

You can increase the values to allow more connections.

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

What are the differences between a pointer variable and a reference variable in C++?

Also, a reference that is a parameter to a function that is inlined may be handled differently than a pointer.

void increment(int *ptrint) { (*ptrint)++; }
void increment(int &refint) { refint++; }
void incptrtest()
{
    int testptr=0;
    increment(&testptr);
}
void increftest()
{
    int testref=0;
    increment(testref);
}

Many compilers when inlining the pointer version one will actually force a write to memory (we are taking the address explicitly). However, they will leave the reference in a register which is more optimal.

Of course, for functions that are not inlined the pointer and reference generate the same code and it's always better to pass intrinsics by value than by reference if they are not modified and returned by the function.

TypeError: argument of type 'NoneType' is not iterable

If a function does not return anything, e.g.:

def test():
    pass

it has an implicit return value of None.

Thus, as your pick* methods do not return anything, e.g.:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")

the lines that call them, e.g.:

word = pickEasy()

set word to None, so wordInput in getInput is None. This means that:

if guess in wordInput:

is the equivalent of:

if guess in None:

and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

The fix is to add the return type:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

How to trim a string after a specific character in java

This is the simplest method you can do and reduce your efforts. just paste this function in your class and call it anywhere:

you can do this by creating a substring.

simple exampe is here:

_x000D_
_x000D_
public static String removeTillWord(String input, String word) {
    return input.substring(input.indexOf(word));
}

removeTillWord("Your String", "\");
_x000D_
_x000D_
_x000D_

How can I use an array of function pointers?

The simplest solution is to give the address of the final vector you want , and modify it inside the function.

void calculation(double result[] ){  //do the calculation on result

   result[0] = 10+5;
   result[1] = 10 +6;
   .....
}

int main(){

    double result[10] = {0}; //this is the vector of the results

    calculation(result);  //this will modify result
}

React - Component Full Screen (with height 100%)

For a project using CRNA i use this in index.css

html, body, #root {
  height: 100%;
}

and then in my App.css i use this

.App {
  height: 100%;
}

and also set height to 100% for a div within App if there is one eg-

.MainGridContainer {
  display: grid;
  width: 100%;
  height:100%;
  grid-template-columns: 1fr 3fr;
  grid-template-rows: 50px auto;
}

How to delete specific columns with VBA?

You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.

I think what you were looking for in your Range was this:

Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete

Just change the column letters to match your needs.

JFrame in full screen Java

it will helps you use your object instant of the frame

frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

I/O error(socket error): [Errno 111] Connection refused

I'm not exactly sure what's causing this. You can try looking in your socket.py (mine is a different version, so line numbers from the trace don't match, and I'm afraid some other details might not match as well).

Anyway, it seems like a good practice to put your url fetching code in a try: ... except: ... block, and handle this with a short pause and a retry. The URL you're trying to fetch may be down, or too loaded, and that's stuff you'll only be able to handle in with a retry anyway.

What is the --save option for npm install?

As of npm 5, npm will now save by default. In case,if you would like npm to work in a similar old fashion (no autosave) to how it was working in previous versions, you can update the config option to enable autosave as below.

npm config set save false

To get the current setting, you can execute the following command:

npm config get save

Source:https://blog.pusher.com/what-you-need-know-npm-5/

Android: how to make an activity return results to the activity which calls it?

UPDATE Feb. 2021

As in Activity v1.2.0 and Fragment v1.3.0, the new Activity Result APIs have been introduced.

The Activity Result APIs provide components for registering for a result, launching the result, and handling the result once it is dispatched by the system.

So there is no need of using startActivityForResult and onActivityResult anymore.

In order to use the new API, you need to create an ActivityResultLauncher in your origin Activity, specifying the callback that will be run when the destination Activity finishes and returns the desired data:

private val intentLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->

        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.getStringExtra("streetkey")
            result.data?.getStringExtra("citykey")
            result.data?.getStringExtra("homekey")
        }
    }

and then, launching your intent whenever you need to:

intentLauncher.launch(Intent(this, YourActivity::class.java))

And to return data from the destination Activity, you just have to add an intent with the values to return to the setResult() method:

val data = Intent()
data.putExtra("streetkey", "streetname")
data.putExtra("citykey", "cityname")
data.putExtra("homekey", "homename")

setResult(Activity.RESULT_OK, data)
finish()

For any additional information, please refer to Android Documentation

How to style HTML5 range input to have different color before and after slider?

Yes, it is possible. Though I wouldn't recommend it because input range is not really supported properly by all browsers because is an new element added in HTML5 and HTML5 is only a draft (and will be for long) so going as far as to styling it is perhaps not the best choice.

Also, you'll need a bit of JavaScript too. I took the liberty of using jQuery library for this, for simplicity purposes.

Here you go: http://jsfiddle.net/JnrvG/1/.

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Scope Identity: Identity of last record added within the stored procedure being executed.

@@Identity: Identity of last record added within the query batch, or as a result of the query e.g. a procedure that performs an insert, the then fires a trigger that then inserts a record will return the identity of the inserted record from the trigger.

IdentCurrent: The last identity allocated for the table.

Java integer to byte array

How about:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

The idea is not mine. I've taken it from some post on dzone.com.

How do I find out what keystore my JVM is using?

Your keystore will be in your JAVA_HOME---> JRE -->lib---> security--> cacerts. You need to check where your JAVA_HOME is configured, possibly one of these places,

  1. Computer--->Advanced --> Environment variables---> JAVA_HOME

  2. Your server startup batch files.

In your import command -keystore cacerts (give full path to the above JRE here instead of just saying cacerts).

How to save to local storage using Flutter?

I think If you are going to store large amount of data in local storage you can use sqflite library. It is very easy to setup and I have personally used for some test project and it works fine.

https://github.com/tekartik/sqflite This a tutorial - https://proandroiddev.com/flutter-bookshelf-app-part-2-personal-notes-and-database-integration-a3b47a84c57

If you want to store data in cloud you can use firebase. It is solid service provide by google.

https://firebase.google.com/docs/flutter/setup

How can I assign the output of a function to a variable using bash?

You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:

VAR=$(scan)

Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.

Preserving trailing Newlines:

One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.

function scan2 () {
    local nl=$'\x0a';  # that's just \n
    echo "output${nl}${nl}" # 2 in the string + 1 by echo
}

# append a character to the total output.
# and strip it with %% parameter expansion.
VAR=$(scan2; echo "x"); VAR="${VAR%%x}"

echo "${VAR}---"

prints (3 newlines kept):

output


---

Use an output parameter: avoiding the subshell (and preserving newlines)

If what the function tries to achieve is to "return" a string into a variable , with bash v4.3 and up, one can use what's called a nameref. Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it 'points to/references'.

function scan3() {
    local -n outvar=$1    # -n makes it a nameref.
    local nl=$'\x0a'
    outvar="output${nl}${nl}"  # two total. quotes preserve newlines
}

VAR="some prior value which will get overwritten"

# you pass the name of the variable. VAR will be modified.
scan3 VAR

# newlines are also preserved.
echo "${VAR}==="

prints:

output

===

This form has a few advantages. Namely, it allows your function to modify the environment of the caller without using global variables everywhere.

Note: using namerefs can improve the performance of your program greatly if your functions rely heavily on bash builtins, because it avoids the creation of a subshell that is thrown away just after. This generally makes more sense for small functions reused often, e.g. functions ending in echo "$returnstring"

This is relevant. https://stackoverflow.com/a/38997681/5556676

NSString property: copy or retain?

Since name is a (immutable) NSString, copy or retain makes no difference if you set another NSString to name. In another word, copy behaves just like retain, increasing the reference count by one. I think that is an automatic optimization for immutable classes, since they are immutable and of no need to be cloned. But when a NSMutalbeString mstr is set to name, the content of mstr will be copied for the sake of correctness.

Select N random elements from a List<T> in C#

This will solve your issue

var entries=new List<T>();
var selectedItems = new List<T>();


                for (var i = 0; i !=10; i++)
                {
                    var rdm = new Random().Next(entries.Count);
                        while (selectedItems.Contains(entries[rdm]))
                            rdm = new Random().Next(entries.Count);

                    selectedItems.Add(entries[rdm]);
                }

Git Pull vs Git Rebase

git pull and git rebase are not interchangeable, but they are closely connected.

git pull fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull is similar to git fetch & git merge.

Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.

You can pull using rebase instead of merge (git pull --rebase). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.

Atlassian has some excellent documentation on merging vs. rebasing.

Add 10 seconds to a Date

Just for the performance maniacs among us.

getTime

var d = new Date('2014-01-01 10:11:55');
d = new Date(d.getTime() + 10000);

5,196,949 Ops/sec, fastest


setSeconds

var d = new Date('2014-01-01 10:11:55');
d.setSeconds(d.getSeconds() + 10);

2,936,604 Ops/sec, 43% slower


moment.js

var d = new moment('2014-01-01 10:11:55');
d = d.add(10, 'seconds');

22,549 Ops/sec, 100% slower


So maybe its the least human readable (not that bad) but the fastest way of going :)

jspref online tests

Java double.MAX_VALUE?

this states that Account.deposit(Double.MAX_VALUE); it is setting deposit value to MAX value of Double dataType.to procced for running tests.

How to increase Bootstrap Modal Width?

I suppose this happens due to the max-width of a modal being set to 500px and max-width of modal-lg is 800px I suppose setting it to auto will make your modal responsive

How to change line width in ggplot?

If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.

library(ggplot2)
library(tidyr)

x = seq(0,10,0.05)

df <- data.frame(A = 2 * x + 10,
                 B = x**2 - x*6,
                 C = 30 - x**1.5,
                 X = x)


df = gather(df,A,B,C,key="Model",value="Y")


ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
  geom_line()+
  scale_size_manual( values = c(4,2,1) ) +
  scale_color_manual( values = c("orange","red","navy") ) 

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

if you have a date in a string with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:

DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy", 
                                  CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");

How to create a <style> tag with Javascript?

Here's a script which adds IE-style createStyleSheet() and addRule() methods to browsers which don't have them:

if(typeof document.createStyleSheet === 'undefined') {
    document.createStyleSheet = (function() {
        function createStyleSheet(href) {
            if(typeof href !== 'undefined') {
                var element = document.createElement('link');
                element.type = 'text/css';
                element.rel = 'stylesheet';
                element.href = href;
            }
            else {
                var element = document.createElement('style');
                element.type = 'text/css';
            }

            document.getElementsByTagName('head')[0].appendChild(element);
            var sheet = document.styleSheets[document.styleSheets.length - 1];

            if(typeof sheet.addRule === 'undefined')
                sheet.addRule = addRule;

            if(typeof sheet.removeRule === 'undefined')
                sheet.removeRule = sheet.deleteRule;

            return sheet;
        }

        function addRule(selectorText, cssText, index) {
            if(typeof index === 'undefined')
                index = this.cssRules.length;

            this.insertRule(selectorText + ' {' + cssText + '}', index);
        }

        return createStyleSheet;
    })();
}

You can add external files via

document.createStyleSheet('foo.css');

and dynamically create rules via

var sheet = document.createStyleSheet();
sheet.addRule('h1', 'background: red;');

Handling the TAB character in Java

Or you could just perform a trim() on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)