Programs & Examples On #Peterblum

How to put labels over geom_bar in R with ggplot2

Another solution is to use stat_count() when dealing with discrete variables (and stat_bin() with continuous ones).

ggplot(data = df, aes(x = x)) +
geom_bar(stat = "count") + 
stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5))

enter image description here

How to use JNDI DataSource provided by Tomcat in Spring?

According to Apache Tomcat 7 JNDI Datasource HOW-TO page there must be a resource configuration in web.xml:

<resource-ref>
  <description>DB Connection</description>
  <res-ref-name>jdbc/TestDB</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>

That works for me

Is there a better way to refresh WebView?

Yes for some reason WebView.reload() causes a crash if it failed to load before (something to do with the way it handles history). This is the code I use to refresh my webview. I store the current url in self.url

# 1: Pause timeout and page loading

self.timeout.pause()
sleep(1)

# 2: Check for internet connection (Really lazy way)

while self.page().networkAccessManager().networkAccessible() == QNetworkAccessManager.NotAccessible: sleep(2)

# 3:Try again

if self.url == self.page().mainFrame().url():
    self.page().action(QWebPage.Reload)
    self.timeout.resume(60)

else:
    self.page().action(QWebPage.Stop)
    self.page().mainFrame().load(self.url)
    self.timeout.resume(30)

return False

C# Foreach statement does not contain public definition for GetEnumerator

You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).

http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx

But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends

http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx

Your code also seems a bit strange, like you are nesting lists?

ssh connection refused on Raspberry Pi

I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.

Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.

Can I use conditional statements with EJS templates (in JMVC)?

Yes , You can use conditional statement with EJS like if else , ternary operator or even switch case also

For Example

Ternary operator : <%- role == 'Admin' ? 'Super Admin' : role == 'subAdmin' ? 'Sub Admin' : role %>

Switch Case

<% switch (role) {
case 'Admin' : %>
        Super Admin
        <% break;

case 'eventAdmin' : %>
        Event Admin
        <% break;

case 'subAdmin' : %>
        Sub Admin
        <% break;

} %>

Delete all nodes and relationships in neo4j 1.8

Neo4j cannot delete nodes that have a relation. You have to delete the relations before you can delete the nodes.

But, it is simple way to delete "ALL" nodes and "ALL" relationships with a simple chyper. This is the code:

MATCH (n) DETACH DELETE n

--> DETACH DELETE will remove all of the nodes and relations by Match

Error: macro names must be identifiers using #ifdef 0

#ifdef 0
...
#endif

#ifdef expect a macro rather than expression when using constant or expression

#if 0
...
#endif

or

#if !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

if #ifdef is used the it reports this error

#ifdef !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

Where #ifdef expect a macro rather than macro expresssion

Properties private set;

Depending on the scope of my application, I like to put the object hydration mechanisms in the object itself. I'll wrap the data reader with a custom object and pass it a delegate that gets executed once the query returns. The delegate gets passed the DataReader. Then, since I'm in my smart business object, I can hydrate away with my private setters.

Edit for Pseudo-Code

The "DataAccessWrapper" wraps all of the connection and object lifecycle management for me. So, when I call "ExecuteDataReader," it creates the connection, with the passed proc (there's an overload for params,) executes it, executes the delegate and then cleans up after itself.

public class User
{
    public static List<User> GetAllUsers()
    {
        DataAccessWrapper daw = new DataAccessWrapper();
        return (List<User>)(daw.ExecuteDataReader("MyProc", new ReaderDelegate(ReadList)));
    }

    protected static object ReadList(SQLDataReader dr)
    {
        List<User> retVal = new List<User>();
        while(dr.Read())
        {
            User temp = new User();
            temp.Prop1 = dr.GetString("Prop1");
            temp.Prop2 = dr.GetInt("Prop2");
            retVal.Add(temp);
        }
        return retVal;
    }
}

Similarity String Comparison in Java

Sounds like a plagiarism finder to me if your string turns into a document. Maybe searching with that term will turn up something good.

"Programming Collective Intelligence" has a chapter on determining whether two documents are similar. The code is in Python, but it's clean and easy to port.

Shell - How to find directory of some command?

The Korn shell, ksh, offers the whence built-in, which identifies other shell built-ins, macros, etc. The which command is more portable, however.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

How to pass multiple arguments in processStartInfo?

Remember to include System.Diagnostics

ProcessStartInfo startInfo = new ProcessStartInfo("myfile.exe");        // exe file
startInfo.WorkingDirectory = @"C:\..\MyFile\bin\Debug\netcoreapp3.1\"; // exe folder

//here you add your arguments
startInfo.ArgumentList.Add("arg0");       // First argument          
startInfo.ArgumentList.Add("arg2");       // second argument
startInfo.ArgumentList.Add("arg3");       // third argument
Process.Start(startInfo);                 

How can I change the font-size of a select option?

try this

http://jsfiddle.net/VggvD/2/

CSS add your code

.select_join option{
    font-size:13px;
}

Why are empty catch blocks a bad idea?

Usually empty try-catch is a bad idea because you are silently swallowing an error condition and then continuing execution. Occasionally this may be the right thing to do, but often it's a sign that a developer saw an exception, didn't know what to do about it, and so used an empty catch to silence the problem.

It's the programming equivalent of putting black tape over an engine warning light.

I believe that how you deal with exceptions depends on what layer of the software you are working in: Exceptions in the Rainforest.

ORA-00972 identifier is too long alias column name

The object where Oracle stores the name of the identifiers (e.g. the table names of the user are stored in the table named as USER_TABLES and the column names of the user are stored in the table named as USER_TAB_COLUMNS), have the NAME columns (e.g. TABLE_NAME in USER_TABLES) of size Varchar2(30)...and it's uniform through all system tables of objects or identifiers --

 DBA_ALL_TABLES         ALL_ALL_TABLES        USER_ALL_TABLES
 DBA_PARTIAL_DROP_TABS  ALL_PARTIAL_DROP_TABS USER_PARTIAL_DROP_TABS
 DBA_PART_TABLES        ALL_PART_TABLES       USER_PART_TABLES 
 DBA_TABLES             ALL_TABLES            USER_TABLES           
 DBA_TABLESPACES        USER_TABLESPACES      TAB
 DBA_TAB_COLUMNS      ALL_TAB_COLUMNS         USER_TAB_COLUMNS 
 DBA_TAB_COLS         ALL_TAB_COLS            USER_TAB_COLS 
 DBA_TAB_COMMENTS     ALL_TAB_COMMENTS        USER_TAB_COMMENTS 
 DBA_TAB_HISTOGRAMS   ALL_TAB_HISTOGRAMS      USER_TAB_HISTOGRAMS 
 DBA_TAB_MODIFICATIONS  ALL_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS 
 DBA_TAB_PARTITIONS   ALL_TAB_PARTITIONS      USER_TAB_PARTITIONS

How to automatically start a service when running a docker container?

In my case, I have a PHP web application being served by Apache2 within the docker container that connects to a MYSQL backend database. Larry Cai's solution worked with minor modifications. I created a entrypoint.sh file within which I am managing my services. I think creating an entrypoint.sh when you have more than one command to execute when your container starts up is a cleaner way to bootstrap docker.

#!/bin/sh

set -e

echo "Starting the mysql daemon"
service mysql start

echo "navigating to volume /var/www"
cd /var/www
echo "Creating soft link"
ln -s /opt/mysite mysite

a2enmod headers
service apache2 restart

a2ensite mysite.conf
a2dissite 000-default.conf
service apache2 reload

if [ -z "$1" ]
then
    exec "/usr/sbin/apache2 -D -foreground"
else
    exec "$1"
fi

Alter table add multiple columns ms sql

ALTER TABLE Regions
ADD ( HasPhotoInReadyStorage  bit,
     HasPhotoInWorkStorage  bit,
     HasPhotoInMaterialStorage bit *(Missing ,)*
     HasText  bit);

Check if EditText is empty.

Try this out: its in Kotlin

//button from xml
button.setOnClickListener{                                         
    val new=addText.text.toString()//addText is an EditText
    if(new=isNotEmpty())
    {
         //do something
    }
    else{
        new.setError("Enter some msg")
        //or
        Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
    }
}

Thank you

How to resolve Unneccessary Stubbing exception

If you use any() when mocking, you have to relpace @RunWith(MockitoJUnitRunner.class) with @RunWith(MockitoJUnitRunner.Silent.class).

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

In my case it was fixed by adding a reference to the constraint-layout package

    implementation 'com.android.support.constraint:constraint-layout:1.1.0'

Initialize empty vector in structure - c++

The default vector constructor will create an empty vector. As such, you should be able to write:

struct user r = { string(), vector<unsigned char>() };

Note, I've also used the default string constructor instead of "".

You might want to consider making user a class and adding a default constructor that does this for you:

class User {
  User() {}
  string username;
  vector<unsigned char> password;
};

Then just writing:

User r;

Will result in a correctly initialized user.

What is difference between png8 and png24

From the Web Designer’s Guide to PNG Image Format

PNG-8 and PNG-24

There are two PNG formats: PNG-8 and PNG-24. The numbers are shorthand for saying "8-bit PNG" or "24-bit PNG." Not to get too much into technicalities — because as a web designer, you probably don’t care — 8-bit PNGs mean that the image is 8 bits per pixel, while 24-bit PNGs mean 24 bits per pixel.

To sum up the difference in plain English: Let’s just say PNG-24 can handle a lot more color and is good for complex images with lots of color such as photographs (just like JPEG), while PNG-8 is more optimized for things with simple colors, such as logos and user interface elements like icons and buttons.

Another difference is that PNG-24 natively supports alpha transparency, which is good for transparent backgrounds. This difference is not 100% true because Adobe products’ Save for Web command allows PNG-8 with alpha transparency.

How to comment/uncomment in HTML code

Depending on your editor, this should be a fairly easy macro to write.

  • Go to beginning of line or highlighted area
  • Insert <!--
  • Go to end of line or highlighted area
  • Insert -->

Another macro to reverse these steps, and you are done.

Edit: this simplistic approach does not handle nested comment tags, but should make the commenting/uncommenting easier in the general case.

Abstract Class vs Interface in C++

An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

Why are unnamed namespaces used and what are their benefits?

In addition to the other answers to this question, using an anonymous namespace can also improve performance. As symbols within the namespace do not need any external linkage, the compiler is freer to perform aggressive optimization of the code within the namespace. For example, a function which is called multiple times once in a loop can be inlined without any impact on the code size.

For example, on my system the following code takes around 70% of the run time if the anonymous namespace is used (x86-64 gcc-4.6.3 and -O2; note that the extra code in add_val makes the compiler not want to include it twice).

#include <iostream>

namespace {
  double a;
  void b(double x)
  {
    a -= x;
  }
  void add_val(double x)
  {
    a += x;
    if(x==0.01) b(0);
    if(x==0.02) b(0.6);
    if(x==0.03) b(-0.1);
    if(x==0.04) b(0.4);
  }
}

int main()
{
  a = 0;
  for(int i=0; i<1000000000; ++i)
    {
      add_val(i*1e-10);
    }
  std::cout << a << '\n';
  return 0;
}

Spring 3 RequestMapping: Get path value

I have a similar problem and I resolved in this way:

@RequestMapping(value = "{siteCode}/**/{fileName}.{fileExtension}")
public HttpEntity<byte[]> getResource(@PathVariable String siteCode,
        @PathVariable String fileName, @PathVariable String fileExtension,
        HttpServletRequest req, HttpServletResponse response ) throws IOException {
    String fullPath = req.getPathInfo();
    // Calling http://localhost:8080/SiteXX/images/argentine/flag.jpg
    // fullPath conentent: /SiteXX/images/argentine/flag.jpg
}

Note that req.getPathInfo() will return the complete path (with {siteCode} and {fileName}.{fileExtension}) so you will have to process conveniently.

How do operator.itemgetter() and sort() work?

Answer for Python beginners

In simpler words:

  1. The key= parameter of sort requires a key function (to be applied to be objects to be sorted) rather than a single key value and
  2. that is just what operator.itemgetter(1) will give you: A function that grabs the first item from a list-like object.

(More precisely those are callables, not functions, but that is a difference that can often be ignored.)

Javascript - Replace html using innerHTML

You should chain the replace() together instead of assigning the result and replacing again.

var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
                        .replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
                        .replace(/.bbbbbb/g,'/world\">Helloworld</a>');

See DEMO.

Retrieving a random item from ArrayList

Here's a better way of doing things:

import java.util.ArrayList;
import java.util.Random;

public class facultyquotes
{
    private ArrayList<String> quotes;
    private String quote1;
    private String quote2;
    private String quote3;
    private String quote4;
    private String quote5;
    private String quote6;
    private String quote7;
    private String quote8;
    private String quote9;
    private String quote10;
    private String quote11;
    private String quote12;
    private String quote13;
    private String quote14;
    private String quote15;
    private String quote16;
    private String quote17;
    private String quote18;
    private String quote19;
    private String quote20;
    private String quote21;
    private String quote22;
    private String quote23;
    private String quote24;
    private String quote25;
    private String quote26;
    private String quote27;
    private String quote28;
    private String quote29;
    private String quote30;
    private int n;
    Random random;

    String teacher;


    facultyquotes()
    {
        quotes=new ArrayList<>();
        random=new Random();
        n=random.nextInt(3) + 0;
        quote1="life is hard";
        quote2="trouble shall come to an end";
        quote3="never give lose and never get lose";
        quote4="gamble with the devil and win";
        quote5="If you don’t build your dream, someone else will hire you to help them build theirs.";
        quote6="The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself.";
        quote7="When I dare to be powerful – to use my strength in the service of my vision, then it becomes less and less important whether I am afraid.";
        quote8="Whenever you find yourself on the side of the majority, it is time to pause and reflect";
        quote9="Great minds discuss ideas; average minds discuss events; small minds discuss people.";
        quote10="I have not failed. I’ve just found 10,000 ways that won’t work.";
        quote11="If you don’t value your time, neither will others. Stop giving away your time and talents. Value what you know & start charging for it.";
        quote12="A successful man is one who can lay a firm foundation with the bricks others have thrown at him.";
        quote13="No one can make you feel inferior without your consent.";
        quote14="Let him who would enjoy a good future waste none of his present.";
        quote15="Live as if you were to die tomorrow. Learn as if you were to live forever.";
        quote16="Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do.";
        quote17="The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will.";
        quote18="Success is about creating benefit for all and enjoying the process. If you focus on this & adopt this definition, success is yours.";
        quote19="I used to want the words ‘She tried’ on my tombstone. Now I want ‘She did it.";
        quote20="It is our choices, that show what we truly are, far more than our abilities.";
        quote21="You have to learn the rules of the game. And then you have to play better than anyone else.";
        quote22="The successful warrior is the average man, with laser-like focus.";
        quote23="Develop success from failures. Discouragement and failure are two of the surest stepping stones to success.";
        quote24="If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much.";
        quote25="The question isn’t who is going to let me; it’s who is going to stop me.";
        quote26="If you genuinely want something, don’t wait for it – teach yourself to be impatient.";
        quote27="Don’t let the fear of losing be greater than the excitement of winning.";
        quote28="But man is not made for defeat. A man can be destroyed but not defeated.";
        quote29="There is nothing permanent except change.";
        quote30="You cannot shake hands with a clenched fist.";

        quotes.add(quote1);
        quotes.add(quote2);
        quotes.add(quote3);
        quotes.add(quote4);
        quotes.add(quote5);
        quotes.add(quote6);
        quotes.add(quote7);
        quotes.add(quote8);
        quotes.add(quote9);
        quotes.add(quote10);
        quotes.add(quote11);
        quotes.add(quote12);
        quotes.add(quote13);
        quotes.add(quote14);
        quotes.add(quote15);
        quotes.add(quote16);
        quotes.add(quote17);
        quotes.add(quote18);
        quotes.add(quote19);
        quotes.add(quote20);
        quotes.add(quote21);
        quotes.add(quote22);
        quotes.add(quote23);
        quotes.add(quote24);
        quotes.add(quote25);
        quotes.add(quote26);
        quotes.add(quote27);
        quotes.add(quote28);
        quotes.add(quote29);
        quotes.add(quote30);
    }

    public void setTeacherandQuote(String teacher)
    {
        this.teacher=teacher;
    }

    public void printRandomQuotes()
    {
        System.out.println(quotes.get(n++)+"  ~ "+ teacher);  
    }

    public void printAllQuotes()
    {
        for (String i : quotes)
        {
            System.out.println(i.toString());
        }
    }
}

What is a reasonable length limit on person "Name" fields?

If it's full name in one field, I usually go with 128 - 64/64 for first and last in separate fields - you just never know.

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:

HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::

=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))

Format..., select formatting, OK, OK.

SO22487695 example

where I have filled yellow the cells that are triggering the red fill result.

error: request for member '..' in '..' which is of non-class type

Just for the record..

It is actually not a solution to your code, but I had the same error message when incorrectly accessing the method of a class instance pointed to by myPointerToClass, e.g.

MyClass* myPointerToClass = new MyClass();
myPointerToClass.aMethodOfThatClass();

where

myPointerToClass->aMethodOfThatClass();

would obviously be correct.

React passing parameter via onclick event using ES6 syntax

I am using React-Bootstrap. The onSelect trigger for dropdowns were not allowing me to pass data. Just the event. So remember you can just set any values as attributes and pick them up from the function using javascript. Picking up those attributes you set in that event target.

    let currentTarget = event.target;
    let currentId = currentTarget.getAttribute('data-id');
    let currentValue = currentTarget.getAttribute('data-value');

Use a.empty, a.bool(), a.item(), a.any() or a.all()

As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

It would go something like this:

mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...

In order to avoid that, you can build series for lower and upper limits:

low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)

Now you can slice it as follows:

mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out: 
     dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
17                        136          62              97                15   
69                        110          85              96                18   
72                        105          85              97                16   
161                       126          57              99                16   
286                       127          84              99                12   
435                        92          67              96                13   
499                       110          66              97                15   

     systolic blood pressure  temperature  
17                       141           37  
69                       155           38  
72                       154           36  
161                      153           36  
286                      156           37  
435                      155           36  
499                      149           36  

And for assignment you can use np.where:

df['class'] = np.where(mask, 'excellent', 'critical')

How to get the last row of an Oracle a table

SELECT * FROM 
  MY_TABLE
WHERE 
  <your filters>
ORDER BY PRIMARY_KEY DESC FETCH FIRST ROW ONLY

Android: Align button to bottom-right of screen using FrameLayout?

I also ran into this situation and figured out how to do it using FrameLayout. The following output is produced by the code given below.

Some right-bottom aligned text showing up over an image using FrameLayout.

              <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" >

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/contactbook_icon"
                        android:layout_gravity="center" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="140"
                        android:textSize="12dp"
                        android:textColor="#FFFFFF"
                        android:layout_gravity="bottom|right"
                        android:layout_margin="15dp" />
                </FrameLayout>

Change the margin value to adjust the text position over the image. Removing margin might make the text to go out of the view sometimes.

What is the most "pythonic" way to iterate over a list in chunks?

def chunker(iterable, n):
    """Yield iterable in chunk sizes.

    >>> chunks = chunker('ABCDEF', n=4)
    >>> chunks.next()
    ['A', 'B', 'C', 'D']
    >>> chunks.next()
    ['E', 'F']
    """
    it = iter(iterable)
    while True:
        chunk = []
        for i in range(n):
            try:
                chunk.append(next(it))
            except StopIteration:
                yield chunk
                raise StopIteration
        yield chunk

if __name__ == '__main__':
    import doctest

    doctest.testmod()

How to use awk sort by column 3

How about just sort.

sort -t, -nk3 user.csv

where

  • -t, - defines your delimiter as ,.

  • -n - gives you numerical sort. Added since you added it in your attempt. If your user field is text only then you dont need it.

  • -k3 - defines the field (key). user is the third field.

How do I make a file:// hyperlink that works in both IE and Firefox?

just use

file:///

works in IE, Firefox and Chrome as far as I can tell.

see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info

Installing PDO driver on MySQL Linux server

On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql

There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.

CakePHP find method with JOIN

Otro example, custom Data Pagination for JOIN

CODE in Controller CakePHP 2.6 is OK:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        'conditions'=>array(
            'Clientes.requiere_senasa'=>1
        ),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

OR Example 2, NOT active conditions:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id',
                    'Clientes.requiere_senasa = 1'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        //'conditions'=>array(
        //    'Clientes.requiere_senasa'=>1
        //),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

Where are static variables stored in C and C++?

Data declared in a compilation unit will go into the .BSS or the .Data of that files output. Initialised data in BSS, uninitalised in DATA.

The difference between static and global data comes in the inclusion of symbol information in the file. Compilers tend to include the symbol information but only mark the global information as such.

The linker respects this information. The symbol information for the static variables is either discarded or mangled so that static variables can still be referenced in some way (with debug or symbol options). In neither case can the compilation units gets affected as the linker resolves local references first.

PHP Fatal error: Cannot redeclare class

i have encountered that same problem. found out the case was the class name. i dealt with it by changing the name. hence resolving the problem.

Getting a POST variable

Use the

Request.Form[]

for POST variables,

Request.QueryString[]

for GET.

Where is the documentation for the values() method of Enum?

You can't see this method in javadoc because it's added by the compiler.

Documented in three places :

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

  • Enum.valueOf class
    (The special implicit values method is mentioned in description of valueOf method)

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

The values function simply list all values of the enumeration.

Where to find the complete definition of off_t type?

As the "GNU C Library Reference Manual" says

off_t
    This is a signed integer type used to represent file sizes. 
    In the GNU C Library, this type is no narrower than int.
    If the source is compiled with _FILE_OFFSET_BITS == 64 this 
    type is transparently replaced by off64_t.

and

off64_t
    This type is used similar to off_t. The difference is that 
    even on 32 bit machines, where the off_t type would have 32 bits,
    off64_t has 64 bits and so is able to address files up to 2^63 bytes
    in length. When compiling with _FILE_OFFSET_BITS == 64 this type 
    is available under the name off_t.

Thus if you want reliable way of representing file size between client and server, you can:

  1. Use off64_t type and stat64() function accordingly (as it fills structure stat64, which contains off64_t type itself). Type off64_t guaranties the same size on 32 and 64 bit machines.
  2. As was mentioned before compile your code with -D_FILE_OFFSET_BITS == 64 and use usual off_t and stat().
  3. Convert off_t to type int64_t with fixed size (C99 standard). Note: (my book 'C in a Nutshell' says that it is C99 standard, but optional in implementation). The newest C11 standard says:
7.20.1.1 Exact-width integer types

    1 The typedef name intN_t designates a signed integer type with width N ,
    no padding bits, and a two’s complement representation. Thus, int8_t 
    denotes such a signed integer type with a width of exactly 8 bits.
    without mentioning.

And about implementation:

7.20 Integer types <stdint.h>

    ... An implementation shall provide those types described as ‘‘required’’,
    but need not provide any of the others (described as ‘‘optional’’).
    ...
    The following types are required:
    int_least8_t  uint_least8_t
    int_least16_t uint_least16_t
    int_least32_t uint_least32_t
    int_least64_t uint_least64_t
    All other types of this form are optional.

Thus, in general, C standard can't guarantee types with fixed sizes. But most compilers (including gcc) support this feature.

Efficient way to insert a number into a sorted array of numbers?

There's a bug in your code. It should read:

function locationOf(element, array, start, end) {
  start = start || 0;
  end = end || array.length;
  var pivot = parseInt(start + (end - start) / 2, 10);
  if (array[pivot] === element) return pivot;
  if (end - start <= 1)
    return array[pivot] > element ? pivot - 1 : pivot;
  if (array[pivot] < element) {
    return locationOf(element, array, pivot, end);
  } else {
    return locationOf(element, array, start, pivot);
  }
}

Without this fix the code will never be able to insert an element at the beginning of the array.

'git' is not recognized as an internal or external command

If you want to setup for temporary purpose, just execute below command.

  1. open command prompt < run --> cmd >
  2. Run below command.
    set PATH=C:\Program Files\Git\bin;%PATH%
  3. Type git, it will work.

This is valid for current window/cell only, if you will close command prompt, everything will get vanish. For permanently setting, set GIT in environment variable.

a. press Window+Pause
b. click on Advance system setting.

c. Click on Environment variable under Advance Tab.

d. Edit Path Variable.

e. Add below line in end of statement.
;c:\Program Files\Git\bin;

f. Press OK!!
g. Open new command prompt .
h. Type git and press Enter

Thanks

Use of "this" keyword in formal parameters for static methods in C#

"this" extends the next class in the parameter list

So in the method signature below "this" extends "String". Line is passed to the function as a normal argument to the method. public static string[] SplitCsvLine(this String line)

In the above example "this" class is extending the built in "String" class.

What's the HTML to have a horizontal space between two objects?

You should put a padding in each object. For example, you want a space between images, you can use the following:

img{
   padding: 5px;
}

That means 5px paddin for ALL sides. Read more at http://www.w3schools.com/css/css_padding.asp. By the way, studying a lot before attempting to program will make things easier for you (and for us).

Indent multiple lines quickly in vi

Go to the start of the text

  • press v for visual mode.
  • use up/down arrow to highlight text.
  • press = to indent all the lines you highlighted.

Getting around the Max String size in a vba function?

Excel only shows 255 characters but in fact if more than 255 characters are saved, to see the complete string, consult it in the immediate window

Press Crl + G and type ?RunWhat in the immediate window and press Enter

EF 5 Enable-Migrations : No context type was found in the assembly

In mosh tutorial, individual user account was selected which created a db context in the template. Also, make sure EntityFramework is installed in the Nuget package manager. enter image description here

How to check the function's return value if true or false

You don't need to call ValidateForm() twice, as you are above. You can just do

if(!ValidateForm()){
..
} else ...

I think that will solve the issue as above it looks like your comparing true/false to the string equivalent 'false'.

How to load my app from Eclipse to my Android phone instead of AVD

just for additional info, If your apps is automatically run on emulator, right click on the project, Run As -> Run Configuration, then on the Run Configuration choose on the Manual. after that, if you run your apps you will be prompted to chose where you want to run your apps, there will be listed all the available device and emulator.

How to remove all the punctuation in a string? (Python)

Strip won't work. It only removes leading and trailing instances, not everything in between: http://docs.python.org/2/library/stdtypes.html#str.strip

Having fun with filter:

import string
asking = "hello! what's your name?"
predicate = lambda x:x not in string.punctuation
filter(predicate, asking)

Combine two or more columns in a dataframe into a new column with a new name

Use paste.

 df$x <- paste(df$n,df$s)
 df
#   n  s     b    x
# 1 2 aa  TRUE 2 aa
# 2 3 bb FALSE 3 bb
# 3 5 cc  TRUE 5 cc

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

What worked with me, in the Storyboard, go to the Navigation Controller, select the navigation bar, click on the Attributes Inspector, then change the style from default to black. That's it!

How many parameters are too many?

Seven things in short term memory?

  1. Name of the function
  2. Return value of the function
  3. Purpose of the function
  4. Parameter 1
  5. Parameter 2
  6. Parameter 3
  7. Parameter 4

How to set default value for HTML select?

You first need to add values to your select options and for easy targetting give the select itself an id.

Let's make option b the default:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.

Generate Java class from JSON?

Answering this old question with recent project ;-).

At the moment the best solution is probably JsonSchema2Pojo :

It does the job from the seldom used Json Schema but also with plain Json. It provides Ant and Maven plugin and an online test application can give you an idea of the tool. I put a Json Tweet and generated all the containing class (Tweet, User, Location, etc..).

We'll use it on Agorava project to generate Social Media mapping and follow the contant evolution in their API.

Install psycopg2 on Ubuntu

This works for me in Ubuntu 12.04 and 15.10

if pip not installed:

sudo apt-get install python-pip

and then:

sudo apt-get update
sudo apt-get install libpq-dev python-dev
sudo pip install psycopg2

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

You want

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

To get the value of errormessage

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

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

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

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

How can I do a line break (line continuation) in Python?

The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.

See Python Idioms and Anti-Idioms (for Python 2 or Python 3) for more.

Where is the visual studio HTML Designer?

The solution of creating a new HTML file with HTML (Web Forms) Designer worked for that file but not for other, individual HTML files that I wanted to edit.

I did find the Open With option in the Open File dialogue and was able to select the HTML (Web Forms) Editor there. Having clicked the "Set as Default" option in that window, VS then remembered to use that editor when I opened other HTML files.

How to Convert date into MM/DD/YY format in C#

Look into using the ToString() method with a specified format.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

I happened to run with the same issue in iOS 7 (with some devices no simulators).

Looks like Safari in iOS 7 has a lower storage quota, which apparently is reached by having a long history log.

I guess the best practice will be to catch the exception.

The Modernizr project has an easy patch, you should try something similar: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

Errors: Data path ".builders['app-shell']" should have required property 'class'

This setting works well under angular 8:

Package.json:

...
"dependencies": {
  "@angular/animations": "^8.2.14",
  "@angular/cdk": "8.2.3",
  "@angular/common": "^8.2.14",
  "@angular/compiler": "^8.2.14",
  "@angular/core": "^8.2.14",

...

"devDependencies": {
  "@angular-devkit/build-angular": "~0.803.29",
  "@angular/cli": "~8.3.29",
  "@angular/compiler-cli": "^8.2.14"

How to detect page zoom level in all modern browsers?

Have it currently working however still need to separate by browser. Tested successfully on Chrome(75) and Safari(11.1) (haven't found way for FF as of yet). It also gets the zoom value correct on retina display and calculations are triggered on resize event.

    private pixelRatio() {
      const styleString = "(min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 1.5),(-moz-min-device-pixel-ratio: 1.5),(min-device-pixel-ratio: 1.5)";
      const chromeRatio = (Math.round((this.window.outerWidth / this.window.innerWidth)*100) / 100);
      const otherRatio = (Math.round(window.devicePixelRatio * 100) / 100);
      const resizeValue = (this.isChrome()) ? chromeRatio : otherRatio;

      return resizeValue || (this.window.matchMedia && this.window.matchMedia(styleString).matches ? 2 : 1) || 1;
    }


  private isChrome():boolean {
    return (!!this.window.chrome && !(!!this.window.opera || this.window.navigator.userAgent.indexOf(' Opera') >= 0))
  }

  private chrome() {
    const zoomChrome = Math.round(((this.window.outerWidth) / this.window.innerWidth)*100) / 100;
    return {
      zoom: zoomChrome,
      devicePxPerCssPx: zoomChrome1 * this.pixelRatio()
    };
  }

JavaScript - Get Browser Height

With JQuery you can try this $(window).innerHeight() (Works for me on Chrome, FF and IE). With bootstrap modal I used something like the following;

$('#YourModal').on('show.bs.modal', function () {
    $('.modal-body').css('height', $(window).innerHeight() * 0.7);
});

Add event handler for body.onload by javascript within <body> part

As @epascarello mentioned for W3C standard browsers, you should use:

body.addEventListener("load", init, false);

However, if you want it to work on IE<9 as well you can use:

var prefix = window.addEventListener ? "" : "on";
var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
document.body[eventName](prefix + "load", init, false);

Or if you want it in a single line:

document.body[window.addEventListener ? 'addEventListener' : 'attachEvent'](
    window.addEventListener ? "load" : "onload", init, false);

Note: here I get a straight reference to the body element via the document, saving the need for the first line.

Also, if you're using jQuery, and you want to use the DOM ready event rather than when the body loads, the answer can be even shorter...

$(init);

Get connection status on Socket.io client

You can check whether the connection was lost or not by using this function:-

var socket = io( /**connection**/ );
socket.on('disconnect', function(){
//Your Code Here
});

Hope it will help you.

Selenium WebDriver.get(url) does not open the URL

Check your browser version and do the following.

1. Download the Firefox/Chrome webdriver from Google

2. Put the webdriver in Chrome's directory.

iOS 7 status bar overlapping UI

From Apple iOS7 transition Guide,

Specifically,

self.automaticallyAdjustsScrollViewInsets = YES;
self.edgesForExtendedLayout = UIRectEdgeNone;

works for me when I don't want to overlap and I have a UITableViewController.

How to center an image horizontally and align it to the bottom of the container?

have you tried:

.image_block{
text-align: center;
vertical-align: bottom;
}

Asynchronous Function Call in PHP

I think if the HTML and other UI stuff needs the data returned then there is not going to be a way to async it.

I believe the only way to do this in PHP would be to log a request in a database and have a cron check every minute, or use something like Gearman queue processing, or maybe exec() a command line process

In the meantime you php page would have to generate some html or js that makes it reload every few seconds to check on progress, not ideal.

To sidestep the issue, how many different requests are you expecting? Could you download them all automatically every hour or so and save to a database?

Hive External Table Skip First Row

Just for those who have already created the table with the header. Here is the alter command for the same. This is useful in case you already have the table and want the first row to be ignored without dropping and recreating. It also helps with people to familiarize with ALTER as a option with TBLPROPERTIES.

ALTER TABLE tablename SET TBLPROPERTIES ("skip.header.line.count"="1");

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Fast Linux file count for a large number of files

I realized that not using in memory processing, when you have a huge amount of data, is faster than "piping" the commands. So I saved the result to a file and analyzed it afterwards:

ls -1 /path/to/dir > count.txt && cat count.txt | wc -l

Can I give a default value to parameters or optional parameters in C# functions?

It is only possible as from C# 4.0

However, when you use a version of C#, prior to 4.0, you can work around this by using overloaded methods:

public void Func( int i, int j )
{
    Console.WriteLine (String.Format ("i = {0}, j = {1}", i, j));
}

public void Func( int i )
{
    Func (i, 4);
}

public void Func ()
{
    Func (5);
}

(Or, you can upgrade to C# 4.0 offcourse).

List of Stored Procedures/Functions Mysql Command Line

A variation on Praveenkumar_V's post:

SELECT `name` FROM mysql.proc WHERE db = 'dbname' AND `type` = 'PROCEDURE';
SELECT `name` FROM mysql.proc WHERE db = 'dbname' AND `type` = 'FUNCTION';

..and this because I needed to save time after some housekeeping:

SELECT CONCAT(
     "GRANT EXECUTE ON PROCEDURE `"
    ,`name`
    ,"` TO username@'%'; -- "
    ,`comment`
)
FROM mysql.proc
WHERE db = 'dbname'
AND `type` = 'PROCEDURE';

SELECT CONCAT(
     "GRANT EXECUTE ON FUNCTION `"
    ,`name`
    ,"` TO username@'%'; -- "
    ,`comment`
)
FROM mysql.proc
WHERE db = 'dbname'
AND `type` = 'FUNCTION';

Reset the database (purge all), then seed a database

You can delete everything and recreate database + seeds with both:

  1. rake db:reset: loads from schema.rb
  2. rake db:drop db:create db:migrate db:seed: loads from migrations

Make sure you have no connections to db (rails server, sql client..) or the db won't drop.

schema.rb is a snapshot of the current state of your database generated by:

rake db:schema:dump

Click event on select option element in chrome

Looking for this on 2018. Click event on option tag, inside a select tag, is not fired on Chrome.

Use change event, and capture the selected option:

$(document).delegate("select", "change", function() {
    //capture the option
    var $target = $("option:selected",$(this));
});

Be aware that $target may be a collection of objects if the select tag is multiple.

Enter key press in C#

Keeping in mind that

Keys.Return is different to Keys.Enter

//Makes it easier to Type user and password and press Enter, 
//Rather than using the mouse to Click the Button all the time
    private void Txt_Password_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.Return)
        {
            Btn_Login_Click(null, null);
        }
    }

Hope this help someone.

Byte[] to ASCII

Encoding.GetString Method (Byte[]) convert bytes to a string.

When overridden in a derived class, decodes all the bytes in the specified byte array into a string.

Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)

Syntax

public virtual string GetString(byte[] bytes)

Parameters

bytes
    Type: System.Byte[]
    The byte array containing the sequence of bytes to decode.

Return Value

Type: System.String
A String containing the results of decoding the specified sequence of bytes.

Exceptions

ArgumentException        - The byte array contains invalid Unicode code points.
ArgumentNullException    - bytes is null.
DecoderFallbackException - A fallback occurred (see Character Encoding in the .NET Framework for complete explanation) or DecoderFallback is set to DecoderExceptionFallback.

Remarks

If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively, of a derived class.

See the Remarks under Encoding.GetChars for more discussion of decoding techniques and considerations.

How to copy data from one table to another new table in MySQL?

You can try this code

insert into #temp 
select Product_ID,Max(Grand_Total) AS 'Sales_Amt', Max(Rec_Amount) ,'',''
from Table_Name group by Id

How do you install GLUT and OpenGL in Visual Studio 2012?

the instructions for Vs2012

To Install FreeGLUT

  1. Download "freeglut 2.8.1 MSVC Package" from http://www.transmissionzero.co.uk/software/freeglut-devel/
  2. Extract the compressed file freeglut-MSVC.zip to a folder freeglut

  3. Inside freeglut folder:

On 32bit versions of windows

copy all files in include/GL folder to C:\Program Files\Windows Kits\8.0\Include\um\gl

copy all files in lib folder to C:\Program Files\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)

copy freeglut.dll to C:\windows\system32

On 64bit versions of windows:(not 100% sure but try)

copy all files in include/GL folder to C:\Program Files(x86)\Windows Kits\8.0\Include\um\gl

copy all files in lib folder to C:\Program Files(x86)\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)

copy freeglut.dll to C:\windows\SysWOW64

Set Background color programmatically

you need to use getResources() method, try to use following code

View someView = findViewById(R.id.screen);
View root = someView.getRootView();
root.setBackgroundColor(getResources().getColor(color.white)); 

Edit::

getResources.getColor() is deprecated so, use like below

 root.setBackgroundColor(ContextCompat.getColor(this, R.color.white)); 

How to push elements in JSON from javascript array

I think you want to make objects from array and combine it with an old object (BODY.recipients.values), if it's then you may do it using $.extent (because you are using jQuery/tagged) method after prepare the object from array

var BODY = {
    "recipients": {
        "values": []
    },
    "subject": 'TitleOfSubject',
    "body": 'This is the message body.'
}

var values = [],
names = ['sheikh', 'muhammed', 'Answer', 'Uddin', 'Heera']; // for testing
for (var ln = 0; ln < names.length; ln++) {
    var item1 = {
        "person": { "_path": "/people/"+names[ln] }
    };
    values.push(item1);
}

// Now merge with BODY
$.extend(BODY.recipients.values, values);

DEMO.

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

_x000D_
_x000D_
var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

How can I set NODE_ENV=production on Windows?

It would be ideal if you could set parameters on the same line as your call to start Node.js on Windows. Look at the following carefully, and run it exactly as stated:

You have these two options:

  1. At the command line:

    set NODE_ENV=production&&npm start
    

    or

    set NODE_ENV=production&&node index.js
    
  2. The trick for it to work on Windows is you need to remove the whitespace before and after the "&&". Configured your package.json file with start_windows (see below) below. Then Run "npm run start_windows" at the command line.

    //package.json
    
    "scripts": {
      "start": "node index.js"
      "start_windows": "set NODE_ENV=production&&node index.js"
    }
    

Java NIO FileChannel versus FileOutputstream performance / usefulness

My experience with larger files sizes has been that java.nio is faster than java.io. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:

The buffer size. The algorithm you basically have is

  • copy from disk to buffer
  • copy from buffer to disk

My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.

Don't perform java benchmarks that read and write to the same disk.

If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.

Don't use a buffer if you don't need to.

Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.

Like other have said, use FileChannel.transferTo() or FileChannel.transferFrom(). The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.

The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:

Use production data and environments

Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.

My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.

What are you running on? It matters.

Uninstall Node.JS using Linux command line?

If you installed from source, you can issue the following command:

sudo make uninstall

If you followed the instructions on https://github.com/nodejs/node/wiki to install to your $HOME/local/node, then you have to type the following before the line above:

./configure --prefix=$HOME/local/node

Getting a list item by index

Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array.

List[index]

See for instance: https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx

How to send an HTTPS GET Request in C#

Simple Get Request using HttpClient Class

using System.Net.Http;

class Program
{
   static void Main(string[] args)
    {
        HttpClient httpClient = new HttpClient();
        var result = httpClient.GetAsync("https://www.google.com").Result;
    }

}

Tooltip with HTML content without JavaScript

This one is very interesting,

HTML and CSS only

_x000D_
_x000D_
.help-tip {_x000D_
  position: absolute;_x000D_
  top: 18px;_x000D_
  left: 18px;_x000D_
  text-align: center;_x000D_
  background-color: #BCDBEA;_x000D_
  border-radius: 50%;_x000D_
  width: 24px;_x000D_
  height: 24px;_x000D_
  font-size: 14px;_x000D_
  line-height: 26px;_x000D_
  cursor: default;_x000D_
}_x000D_
_x000D_
.help-tip:before {_x000D_
  content: '?';_x000D_
  font-weight: bold;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.help-tip:hover span {_x000D_
  display: block;_x000D_
  transform-origin: 100% 0%;_x000D_
  -webkit-animation: fadeIn 0.3s ease-in-out;_x000D_
  animation: fadeIn 0.3s ease-in-out;_x000D_
}_x000D_
_x000D_
.help-tip span {_x000D_
  display: none;_x000D_
  text-align: left;_x000D_
  background-color: #1E2021;_x000D_
  padding: 5px;_x000D_
  width: 200px;_x000D_
  position: absolute;_x000D_
  border-radius: 3px;_x000D_
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);_x000D_
  left: -4px;_x000D_
  color: #FFF;_x000D_
  font-size: 13px;_x000D_
  line-height: 1.4;_x000D_
}_x000D_
_x000D_
.help-tip span:before {_x000D_
  position: absolute;_x000D_
  content: '';_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border: 6px solid transparent;_x000D_
  border-bottom-color: #1E2021;_x000D_
  left: 10px;_x000D_
  top: -12px;_x000D_
}_x000D_
_x000D_
.help-tip span:after {_x000D_
  width: 100%;_x000D_
  height: 40px;_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: -40px;_x000D_
  left: 0;_x000D_
}
_x000D_
<span class="help-tip">_x000D_
     <span > This is the inline help tip! </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to run python script on terminal (ubuntu)?

First create the file you want, with any editor like vi r gedit. And save with. Py extension.In that the first line should be

!/usr/bin/env python

Forbidden You don't have permission to access /wp-login.php on this server

I had this same problem, and after temporarily deleting all my .htaccess files, then trying to modify them as suggested, and making sure all my files and folder permissions were set to 777, I still couldn't get it to work. I don't know why I couldn't access the file, but I was able to create a new file and access it no problem. So what I did was create a new file in /wp-admin/ called temp.php and pasted all the code from install.php into it. This allowed me to access the file. The only other thing I had to do was edit the code so that the form submitted to temp.php instead of install.php. After that, I could finish the install and everything worked.

<form id="setup" method="post" action="temp.php?step=2">

Changing the CommandTimeout in SQL Management studio

Right click in the query pane, select Query Options... and in the Execution->General section (the default when you first open it) there is an Execution time-out setting.

Check if string contains only whitespace

To check if a string is just a spaces or newline

Use this simple code

mystr = "      \n  \r  \t   "
if not mystr.strip(): # The String Is Only Spaces!
    print("\n[!] Invalid String !!!")
    exit(1)
mystr = mystr.strip()
print("\n[*] Your String Is: "+mystr)

Default argument values in JavaScript functions

I have never seen it done that way in JavaScript. If you want a function with optional parameters that get assigned default values if the parameters are omitted, here's a way to do it:

 function(a, b) {
      if (typeof a == "undefined") {
        a = 10;
      }

      if (typeof b == "undefined") {
        a = 20;
      }

      alert("a: " + a + " b: " + b);
    }

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

I'll take a stab at it:

/^[a-z](?:_?[a-z0-9]+)*$/i

Explained:

/
 ^           # match beginning of string
 [a-z]       # match a letter for the first char
 (?:         # start non-capture group
   _?          # match 0 or 1 '_'
   [a-z0-9]+   # match a letter or number, 1 or more times
 )*          # end non-capture group, match whole group 0 or more times
 $           # match end of string
/i           # case insensitive flag

The non-capture group takes care of a) not allowing two _'s (it forces at least one letter or number per group) and b) only allowing the last char to be a letter or number.

Some test strings:

"a": match
"_": fail
"zz": match
"a0": match
"A_": fail
"a0_b": match
"a__b": fail
"a_1_c": match

adding css file with jquery

This is how I add css using jQuery ajax. Hope it helps someone..

$.ajax({
            url:"site/test/style.css",
            success:function(data){
                 $("<style></style>").appendTo("head").html(data);
            }
        })

How to sort the files according to the time stamp in unix?

File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

I have tried all suggestions and found my own simple solution.

The problem is that codes written in external environment like C need compiler. Look for its own VS environment, i.e. VS 2008.

Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat. I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS as variable name and gave the value of VS120COMNTOOLS.

You can find my step by step solution below:

  1. Right click on My Computer.
  2. Click Properties
  3. Advanced system settings
  4. Environment variables
  5. Add New system variable
  6. Enter VS90COMNTOOLS to the variable name
  7. Enter the value of current version to the new variable.
  8. Close all windows

Now open a new session and pip install your-package

What exactly does an #if 0 ..... #endif block do?

Not quite

int main(void)
{
   #if 0
     the apostrophe ' causes a warning
   #endif
   return 0;
}

It shows "t.c:4:19: warning: missing terminating ' character" with gcc 4.2.4

How do I get the width and height of a HTML5 canvas?

The context object allows you to manipulate the canvas; you can draw rectangles for example and a lot more.

If you want to get the width and height, you can just use the standard HTML attributes width and height:

var canvas = document.getElementById( 'yourCanvasID' );
var ctx = canvas.getContext( '2d' );

alert( canvas.width );
alert( canvas.height ); 

The default XML namespace of the project must be the MSBuild XML namespace

if the project is not a big ,

1- change the name of folder project

2- make a new project with the same project (before renaming)

3- add existing files from the old project to the new project (totally same , same folders , same names , ...)

4- open the the new project file (as xml ) and the old project

5- copy the new project file (xml content ) and paste it in the old project file

6- delete the old project

7- rename the old folder project to old name

How do I find the current machine's full hostname in C (hostname and domain information)?

gethostname() is POSIX way to get local host name. Check out man.

BSD function getdomainname() can give you domain name so you can build fully qualified hostname. There is no POSIX way to get a domain I'm afraid.

Setting up connection string in ASP.NET to SQL SERVER

it should be within the <configuration> node:

  <connectionStrings >
    <add name="myconnectionstring" connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

this site has more info on it:

Passing multiple values to a single PowerShell script parameter

The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.

param([String[]] $Hosts, [String] $VLAN)

Instead of

foreach ($i in $args)

you can use

foreach ($hostName in $Hosts)

If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:

myScript.ps1 -Hosts host1,host2,host3 -VLAN 2

...or something similar.

jQuery detect if string contains something

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
   alert(str2 + " found");
}

Installing Python packages from local file system folder to virtualenv with pip

From the installing-packages page you can simply run:

pip install /srv/pkg/mypackage

where /srv/pkg/mypackage is the directory, containing setup.py.


Additionally1, you can install it from the archive file:

pip install ./mypackage-1.0.4.tar.gz

1 Although noted in the question, due to its popularity, it is also included.

What is SaaS, PaaS and IaaS? With examples

Adding to that, I have used AWS, heroku and currently using Jelastic and found -

Jelastic offers a Java and PHP cloud hosting platform. Jelastic automatically scales Java and PHP applications and allocates server resources, thus delivering true next-generation Java and PHP cloud computing. http://blog.jelastic.com/2013/04/16/elastic-beanstalk-vs-jelastic/ or http://cloud.dzone.com/articles/jelastic-vs-heroku-1

Personally I found -

  • Jelastic is faster
  • You don’t need to code to any jelastic APIs – just upload your application and select your stack. You can also mix and match software stacks at will.

Try any of them and explore yourself. Its fun :-)

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:

Request:

GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:

Request:

GET /BigBuckBunny_320x180.mp4
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*

Tips:

You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456

Or:

Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.

Using DISTINCT inner join in SQL

I believe your 1:m relationships should already implicitly create DISTINCT JOINs.

But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.

SELECT DISTINCT a.valueA, c.valueC
FROM C
    INNER JOIN B ON B.lookupC = C.id
    INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC

How to pass a value from one Activity to another in Android?

You can use Bundle to do the same in Android

Create the intent:

Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();

//Create the bundle
Bundle bundle = new Bundle();

//Add your data to bundle
bundle.putString(“stuff”, getrec);

//Add the bundle to the intent
i.putExtras(bundle);

//Fire that second activity
startActivity(i);

Now in your second activity retrieve your data from the bundle:

//Get the bundle
Bundle bundle = getIntent().getExtras();

//Extract the data…
String stuff = bundle.getString(“stuff”); 

Emulator error: This AVD's configuration is missing a kernel file

In my own case, I had multiple errors most of which were about mis-configured ANDROID_SDK_ROOT, at the end of the day, one thing seemed to fix the whole thing.

Follow the following process:

After Creating the A new Emulator Device on AVD, go to the Actions menu and click on the arrow pointing downwards as shown below.

enter image description here

Click on Show on Disk

Edit Config.ini

Look for image.sysdir.1

it should have a value like this : **image.sysdir.1=system-images\android-28\google_apis_playstore\x86**

Your own value might be different

Now, fix in the path of the Android Sdk to make a complete path.

image.sysdir.1=**C:\androidsdk**system-images\android-28\google_apis_playstore\x86\

If you noticed, the android sdk path shown above is different from the normal default android sdk, I had to move it to C:/androidsdk to avoid NDK issues as my main USER HOME on my PC has whitespaces which NDK might not support.

NOTE: Moving the SDK directory away from its default directory is usually the cause of these errors AVD emulator gives, most especially as regarding broken and misconfigured path. The fix I provided above is a quick fix, you may have to do that each time you create a new device on AVD Emulator.

This fix should also work when working on CMD with cordova .

When should I use File.separator and when File.pathSeparator?

java.io.File class contains four static separator variables. For better understanding, Let's understand with the help of some code

  1. separator: Platform dependent default name-separator character as String. For windows, it’s ‘\’ and for unix it’s ‘/’
  2. separatorChar: Same as separator but it’s char
  3. pathSeparator: Platform dependent variable for path-separator. For example PATH or CLASSPATH variable list of paths separated by ‘:’ in Unix systems and ‘;’ in Windows system
  4. pathSeparatorChar: Same as pathSeparator but it’s char

Note that all of these are final variables and system dependent.

Here is the java program to print these separator variables. FileSeparator.java

import java.io.File;

public class FileSeparator {

    public static void main(String[] args) {
        System.out.println("File.separator = "+File.separator);
        System.out.println("File.separatorChar = "+File.separatorChar);
        System.out.println("File.pathSeparator = "+File.pathSeparator);
        System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
    }

}

Output of above program on Unix system:

File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :

Output of the program on Windows system:

File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;

To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.

Here is the code snippet showing how to use separators correctly.

//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");

How do I change the font-size of an <option> element within <select>?

.service-small option {
    font-size: 14px;
    padding: 5px;
    background: #5c5c5c;
}

I think it because you used .styled-select in start of the class code.

How to make Bootstrap carousel slider use mobile left/right swipe

With bootstrap 4.2 its now very easy, you just need to pass the touch option in the carousel div as data-touch="true", as it accepts Boolean value only.

As in your case update bootstrap to 4.2 and paste(Or download source files) the following in exact order :

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

and then add the touch option in your bootstrap carousel div

    <div id="sidebar-carousel-1" class="carousel slide" data-ride="carousel" data-touch="true">

How to round up the result of integer division?

The integer math solution that Ian provided is nice, but suffers from an integer overflow bug. Assuming the variables are all int, the solution could be rewritten to use long math and avoid the bug:

int pageCount = (-1L + records + recordsPerPage) / recordsPerPage;

If records is a long, the bug remains. The modulus solution does not have the bug.

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');
}

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

Android - Share on Facebook, Twitter, Mail, ecc

Paresh Mayani's answer is mostly correct. Simply use a Broadcast Intent to let the system and all the other apps choose in what way the content is going to be shared.

To share text use the following code:

String message = "Text I want to share.";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(share, "Title of the dialog the system will open"));

Is it safe to use Project Lombok?

Wanted to use lombok's @ToString but soon faced random compile errors on project rebuild in Intellij IDEA. Had to hit compile several times before incremental compilation could complete with success.

Tried both lombok 1.12.2 and 0.9.3 with Intellij IDEA 12.1.6 and 13.0 without any lombok plugin under jdk 1.6.0_39 and 1.6.0_45.

Had to manually copy generated methods from delomboked source and put lombok on hold until better times.

Update

The problem happens only with parallel compile enabled.

Filed an issue: https://github.com/rzwitserloot/lombok/issues/648

Update

mplushnikov commented on 30 Jan 2016:

Newer version of Intellij doesn't have such issues anymore. I think it can be closed here.

Update

I would highly recommend to switch from Java+Lombok to Kotlin if possible. As it has resolved from the ground up all Java issues that Lombok tries to work around.

What static analysis tools are available for C#?

Have you seen CAT.NET?

From the blurb -

CAT.NET is a binary code analysis tool that helps identify common variants of certain prevailing vulnerabilities that can give rise to common attack vectors such as Cross-Site Scripting (XSS), SQL Injection and XPath Injection.

I used an early beta and it did seem to turn up a few things worth looking at.

Typedef function pointer?

  1. typedef is used to alias types; in this case you're aliasing FunctionFunc to void(*)().

  2. Indeed the syntax does look odd, have a look at this:

    typedef   void      (*FunctionFunc)  ( );
    //         ^                ^         ^
    //     return type      type name  arguments
    
  3. No, this simply tells the compiler that the FunctionFunc type will be a function pointer, it doesn't define one, like this:

    FunctionFunc x;
    void doSomething() { printf("Hello there\n"); }
    x = &doSomething;
    
    x(); //prints "Hello there"
    

Defining private module functions in python

This is an ancient question, but both module private (one underscore) and class-private (two underscores) mangled variables are now covered in the standard documentation:

The Python Tutorial » Classes » Private Variables

JQUERY ajax passing value from MVC View to Controller

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatu`enter code here`s) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Does calling clone() on an array also clone its contents?

1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).

Remember that 2D array clone doesn't work due to shallow copy implementation of clone().

public static void main(String[] args) {
    int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false

    int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true
}

How to export JSON from MongoDB using Robomongo

I don't think robomongo have such a feature. So you better use mongodb function as mongoexport for a specific Collection.

http://docs.mongodb.org/manual/reference/program/mongoexport/#export-in-json-format

But if you are looking for a backup solution is better to use

mongodump / mongorestore

How to repair COMException error 80040154?

Move excel variables which are global declare in your form to local like in my form I have:

Dim xls As New MyExcel.Interop.Application  
Dim xlb As MyExcel.Interop.Workbook

above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.

What Does This Mean in PHP -> or =>

-> is used to call a method, or access a property, on the object of a class

=> is used to assign values to the keys of an array

E.g.:

    $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34, 1=>2); 

And since PHP 7.4+ the operator => is used too for the added arrow functions, a more concise syntax for anonymous functions.

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to :

  • Stop the Oracle-related services (before deleting them from the registry).
  • In the registry, look not only for entries named "Oracle" but also e.g. for "ODP".

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

I fixed my problem with placing the:

<h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>

In:

<h:form>
     <h:commandButton class="btn btn-danger" value = "Remove" action="#{deleteEmployeeBean.delete}"></h:commandButton>
</h:form>

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Try the following code:

$cfg['Servers'][$i]['password'] = '';

if you see Password column field as 'No' for the 'root' user in Users Overview page of phpMyAdmin.

Find the last element of an array while using a foreach loop in PHP

I have a strong feeling that at the root of this "XY problem" the OP wanted just implode() function.

Laravel check if collection is empty

Starting from Laravel 5.3 you can simply use :

if ($mentor->isNotEmpty()) {
//do something.
}

Documentation https://laravel.com/docs/5.5/collections#method-isnotempty

Capture key press (or keydown) event on DIV element

Here example on plain JS:

_x000D_
_x000D_
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
  console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
  outline: none;_x000D_
}
_x000D_
<div _x000D_
  id="myDiv"_x000D_
  tabindex="0"_x000D_
>_x000D_
  Press me and start typing_x000D_
</div>
_x000D_
_x000D_
_x000D_

Collections.emptyList() vs. new instance

Use Collections.emptyList() if you want to make sure that the returned list is never modified.

This is what is returned on calling emptyList():

/**
 * The empty list (immutable). 
 */
public static final List EMPTY_LIST = new EmptyList();

Java - Including variables within strings?

You can always use String.format(....). i.e.,

String string = String.format("A String %s %2d", aStringVar, anIntVar);

I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.

Change a Django form field to a hidden field

For normal form you can do

class MyModelForm(forms.ModelForm):
    slug = forms.CharField(widget=forms.HiddenInput())

If you have model form you can do the following

class MyModelForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        fields = ('slug', 'ext')
        widgets = {'slug': forms.HiddenInput()}

You can also override __init__ method

class Myform(forms.Form):
    def __init__(self, *args, **kwargs):
        super(Myform, self).__init__(*args, **kwargs)
        self.fields['slug'].widget = forms.HiddenInput()

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)

print Result.groups()

Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.

I'm a beginner too and I faced that issue a couple of times myself.

How to check if variable is array?... or something array-like

PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    }
}

This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

You can also use the function is_array($var) to check if the passed variable is an array:

<?php
    var_dump( is_array(array()) ); // true
    var_dump( is_array(array(1, 2, 3)) ); // true
    var_dump( is_array($_SERVER) ); // true
?>

Read more in How to check if a variable is an array in PHP?

Facebook user url by id

UPDATE 2: This information is no more given by facebook. There is an official announcement for the behavior change (https://developers.facebook.com/blog/post/2018/04/19/facebook-login-changes-address-abuse/) but none for its alternative.

Yes, Just use this link and append your ID to the id parameter:

https://facebook.com/profile.php?id=<UID>

So for example:

https://facebook.com/profile.php?id=4

Will redirect you automatically to https://www.facebook.com/zuck Which is Mark Zuckerberg's profile.

If you want to do this for all your ids, then you can do it using a loop.

If you'd like, I can provide you with a snippet.

UPDATE: Alternatively, You can also do this:

https://facebook.com/<UID>

So that would be: https://facebook.com/4 which would automatically redirect to Zuck!

Switch statement equivalent in Windows batch file

Hariprasad didupe suggested a solution provided by Batchography, but it could be improved a bit. Unlike with other cases getting into default case will set ERRORLEVEL to 1 and, if that is not desired, you should manually set ERRORLEVEL to 0:

goto :switch-case-N-%N% 2>nul || (
    rem Default case
    rem Manually set ERRORLEVEL to 0 
    type nul>nul
    echo Something else
)
...

The readability could be improved for the price of a call overhead:

call:Switch SwitchLabel %N% || (
:SwitchLabel-1
    echo One
    goto:EOF     
:SwitchLabel-2
    echo Two
    goto:EOF
:SwitchLabel-3
    echo Three
    goto:EOF
:SwitchLabel-
    echo Default case
)

:Switch
goto:%1-%2 2>nul || (
    type nul>nul
    goto:%1-
)
exit /b

Few things to note:

  1. As stated before, this has a call overhead;
  2. Default case is required. If no action is needed put rem inside to avoid parenthesis error;
  3. All cases except the default one are executed in the sub-context. If you want to exit parent context (usually script) you may use this;
  4. Default case is executed in a parent context, so it cannot be combined with other cases (as reaching goto:EOF will exit parent context). This could be circumvented by replacing goto:%1- in subroutine with call:%1- for the price of additional call overhead;
  5. Subroutine takes label prefix (sans hyphen) and control variable. Without label prefix switch will look for labels with :- prefix (which are valid) and not passing a control variable will lead to default case.

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

Generate GUID in MySQL for existing Data?

The approved solution does create unique IDs but on first glance they look identical, only the first few characters differ.

If you want visibly different keys, try this:

update CityPopCountry set id = (select md5(UUID()));


MySQL [imran@lenovo] {world}> select city, id from CityPopCountry limit 10;
+------------------------+----------------------------------+
| city                   | id                               |
+------------------------+----------------------------------+
| A Coruña (La Coruña)   | c9f294a986a1a14f0fe68467769feec7 |
| Aachen                 | d6172223a472bdc5f25871427ba64e46 |
| Aalborg                | 8d11bc300f203eb9cb7da7cb9204aa8f |
| Aba                    | 98aeeec8aa81a4064113764864114a99 |
| Abadan                 | 7aafe6bfe44b338f99021cbd24096302 |
| Abaetetuba             | 9dd331c21b983c3a68d00ef6e5852bb5 |
| Abakan                 | e2206290ce91574bc26d0443ef50fc05 |
| Abbotsford             | 50ca17be25d1d5c2ac6760e179b7fd15 |
| Abeokuta               | ab026fa6238e2ab7ee0d76a1351f116f |
| Aberdeen               | d85eef763393862e5fe318ca652eb16d |
+------------------------+----------------------------------+

I'm using MySQL Server version: 5.5.40-0+wheezy1 (Debian)

Filename too long in Git for Windows

I had this error too, but in my case the cause was using an outdated version of npm, v1.4.28.

Updating to npm v3 followed by

rm -rf node_modules
npm -i

worked for me. npm issue 2697 has details of the "maximally flat" folder structure included in npm v3 (released 2015-06-25).

how to concat two columns into one with the existing column name in mysql?

Remove the * from your query and use individual column names, like this:

SELECT SOME_OTHER_COLUMN, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`;

Using * means, in your results you want all the columns of the table. In your case * will also include FIRSTNAME. You are then concatenating some columns and using alias of FIRSTNAME. This creates 2 columns with same name.

Ignore cells on Excel line graph

  1. In the value or values you want to separate, enter the =NA() formula. This will appear that the value is skipped but the preceding and following data points will be joined by the series line.
  2. Enter the data you want to skip in the same location as the original (row or column) but add it as a new series. Add the new series to your chart.
  3. Format the new data point to match the original series format (color, shape, etc.). It will appear as though the data point was just skipped in the original series but will still show on your chart if you want to label it or add a callout.

How to print to console using swift playground?

In Xcode 6.3 and later (including Xcode 7 and 8), console output appears in the Debug area at the bottom of the playground window (similar to where it appears in a project). To show it:

  • Menu: View > Debug Area > Show Debug Area (??Y)

  • Click the middle button of the workspace-layout widget in the toolbar

    workspace layout widget

  • Click the triangle next to the timeline at the bottom of the window

    triangle for console

Anything that writes to the console, including Swift's print statement (renamed from println in Swift 2 beta) shows up there.


In earlier Xcode 6 versions (which by now you probably should be upgrading from anyway), show the Assistant editor (e.g. by clicking the little circle next to a bit in the output area). Console output appears there.

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Strangely, none of these solutions work as RestTemplate does not seem to return the response on some client and server 500x errors. In which case, you will have log those as well by implementing ResponseErrorHandler as follows. Here is a draft code, but you get the point:

You can set the same interceptor as the error handler:

restTemplate.getInterceptors().add(interceptor);
restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
restTemplate.setErrorHandler(interceptor);

And the intercept implements both interfaces:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus.Series;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.ResponseErrorHandler;

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor, ResponseErrorHandler {
    static final Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.class);
    static final DefaultResponseErrorHandler defaultResponseErrorHandler = new DefaultResponseErrorHandler();
    final Set<Series> loggableStatuses = new HashSet();

    public LoggingRequestInterceptor() {
    }

    public LoggingRequestInterceptor(Set<Series> loggableStatuses) {
        loggableStatuses.addAll(loggableStatuses);
    }

    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        this.traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        if(response != null) {
            this.traceResponse(response);
        }

        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        log.debug("===========================request begin================================================");
        log.debug("URI         : {}", request.getURI());
        log.debug("Method      : {}", request.getMethod());
        log.debug("Headers     : {}", request.getHeaders());
        log.debug("Request body: {}", new String(body, "UTF-8"));
        log.debug("==========================request end================================================");
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        if(this.loggableStatuses.isEmpty() || this.loggableStatuses.contains(response.getStatusCode().series())) {
            StringBuilder inputStringBuilder = new StringBuilder();

            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));

                for(String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
                    inputStringBuilder.append(line);
                    inputStringBuilder.append('\n');
                }
            } catch (Throwable var5) {
                log.error("cannot read response due to error", var5);
            }

            log.debug("============================response begin==========================================");
            log.debug("Status code  : {}", response.getStatusCode());
            log.debug("Status text  : {}", response.getStatusText());
            log.debug("Headers      : {}", response.getHeaders());
            log.debug("Response body: {}", inputStringBuilder.toString());
            log.debug("=======================response end=================================================");
        }

    }

    public boolean hasError(ClientHttpResponse response) throws IOException {
        return defaultResponseErrorHandler.hasError(response);
    }

    public void handleError(ClientHttpResponse response) throws IOException {
        this.traceResponse(response);
        defaultResponseErrorHandler.handleError(response);
    }
}

Execute PowerShell Script from C# with Commandline Arguments

I have another solution. I just want to test if executing a PowerShell script succeeds, because perhaps somebody might change the policy. As the argument, I just specify the path of the script to be executed.

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'c:\Scripts\test.ps1'";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();

string output = process.StandardOutput.ReadToEnd();
Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));

string errors = process.StandardError.ReadToEnd();
Assert.IsTrue(string.IsNullOrEmpty(errors));

With the contents of the script being:

$someVariable = "StringToBeVerifiedInAUnitTest"
$someVariable

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

I suggest a convenient way to solve this problem. Just assign the attribute "android:configChanges" value as followed in the Mainfest.xml for your errored activity. like this:

<activity android:name=".main.MainActivity"
              android:label="mainActivity"
              android:configChanges="orientation|keyboardHidden|navigation">
</activity>

the first solution I gave out had really reduced the frequency of OOM error to a low level. But, it did not solve the problem totally. And then I will give out the 2nd solution:

As the OOM detailed, I have used too much runtime memory. So, I reduce the picture size in ~/res/drawable of my project. Such as an overqualified picture which has a resolution of 128X128, could be resized to 64x64 which would also be suitable for my application. And after I did so with a pile of pictures, the OOM error doesn't occur again.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

Android: adb: Permission Denied

Do adb remount. And then try adb shell

How to disable GCC warnings for a few lines of code

I had same issue with external libraries like ROS headers. I like to use following options in CMakeLists.txt for stricter compilation:

set(CMAKE_CXX_FLAGS "-std=c++0x -Wall -Wextra -Wstrict-aliasing -pedantic -Werror -Wunreachable-code ${CMAKE_CXX_FLAGS}")

However doing this causes all kind of pedantic errors in externally included libraries as well. The solution is to disable all pedantic warnings before you include external libraries and re-enable like this:

//save compiler switches
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"

//Bad headers with problem goes here
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>

//restore compiler switches
#pragma GCC diagnostic pop

How to know the git username and email saved during configuration?

If you want to check or set the user name and email you can use the below command

Check user name

git config user.name

Set user name

git config user.name "your_name"

Check your email

git config user.email

Set/change your email

git config user.email "[email protected]"

List/see all configuration

git config --list

Please explain the exec() function and its family

Simplistically, in UNIX, you have the concept of processes and programs. A process is an environment in which a program executes.

The simple idea behind the UNIX "execution model" is that there are two operations you can do.

The first is to fork(), which creates a brand new process containing a duplicate (mostly) of the current program, including its state. There are a few differences between the two processes which allow them to figure out which is the parent and which is the child.

The second is to exec(), which replaces the program in the current process with a brand new program.

From those two simple operations, the entire UNIX execution model can be constructed.


To add some more detail to the above:

The use of fork() and exec() exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.

The fork() call makes a near duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations, but the idea is to create as close a copy as possible). Only one process calls fork() but two processes return from that call - sounds bizarre but it's really quite elegant

The new process (called the child) gets a different process ID (PID) and has the PID of the old process (the parent) as its parent PID (PPID).

Because the two processes are now running exactly the same code, they need to be able to tell which is which - the return code of fork() provides this information - the child gets 0, the parent gets the PID of the child (if the fork() fails, no child is created and the parent gets an error code).

That way, the parent knows the PID of the child and can communicate with it, kill it, wait for it and so on (the child can always find its parent process with a call to getppid()).

The exec() call replaces the entire current contents of the process with a new program. It loads the program into the current process space and runs it from the entry point.

So, fork() and exec() are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find - the shell forks, then the child loads the find program into memory, setting up all command line arguments, standard I/O and so forth.

But they're not required to be used together. It's perfectly acceptable for a program to call fork() without a following exec() if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions).

This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork a copy of themselves to process a specific request while the parent goes back to listening. For this situation, the program contains both the parent and the child code.

Similarly, programs that know they're finished and just want to run another program don't need to fork(), exec() and then wait()/waitpid() for the child. They can just load the child directly into their current process space with exec().

Some UNIX implementations have an optimized fork() which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork() until the program attempts to change something in that space. This is useful for those programs using only fork() and not exec() in that they don't have to copy an entire process space. Under Linux, fork() only makes a copy of the page tables and a new task structure, exec() will do the grunt work of "separating" the memory of the two processes.

If the exec is called following fork (and this is what happens mostly), that causes a write to the process space and it is then copied for the child process, before modifications are allowed.

Linux also has a vfork(), even more optimised, which shares just about everything between the two processes. Because of that, there are certain restrictions in what the child can do, and the parent halts until the child calls exec() or _exit().

The parent has to be stopped (and the child is not permitted to return from the current function) since the two processes even share the same stack. This is slightly more efficient for the classic use case of fork() followed immediately by exec().

Note that there is a whole family of exec calls (execl, execle, execve and so on) but exec in context here means any of them.

The following diagram illustrates the typical fork/exec operation where the bash shell is used to list a directory with the ls command:

+--------+
| pid=7  |
| ppid=4 |
| bash   |
+--------+
    |
    | calls fork
    V
+--------+             +--------+
| pid=7  |    forks    | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash   |             | bash   |
+--------+             +--------+
    |                      |
    | waits for pid 22     | calls exec to run ls
    |                      V
    |                  +--------+
    |                  | pid=22 |
    |                  | ppid=7 |
    |                  | ls     |
    V                  +--------+
+--------+                 |
| pid=7  |                 | exits
| ppid=4 | <---------------+
| bash   |
+--------+
    |
    | continues
    V

file_get_contents() how to fix error "Failed to open stream", "No such file"

I just solve this by encode params in the url.
URL may be: http://abc/dgdc.php?p1=Hello&p2=some words
we just need to encode the params2.

$params2 = "some words";
$params2 = urlencode($params2);

$url = "http://abc/dgdc.php?p1=djkl&p2=$params2"

$result = file_get_contents($url);

What is the difference between ndarray and array in numpy?

I think with np.array() you can only create C like though you mention the order, when you check using np.isfortran() it says false. but with np.ndarrray() when you specify the order it creates based on the order provided.

Text inset for UITextField?

You can adjust the positioning of the text within a text field by making it a subclass of UITextField and overriding the -textRectForBounds: method.

How to update array value javascript?

Why not use an object1?

var dict = { "a": 1, "b": 2, "c": 3 };

Then you can update it like so

dict.a = 23;

or

dict["a"] = 23;

If you wan't to delete2 a particular key, it's as simple as:

delete dict.a;

1 See Objects vs arrays in Javascript for key/value pairs.
2 See the delete operator.

Sql Server trigger insert values from new row into another table

You use an insert trigger - inside the trigger, inserted row items will be exposed as a logical table INSERTED, which has the same column layout as the table the trigger is defined on.

Delete triggers have access to a similar logical table called DELETED.

Update triggers have access to both an INSERTED table that contains the updated values and a DELETED table that contains the values to be updated.

Quickest way to compare two generic lists for differences

If only combined result needed, this will work too:

var set1 = new HashSet<T>(list1);
var set2 = new HashSet<T>(list2);
var areEqual = set1.SetEquals(set2);

where T is type of lists element.

How to implement debounce in Vue2?

Very simple without lodash

  handleScroll: function() {
    if (this.timeout) 
      clearTimeout(this.timeout); 

    this.timeout = setTimeout(() => {
      // your action
    }, 200); // delay
  }

How to see the changes between two commits without commits in-between?

Since Git 2.19, you can simply use:

git range-diff rev1...rev2 - compare two commit trees, starting by their common ancestor

or git range-diff rev1~..rev1 rev2~..rev2 - compare of changes introduced by 2 given commits

How do I access store state in React Redux?

You want to do more than just getState. You want to react to changes in the store.

If you aren't using react-redux, you can do this:

function rerender() {
    const state = store.getState();
    render(
        <div>
            { state.items.map((item) => <p> {item.title} </p> )}
        </div>,
        document.getElementById('app')
    );
}

// subscribe to store
store.subscribe(rerender);

// do initial render
rerender();

// dispatch more actions and view will update

But better is to use react-redux. In this case you use the Provider like you mentioned, but then use connect to connect your component to the store.

How to use a client certificate to authenticate and authorize in a Web API

I actually had a similar issue, where we had to many trusted root certificates. Our fresh installed webserver had over a hunded. Our root started with the letter Z so it ended up at the end of the list.

The problem was that the IIS sent only the first twenty-something trusted roots to the client and truncated the rest, including ours. It was a few years ago, can't remember the name of the tool... it was part of the IIS admin suite, but Fiddler should do as well. After realizing the error, we removed a lot trusted roots that we don't need. This was done trial and error, so be careful what you delete.

After the cleanup everything worked like a charm.

How to set Spinner default value to null?

Alternatively, you could override your spinner adapter, and provide an empty view for position 0 in your getView method, and a view with 0dp height in the getDropDownView method.

This way, you have an initial text such as "Select an Option..." that shows up when the spinner is first loaded, but it is not an option for the user to choose (technically it is, but because the height is 0, they can't see it).

How to change the Content of a <textarea> with JavaScript

If it's jQuery...

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

or

document.getElementById('myText').value = '';

Reference: Text Area Object

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Type Checking: typeof, GetType, or is?

if (c is UserControl) c.Enabled = enable;

Why is enum class preferred over plain enum?

One thing that hasn't been explicitly mentioned - the scope feature gives you an option to have the same name for an enum and class method. For instance:

class Test
{
public:
   // these call ProcessCommand() internally
   void TakeSnapshot();
   void RestoreSnapshot();
private:
   enum class Command // wouldn't be possible without 'class'
   {
        TakeSnapshot,
        RestoreSnapshot
   };
   void ProcessCommand(Command cmd); // signal the other thread or whatever
};

Make a DIV fill an entire table cell

I'm not sure what you want to do but you might try this one:

<td width="661" valign="top"><div>Content for New Div Tag Goes Here</div></td>

Breaking up long strings on multiple lines in Ruby without stripping newlines

You can use \ to indicate that any line of Ruby continues on the next line. This works with strings too:

string = "this is a \
string that spans lines"

puts string.inspect

will output "this is a string that spans lines"

How to decrypt a password from SQL server?

You cannot decrypt this password again but there is another method named "pwdcompare". Here is a example how to use it with SQL syntax:

USE TEMPDB
GO
declare @hash varbinary (255)
CREATE TABLE tempdb..h (id_num int, hash varbinary (255))
SET @hash = pwdencrypt('123') -- encryption
INSERT INTO tempdb..h (id_num,hash) VALUES (1,@hash)
SET @hash = pwdencrypt('123')
INSERT INTO tempdb..h (id_num,hash) VALUES (2,@hash)
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 2
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
INSERT INTO tempdb..h (id_num,hash) 
VALUES (3,CONVERT(varbinary (255),
0x01002D60BA07FE612C8DE537DF3BFCFA49CD9968324481C1A8A8FE612C8DE537DF3BFCFA49CD9968324481C1A8A8))
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 3
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
DROP TABLE tempdb..h
GO

Can't clone a github repo on Linux via HTTPS

I met the same problem, the error message and OS info are as follows

OS info:

CentOS release 6.5 (Final)

Linux 192-168-30-213 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

error info:

Initialized empty Git repository in /home/techops/pyenv/.git/ Password: error: while accessing https://[email protected]/pyenv/pyenv.git/info/refs

fatal: HTTP request failed

git & curl version info

git info :git version 1.7.1

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz

debugging

$ curl --verbose https://github.com

  • About to connect() to github.com port 443 (#0)
  • Trying 13.229.188.59... connected
  • Connected to github.com (13.229.188.59) port 443 (#0)
  • Initializing NSS with certpath: sql:/etc/pki/nssdb
  • CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
  • NSS error -12190
  • Error in TLS handshake, trying SSLv3... GET / HTTP/1.1 User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 Host: github.com Accept: /

  • Connection died, retrying a fresh connect

  • Closing connection #0
  • Issue another request to this URL: 'https://github.com'
  • About to connect() to github.com port 443 (#0)
  • Trying 13.229.188.59... connected
  • Connected to github.com (13.229.188.59) port 443 (#0)
  • TLS disabled due to previous handshake failure
  • CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none
  • NSS error -12286
  • Closing connection #0
  • SSL connect error curl: (35) SSL connect error

after upgrading curl , libcurl and nss , git clone works fine again, so here it is. the update command is as follows

sudo yum update -y nss curl libcurl

Force flushing of output to a file while bash script is still running

This isn't a function of bash, as all the shell does is open the file in question and then pass the file descriptor as the standard output of the script. What you need to do is make sure output is flushed from your script more frequently than you currently are.

In Perl for example, this could be accomplished by setting:

$| = 1;

See perlvar for more information on this.

Angular/RxJs When should I unsubscribe from `Subscription`

In my case I am using a variation of the solution proposed by @seanwright:
https://github.com/NetanelBasal/ngx-take-until-destroy

It's a file used in the ngx-rocket / starter-kit project. You can access it here until-destroyed.ts

The component would look like so

/**
 * RxJS operator that unsubscribe from observables on destory.
 * Code forked from https://github.com/NetanelBasal/ngx-take-until-destroy
 *
 * IMPORTANT: Add the `untilDestroyed` operator as the last one to
 * prevent leaks with intermediate observables in the
 * operator chain.
 *
 * @param instance The parent Angular component or object instance.
 * @param destroyMethodName The method to hook on (default: 'ngOnDestroy').
 */
import { untilDestroyed } from '../../core/until-destroyed';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})
export class ExampleComponent implements OnInit, OnDestroy {

  ngOnInit() {
    interval(1000)
        .pipe(untilDestroyed(this))
        .subscribe(val => console.log(val));

    // ...
  }


  // This method must be present, even if empty.
  ngOnDestroy() {
    // To protect you, an error will be thrown if it doesn't exist.
  }
}

How can I use a JavaScript variable as a PHP variable?

PHP runs on the server. It outputs some text (usually). This is then parsed by the client.

During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.

If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).

You can do this by:

  • Setting location (GET only)
  • Submitting a form (with the FormElement.submit() method)
  • Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.

Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

I generally like to create my own function as has been stated above. However I like to add a few things to it so that if I accidentally leave in debugging code I can quickly find it in the code base. Maybe this will help someone else out.

function _pr($d) {
    echo "<div style='border: 1px solid#ccc; padding: 10px;'>";
    echo '<strong>' . debug_backtrace()[0]['file'] . ' ' . debug_backtrace()[0]['line'] . '</strong>';
    echo "</div>";
    echo '<pre>';
    if(is_array($d)) {
    print_r($d);
    } else if(is_object($d)) {
    var_dump($d);
    }
    echo '</pre>';
}

What is an efficient way to implement a singleton pattern in Java?

This is how to implement a simple singleton:

public class Singleton {
    // It must be static and final to prevent later modification
    private static final Singleton INSTANCE = new Singleton();
    /** The constructor must be private to prevent external instantiation */
    private Singleton(){}
    /** The public static method allowing to get the instance */
    public static Singleton getInstance() {
        return INSTANCE;
    }
}

This is how to properly lazy create your singleton:

public class Singleton {
    // The constructor must be private to prevent external instantiation
    private Singleton(){}
    /** The public static method allowing to get the instance */
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
    /**
     * The static inner class responsible for creating your instance only on demand,
     * because the static fields of a class are only initialized when the class
     * is explicitly called and a class initialization is synchronized such that only
     * one thread can perform it, this rule is also applicable to inner static class
     * So here INSTANCE will be created only when SingletonHolder.INSTANCE
     * will be called
     */
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
}

Store select query's output in one array in postgres

I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):

SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)

HTML / CSS How to add image icon to input type="button"?

you can try insert image inside button http://jsfiddle.net/s5GVh/1415/

<button type="submit"><img src='https://aca5.accela.com/bcc/app_themesDefault/assets/gsearch_disabled.png'/></button>

SQL Statement using Where clause with multiple values

Select t1.SongName
From tablename t1
left join tablename t2
 on t1.SongName = t2.SongName
    and t1.PersonName <> t2.PersonName
    and t1.Status = 'Complete' -- my assumption that this is necessary
    and t2.Status = 'Complete' -- my assumption that this is necessary
    and t1.PersonName IN ('Holly', 'Ryan')
    and t2.PersonName IN ('Holly', 'Ryan')

PermGen elimination in JDK 8

This is one of the new features of Java 8, part of JDK Enhancement Proposals 122:

Remove the permanent generation from the Hotspot JVM and thus the need to tune the size of the permanent generation.

The list of all the JEPs that will be included in Java 8 can be found on the JDK8 milestones page.

How to get the background color code of an element in hex?

Adding on @Newred solution. If your style has more than just the background-color you can use this:

$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1]

Custom HTTP Authorization Header

Put it in a separate, custom header.

Overloading the standard HTTP headers is probably going to cause more confusion than it's worth, and will violate the principle of least surprise. It might also lead to interoperability problems for your API client programmers who want to use off-the-shelf tool kits that can only deal with the standard form of typical HTTP headers (such as Authorization).

How can I disable a button in a jQuery dialog from a function?

Here's an example that I just implemented using the Array method of assigning buttons, which then allows me to use id selectors later on - just as the accepted answer stated originally - to enable/disable buttons and even show/hide them completely as I'm doing.

$( "#dialog-form" ).dialog({
autoOpen: true,
height: 500,
width: 450,
modal: true,
buttons: [
{
    id: "submit_btn",
    text: "Make Apointment",
    click: function() { 
        //do ajax       
    }       
},
{
    id: "cancel_btn",
    text: "Cancel",
    click: function() {
       $( this ).dialog( "close" );
    }
},
{
    id: "ok_btn",
    text: "OK",
    click: function() {
       $( this).dialog('close');
    },
    disabled: "disabled"
}],
close: function() {
    allFields.val( "" ).removeClass( "ui-state-error" );
}
});

After successfully submitting, I disable and hide two of the buttons and enable the OK button that was disabled by default.

$('#submit_btn, #cancel_btn').attr('disabled','disabled').addClass('ui-state-disabled').hide();
$('#ok_btn').attr('disabled','').removeClass('ui-state-disabled').show();

Hope this helps.