Programs & Examples On #Boolean logic

An algebraic system developed by George Boole. Uses operations such as "And", "Or" and "Not" on Binary True/False values. It may be used to accomplish complex tasks.

How to use boolean 'and' in Python

& is used for bit-wise comparison. use and instead. and btw, you don't need semicolon at the end of print statement.

Easiest way to flip a boolean value?

Clearly you need a flexible solution that can support types masquerading as boolean. The following allows for that:

template<typename T>    bool Flip(const T& t);

You can then specialize this for different types that might pretend to be boolean. For example:

template<>  bool Flip<bool>(const bool& b)  { return !b; }
template<>  bool Flip<int>(const int& i)    { return !(i == 0); }

An example of using this construct:

if(Flip(false))  { printf("flipped false\n"); }
if(!Flip(true))  { printf("flipped true\n"); }

if(Flip(0))  { printf("flipped 0\n"); }
if(!Flip(1)) { printf("flipped 1\n"); }

No, I'm not serious.

Does Python support short-circuiting?

Yep, both and and or operators short-circuit -- see the docs.

pandas: multiple conditions while indexing data frame - unexpected behavior

As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them.

That's right. Remember that you're writing the condition in terms of what you want to keep, not in terms of what you want to drop. For df1:

df1 = df[(df.a != -1) & (df.b != -1)]

You're saying "keep the rows in which df.a isn't -1 and df.b isn't -1", which is the same as dropping every row in which at least one value is -1.

For df2:

df2 = df[(df.a != -1) | (df.b != -1)]

You're saying "keep the rows in which either df.a or df.b is not -1", which is the same as dropping rows where both values are -1.

PS: chained access like df['a'][1] = -1 can get you into trouble. It's better to get into the habit of using .loc and .iloc.

How can I obtain the element-wise logical NOT of a pandas Series?

In support to the excellent answers here, and for future convenience, there may be a case where you want to flip the truth values in the columns and have other values remain the same (nan values for instance)

In[1]: series = pd.Series([True, np.nan, False, np.nan])
In[2]: series = series[series.notna()] #remove nan values
 
In[3]: series # without nan                                            
Out[3]: 
0     True
2    False
dtype: object

# Out[4] expected to be inverse of Out[3], pandas applies bitwise complement 
# operator instead as in `lambda x : (-1*x)-1`

In[4]: ~series
Out[4]: 
0    -2
2    -1
dtype: object

as a simple non-vectorized solution you can just, 1. check types2. inverse bools

In[1]: series = pd.Series([True, np.nan, False, np.nan])

In[2]: series = series.apply(lambda x : not x if x is bool else x)
Out[2]: 
Out[2]: 
0     True
1      NaN
2    False
3      NaN
dtype: object

How to convert "0" and "1" to false and true

Or if the Boolean value is not been returned, you can do something like this:

bool boolValue = (returnValue == "1");

if (boolean == false) vs. if (!boolean)

- Here its more about the coding style than being the functionality....

- The 1st option is very clear, but then the 2nd one is quite elegant... no offense, its just my view..

Any good boolean expression simplifiers out there?

Try Logic Friday 1 It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.

The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.

Your expression simplifies to C.

Check if at least two out of three booleans are true

Taking another approach to this using Java 8's Stream functionality, for any number of booleans with an arbitrary required amount. The Stream short circuits if it hits the limit before processing all of the elements:

public static boolean atLeastTrue(int amount, Boolean ... booleans) {
    return Stream.of(booleans).filter(b -> b).limit(amount).count() == amount;
}

public static void main(String[] args){
    System.out.println("1,2: " + atLeastTrue(1, true, false, true));
    System.out.println("1,1: " + atLeastTrue(1, false, true));
    System.out.println("1,0: " + atLeastTrue(1, false));
    System.out.println("1,1: " + atLeastTrue(1, true, false));
    System.out.println("2,3: " + atLeastTrue(2, true, false, true, true));
    System.out.println("3,2: " + atLeastTrue(3, true, false, true, false));
    System.out.println("3,3: " + atLeastTrue(3, true, true, true, false));
}

Output:

1,2: true
1,1: true
1,0: false
1,1: true
2,3: true
3,2: false
3,3: true

How to test multiple variables against a value?

The most pythonic way of representing your pseudo-code in Python would be:

x = 0
y = 1
z = 3
mylist = []

if any(v == 0 for v in (x, y, z)):
    mylist.append("c")
if any(v == 1 for v in (x, y, z)):
    mylist.append("d")
if any(v == 2 for v in (x, y, z)):
    mylist.append("e")
if any(v == 3 for v in (x, y, z)):
    mylist.append("f")

Differences in boolean operators: & vs && and | vs ||

In Java, the single operators &, |, ^, ! depend on the operands. If both operands are ints, then a bitwise operation is performed. If both are booleans, a "logical" operation is performed.

If both operands mismatch, a compile time error is thrown.

The double operators &&, || behave similarly to their single counterparts, but both operands must be conditional expressions, for example:

if (( a < 0 ) && ( b < 0 )) { ... } or similarly, if (( a < 0 ) || ( b < 0 )) { ... }

source: java programming lang 4th ed

How do I test if a variable does not equal either of two values?

Think of ! (negation operator) as "not", || (boolean-or operator) as "or" and && (boolean-and operator) as "and". See Operators and Operator Precedence.

Thus:

if(!(a || b)) {
  // means neither a nor b
}

However, using De Morgan's Law, it could be written as:

if(!a && !b) {
  // is not a and is not b
}

a and b above can be any expression (such as test == 'B' or whatever it needs to be).

Once again, if test == 'A' and test == 'B', are the expressions, note the expansion of the 1st form:

// if(!(a || b)) 
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')

Download files from server php

If the folder is accessible from the browser (not outside the document root of your web server), then you just need to output links to the locations of those files. If they are outside the document root, you will need to have links, buttons, whatever, that point to a PHP script that handles getting the files from their location and streaming to the response.

Getting XML Node text value with Java DOM

If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

import com.ximpleware.*;
public class queryText {
    public static void main(String[] s) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        // first manually navigate
        if(vn.toElement(VTDNav.FC,"tag")){
            int i= vn.getText();
            if (i!=-1){
                System.out.println("text ===>"+vn.toString(i));
            }
            if (vn.toElement(VTDNav.NS,"tag")){
                i=vn.getText();
                System.out.println("text ===>"+vn.toString(i));
            }
        }

        // second version use XPath
        ap.selectXPath("/add/tag/text()");
        int i=0;
        while((i=ap.evalXPath())!= -1){
            System.out.println("text node ====>"+vn.toString(i));
        }
    }
}

Java JDBC - How to connect to Oracle using Service Name instead of SID

This discussion helped me resolve the issue I was struggling with for days. I looked around all over the internet until I found the answered by Jim Tough on May 18 '11 at 15:17. With that answer I was able to connect. Now I want to give back and help others with a complete example. Here goes:

import java.sql.*; 

public class MyDBConnect {

    public static void main(String[] args) throws SQLException {

        try { 
            String dbURL = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=whatEverYourHostNameIs)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=yourServiceName)))";
            String strUserID = "yourUserId";
            String strPassword = "yourPassword";
            Connection myConnection=DriverManager.getConnection(dbURL,strUserID,strPassword);

            Statement sqlStatement = myConnection.createStatement();
            String readRecordSQL = "select * from sa_work_order where WORK_ORDER_NO = '1503090' ";  
            ResultSet myResultSet = sqlStatement.executeQuery(readRecordSQL);
            while (myResultSet.next()) {
                System.out.println("Record values: " + myResultSet.getString("WORK_ORDER_NO"));
            }
            myResultSet.close();
            myConnection.close();

        } catch (Exception e) {
            System.out.println(e);
        }       
    }
}

How can I pass a Bitmap object from one activity to another

Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.

To store bitmap in a file myImage in internal storage:

public String createImageFromBitmap(Bitmap bitmap) {
    String fileName = "myImage";//no .png or .jpg needed
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
        fo.write(bytes.toByteArray());
        // remember close file output
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
        fileName = null;
    }
    return fileName;
}

Then in the next activity you can decode this file myImage to a bitmap using following code:

//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));

Note A lot of checking for null and scaling bitmap's is ommited.

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

With quotes around the date:

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

Only using @JsonIgnore during serialization, but not deserialization

"user": {
        "firstName": "Musa",
        "lastName": "Aliyev",
        "email": "[email protected]",
        "passwordIn": "98989898", (or encoded version in front if we not using https)
        "country": "Azeribaijan",
        "phone": "+994707702747"
    }

@CrossOrigin(methods=RequestMethod.POST)
@RequestMapping("/public/register")
public @ResponseBody MsgKit registerNewUsert(@RequestBody User u){

        root.registerUser(u);

    return new MsgKit("registered");
}  

@Service
@Transactional
public class RootBsn {

    @Autowired UserRepository userRepo;

    public void registerUser(User u) throws Exception{

        u.setPassword(u.getPasswordIn());
        //Generate some salt and  setPassword (encoded -  salt+password)
        User u=userRepo.save(u);

        System.out.println("Registration information saved");
    }

}

    @Entity        
@JsonIgnoreProperties({"recordDate","modificationDate","status","createdBy","modifiedBy","salt","password"})
                    public class User implements Serializable {
                        private static final long serialVersionUID = 1L;

                        @Id
                        @GeneratedValue(strategy=GenerationType.AUTO)
                        private Long id;

                        private String country;

                        @Column(name="CREATED_BY")
                        private String createdBy;

                        private String email;

                        @Column(name="FIRST_NAME")
                        private String firstName;

                        @Column(name="LAST_LOGIN_DATE")
                        private Timestamp lastLoginDate;

                        @Column(name="LAST_NAME")
                        private String lastName;

                        @Column(name="MODIFICATION_DATE")
                        private Timestamp modificationDate;

                        @Column(name="MODIFIED_BY")
                        private String modifiedBy;

                        private String password;

                        @Transient
                        private String passwordIn;

                        private String phone;

                        @Column(name="RECORD_DATE")
                        private Timestamp recordDate;

                        private String salt;

                        private String status;

                        @Column(name="USER_STATUS")
                        private String userStatus;

                        public User() {
                        }
                // getters and setters
                }

Get a resource using getResource()

TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
  • leading slash to denote the root of the classpath
  • slashes instead of dots in the path
  • you can call getResource() directly on the class.

Is Laravel really this slow?

Laravel is not actually that slow. 500-1000ms is absurd; I got it down to 20ms in debug mode.

The problem was Vagrant/VirtualBox + shared folders. I didn't realize they incurred such a performance hit. I guess because Laravel has so many dependencies (loads ~280 files) and each of those file reads is slow, it adds up really quick.

kreeves pointed me in the right direction, this blog post describes a new feature in Vagrant 1.5 that lets you rsync your files into the VM rather than using a shared folder.

There's no native rsync client on Windows, so you'll have to use cygwin. Install it, and make sure to check off Net/rsync. Add C:\cygwin64\bin to your paths. [Or you can install it on Win10/Bash]

Vagrant introduces the new feature. I'm using Puphet, so my Vagrantfile looks a bit funny. I had to tweak it to look like this:

  data['vm']['synced_folder'].each do |i, folder|
    if folder['source'] != '' && folder['target'] != '' && folder['id'] != ''
      config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", 
        id: "#{folder['id']}", 
        type: "rsync",
        rsync__auto: "true",
        rsync__exclude: ".hg/"
    end
  end

Once you're all set up, try vagrant up. If everything goes smoothly your machine should boot up and it should copy all the files over. You'll need to run vagrant rsync-auto in a terminal to keep the files up to date. You'll pay a little bit in latency, but for 30x faster page loads, it's worth it!


If you're using PhpStorm, it's auto-upload feature works even better than rsync. PhpStorm creates a lot of temporary files which can trip up file watchers, but if you let it handle the uploads itself, it works nicely.


One more option is to use lsyncd. I've had great success using this on Ubuntu host -> FreeBSD guest. I haven't tried it on a Windows host yet.

How to get a Char from an ASCII Character Code in c#

Two options:

char c1 = '\u0001';
char c1 = (char) 1;

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

Despite this question being rather old, I had to deal with a similar warning and wanted to share what I found out.

First of all this is a warning and not an error. So there is no need to worry too much about it. Basically it means, that Tomcat does not know what to do with the source attribute from context.

This source attribute is set by Eclipse (or to be more specific the Eclipse Web Tools Platform) to the server.xml file of Tomcat to match the running application to a project in workspace.

Tomcat generates a warning for every unknown markup in the server.xml (i.e. the source attribute) and this is the source of the warning. You can safely ignore it.

Check if current directory is a Git repository

if ! [[ $(pwd) = *.git/* || $(pwd) = *.git ]]; then 
  if type -P git >/dev/null; then
    ! git rev-parse --is-inside-work-tree >/dev/null 2>&1 || {
     printf '\n%s\n\n' "GIT repository detected." && git status
    }
  fi
fi

Thank you ivan_pozdeev, Now I have a test if inside the .git directory the code will not run so no errors printed out or false exit status.

The "! [[ $(pwd) = .git/ || $(pwd) = *.git ]]" tests if you're not inside a .git repo then it will run the git command. The builtin type command is use to check if you have git installed or it is within your PATH. see help type

Laravel Request getting current path with query string

Laravel 4.5

Just use

Request::fullUrl()

It will return the full url

You can extract the Querystring with str_replace

str_replace(Request::url(), '', Request::fullUrl())

Or you can get a array of all the queries with

Request::query()

Laravel >5.1

Just use

$request->fullUrl()

It will return the full url

You can extract the Querystring with str_replace

str_replace($request->url(), '',$request->fullUrl())

Or you can get a array of all the queries with

$request->query()

Find the PID of a process that uses a port on Windows

Just open a command shell and type (saying your port is 123456):

netstat -a -n -o | find "123456"

You will see everything you need.

The headers are:

 Proto  Local Address          Foreign Address        State           PID
 TCP    0.0.0.0:37             0.0.0.0:0              LISTENING       1111

Return an empty Observable

In my case with Angular2 and rxjs, it worked with:

import {EmptyObservable} from 'rxjs/observable/EmptyObservable';
...
return new EmptyObservable();
...

How do I use spaces in the Command Prompt?

Single quotation marks won't do in that case. You have to add quotation marks around each path and also enclose the whole command in quotation marks:

cmd /C ""C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*""

Running two projects at once in Visual Studio

Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.

Solution properties dialog

Take multiple lists into dataframe

I think you're almost there, try removing the extra square brackets around the lst's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):

import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
percentile_list = pd.DataFrame(
    {'lst1Title': lst1,
     'lst2Title': lst2,
     'lst3Title': lst3
    })

percentile_list
    lst1Title  lst2Title  lst3Title
0          0         0         0
1          1         1         1
2          2         2         2
3          3         3         3
4          4         4         4
5          5         5         5
6          6         6         6
...

If you need a more performant solution you can use np.column_stack rather than zip as in your first attempt, this has around a 2x speedup on the example here, however comes at bit of a cost of readability in my opinion:

import numpy as np
percentile_list = pd.DataFrame(np.column_stack([lst1, lst2, lst3]), 
                               columns=['lst1Title', 'lst2Title', 'lst3Title'])

Return multiple fields as a record in PostgreSQL with PL/pgSQL

you can do this using OUT parameter and CROSS JOIN

CREATE OR REPLACE FUNCTION get_object_fields(my_name text, OUT f1 text, OUT f2 text)
AS $$
SELECT t1.name, t2.name
FROM  table1 t1 
CROSS JOIN table2 t2 
WHERE t1.name = my_name AND t2.name = my_name;
$$ LANGUAGE SQL;

then use it as a table:

select get_object_fields( 'Pending') ;
get_object_fields
-------------------
(Pending,code)
(1 row)

or

select * from get_object_fields( 'Pending');
f1    |   f
---------+---------
Pending | code
(1 row)

or

select (get_object_fields( 'Pending')).f1;
f1
---------
Pending
(1 row)

Access event to call preventdefault from custom function originating from onclick attribute of tag

The simplest solution simply is:

<a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>

It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)

<a onclick="
if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' + 
Math.round(new Date().getTime() / 1000);" 
href="http://www.domain.com/docs/thingy.pdf">

If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.

Most Pythonic way to provide global configuration variables in config.py?

please check out the IPython configuration system, implemented via traitlets for the type enforcement you are doing manually.

Cut and pasted here to comply with SO guidelines for not just dropping links as the content of links changes over time.

traitlets documentation

Here are the main requirements we wanted our configuration system to have:

Support for hierarchical configuration information.

Full integration with command line option parsers. Often, you want to read a configuration file, but then override some of the values with command line options. Our configuration system automates this process and allows each command line option to be linked to a particular attribute in the configuration hierarchy that it will override.

Configuration files that are themselves valid Python code. This accomplishes many things. First, it becomes possible to put logic in your configuration files that sets attributes based on your operating system, network setup, Python version, etc. Second, Python has a super simple syntax for accessing hierarchical data structures, namely regular attribute access (Foo.Bar.Bam.name). Third, using Python makes it easy for users to import configuration attributes from one configuration file to another. Fourth, even though Python is dynamically typed, it does have types that can be checked at runtime. Thus, a 1 in a config file is the integer ‘1’, while a '1' is a string.

A fully automated method for getting the configuration information to the classes that need it at runtime. Writing code that walks a configuration hierarchy to extract a particular attribute is painful. When you have complex configuration information with hundreds of attributes, this makes you want to cry.

Type checking and validation that doesn’t require the entire configuration hierarchy to be specified statically before runtime. Python is a very dynamic language and you don’t always know everything that needs to be configured when a program starts.

To acheive this they basically define 3 object classes and their relations to each other:

1) Configuration - basically a ChainMap / basic dict with some enhancements for merging.

2) Configurable - base class to subclass all things you'd wish to configure.

3) Application - object that is instantiated to perform a specific application function, or your main application for single purpose software.

In their words:

Application: Application

An application is a process that does a specific job. The most obvious application is the ipython command line program. Each application reads one or more configuration files and a single set of command line options and then produces a master configuration object for the application. This configuration object is then passed to the configurable objects that the application creates. These configurable objects implement the actual logic of the application and know how to configure themselves given the configuration object.

Applications always have a log attribute that is a configured Logger. This allows centralized logging configuration per-application. Configurable: Configurable

A configurable is a regular Python class that serves as a base class for all main classes in an application. The Configurable base class is lightweight and only does one things.

This Configurable is a subclass of HasTraits that knows how to configure itself. Class level traits with the metadata config=True become values that can be configured from the command line and configuration files.

Developers create Configurable subclasses that implement all of the logic in the application. Each of these subclasses has its own configuration information that controls how instances are created.

How to add an extra row to a pandas dataframe

Try this:

df.loc[len(df)]=['8/19/2014','Jun','Fly','98765'] 

Warning: this method works only if there are no "holes" in the index. For example, suppose you have a dataframe with three rows, with indices 0, 1, and 3 (for example, because you deleted row number 2). Then, len(df) = 3, so by the above command does not add a new row - it overrides row number 3.

Can't build create-react-app project with custom PUBLIC_URL

If the other answers aren't working for you, there's also a homepage field in package.json. After running npm run build you should get a message like the following:

The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:

  "homepage" : "http://myname.github.io/myapp",

You would just add it as one of the root fields in package.json, e.g.

{
  // ...
  "scripts": {
    // ...
  },
  "homepage": "https://example.com"
}

When it's successfully set, either via homepage or PUBLIC_URL, you should instead get a message like this:

The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.

Change icon-bar (?) color in bootstrap

I do not know if your still looking for the answer to this problem but today I happened the same problem and solved it. You need to specify in the HTML code,

**<Div class = "navbar"**>
         div class = "container">
               <Div class = "navbar-header">

or

**<Div class = "navbar navbar-default">**
        div class = "container">
               <Div class = "navbar-header">

You got that place in your CSS

.navbar-default-toggle .navbar .icon-bar {
  background-color: # 0000ff;
}

and what I did was add above

.navbar .navbar-toggle .icon-bar {
  background-color: # ff0000;
}

Because my html code is

**<Div class = "navbar">**
         div class = "container">
               <Div class = "navbar-header">

and if you associate a file less / css

search this section and also here placed the color you want to change, otherwise it will self-correct the css file to the state it was before

// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-default-toggle-icon-bar-bg: # 888;**
@ Navbar-default-toggle-border-color: #ddd;

if your html code is like mine and is not navbar-default, add it as you did with the css.

// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-toggle-icon-bar-bg : #888;**
@ Navbar-default-toggle-icon-bar-bg: # 888;
@ Navbar-default-toggle-border-color: #ddd;

good luck

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

How to export dataGridView data Instantly to Excel on button click?

This is a great question and I was surprised at how difficult it was to find a clear and complete answer, most of the answers I found were either sudo-code or not 100% complete.

I was able to create a complete solution to copy and save the data from my DataGridView to an excel file based on Jake's answer so I'm posting my complete solution in the hopes that it can help other new comers to c# like myself :)

First off, you will need the Microsoft.Office.Interop.Excel reference in your project. See MSDN on how to add it.

My Code:

using Excel = Microsoft.Office.Interop.Excel;

private void btnExportToExcel_Click(object sender, EventArgs e)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Excel Documents (*.xls)|*.xls";
    sfd.FileName = "Inventory_Adjustment_Export.xls";
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        // Copy DataGridView results to clipboard
        copyAlltoClipboard();

        object misValue = System.Reflection.Missing.Value;
        Excel.Application xlexcel = new Excel.Application();

        xlexcel.DisplayAlerts = false; // Without this you will get two confirm overwrite prompts
        Excel.Workbook xlWorkBook = xlexcel.Workbooks.Add(misValue);
        Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        // Format column D as text before pasting results, this was required for my data
        Excel.Range rng = xlWorkSheet.get_Range("D:D").Cells;
        rng.NumberFormat = "@";

        // Paste clipboard results to worksheet range
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);

        // For some reason column A is always blank in the worksheet. ¯\_(?)_/¯
        // Delete blank column A and select cell A1
        Excel.Range delRng = xlWorkSheet.get_Range("A:A").Cells;
        delRng.Delete(Type.Missing);
        xlWorkSheet.get_Range("A1").Select();

        // Save the excel file under the captured location from the SaveFileDialog
        xlWorkBook.SaveAs(sfd.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlexcel.DisplayAlerts = true;
        xlWorkBook.Close(true, misValue, misValue);
        xlexcel.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlexcel);

        // Clear Clipboard and DataGridView selection
        Clipboard.Clear();
        dgvItems.ClearSelection();

        // Open the newly saved excel file
        if (File.Exists(sfd.FileName))
            System.Diagnostics.Process.Start(sfd.FileName);
    }
}

private void copyAlltoClipboard()
{
    dgvItems.SelectAll();
    DataObject dataObj = dgvItems.GetClipboardContent();
    if (dataObj != null)
        Clipboard.SetDataObject(dataObj);
}

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        MessageBox.Show("Exception Occurred while releasing object " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}

How to compile and run C/C++ in a Unix console/Mac terminal?

Add following to get best warnings, you will not regret it. If you can, compile WISE (warning is error)

- Wall -pedantic -Weffc++ -Werror

Javascript date.getYear() returns 111 in 2011?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear

getYear is no longer used and has been replaced by the getFullYear method.

The getYear method returns the year minus 1900; thus:

  • For years greater than or equal to 2000, the value returned by getYear is 100 or greater. For example, if the year is 2026, getYear returns 126.
  • For years between and including 1900 and 1999, the value returned by getYear is between 0 and 99. For example, if the year is 1976, getYear returns 76.
  • For years less than 1900, the value returned by getYear is less than 0. For example, if the year is 1800, getYear returns -100.
  • To take into account years before and after 2000, you should use getFullYear instead of getYear so that the year is specified in full.

Building a complete online payment gateway like Paypal

What you're talking about is becoming a payment service provider. I have been there and done that. It was a lot easier about 10 years ago than it is now, but if you have a phenomenal amount of time, money and patience available, it is still possible.

You will need to contact an acquiring bank. You didnt say what region of the world you are in, but by this I dont mean a local bank branch. Each major bank will generally have a separate card acquiring arm. So here in the UK we have (eg) Natwest bank, which uses Streamline (or Worldpay) as its acquiring arm. In total even though we have scores of major banks, they all end up using one of five or so card acquirers.

Happily, all UK card acquirers use a standard protocol for communication of authorisation requests, and end of day settlement. You will find minor quirks where some acquiring banks support some features and have slightly different syntax, but the differences are fairly minor. The UK standards are published by the Association for Payment Clearing Services (APACS) (which is now known as the UKPA). The standards are still commonly referred to as APACS 30 (authorization) and APACS 29 (settlement), but are now formally known as APACS 70 (books 1 through 7).

Although the APACS standard is widely supported across the UK (Amex and Discover accept messages in this format too) it is not used in other countries - each country has it's own - for example: Carte Bancaire in France, CartaSi in Italy, Sistema 4B in Spain, Dankort in Denmark etc. An effort is under way to unify the protocols across Europe - see EPAS.org

Communicating with the acquiring bank can be done a number of ways. Again though, it will depend on your region. In the UK (and most of Europe) we have one communications gateway that provides connectivity to all the major acquirers, they are called TNS and there are dozens of ways of communicating through them to the acquiring bank, from dialup 9600 baud modems, ISDN, HTTPS, VPN or dedicated line. Ultimately the authorisation request will be converted to X25 protocol, which is the protocol used by these acquiring banks when communicating with each other.

In summary then: it all depends on your region.

  • Contact a major bank and try to get through to their card acquiring arm.
  • Explain that you're setting up as a payment service provider, and request details on comms format for authorization requests and end of day settlement files
  • Set up a test merchant account and develop auth/settlement software and go through the accreditation process. Most acquirers help you through this process for free, but when you want to register as an accredited PSP some will request a fee.
  • you will need to comply with some regulations too, for example you may need to register as a payment institution

Once you are registered and accredited you'll then be able to accept customers and set up merchant accounts on behalf of the bank/s you're accredited against (bearing in mind that each acquirer will generally support multiple banks). Rinse and repeat with other acquirers as you see necessary.

Beyond that you have lots of other issues, mainly dealing with PCI-DSS. Thats a whole other topic and there are already some q&a's on this site regarding that. Like I say, its a phenomenal undertaking - most likely a multi-year project even for a reasonably sized team, but its certainly possible.

Rails: update_attribute vs update_attributes

Tip: update_attribute is being deprecated in Rails 4 via Commit a7f4b0a1. It removes update_attribute in favor of update_column.

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

How to write and save html file in python?

As others have mentioned, use triple quotes ”””abc””” for multiline strings. Also, you can do this without having to call close() using the with keyword. For example:

# HTML String
html = """
<table border=1>
     <tr>
       <th>Number</th>
       <th>Square</th>
     </tr>
     <indent>
     <% for i in range(10): %>
       <tr>
         <td><%= i %></td>
         <td><%= i**2 %></td>
       </tr>
     </indent>
</table>
"""

# Write HTML String to file.html
with open("file.html", "w") as file:
    file.write(html)

See https://stackoverflow.com/a/11783672/2206251 for more details on the with keyword in Python.

How to recursively find and list the latest modified files in a directory with subdirectories and times

For those, who faced

stat: unrecognized option: format

when executed the line from Heppo's answer (find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head)

Please try the -c key to replace --format and finally the call will be:

find $1 -type f -exec stat -c '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head

That worked for me inside of some Docker containers, where stat was not able to use --format option.

How to force NSLocalizedString to use a specific language

Do not use on iOS 9. This returns nil for all strings passed through it.

I have found another solution that allows you to update the language strings, w/o restarting the app and compatible with genstrings:

Put this macro in the Prefix.pch:

#define currentLanguageBundle [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:[[NSLocale preferredLanguages] objectAtIndex:0] ofType:@"lproj"]]

and where ever you need a localized string use:

NSLocalizedStringFromTableInBundle(@"GalleryTitleKey", nil, currentLanguageBundle, @"")

To set the language use:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"de"] forKey:@"AppleLanguages"];

Works even with consecutive language hopping like:

NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"fr"] forKey:@"AppleLanguages"];
NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"it"] forKey:@"AppleLanguages"];
NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:@"de"] forKey:@"AppleLanguages"];
NSLog(@"test %@", NSLocalizedStringFromTableInBundle(@"NewKey", nil, currentLanguageBundle, @""));

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

Android checkbox style

Perhaps you want something like:

<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
    <item name="android:checkboxStyle">@style/customCheckBoxStyle</item>
</style>

<style name="customCheckBoxStyle" parent="@android:style/Widget.CompoundButton.CheckBox">
    <item name="android:textColor">@android:color/black</item>
</style>

Note, the textColor item.

EC2 Instance Cloning

The easier way is through the web management console:

  1. go to the instance
  2. select the instance and click on instance action
  3. create image

Once you have an image you can launch another cloned instance, data and all. :)

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 update one file in a zip archive

Use the update flag: -u

Example:

zip -ur existing.zip myFolder

This command will compress and add myFolder (and it's contents) to the existing.zip.


Advanced Usage:

The update flag actually compares the incoming files against the existing ones and will either add new files, or update existing ones.

Therefore, if you want to add/update a specific subdirectory within the zip file, just update the source as desired, and then re-zip the entire source with the -u flag. Only the changed files will be zipped.

If you don't have access to the source files, you can unzip the zip file, then update the desired files, and then re-zip with the -u flag. Again, only the changed files will be zipped.

Example:

Original Source Structure


ParentDir
+-- file1.txt
+-- file2.txt
+-- ChildDir
¦   +-- file3.txt
¦   +-- Logs
¦   ¦   +-- logs1.txt
¦   ¦   +-- logs2.txt
¦   ¦   +-- logs3.txt

Updated Source Structure


ParentDir
+-- file1.txt
+-- file2.txt
+-- ChildDir
¦   +-- file3.txt
¦   +-- Logs
¦   ¦   +-- logs1.txt
¦   ¦   +-- logs2.txt
¦   ¦   +-- logs3.txt 
¦   ¦   +-- logs4.txt <-- NEW FILE 

Usage

$ zip -ur existing.zip ParentDir 
> updating: ParentDir/ChildDir/Logs (stored 0%)
>   adding: ParentDir/ChildDir/Logs/logs4.txt (stored 96%)

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

Just in case you do this for a lot of functions in your class:

class Foo {
public:
  virtual void f1() {
    // ...
  }
  virtual void f2() {
    // ...
  }
  //...
};

class Bar : public Foo {
private:
  typedef Foo super;
public:
  void f1() {
    super::f1();
  }
};

This might save a bit of writing if you want to rename Foo.

Where to put the gradle.properties file

Gradle looks for gradle.properties files in these places:

  • in project build dir (that is where your build script is)
  • in sub-project dir
  • in gradle user home (defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle)

Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).

Reference: https://gradle.org/docs/current/userguide/build_environment.html

Array String Declaration

Declare the array size will solve your problem

 String[] title = {
            "Abundance",
            "Anxiety",
            "Bruxism",
            "Discipline",
            "Drug Addiction"
        };
    String urlbase = "http://www.somewhere.com/data/";
    String imgSel = "/logo.png";
    String[] mStrings = new String[title.length];

    for(int i=0;i<title.length;i++) {
        mStrings[i] = urlbase + title[i].toLowerCase() + imgSel;

        System.out.println(mStrings[i]);
    }

Create a List that contain each Line of a File

f.readlines() returns a list that contains each line as an item in the list

if you want eachline to be split(",") you can use list comprehensions

[ list.split(",") for line in file ]

How to enable CORS in flask

My solution is a wrapper around app.route:

def corsapp_route(path, origin=('127.0.0.1',), **options):
    """
    Flask app alias with cors
    :return:
    """

    def inner(func):
        def wrapper(*args, **kwargs):
            if request.method == 'OPTIONS':
                response = make_response()
                response.headers.add("Access-Control-Allow-Origin", ', '.join(origin))
                response.headers.add('Access-Control-Allow-Headers', ', '.join(origin))
                response.headers.add('Access-Control-Allow-Methods', ', '.join(origin))
                return response
            else:
                result = func(*args, **kwargs)
            if 'Access-Control-Allow-Origin' not in result.headers:
                result.headers.add("Access-Control-Allow-Origin", ', '.join(origin))
            return result

        wrapper.__name__ = func.__name__

        if 'methods' in options:
            if 'OPTIONS' in options['methods']:
                return app.route(path, **options)(wrapper)
            else:
                options['methods'].append('OPTIONS')
                return app.route(path, **options)(wrapper)

        return wrapper

    return inner

@corsapp_route('/', methods=['POST'], origin=['*'])
def hello_world():
    ...

How to change font size in Eclipse for Java text editors?

You can have a look at Eclipse color theme, also which has a hell of a lot of options for customizing font, background color, etc.

Codeigniter's `where` and `or_where`

You can use : Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow you to create queries with complex WHERE clauses. Nested groups are supported. Example:

$this->db->select('*')->from('my_table')
        ->group_start()
                ->where('a', 'a')
                ->or_group_start()
                        ->where('b', 'b')
                        ->where('c', 'c')
                ->group_end()
        ->group_end()
        ->where('d', 'd')
->get();

https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping

javascript date to string

I like Daniel Cerecedo's answer using toJSON() and regex. An even simpler form would be:

var now = new Date();
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
var token_array = regex.exec(now.toJSON());
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
var myFormat = token_array.slice(1).join('');
// "20171031022445"

How to work with complex numbers in C?

This code will help you, and it's fairly self-explanatory:

#include <stdio.h>      /* Standard Library of Input and Output */
#include <complex.h>    /* Standard Library of Complex Numbers */

int main() {

    double complex z1 = 1.0 + 3.0 * I;
    double complex z2 = 1.0 - 4.0 * I;

    printf("Working with complex numbers:\n\v");

    printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));

    double complex sum = z1 + z2;
    printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));

    double complex difference = z1 - z2;
    printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));

    double complex product = z1 * z2;
    printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));

    double complex quotient = z1 / z2;
    printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));

    double complex conjugate = conj(z1);
    printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));

    return 0;
}

  with:

creal(z1): get the real part (for float crealf(z1), for long double creall(z1))

cimag(z1): get the imaginary part (for float cimagf(z1), for long double cimagl(z1))

Another important point to remember when working with complex numbers is that functions like cos(), exp() and sqrt() must be replaced with their complex forms, e.g. ccos(), cexp(), csqrt().

Remove elements from collection while iterating

Are there any reasons to prefer one approach over the other

The first approach will work, but has the obvious overhead of copying the list.

The second approach will not work because many containers don't permit modification during iteration. This includes ArrayList.

If the only modification is to remove the current element, you can make the second approach work by using itr.remove() (that is, use the iterator's remove() method, not the container's). This would be my preferred method for iterators that support remove().

Site does not exist error for a2ensite

I realise that's not the case here but it might help someone.

Double-check you didn't create the conf file in /etc/apache2/sites-enabled by mistake. You get the same error.

Android: remove notification from notification bar

Use the NotificationManager to cancel your notification. You only need to provide your notification id

mNotificationManager.cancel(YOUR_NOTIFICATION_ID);

also check this link See Developer Link

How to check if a value is not null and not empty string in JS

Both null and empty could be validated as follows:

<script>
function getName(){
    var myname = document.getElementById("Name").value;
    if(myname != '' && myname != null){
        alert("My name is "+myname);
    }else{
        alert("Please Enter Your Name");
    }       
}

Check if a number is odd or even in python

It shouldn't matter if the word has an even or odd amount fo letters:

def is_palindrome(word):
    if word == word[::-1]:
        return True
    else:
        return False

setting system property

System.setProperty("gate.home", "/some/directory");

For more information, see:

How to make Bitmap compress without change the bitmap size?

If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.

Quality Accepts 0 - 100

0 = MAX Compression (Least Quality which is suitable for Small images)

100 = Least Compression (MAX Quality which is suitable for Big images)

How do I validate a date in this format (yyyy-mm-dd) using jquery?

Working Demo fiddle here Demo

Changed your validation function to this

function isDate(txtDate)
{
return txtDate.match(/^d\d?\/\d\d?\/\d\d\d\d$/);
}

Kill process by name?

import os, signal

def check_kill_process(pstring):
    for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
        fields = line.split()
        pid = fields[0]
        os.kill(int(pid), signal.SIGKILL)

LEFT JOIN in LINQ to entities?

You can read an article i have written for joins in LINQ here

var query = 
from  u in Repo.T_Benutzer
join bg in Repo.T_Benutzer_Benutzergruppen
    on u.BE_ID equals bg.BEBG_BE
into temp
from j in temp.DefaultIfEmpty()
select new
{
    BE_User = u.BE_User,
    BEBG_BG = (int?)j.BEBG_BG// == null ? -1 : j.BEBG_BG
            //, bg.Name 
}

The following is the equivalent using extension methods:

var query = 
Repo.T_Benutzer
.GroupJoin
(
    Repo.T_Benutzer_Benutzergruppen,
    x=>x.BE_ID,
    x=>x.BEBG_BE,
    (o,i)=>new {o,i}
)
.SelectMany
(
    x => x.i.DefaultIfEmpty(),
    (o,i) => new
    {
        BE_User = o.o.BE_User,
        BEBG_BG = (int?)i.BEBG_BG
    }
);

How do I create an Android Spinner as a popup?

You can use a spinner and set the spinnerMode to dialog, and set the layout_width and layout_height to 0, so that the main view does not show, only the dialog (dropdown view). Call performClick in the button click listener.

    mButtonAdd.setOnClickListener(view -> {
        spinnerAddToList.performClick();
    });

Layout:

    <Spinner
        android:id="@+id/spinnerAddToList"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="10dp"
        android:prompt="@string/select_from_list"
        android:theme="@style/ThemeOverlay.AppCompat.Light"
        android:spinnerMode="dialog"/>

The advantage of this is you can customize your spinner any way you want.

See my answer here to customize spinner: Overriding dropdown list style for Spinner in Dialog mode

How to create and write to a txt file using VBA

Open ThisWorkbook.Path & "\template.txt" For Output As #1
Print #1, strContent
Close #1

More Information:

adding onclick event to dynamically added button?

I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:

//Bad code.
var btn = document.createElement('button');
btn.onClick = function() {  console.log("hey");  }

to this:

//Working Code.  I don't like it, but it works. 
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);

document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){  console.log("hey");  }

I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.

How to get UTC value for SYSDATE on Oracle

You can use

SELECT SYS_EXTRACT_UTC(TIMESTAMP '2000-03-28 11:30:00.00 -02:00') FROM DUAL;

You may also need to change your timezone

ALTER SESSION SET TIME_ZONE = 'Europe/Berlin';

Or read it

SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM dual;

How to check the value given is a positive or negative integer?

You should first check if the input value is interger with isNumeric() function. Then add the condition or greater than 0. This is the jQuery code for it.

function isPositiveInteger(n) {
        return ($.isNumeric(n) && (n > 0));
}

Use CSS3 transitions with gradient backgrounds

For what it's worth, here's a Sass mixin:

Usage:

@include gradientAnimation(red, blue, .6s);

Mixin:

@mixin gradientAnimation( $start, $end, $transTime ){
    background-size: 100%;
    background-image: linear-gradient($start, $end);
    position: relative;
    z-index: 100;
    &:before {
        background-image: linear-gradient($end, $start);
        content: "";
        display: block;
        height: 100%;
        position: absolute;
        top: 0; left: 0;
        opacity: 0;
        width: 100%;
        z-index: -100;
        transition: opacity $transTime;
    }
    &:hover {
        &:before {
            opacity: 1;
        }
    }
}

Taken from this awesome post on Medium from Dave Lunny: https://medium.com/@dave_lunny/animating-css-gradients-using-only-css-d2fd7671e759

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Maybe check Hibernate Validator 4.0, the Reference Implementation of the JSR 303: Bean Validation.

This is an example of an annotated class:

public class Address {

    @NotNull 
    private String line1;
    private String line2;
    private String zip;
    private String state;

    @Length(max = 20)
    @NotNull
    private String country;

    @Range(min = -2, max = 50, message = "Floor out of range")
    public int floor;

        ...
}

For an introduction, see Getting started with JSR 303 (Bean Validation) – part 1 and part 2 or the "Getting started" section of the reference guide which is part of the Hibernate Validator distribution.

How to view AndroidManifest.xml from APK file?

To decode the AndroidManifest.xml file using axmldec:

axmldec -o output.xml AndroidManifest.xml

or

axmldec -o output.xml AndroidApp.apk

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

If you are dealing with a table and one of the dates happens to be null, you can code it like this:

  @{
     if (Model.SomeCollection[i].date_due == null)
       {
         <td><input type='date' id="@("dd" + i)" name="dd" /></td>
       }
       else
       {
         <td><input type='date' value="@Model.SomeCollection[i].date_due.Value.ToString("yyyy-MM-dd")" id="@("dd" + i)" name="dd" /></td>
       }
   }

Callback to a Fragment from a DialogFragment

I followed this simple steps to do this stuff.

  1. Create interface like DialogFragmentCallbackInterface with some method like callBackMethod(Object data). Which you would calling to pass data.
  2. Now you can implement DialogFragmentCallbackInterface interface in your fragment like MyFragment implements DialogFragmentCallbackInterface
  3. At time of DialogFragment creation set your invoking fragment MyFragment as target fragment who created DialogFragment use myDialogFragment.setTargetFragment(this, 0) check setTargetFragment (Fragment fragment, int requestCode)

    MyDialogFragment dialogFrag = new MyDialogFragment();
    dialogFrag.setTargetFragment(this, 1); 
    
  4. Get your target fragment object into your DialogFragment by calling getTargetFragment() and cast it to DialogFragmentCallbackInterface.Now you can use this interface to send data to your fragment.

    DialogFragmentCallbackInterface callback = 
               (DialogFragmentCallbackInterface) getTargetFragment();
    callback.callBackMethod(Object data);
    

    That's it all done! just make sure you have implemented this interface in your fragment.

How to convert a string to lower case in Bash?

In spite of how old this question is and similar to this answer by technosaurus. I had a hard time finding a solution that was portable across most platforms (That I Use) as well as older versions of bash. I have also been frustrated with arrays, functions and use of prints, echos and temporary files to retrieve trivial variables. This works very well for me so far I thought I would share. My main testing environments are:

  1. GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
  2. GNU bash, version 3.2.57(1)-release (sparc-sun-solaris2.10)
lcs="abcdefghijklmnopqrstuvwxyz"
ucs="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
input="Change Me To All Capitals"
for (( i=0; i<"${#input}"; i++ )) ; do :
    for (( j=0; j<"${#lcs}"; j++ )) ; do :
        if [[ "${input:$i:1}" == "${lcs:$j:1}" ]] ; then
            input="${input/${input:$i:1}/${ucs:$j:1}}" 
        fi
    done
done

Simple C-style for loop to iterate through the strings. For the line below if you have not seen anything like this before this is where I learned this. In this case the line checks if the char ${input:$i:1} (lower case) exists in input and if so replaces it with the given char ${ucs:$j:1} (upper case) and stores it back into input.

input="${input/${input:$i:1}/${ucs:$j:1}}"

Difference Between ViewResult() and ActionResult()

To save you some time here is the answer from a link in a previous answer at https://forums.asp.net/t/1448398.aspx

ActionResult is an abstract class, and it's base class for ViewResult class.

In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it.

And ViewResult is an implementation for this abstract class. It will try to find a view page (usually aspx page) in some predefined paths(/views/controllername/, /views/shared/, etc) by the given view name.

It's usually a good practice to have your method return a more specific class. So if you are sure that your action method will return some view page, you can use ViewResult. But if your action method may have different behavior, like either render a view or perform a redirection. You can use the more general base class ActionResult as the return type.

A function to convert null to string

You can just use the null coalesce operator.

string result = value ?? "";

How to add Certificate Authority file in CentOS 7

Complete instruction is as follow:

  1. Extract Private Key from PFX

openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes

  1. Extract Certificate from PFX

openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem

  1. install certificate

yum install -y ca-certificates,

cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem ,

update-ca-trust ,

update-ca-trust force-enable

Hope to be useful

How to SUM two fields within an SQL query

SUM is an aggregate function. It will calculate the total for each group. + is used for calculating two or more columns in a row.

Consider this example,

ID  VALUE1  VALUE2
===================
1   1       2
1   2       2
2   3       4
2   4       5

 

SELECT  ID, SUM(VALUE1), SUM(VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1), SUM(VALUE2)
1   3           4
2   7           9

 

SELECT  ID, VALUE1 + VALUE2
FROM    TableName

will result

ID, VALUE1 + VALUE2
1   3
1   4
2   7
2   9

 

SELECT  ID, SUM(VALUE1 + VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1 + VALUE2)
1   7
2   16

How to create helper file full of functions in react native?

If you want to use class, you can do this.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x

Django: TemplateSyntaxError: Could not parse the remainder

also happens when you use jinja templates (which have different syntax for calling object methods) and you forget to set it in settings.py

Write Array to Excel Range

This is an excerpt from method of mine, which converts a DataTable (the dt variable) into an array and then writes the array into a Range on a worksheet (wsh var). You can also change the topRow variable to whatever row you want the array of strings to be placed at.

object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; r++)
{
    DataRow dr = dt.Rows[r];
    for (int c = 0; c < dt.Columns.Count; c++)
    {
        arr[r, c] = dr[c];
    }
}
Excel.Range c1 = (Excel.Range)wsh.Cells[topRow, 1];
Excel.Range c2 = (Excel.Range)wsh.Cells[topRow + dt.Rows.Count - 1, dt.Columns.Count];
Excel.Range range = wsh.get_Range(c1, c2);
range.Value = arr;

Of course you do not need to use an intermediate DataTable like I did, the code excerpt is just to demonstrate how an array can be written to worksheet in single call.

SqlDataAdapter vs SqlDataReader

A SqlDataAdapter is typically used to fill a DataSet or DataTable and so you will have access to the data after your connection has been closed (disconnected access).

The SqlDataReader is a fast forward-only and connected cursor which tends to be generally quicker than filling a DataSet/DataTable.

Furthermore, with a SqlDataReader, you deal with your data one record at a time, and don't hold any data in memory. Obviously with a DataTable or DataSet, you do have a memory allocation overhead.

If you don't need to keep your data in memory, so for rendering stuff only, go for the SqlDataReader. If you want to deal with your data in a disconnected fashion choose the DataAdapter to fill either a DataSet or DataTable.

UITableViewCell Selected Background Color on Multiple Selection

Swift 4

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{
    let selectedCell = tableView.cellForRow(at: indexPath)! as! LeftMenuCell
    selectedCell.contentView.backgroundColor = UIColor.blue
}

If you want to unselect the previous cell, also you can use the different logic for this

var tempcheck = 9999
var lastrow = IndexPath()
var lastcolor = UIColor()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if tempcheck == 9999
    {
        tempcheck = 0
        let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
        lastcolor = selectedCell.contentView.backgroundColor!
        selectedCell.contentView.backgroundColor = UIColor.blue
        lastrow = indexPath
    }
    else
    {
        let selectedCelllasttime = tableView.cellForRow(at: lastrow)! as! HealthTipsCell
        selectedCelllasttime.contentView.backgroundColor = lastcolor
        let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
        lastcolor = selectedCell.contentView.backgroundColor!
        selectedCell.contentView.backgroundColor = UIColor.blue
        lastrow = indexPath
    }
}

HTML code for INR

Use this for Indian rupee sign:

&#2352; — र

Simple way to find if two different lists contain exactly the same elements?

The equals method on List will do this, Lists are ordered, so to be equal two Lists must have the same elements in the same order.

return list1.equals(list2);

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I solved this by referring properties of login user under the security, logins. then go to User Mapping and select the database then check db_datareader and db_dataweriter options.

How to properly use the "choices" field option in Django

You can't have bare words in the code, that's the reason why they created variables (your code will fail with NameError).

The code you provided would create a database table named month (plus whatever prefix django adds to that), because that's the name of the CharField.

But there are better ways to create the particular choices you want. See a previous Stack Overflow question.

import calendar
tuple((m, m) for m in calendar.month_name[1:])

Different ways of loading a file as an InputStream

It Works , try out this :

InputStream in_s1 =   TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");

Get index of a key in json

In principle, it is wrong to look for an index of a key. Keys of a hash map are unordered, you should never expect specific order.

Multiple lines of text in UILabel

The best solution I have found (to an otherwise frustrating problem that should have been solved in the framework) is similar to vaychick's.

Just set number of lines to 0 in either IB or code

myLabel.numberOfLines = 0;

This will display the lines needed but will reposition the label so its centered horizontally (so that a 1 line and 3 line label are aligned in their horizontal position). To fix that add:

CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode]; 
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;

Binding arrow keys in JS/jQuery

This is a bit late, but HotKeys has a very major bug which causes events to get executed multiple times if you attach more than one hotkey to an element. Just use plain jQuery.

$(element).keydown(function(ev) {
    if(ev.which == $.ui.keyCode.DOWN) {
        // your code
        ev.preventDefault();
    }
});

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

If you are using the Chrome Driver you can set the capabilities

    var capabilities = new DesiredCapabilities();

    var switches = new List<string>
                       {
                           "--start-maximized"
                       };

    capabilities.SetCapability("chrome.switches", switches);

    new ChromeDriver(chromedriver_path, capabilities);

ArrayList of String Arrays

Use a second ArrayList for the 3 strings, not a primitive array. Ie.
private List<List<String>> addresses = new ArrayList<List<String>>();

Then you can have:

ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");

addresses.add(singleAddress);

(I think some strange things can happen with type erasure here, but I don't think it should matter here)

If you're dead set on using a primitive array, only a minor change is required to get your example to work. As explained in other answers, the size of the array can not be included in the declaration. So changing:

private ArrayList<String[]> addresses = new ArrayList<String[3]>();

to

private ArrayList<String[]> addresses = new ArrayList<String[]>();

will work.

Using setImageDrawable dynamically to set image in an ImageView

As simple as this answer:

Drawable myDrawable = getResources().getDrawable(R.drawable.pic);
imageview.setImageDrawable(myDrawable);

Try-Catch-End Try in VBScript doesn't seem to work

Try Catch exists via workaround in VBScript:

http://web.archive.org/web/20140221063207/http://my.opera.com/Lee_Harvey/blog/2007/04/21/try-catch-finally-in-vbscript-sure

Class CFunc1
    Private Sub Class_Initialize
        WScript.Echo "Starting"
        Dim i : i = 65535 ^ 65535 
        MsgBox "Should not see this"
    End Sub

    Private Sub CatchErr
        If Err.Number = 0 Then Exit Sub
        Select Case Err.Number
            Case 6 WScript.Echo "Overflow handled!" 
            Case Else WScript.Echo "Unhandled error " & Err.Number & " occurred."
        End Select
        Err.Clear
    End Sub

    Private Sub Class_Terminate
        CatchErr
        WScript.Echo "Exiting" 
    End Sub 
End Class

Dim Func1 : Set Func1 = New CFunc1 : Set Func1 = Nothing

MySQL "Or" Condition

try this

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

my be like this

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

SQLite DateTime comparison

You could also write up your own user functions to handle dates in the format you choose. SQLite has a fairly simple method for writing your own user functions. For example, I wrote a few to add time durations together.

Flutter: Run method on Widget build complete

You could use

https://github.com/slightfoot/flutter_after_layout

which executes a function only one time after the layout is completed. Or just look at its implementation and add it to your code :-)

Which is basically

  void initState() {
    super.initState();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => yourFunction(context));
  }

How to make layout with rounded corners..?

I think a better way to do it is to merge 2 things:

  1. make a bitmap of the layout, as shown here.

  2. make a rounded drawable from the bitmap, as shown here

  3. set the drawable on an imageView.

This will handle cases that other solutions have failed to solve, such as having content that has corners.

I think it's also a bit more GPU-friendly, as it shows a single layer instead of 2 .

The only better way is to make a totally customized view, but that's a lot of code and might take a lot of time. I think that what I suggested here is the best of both worlds.

Here's a snippet of how it can be done:

RoundedCornersDrawable.java

/**
 * shows a bitmap as if it had rounded corners. based on :
 * http://rahulswackyworld.blogspot.co.il/2013/04/android-drawables-with-rounded_7.html
 * easy alternative from support library: RoundedBitmapDrawableFactory.create( ...) ; 
 */
public class RoundedCornersDrawable extends BitmapDrawable {

    private final BitmapShader bitmapShader;
    private final Paint p;
    private final RectF rect;
    private final float borderRadius;

    public RoundedCornersDrawable(final Resources resources, final Bitmap bitmap, final float borderRadius) {
        super(resources, bitmap);
        bitmapShader = new BitmapShader(getBitmap(), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        final Bitmap b = getBitmap();
        p = getPaint();
        p.setAntiAlias(true);
        p.setShader(bitmapShader);
        final int w = b.getWidth(), h = b.getHeight();
        rect = new RectF(0, 0, w, h);
        this.borderRadius = borderRadius < 0 ? 0.15f * Math.min(w, h) : borderRadius;
    }

    @Override
    public void draw(final Canvas canvas) {
        canvas.drawRoundRect(rect, borderRadius, borderRadius, p);
    }
}

CustomView.java

public class CustomView extends ImageView {
    private View mMainContainer;
    private boolean mIsDirty=false;

    // TODO for each change of views/content, set mIsDirty to true and call invalidate

    @Override
    protected void onDraw(final Canvas canvas) {
        if (mIsDirty) {
            mIsDirty = false;
            drawContent();
            return;
        }
        super.onDraw(canvas);
    }

    /**
     * draws the view's content to a bitmap. code based on :
     * http://nadavfima.com/android-snippet-inflate-a-layout-draw-to-a-bitmap/
     */
    public static Bitmap drawToBitmap(final View viewToDrawFrom, final int width, final int height) {
        // Create a new bitmap and a new canvas using that bitmap
        final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bmp);
        viewToDrawFrom.setDrawingCacheEnabled(true);
        // Supply measurements
        viewToDrawFrom.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));
        // Apply the measures so the layout would resize before drawing.
        viewToDrawFrom.layout(0, 0, viewToDrawFrom.getMeasuredWidth(), viewToDrawFrom.getMeasuredHeight());
        // and now the bmp object will actually contain the requested layout
        canvas.drawBitmap(viewToDrawFrom.getDrawingCache(), 0, 0, new Paint());
        return bmp;
    }

    private void drawContent() {
        if (getMeasuredWidth() <= 0 || getMeasuredHeight() <= 0)
            return;
        final Bitmap bitmap = drawToBitmap(mMainContainer, getMeasuredWidth(), getMeasuredHeight());
        final RoundedCornersDrawable drawable = new RoundedCornersDrawable(getResources(), bitmap, 15);
        setImageDrawable(drawable);
    }

}

EDIT: found a nice alternative, based on "RoundKornersLayouts" library. Have a class that will be used for all of the layout classes you wish to extend, to be rounded:

//based on https://github.com/JcMinarro/RoundKornerLayouts
class CanvasRounder(cornerRadius: Float, cornerStrokeColor: Int = 0, cornerStrokeWidth: Float = 0F) {
    private val path = android.graphics.Path()
    private lateinit var rectF: RectF
    private var strokePaint: Paint?
    var cornerRadius: Float = cornerRadius
        set(value) {
            field = value
            resetPath()
        }

    init {
        if (cornerStrokeWidth <= 0)
            strokePaint = null
        else {
            strokePaint = Paint()
            strokePaint!!.style = Paint.Style.STROKE
            strokePaint!!.isAntiAlias = true
            strokePaint!!.color = cornerStrokeColor
            strokePaint!!.strokeWidth = cornerStrokeWidth
        }
    }

    fun round(canvas: Canvas, drawFunction: (Canvas) -> Unit) {
        val save = canvas.save()
        canvas.clipPath(path)
        drawFunction(canvas)
        if (strokePaint != null)
            canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, strokePaint)
        canvas.restoreToCount(save)
    }

    fun updateSize(currentWidth: Int, currentHeight: Int) {
        rectF = android.graphics.RectF(0f, 0f, currentWidth.toFloat(), currentHeight.toFloat())
        resetPath()
    }

    private fun resetPath() {
        path.reset()
        path.addRoundRect(rectF, cornerRadius, cornerRadius, Path.Direction.CW)
        path.close()
    }

}

Then, in each of your customized layout classes, add code similar to this one:

class RoundedConstraintLayout : ConstraintLayout {
    private lateinit var canvasRounder: CanvasRounder

    constructor(context: Context) : super(context) {
        init(context, null, 0)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context, attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        init(context, attrs, defStyle)
    }

    private fun init(context: Context, attrs: AttributeSet?, defStyle: Int) {
        val array = context.obtainStyledAttributes(attrs, R.styleable.RoundedCornersView, 0, 0)
        val cornerRadius = array.getDimension(R.styleable.RoundedCornersView_corner_radius, 0f)
        val cornerStrokeColor = array.getColor(R.styleable.RoundedCornersView_corner_stroke_color, 0)
        val cornerStrokeWidth = array.getDimension(R.styleable.RoundedCornersView_corner_stroke_width, 0f)
        array.recycle()
        canvasRounder = CanvasRounder(cornerRadius,cornerStrokeColor,cornerStrokeWidth)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            setLayerType(FrameLayout.LAYER_TYPE_SOFTWARE, null)
        }
    }

    override fun onSizeChanged(currentWidth: Int, currentHeight: Int, oldWidth: Int, oldheight: Int) {
        super.onSizeChanged(currentWidth, currentHeight, oldWidth, oldheight)
        canvasRounder.updateSize(currentWidth, currentHeight)
    }

    override fun draw(canvas: Canvas) = canvasRounder.round(canvas) { super.draw(canvas) }

    override fun dispatchDraw(canvas: Canvas) = canvasRounder.round(canvas) { super.dispatchDraw(canvas) }

}

If you wish to support attributes, use this as written on the library:

<resources>
  <declare-styleable name="RoundedCornersView">
      <attr name="corner_radius" format="dimension"/>
      <attr name="corner_stroke_width" format="dimension"/>
      <attr name="corner_stroke_color" format="color"/>
  </declare-styleable>
</resources>

Another alternative, which might be easier for most uses: use MaterialCardView . It allows customizing the rounded corners, stroke color and width, and elevation.

Example:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false"
    tools:context=".MainActivity">

    <com.google.android.material.card.MaterialCardView
        android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center"
        app:cardCornerRadius="8dp" app:cardElevation="8dp" app:strokeColor="#f00" app:strokeWidth="2dp">

        <ImageView
            android:layout_width="match_parent" android:layout_height="match_parent" android:background="#0f0"/>

    </com.google.android.material.card.MaterialCardView>

</FrameLayout>

And the result:

enter image description here

Do note that there is a slight artifacts issue at the edges of the stroke (leaves some pixels of the content there), if you use it. You can notice it if you zoom in. I've reported about this issue here.

EDIT: seems to be fixed, but not on the IDE. Reported here.

How to stop (and restart) the Rails Server?

I had to restart the rails application on the production so I looked for an another answer. I have found it below:

http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger

How do I position one image on top of another in HTML?

The easy way to do it is to use background-image then just put an <img> in that element.

The other way to do is using css layers. There is a ton a resources available to help you with this, just search for css layers.

Efficient way to return a std::vector in c++

It's time I post an answer about RVO, me too...

If you return an object by value, the compiler often optimizes this so it doesn't get constructed twice, since it's superfluous to construct it in the function as a temporary and then copy it. This is called return value optimization: the created object will be moved instead of being copied.

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

As mentioned this occurs when using RubyGems 1.6.0 with Ruby on Rails version earlier than version 3. My app is using Ruby on Rails 2.3.3 vendored into the /vendor of the project.

No doubt an upgrade of Ruby on Rails to a newer 2.3.X version may also fix this issue. However, this problem prevents you running Rake to unvendor Ruby on Rails and upgrade it.

Adding require 'thread' to the top of environment.rb did not fix the issue for me. Adding require 'thread' to /vendor/rails/activesupport/lib/active_support.rb did fix the problem.

Regex for string not ending with given suffix

.*[^a]$

the regex above will match strings which is not ending with a.

INSERT with SELECT

I think your INSERT statement is wrong, see correct syntax: http://dev.mysql.com/doc/refman/5.1/en/insert.html

edit: as Andrew already pointed out...

Is there a way to @Autowire a bean that requires constructor arguments?

You need to use @Autowired and @Value. Refer this post for more information on this topic.

How to correctly link php-fpm and Nginx Docker containers?

For anyone else getting

Nginx 403 error: directory index of [folder] is forbidden

when using index.php while index.html works perfectly and having included index.php in the index in the server block of their site config in sites-enabled

server {
    listen 80;

    # this path MUST be exactly as docker-compose php volumes
    root /usr/share/nginx/html;

    index index.php

    ...
}

Make sure your nginx.conf file at /etc/nginx/nginx.conf actually loads your site config in the http block...

http {

    ...

    include /etc/nginx/conf.d/*.conf;

    # Load our websites config 
    include /etc/nginx/sites-enabled/*;
}

Default value to a parameter while passing by reference in C++

void f(const double& v = *(double*) NULL)
{
  if (&v == NULL)
    cout << "default" << endl;
  else
    cout << "other " << v << endl;
}

How to make MySQL handle UTF-8 properly

MySQL 4.1 and above has a default character set that it calls utf8 but which is actually only a subset of UTF-8 (allows only three-byte characters and smaller).

Use utf8mb4 as your charset if you want "full" UTF-8.

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

it should vary with the architecture because it represents the size of any object. So on a 32-bit system size_t will likely be at least 32-bits wide. On a 64-bit system it will likely be at least 64-bit wide.

Select value from list of tuples where condition

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

Owl Carousel Won't Autoplay

Yes, its a typing error.

Write

autoPlay

not

autoplay

The autoplay-plugin code defines the variable as "autoPlay".

How to compare arrays in C#?

You're comparing the object references, and they are not the same. You need to compare the array contents.

.NET2 solution

An option is iterating through the array elements and call Equals() for each element. Remember that you need to override the Equals() method for the array elements, if they are not the same object reference.

An alternative is using this generic method to compare two generic arrays:

static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1, a2))
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    var comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}

.NET 3.5 or higher solution

Or use SequenceEqual if Linq is available for you (.NET Framework >= 3.5)

babel-loader jsx SyntaxError: Unexpected token

You can find a really good boilerplate made by Henrik Joreteg (ampersandjs) here: https://github.com/HenrikJoreteg/hjs-webpack

Then in your webpack.config.js

var getConfig = require('hjs-webpack')

module.exports = getConfig({
  in: 'src/index.js',
  out: 'public',
  clearBeforeBuild: true,
  https: process.argv.indexOf('--https') !== -1
})

Handling MySQL datetimes and timestamps in Java

The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp. A few resources include:

http://dev.mysql.com/doc/refman/5.1/en/datetime.html

http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion

How to store Java Date to Mysql datetime...?

http://www.velocityreviews.com/forums/t599436-the-best-practice-to-deal-with-datetime-in-mysql-using-jdbc.html

EDIT:

As others have indicated, the suggestion of using strings may lead to issues.

How to style the menu items on an Android action bar

My guess is that you have to also style the views that are generated from the menu information in your onCreateOptionsMenu(). The styling you applied so far is working, but I doubt that the menu items, when rendered with text use a style that is the same as the title part of the ActionBar.

You may want to look at Menu.getActionView() to get the view for the menu action and then adjust it accordingly.

Can I pass a JavaScript variable to another browser window?

Alternatively, you can add it to the URL and let the scripting language (PHP, Perl, ASP, Python, Ruby, whatever) handle it on the other side. Something like:

var x = 10;
window.open('mypage.php?x='+x);

Nuget connection attempt failed "Unable to load the service index for source"

Go to -> Tools -> Extensions and Updates and uninstall NuGet package manager.. restart visual studio and reinstall it.... every thing will set to normal

Is it possible to use the instanceof operator in a switch statement?

I know this is very late but for future readers ...

Beware of the approaches above that are based only on the name of the class of A, B, C ... :

Unless you can guarantee that A, B, C ... (all subclasses or implementers of Base) are final then subclasses of A, B, C ... will not be dealt with.

Even though the if, elseif, elseif .. approach is slower for large number of subclasses/implementers, it is more accurate.

How do I set up CLion to compile and run?

You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.

Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)

follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html

Unpivot with column name

Your query is very close. You should be able to use the following which includes the subject in the final select list:

select u.name, u.subject, u.marks
from student s
unpivot
(
  marks
  for subject in (Maths, Science, English)
) u;

See SQL Fiddle with demo

How to get GET (query string) variables in Express.js on Node.js?

In Express, use req.query.

req.params only gets the route parameters, not the query string parameters. See the express or sails documentation:

(req.params) Checks route params, ex: /user/:id

(req.query) Checks query string params, ex: ?id=12 Checks urlencoded body params

(req.body), ex: id=12 To utilize urlencoded request bodies, req.body should be an object. This can be done by using the _express.bodyParser middleware.

That said, most of the time, you want to get the value of a parameter irrespective of its source. In that case, use req.param('foo').

The value of the parameter will be returned whether the variable was in the route parameters, query string, or the encoded request body.

Side note- if you're aiming to get the intersection of all three types of request parameters (similar to PHP's $_REQUEST), you just need to merge the parameters together-- here's how I set it up in Sails. Keep in mind that the path/route parameters object (req.params) has array properties, so order matters (although this may change in Express 4)

Stored procedure - return identity as output parameter or scalar

Its all depend on your client data access-layer. Many ORM frameworks rely on explicitly querying the SCOPE_IDENTITY during the insert operation.

If you are in complete control over the data access layer then is arguably better to return SCOPE_IDENTITY() as an output parameter. Wrapping the return in a result set adds unnecessary meta data overhead to describe the result set, and complicates the code to process the requests result.

If you prefer a result set return, then again is arguable better to use the OUTPUT clause:

INSERT INTO  MyTable (col1, col2, col3)
OUTPUT INSERTED.id, col1, col2, col3
VALUES (@col1, @col2, @col3);

This way you can get the entire inserted row back, including default and computed columns, and you get a result set containing one row for each row inserted, this working correctly with set oriented batch inserts.

Overall, I can't see a single case when returning SCOPE_IDENTITY() as a result set would be a good practice.

Exclude property from type

I do like that:

interface XYZ {
  x: number;
  y: number;
  z: number;
}
const a:XYZ = {x:1, y:2, z:3};
const { x, y, ...last } = a;
const { z, ...firstTwo} = a;
console.log(firstTwo, last);

IIS Express Windows Authentication

I'm using visual studio 2019 develop against ASP.Net application. Here's what been worked for us:

  1. Open your Project Property Windows, Disable Anonymous Authentication and Enable Windows Authentication
  2. In your Web.Config under system.web

_x000D_
_x000D_
<authentication mode="Windows"></authentication>p
_x000D_
_x000D_
_x000D_

And I didn't change application.config in iis express.

UTF-8 encoded html pages show ? (questions marks) instead of characters

Looks like nobody mentioned

SET NAMES utf8;

I found this solution here and it helped me. How to apply it:

To be all UTF-8, issue the following statement just after you’ve made the connection to the database server: SET NAMES utf8;

Maybe this will help someone.

Javascript: console.log to html

Create an ouput

<div id="output"></div>

Write to it using JavaScript

var output = document.getElementById("output");
output.innerHTML = "hello world";

If you would like it to handle more complex output values, you can use JSON.stringify

var myObj = {foo: "bar"};
output.innerHTML = JSON.stringify(myObj);

Why can't I shrink a transaction log file, even after backup?

If you set the recovery mode on the database in 2005 (don't know for pre-2005) it will drop the log file all together and then you can put it back in full recovery mode to restart/recreate the logfile. We ran into this with SQL 2005 express in that we couldn't get near the 4GB limit with data until we changed the recovery mode.

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

Difference between parameter and argument

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

Call Class Method From Another Class

class CurrentValue:

    def __init__(self, value):
        self.value = value

    def set_val(self, k):
        self.value = k

    def get_val(self):
        return self.value


class AddValue:

    def av(self, ocv):
        print('Before:', ocv.get_val())
        num = int(input('Enter number to add : '))
        nnum = num + ocv.get_val()
        ocv.set_val(nnum)
        print('After add :', ocv.get_val())


cvo = CurrentValue(5)

avo = AddValue()

avo.av(cvo)

We define 2 classes, CurrentValue and AddValue We define 3 methods in the first class One init in order to give to the instance variable self.value an initial value A set_val method where we set the self.value to a k A get_val method where we get the valuue of self.value We define one method in the second class A av method where we pass as parameter(ovc) an object of the first class We create an instance (cvo) of the first class We create an instance (avo) of the second class We call the method avo.av(cvo) of the second class and pass as an argument the object we have already created from the first class. So by this way I would like to show how it is possible to call a method of a class from another class.

I am sorry for any inconvenience. This will not happen again.

Before: 5

Enter number to add : 14

After add : 19

Bubble Sort Homework

def bubble_sort(l):
    exchanged = True
    iteration = 0
    n = len(l)

    while(exchanged):
        iteration += 1
        exchanged = False

        # Move the largest element to the end of the list
        for i in range(n-1):
            if l[i] > l[i+1]:
                exchanged = True
                l[i], l[i+1] = l[i+1], l[i]
        n -= 1   # Largest element already towards the end

    print 'Iterations: %s' %(iteration)
    return l

Getting input values from text box

<script>
  function submit(){
      var userPass = document.getElementById('pass');
      var userName = document.getElementById('user');
      alert(user.value);
      alert(pass.value);
  }
</script>

<input type="text" id="user" />
<input type="text" id="pass" />
<button onclick="submit();" href="javascript:;">Submit</button>

Embedding SVG into ReactJS

According to a react developer, you dont need the namespace xmlns. If you need the attribute xlink:href you can use xlinkHref from react 0.14

Example

Icon = (props) => {
  return <svg className="icon">
    <use xlinkHref={ '#' + props.name }></use>
  </svg>;
}

Is there a Social Security Number reserved for testing/examples?

I used this 457-55-5462 as testing SSN and it worked for me. I used it at paypal sandbox account. Hope it helps somebody

Calling one Activity from another in Android

Very easiest way to call one activity to another is

startActivity( new Intent( getApplicationContext(), YourActivity.class ) );

Updating a JSON object using Javascript

$(document).ready(function(){        
    var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
               {'Id':'2','Username':'Steve','FatherName':'Johnson'},
               {'Id':'3','Username':'Albert','FatherName':'Einstein'}];

    $.each(jsonObj,function(i,v){       
      if (v.Id == 3) {
        v.Username = "Thomas";
        return false;
      }
    });

alert("New Username: " + jsonObj[2].Username);

});

Handling onchange event in HTML.DropDownList Razor MVC

Description

You can use another overload of the DropDownList method. Pick the one you need and pass in a object with your html attributes.

Sample

@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })

More Information

How to save an image to localStorage and display it on the next page?

"Note that you need to have image fully loaded first (otherwise ending up in having empty images), so in some cases you'd need to wrap handling into: bannerImage.addEventListener("load", function () {}); – yuga Nov 1 '17 at 13:04"

This is extremely IMPORTANT. One of the the options i'm exploring this afternoon is using javascript callback methods rather than addEventListeners since that doesn't seem to bind correctly either. Getting all the elements ready before page load WITHOUT a page refresh is critical.

If anyone can expand upon this please do - as in, did you use a settimeout, a wait, a callback, or an addEventListener method to get the desired result. Which one and why?

set the width of select2 input (through Angular-ui directive)

Add width resolve option to your select2 function

$(document).ready(function() { 
        $("#myselect").select2({ width: 'resolve' });           
});

After add below CSS to your stylesheet

.select2-container {
width: 100% !important;
}

It will sort the issue

Copy row but with new id

INSERT into table_name (  
    `product_id`, 
    `other_products_url_id`, 
    `brand`, 
    `title`, 
    `price`, 
    `category`, 
    `sub_category`, 
    `quantity`, 
    `buy_now`, 
    `buy_now_url`, 
    `is_available`, 
    `description`, 
    `image_url`, 
    `image_type`, 
    `server_image_url`, 
    `reviews`, 
    `hits`, 
    `rating`, 
    `seller_name`, 
    `seller_desc`, 
    `created_on`, 
    `modified_on`, 
    `status`) 
SELECT 
    `product_id`, 
    `other_products_url_id`, 
    `brand`, 
    `title`, 
    `price`, 
    `category`, 
    `sub_category`, 
    `quantity`, 
    `buy_now`, 
    concat(`buy_now_url`,'','#test123456'), 
    `is_available`, 
    `description`, 
    `image_url`, 
    `image_type`, 
    `server_image_url`, 
    `reviews`, 
    `hits`, 
    `rating`, 
    `seller_name`, 
    `seller_desc`, 
    `created_on`, 
    `modified_on`, 
    `status` 
FROM `table_name` WHERE id='YourRowID';

Prevent screen rotation on Android

In your Manifest file, for each Activity that you want to lock the screen rotation add: if you want to lock it in horizontal mode:

<activity
        ...
        ...
        android:screenOrientation="landscape">

or if you want to lock it in vertical mode:

<activity
            ...
            ...
            android:screenOrientation="portrait">

int to unsigned int conversion

This conversion is well defined and will yield the value UINT_MAX - 61. On a platform where unsigned int is a 32-bit type (most common platforms, these days), this is precisely the value that others are reporting. Other values are possible, however.

The actual language in the standard is

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type).

Delete all items from a c++ std::vector

I think you should use std::vector::clear:

vec.clear();

EDIT:

Doesn't clear destruct the elements held by the vector?

Yes it does. It calls the destructor of every element in the vector before returning the memory. That depends on what "elements" you are storing in the vector. In the following example, I am storing the objects them selves inside the vector:

class myclass
{
public:
    ~myclass()
    {

    }
...
};

std::vector<myclass> myvector;
...
myvector.clear(); // calling clear will do the following:
// 1) invoke the deconstrutor for every myclass
// 2) size == 0 (the vector contained the actual objects).

If you want to share objects between different containers for example, you could store pointers to them. In this case, when clear is called, only pointers memory is released, the actual objects are not touched:

std::vector<myclass*> myvector;
...
myvector.clear(); // calling clear will do:
// 1) ---------------
// 2) size == 0 (the vector contained "pointers" not the actual objects).

For the question in the comment, I think getVector() is defined like this:

std::vector<myclass> getVector();

Maybe you want to return a reference:

// vector.getVector().clear() clears m_vector in this case
std::vector<myclass>& getVector(); 

Using the Jersey client to do a POST operation

Starting from Jersey 2.x, the MultivaluedMapImpl class is replaced by MultivaluedHashMap. You can use it to add form data and send it to the server:

    WebTarget webTarget = client.target("http://www.example.com/some/resource");
    MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
    formData.add("key1", "value1");
    formData.add("key2", "value2");
    Response response = webTarget.request().post(Entity.form(formData));

Note that the form entity is sent in the format of "application/x-www-form-urlencoded".

How to do a redirect to another route with react-router?

With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.

import { Router } from 'react-router';

export default class Foo extends Component {

  static get contextTypes() {
    return {
      router: React.PropTypes.object.isRequired,
    };
  }

  handleClick() {
    this.context.router.push('/some-path');
  }
}

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

how to increase the limit for max.print in R

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

See ?options:

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

How to show imageView full screen on imageView click?

It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)

    public class UIutils {

private Activity mActivity;

    public UIutils(Activity activity){
        mActivity = activity;
    }

public void showPhoto(Uri photoUri){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(photoUri, "image/*");
        mActivity.startActivity(intent);
    }
}

Then to use it just do this:

imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));

I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.

How to cache data in a MVC application

HttpContext.Current.Cache.Insert("subjectlist", subjectlist);

How do you uninstall a python package that was installed using distutils?

Yes, it is safe to simply delete anything that distutils installed. That goes for installed folders or .egg files. Naturally anything that depends on that code will no longer work.

If you want to make it work again, simply re-install.

By the way, if you are using distutils also consider using the multi-version feature. It allows you to have multiple versions of any single package installed. That means you do not need to delete an old version of a package if you simply want to install a newer version.

How do I create a table based on another table

select * into newtable from oldtable

In Java, what does NaN mean?

NaN = Not a Number.

illegal use of break statement; javascript

I have a function next() which will maybe inspire you.

function queue(target) {
        var array = Array.prototype;

        var queueing = [];

        target.queue = queue;
        target.queued = queued;

        return target;

        function queued(action) {
            return function () {
                var self = this;
                var args = arguments;

                queue(function (next) {
                    action.apply(self, array.concat.apply(next, args));
                });
            };
        }

        function queue(action) {
            if (!action) {
                return;
            }

            queueing.push(action);

            if (queueing.length === 1) {
                next();
            }
        }

        function next() {
            queueing[0](function (err) {
                if (err) {
                    throw err;
                }

                queueing = queueing.slice(1);

                if (queueing.length) {
                    next();
                }
            });
        }
    }

Reliable method to get machine's MAC address in C#

IMHO returning first mac address isn't good idea, especially when virtual machines are hosted. Therefore i check send/received bytes sum and select most used connection, that is not perfect, but should be correct 9/10 times.

public string GetDefaultMacAddress()
{
    Dictionary<string, long> macAddresses = new Dictionary<string, long>();
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
            macAddresses[nic.GetPhysicalAddress().ToString()] = nic.GetIPStatistics().BytesSent + nic.GetIPStatistics().BytesReceived;
    }
    long maxValue = 0;
    string mac = "";
    foreach(KeyValuePair<string, long> pair in macAddresses)
    {
        if (pair.Value > maxValue)
        {
            mac = pair.Key;
            maxValue = pair.Value;
        }
    }
    return mac;
}

kill a process in bash

You can use the command pkill to kill processes. If you want to "play around", you can use "pgrep", which works exactly the same but returns the process rather than killing it.

pkill has the -f parameter that allows you to match against the entire command. So for your example, you can: pkill -f "gedit file.txt"

Change jsp on button click

If all you are looking for is navigation to page 2 and 3 from page one, replace the buttons with anchor elements as below:

<form name="TrainerMenu" action="TrainerMenu" method="get">

<h1>Benvenuto in LESSON! Scegli l'operazione da effettuare:</h1>
<a href="Page2.jsp" id="CreateCourse" >Creazione Nuovo Corso</a>&nbsp;
<a href="Page3.jsp" id="AuthorizationManager">Gestione Autorizzazioni</a>
<input type="button" value="" name="AuthorizationManager" />
</form>

If for some reason you need to use buttons, try this:

<form name="TrainerMenu" action="TrainerMenu" method="get">

   <h1>Benvenuto in LESSON! Scegli l'operazione da effettuare:</h1>
   <input type="button" value="Creazione Nuovo Corso" name="CreateCourse"
    onclick="openPage('Page2.jsp')"/>
   <input type="button" value="Gestione Autorizzazioni" name="AuthorizationManager"
    onclick="openPage('Page3.jsp')" />

</form>
<script type="text/javascript">
 function openPage(pageURL)
 {
 window.location.href = pageURL;
 }
</script>

What is the difference between the HashMap and Map objects in Java?

Adding to the top voted answer and many ones above stressing the "more generic, better", I would like to dig a little bit more.

Map is the structure contract while HashMap is an implementation providing its own methods to deal with different real problems: how to calculate index, what is the capacity and how to increment it, how to insert, how to keep the index unique, etc.

Let's look into the source code:

In Map we have the method of containsKey(Object key):

boolean containsKey(Object key);

JavaDoc:

boolean java.util.Map.containsValue(Object value)

Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of the Map interface.

Parameters:value

value whose presence in this map is to betested

Returns:true

if this map maps one or more keys to the specified

valueThrows:

ClassCastException - if the value is of an inappropriate type for this map (optional)

NullPointerException - if the specified value is null and this map does not permit null values (optional)

It requires its implementations to implement it, but the "how to" is at its freedom, only to ensure it returns correct.

In HashMap:

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

It turns out that HashMap uses hashcode to test if this map contains the key. So it has the benefit of hash algorithm.

How to Change Margin of TextView

You were probably changing the layout margin after it has been drawn. mOldTextView.invalidate() is useless. you needed to call requestLayout() on the parent to relayout the new configuration. When you moved the layout changing code before the drawing took place, everything worked fine.

Load text file as strings using numpy.loadtxt()

Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.

def load(fname):
    ''' Load the file using std open'''
    f = open(fname,'r')

    data = []
    for line in f.readlines():
        data.append(line.replace('\n','').split(' '))

    f.close()

    return data

For a text file with 4000x4000 words this is about 10 times faster than loadtxt.

z-index not working with fixed positioning

since your over div doesn't have a positioning, the z-index doesn't know where and how to position it (and with respect to what?). Just change your over div's position to relative, so there is no side effects on that div and then the under div will obey to your will.

here is your example on jsfiddle: Fiddle

edit: I see someone already mentioned this answer!

TCPDF output without saving file

I've been using the Output("doc.pdf", "I"); and it doesn't work, I'm always asked for saving the file.

I took a look in documentation and found that

I send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF. http://www.tcpdf.org/doc/classTCPDF.html#a3d6dcb62298ec9d42e9125ee2f5b23a1

Then I think you have to use a plugin to print it, otherwise it is going to be downloaded.

How to insert values in table with foreign key using MySQL?

http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

For case1:

INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
  FROM TAB_TEACHER
 WHERE name_teacher = 'Professor Jack'
 LIMIT 1

For case2 you just have to do 2 separate insert statements

How to add spacing between UITableViewCell

Using the headers as spacing would work fine I guess if you don't want to use any headers. Otherwise, probably not the best idea. What I'm thinking is create a custom cell view.

Examples:

In the custom cell, make a background view with constraints so that it doesn't fill the entire cell, give it some padding.

Then, make the tableview background invisible and remove the separators:

// Make the background invisible
tableView.backgroundView = UIView()
tableView.backgroundColor = .clear

// Remove the separators
tableview.separatorStyle = .none

How to open a new window on form submit

I generally use a small jQuery snippet globally to open any external links in a new tab / window. I've added the selector for a form for my own site and it works fine so far:

// URL target
    $('a[href*="//"]:not([href*="'+ location.hostname +'"]),form[action*="//"]:not([href*="'+ location.hostname +'"]').attr('target','_blank');

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

I encountered this issue while importing some of the files from the Add Health data into R (see: http://www.icpsr.umich.edu/icpsrweb/ICPSR/studies/21600?archive=ICPSR&q=21600 ) For example, the following command to read the DS12 data file in tab separated .tsv format will generate the following error:

ds12 <- read.table("21600-0012-Data.tsv", sep="\t", comment.char="", 
quote = "\"", header=TRUE)

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, 
na.strings,  : line 2390 did not have 1851 elements

It appears there is a slight formatting issue with some of the files that causes R to reject the file. At least part of the issue appears to be the occasional use of double quotes instead of an apostrophe that causes an uneven number of double quote characters in a line.

After fiddling, I've identified three possible solutions:

  1. Open the file in a text editor and search/replace all instances of a quote character " with nothing. In other words, delete all double quotes. For this tab-delimited data, this meant only that some verbatim excerpts of comments from subjects were no longer in quotes which was a non-issue for my data analysis.

  2. With data stored on ICPSR (see link above) or other archives another solution is to download the data in a new format. A good option in this case is to download the Stata version of the DS12 and then open it using the read.dta command as follows:

    library(foreign)
    ds12 <- read.dta("21600-0012-Data.dta")
    
  3. A related solution/hack is to open the .tsv file in Excel and re-save it as a tab separated text file. This seems to clean up whatever formatting issue makes R unhappy.

None of these are ideal in that they don't quite solve the problem in R with the original .tsv file but data wrangling often requires the use of multiple programs and formats.

max(length(field)) in mysql

Ok, I am not sure what are you using(MySQL, SLQ Server, Oracle, MS Access..) But you can try the code below. It work in W3School example DB. Here try this:

SELECT city, max(length(city)) FROM Customers;

animating addClass/removeClass with jQuery

You could use jquery ui's switchClass, Heres an example:

$( "selector" ).switchClass( "oldClass", "newClass", 1000, "easeInOutQuad" );

Or see this jsfiddle.

Change button text from Xcode?

myapp.h

{
UIButton *myButton;
}
@property (nonatomic,retain)IBoutlet UIButton *myButton;

myapp.m

@synthesize myButton;

-(IBAction)buttonTitle{
[myButton setTitle:@"Play" forState:UIControlStateNormal];
}

jQuery Ajax calls and the Html.AntiForgeryToken()

I use a simple js function like this

AddAntiForgeryToken = function(data) {
    data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
    return data;
};

Since every form on a page will have the same value for the token, just put something like this in your top-most master page

<%-- used for ajax in AddAntiForgeryToken() --%>
<form id="__AjaxAntiForgeryForm" action="#" method="post"><%= Html.AntiForgeryToken()%></form>  

Then in your ajax call do (edited to match your second example)

$.ajax({
    type: "post",
    dataType: "html",
    url: $(this).attr("rel"),
    data: AddAntiForgeryToken({ id: parseInt($(this).attr("title")) }),
    success: function (response) {
        // ....
    }
});

How to convert ASCII code (0-255) to its corresponding character?

One can iterate from a to z like this

int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
    search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}

How to create custom exceptions in Java?

For a checked exception:

public class MyCustomException extends Exception { }

Technically, anything that extends Throwable can be an thrown, but exceptions are generally extensions of the Exception class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Errors which usually are not something designed to be gracefully handled beyond the JVM internals.

You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.

As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via

throw new MyCustomException()

and catch via

catch (MyCustomException e) { }

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

i got the same problem and i notice that my security config has diferent TAGS like the @Xenolion answer says

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

so i change the TAGS "domain-config" for "base-config" and works, like this:

<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </base-config>
</network-security-config>

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Problem: (Sql server 2014) This issue happens when assembly Microsoft.SqlServer.management.sdk.sfc version 12.0.0.0 not found by visual studio.

Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=42295 and download:

  • ENU\x64\SharedManagementObjects.msi for X64 OS or
  • ENU\x86\SharedManagementObjects.msi for X86 OS,

then install it, and restart visual studio.

PS: You may need install DB2OLEDBV5_x64.msi or DB2OLEDBV5_x86.msi too.


Problem: (Sql server 2012) This issue happens when assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 not found by visual studio.

Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=35580 and download:

  • ENU\x64\SharedManagementObjects.msi for X64 OS or
  • ENU\x86\SharedManagementObjects.msi for X86 OS,

then install it, and restart visual studio.


Problem: (Sql server 2008) This issue happens when assembly Microsoft.SqlServer.management.sdk.sfc version 10.0.0.0 not found by visual studio.

Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=26728 and download:

  • 1033\x64\SharedManagementObjects.msi for X64 OS or
  • 1033\x86\SharedManagementObjects.msi for X86 OS,

(In most cases downloading this is better http://go.microsoft.com/fwlink/?LinkId=123708&clcid=0x409)

then install it, and restart visual studio.


Problem: I recently got similar problem after installing SharedManagementObjects. assembly Microsoft.SqlServer.ConnectionInfo, Version=12.0.0.0 not found by visual studio. The problem was Visual C++ Redistributable Packages for Visual Studio was not installed yet.

Solution: for Visual Studio 2013 just go to http://www.microsoft.com/en-us/download/details.aspx?id=40784 and download:

  • vcredist_x64.exe for X64 OS or
  • vcredist_x86.exe for X86 OS,

then install it, and restart visual studio.

PS: You can find Visual C++ Redistributable Packages for Visual Studio 20XX for other versions of Visual Studio easily by googling it.

How do I post button value to PHP?

As Josh has stated above, you want to give each one the same name (letter, button, etc.) and all of them work. Then you want to surround all of these with a form tag:

<form name="myLetters" action="yourScript.php" method="POST">
<!-- Enter your values here with the following syntax: -->
<input type="radio" name="letter" value="A" /> A
<!-- Then add a submit value & close your form -->
<input type="submit" name="submit" value="Choose Letter!" />
</form>

Then, in the PHP script "yourScript.php" as defined by the action attribute, you can use:

$_POST['letter']

To get the value chosen.

Mongoimport of json file

console:

mongoimport -d dbName -c collectionName dataFile.js 

Unexpected character encountered while parsing value

This error occurs when we parse json content to model object. Json content type is string. For example: https://dotnetfiddle.net/uFClKj Some times, an api that we call may return an error. If we do not check the response status, but proceed to parse the response to model, this issue will occur.

Mapping composite keys using EF code first

I thought I would add to this question as it is the top google search result.

As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.

As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating

// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
    .Where(t => 
        t.ClrType.GetProperties()
            .Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
    // get the keys in the appropriate order
    var orderedKeys = entity.ClrType
        .GetProperties()
        .Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
        .OrderBy(p => 
            p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
                .NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
                .TypedValue.Value ?? 0)
        .Select(x => x.Name)
        .ToArray();

    // apply the keys to the model builder
    modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}

I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone

Is there a difference between "==" and "is"?

As John Feminella said, most of the time you will use == and != because your objective is to compare values. I'd just like to categorise what you would do the rest of the time:

There is one and only one instance of NoneType i.e. None is a singleton. Consequently foo == None and foo is None mean the same. However the is test is faster and the Pythonic convention is to use foo is None.

If you are doing some introspection or mucking about with garbage collection or checking whether your custom-built string interning gadget is working or suchlike, then you probably have a use-case for foo is bar.

True and False are also (now) singletons, but there is no use-case for foo == True and no use case for foo is True.

HTML input time in 24 format

As stated in this answer not all browsers support the standard way. It is not a good idea to use for robust user experience. And if you use it, you cannot ask too much.

Instead use time-picker libraries. For example: TimePicker.js is a zero dependency and lightweight library. Use it like:

_x000D_
_x000D_
var timepicker = new TimePicker('time', {_x000D_
  lang: 'en',_x000D_
  theme: 'dark'_x000D_
});_x000D_
timepicker.on('change', function(evt) {_x000D_
  _x000D_
  var value = (evt.hour || '00') + ':' + (evt.minute || '00');_x000D_
  evt.element.value = value;_x000D_
_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>_x000D_
<link href="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div>_x000D_
  <input type="text" id="time" placeholder="Time">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

HTML

<form id="some_form">
<!-- some form elements -->
</form>

and jquery

$("#some_form").reset();

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

I believe the answer is outlined on the slf4j web-site (Failed to load class org.slf4j.impl.StaticLoggerBinder)

For a very quick solution I suggest adding no-operation (NOP) logger implementation (slf4j-nop.jar)

For example, if using maven:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-nop</artifactId>
    <version>${slf4j-nop-version}</version>
</dependency>

Creating executable files in Linux

Make file executable:

chmod +x file

Find location of perl:

which perl

This should return something like

/bin/perl sometimes /usr/local/bin

Then in the first line of your script add:

#!"path"/perl with path from above e.g.

#!/bin/perl

Then you can execute the file

./file

There may be some issues with the PATH, so you may want to change that as well ...

What in the world are Spring beans?

Well you understood it partially. You have to tailor the beans according to your need and inform Spring container to manage it when required, by using a methodology populalrly known as IoC (Inversion of Control) coined by Martin Fowler, also known as Dependency Injection (DI).

You wire the beans in a way, so that you do not have to take care of the instantiating or evaluate any dependency on the bean. This is popularly known as Hollywood Principle.

Google is the best tool to explore more on this in addition to the links you would get flooded with here in this question. :)

Removing duplicates from a String in Java

public class StringTest {

    public static String dupRemove(String str) {

        Set<Character> s1 = new HashSet<Character>();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {

            Character c = str.charAt(i);

            if (!s1.contains(c)) {
                s1.add(c);
                sb.append(c);
            }


        }

        System.out.println(sb.toString());

        return sb.toString();

    }

    public static void main(String[] args) {

        dupRemove("AAAAAAAAAAAAAAAAA BBBBBBBB");
    }

}

Can you break from a Groovy "each" closure?

No, you can't break from a closure in Groovy without throwing an exception. Also, you shouldn't use exceptions for control flow.

If you find yourself wanting to break out of a closure you should probably first think about why you want to do this and not how to do it. The first thing to consider could be the substitution of the closure in question with one of Groovy's (conceptual) higher order functions. The following example:

for ( i in 1..10) { if (i < 5) println i; else return}

becomes

(1..10).each{if (it < 5) println it}

becomes

(1..10).findAll{it < 5}.each{println it} 

which also helps clarity. It states the intent of your code much better.

The potential drawback in the shown examples is that iteration only stops early in the first example. If you have performance considerations you might want to stop it right then and there.

However, for most use cases that involve iterations you can usually resort to one of Groovy's find, grep, collect, inject, etc. methods. They usually take some "configuration" and then "know" how to do the iteration for you, so that you can actually avoid imperative looping wherever possible.

What is the correct value for the disabled attribute?

From MDN by setAttribute():

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

Link to MDN

Solution

  • I mean that in XHTML Strict is right disabled="disabled",
  • and in HTML5 is only disabled, like <input name="myinput" disabled>
  • In javascript, I set the value to true via e.disabled = true;
    or to "" via setAttribute( "disabled", "" );

Test in Chrome

var f = document.querySelectorAll( "label.disabled input" );
for( var i = 0; i < f.length; i++ )
{
    // Reference
    var e = f[ i ];

    // Actions
    e.setAttribute( "disabled", false|null|undefined|""|0|"disabled" );
    /*
        <input disabled="false"|"null"|"undefined"|empty|"0"|"disabled">
        e.getAttribute( "disabled" ) === "false"|"null"|"undefined"|""|"0"|"disabled"
        e.disabled === true
    */
    
    e.removeAttribute( "disabled" );
    /*
        <input>
        e.getAttribute( "disabled" ) === null
        e.disabled === false
    */

    e.disabled = false|null|undefined|""|0;
    /*
        <input>
        e.getAttribute( "disabled" ) === null|null|null|null|null
        e.disabled === false
    */

    e.disabled = true|" "|"disabled"|1;
    /*
        <input disabled>
        e.getAttribute( "disabled" ) === ""|""|""|""
        e.disabled === true
    */
}

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

What is the difference between == and equals() in Java?

There are some small differences depending whether you are talking about "primitives" or "Object Types"; the same can be said if you are talking about "static" or "non-static" members; you can also mix all the above...

Here is an example (you can run it):

public final class MyEqualityTest
{
    public static void main( String args[] )
    {
        String s1 = new String( "Test" );
        String s2 = new String( "Test" );

        System.out.println( "\n1 - PRIMITIVES ");
        System.out.println( s1 == s2 ); // false
        System.out.println( s1.equals( s2 )); // true

        A a1 = new A();
        A a2 = new A();

        System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" );
        System.out.println( a1 == a2 ); // false
        System.out.println( a1.s == a2.s ); // true
        System.out.println( a1.s.equals( a2.s ) ); // true

        B b1 = new B();
        B b2 = new B();

        System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
        System.out.println( b1 == b2 ); // false
        System.out.println( b1.getS() == b2.getS() ); // false
        System.out.println( b1.getS().equals( b2.getS() ) ); // true
    }
}

final class A
{
    // static
    public static String s;
    A()
    {
        this.s = new String( "aTest" );
    }
}

final class B
{
    private String s;
    B()
    {
        this.s = new String( "aTest" );
    }

    public String getS()
    {
        return s;
    }

}

You can compare the explanations for "==" (Equality Operator) and ".equals(...)" (method in the java.lang.Object class) through these links:

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

C# equivalent of the IsNull() function in SQL Server

Use below methods.

    /// <summary>
    /// Returns replacement value if expression is null
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="replacement"></param>
    /// <returns></returns>
    public static long? IsNull(long? expression, long? replacement)
    {
        if (expression.HasValue)
            return expression;
        else
            return replacement;
    }

    /// <summary>
    /// Returns replacement value if expression is null
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="replacement"></param>
    /// <returns></returns>
    public static string IsNull(string expression, string replacement)
    {
        if (string.IsNullOrWhiteSpace(expression))
            return replacement;
        else
            return expression;
    }

Detect whether Office is 32bit or 64bit via the registry

Open Outlook 2013 > File > Office account > About Outlook > click large "? About Outlook" button > read popup description

Case Function Equivalent in Excel

I used this solution to convert single letter color codes into their descriptions:

=CHOOSE(FIND(H5,"GYR"),"Good","OK","Bad")

You basically look up the element you're trying to decode in the array, then use CHOOSE() to pick the associated item. It's a little more compact than building a table for VLOOKUP().

How to view file diff in git before commit

To check for local differences:

git diff myfile.txt

or you can use a diff tool (in case you'd like to revert some changes):

git difftool myfile.txt

To use git difftool more efficiently, install and use your favourite GUI tool such as Meld, DiffMerge or OpenDiff.

Note: You can also use . (instead of filename) to see current dir changes.

In order to check changes per each line, use: git blame which will display which line was commited in which commit.


To view the actual file before the commit (where master is your branch), run:

git show master:path/my_file

Is there a way to get a list of all current temporary tables in SQL Server?

SELECT left(NAME, charindex('_', NAME) - 1)
FROM tempdb..sysobjects
WHERE NAME LIKE '#%'
    AND NAME NOT LIKE '##%'
    AND upper(xtype) = 'U'
    AND NOT object_id('tempdb..' + NAME) IS NULL

you can remove the ## line if you want to include global temp tables.

Converting pixels to dp

To convert dp to px this code can be helpful :

public static int dpToPx(Context context, int dp) {
       final float scale = context.getResources().getDisplayMetrics().density;
       return (int) (dp * scale + 0.5f);
    }

How to split a file into equal parts, without breaking individual lines?

The script isn't even necessary, split(1) supports the wanted feature out of the box:
split -l 75 auth.log auth.log. The above command splits the file in chunks of 75 lines a piece, and outputs file on the form: auth.log.aa, auth.log.ab, ...

wc -l on the original file and output gives:

  321 auth.log
   75 auth.log.aa
   75 auth.log.ab
   75 auth.log.ac
   75 auth.log.ad
   21 auth.log.ae
  642 total

Can I use Objective-C blocks as properties?

For Swift, just use closures: example.


In Objective-C:

@property (copy)void

@property (copy)void (^doStuff)(void);

It's that simple.

Here is the actual Apple documentation, which states precisely what to use:

Apple doco.

In your .h file:

// Here is a block as a property:
//
// Someone passes you a block. You "hold on to it",
// while you do other stuff. Later, you use the block.
//
// The property 'doStuff' will hold the incoming block.

@property (copy)void (^doStuff)(void);

// Here's a method in your class.
// When someone CALLS this method, they PASS IN a block of code,
// which they want to be performed after the method is finished.

-(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater;

// We will hold on to that block of code in "doStuff".

Here's your .m file:

 -(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater
    {
    // Regarding the incoming block of code, save it for later:
    self.doStuff = pleaseDoMeLater;

    // Now do other processing, which could follow various paths,
    // involve delays, and so on. Then after everything:
    [self _alldone];
    }

-(void)_alldone
    {
    NSLog(@"Processing finished, running the completion block.");
    // Here's how to run the block:
    if ( self.doStuff != nil )
       self.doStuff();
    }

Beware of out-of-date example code.

With modern (2014+) systems, do what is shown here. It is that simple.

Which ORM should I use for Node.js and MySQL?

One major difference between Sequelize and Persistence.js is that the former supports a STRING datatype, i.e. VARCHAR(255). I felt really uncomfortable making everything TEXT.

how to read certain columns from Excel using Pandas - Python

"usecols" should help, use range of columns (as per excel worksheet, A,B...etc.) below are the examples

  1. Selected Columns
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A,C,F")
  1. Range of Columns and selected column
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H")
  1. Multiple Ranges
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H,J:N")
  1. Range of columns
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:N")

Target Unreachable, identifier resolved to null in JSF 2.2

I solved this problem.

My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.

Thanks @PM77-1


Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

Check if key exists and iterate the JSON array using Python

It is a good practice to create helper utility methods for things like that so that whenever you need to change the logic of attribute validation it would be in one place, and the code will be more readable for the followers.

For example create a helper method (or class JsonUtils with static methods) in json_utils.py:

def get_attribute(data, attribute, default_value):
    return data.get(attribute) or default_value

and then use it in your project:

from json_utils import get_attribute

def my_cool_iteration_func(data):

    data_to = get_attribute(data, 'to', None)
    if not data_to:
        return

    data_to_data = get_attribute(data_to, 'data', [])
    for item in data_to_data:
        print('The id is: %s' % get_attribute(item, 'id', 'null'))

IMPORTANT NOTE:

There is a reason I am using data.get(attribute) or default_value instead of simply data.get(attribute, default_value):

{'my_key': None}.get('my_key', 'nothing') # returns None
{'my_key': None}.get('my_key') or 'nothing' # returns 'nothing'

In my applications getting attribute with value 'null' is the same as not getting the attribute at all. If your usage is different, you need to change this.

How to set character limit on the_content() and the_excerpt() in wordpress

You could use a Wordpress filter callback function. In your theme's directory, locate or create a file called functions.php and add the following in:

<?php   
  add_filter("the_content", "plugin_myContentFilter");

  function plugin_myContentFilter($content)
  {
    // Take the existing content and return a subset of it
    return substr($content, 0, 300);
  }
?>

The plugin_myContentFilter() is a function you provide that will be called each time you request the content of a post type like posts/pages via the_content(). It provides you with the content as an input, and will use whatever you return from the function for subsequent output or other filter functions.

You can also use add_filter() for other functions like the_excerpt() to provide a callback function whenever the excerpt is requested.

See the Wordpress filter reference docs for more details.

Replace image src location using CSS

You can use a background image

_x000D_
_x000D_
.application-title img {_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
  box-sizing:border-box;_x000D_
  padding-left: 200px;_x000D_
  /*width of the image*/_x000D_
  background: url(http://lorempixel.com/200/200/city/2) left top no-repeat;_x000D_
}
_x000D_
<div class="application-title">_x000D_
  <img src="http://lorempixel.com/200/200/city/1/">_x000D_
</div><br />_x000D_
Original Image: <br />_x000D_
_x000D_
<img src="http://lorempixel.com/200/200/city/1/">
_x000D_
_x000D_
_x000D_

Android Spinner : Avoid onItemSelected calls during initialization

This worked for me

Spinner's initialization in Android is problematic sometimes the above problem was solved by this pattern.

Spinner.setAdapter();
Spinner.setSelected(false);  // must
Spinner.setSelection(0,true);  //must
Spinner.setonItemSelectedListener(this);

Setting adapter should be first part and onItemSelectedListener(this) will be last when initializing a spinner. By the pattern above my OnItemSelected() is not called during initialization of spinner