Programs & Examples On #Speex

Speex is an open-source audio compression format designed for speech. It is based on CELP and is designed to compress voice at bitrates ranging from 2 to 44 kbps.

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

When to use MongoDB or other document oriented database systems?

I would say use an RDBMS if you need complex transactions. Otherwise I would go with MongoDB - more flexible to work with and you know it can scale when you need to. (I'm biased though - I work on the MongoDB project)

How to count items in JSON object using command line?

The shortest expression is

curl 'http://…' | jq length

what is the unsigned datatype?

unsigned really is a shorthand for unsigned int, and so defined in standard C.

Why does intellisense and code suggestion stop working when Visual Studio is open?

I had this problem when some of the dependent assemblies are changed but locked by an other instance of visual studio (2015).

Error Running React Native App From Terminal (iOS)

1) Go to Xcode Preferences

2) Locate the location tab

3) Set the Xcode verdion in Given Command Line Tools

Now, it ll successfully work.

Indirectly referenced from required .class file

This issue happen because of few jars are getting references from other jar and reference jar is missing .

Example : Spring framework

Description Resource    Path    Location    Type
The project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project   SpringBatch     Unknown Java Problem

In this case "org.springframework.beans.factory.annotation.Autowire" is missing.

Spring-bean.jar is missing

Once you add dependency in your class path issue will resolve.

When to use RDLC over RDL reports?

If we have fewer number of reports which are less complex and consumed by asp.net web pages. It's better to go with rdlc,reason is we can avoid maintaing reports on RS instance. but we have to fetch the data from DB manually and bind it to rdlc.

Cons:designing rdlc in visual studio is little difficult compared to SSrs designer.

Pro:Maintenance is easy. while exporting the report from we page,observed that performance gain compared to server side reports.

Automatically run %matplotlib inline in IPython Notebook

The setting was disabled in Jupyter 5.X and higher by adding below code

pylab = Unicode('disabled', config=True,
    help=_("""
    DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
    """)
)

@observe('pylab')
def _update_pylab(self, change):
    """when --pylab is specified, display a warning and exit"""
    if change['new'] != 'warn':
        backend = ' %s' % change['new']
    else:
        backend = ''
    self.log.error(_("Support for specifying --pylab on the command line has been removed."))
    self.log.error(
        _("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(backend)
    )
    self.exit(1)

And in previous versions it has majorly been a warning. But this not a big issue because Jupyter uses concepts of kernels and you can find kernel for your project by running below command

$ jupyter kernelspec list
Available kernels:
  python3    /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3

This gives me the path to the kernel folder. Now if I open the /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json file, I see something like below

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
 ],
 "display_name": "Python 3",
 "language": "python"
}

So you can see what command is executed to launch the kernel. So if you run the below command

$ python -m ipykernel_launcher --help
IPython: an enhanced interactive Python shell.

Subcommands
-----------

Subcommands are launched as `ipython-kernel cmd [args]`. For information on
using subcommand 'cmd', do: `ipython-kernel cmd -h`.

install
    Install the IPython kernel

Options
-------

Arguments that take values are actually convenience aliases to full
Configurables, whose aliases are listed on the help line. For more information
on full configurables, see '--help-all'.

....
--pylab=<CaselessStrEnum> (InteractiveShellApp.pylab)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Pre-load matplotlib and numpy for interactive use, selecting a particular
    matplotlib backend and loop integration.
--matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Configure matplotlib for interactive use with the default matplotlib
    backend.
...    
To see all available configurables, use `--help-all`

So now if we update our kernel.json file to

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
  "--pylab",
  "inline"
 ],
 "display_name": "Python 3",
 "language": "python"
}

And if I run jupyter notebook the graphs are automatically inline

Auto Inline

Note the below approach also still works, where you create a file on below path

~/.ipython/profile_default/ipython_kernel_config.py

c = get_config()
c.IPKernelApp.matplotlib = 'inline'

But the disadvantage of this approach is that this is a global impact on every environment using python. You can consider that as an advantage also if you want to have a common behaviour across environments with a single change.

So choose which approach you would like to use based on your requirement

Remove redundant paths from $PATH variable

Here is a one line code that cleans up the PATH

  • It does not disturb the order of the PATH, just removes duplicates
  • Treats : and empth PATH gracefully
  • No special characters used, so does not require escape
  • Uses /bin/awk so it works even when PATH is broken

    export PATH="$(echo "$PATH" |/bin/awk 'BEGIN{RS=":";}
    {sub(sprintf("%c$",10),"");if(A[$0]){}else{A[$0]=1;
    printf(((NR==1)?"":":")$0)}}')";
    

What does Maven do, in theory and in practice? When is it worth to use it?

From the Sonatype doc:

The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.

I'd strongly recommend looking at the Sonatype doc and spending some time looking at the available plugins to understand the power of Maven.

Very briefly, it operates at a higher conceptual level than (say) Ant. With Ant, you'd specify the set of files and resources that you want to build, then specify how you want them jarred together, and specify the order that should occur in (clean/compile/jar). With Maven this is all implicit. Maven expects to find your files in particular places, and will work automatically with that. Consequently setting up a project with Maven can be a lot simpler, but you have to play by Maven's rules!

How to throw an exception in C?

This question is super old, but I just stumbled across it and thought I'd share a technique: divide by zero, or dereference a null pointer.

The question is simply "how to throw", not how to catch, or even how to throw a specific type of exception. I had a situation ages ago where we needed to trigger an exception from C to be caught in C++. Specifically, we had occasional reports of "pure virtual function call" errors, and needed to convince the C runtime's _purecall function to throw something. So we added our own _purecall function that divided by zero, and boom, we got an exception that we could catch on C++, and even use some stack fun to see where things went wrong.

Ordering issue with date values when creating pivot tables

The problem I had was that although the source data was correctly formatted as 'date' dd/mm/yyyy, the pivot table placed (for example) 22/05/2019 between 16/05/2019 and 17/05/2019. This data was visible in the pivot table, but in the wrong place. In addition, the Pivot chart refused to show that data for that date even though the 'Date' filter allowed it to be selected.

In my case, I had to:

  1. From the Pivot Chart,open the 'Date' Filter menu.

  2. select the 'Sort Oldest to Newest' option.

  3. Bingo! The Pivot chart now shows the missing date data.

npm ERR! Error: EPERM: operation not permitted, rename

I am using macOS catalina ,

      npm init 

I got error

       operation not permitted, uv_cwd

in 2021, this is how you can fix this problem.

very simple:

step 1: go to parent folder

         cd ../
         

step 2: go to your project folder again,

         cd  your-project-folder

That is it. it works.

What is the difference between a symbolic link and a hard link?

Hard links are useful when the original file is getting moved around. For example, moving a file from /bin to /usr/bin or to /usr/local/bin. Any symlink to the file in /bin would be broken by this, but a hardlink, being a link directly to the inode for the file, wouldn't care.

Hard links may take less disk space as they only take up a directory entry, whereas a symlink needs its own inode to store the name it points to.

Hard links also take less time to resolve - symlinks can point to other symlinks that are in symlinked directories. And some of these could be on NFS or other high-latency file systems, and so could result in network traffic to resolve. Hard links, being always on the same file system, are always resolved in a single look-up, and never involve network latency (if it's a hardlink on an NFS filesystem, the NFS server would do the resolution, and it would be invisible to the client system). Sometimes this is important. Not for me, but I can imagine high-performance systems where this might be important.

I also think things like mmap(2) and even open(2) use the same functionality as hardlinks to keep a file's inode active so that even if the file gets unlink(2)ed, the inode remains to allow the process continued access, and only once the process closes it does the file really go away. This allows for much safer temporary files (if you can get the open and unlink to happen atomically, which there may be a POSIX API for that I'm not remembering, then you really have a safe temporary file) where you can read/write your data without anyone being able to access it. Well, that was true before /proc gave everyone the ability to look at your file descriptors, but that's another story.

Speaking of which, recovering a file that is open in process A, but unlinked on the file system revolves around using hardlinks to recreate the inode links so the file doesn't go away when the process which has it open closes it or goes away.

App.Config file in console application C#

You can add a reference to System.Configuration in your project and then:

using System.Configuration;

then

string sValue = ConfigurationManager.AppSettings["BatchFile"];

with an app.config file like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
       <add key="BatchFile" value="blah.bat" />
   </appSettings>
</configuration>

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

If someone is using AFHTTPSessionManager then one can do like this to solve the issue,

I subclassed AFHTTPSessionManager where I'm doing like this,

NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:self.responseSerializer.acceptableContentTypes];
[contentTypes addObject:@"text/html"];
self.responseSerializer.acceptableContentTypes = contentTypes;

IsNull function in DB2 SQL?

I'm not familiar with DB2, but have you tried COALESCE?

ie:


SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product

Extract a substring from a string in Ruby using a regular expression

You can use a regular expression for that pretty easily…

Allowing spaces around the word (but not keeping them):

str.match(/< ?([^>]+) ?>\Z/)[1]

Or without the spaces allowed:

str.match(/<([^>]+)>\Z/)[1]

WCF gives an unsecured or incorrectly secured fault error

Make sure your SendTimeout hasn't elapsed after opening the client.

REST API 404: Bad URI, or Missing Resource?

404 Not Found technically means that uri does not currently map to a resource. In your example, I interpret a request to http://mywebsite/api/user/13 that returns a 404 to imply that this url was never mapped to a resource. To the client, that should be the end of conversation.

To address concerns with ambiguity, you can enhance your API by providing other response codes. For example, suppose you want to allow clients to issue GET requests the url http://mywebsite/api/user/13, you want to communicate that clients should use the canonical url http://mywebsite/restapi/user/13. In that case, you may want to consider issuing a permanent redirect by returning a 301 Moved Permanently and supply the canonical url in the Location header of the response. This tells the client that for future requests they should use the canonical url.

Correct way to remove plugin from Eclipse

For some 'Eclipse Marketplace' plugins Uninstall may not work. (Ex: SonarLint v5)

So Try,

Help -> About Eclipse -> Installation details
  • search the plugin name in 'Installed Software'

  • Select plugin name and Uninstall it

Additional Detail

To fix plugin errors, after the uninstall revert back older version of plugin,

Help -> install new software..
  • Get plugin url from Google search and Add it (Example: https://eclipse-uc.sonarlint.org)

  • Select and install older versions of the Plugin. This will fix most of the plugin problems.

How to set the custom border color of UIView programmatically?

In Swift 4 you can set the border color and width to UIControls using below code.

let yourColor : UIColor = UIColor( red: 0.7, green: 0.3, blue:0.1, alpha: 1.0 )
yourControl.layer.masksToBounds = true
yourControl.layer.borderColor = yourColor.CGColor
yourControl.layer.borderWidth = 1.0

< Swift 4, You can set UIView's border width and border color using the below code.

yourView.layer.borderWidth = 1

yourView.layer.borderColor = UIColor.red.cgColor

How to compare binary files to check if they are the same?

For finding flash memory defects, I had to write this script which shows all 1K blocks which contain differences (not only the first one as cmp -b does)

#!/bin/sh

f1=testinput.dat
f2=testoutput.dat

size=$(stat -c%s $f1)
i=0
while [ $i -lt $size ]; do
  if ! r="`cmp -n 1024 -i $i -b $f1 $f2`"; then
    printf "%8x: %s\n" $i "$r"
  fi
  i=$(expr $i + 1024)
done

Output:

   2d400: testinput.dat testoutput.dat differ: byte 3, line 1 is 200 M-^@ 240 M- 
   2dc00: testinput.dat testoutput.dat differ: byte 8, line 1 is 327 M-W 127 W
   4d000: testinput.dat testoutput.dat differ: byte 37, line 1 is 270 M-8 260 M-0
   4d400: testinput.dat testoutput.dat differ: byte 19, line 1 is  46 &  44 $

Disclaimer: I hacked the script in 5 min. It doesn't support command line arguments nor does it support spaces in file names

How to shrink temp tablespace in oracle?

You should have written what version of Oracle you use. You most likely use something else than Oracle 11g, that's why you can't shrink a temp tablespace.

Alternatives:

1) alter database tempfile '[your_file]' resize 128M; which will probably fail
2) Drop and recreate the tablespace. If the temporary tablespace you want to shrink is your default temporary tablespace, you may have to first create a new temporary tablespace, set it as the default temporary tablespace then drop your old default temporary tablespace and recreate it. Afterwards drop the second temporary table created. 3) For Oracle 9i and higher you could just drop the tempfile(s) and add a new one(s)

Everything is described here in great detail.


See this link: http://databaseguide.blogspot.com/2008/06/resizing-temporary-tablespace.html
It was already linked, but maybe you missed it, so here it is again.

Switch with if, else if, else, and loops inside case

Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:

boolean found = false;

case 1:

for (Element arrayItem : array) {
    if (arrayItem == whateverValue) {
        found = true;    
    } // else if ...
}
if (found) {
    break;
}
case 2:

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

From Now() to Current_timestamp in Postgresql

select * from table where column_date > now()- INTERVAL '6 hours';

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Gustavomcls's solution to change com.google.* version to same version worked for me .

I change both dependancies to 9.2.1 in buid.gradle (Module:app)

compile 'com.google.firebase:firebase-ads:9.2.1'
compile 'com.google.android.gms:play-services:9.2.1'

Javascript (+) sign concatenates instead of giving sum of variables

Since you are concatenating numbers on to a string, the whole thing is treated as a string. When you want to add numbers together, you either need to do it separately and assign it to a var and use that var, like this:

i = i + 1;
divID = "question-" + i;

Or you need to specify the number addition like this:

divID = "question-" + Number(i+1);

EDIT

I should have added this long ago, but based on the comments, this works as well:

divID = "question-" + (i+1);

indexOf Case Sensitive?

There is an ignore case method in StringUtils class of Apache Commons Lang library

indexOfIgnoreCase(CharSequence str, CharSequence searchStr)

Setting background images in JFrame

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class BackgroundImageJFrame extends JFrame
{

    JButton b1;
    JLabel l1;

    public BackgroundImageJFrame() {

        setSize(400,400);
        setVisible(true);

        setLayout(new BorderLayout());

        JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful_design.png"));

        add(background);

        background.setLayout(new FlowLayout());

        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");

        background.add(l1);
        background.add(b1);
    }

    public static void main(String args[]) 
    {
        new BackgroundImageJFrame();
    }
}

check out the below link

http://java-demos.blogspot.in/2012/09/setting-background-image-in-jframe.html

Iterate over each line in a string in PHP

If you need to handle newlines in diferent systems you can simply use the PHP predefined constant PHP_EOL (http://php.net/manual/en/reserved.constants.php) and simply use explode to avoid the overhead of the regular expression engine.

$lines = explode(PHP_EOL, $subject);

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

Expand a random range from 1–5 to 1–7

This is the answer I came up with but these complicated answers are making me think this is completely off/ :))

import random

def rand5():
    return float(random.randint(0,5))

def rand7():
    random_val = rand5()
    return float(random.randint((random_val-random_val),7))

print rand7()

BackgroundWorker vs background Thread

You know, sometimes it's just easier to work with a BackgroundWorker regardless of if you're using Windows Forms, WPF or whatever technology. The neat part about these guys is you get threading without having to worry too much about where you're thread is executing, which is great for simple tasks.

Before using a BackgroundWorker consider first if you wish to cancel a thread (closing app, user cancellation) then you need to decide if your thread should check for cancellations or if it should be thrust upon the execution itself.

BackgroundWorker.CancelAsync() will set CancellationPending to true but won't do anything more, it's then the threads responsibility to continually check this, keep in mind also that you could end up with a race condition in this approach where your user cancelled, but the thread completed prior to testing for CancellationPending.

Thread.Abort() on the other hand will throw an exception within the thread execution which enforces cancellation of that thread, you must be careful about what might be dangerous if this exception was suddenly raised within the execution though.

Threading needs very careful consideration no matter what the task, for some further reading:

Parallel Programming in the .NET Framework Managed Threading Best Practices

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)

    [Table("UserOtherEntity")]
        public partial class UserOtherEntity
        {
            public Guid UserOtherEntityId { get; set; }
            [Required]
            [StringLength(128)]
            public string UserId { get; set; }
            [Required]
            public Guid OtherEntityId { get; set; }
            public virtual OtherEntity OtherEntity { get; set; }
        }

    public partial class UserOtherEntity : DataManager
        {
            public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
            {
                return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
            }
        }

public partial class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        [NotMapped]
        public IEnumerable<OtherEntity> OtherEntities
        {
            get
            {
                return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
            }
        }
    }

Update a column in MySQL

UPDATE table1 SET col_a = 'newvalue'

Add a WHERE condition if you want to only update some of the rows.

How to control the width and height of the default Alert Dialog in Android?

If you wanna add dynamic width and height based on your device frame, you can do these calculations and assign the height and width.

 AlertDialog.Builder builderSingle = new 
 AlertDialog.Builder(getActivity());
 builderSingle.setTitle("Title");

 final AlertDialog alertDialog = builderSingle.create();
 alertDialog.show();

 Rect displayRectangle = new Rect();
 Window window = getActivity().getWindow();

 window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

 alertDialog.getWindow().setLayout((int)(displayRectangle.width() * 
 0.8f), (int)(displayRectangle.height() * 0.8f));

P.S : Show the dialog first and then try to modify the window's layout attributes

How to sort Map values by key in Java?

Assuming TreeMap is not good for you (and assuming you can't use generics):

List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1 is null or ConfigurationManager.AppSettings.Get("Url") is returning null.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Closing database connections in Java

Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.

You should do this with any object that implements AutoClosable.

try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
    String sqlToExecute = "SELECT * FROM persons";
    try (ResultSet resultSet = statement.execute(sqlToExecute)) {
        if (resultSet.next()) {
            System.out.println(resultSet.getString("name");
        }
    }
} catch (SQLException e) {
    System.out.println("Failed to select persons.");
}

The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.

How do you convert WSDLs to Java classes using Eclipse?

Using command prompt in windows you can use below command to get class files.

wsimport "complete file path of your .wsdl file"
example : wsimport C:\Users\schemas\com\myprofile\myprofile2019.wsdl

if you want to generate source code you should be using below commnad.

wsimport -keep -s src "complete file path of your .wsdl file"
example : wsimport -keep -s src C:\Users\schemas\com\myprofile\myprofile2019.wsdl

Note : Here "-s" means source directory and "src" is name of folder that should be created before executing this command. Wsimport is a tool which is bundled along with JAVA SE, no seperate download is required.

Android Studio cannot resolve R in imported project?

check the build tools version in build.gradle(for module app). Then go to android sdk manager see if the version is installed if not install it or change the build tools version to the one which is installed like below.

    android {
          buildToolsVersion "22.0.1"
          ..
          ..
          ..
     }

How can I view the shared preferences file using Android Studio?

Single or Multiple Shared Preference Files

If you have multiple Shared Preference files, then here is a good way to show all of them, but you can just pass in 1 filename, too.

  • loadSharedPrefs("pref_name");

  • loadSharedPrefs("shared_pref1", "shared_pref2", "shared_pref3");

Choose one of the following to suit your needs...

Single-Type Values

public void loadSharedPrefs(String ... prefs) {

    // Logging messages left in to view Shared Preferences. I filter out all logs except for ERROR; hence why I am printing error messages.

    Log.i("Loading Shared Prefs", "-----------------------------------");
    Log.i("----------------", "---------------------------------------");

    for (String pref_name: prefs) {

        SharedPreferences preference = getSharedPreferences(pref_name, MODE_PRIVATE);
        for (String key : preference.getAll().keySet()) {

            Log.i(String.format("Shared Preference : %s - %s", pref_name, key),
                  preference.getString(key, "error!"));

        }

        Log.i("----------------", "---------------------------------------");

    }

    Log.i("Finished Shared Prefs", "----------------------------------");

}

Multiple-Type Values

public void loadSharedPrefs(String ... prefs) {

    // Define default return values. These should not display, but are needed
    final String STRING_ERROR = "error!";
    final Integer INT_ERROR = -1;
    // ...
    final Set<String> SET_ERROR = new HashSet<>(1);

    // Add an item to the set
    SET_ERROR.add("Set Error!");

    // Loop through the Shared Prefs
    Log.i("Loading Shared Prefs", "-----------------------------------");
    Log.i("------------------", "-------------------------------------");

    for (String pref_name: prefs) {

        SharedPreferences preference = getSharedPreferences(pref_name, MODE_PRIVATE);
        Map<String, ?> prefMap = preference.getAll();

        Object prefObj;
        Object prefValue = null;

        for (String key : prefMap.keySet()) {

            prefObj = prefMap.get(key);

            if (prefObj instanceof String) prefValue = preference.getString(key, STRING_ERROR);
            if (prefObj instanceof Integer) prefValue = preference.getInt(key, INT_ERROR);
            // ...
            if (prefObj instanceof Set) prefValue = preference.getStringSet(key, SET_ERROR);

            Log.i(String.format("Shared Preference : %s - %s", pref_name, key),
                  String.valueOf(prefValue));

        }

        Log.i("------------------", "-------------------------------------");

    }

    Log.i("Loaded Shared Prefs", "------------------------------------");

}

}

Logcat Output

My Shared Preference values are all String, but this is the output using either of the 2 methods above...

I/Loading Shared Prefs? -----------------------------------
I/------------------? -------------------------------------
I/Shared Preference : FAVORITE - 135397? Jurassic World
I/Shared Preference : FAVORITE - 87101? Terminator Genisys
I/Shared Preference : FAVORITE - 177677? Mission: Impossible – Rogue Nation
I/------------------? -------------------------------------
I/Shared Preference : WATCHED - 177677? Mission: Impossible – Rogue Nation
I/Shared Preference : WATCHED - 157336? Interstellar
I/Shared Preference : WATCHED - 135397? Jurassic World
I/Shared Preference : WATCHED - 87101? Terminator Genisys
I/------------------? -------------------------------------
I/Shared Preference : WILL_WATCH - 211672? Minions
I/Shared Preference : WILL_WATCH - 102899? Ant-Man
I/------------------? -------------------------------------
I/Loaded Shared Prefs? ------------------------------------

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

TensorFlow not found using pip

I've found out the problem.

I'm using a Windows computer which has Python 2 installed previously. After Python 3 is installed (without setting the path, I successfully check the version of pip3 - but the python executable file still points to the Python2)

Then I set the path to the python3 executable file (remove all python2 paths) then start a new command prompt, try to reinstall Tensorflow. It works!

I think this problem could happend on MAC OS too since there is a default python which is on the MAC system.

What is the difference between printf() and puts() in C?

puts is simpler than printf but be aware that the former automatically appends a newline. If that's not what you want, you can fputs your string to stdout or use printf.

Uploading/Displaying Images in MVC 4

        <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }

Select data from date range between two dates

Please try:

DECLARE @FrmDt DATETIME, @ToDt DATETIME
SELECT @FrmDt='2013-01-03', @ToDt='2013-01-09'

SELECT * 
FROM Product_sales 
WHERE (@FrmDt BETWEEN From_date AND To_date) OR 
    (@ToDt BETWEEN From_date AND To_date)

Getting SyntaxError for print with keyword argument end=' '

First of all, you're missing a quote at the beginning but this is probably a copy/paste error.

In Python 3.x, the end=' ' part will place a space after the displayed string instead of a newline. To do the same thing in Python 2.x, you'd put a comma at the end:

print "Building internam Index for %d tile(s) ..." % len(inputTiles),

Difference between "char" and "String" in Java

A char consists of a single character and should be specified in single quotes. It can contain an alphabetic, numerical or even special character. below are a few examples:

char a = '4';
char b = '$';
char c = 'B';

A String defines a line can be used which is specified in double quotes. Below are a few examples:

String a = "Hello World";
String b = "1234";
String c = "%%";

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

GIT: Checkout to a specific folder

Another solution which is a bit cleaner - just specify a different work tree.

To checkout everything from your HEAD (not index) to a specific out directory:

git --work-tree=/path/to/outputdir checkout HEAD -- .

To checkout a subdirectory or file from your HEAD to a specific directory:

git --work-tree=/path/to/outputdir checkout HEAD -- subdirname

What is the difference between a HashMap and a TreeMap?

I'll talk about the HashMap and TreeMap implementation in Java:

  • HashMap -- implement basic map interface

    1. implemented by an array of buckets, each bucket is a LinkedList of entries
    2. running time of basic operations: put(), average O(1), worst case O(n), happens when the table is resized; get(), remove(), average O(1)
    3. not synchronized, to synchronize it: Map m = Collections.synchronizedMap(new HashMap(...));
    4. Iteration order of the map is unpredictable.
  • TreeMap -- implement navigable map interface

    1. implemented by a red-black tree
    2. running time of basic operations: put(), get(), remove(), worst case O(lgn)
    3. not synchronized, to synchronize it: SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
    4. provide ordered iteration. higherKey(), lowerKey() can be used to get the successor and predecessor of a given key.

To sum, the biggest difference between HashMap and TreeMap is that TreeMap implements NavigableMap<K,V>, which provide the feature of ordered iteration. Besides, both HashMap and TreeMap are members of Java Collection framework. You can investigate the source code of Java to know more about their implementations.

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Check the target definition if you are working with an RCP-SWT project.

Open the target editor of and navigate to the environent definition. There you can set the architecture. The idea is that by starting up your RCP application then only the 32 bit SWT libraries/bundles will be loaded. If you have already a runtime configuration it is advisable to create a new one as well.

Target Editor in Eclipse

Can I have multiple Xcode versions installed?

  1. First, remove the current Xcode installation from your machine. You can probably skip this step but I wanted to start fresh. Plus — Xcode was behaving a little weird lately so this is a good opportunity to do that.
  2. Install Xcode 8 from the App Store. Make sure project files (.xcodeproj) and workspace files (.xcworkspace) can be opened with the new Xcode installation (remember to select the Later option whenever prompted).
  3. Download the Xcode 7.3.1 dmg file from Apple. Double-tap the newly downloaded dmg file in order to get the standard “Drag to install Xcode in your Applications folder”. Don’t do that. Instead, drag the Xcode icon to the desktop. Change the file name to Xcode 7.3.1. Now drag it to the Applications folder.

Now you have two versions of Xcode installed on your machine. Xcode 7.3.1 and Xcode 8.

Details: Install Xcode 7 & Xcode 8 side by side

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

For those who are having this issue through a VS client side once successfully added a service reference and trying to execute the first call got this exception: “The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel” If you are using (like my case) an endpoint URL with the IP address and got this exception, then you should probably need to re-add the service reference doing this steps:

  • Open the endpoint URL on Internet Explorer.
  • Click on the certificate error (red icon in address bar)
  • Click on View certificates.
  • Grab the issued to: "name" and replace the IP address or whatever name we were using and getting the error for this "name".

Try again :). Thanks

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

People using Java 9 include this dependency:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

Get program path in VB.NET?

You can also use:

Dim strPath As String = AppDomain.CurrentDomain.BaseDirectory

How to add elements of a Java8 stream into an existing List

As far as I can see, all other answers so far used a collector to add elements to an existing stream. However, there's a shorter solution, and it works for both sequential and parallel streams. You can simply use the method forEachOrdered in combination with a method reference.

List<String> source = ...;
List<Integer> target = ...;

source.stream()
      .map(String::length)
      .forEachOrdered(target::add);

The only restriction is, that source and target are different lists, because you are not allowed to make changes to the source of a stream as long as it is processed.

Note that this solution works for both sequential and parallel streams. However, it does not benefit from concurrency. The method reference passed to forEachOrdered will always be executed sequentially.

How to check type of files without extensions in python?

There are Python libraries that can recognize files based on their content (usually a header / magic number) and that don't rely on the file name or extension.

If you're addressing many different file types, you can use python-magic. That's just a Python binding for the well-established magic library. This has a good reputation and (small endorsement) in the limited use I've made of it, it has been solid.

There are also libraries for more specialized file types. For example, the Python standard library has the imghdr module that does the same thing just for image file types.

If you need dependency-free (pure Python) file type checking, see filetype.

Can the :not() pseudo-class have multiple arguments?

If you install the "cssnext" Post CSS plugin, then you can safely start using the syntax that you want to use right now.

Using cssnext will turn this:

input:not([type="radio"], [type="checkbox"]) {
  /* css here */
}

Into this:

input:not([type="radio"]):not([type="checkbox"]) {
  /* css here */
}

https://cssnext.github.io/features/#not-pseudo-class

Displaying tooltip on mouse hover of a text

Just add ToolTip tool from toolbox to the form and add this code in a mousemove event of any control you want to make the tooltip start on its mousemove

private void textBox3_MouseMove(object sender, MouseEventArgs e)
    {
      toolTip1.SetToolTip(textBox3,"Tooltip text"); // you can change the first parameter (textbox3) on any control you wanna focus
    }

hope it helps

peace

How do you Change a Package's Log Level using Log4j?

I just encountered the issue and couldn't figure out what was going wrong even after reading all the above and everything out there. What I did was

  1. Set root logger level to WARN
  2. Set package log level to DEBUG

Each logging implementation has it's own way of setting it via properties or via code(lot of help available on this)

Irrespective of all the above I would not get the logs in my console or my log file. What I had overlooked was the below...


enter image description here


All I was doing with the above jugglery was controlling only the production of the logs(at root/package/class etc), left of the red line in above image. But I was not changing the way displaying/consumption of the logs of the same, right of the red line in above image. Handler(Consumption) is usually defaulted at INFO, therefore your precious debug statements wouldn't come through. Consumption/displaying is controlled by setting the log levels for the Handlers(ConsoleHandler/FileHandler etc..) So I went ahead and set the log levels of all my handlers to finest and everything worked.

This point was not made clear in a precise manner in any place.

I hope someone scratching their head, thinking why the properties are not working will find this bit helpful.

How to pass integer from one Activity to another?

Their are two methods you can use to pass an integer. One is as shown below.

A.class

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

B.class

Intent intent = getIntent();
int intValue = intent.getIntExtra("intVariableName", 0);

The other method converts the integer to a string and uses the following code.

A.class

Intent intent = new Intent(A.this, B.class);
Bundle extras = new Bundle();
extras.putString("StringVariableName", intValue + "");
intent.putExtras(extras);
startActivity(intent);

The code above will pass your integer value as a string to class B. On class B, get the string value and convert again as an integer as shown below.

B.class

   Bundle extras = getIntent().getExtras();
   String stringVariableName = extras.getString("StringVariableName");
   int intVariableName = Integer.parseInt(stringVariableName);

How do I mock a service that returns promise in AngularJS Jasmine unit test?

I'm not sure why the way you did it doesn't work, but I usually do it with the spyOn function. Something like this:

describe('Testing remote call returning promise', function() {
  var myService;

  beforeEach(module('app.myService'));

  beforeEach(inject( function(_myService_, myOtherService, $q){
    myService = _myService_;
    spyOn(myOtherService, "makeRemoteCallReturningPromise").and.callFake(function() {
        var deferred = $q.defer();
        deferred.resolve('Remote call result');
        return deferred.promise;
    });
  }

  it('can do remote call', inject(function() {
    myService.makeRemoteCall()
      .then(function() {
        console.log('Success');
      });    
  }));

Also remember that you will need to make a $digest call for the then function to be called. See the Testing section of the $q documentation.

------EDIT------

After looking closer at what you're doing, I think I see the problem in your code. In the beforeEach, you're setting myOtherServiceMock to a whole new object. The $provide will never see this reference. You just need to update the existing reference:

beforeEach(inject( function(_myService_, $q){
    myService = _myService_;
    myOtherServiceMock.makeRemoteCallReturningPromise = function() {
        var deferred = $q.defer();
        deferred.resolve('Remote call result');
        return deferred.promise;   
    };
  }

Executing <script> injected by innerHTML after AJAX call

I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div

Pass parameters in setInterval function

You can pass the parameter(s) as a property of the function object, not as a parameter:

var f = this.someFunction;  //use 'this' if called from class
f.parameter1 = obj;
f.parameter2 = this;
f.parameter3 = whatever;
setInterval(f, 1000);

Then in your function someFunction, you will have access to the parameters. This is particularly useful inside classes where the scope goes to the global space automatically and you lose references to the class that called setInterval to begin with. With this approach, "parameter2" in "someFunction", in the example above, will have the right scope.

using jquery $.ajax to call a PHP function

I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).

You basically send a JSON string in a specific format to the server, e.g.

{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}

which includes the function to call and the parameters of that function.

Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.


This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

I have read carefully all the answers above, but none of them solved my problem.

In my case, I was compiling a class library (DLL). No modules seem to be loaded in Debug -> Modules, so I couldn't even load the symbols manually.

My solution was to add this line to my code:

System.Diagnostics.Debugger.Launch();

Once this code is reached, an exception is triggered and .NET Framework shows a dialog box asking which Visual Studio (i.e. new instance of VS 2008, new instance of VS 2013, etc) you want to use to debug the program. You can choose the existing instance of VS with your project loaded. This will attach the process to your VS session and load all symbols, and now you can debug your project.

Of course, the compilation has to be done using the Debug configuration, not Release.

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

UITableView - scroll to the top

Swift 3

tableView.setContentOffset(CGPoint.zero, animated: true)

if tableView.setContentOffset don't work.

Use:

tableView.beginUpdates()
tableView.setContentOffset(CGPoint.zero, animated: true)
tableView.endUpdates()

How can I create database tables from XSD files?

Commercial Product: Altova's XML Spy.

Note that there's no general solution to this. An XSD can easily describe something that does not map to a relational database.

While you can try to "automate" this, your XSD's must be designed with a relational database in mind, or it won't work out well.

If the XSD's have features that don't map well you'll have to (1) design a mapping of some kind and then (2) write your own application to translate the XSD's into DDL.

Been there, done that. Work for hire -- no open source available.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.

SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';

Check mySQL version on Mac 10.8.5

Or just call mysql command with --version option.

mysql --version

std::vector versus std::array in C++

If you are considering using multidimensional arrays, then there is one additional difference between std::array and std::vector. A multidimensional std::array will have the elements packed in memory in all dimensions, just as a c style array is. A multidimensional std::vector will not be packed in all dimensions.

Given the following declarations:

int cConc[3][5];
std::array<std::array<int, 5>, 3> aConc;
int **ptrConc;      // initialized to [3][5] via new and destructed via delete
std::vector<std::vector<int>> vConc;    // initialized to [3][5]

A pointer to the first element in the c-style array (cConc) or the std::array (aConc) can be iterated through the entire array by adding 1 to each preceding element. They are tightly packed.

A pointer to the first element in the vector array (vConc) or the pointer array (ptrConc) can only be iterated through the first 5 (in this case) elements, and then there are 12 bytes (on my system) of overhead for the next vector.

This means that a std::vector> array initialized as a [3][1000] array will be much smaller in memory than one initialized as a [1000][3] array, and both will be larger in memory than a std:array allocated either way.

This also means that you can't simply pass a multidimensional vector (or pointer) array to, say, openGL without accounting for the memory overhead, but you can naively pass a multidimensional std::array to openGL and have it work out.

(HTML) Download a PDF file instead of opening them in browser when clicked

you will need to use a PHP script (or an other server side language for this)

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

and use httacces to redirect (rewrite) to the PHP file instead of the pdf

Git: How do I list only local branches?

just the plain command

git branch

Align an element to bottom with flexbox

The solution with align-self: flex-end; didn't work for me but this one did in case you want to use flex:

Result

 -------------------
|heading 1          |
|heading 2          | 
|paragraph text     |
|                   |
|                   |
|                   | 
|link button        |
 -------------------

Code

Note: When "running the code snippet" you have to scroll down to see the link at the bottom.

_x000D_
_x000D_
.content {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  flex-direction: column;_x000D_
  height: 300px;_x000D_
}_x000D_
_x000D_
.content .upper {_x000D_
  justify-content: normal;_x000D_
}_x000D_
_x000D_
/* Just to show container boundaries */_x000D_
.content .upper, .content .bottom, .content .upper > * {_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="upper">_x000D_
   <h1>heading 1</h1>_x000D_
   <h2>heading 2</h2>_x000D_
   <p>paragraph text</p>_x000D_
  </div>_x000D_
_x000D_
  <div class="bottom">_x000D_
   <a href="/" class="button">link button</a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Forcing to download a file using PHP

Configure your server to send the file with the media type application/octet-stream.

Behaviour of increment and decrement operators in Python

Yeah, I missed ++ and -- functionality as well. A few million lines of c code engrained that kind of thinking in my old head, and rather than fight it... Here's a class I cobbled up that implements:

pre- and post-increment, pre- and post-decrement, addition,
subtraction, multiplication, division, results assignable
as integer, printable, settable.

Here 'tis:

class counter(object):
    def __init__(self,v=0):
        self.set(v)

    def preinc(self):
        self.v += 1
        return self.v
    def predec(self):
        self.v -= 1
        return self.v

    def postinc(self):
        self.v += 1
        return self.v - 1
    def postdec(self):
        self.v -= 1
        return self.v + 1

    def __add__(self,addend):
        return self.v + addend
    def __sub__(self,subtrahend):
        return self.v - subtrahend
    def __mul__(self,multiplier):
        return self.v * multiplier
    def __div__(self,divisor):
        return self.v / divisor

    def __getitem__(self):
        return self.v

    def __str__(self):
        return str(self.v)

    def set(self,v):
        if type(v) != int:
            v = 0
        self.v = v

You might use it like this:

c = counter()                          # defaults to zero
for listItem in myList:                # imaginary task
     doSomething(c.postinc(),listItem) # passes c, but becomes c+1

...already having c, you could do this...

c.set(11)
while c.predec() > 0:
    print c

....or just...

d = counter(11)
while d.predec() > 0:
    print d

...and for (re-)assignment into integer...

c = counter(100)
d = c + 223 # assignment as integer
c = c + 223 # re-assignment as integer
print type(c),c # <type 'int'> 323

...while this will maintain c as type counter:

c = counter(100)
c.set(c + 223)
print type(c),c # <class '__main__.counter'> 323

EDIT:

And then there's this bit of unexpected (and thoroughly unwanted) behavior,

c = counter(42)
s = '%s: %d' % ('Expecting 42',c) # but getting non-numeric exception
print s

...because inside that tuple, getitem() isn't what used, instead a reference to the object is passed to the formatting function. Sigh. So:

c = counter(42)
s = '%s: %d' % ('Expecting 42',c.v) # and getting 42.
print s

...or, more verbosely, and explicitly what we actually wanted to happen, although counter-indicated in actual form by the verbosity (use c.v instead)...

c = counter(42)
s = '%s: %d' % ('Expecting 42',c.__getitem__()) # and getting 42.
print s

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Differences in In python 2 and 3 version:

If you already have a default method in a class with same name and you re-declare as a same name it will appear as unbound-method call of that class instance when you wanted to instantiated it.

If you wanted class methods, but you declared them as instance methods instead.

An instance method is a method that is used when to create an instance of the class.

An example would be

   def user_group(self):   #This is an instance method
        return "instance method returning group"

Class label method:

   @classmethod
   def user_group(groups):   #This is an class-label method
        return "class method returning group"

In python 2 and 3 version differ the class @classmethod to write in python 3 it automatically get that as a class-label method and don't need to write @classmethod I think this might help you.

'JSON' is undefined error in JavaScript in Internet Explorer

I had this error 2 times. Each time it was solved by changing the ajax type. Either GET to POST or POST to GET.

$.ajax({
        type:'GET', // or 'POST'
        url: "file.cfm?action=get_table&varb=" + varb
    });

How to import Maven dependency in Android Studio/IntelliJ?

Try itext. Add dependency to your build.gradle for latest as of this post

Note: special version for android, trailing "g":

dependencies {
    compile 'com.itextpdf:itextg:5.5.9'
}

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

I had this problem because of a trigger not working..Worked after I deleted the trigger.

Print Html template in Angular 2 (ng-print in Angular 2)

you can do like this in angular 2

in ts file

 export class Component{          
      constructor(){
      }
       printToCart(printSectionId: string){
        let popupWinindow
        let innerContents = document.getElementById(printSectionId).innerHTML;
        popupWinindow = window.open('', '_blank', 'width=600,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWinindow.document.open();
        popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + innerContents + '</html>');
        popupWinindow.document.close();
  }

 }

in html

<div id="printSectionId" >
  <div>
    <h1>AngularJS Print html templates</h1>
    <form novalidate>
      First Name:
      <input type="text"  class="tb8">
      <br>
      <br> Last Name:
      <input type="text"  class="tb8">
      <br>
      <br>
      <button  class="button">Submit</button>
      <button (click)="printToCart('printSectionId')" class="button">Print</button>
    </form>
  </div>
  <div>
    <br/>
   </div>
</div>

Access multiple elements of list knowing their index

You can use operator.itemgetter:

from operator import itemgetter 
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)

Or you can use numpy:

import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]

But really, your current solution is fine. It's probably the neatest out of all of them.

Curl : connection refused

127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.

Generate insert script for selected records?

You could create a view with your criteria and then export the view?

How to scroll the page when a modal dialog is longer than the screen?

Window Page Scrollbar clickable when Modal is open

This one works for me. Pure CSS.

<style type="text/css">

body.modal-open {
padding-right: 17px !important;
}

.modal-backdrop.in {
margin-right: 16px; 

</style>

Try it and let me know

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

How to declare and use 1D and 2D byte arrays in Verilog?

In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:

module tb;

byte b [4];

initial begin
    foreach (b[i]) b[i] = 1 << i;
    foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
    $finish;
end

endmodule

This prints out:

Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000

This is similar in concept to Marty's reg [7:0] a [0:3];. However, byte is a 2-state data type (0 and 1), but reg is 4-state (01xz). Using byte also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i]) loop syntax.

The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.

Sending email with PHP from an SMTP server

For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.

sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"

Then even the lowly mail() function can work with SMTP goodness. It is super useful if you're trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

is soft link of

/etc/ssl/openssl.cnf

You can see that using long list (ls -l) on the /usr/local/ssl/ directory where you will find

lrwxrwxrwx 1 root root 20 Mar 1 05:15 openssl.cnf -> /etc/ssl/openssl.cnf

The SQL OVER() clause - when and why is it useful?

You can use GROUP BY SalesOrderID. The difference is, with GROUP BY you can only have the aggregated values for the columns that are not included in GROUP BY.

In contrast, using windowed aggregate functions instead of GROUP BY, you can retrieve both aggregated and non-aggregated values. That is, although you are not doing that in your example query, you could retrieve both individual OrderQty values and their sums, counts, averages etc. over groups of same SalesOrderIDs.

Here's a practical example of why windowed aggregates are great. Suppose you need to calculate what percent of a total every value is. Without windowed aggregates you'd have to first derive a list of aggregated values and then join it back to the original rowset, i.e. like this:

SELECT
  orig.[Partition],
  orig.Value,
  orig.Value * 100.0 / agg.TotalValue AS ValuePercent
FROM OriginalRowset orig
  INNER JOIN (
    SELECT
      [Partition],
      SUM(Value) AS TotalValue
    FROM OriginalRowset
    GROUP BY [Partition]
  ) agg ON orig.[Partition] = agg.[Partition]

Now look how you can do the same with a windowed aggregate:

SELECT
  [Partition],
  Value,
  Value * 100.0 / SUM(Value) OVER (PARTITION BY [Partition]) AS ValuePercent
FROM OriginalRowset orig

Much easier and cleaner, isn't it?

What is the reason for the error message "System cannot find the path specified"?

There is not only 1 %SystemRoot%\System32 on Windows x64. There are 2 such directories.

The real %SystemRoot%\System32 directory is for 64-bit applications. This directory contains a 64-bit cmd.exe.

But there is also %SystemRoot%\SysWOW64 for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32. It contains a 32-bit cmd.exe.

32-bit applications can access %SystemRoot%\System32 for 64-bit applications by using the alias %SystemRoot%\Sysnative in path.

For more details see the Microsoft documentation about File System Redirector.

So the subdirectory run was created either in %SystemRoot%\System32 for 64-bit applications and 32-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\SysWOW64 which is %SystemRoot%\System32 for 32-bit cmd.exe or the subdirectory run was created in %SystemRoot%\System32 for 32-bit applications and 64-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\System32 as this subdirectory exists only in %SystemRoot%\SysWOW64.

The following code could be used at top of the batch file in case of subdirectory run is in %SystemRoot%\System32 for 64-bit applications:

@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"

Every console application in System32\run directory must be executed with %SystemPath% in the batch file, for example %SystemPath%\run\YourApp.exe.

How it works?

There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32 as defined at top.

But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative. In this case the batch file is processed currently by 32-bit cmd.exe and only in this case %SystemRoot%\Sysnative needs to be used at all. Otherwise %SystemRoot%\System32 can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe, this is the directory containing the 64-bit console applications (and the subdirectory run).

Note: %SystemRoot%\Sysnative is not a directory! It is not possible to cd to %SystemRoot%\Sysnative or use if exist %SystemRoot%\Sysnative or if exist %SystemRoot%\Sysnative\. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe or more general if exist %SystemRoot%\Sysnative\*.

Combining COUNT IF AND VLOOK UP EXCEL

Try this:

=IF(NOT(ISERROR(MATCH(A3,worksheet2!A:A,0))),COUNTIF(worksheet2!A:A,A3),"No Match Found")

Simple and clean way to convert JSON string to Object in Swift

For iOS 10 & Swift 3, using Alamofire & Gloss:

Alamofire.request("http://localhost:8080/category/en").responseJSON { response in

if let data = response.data {

    if let categories = [Category].from(data: response.data) {

        self.categories = categories

        self.categoryCollectionView.reloadData()
    } else {

        print("Casting error")
    }
  } else {

    print("Data is null")
  }
}

and here is the Category class

import Gloss

struct Category: Decodable {

    let categoryId: Int?
    let name: String?
    let image: String?

    init?(json: JSON) {
        self.categoryId = "categoryId" <~~ json
        self.name = "name" <~~ json
        self.image = "image" <~~ json
    }
}

IMO, this is by far the most elegant solution.

Using iText to convert HTML to PDF

Use itext libray:

Here is the sample code. It is working perfectly fine:

        String htmlFilePath = filePath + ".html";
        String pdfFilePath = filePath + ".pdf";

        // create an html file on given file path
        Writer unicodeFileWriter = new OutputStreamWriter(new FileOutputStream(htmlFilePath), "UTF-8");
        unicodeFileWriter.write(document.toString());
        unicodeFileWriter.close();

        ConverterProperties properties = new ConverterProperties();
        properties.setCharset("UTF-8");
        if (url.contains(".kr") || url.contains(".tw") || url.contains(".cn") || url.contains(".jp")) {
            properties.setFontProvider(new DefaultFontProvider(false, false, true));
        }

        // convert the html file to pdf file.
        HtmlConverter.convertToPdf(new File(htmlFilePath), new File(pdfFilePath), properties);

Maven dependencies

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext7-core</artifactId>
        <version>7.1.6</version>
        <type>pom</type>
    </dependency>

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>html2pdf</artifactId>
        <version>2.1.3</version>
    </dependency>

vertical & horizontal lines in matplotlib

This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.

The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].

On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin and xmax are the in the range of data limit of x axis.

Let's take a concrete example,

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 100)
y = np.sin(x)

fig, ax = plt.subplots()

ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')

plt.show()

It will produce the following plot: enter image description here

The value for xmin and xmax are the same for the axhline and hlines method. But the length of produced line is different.

Sort Pandas Dataframe by Date

@JAB's answer is fast and concise. But it changes the DataFrame you are trying to sort, which you may or may not want.

(Note: You almost certainly will want it, because your date columns should be dates, not strings!)

In the unlikely event that you don't want to change the dates into dates, you can also do it a different way.

First, get the index from your sorted Date column:

In [25]: pd.to_datetime(df.Date).order().index
Out[25]: Int64Index([0, 2, 1], dtype='int64')

Then use it to index your original DataFrame, leaving it untouched:

In [26]: df.ix[pd.to_datetime(df.Date).order().index]
Out[26]: 
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

Magic!

Note: for Pandas versions 0.20.0 and later, use loc instead of ix, which is now deprecated.

How do I convert an integer to binary in JavaScript?

This is the solution . Its quite simple as a matter of fact

function binaries(num1){ 
        var str = num1.toString(2)
        return(console.log('The binary form of ' + num1 + ' is: ' + str))
     }
     binaries(3

)

        /*
         According to MDN, Number.prototype.toString() overrides 
         Object.prototype.toString() with the useful distinction that you can 
         pass in a single integer argument. This argument is an optional radix, 
         numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to 
         get a string representation of the binary for the base 10 number 100, 
         i.e. 1100100.
        */

Entity Framework - Generating Classes

I found very nice solution. Microsoft released a beta version of Entity Framework Power Tools: Entity Framework Power Tools Beta 2

There you can generate POCO classes, derived DbContext and Code First mapping for an existing database in some clicks. It is very nice!

After installation some context menu options would be added to your Visual Studio.

Right-click on a C# project. Choose Entity Framework-> Reverse Engineer Code First (Generates POCO classes, derived DbContext and Code First mapping for an existing database):

Visual Studio Context Menu

Then choose your database and click OK. That's all! It is very easy.

Where can I find "make" program for Mac OS X Lion?

Xcode 4.3.2 didn't install "Command Line Tools" by default. I had to open Xcode Preferences / Downloads / Components Tab. It had a list of optional components with an "Install" button beside each. This includes "Command Line Tools" and components to support developing for older versions of iOS.

Now "make" is available and you can check by opening terminal and typing:make -v

The result should look like:GNU Make 3.81

You may need "make" even if you don't need Xcode, such as a Perl developer installing Perl Modules using cpan -i on the commandline.

BULK INSERT with identity (auto-increment) column

Add an id column to the csv file and leave it blank:

id,Name,Address
,name1,addr test 1
,name2,addr test 2

Remove KEEPIDENTITY keyword from query:

BULK INSERT Employee  FROM 'path\tempFile.csv ' 
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');

The id identity field will be auto-incremented.

If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.

How can I parse a CSV string with JavaScript, which contains comma in data?

My answer presumes your input is a reflection of code/content from web sources where single and double quote characters are fully interchangeable provided they occur as an non-escaped matching set.

You cannot use regex for this. You actually have to write a micro parser to analyze the string you wish to split. I will, for the sake of this answer, call the quoted parts of your strings as sub-strings. You need to specifically walk across the string. Consider the following case:

var a = "some sample string with \"double quotes\" and 'single quotes' and some craziness like this: \\\" or \\'",
    b = "sample of code from JavaScript with a regex containing a comma /\,/ that should probably be ignored.";

In this case you have absolutely no idea where a sub-string starts or ends by simply analyzing the input for a character pattern. Instead you have to write logic to make decisions on whether a quote character is used a quote character, is itself unquoted, and that the quote character is not following an escape.

I am not going to write that level of complexity of code for you, but you can look at something I recently wrote that has the pattern you need. This code has nothing to do with commas, but is otherwise a valid enough micro-parser for you to follow in writing your own code. Look into the asifix function of the following application:

https://github.com/austincheney/Pretty-Diff/blob/master/fulljsmin.js

Force IE9 to emulate IE8. Possible?

On the client side you can add and remove websites to be displayed in Compatibility View from Compatibility View Settings window of IE:

Tools-> Compatibility View Settings

How to convert NSNumber to NSString

The funny thing is that NSNumber converts to string automatically if it becomes a part of a string. I don't think it is documented. Try these:

NSLog(@"My integer NSNumber:%@",[NSNumber numberWithInt:184]);
NSLog(@"My float NSNumber:%@",[NSNumber numberWithFloat:12.23f]);
NSLog(@"My bool(YES) NSNumber:%@",[NSNumber numberWithBool:YES]);
NSLog(@"My bool(NO) NSNumber:%@",[NSNumber numberWithBool:NO]);

NSString *myStringWithNumbers = [NSString stringWithFormat:@"Int:%@, Float:%@ Bool:%@",[NSNumber numberWithInt:132],[NSNumber numberWithFloat:-4.823f],[NSNumber numberWithBool:YES]];
NSLog(@"%@",myStringWithNumbers);

It will print:

My integer NSNumber:184
My float NSNumber:12.23
My bool(YES) NSNumber:1
My bool(NO) NSNumber:0
Int:132, Float:-4.823 Bool:1

Works on both Mac and iOS

This one does not work:

NSString *myNSNumber2 = [NSNumber numberWithFloat:-34512.23f];

Set background image in CSS using jquery

<div class="rmz-srchbg">
  <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
  <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
  <br style="clear:both;">
</div>
$(document).ready(function() {
  $('#globalsearchstr').bind('mouseenter', function() {
    $(this).parent().css("background", "black");
  });
});

Merge, update, and pull Git branches without using checkouts

In your case you can use

git fetch origin branchB:branchB

which does what you want (assuming the merge is fast-forward). If the branch can't be updated because it requires a non-fast-forward merge, then this fails safely with a message.

This form of fetch has some more useful options too:

git fetch <remote> <sourceBranch>:<destinationBranch>

Note that <remote> can be a local repository, and <sourceBranch> can be a tracking branch. So you can update a local branch, even if it's not checked out, without accessing the network.

Currently, my upstream server access is via a slow VPN, so I periodically connect, git fetch to update all remotes, and then disconnect. Then if, say, the remote master has changed, I can do

git fetch . remotes/origin/master:master

to safely bring my local master up to date, even if I currently have some other branch checked out. No network access required.

How to Store Historical Data

You can use MSSQL Server Auditing feature. From version SQL Server 2012 you will find this feature in all editions:

http://technet.microsoft.com/en-us/library/cc280386.aspx

Running Groovy script from the command line

#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;

println("hello");

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

Selenium Webdriver: Entering text into text field

I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.

import org.openqa.selenium.Keys;

String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);

element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field

I hope it helps..

Disable webkit's spin buttons on input type="number"?

It seems impossible to prevent spinners from appearing in Opera. As a temporary workaround, you can make room for the spinners. As far as I can tell, the following CSS adds just enough padding, only in Opera:

noindex:-o-prefocus,
input[type=number] {
    padding-right: 1.2em;
}

Trim Cells using VBA in Excel

Worked for me perfectly as this:

Trims all selected cells. Beware of selecting full columns/rows :P.

Sub TrimSelected()    
Dim rng As Range, cell As Range    
Set rng = Selection   

For Each cell In rng    
cell = Trim(cell)   

Next cell    

End Sub

Git push error '[remote rejected] master -> master (branch is currently checked out)'

An article I found that might be useful to others is Git in 5 minutes.

I had an Xcode project under Git version control that I wanted to push up to a Virtual Distributed Ethernet (VDE) I have in a DC. The VDE runs Centos 5.

None of the articles I read about Git talked about bare repositories. It all sounded so simple until I tried what I thought should be easy coming from an SVN background.

The suggestions here to make the remote repository bare worked. Even better for my requirements was to clone the Xcode project to projectname.git, copy that to the remote server; then pushes magically worked. The next step will be getting Xcode to push without errors about commits, but for now I'm okay doing it from Terminal.

So:

cd /tmp (or another other directory on your system)<br/>
git clone --bare /xcode-project-directory projectname.git<br/>
scp -r projectname.git [email protected]:repos/<br/>

To push changes from your Xcode project after you've committed in Xcode:

cd /xcode-project-directory<br/>
git push [email protected]:repos/projectname.git<br/>

I'm certain there is a smoother more sophisticated way of doing the above, but at a minimum this works. Just so everything is clear, here are some clarifications: /xcode-project-directory is the directory your xcode project is stored in. It's probably /Users/Your_Name/Documents/Project_Name. projectname is literally the name of the project, but it can be anything you care to call it. Git doesn't care, you will.

To use scp you need to have a user account on the remote server that's allowed SSH access. Anyone running their own server will have this. If you're using shared hosting or the like, you might be out of luck.

remotehost.com is the name of your remote host. You could as easily use its IP address. Just for further clarity I'm using Gitosis on the remote host with SSH keys, so I'm not prompted for passwords when I push. The article Hosting Git Repositories, the Easy (and Secure) Way tells you how to set all that up.

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

Send email with PHP from html form on submit with the same script

You can also use mandrill app to send the mail in php. You will get the API from https://mandrillapp.com/api/docs/index.php.html where you can find the complete details about emails sended and other details.

VBA equivalent to Excel's mod function

In vba the function is MOD. e.g

 5 MOD 2

Here is a useful link.

How to perform runtime type checking in Dart?

Simply call

print(unknownDataType.runtimeType)

on the data.

TypeScript Objects as Dictionary types as in C#

Lodash has a simple Dictionary implementation and has good TypeScript support

Install Lodash:

npm install lodash @types/lodash --save

Import and usage:

import { Dictionary } from "lodash";
let properties : Dictionary<string> = {
    "key": "value"        
}
console.log(properties["key"])

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

Input Type image submit form value?

An input type="image" only defines that image as the submit button and not as an input that can carry over a value to the server.

RegEx pattern any two letters followed by six numbers

Everything you need here can be found in this quickstart guide. A straightforward solution would be [A-Za-z][A-Za-z]\d\d\d\d\d\d or [A-Za-z]{2}\d{6}.

If you want to accept only capital letters then replace [A-Za-z] with [A-Z].

Sorted array list in Java

Minimalistic Solution

Here is a "minimal" solution.

class SortedArrayList<T> extends ArrayList<T> {

    @SuppressWarnings("unchecked")
    public void insertSorted(T value) {
        add(value);
        Comparable<T> cmp = (Comparable<T>) value;
        for (int i = size()-1; i > 0 && cmp.compareTo(get(i-1)) < 0; i--)
            Collections.swap(this, i, i-1);
    }
}

The insert runs in linear time, but that would be what you would get using an ArrayList anyway (all elements to the right of the inserted element would have to be shifted one way or another).

Inserting something non-comparable results in a ClassCastException. (This is the approach taken by PriorityQueue as well: A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).)

Overriding List.add

Note that overriding List.add (or List.addAll for that matter) to insert elements in a sorted fashion would be a direct violation of the interface specification. What you could do, is to override this method to throw an UnsupportedOperationException.

From the docs of List.add:

boolean add(E e)
    Appends the specified element to the end of this list (optional operation).

Same reasoning applies for both versions of add, both versions of addAll and set. (All of which are optional operations according to the list interface.)


Some tests

SortedArrayList<String> test = new SortedArrayList<String>();

test.insertSorted("ddd");    System.out.println(test);
test.insertSorted("aaa");    System.out.println(test);
test.insertSorted("ccc");    System.out.println(test);
test.insertSorted("bbb");    System.out.println(test);
test.insertSorted("eee");    System.out.println(test);

....prints:

[ddd]
[aaa, ddd]
[aaa, ccc, ddd]
[aaa, bbb, ccc, ddd]
[aaa, bbb, ccc, ddd, eee]

Check if table exists in SQL Server

Please see the below approaches,

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a Customers Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')
BEGIN
    PRINT 'Table Exists'
END

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database.

IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL
BEGIN
    PRINT 'Table Exists'
END

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')
BEGIN
   PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

 IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'Customers' AND Type = N'U')
 BEGIN
      PRINT 'Table Exists'
 END

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

  IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')
  BEGIN
     PRINT 'Table Exists'
  END

referred from: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

regular expression: match any word until first space

I think, that will be good solution: /\S\w*/

Maven compile: package does not exist

You do not include a <scope> tag in your dependency. If you add it, your dependency becomes something like:

<dependency>
     <groupId>org.openrdf.sesame</groupId>
     <artifactId>sesame-runtime</artifactId>
     <version>2.7.2</version>
     <scope> ... </scope>
</dependency>

The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.

Send File Attachment from Form Using phpMailer and PHP

Try:

if (isset($_FILES['uploaded_file']) &&
    $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
    $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);
}

Basic example can also be found here.

The function definition for AddAttachment is:

public function AddAttachment($path,
                              $name = '',
                              $encoding = 'base64',
                              $type = 'application/octet-stream')

Add Keypair to existing EC2 instance

In my case I used this documentation to associate a key pair with my instance of Elastic Beanstalk

Important

You must create an Amazon EC2 key pair and configure your Elastic Beanstalk–provisioned Amazon EC2 instances to use the Amazon EC2 key pair before you can access your Elastic Beanstalk–provisioned Amazon EC2 instances. You can set up your Amazon EC2 key pairs using the AWS Management Console. For instructions on creating a key pair for Amazon EC2, see the Amazon Elastic Compute Cloud Getting Started Guide.

Configuring Amazon EC2 Server Instances with Elastic Beanstalk

Is there a better way to do optional function parameters in JavaScript?

  1. arg || 'default' is a great way and works for 90% of cases

  2. It fails when you need to pass values that might be 'falsy'

    • false
    • 0
    • NaN
    • ""

    For these cases you will need to be a bit more verbose and check for undefined

  3. Also be careful when you have optional arguments first, you have to be aware of the types of all of your arguments

How to format a number 0..9 to display with 2 digits (it's NOT a date)

The String class comes with the format abilities:

System.out.println(String.format("%02d", 5));

for full documentation, here is the doc

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

Chrome:The website uses HSTS. Network errors...this page will probably work later

I have been suffering of this issue for very long time. I was unable to open websites like GitHub. I almost tried all the answer on web and not anyone worked. Tried to reinstall chrome also. I found the solution for this from our network guy and it worked. There is a fix in registry which will resolve this error for permanent basis.

  1. Press Windows+R key to open run dialogue box
  2. type : regeditand press enter to open registry
  3. In the tree view at left click through following path HKEY_LOCAL_MACHINE > SOFTWARE > POLICIES > Microsoft > SystemCertificate > Authroot
  4. Now double click on DisableRootAutoUpdate on the right and set it to 0(zero) in the dialogue box appearing
  5. Restart your PC to apply registry changes and you will not get this error anymore

The solution above is for Windows 8. It is almost identical in later versions but i’m not sure for earlier versions like XP and vista. So that needs to be checked.

how does Array.prototype.slice.call() work?

What happens under the hood is that when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.

How is this in the .slice() function an Array? Because when you do:

object.method();

...the object automatically becomes the value of this in the method(). So with:

[1,2,3].slice()

...the [1,2,3] Array is set as the value of this in .slice().


But what if you could substitute something else as the this value? As long as whatever you substitute has a numeric .length property, and a bunch of properties that are numeric indices, it should work. This type of object is often called an array-like object.

The .call() and .apply() methods let you manually set the value of this in a function. So if we set the value of this in .slice() to an array-like object, .slice() will just assume it's working with an Array, and will do its thing.

Take this plain object as an example.

var my_object = {
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    length: 5
};

This is obviously not an Array, but if you can set it as the this value of .slice(), then it will just work, because it looks enough like an Array for .slice() to work properly.

var sliced = Array.prototype.slice.call( my_object, 3 );

Example: http://jsfiddle.net/wSvkv/

As you can see in the console, the result is what we expect:

['three','four'];

So this is what happens when you set an arguments object as the this value of .slice(). Because arguments has a .length property and a bunch of numeric indices, .slice() just goes about its work as if it were working on a real Array.

how to convert rgb color to int in java

First of all, android.graphics.Color is a class thats composed of only static methods. How and why did you create a new android.graphics.Color object? (This is completely useless and the object itself stores no data)

But anyways... I'm going to assume your using some object that actually stores data...

A integer is composed of 4 bytes (in java). Looking at the function getRGB() from the standard java Color object we can see java maps each color to one byte of the integer in the order ARGB (Alpha-Red-Green-Blue). We can replicate this behavior with a custom method as follows:

public int getIntFromColor(int Red, int Green, int Blue){
    Red = (Red << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
    Green = (Green << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
    Blue = Blue & 0x000000FF; //Mask out anything not blue.

    return 0xFF000000 | Red | Green | Blue; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}

This assumes you can somehow retrieve the individual red, green and blue colour components and that all the values you passed in for the colours are 0-255.

If your RGB values are in form of a float percentage between 0 and 1 consider the following method:

public int getIntFromColor(float Red, float Green, float Blue){
    int R = Math.round(255 * Red);
    int G = Math.round(255 * Green);
    int B = Math.round(255 * Blue);

    R = (R << 16) & 0x00FF0000;
    G = (G << 8) & 0x0000FF00;
    B = B & 0x000000FF;

    return 0xFF000000 | R | G | B;
}

As others have stated, if you're using a standard java object, just use getRGB();

If you decide to use the android color class properly you can also do:

int RGB = android.graphics.Color.argb(255, Red, Green, Blue); //Where Red, Green, Blue are the RGB components. The number 255 is for 100% Alpha

or

int RGB = android.graphics.Color.rgb(Red, Green, Blue); //Where Red, Green, Blue are the RGB components.

as others have stated... (Second function assumes 100% alpha)

Both methods basically do the same thing as the first method created above.

Which MySQL data type to use for storing boolean values

If you use the BOOLEAN type, this is aliased to TINYINT(1). This is best if you want to use standardised SQL and don't mind that the field could contain an out of range value (basically anything that isn't 0 will be 'true').

ENUM('False', 'True') will let you use the strings in your SQL, and MySQL will store the field internally as an integer where 'False'=0 and 'True'=1 based on the order the Enum is specified.

In MySQL 5+ you can use a BIT(1) field to indicate a 1-bit numeric type. I don't believe this actually uses any less space in the storage but again allows you to constrain the possible values to 1 or 0.

All of the above will use approximately the same amount of storage, so it's best to pick the one you find easiest to work with.

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

Error occurred during initialization of boot layer FindException: Module not found

I just encountered the same issue after adding the bin folder to .gitignore, not sure if that caused the issue.

I solved it by going to Project/Properties/Build Path and I removed the scr folder and added it again.

C# testing to see if a string is an integer?

private bool isNumber(object p_Value)
    {
        try
        {
            if (int.Parse(p_Value.ToString()).GetType().Equals(typeof(int)))
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

Something I wrote a while back. Some good examples above but just my 2 cents worth.

What is the difference between a heuristic and an algorithm?

One of the best explanations I have read comes from the great book Code Complete, which I now quote:

A heuristic is a technique that helps you look for an answer. Its results are subject to chance because a heuristic tells you only how to look, not what to find. It doesn’t tell you how to get directly from point A to point B; it might not even know where point A and point B are. In effect, a heuristic is an algorithm in a clown suit. It’s less predict- able, it’s more fun, and it comes without a 30-day, money-back guarantee.

Here is an algorithm for driving to someone’s house: Take Highway 167 south to Puy-allup. Take the South Hill Mall exit and drive 4.5 miles up the hill. Turn right at the light by the grocery store, and then take the first left. Turn into the driveway of the large tan house on the left, at 714 North Cedar.

Here’s a heuristic for getting to someone’s house: Find the last letter we mailed you. Drive to the town in the return address. When you get to town, ask someone where our house is. Everyone knows us—someone will be glad to help you. If you can’t find anyone, call us from a public phone, and we’ll come get you.

The difference between an algorithm and a heuristic is subtle, and the two terms over-lap somewhat. For the purposes of this book, the main difference between the two is the level of indirection from the solution. An algorithm gives you the instructions directly. A heuristic tells you how to discover the instructions for yourself, or at least where to look for them.

How can I print to the same line?

First, I'd like to apologize for bringing this question back up, but I felt that it could use another answer.

Derek Schultz is kind of correct. The '\b' character moves the printing cursor one character backwards, allowing you to overwrite the character that was printed there (it does not delete the entire line or even the character that was there unless you print new information on top). The following is an example of a progress bar using Java though it does not follow your format, it shows how to solve the core problem of overwriting characters (this has only been tested in Ubuntu 12.04 with Oracle's Java 7 on a 32-bit machine, but it should work on all Java systems):

public class BackSpaceCharacterTest
{
    // the exception comes from the use of accessing the main thread
    public static void main(String[] args) throws InterruptedException
    {
        /*
            Notice the user of print as opposed to println:
            the '\b' char cannot go over the new line char.
        */
        System.out.print("Start[          ]");
        System.out.flush(); // the flush method prints it to the screen

        // 11 '\b' chars: 1 for the ']', the rest are for the spaces
        System.out.print("\b\b\b\b\b\b\b\b\b\b\b");
        System.out.flush();
        Thread.sleep(500); // just to make it easy to see the changes

        for(int i = 0; i < 10; i++)
        {
            System.out.print("."); //overwrites a space
            System.out.flush();
            Thread.sleep(100);
        }

        System.out.print("] Done\n"); //overwrites the ']' + adds chars
        System.out.flush();
    }
}

Android Facebook style slide

After a search for several hours, I found Paul Grime's solution probably is the best one. But it has too much functionality in it. So it may be hard to study for beginners. So I would like to provide my implementation which is came from Paul's idea but it is simpler and should be easy to read.

implementation of side menu bar by using java code without XML

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

Angular JS update input field after change

You just need to correct the format of your html

<form>
    <li>Number 1: <input type="text" ng-model="one"/> </li>
    <li>Number 2: <input type="text" ng-model="two"/> </li>
        <li>Total <input type="text" value="{{total()}}"/>  </li>      
    {{total()}}

</form>

http://jsfiddle.net/YUza7/105/

What does the function then() mean in JavaScript?

then() function is related to "Javascript promises" that are used in some libraries or frameworks like jQuery or AngularJS.

A promise is a pattern for handling asynchronous operations. The promise allows you to call a method called "then" that lets you specify the function(s) to use as the callbacks.

For more information see: http://wildermuth.com/2013/8/3/JavaScript_Promises

And for Angular promises: http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/

count (non-blank) lines-of-code in bash

'wc' counts lines, words, chars, so to count all lines (including blank ones) use:

wc *.py

To filter out the blank lines, you can use grep:

grep -v '^\s*$' *.py | wc

'-v' tells grep to output all lines except those that match '^' is the start of a line '\s*' is zero or more whitespace characters '$' is the end of a line *.py is my example for all the files you wish to count (all python files in current dir) pipe output to wc. Off you go.

I'm answering my own (genuine) question. Couldn't find an stackoverflow entry that covered this.

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

How does Java handle integer underflows and overflows and how would you check for it?

It doesn't do anything -- the under/overflow just happens.

A "-1" that is the result of a computation that overflowed is no different from the "-1" that resulted from any other information. So you can't tell via some status or by inspecting just a value whether it's overflowed.

But you can be smart about your computations in order to avoid overflow, if it matters, or at least know when it will happen. What's your situation?

How do I convert an Array to a List<object> in C#?

Everything everyone is saying is correct so,

int[] aArray = {1,2,3};
List<int> list = aArray.OfType<int> ().ToList();

would turn aArray into a list, list. However the biggest thing that is missing from a lot of comments is that you need to have these 2 using statements at the top of your class

using System.Collections.Generic;
using System.Linq;

I hope this helps!

iPhone App Development on Ubuntu

Many of the other solutions will work, but they all make use of the open-toolchain for the iPhone SDK. So, yes, you can write software for the iPhone on other platforms... BUT...

Since you specify that you want your app to end up on the App Store, then, no, there's not really any way to do this. There's certainly no time effective way to do this. Even if you only value your own time at $20/hr, it will be far more efficient to buy a used intel Mac, and download the free SDK.

How can you strip non-ASCII characters from a string? (in C#)

Here is a pure .NET solution that doesn't use regular expressions:

string inputString = "Räksmörgås";
string asAscii = Encoding.ASCII.GetString(
    Encoding.Convert(
        Encoding.UTF8,
        Encoding.GetEncoding(
            Encoding.ASCII.EncodingName,
            new EncoderReplacementFallback(string.Empty),
            new DecoderExceptionFallback()
            ),
        Encoding.UTF8.GetBytes(inputString)
    )
);

It may look cumbersome, but it should be intuitive. It uses the .NET ASCII encoding to convert a string. UTF8 is used during the conversion because it can represent any of the original characters. It uses an EncoderReplacementFallback to to convert any non-ASCII character to an empty string.

Transport endpoint is not connected

I get this error from the sshfs command from Fedora 17 linux to debian linux on the Mindstorms EV3 brick over the LAN and through a wireless connection.

Bash command:

el@defiant /mnt $ sshfs [email protected]:/root -p 22 /mnt/ev3
fuse: bad mount point `/mnt/ev3': Transport endpoint is not connected

This is remedied with the following command and trying again:

fusermount -u /mnt/ev3

These additional sshfs options prevent the above error from concurring:

sudo sshfs -d -o allow_other -o reconnect -o ServerAliveInterval=15 [email protected]:/var/lib/redmine/plugins /mnt -p 12345 -C

In order to use allow_other above, you need to uncomment the last line in /etc/fuse.conf:

# Set the maximum number of FUSE mounts allowed to non-root users.
# The default is 1000.
#
#mount_max = 1000

# Allow non-root users to specify the 'allow_other' or 'allow_root'
# mount options.
#
user_allow_other

Source: http://slopjong.de/2013/04/26/sshfs-transport-endpoint-is-not-connected/

Visual Studio Code pylint: Unable to import 'protorpc'

I resolved this by adding the protorpc library to the $PYTHONPATH environment variable. Specifically, I pointed to the library installed in my App Engine directory:

export PYTHONPATH=$PYTHONPATH:/Users/jackwootton/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0

After adding this to ~/.bash_profile, restarting my machine and Visual Studio Code, the import errors went away.

For completeness, I did not modify any Visual Studio Code settings relating to Python. Full ~/.bash_profile file:

export PATH=/Users/jackwootton/protoc3/bin:$PATH

export PYTHONPATH=/Users/jackwootton/google-cloud-sdk/platform/google_appengine

export PYTHONPATH=$PYTHONPATH:/Users/jackwootton/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0

# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/jackwootton/google-cloud-sdk/path.bash.inc' ]; then source '/Users/jackwootton/google-cloud-sdk/path.bash.inc'; fi

# The next line enables shell command completion for gcloud.
if [ -f '/Users/jackwootton/google-cloud-sdk/completion.bash.inc' ]; then source '/Users/jackwootton/google-cloud-sdk/completion.bash.inc'; fi

Send POST data using XMLHttpRequest

Just for feature readers finding this question. I found that the accepted answer works fine as long as you have a given path, but if you leave it blank it will fail in IE. Here is what I came up with:

function post(path, data, callback) {
    "use strict";
    var request = new XMLHttpRequest();

    if (path === "") {
        path = "/";
    }
    request.open('POST', path, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.onload = function (d) {
        callback(d.currentTarget.response);
    };
    request.send(serialize(data));
}

You can you it like so:

post("", {orem: ipsum, name: binny}, function (response) {
    console.log(respone);
})

How to set a default row for a query that returns no rows?

I figured it out, and it should also work for other systems too. It's a variation of WW's answer.

select rate 
from d_payment_index
where fy = 2007
  and payment_year = 2008
  and program_id = 18
union
select 0 as rate 
from d_payment_index 
where not exists( select rate 
                  from d_payment_index
                  where fy = 2007
                    and payment_year = 2008
                    and program_id = 18 )

How to write a PHP ternary operator

To be honest, a ternary operator would only make this worse, what i would suggest if making it simpler is what you are aiming at is:

$groups = array(1=>"Player", 2=>"Gamemaster", 3=>"God");
echo($groups[$result->group_id]);

and then a similar one for your vocations

$vocations = array(
  1=>"Sorcerer",
  2=>"Druid",
  3=>"Paladin",
  4=>"Knight",
  ....
);
echo($vocations[$result->vocation]);

With a ternary operator, you would end up with

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Which as you can tell, only gets more complicated the more you add to it

Determine when a ViewPager changes pages

For ViewPager2,

viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
  override fun onPageSelected(position: Int) {
    super.onPageSelected(position)
  }
})

where OnPageChangeCallback is a static class with three methods:

onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position), 
onPageScrollStateChanged(@ScrollState int state)

Which keycode for escape key with jQuery

A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.

http://jaywcjlove.github.io/hotkeys/

hotkeys('enter,esc', function(event,handler){
    switch(handler.key){
        case "enter":$('.save').click();break;
        case "esc":$('.cancel').click();break;
    }
});

hotkeys understands the following modifiers: ?,shiftoption?altctrlcontrolcommand, and ?.

The following special keys can be used for shortcuts:backspacetab,clear,enter,return,esc,escape,space,up,down,left,right,home,end,pageup,pagedown,del,delete andf1 throughf19.

How do I sort a dictionary by value?

You can use the collections.Counter. Note, this will work for both numeric and non-numeric values.

>>> x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
>>> from collections import Counter
>>> #To sort in reverse order
>>> Counter(x).most_common()
[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
>>> #To sort in ascending order
>>> Counter(x).most_common()[::-1]
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
>>> #To get a dictionary sorted by values
>>> from collections import OrderedDict
>>> OrderedDict(Counter(x).most_common()[::-1])
OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])

List of enum values in java

tl;dr

Can you make and edit a collection of objects from an enum? Yes.

If you do not care about the order, use EnumSet, an implementation of Set.

enum Animal{ DOG , CAT , BIRD , BAT ; }

Set<Animal> flyingAnimals = EnumSet.of( BIRD , BAT );

Set<Animal> featheredFlyingAnimals = flyingAnimals.clone().remove( BAT ) ;

If you care about order, use a List implementation such as ArrayList. For example, we can create a list of a person’s preference in choosing a pet, in the order of their most preferred.

List< Animal > favoritePets = new ArrayList<>() ;
favoritePets.add( CAT ) ;  // This person prefers cats over dogs…
favoritePets.add( DOG ) ;  // …but would accept either.
                           // This person would not accept a bird nor a bat.

For a non-modifiable ordered list, use List.of.

List< Animal > favoritePets = List.of( CAT , DOG ) ;  // This person prefers cats over dogs, but would accept either. This person would not accept a bird nor a bat. 

Details

The Answer (EnumSet) by Amit Deshpande and the Answer (.values) by Marko Topolnik are both correct. Here is a bit more info.

Enum.values

The .values() method is an implicitly declared method on Enum, added by the compiler. It produces a crude array rather than a Collection. Certainly usable.

Special note about documentation: Being unusual as an implicitly declared method, the .values() method is not listed among the methods on the Enum class. The method is defined in the Java Language Specification, and is mentioned in the doc for Enum.valueOf.

EnumSet – Fast & Small

The upsides to EnumSet include:

  • Extreme speed.
  • Compact use of memory.

To quote the class doc:

Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.

Given this enum:

enum Animal
{
    DOG , CAT , BIRD , BAT ;
}

Make an EnumSet in one line.

Set<Animal> allAnimals = EnumSet.allOf( Animal.class );

Dump to console.

System.out.println( "allAnimals : " + allAnimals );

allAnimals : [DOG, CAT, BIRD, BAT]

Make a set from a subset of the enum objects.

Set<Animal> flyingAnimals = EnumSet.of( BIRD , BAT );

Look at the class doc to see many ways to manipulate the collection including adding or removing elements.

Set<Animal> featheredFlyingAnimals = 
    EnumSet.copyOf( flyingAnimals ).remove( BAT );

Natural Order

The doc promises the Iterator for EnumSet is in natural order, the order in which the values of the enum were originally declared.

To quote the class doc:

The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared).

Frankly, given this promise, I'm confused why this is not a SortedSet. But, oh well, good enough. We can create a List from the Set if desired. Pass any Collection to constructor of ArrayList and that collection’s Iterator is automatically called on your behalf.

List<Animal> list = new ArrayList<>( allAnimals );

Dump to console.

System.out.println("list : " + list );

When run.

list : [DOG, CAT, BIRD, BAT]

In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet. The order of the new list will be in the iterator order of the EnumSet. The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum.

List< Animal > nonModList = List.copyOf( allAnimals ) ;  // Or pass Animals.values() 

How to return a value from pthread threads in C?

You are returning the address of a local variable, which no longer exists when the thread function exits. In any case, why call pthread_exit? why not simply return a value from the thread function?

void *myThread()
{
   return (void *) 42;
}

and then in main:

printf("%d\n",(int)status);   

If you need to return a complicated value such a structure, it's probably easiest to allocate it dynamically via malloc() and return a pointer. Of course, the code that initiated the thread will then be responsible for freeing the memory.

Command line input in Python

It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:

For interactive user input (or piped commands or redirected input)

Use raw_input in Python 2.x, and input in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)

For example:

user_input = raw_input("Some input please: ")

More details can be found here.

So, for example, you might have a script that looks like this

# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)

# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3

# Now do something with the above
print(user_input)

If you saved this in foo.py, you could just call the script from the command line, it would print out tok tiktok, then ask you for input. You could enter bar baz (followed by the enter key) and it would print bar baz. Here's what that would look like:

$ python foo.py
tok tiktok
Some input please: bar baz
bar baz

Here, $ represents the command-line prompt (so you don't actually type that), and I hit Enter after typing bar baz when it asked for input.

For command-line arguments

Suppose you have a script named foo.py and want to call it with arguments bar and baz from the command line like

$ foo.py bar baz

(Again, $ represents the command-line prompt.) Then, you can do that with the following in your script:

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]

Here, the variable arg1 will contain the string 'bar', and arg2 will contain 'baz'. The object sys.argv is just a list containing everything from the command line. Note that sys.argv[0] is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:].

What's the most useful and complete Java cheat sheet?

  1. I have personally found the dzone cheatsheet on core java to be really handy in the beginning. However the needs change as we grow and get used to things.

  2. There are a few listed (at the end of the post) in on this java learning resources article too

  3. For the most practical use, in recent past I have found Java API doc to be the best place to cheat code and learn new api. This helps specially when you want to focus on latest version of java.

  4. mkyong - is one my fav places to cheat a lot of code for quick start - http://www.mkyong.com/

  5. And last but not the least, Stackoverflow is king of all small handy code snippets. Just google a stuff you are trying and there is a chance that a page will be top of search results, most of my google search results end at stackoverflow. Many of the common questions are available here - https://stackoverflow.com/questions/tagged/java?sort=frequent

How to check all versions of python installed on osx and centos

Find out which version of Python is installed by issuing the command python --version: $ python --version Python 2.7.10

If you see something like this, Python 2.7 is your default version. You can also see if you have Python 3 installed:

$ python3 --version
Python 3.7.2

If you also want to know the path where it is installed, you can issue the command "which" with python and python3:

$ which python
/usr/bin/python

$ which python3
/usr/local/bin/python3

Why does Google prepend while(1); to their JSON responses?

After authentication is in place, JSON hijacking protection can take a variety of forms. Google appends while(1) into their JSON data, so that if any malicious script evaluates it, the malicious script enters an infinite loop.

Reference: Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast

Win32Exception (0x80004005): The wait operation timed out

The problem you are having is the query command is taking too long. I believe that the default timeout for a query to execute is 15 seconds. You need to set the CommandTimeout (in seconds) so that it is long enough for the command to complete its execution. The "CommandTimeout" is different than the "Connection Timeout" in your connection string and must be set for each command.

In your sql Selecting Event, use the command:

e.Command.CommandTimeout = 60

for example:

Protected Sub SqlDataSource1_Selecting(sender As Object, e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)
    e.Command.CommandTimeout = 60
End Sub

Call a method of a controller from another controller using 'scope' in AngularJS

Each controller has it's own scope(s) so that's causing your issue.

Having two controllers that want access to the same data is a classic sign that you want a service. The angular team recommends thin controllers that are just glue between views and services. And specifically- "services should hold shared state across controllers".

Happily, there's a nice 15-minute video describing exactly this (controller communication via services): video

One of the original author's of Angular, Misko Hevery, discusses this recommendation (of using services in this situation) in his talk entitled Angular Best Practices (skip to 28:08 for this topic, although I very highly recommended watching the whole talk).

You can use events, but they are designed just for communication between two parties that want to be decoupled. In the above video, Misko notes how they can make your app more fragile. "Most of the time injecting services and doing direct communication is preferred and more robust". (Check out the above link starting at 53:37 to hear him talk about this)

ruby 1.9: invalid byte sequence in UTF-8

In Ruby 1.9.3 it is possible to use String.encode to "ignore" the invalid UTF-8 sequences. Here is a snippet that will work both in 1.8 (iconv) and 1.9 (String#encode) :

require 'iconv' unless String.method_defined?(:encode)
if String.method_defined?(:encode)
  file_contents.encode!('UTF-8', 'UTF-8', :invalid => :replace)
else
  ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
  file_contents = ic.iconv(file_contents)
end

or if you have really troublesome input you can do a double conversion from UTF-8 to UTF-16 and back to UTF-8:

require 'iconv' unless String.method_defined?(:encode)
if String.method_defined?(:encode)
  file_contents.encode!('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
  file_contents.encode!('UTF-8', 'UTF-16')
else
  ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
  file_contents = ic.iconv(file_contents)
end

How to get the cursor to change to the hand when hovering a <button> tag

All u need is just use one of the attribute of CSS , which is---->

cursor:pointer

just use this property in css , no matter its inline or internal or external

for example(for inline css)

<form>
<input type="submit" style= "cursor:pointer" value="Button" name="Button">
</form>

Is ncurses available for windows?

Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.

ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.

The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).

A better option

Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses (and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

How To limit the number of characters in JTextField?

Just put this code in KeyTyped event:

    if ((jtextField.getText() + evt.getKeyChar()).length() > 20) {
        evt.consume();
    }

Where "20" is the maximum number of characters that you want.

Post parameter is always null

I'm a little late to the party, but anyone who stumbles across a NULL value passed when using a controller simply add "=" to the front of your POST request.

The controller also passed a NULL value when I used the application/json Content-Type. Note the "application/x-www-form-urlencoded" Content-Type below. The return type from the API however is "application/json".

 public static string HttpPostRequest(string url, Dictionary<string, string> postParameters)
    {
        string postData = "=";

        foreach (string key in postParameters.Keys)
        {
            postData += HttpUtility.UrlEncode(key) + "="
                  + HttpUtility.UrlEncode(postParameters[key]) + ",";
        }

        HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
        myHttpWebRequest.Method = "POST";

        byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);

        myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
        myHttpWebRequest.ContentLength = data.Length;

        Stream requestStream = myHttpWebRequest.GetRequestStream();
        requestStream.Write(data, 0, data.Length);
        requestStream.Close();

        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

        Stream responseStream = myHttpWebResponse.GetResponseStream();

        StreamReader myStreamReader = new StreamReader(responseStream, System.Text.Encoding.Default);

        string pageContent = myStreamReader.ReadToEnd();

        myStreamReader.Close();
        responseStream.Close();

        myHttpWebResponse.Close();

        return pageContent;
    }

Run a Python script from another Python script, passing in arguments

SubProcess module:
http://docs.python.org/dev/library/subprocess.html#using-the-subprocess-module

import subprocess
subprocess.Popen("script2.py 1", shell=True)

With this, you can also redirect stdin, stdout, and stderr.

How do I programmatically determine operating system in Java?

some of the links in the answers above seem to be broken. I have added pointers to current source code in the code below and offer an approach for handling the check with an enum as an answer so that a switch statement can be used when evaluating the result:

OsCheck.OSType ostype=OsCheck.getOperatingSystemType();
switch (ostype) {
    case Windows: break;
    case MacOS: break;
    case Linux: break;
    case Other: break;
}

The helper class is:

/**
 * helper class to check the operating system this Java VM runs in
 *
 * please keep the notes below as a pseudo-license
 *
 * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
 * compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java
 * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html
 */
import java.util.Locale;
public static final class OsCheck {
  /**
   * types of Operating Systems
   */
  public enum OSType {
    Windows, MacOS, Linux, Other
  };

  // cached result of OS detection
  protected static OSType detectedOS;

  /**
   * detect the operating system from the os.name System property and cache
   * the result
   * 
   * @returns - the operating system detected
   */
  public static OSType getOperatingSystemType() {
    if (detectedOS == null) {
      String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
      if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) {
        detectedOS = OSType.MacOS;
      } else if (OS.indexOf("win") >= 0) {
        detectedOS = OSType.Windows;
      } else if (OS.indexOf("nux") >= 0) {
        detectedOS = OSType.Linux;
      } else {
        detectedOS = OSType.Other;
      }
    }
    return detectedOS;
  }
}

Java - using System.getProperty("user.dir") to get the home directory

"user.dir" is the current working directory, not the home directory It is all described here.

http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Also, by using \\ instead of File.separator, you will lose portability with *nix system which uses / for file separator.

How to check for empty value in Javascript?

In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:

const isEmptyValue = (value) => {
    if (value === '' || value === null || value === undefined) {
        return true
    } else {
        return false
    }
}

What is size_t in C?

The manpage for types.h says:

size_t shall be an unsigned integer type

How to remove trailing whitespaces with sed?

For those who look for efficiency (many files to process, or huge files), using the + repetition operator instead of * makes the command more than twice faster.

With GNU sed:

sed -Ei 's/[ \t]+$//' "$1"
sed -i 's/[ \t]\+$//' "$1"   # The same without extended regex

I also quickly benchmarked something else: using [ \t] instead of [[:space:]] also significantly speeds up the process (GNU sed v4.4):

sed -Ei 's/[ \t]+$//' "$1"

real    0m0,335s
user    0m0,133s
sys 0m0,193s

sed -Ei 's/[[:space:]]+$//' "$1"

real    0m0,838s
user    0m0,630s
sys 0m0,207s

sed -Ei 's/[ \t]*$//' "$1"

real    0m0,882s
user    0m0,657s
sys 0m0,227s

sed -Ei 's/[[:space:]]*$//' "$1"

real    0m1,711s
user    0m1,423s
sys 0m0,283s

Pointer vs. Reference

You should pass a pointer if you are going to modify the value of the variable. Even though technically passing a reference or a pointer are the same, passing a pointer in your use case is more readable as it "advertises" the fact that the value will be changed by the function.

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

For those of you in a .NET environment the following can be a handy way to filter non-numbers out (this example is in VB.NET, but it's probably similar in C#):

If Double.IsNaN(MyVariableName) Then
    MyVariableName = 0 ' Or whatever you want to do here to "correct" the situation
End If

If you try to use a variable that has a NaN value you will get the following error:

Value was either too large or too small for a Decimal.

Why does JSHint throw a warning if I am using const?

In a new version of Dreamweaver to solve this error

  • Go to Edit->Preference->Linting
  • And the go-to js Edit rule set and past

    "jshintConfig":{ "esversion": 6 }

How to remove newlines from beginning and end of a string?

If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:

Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:

 s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")

Complete Example:

public class RemoveLineBreaks {
    public static void main(String[] args) {
        var s = "\nHello\nWorld\n";
        System.out.println("before: >"+s+"<");
        s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
        System.out.println("after: >"+s+"<");
    }
}

It outputs:

before: >
Hello
World
<
after: >Hello
World<

How do I clone a job in Jenkins?

I was not able to copy Jenkins job from subfolder. copy from option did not show the suggestion which i was looking for.Without using suggestion copying the job name didn't work.

So if you want to create a job from outer folder, you need to first create the job in subfolder and then move it in different folder where you need to place it.

How to indent a few lines in Markdown markup?

Check if you can use HTML with your markdown. Maybe this works out for you:

  • List entry one<br/>
    Indented line<br/>
    <br/>
    And some more..
  • Second entry
    • Subentry<br/>
      Hello there!

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

For me this worked: (added into .ssh\config)

Host *
HostkeyAlgorithms +ssh-dss
PubkeyAcceptedKeyTypes +ssh-dss

Return JsonResult from web api without its properties

I had a similar problem (differences being I wanted to return an object that was already converted to a json string and my controller get returns a IHttpActionResult)

Here is how I solved it. First I declared a utility class

public class RawJsonActionResult : IHttpActionResult
{
    private readonly string _jsonString;

    public RawJsonActionResult(string jsonString)
    {
        _jsonString = jsonString;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var content = new StringContent(_jsonString);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
        return Task.FromResult(response);
    }
}

This class can then be used in your controller. Here is a simple example

public IHttpActionResult Get()
{
    var jsonString = "{\"id\":1,\"name\":\"a small object\" }";
    return new RawJsonActionResult(jsonString);
}

Bat file to run a .exe at the command prompt

What's stopping you?

Put this command in a text file, save it with the .bat (or .cmd) extension and double click on it...

Presuming the command executes on your system, I think that's it.

Check if an object exists

I think the easiest from a logical and efficiency point of view is using the queryset's exists() function, documented here:

https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.exists

So in your example above I would simply write:

if User.objects.filter(email = cleaned_info['username']).exists():
    # at least one object satisfying query exists
else:
    # no object satisfying query exists

What's the fastest way to delete a large folder in Windows?

Using Windows Command Prompt:

rmdir /s /q folder

Using Powershell:

powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"

Note that in more cases del and rmdir wil leave you with leftover files, where Powershell manages to delete the files.

illegal character in path

Try this:

string path = @"C:\Program Files (x86)\test software\myapp\demo.exe";

JavaScript check if value is only undefined, null or false

Boolean(val) === false. This worked for me to check if value was falsely.

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

Node.js Error: Cannot find module express

I'm guessing that this is coursework from Colt Steele's Web Development course... I was looking for the same answer as to why I ended up with that error too.. Colt doesn't say so but you take the node_module folder and move into the new folder you're working in... that's what worked for me.

How to get box-shadow on left & right sides only

Another idea could be creating a dark blurred pseudo element eventually with transparency to imitate shadow. Make it with slightly less height and more width i.g.

Reset textbox value in javascript

I know this is an old post, but this may help clarify:

$('#searchField')
    .val('')// [property value] e.g. what is visible / will be submitted
    .attr('value', '');// [attribute value] e.g. <input value="preset" ...

Changing [attribute value] has no effect if there is a [property value]. (user || js altered input)

A keyboard shortcut to comment/uncomment the select text in Android Studio

I had the same problem, usually, you have found the shortcut but it doesn't work because you have not a NumPad. Actually, the only one issue I found is to set my own shortcut with the one I suppose should works.

First step, find the IDE shortcuts : cmd + shift + A enter shortcuts First step, find the IDE shortcuts : <code>cmd + shift + A</code> enter shortcuts

Second step : Find Comments Shortcut with the finder enter image description here

Third step : Set your custom shortcut (I suggest cmd + shift + / or cmd + : ) enter image description here

Now enjoy, it works on a macBook without NumPad

edit : cmd + shift + : has conflicts

Edit : this both works without conflicts enter image description hereIssue on MacBook