Programs & Examples On #Autoconf

GNU Autoconf creates a shell script `configure` that is used to configure software for compilation for UNIX-like operating systems.

possibly undefined macro: AC_MSG_ERROR

I had the same problem with the Macports port "openocd" (locally modified the Portfile to use the git repository) on a freshly installed machine.

The permanent fix is easy, define a dependency to pkgconfig in the Portfile: depends_lib-append port:pkgconfig

CFLAGS vs CPPFLAGS

The CPPFLAGS macro is the one to use to specify #include directories.

Both CPPFLAGS and CFLAGS work in your case because the make(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).

You don't need to specify . as an include-directory if you use the form #include "...". You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.

How to add include and lib paths to configure/make cycle?

You want a config.site file. Try:

$ mkdir -p ~/local/share
$ cat << EOF > ~/local/share/config.site
CPPFLAGS=-I$HOME/local/include
LDFLAGS=-L$HOME/local/lib
...
EOF

Whenever you invoke an autoconf generated configure script with --prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the ... in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler.

How do I reference tables in Excel using VBA?

Converting a range to a table as described in this answer:

Sub CreateTable()
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes).Name = _
        "Table1"
        'No go in 2003
    ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight2"
End Sub

What's the fastest way to loop through an array in JavaScript?

var arr = []; // The array
var i = 0;
while (i < arr.length) {
    // Do something with arr[i]
    i++;
}

i++ is faster than ++i, --i and i--

Also, you can save the last line doing arr[i++] the last time you need to access i (but this can be hard to debug).

You can test it here (with other loop tests): http://jsperf.com/for-vs-whilepop/5

How to display UTF-8 characters in phpMyAdmin?

Add:

mysql_query("SET NAMES UTF8");

below:

mysql_select_db(/*your_database_name*/);

Convert array of indices to 1-hot encoded numpy array

>>> values = [1, 0, 3]
>>> n_values = np.max(values) + 1
>>> np.eye(n_values)[values]
array([[ 0.,  1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.]])

Java - remove last known item from ArrayList

You're trying to assign the return value of clients.get(clients.size()) to the string hey, but the object returned is a ClientThread, not a string. As Andre mentioned, you need to use the proper index as well.

As far as your second error is concerned, there is no static method remove() on the type ClientThread. Really, you likely wanted the remove method of your List instance, clients.

You can remove the last item from the list, if there is one, as follows. Since remove also returns the object that was removed, you can capture the return and use it to print out the name:

int size = clients.size();

if (size > 0) {
    ClientThread client = clients.remove(size - 1);

    System.out.println(client + " has logged out.");
    System.out.println("CONNECTED PLAYERS: " + clients.size());
}

How do I set session timeout of greater than 30 minutes

Setting the timeout in the web.xml is the correct way to set the timeout.

How to push changes to github after jenkins build completes?

Found an answer myself, this blog helped: http://thingsyoudidntknowaboutjenkins.tumblr.com/post/23596855946/git-plugin-part-3

Basically need to execute:

git checkout master

before modifying any files

then

git commit -am "Updated version number"

after modified files

and then use post build action of Git Publisher with an option of Merge Results which will push changes to github on successful build.

How to execute shell command in Javascript

Here is simple command that executes ifconfig shell command of Linux

var process = require('child_process');
process.exec('ifconfig',function (err,stdout,stderr) {
    if (err) {
        console.log("\n"+stderr);
    } else {
        console.log(stdout);
    }
});

How to Disable landscape mode in Android?

If you are using Xamarin C# some of these solutions will not work. Here is the solution I found to work.

[Activity(MainLauncher = true, Icon = "@drawable/icon", ScreenOrientation = ScreenOrientation.Portrait)]

Above the class works well, similar to the other solutions, also not globally applicable and needs to be placed in each activity header.

CSS: stretching background image to 100% width and height of screen?

You need to set the height of html to 100%

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
html {
    height: 100%
}

http://jsfiddle.net/8XUjP/

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

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
            //    relationship.DeleteBehavior = DeleteBehavior.Restrict;

            modelBuilder.Entity<User>().ToTable("Users");

            modelBuilder.Entity<IdentityRole<string>>().ToTable("Roles");
            modelBuilder.Entity<IdentityUserToken<string>>().ToTable("UserTokens");
            modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims");
            modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins");
            modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaims");
            modelBuilder.Entity<IdentityUserRole<string>>().ToTable("UserRoles");

        }
    }

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

Do aman 2 sendfile. You only need to open the source file on the client and destination file on the server, then call sendfile and the kernel will chop and move the data.

Do I cast the result of malloc?

A void pointer is a generic pointer and C supports implicit conversion from a void pointer type to other types, so there is no need of explicitly typecasting it.

However, if you want the same code work perfectly compatible on a C++ platform, which does not support implicit conversion, you need to do the typecasting, so it all depends on usability.

Send email using java

Here is the working solution bro. It's guranteed.

  1. First of all open your gmail account from which you wanted to send mail, like in you case [email protected]
  2. Open this link below:

    https://support.google.com/accounts/answer/6010255?hl=en

  3. Click on "Go to the "Less secure apps" section in My Account." option
  4. Then turn on it
  5. That's it (:

Here is my code:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmail {

   final String senderEmailID = "Sender Email id";
final String senderPassword = "Sender Pass word";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
static String emailSubject = "Test Mail";
static String emailBody = ":)";
public SendEmail(String receiverEmailID, String emailSubject, String emailBody)
{
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;
Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
System.out.println("Message send Successfully:)");
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
    public static void main(String[] args) {
       SendEmail mailSender;
        mailSender = new SendEmail("Receiver Email id","Testing Code 2 example","Testing Code Body yess");
    }

}

node.js execute system command synchronously

you can do synchronous shell operations in nodejs like so:

var execSync = function(cmd) {

    var exec  = require('child_process').exec;
    var fs = require('fs');

    //for linux use ; instead of &&
    //execute your command followed by a simple echo 
    //to file to indicate process is finished
    exec(cmd + " > c:\\stdout.txt && echo done > c:\\sync.txt");

    while (true) {
        //consider a timeout option to prevent infinite loop
        //NOTE: this will max out your cpu too!
        try {
            var status = fs.readFileSync('c:\\sync.txt', 'utf8');

            if (status.trim() == "done") {
                var res = fs.readFileSync("c:\\stdout.txt", 'utf8');
                fs.unlinkSync("c:\\stdout.txt"); //cleanup temp files
                fs.unlinkSync("c:\\sync.txt");
                return res;
            }
        } catch(e) { } //readFileSync will fail until file exists
    }

};

//won't return anything, but will take 10 seconds to run
console.log(execSync("sleep 10")); 

//assuming there are a lot of files and subdirectories, 
//this too may take a while, use your own applicable file path
console.log(execSync("dir /s c:\\usr\\docs\\"));

EDIT - this example is meant for windows environments, adjust for your own linux needs if necessary

SQL Server : trigger how to read value for Insert, Update, Delete

There is no updated dynamic table. There is just inserted and deleted. On an UPDATE command, the old data is stored in the deleted dynamic table, and the new values are stored in the inserted dynamic table.

Think of an UPDATE as a DELETE/INSERT combination.

What is the backslash character (\\)?

If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.

Console.WriteLine(@"Mango \ Nightangle");

Don't you just wish Java had something like this ;-)

When to use static keyword before global variables?

static before a global variable means that this variable is not accessible from outside the compilation module where it is defined.

E.g. imagine that you want to access a variable in another module:

foo.c

int var; // a global variable that can be accessed from another module
// static int var; means that var is local to the module only.
...

bar.c

extern int var; // use the variable in foo.c
...

Now if you declare var to be static you can't access it from anywhere but the module where foo.c is compiled into.

Note, that a module is the current source file, plus all included files. i.e. you have to compile those files separately, then link them together.

How to implement a secure REST API with node.js

If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.

You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:

1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)

2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)

3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized

4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request

5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.

Many libraries provide easy ways to create & validate JWTs in most programming languages, for example: in node.js one of the most popular is jsonwebtoken

Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.

One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).

You can learn more about JWTs from this link

What is Vim recording and how can it be disabled?

It means you're in "record macro" mode. This mode is entered by typing q followed by a register name, and can be exited by typing q again.

How can I read a whole file into a string variable

I'm not with computer,so I write a draft. You might be clear of what I say.

func main(){
    const dir = "/etc/"
    filesInfo, e := ioutil.ReadDir(dir)
    var fileNames = make([]string, 0, 10)
    for i,v:=range filesInfo{
        if !v.IsDir() {
            fileNames = append(fileNames, v.Name())
        }
    }

    var fileNumber = len(fileNames)
    var contents = make([]string, fileNumber, 10)
    wg := sync.WaitGroup{}
    wg.Add(fileNumber)

    for i,_:=range content {
        go func(i int){
            defer wg.Done()
            buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
            defer file.Close()  
            content[i] = string(buf)
        }(i)   
    }
    wg.Wait()
}

How to enable loglevel debug on Apache2 server

Edit: note that this answer is 3+ years old. For newer versions of apache, please see the answer by sp00n. Leaving this answer for users of older versions of apache.

For older version apache:

For debugging mod_rewrite issues, you'll want to use RewriteLogLevel and RewriteLog:

RewriteLogLevel 3
RewriteLog "/usr/local/var/apache/logs/rewrite.log"

non static method cannot be referenced from a static context

Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.

The variable Random is only "in scope" inside the main method. It's not accessible to any methods called by main. When you return from main, the variable disappears (it's part of the stack frame).

If you want all of the methods of your class to use the same Random instance, declare a member variable:

class MyObj {
  private final Random random = new Random();
  public void compTurn() {
    while (true) {
      int a = random.nextInt(10);
      if (possibles[a] == 1) 
        break;
    }
  }
}

java.util.NoSuchElementException - Scanner reading user input

the reason of the exception has been explained already, however the suggested solution isn't really the best.

You should create a class that keeps a Scanner as private using Singleton Pattern, that makes that scanner unique on your code.

Then you can implement the methods you need or you can create a getScanner ( not recommended ) and you can control it with a private boolean, something like alreadyClosed.

If you are not aware how to use Singleton Pattern, here's a example:

public class Reader {
    
    
    private Scanner reader;
    private static Reader singleton = null;
    private boolean alreadyClosed;
    
    private Reader() {
        alreadyClosed = false;
        reader = new Scanner(System.in);
    }
    
    public static Reader getInstance() {
        if(singleton == null) {
            singleton = new Reader();
        }
        return singleton;
    }
    
    public int nextInt() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextInt();
        }
        throw new AlreadyClosedException(); //Custom exception
    }
    
    public double nextDouble() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextDouble();
        }
        throw new AlreadyClosedException();
    }
    
    public String nextLine() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextLine();
        }
        throw new AlreadyClosedException();
    }
    
    public void close() {
        alreadyClosed = true;
        reader.close();
    }   
}

How to select date from datetime column?

You can use MySQL's DATE() function:

WHERE DATE(datetime) = '2009-10-20'

You could also try this:

WHERE datetime LIKE '2009-10-20%'

See this answer for info on the performance implications of using LIKE.

How to create a TextArea in Android

Defining an Android Mulitline EditText Field is done via the inputType=”textMultiline”. Unfortunately the text looks strangely aligned. To solve that also use the gravity=”left|top” attribute.

<EditText
   android:id="@+id/editText1"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:ems="10"
   android:gravity="left|top"
   android:inputType="textMultiLine" >

   <requestFocus />

check this vogella blog

Transparent background in JPEG image

You can't make a JPEG image transparent. You should use a format that allows transparency, like GIF or PNG.

Paint will open these files, but AFAIK it'll erase transparency if you edit the file. Use some other application like Paint.NET (it's free).

Edit: since other people have mentioned it: you can convert JPEG images into PNG, in any editor that's capable of working with both types.

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

Why is semicolon allowed in this python snippet?

Semicolons (like dots, commas and parentheses) tend to cause religious wars. Still, they (or some similar symbol) are useful in any programming language for various reasons.

  • Practical: the ability to put several short commands that belong conceptually together on the same line. A program text that looks like a narrow snake has the opposite effect of what is intended by newlines and indentation, which is highlighting structure.

  • Conceptual: separation of concerns between pure syntax (in this case, for a sequence of commands) from presentation (e.g. newline), in the old days called "pretty-printing".

Observation: for highlighting structure, indentation could be augmented/replaced by vertical lines in the obvious way, serving as a "visual ruler" to see where an indentation begins and ends. Different colors (e.g. following the color code for resistors) may compensate for crowding.

How to know a Pod's own IP address from inside a container in the Pod?

In some cases, instead of relying on downward API, programmatically reading the local IP address (from network interfaces) from inside of the container also works.

For example, in golang: https://stackoverflow.com/a/31551220/6247478

Reverse ip, find domain names on ip address

You can use ping -a <ip> or nbtstat -A <ip>

#if DEBUG vs. Conditional("DEBUG")

Let's presume your code also had an #else statement which defined a null stub function, addressing one of Jon Skeet's points. There's a second important distinction between the two.

Suppose the #if DEBUG or Conditional function exists in a DLL which is referenced by your main project executable. Using the #if, the evaluation of the conditional will be performed with regard to the library's compilation settings. Using the Conditional attribute, the evaluation of the conditional will be performed with regard to the compilation settings of the invoker.

How to change active class while click to another link in bootstrap use jquery?

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
        var url = window.location;_x000D_
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');_x000D_
        $('ul.nav a').filter(function () {_x000D_
            return this.href == url;_x000D_
        }).parent().addClass('active').parent().parent().addClass('active');_x000D_
    });_x000D_
    _x000D_
    This works perfectly
_x000D_
_x000D_
_x000D_

Play local (hard-drive) video file with HTML5 video tag?

Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4

<div id="videoDiv">
     <video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
    </div>
<!--End videoDiv-->

Not an ideal solution but worked for me.

Check if returned value is not null and if so assign it, in one line, with one method call

Using Java 1.8 you can use Optional

public class Main  {

    public static void main(String[] args) {

        //example call, the methods are just dumb templates, note they are static
        FutureMeal meal = getChicken().orElse(getFreeRangeChicken());

        //another possible way to call this having static methods is
        FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference

        //or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
        // as nonstatic methods (assume static would be replaced with public for this)
        Main m = new Main();
        FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference

        //or
        FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call


    }

    static Optional<FutureMeal> getChicken(){

        //instead of returning null, you would return Optional.empty() 
        //here I just return it to demonstrate
        return Optional.empty();

        //if you would return a valid object the following comment would be the code
        //FutureMeal ret = new FutureMeal(); //your return object
        //return Optional.of(ret);            

    }

    static FutureMeal getFreeRangeChicken(){
        return new FutureMeal();
    }
}

You would implement a logic for getChicken to return either Optional.empty() instead of null, or Optional.of(myReturnObject), where myReturnObject is your chicken.

Then you can call getChicken() and if it would return Optional.empty() the orElse(fallback) would give you whatever the fallback would be, in your case the second method.

How do I escape a percentage sign in T-SQL?

You can use the code below to find a specific value.

WHERE col1 LIKE '%[%]75%'

When you want a single digit number after the% sign, you can write the following code.

WHERE col2 LIKE '%[%]_'

What in the world are Spring beans?

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

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

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

css overflow - only 1 line of text

I had the same issue and I solved it by using:

display: inline-block;

on the div in question.

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

how to set length of an column in hibernate with maximum length

if your column is varchar use annotation length

@Column(length = 255)

or use another column type

@Column(columnDefinition="TEXT")

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.

GPS

A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.

AGPS

As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

Difference between char* and const char*?

The first you can actually change if you want to, the second you can't. Read up about const correctness (there's some nice guides about the difference). There is also char const * name where you can't repoint it.

How to trim leading and trailing white spaces of a string?

@peterSO has correct answer. I am adding more examples here:

package main

import (
    "fmt"
    strings "strings"
)

func main() { 
    test := "\t pdftk 2.0.2  \n"
    result := strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\n\r pdftk 2.0.2 \n\r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\n\r\n\r pdftk 2.0.2 \n\r\n\r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))

    test = "\r pdftk 2.0.2 \r"
    result = strings.TrimSpace(test)
    fmt.Printf("Length of %q is %d\n", test, len(test))
    fmt.Printf("Length of %q is %d\n\n", result, len(result))   
}

You can find this in Go lang playground too.

How do I prevent people from doing XSS in Spring MVC?

When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.

I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91

Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.

How to create a file in memory for user to download, but not through server?

We can use the URL api, in particular URL.createObjectURL(), and the Blob api to encode and download pretty much anything.

If your download is small, this works fine:

_x000D_
_x000D_
document.body.innerHTML += 
`<a id="download" download="PATTERN.json" href="${URL.createObjectURL(new Blob([JSON.stringify("HELLO WORLD", null, 2)]))}"> Click me</a>`
download.click()
download.outerHTML = ""
_x000D_
_x000D_
_x000D_


If your download is huge, instead of using the DOM, a better way is to create a link element with the download parameters, and trigger a click.

Notice the link element isn't appended to the document but the click work anyway! This is possible to create a download of many hundreds of Mo this way.

_x000D_
_x000D_
const stack = {
 some: "stuffs",
 alot: "of them!"
}

BUTTONDOWNLOAD.onclick = (function(){
  let j = document.createElement("a")
  j.download = "stack_"+Date.now()+".json"
  j.href = URL.createObjectURL(new Blob([JSON.stringify(stack, null, 2)]))
  j.click()
})
_x000D_
<button id="BUTTONDOWNLOAD">DOWNLOAD!</button>
_x000D_
_x000D_
_x000D_


Bonus! Download any cyclic objects, avoid the errors:

TypeError: cyclic object value (Firefox) TypeError: Converting

circular structure to JSON (Chrome and Opera) TypeError: Circular

reference in value argument not supported (Edge)

Using https://github.com/douglascrockford/JSON-js/blob/master/cycle.js

On this example, downloading the document object as json.

_x000D_
_x000D_
/* JSON.decycle */
if(typeof JSON.decycle!=="function"){JSON.decycle=function decycle(object,replacer){"use strict";var objects=new WeakMap();return(function derez(value,path){var old_path;var nu;if(replacer!==undefined){value=replacer(value)}
if(typeof value==="object"&&value!==null&&!(value instanceof Boolean)&&!(value instanceof Date)&&!(value instanceof Number)&&!(value instanceof RegExp)&&!(value instanceof String)){old_path=objects.get(value);if(old_path!==undefined){return{$ref:old_path}}
objects.set(value,path);if(Array.isArray(value)){nu=[];value.forEach(function(element,i){nu[i]=derez(element,path+"["+i+"]")})}else{nu={};Object.keys(value).forEach(function(name){nu[name]=derez(value[name],path+"["+JSON.stringify(name)+"]")})}
return nu}
return value}(object,"$"))}}


document.body.innerHTML += 
`<a id="download" download="PATTERN.json" href="${URL.createObjectURL(new Blob([JSON.stringify(JSON.decycle(document), null, 2)]))}"></a>`
download.click()
_x000D_
_x000D_
_x000D_

Show red border for all invalid fields after submitting form angularjs

Reference article: Show red color border for invalid input fields angualrjs

I used ng-class on all input fields.like below

<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>

when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).

So now my input field contains classes like this

class="ng-pristine ng-invalid submitted"

now I am using below css code to show red border on all invalid input fields(after submitting the form)

input.submitted.ng-invalid
{
  border:1px solid #f00;
}

Thank you !!

Update:

We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector

form.submitted .ng-invalid
{
    border:1px solid #f00;
}

how to properly display an iFrame in mobile safari

I have put @Sharon's code together into the following, which works for me on the iPad with two-finger scrolling. The only thing you should have to change to get it working is the src attribute on the iframe (I used a PDF document).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Pdf Scrolling in mobile Safari</title>
</head>
<body>
<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" id="iframe" src="data/testdocument.pdf" />
</div>
<script type="text/javascript">
    setTimeout(function () {
        var startY = 0;
        var startX = 0;
        var b = document.body;
        b.addEventListener('touchstart', function (event) {
            parent.window.scrollTo(0, 1);
            startY = event.targetTouches[0].pageY;
            startX = event.targetTouches[0].pageX;
        });
        b.addEventListener('touchmove', function (event) {
            event.preventDefault();
            var posy = event.targetTouches[0].pageY;
            var h = parent.document.getElementById("scroller");
            var sty = h.scrollTop;

            var posx = event.targetTouches[0].pageX;
            var stx = h.scrollLeft;
            h.scrollTop = sty - (posy - startY);
            h.scrollLeft = stx - (posx - startX);
            startY = posy;
            startX = posx;
        });
    }, 1000);
    </script>
</body>
</html>

PHP Get Highest Value from Array

asort() is the way to go:

$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
asort($array);
$highestValue       = end($array);
$keyForHighestValue = key($array);

How to concatenate two strings in SQL Server 2005

I got a easy solution which will select from database table and let you do easily.

SELECT b.FirstName + b.LastName FROM tbl_Users b WHERE b.Id='11'

You can easily add a space there if you try

SELECT b.FirstName +' '+ b.LastName FROM Users b WHERE b.Id='23'

Here you can combine as much as your table have.

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

MySQL InnoDB not releasing disk space after deleting data rows from table

MySQL doesn't reduce the size of ibdata1. Ever. Even if you use optimize table to free the space used from deleted records, it will reuse it later.

An alternative is to configure the server to use innodb_file_per_table, but this will require a backup, drop database and restore. The positive side is that the .ibd file for the table is reduced after an optimize table.

Variable might not have been initialized error

You declared them but did not provide them with an intial value - thus, they're unintialized. Try something like:

public static Rand searchCount (int[] x)  
{ 
  int a = 0 ;  
  int b = 0 ; 

and the warnings should go away.

Java how to sort a Linked List?

I wouldn't. I would use an ArrayList or a sorted collection with a Comparator. Sorting a LinkedList is about the most inefficient procedure I can think of.

Visual Studio: Relative Assembly References Paths

I might be off here, but it seems that the answer is quite obvious: Look at reference paths in the project properties. In our setup I added our common repository folder, to the ref path GUI window, like so

Reference Paths in VS20xx

That way I can copy my dlls (ready for publish) to this folder and every developer now gets the updated DLL every time it builds from this folder.

If the dll is found in the Solution, the builder should prioritize the local version over the published team version.

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

Yes or No confirm box using jQuery

I've used these codes:

HTML:

<a id="delete-button">Delete</a>

jQuery:

<script>
$("#delete-button").click(function(){
    if(confirm("Are you sure you want to delete this?")){
        $("#delete-button").attr("href", "query.php?ACTION=delete&ID='1'");
    }
    else{
        return false;
    }
});
</script>

These codes works for me, but I'm not really sure if this is proper. What do you think?

How can I center <ul> <li> into div

To center the ul and also have the li elements centered in it as well, and make the width of the ul change dynamically, use display: inline-block; and wrap it in a centered div.

<style type="text/css">
    .wrapper {
        text-align: center;
    }
    .wrapper ul {
        display: inline-block;
        margin: 0;
        padding: 0;
        /* For IE, the outcast */
        zoom:1;
        *display: inline;
    }
    .wrapper li {
        float: left;
        padding: 2px 5px;
        border: 1px solid black;
    }
</style>

<div class="wrapper">
    <ul>
        <li>Three</li>
        <li>Blind</li>
        <li>Mice</li>
    </ul>
</div>

Update

Here is a jsFiddle link to the code above.

Open URL in Java to get the content

It works for me. Please check if you are using the right imports?

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

How read Doc or Docx file in java?

Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

For me, the reason is that the gradle.zip IDE downloaded is broken (I cannot uncompress it manually), and following steps help.

  1. gradle sync, and it says could not install from ${link}, ${gralde.zip} ...
  2. download from ${link} manually
  3. go to the ${gradle.zip}'s location
  4. replace the ${gradle.zip} with the one downloaded, remove the .lck file on the same path.
  5. gradle sync.

Note:

  • ${link} is something like https://services.gradle.org/distributions/gradle-4.6-all.zip
  • ${gradle.zip} looks like ~/.gradle/wrapper/dists/gradle-${version}-all/${a-serial-string}/gradle-${version}-all.zip

Removing ul indentation with CSS

Remove this from #info:

    margin-left:auto;

Add this for your header:

#info p {
    text-align: center;
}

Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align.

Sample
http://jsfiddle.net/Vc8CB/

How to style input and submit button with CSS?

Simply style your Submit button like you would style any other html element. you can target different type of input elements using CSS attribute selector

As an example you could write

input[type=text] {
   /*your styles here.....*/
}
input[type=submit] {
   /*your styles here.....*/
}
textarea{
   /*your styles here.....*/
}

Combine with other selectors

input[type=text]:hover {
   /*your styles here.....*/
}
input[type=submit] > p {
   /*your styles here.....*/
}
....

Here is a working Example

Auto-click button element on page load using jQuery

Use the following code

$("#modal").trigger('click');

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

Java - Including variables within strings?

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

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

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

No log4j2 configuration file found. Using default configuration: logging only errors to the console

In my case I am using the log4j2 Json file log4j2.json in the classpath of my gradle project and I got the same error.

The solution here was to add dependency for JSON handling to my gradle dependencies.

compile group:"com.fasterxml.jackson.core", name:"jackson-core", version:'2.8.4'
compile group:"com.fasterxml.jackson.core", name:"jackson-databind", version:'2.8.4'
compile group:"com.fasterxml.jackson.core", name:"jackson-annotations", version:'2.8.4'

See also documentation of log4j2:

The JSON support uses the Jackson Data Processor to parse the JSON files. These dependencies must be added to a project that wants to use JSON for configuration:

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

HTML/Javascript change div content

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="radio" name="radiobutton" value="A" onclick = "populateData(event)">
  <input type="radio" name="radiobutton" value="B" onclick = "populateData(event)">

    <div id="content"></div>
</body>
</html>

-----------------JS- code------------

var targetDiv = document.getElementById('content');
    var htmlContent = '';

    function populateData(event){
      switch(event.target.value){
        case 'A':{
         htmlContent = 'Content for A';
          break;
        }
        case 'B':{
          htmlContent = "content for B";
break;
        }
      }
      targetDiv.innerHTML = htmlContent;
    }

Step1: on click of the radio button it calls function populate data, with event (an object that has event details such as name of the element, value etc..);

Step2: I extracted the value through event.target.value and then simple switch will give me freedom to add custom text.

Live Code

https://jsbin.com/poreway/edit?html,js,output

Hibernate openSession() vs getCurrentSession()

openSession: When you call SessionFactory.openSession, it always creates a new Session object and give it to you.

You need to explicitly flush and close these session objects.

As session objects are not thread safe, you need to create one session object per request in multi-threaded environment and one session per request in web applications too.

getCurrentSession: When you call SessionFactory.getCurrentSession, it will provide you session object which is in hibernate context and managed by hibernate internally. It is bound to transaction scope.

When you call SessionFactory.getCurrentSession, it creates a new Session if it does not exist, otherwise use same session which is in current hibernate context. It automatically flushes and closes session when transaction ends, so you do not need to do it externally.

If you are using hibernate in single-threaded environment , you can use getCurrentSession, as it is faster in performance as compared to creating a new session each time.

You need to add following property to hibernate.cfg.xml to use getCurrentSession method:

<session-factory>
    <!--  Put other elements here -->
    <property name="hibernate.current_session_context_class">
          thread
    </property>
</session-factory>

On linux SUSE or RedHat, how do I load Python 2.7

Execute the below commands to make yum work as well as python2.7

yum groupinstall -y development
yum groupinstall -y 'development tools'
yum install -y zlib-dev openssl-devel wget sqlite-devel bzip2-devel
yum -y install gcc gcc-c++ numpy python-devel scipy git boost*
yum install -y *lapack*
yum install -y gcc gcc-c++ make bison flex autoconf libtool memcached libevent libevent-devel uuidd libuuid-devel  boost boost-devel libcurl-dev libcurl curl gperf mysql-devel

cd
mkdir srk
cd srk 
wget http://www.python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz
yum install xz-libs
xz -d Python-2.7.6.tar.xz
tar -xvf Python-2.7.6.tar
cd Python-2.7.6
./configure --prefix=/usr/local
make
make altinstall



echo "export PATH="/usr/local/bin:$PATH"" >> /etc/profile
source /etc/profile
mv /usr/bin/python /usr/bin/python.bak
update-alternatives --install /usr/bin/python python /usr/bin/python2.6 1
update-alternatives --install /usr/bin/python python /usr/local/bin/python2.7 2
update-alternatives --config python
sed -i "s/python/python2.6/g" /usr/bin/yum

How to append multiple values to a list in Python

If you take a look at the official docs, you'll see right below append, extend. That's what your looking for.

There's also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.

How to set RelativeLayout layout params in code not in xml?

How about you just pull the layout params from the view itself if you created it.

$((RelativeLayout)findViewById(R.id.imageButton1)).getLayoutParams();

AngularJS: how to implement a simple file upload with multipart form?

You can use the simple/lightweight ng-file-upload directive. It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directive.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
  $scope.onFileSelect = function($files) {
  Upload.upload({
    url: 'my/upload/url',
    file: $files,            
  }).progress(function(e) {
  }).then(function(data, status, headers, config) {
    // file is uploaded successfully
    console.log(data);
  }); 

}];

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Creating SubString (prefix and suffix) from String using Swift 4:

let str : String = "ilike"
for i in 0...str.count {
    let index = str.index(str.startIndex, offsetBy: i) // String.Index
    let prefix = str[..<index] // String.SubSequence
    let suffix = str[index...] // String.SubSequence
    print("prefix \(prefix), suffix : \(suffix)")
}

Output

prefix , suffix : ilike
prefix i, suffix : like
prefix il, suffix : ike
prefix ili, suffix : ke
prefix ilik, suffix : e
prefix ilike, suffix : 

If you want to generate a substring between 2 indices , use :

let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You get this error because one of your variables is actually a factor variable . Execute

str(df) 

to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:

df$year <- as.numeric(as.character(df$year))

EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:

df <- data.frame(apply(df, 2, unclass))

and plot again?

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

sending email via php mail function goes to spam

What we usually do with e-mail, preventing spam-folders as the end destination, is using either Gmail as the smtp server or Mandrill as the smtp server.

How to get numeric position of alphabets in java?

String str = "abcdef";
char[] ch  = str.toCharArray();
for(char c : ch){
    int temp = (int)c;
    int temp_integer = 96; //for lower case
    if(temp<=122 & temp>=97)
        System.out.print(temp-temp_integer);
}

Output:

123456

@Shiki for Capital/UpperCase letters use the following code:

String str = "DEFGHI";
char[] ch  = str.toCharArray();
for(char c : ch){
    int temp = (int)c;
    int temp_integer = 64; //for upper case
    if(temp<=90 & temp>=65)
        System.out.print(temp-temp_integer);
}

Output:

456789

Reading/Writing a MS Word file in PHP

2007 might be a bit complicated as well.

The .docx format is a zip file that contains a few folders with other files in them for formatting and other stuff.

Rename a .docx file to .zip and you'll see what I mean.

So if you can work within zip files in PHP, you should be on the right path.

What is the difference between SessionState and ViewState?

Session is used mainly for storing user specific data [ session specific data ]. In the case of session you can use the value for the whole session until the session expires or the user abandons the session. Viewstate is the type of data that has scope only in the page in which it is used. You canot have viewstate values accesible to other pages unless you transfer those values to the desired page. Also in the case of viewstate all the server side control datas are transferred to the server as key value pair in __Viewstate and transferred back and rendered to the appropriate control in client when postback occurs.

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

Another solution for many cases is to make sure that the transition between UIViewControllers happens after the not-suitable (like during initialization) procedure finishes, by doing:

__weak MyViewController *weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
    [weakSelf presentViewController:vc animated:YES];
});

This is general for also pushViewController:animated:, etc.

Powershell Log Off Remote Session

You can use Invoke-RDUserLogoff

An example logging off Active Directory users of a specific Organizational Unit:

$users = Get-ADUser -filter * -SearchBase "ou=YOUR_OU_NAME,dc=contoso,dc=com"

Get-RDUserSession | where { $users.sAMAccountName -contains $_.UserName } | % { $_ | Invoke-RDUserLogoff -Force }

At the end of the pipe, if you try to use only foreach (%), it will log off only one user. But using this combination of foreach and pipe:

| % { $_ | command }

will work as expected.

Ps. Run as Adm.

Change color of PNG image via CSS?

In most browsers, you can use filters :

  • on both <img> elements and background images of other elements

  • and set them either statically in your CSS, or dynamically using JavaScript

See demos below.


<img> elements

You can apply this technique to a <img> element :

_x000D_
_x000D_
#original, #changed {_x000D_
    width: 45%;_x000D_
    padding: 2.5%;_x000D_
    float: left;_x000D_
}_x000D_
_x000D_
#changed {_x000D_
    -webkit-filter : hue-rotate(180deg);_x000D_
    filter : hue-rotate(180deg);_x000D_
}
_x000D_
<img id="original" src="http://i.stack.imgur.com/rfar2.jpg" />_x000D_
_x000D_
<img id="changed" src="http://i.stack.imgur.com/rfar2.jpg" />
_x000D_
_x000D_
_x000D_

Background images

You can apply this technique to a background image :

_x000D_
_x000D_
#original, #changed {_x000D_
    background: url('http://i.stack.imgur.com/kaKzj.jpg');_x000D_
    background-size: cover;_x000D_
    width: 30%;_x000D_
    margin: 0 10% 0 10%;_x000D_
    padding-bottom: 28%;_x000D_
    float: left;_x000D_
}_x000D_
_x000D_
#changed {_x000D_
    -webkit-filter : hue-rotate(180deg);_x000D_
    filter : hue-rotate(180deg);_x000D_
}
_x000D_
<div id="original"></div>_x000D_
_x000D_
<div id="changed"></div>
_x000D_
_x000D_
_x000D_

JavaScript

You can use JavaScript to set a filter at runtime :

_x000D_
_x000D_
var element = document.getElementById("changed");_x000D_
var filter = 'hue-rotate(120deg) saturate(2.4)';_x000D_
element.style['-webkit-filter'] = filter;_x000D_
element.style['filter'] = filter;
_x000D_
#original, #changed {_x000D_
    margin: 0 10%;_x000D_
    width: 30%;_x000D_
    float: left;_x000D_
    background: url('http://i.stack.imgur.com/856IQ.png');_x000D_
    background-size: cover;_x000D_
    padding-bottom: 25%;_x000D_
}
_x000D_
<div id="original"></div>_x000D_
_x000D_
<div id="changed"></div>
_x000D_
_x000D_
_x000D_

How to call a button click event from another method

you can call the button_click event by passing..

private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}

private void ChildNode_Click(object sender, RoutedEventArgs args)
{
   SubGraphButton_Click(sender, args);
}

Also without passing..

private void SubGraphButton_Click(object sender, EventArgs args)
{
}

private void Some_Method() //this method is called
{
   SubGraphButton_Click(new object(), new EventArgs());
}

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

JBoss AS 7: How to clean up tmp?

I do not have experience with version 7 of JBoss but with 5 I often had issues when redeploying apps which went away when I cleaned the work and tmp folder. I wrote a script for that which was executed everytime the server shut down. Maybe executing it before startup is better considering abnormal shutdowns (which weren't uncommon with Jboss 5 :))

ThreadStart with parameters

One of the 2 overloads of the Thread constructor takse a ParameterizedThreadStart delegate which allows you to pass a single parameter to the start method. Unfortunately though it only allows for a single parameter and it does so in an unsafe way because it passes it as object. I find it's much easier to use a lambda expression to capture the relevant parameters and pass them in a strongly typed fashion.

Try the following

public Thread StartTheThread(SomeType param1, SomeOtherType param2) {
  var t = new Thread(() => RealStart(param1, param2));
  t.Start();
  return t;
}

private static void RealStart(SomeType param1, SomeOtherType param2) {
  ...
}

Angular 2: How to write a for loop, not a foreach loop

Depending on the length of the wanted loop, maybe even a more "template-driven" solution:

<ul>
  <li *ngFor="let index of [0,1,2,3,4,5]">
    {{ index }}
  </li>
</ul>

LINQ Contains Case Insensitive

Use String.Equals Method

public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
    return this.ObjectContext.FACILITY_ITEM
           .Where(fi => fi.DESCRIPTION
           .Equals(description, StringComparison.OrdinalIgnoreCase));
}

'setInterval' vs 'setTimeout'

setInterval()

setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().

if you want to loop code for animations or clocks Then use setInterval.

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

setTimeout()

setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);

if you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.

How can I export the schema of a database in PostgreSQL?

pg_dump -d <databasename> -h <hostname> -p <port> -n <schemaname> -f <location of the dump file>

Please notice that you have sufficient privilege to access that schema. If you want take backup as specific user add user name in that command preceded by -U

Set value to currency in <input type="number" />

You guys are completely right numbers can only go in the numeric field. I use the exact same thing as already listed with a bit of css styling on a span tag:

<span>$</span><input type="number" min="0.01" step="0.01" max="2500" value="25.67">

Then add a bit of styling magic:

span{
  position:relative;
  margin-right:-20px
}
input[type='number']{
  padding-left:20px;
  text-align:left;
}

How to increase heap size of an android application?

This can be done by two ways according to your Android OS.

  1. You can use android:largeHeap="true" in application tag of Android manifest to request a larger heap size, but this will not work on any pre Honeycomb devices.
  2. On pre 2.3 devices, you can use the VMRuntime class, but this will not work on Gingerbread and above See below how to do it.
VMRuntime.getRuntime().setMinimumHeapSize(BIGGER_SIZE);

Before Setting HeapSize make sure that you have entered the appropriate size which will not affect other application or OS functionality. Before settings just check how much size your app takes & then set the size just to fulfill your job. Dont use so much of memory otherwise other apps might affect.

Reference: http://dwij.co.in/increase-heap-size-of-android-application

Modifying Objects within stream in Java8 while iterating

To do structural modification on the source of the stream, as Pshemo mentioned in his answer, one solution is to create a new instance of a Collection like ArrayList with the items inside your primary list; iterate over the new list, and do the operations on the primary list.

new ArrayList<>(users).stream().forEach(u -> users.remove(u));

How to pause javascript code execution for 2 seconds

There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:

for (var i = 1; i <= 5; i++) {
    var tick = function(i) {
        return function() {
            console.log(i);
        }
    };
    setTimeout(tick(i), 500 * i);
}

Demo here: http://jsfiddle.net/hW7Ch/

INFO: No Spring WebApplicationInitializer types detected on classpath

I had similar problem with Tomcat 8 embedded in java7 application.

When I launched Tomcat in my application, it worked. But when I launched it through Maven for integration test purpose, I got this error : "No Spring WebApplicationInitializer types detected on classpath".

I fixed it by upgrading org.apache.tomcat.embed:tomcat-embed-* dependencies from version 8.0.29 to 8.0.47.

How to open a link in new tab (chrome) using Selenium WebDriver?

To switch between tabs action class does not always works on all browser and on all webdriver. the best way is to use robot class. try this code.

        String website = "https://www.google.com";
        String website1 = "https://www.msn.com/en-in/";
        String controlpath = "C:\\Libraries\\msedgedriver.exe";
        System.setProperty("webdriver.edge.driver", controlpath);
        driver = new EdgeDriver();
        driver.manage().window().maximize(); //  Maximize browser
        driver.get(website);
        System.out.println("Google page");
        
        Robot robot = new Robot();                          
        robot.keyPress(KeyEvent.VK_CONTROL); 
        robot.keyPress(KeyEvent.VK_T); 
        robot.keyRelease(KeyEvent.VK_CONTROL); 
        robot.keyRelease(KeyEvent.VK_T);
        
        //Switch focus to new tab
        ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
        //System.out.println("Handle info"+ driver.getWindowHandles());
        driver.switchTo().window(tabs.get(1));
    
        //Launch URL in the new tab
        driver.get(website1);
        System.out.println("msn page");
        Thread.sleep(5000);
        driver.switchTo().window(tabs.get(0));
        Thread.sleep(5000);

Breaking out of a nested loop

It seems to me like people dislike a goto statement a lot, so I felt the need to straighten this out a bit.

I believe the 'emotions' people have about goto eventually boil down to understanding of code and (misconceptions) about possible performance implications. Before answering the question, I will therefore first go into some of the details on how it's compiled.

As we all know, C# is compiled to IL, which is then compiled to assembler using an SSA compiler. I'll give a bit of insights into how this all works, and then try to answer the question itself.

From C# to IL

First we need a piece of C# code. Let's start simple:

foreach (var item in array)
{
    // ... 
    break;
    // ...
}

I'll do this step by step to give you a good idea of what happens under the hood.

First translation: from foreach to the equivalent for loop (Note: I'm using an array here, because I don't want to get into details of IDisposable -- in which case I'd also have to use an IEnumerable):

for (int i=0; i<array.Length; ++i)
{
    var item = array[i];
    // ...
    break;
    // ...
}

Second translation: the for and break is translated into an easier equivalent:

int i=0;
while (i < array.Length)
{
    var item = array[i];
    // ...
    break;
    // ...
    ++i;
}

And third translation (this is the equivalent of the IL code): we change break and while into a branch:

    int i=0; // for initialization

startLoop:
    if (i >= array.Length) // for condition
    {
        goto exitLoop;
    }
    var item = array[i];
    // ...
    goto exitLoop; // break
    // ...
    ++i;           // for post-expression
    goto startLoop; 

While the compiler does these things in a single step, it gives you insight into the process. The IL code that evolves from the C# program is the literal translation of the last C# code. You can see for yourself here: https://dotnetfiddle.net/QaiLRz (click 'view IL')

Now, one thing you have observed here is that during the process, the code becomes more complex. The easiest way to observe this is by the fact that we needed more and more code to ackomplish the same thing. You might also argue that foreach, for, while and break are actually short-hands for goto, which is partly true.

From IL to Assembler

The .NET JIT compiler is an SSA compiler. I won't go into all the details of SSA form here and how to create an optimizing compiler, it's just too much, but can give a basic understanding about what will happen. For a deeper understanding, it's best to start reading up on optimizing compilers (I do like this book for a brief introduction: http://ssabook.gforge.inria.fr/latest/book.pdf ) and LLVM (llvm.org).

Every optimizing compiler relies on the fact that code is easy and follows predictable patterns. In the case of FOR loops, we use graph theory to analyze branches, and then optimize things like cycli in our branches (e.g. branches backwards).

However, we now have forward branches to implement our loops. As you might have guessed, this is actually one of the first steps the JIT is going to fix, like this:

    int i=0; // for initialization

    if (i >= array.Length) // for condition
    {
        goto endOfLoop;
    }

startLoop:
    var item = array[i];
    // ...
    goto endOfLoop; // break
    // ...
    ++i;           // for post-expression

    if (i >= array.Length) // for condition
    {
        goto startLoop;
    }

endOfLoop:
    // ...

As you can see, we now have a backward branch, which is our little loop. The only thing that's still nasty here is the branch that we ended up with due to our break statement. In some cases, we can move this in the same way, but in others it's there to stay.

So why does the compiler do this? Well, if we can unroll the loop, we might be able to vectorize it. We might even be able to proof that there's just constants being added, which means our whole loop could vanish into thin air. To summarize: by making the patterns predictable (by making the branches predictable), we can proof that certain conditions hold in our loop, which means we can do magic during the JIT optimization.

However, branches tend to break those nice predictable patterns, which is something optimizers therefore kind-a dislike. Break, continue, goto - they all intend to break these predictable patterns- and are therefore not really 'nice'.

You should also realize at this point that a simple foreach is more predictable then a bunch of goto statements that go all over the place. In terms of (1) readability and (2) from an optimizer perspective, it's both the better solution.

Another thing worth mentioning is that it's very relevant for optimizing compilers to assign registers to variables (a process called register allocation). As you might know, there's only a finite number of registers in your CPU and they are by far the fastest pieces of memory in your hardware. Variables used in code that's in the inner-most loop, are more likely to get a register assigned, while variables outside of your loop are less important (because this code is probably hit less).

Help, too much complexity... what should I do?

The bottom line is that you should always use the language constructs you have at your disposal, which will usually (implictly) build predictable patterns for your compiler. Try to avoid strange branches if possible (specifically: break, continue, goto or a return in the middle of nothing).

The good news here is that these predictable patterns are both easy to read (for humans) and easy to spot (for compilers).

One of those patterns is called SESE, which stands for Single Entry Single Exit.

And now we get to the real question.

Imagine that you have something like this:

// a is a variable.

for (int i=0; i<100; ++i) 
{
  for (int j=0; j<100; ++j)
  {
     // ...

     if (i*j > a) 
     {
        // break everything
     }
  }
}

The easiest way to make this a predictable pattern is to simply eliminate the if completely:

int i, j;
for (i=0; i<100 && i*j <= a; ++i) 
{
  for (j=0; j<100 && i*j <= a; ++j)
  {
     // ...
  }
}

In other cases you can also split the method into 2 methods:

// Outer loop in method 1:

for (i=0; i<100 && processInner(i); ++i) 
{
}

private bool processInner(int i)
{
  int j;
  for (j=0; j<100 && i*j <= a; ++j)
  {
     // ...
  }
  return i*j<=a;
}

Temporary variables? Good, bad or ugly?

You might even decide to return a boolean from within the loop (but I personally prefer the SESE form because that's how the compiler will see it and I think it's cleaner to read).

Some people think it's cleaner to use a temporary variable, and propose a solution like this:

bool more = true;
for (int i=0; i<100; ++i) 
{
  for (int j=0; j<100; ++j) 
  {
     // ...
     if (i*j > a) { more = false; break; } // yuck.
     // ...
  }
  if (!more) { break; } // yuck.
  // ...
}
// ...

I personally am opposed to this approach. Look again on how the code is compiled. Now think about what this will do with these nice, predictable patterns. Get the picture?

Right, let me spell it out. What will happen is that:

  • The compiler will write out everything as branches.
  • As an optimization step, the compiler will do data flow analysis in an attempt to remove the strange more variable that only happens to be used in control flow.
  • If succesful, the variable more will be eliminated from the program, and only branches remain. These branches will be optimized, so you will get only a single branch out of the inner loop.
  • If unsuccesful, the variable more is definitely used in the inner-most loop, so if the compiler won't optimize it away, it has a high chance to be allocated to a register (which eats up valuable register memory).

So, to summarize: the optimizer in your compiler will go into a hell of a lot of trouble to figure out that more is only used for the control flow, and in the best case scenario will translate it to a single branch outside of the outer for loop.

In other words, the best case scenario is that it will end up with the equivalent of this:

for (int i=0; i<100; ++i) 
{
  for (int j=0; j<100; ++j)
  {
     // ...
     if (i*j > a) { goto exitLoop; } // perhaps add a comment
     // ...
  }
  // ...
}
exitLoop:

// ...

My personal opinion on this is quite simple: if this is what we intended all along, let's make the world easier for both the compiler and readability, and write that right away.

tl;dr:

Bottom line:

  • Use a simple condition in your for loop if possible. Stick to the high-level language constructs you have at your disposal as much as possible.
  • If everything fails and you're left with either goto or bool more, prefer the former.

Setting up a cron job in Windows

  1. Make sure you logged on as an administrator or you have the same access as an administrator.
  2. Start->Control Panel->System and Security->Administrative Tools->Task Scheduler
  3. Action->Create Basic Task->Type a name and Click Next
  4. Follow through the wizard.

How can I make my website's background transparent without making the content (images & text) transparent too?

I think the simplest solution, rather than making the body element partially transparent, would be to add an extra div to hold the background, and change the opacity there, instead.

So you would add a div like:

<div id="background"></div>

And move your body element's background CSS to it, as well as some additional positioning properties, like this:

#background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('images/background.jpg');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: 100%;
    opacity: 0.8;
    filter:alpha(opacity=80);
}

Here's an example: http://jsfiddle.net/nbVg4/4/

Where does pip install its packages?

By default, on Linux, Pip installs packages to /usr/local/lib/python2.7/dist-packages.

Using virtualenv or --user during install will change this default location. If you use pip show make sure you are using the right user or else pip may not see the packages you are referencing.

How do I create an .exe for a Java program?

I used exe4j to package all java jars into one final .exe file, which user can use it as normal windows application.

How to get htaccess to work on MAMP

I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:

<Directory "/Applications/MAMP/bin/mamp">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

You need to change: AllowOverride None To: AllowOverride All

Moving up one directory in Python

Well.. I'm not sure how portable os.chdir('..') would actually be. Under Unix those are real filenames. I would prefer the following:

import os
os.chdir(os.path.dirname(os.getcwd()))

That gets the current working directory, steps up one directory, and then changes to that directory.

Node.js global variables

In Node.js, you can set global variables via the "global" or "GLOBAL" object:

GLOBAL._ = require('underscore'); // But you "shouldn't" do this! (see note below)

or more usefully...

GLOBAL.window = GLOBAL;  // Like in the browser

From the Node.js source, you can see that these are aliased to each other:

node-v0.6.6/src/node.js:
28:     global = this;
128:    global.GLOBAL = global;

In the code above, "this" is the global context. With the CommonJS module system (which Node.js uses), the "this" object inside of a module (i.e., "your code") is not the global context. For proof of this, see below where I spew the "this" object and then the giant "GLOBAL" object.

console.log("\nTHIS:");
console.log(this);
console.log("\nGLOBAL:");
console.log(global);

/* Outputs ...

THIS:
{}

GLOBAL:
{ ArrayBuffer: [Function: ArrayBuffer],
  Int8Array: { [Function] BYTES_PER_ELEMENT: 1 },
  Uint8Array: { [Function] BYTES_PER_ELEMENT: 1 },
  Int16Array: { [Function] BYTES_PER_ELEMENT: 2 },
  Uint16Array: { [Function] BYTES_PER_ELEMENT: 2 },
  Int32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Uint32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Float32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Float64Array: { [Function] BYTES_PER_ELEMENT: 8 },
  DataView: [Function: DataView],
  global: [Circular],
  process:
   { EventEmitter: [Function: EventEmitter],
     title: 'node',
     assert: [Function],
     version: 'v0.6.5',
     _tickCallback: [Function],
     moduleLoadList:
      [ 'Binding evals',
        'Binding natives',
        'NativeModule events',
        'NativeModule buffer',
        'Binding buffer',
        'NativeModule assert',
        'NativeModule util',
        'NativeModule path',
        'NativeModule module',
        'NativeModule fs',
        'Binding fs',
        'Binding constants',
        'NativeModule stream',
        'NativeModule console',
        'Binding tty_wrap',
        'NativeModule tty',
        'NativeModule net',
        'NativeModule timers',
        'Binding timer_wrap',
        'NativeModule _linklist' ],
     versions:
      { node: '0.6.5',
        v8: '3.6.6.11',
        ares: '1.7.5-DEV',
        uv: '0.6',
        openssl: '0.9.8n' },
     nextTick: [Function],
     stdout: [Getter],
     arch: 'x64',
     stderr: [Getter],
     platform: 'darwin',
     argv: [ 'node', '/workspace/zd/zgap/darwin-js/index.js' ],
     stdin: [Getter],
     env:
      { TERM_PROGRAM: 'iTerm.app',
        'COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET': '/tmp/launch-nNl1vo/ServiceProcessSocket',
        TERM: 'xterm',
        SHELL: '/bin/bash',
        TMPDIR: '/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/',
        Apple_PubSub_Socket_Render: '/tmp/launch-9Ga0PT/Render',
        USER: 'ddopson',
        COMMAND_MODE: 'unix2003',
        SSH_AUTH_SOCK: '/tmp/launch-sD905b/Listeners',
        __CF_USER_TEXT_ENCODING: '0x12D732E7:0:0',
        PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11/bin',
        PWD: '/workspace/zd/zgap/darwin-js',
        LANG: 'en_US.UTF-8',
        ITERM_PROFILE: 'Default',
        SHLVL: '1',
        COLORFGBG: '7;0',
        HOME: '/Users/ddopson',
        ITERM_SESSION_ID: 'w0t0p0',
        LOGNAME: 'ddopson',
        DISPLAY: '/tmp/launch-l9RQXI/org.x:0',
        OLDPWD: '/workspace/zd/zgap/darwin-js/external',
        _: './index.js' },
     openStdin: [Function],
     exit: [Function],
     pid: 10321,
     features:
      { debug: false,
        uv: true,
        ipv6: true,
        tls_npn: false,
        tls_sni: true,
        tls: true },
     kill: [Function],
     execPath: '/usr/local/bin/node',
     addListener: [Function],
     _needTickCallback: [Function],
     on: [Function],
     removeListener: [Function],
     reallyExit: [Function],
     chdir: [Function],
     debug: [Function],
     error: [Function],
     cwd: [Function],
     watchFile: [Function],
     umask: [Function],
     getuid: [Function],
     unwatchFile: [Function],
     mixin: [Function],
     setuid: [Function],
     setgid: [Function],
     createChildProcess: [Function],
     getgid: [Function],
     inherits: [Function],
     _kill: [Function],
     _byteLength: [Function],
     mainModule:
      { id: '.',
        exports: {},
        parent: null,
        filename: '/workspace/zd/zgap/darwin-js/index.js',
        loaded: false,
        exited: false,
        children: [],
        paths: [Object] },
     _debugProcess: [Function],
     dlopen: [Function],
     uptime: [Function],
     memoryUsage: [Function],
     uvCounters: [Function],
     binding: [Function] },
  GLOBAL: [Circular],
  root: [Circular],
  Buffer:
   { [Function: Buffer]
     poolSize: 8192,
     isBuffer: [Function: isBuffer],
     byteLength: [Function],
     _charsWritten: 8 },
  setTimeout: [Function],
  setInterval: [Function],
  clearTimeout: [Function],
  clearInterval: [Function],
  console: [Getter],
  window: [Circular],
  navigator: {} }
*/

** Note: regarding setting "GLOBAL._", in general you should just do var _ = require('underscore');. Yes, you do that in every single file that uses Underscore.js, just like how in Java you do import com.foo.bar;. This makes it easier to figure out what your code is doing because the linkages between files are 'explicit'. It is mildly annoying, but a good thing. .... That's the preaching.

There is an exception to every rule. I have had precisely exactly one instance where I needed to set "GLOBAL._". I was creating a system for defining "configuration" files which were basically JSON, but were "written in JavaScript" to allow a bit more flexibility. Such configuration files had no 'require' statements, but I wanted them to have access to Underscore.js (the entire system was predicated on Underscore.js and Underscore.js templates), so before evaluating the "configuration", I would set "GLOBAL._". So yeah, for every rule, there's an exception somewhere. But you had better have a darn good reason and not just "I get tired of typing 'require', so I want to break with the convention".

How to bring a window to the front?

This simple method worked for me perfectly in Windows 7:

    private void BringToFront() {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                if(jFrame != null) {
                    jFrame.toFront();
                    jFrame.repaint();
                }
            }
        });
    }

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Pretty-Print JSON Data to a File using Python

If you already have existing JSON files which you want to pretty format you could use this:

    with open('twitterdata.json', 'r+') as f:
        data = json.load(f)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()

Twitter bootstrap progress bar animation on page load

EDIT

  • Class name changed from bar to progress-bar in v3.1.1

HTML

<div class="container">
    <div class="progress progress-striped active">
        <div class="bar" style="width: 0%;"></div>
    </div>
</div>?

CSS

@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');

.container {
    margin-top: 30px;
    width: 400px;
}?

jQuery used in the fiddle below and on the document.ready

$(document).ready(function(){

    var progress = setInterval(function() {
        var $bar = $('.bar');

        if ($bar.width()>=400) {
            clearInterval(progress);
            $('.progress').removeClass('active');
        } else {
            $bar.width($bar.width()+40);
        }
        $bar.text($bar.width()/4 + "%");
    }, 800);

});?

Demo

JSFiddle

Updated JSFiddle

How can I check if a string is null or empty in PowerShell?

If it is a parameter in a function, you can validate it with ValidateNotNullOrEmpty as you can see in this example:

Function Test-Something
{
    Param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$UserName
    )

    #stuff todo
}

Center Oversized Image in Div

One option you can use is object-fit: cover it behaves a bit like background-size: cover. More on object-fit.

ignore all the JS below, that's just for the demo.

The key here is that you need to set the image inside a wrapper and give it the following properties.

.wrapper img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

I've created a demo below where you change the height / width of the wrapper and see in play. The image will always be vertically and horizontally centered. It will take up 100% of its parent width and height, and will not be stretched / squashed. This means that the aspect ratio of the image is maintained. The changes are applied by zooming in / out instead.

The only downside to object-fit is that it doesn't work on IE11.

_x000D_
_x000D_
// for demo only_x000D_
const wrapper = document.querySelector('.wrapper');_x000D_
const button = document.querySelector('button');_x000D_
const widthInput = document.querySelector('.width-input');_x000D_
const heightInput = document.querySelector('.height-input');_x000D_
_x000D_
_x000D_
const resizeWrapper = () => {_x000D_
  wrapper.style.width = widthInput.value + "px";_x000D_
  wrapper.style.height = heightInput.value + "px";_x000D_
}_x000D_
_x000D_
button.addEventListener("click", resizeWrapper);
_x000D_
.wrapper {_x000D_
  overflow: hidden;_x000D_
  max-width: 100%;_x000D_
  margin-bottom: 2em;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
_x000D_
.wrapper img {_x000D_
  display: block;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  object-fit: cover;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <img src="https://i.imgur.com/DrzMS8i.png">_x000D_
</div>_x000D_
_x000D_
_x000D_
<!-- demo only -->_x000D_
<lable for="width">_x000D_
  Width: <input name="width" class='width-input'>_x000D_
</lable>_x000D_
<lable for="height">_x000D_
  height: <input name="height" class='height-input'>_x000D_
</lable>_x000D_
<button>change size!</button>
_x000D_
_x000D_
_x000D_

Fixed height and width for bootstrap carousel

In your main styles.css file change height/auto to whatever settings you desire. For example, 500px:

#myCarousel {
  height: auto;
  width: auto;
  overflow: hidden;
}

How to locate the php.ini file (xampp)

I’ve run into the need while running on PhpStorm on my Mac. Follow the orange text.

enter image description here

Pass object to javascript function

Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object

If using ES6:

    function yourFunction(args){
        let defaults = {opt1: true, opt2: 'something'};
        let params = {...defaults, ...args}; // right-most object overwrites 
        console.log(params.opt1);
    }

Older Browsers using Object.assign(target, source):

    function yourFunction(args){
        var defaults = {opt1: true, opt2: 'something'};
        var params = Object.assign(defaults, args) // args overwrites as it is source
        console.log(params.opt1);
    }

How do I call a non-static method from a static method in C#?

Perhaps what you are looking for is the Singleton pattern?

public class Singleton
{
    private Singleton() {}

    public void DoWork()
    { 
        // do something
    }

    // You can call this static method which calls the singleton instance method.
    public static void DoSomeWork()
    { 
        Instance.DoWork();
    }

    public static Singleton Instance
    {
        get { return instance; } 
    }

    private static Singleton instance = new Singleton();
}

You still have to create an instance of the class but you ensure there is only one instance.

Python 3: EOF when reading a line (Sublime Text 2 is angry)

I had the same problem. The problem with the Sublime Text's default console is that it does not support input.

To solve it, you have to install a package called SublimeREPL. SublimeREPL provides a Python interpreter which accepts input.

There is an article that explains the solution in detail.

GitHub page for SublimeREPL

delete_all vs destroy_all?

You are right. If you want to delete the User and all associated objects -> destroy_all However, if you just want to delete the User without suppressing all associated objects -> delete_all

According to this post : Rails :dependent => :destroy VS :dependent => :delete_all

  • destroy / destroy_all: The associated objects are destroyed alongside this object by calling their destroy method
  • delete / delete_all: All associated objects are destroyed immediately without calling their :destroy method

Android Studio doesn't start, fails saying components not installed

For me, this issue was proxy related. In Mac osx, even while above error is displayed, there is menu bar for Android Studio at top. Select preferences Android Studio -> Preferences and change proxy as below and issue was resolved. There could be similar options in Windows/Linux to access preferences page while error is being displayed.

enter image description here

error code 1292 incorrect date value mysql

An update. Dates of the form '2019-08-00' will trigger the same error. Adding the lines:

[mysqld]

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" 

to mysql.cnf fixes this too. Inserting malformed dates now generates warnings for values out of range but does insert the data.

Trigger change() event when setting <select>'s value with val() function

I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately (a requirement of yours) triggers the following change code.

$('#selectField').change(function(){
    if($('#selectField').val() == 'N'){
        $('#secondaryInput').hide();
    } else {
        $('#secondaryInput').show();
}
});

Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".

$('#selectField').val(valueFromDatabase).change();

So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

Create a .bashrc file under ~/.bashrc and away you go. Similarly for ~/.gitconfig.

~ is usually your C:\Users\<your user name> folder. Typing echo ~ in the Git Bash terminal will tell you what that folder is.

If you can't create the file (e.g. running Windows), run the below command:

copy > ~/.bashrc

The window will output an error message (command not found), but the file will be created and ready for you to edit.

Is it possible to add dynamically named properties to JavaScript object?

ES6 for the win!

const b = 'b';
const c = 'c';

const data = {
    a: true,
    [b]: true, // dynamic property
    [`interpolated-${c}`]: true, // dynamic property + interpolation
    [`${b}-${c}`]: true
}

If you log data you get this:

{
  a: true,
  b: true,
  interpolated-c: true,
  b-c: true
}

This makes use of the new Computed Property syntax and Template Literals.

Printing Mongo query output to a file while in the mongo shell

If you invoke the shell with script-file, db address, and --quiet arguments, you can redirect the output (made with print() for example) to a file:

mongo localhost/mydatabase --quiet myScriptFile.js > output 

PHP Multidimensional Array Searching (Find key by specific value)

Try this

function recursive_array_search($needle,$haystack) {
        foreach($haystack as $key=>$value) {
            $current_key=$key;
            if($needle==$value['uid'] OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
                return $current_key;
            }
        }
        return false;
    }

If input field is empty, disable submit button

Please try this

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery</title>
    <meta charset="utf-8">       
    <script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
  </head>

  <body>

    <input type="text" id="message" value="" />
    <input type="button" id="sendButton" value="Send">

    <script>
    $(document).ready(function(){  

      var checkField;

      //checking the length of the value of message and assigning to a variable(checkField) on load
      checkField = $("input#message").val().length;  

      var enableDisableButton = function(){         
        if(checkField > 0){
          $('#sendButton').removeAttr("disabled");
        } 
        else {
          $('#sendButton').attr("disabled","disabled");
        }
      }        

      //calling enableDisableButton() function on load
      enableDisableButton();            

      $('input#message').keyup(function(){ 
        //checking the length of the value of message and assigning to the variable(checkField) on keyup
        checkField = $("input#message").val().length;
        //calling enableDisableButton() function on keyup
        enableDisableButton();
      });
    });
    </script>
  </body>
</html>

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

you can see this link

to check your node verison right. using NODE_MODULE_VERSION 51 means that your node version is nodejs v7.x, requires NODE_MODULE_VERSION 57 means you need upgrade your node to v8.x,so you need to upgrade your node. and then you need run npm rebuild command to rebuild your project

iptables LOG and DROP in one rule

Although already over a year old, I stumbled across this question a couple of times on other Google search and I believe I can improve on the previous answer for the benefit of others.

Short answer is you cannot combine both action in one line, but you can create a chain that does what you want and then call it in a one liner.

Let's create a chain to log and accept:

iptables -N LOG_ACCEPT

And let's populate its rules:

iptables -A LOG_ACCEPT -j LOG --log-prefix "INPUT:ACCEPT:" --log-level 6
iptables -A LOG_ACCEPT -j ACCEPT

Now let's create a chain to log and drop:

iptables -N LOG_DROP

And let's populate its rules:

iptables -A LOG_DROP -j LOG --log-prefix "INPUT:DROP: " --log-level 6
iptables -A LOG_DROP -j DROP

Now you can do all actions in one go by jumping (-j) to you custom chains instead of the default LOG / ACCEPT / REJECT / DROP:

iptables -A <your_chain_here> <your_conditions_here> -j LOG_ACCEPT
iptables -A <your_chain_here> <your_conditions_here> -j LOG_DROP

How do I call ::CreateProcess in c++ to launch a Windows executable?

There is an example at http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx

Just replace the argv[1] with your constant or variable containing the program.

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]\n", argv[0]);
        return;
    }

    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        argv[1],        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    ) 
    {
        printf( "CreateProcess failed (%d).\n", GetLastError() );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

How to get the last row of an Oracle a table

You can do it like this:

SELECT * FROM (SELECT your_table.your_field, versions_starttime
               FROM your_table
               VERSIONS BETWEEN TIMESTAMP MINVALUE AND MAXVALUE)
WHERE ROWNUM = 1;

Or:

SELECT your_field,ora_rowscn,scn_to_timestamp(ora_rowscn) from your_table WHERE ROWNUM = 1;

Can you remove elements from a std::list while iterating through it?

I think you have a bug there, I code this way:

for (std::list<CAudioChannel *>::iterator itAudioChannel = audioChannels.begin();
             itAudioChannel != audioChannels.end(); )
{
    CAudioChannel *audioChannel = *itAudioChannel;
    std::list<CAudioChannel *>::iterator itCurrentAudioChannel = itAudioChannel;
    itAudioChannel++;

    if (audioChannel->destroyMe)
    {
        audioChannels.erase(itCurrentAudioChannel);
        delete audioChannel;
        continue;
    }
    audioChannel->Mix(outBuffer, numSamples);
}

json parsing error syntax error unexpected end of input

Don't Return Empty Json

In My Case I was returning Empty Json String in .Net Core Web API Project.

So I Changed My Code

From

 return Ok();

To

 return Ok("Done");

It seems you have to return some string or object.

Hope this helps.

Nodejs - Redirect url

You have to use the following code:

response.writeHead(302 , {
           'Location' : '/view/index.html' // This is your url which you want
        });
response.end();

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

the printf() function is used to print both strings and variables to the screen while the puts() function only permits you to print a string only to your screen.

Why can't I call a public method in another class?

You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example

class Example {
  public static string NonInstanceMethod() {
    return "static";
  }
  public string InstanceMethod() { 
    return "non-static";
  }
}

static void SomeMethod() {
  Console.WriteLine(Example.NonInstanceMethod());
  Console.WriteLine(Example.InstanceMethod());  // Does not compile
  Example v1 = new Example();
  Console.WriteLine(v1.InstanceMethod());
}

how to concatenate two dictionaries to create a new one in Python?

Here's a one-liner (imports don't count :) that can easily be generalized to concatenate N dictionaries:

Python 3

from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))

and:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.items() for d in args))

Python 2.6 & 2.7

from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))

Output:

>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}

Generalized to concatenate N dicts:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.iteritems() for d in args))

I'm a little late to this party, I know, but I hope this helps someone.

jQuery - What are differences between $(document).ready and $(window).load?

This three function are the same.

$(document).ready(function(){

}) 

and

$(function(){

}); 

and

jQuery(document).ready(function(){

});

here $ is used for define jQuery like $ = jQuery.

Now difference is that

$(document).ready is jQuery event that is fired when DOM is loaded, so it’s fired when the document structure is ready.

$(window).load event is fired after whole content is loaded like page contain images,css etc.

Add click event on div tag using javascript

the document class selector:

document.getElementsByClassName('drill_cursor')[0].addEventListener('click',function(){},false)

also the document query selector https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

document.querySelector(".drill_cursor").addEventListener('click',function(){},false)

How to increase size of DOSBox window?

Here's how to change the dosbox.conf file in Linux to increase the size of the window. I actually DID what follows, so I can say it works (in 32-bit PCLinuxOS fullmontyKDE, anyway). The question's answer is in the .conf file itself.

You find this file in Linux at /home/(username)/.dosbox . In Konqueror or Dolphin, you must first check 'Hidden files' or you won't see the folder. Open it with KWrite superuser or your fav editor.

  1. Save the file with another name like 'dosbox-0.74original.conf' to preserve the original file in case you need to restore it.
  2. Search on 'resolution' and carefully read what the conf file says about changing it. There are essentially two variables: resolution and output. You want to leave fullresolution alone for now. Your question was about WINDOW, not full. So look for windowresolution, see what the comments in conf file say you can do. The best suggestion is to use a bigger-window resolution like 900x800 (which is what I used on a 1366x768 screen), but NOT the actual resolution of your machine (which would make the window fullscreen, and you said you didn't want that). Be specific, replacing the 'windowresolution=original' with 'windowresolution=900x800' or other dimensions. On my screen, that doubled the window size just as it does with the max Font tab in Windows Properties (for the exe file; as you'll see below the ==== marks, 32-bit Windows doesn't need Dosbox).

Then, search on 'output', and as the instruction in the conf file warns, if and only if you have 'hardware scaling', change the default 'output=surface' to something else; he then lists the optional other settings. I changed it to 'output=overlay'. There's one other setting to test: aspect. Search the file for 'aspect', and change the 'false' to 'true' if you want an even bigger window. When I did this, the window took up over half of the screen. With 'false' left alone, I had a somewhat smaller window (I use widescreen monitors, whether laptop or desktop, maybe that's why).

So after you've made the changes, save the file with the original name of dosbox-0.74.conf . Then, type dosbox at the command line or create a Launcher (in KDE, this is a right click on the desktop) with the command dosbox. You still have to go through the mount command (i.e., mount c~ c:\123 if that's the location and file you'll execute). I'm sure there's a way to make a script, but haven't yet learned how to do that.

`React/RCTBridgeModule.h` file not found

Latest releases of react-native libraries as explained in previous posts and here have breaking compatibility changes. If you do not plan to upgrade to react-native 0.40+ yet you can force install previous version of the library, for example with react-native-fs:

npm install --save -E [email protected]

How to get to a particular element in a List in java?

String[] is an array of Strings. Such an array is internally a class. Like all classes that don't explicitly extend some other class, it extends Object implicitly. The method toString() of class Object, by default, gives you the representation you see: the class name, followed by @, followed by the hash code in hex. Since the String[] class doesn't override the toString() method, you get that as a result.

Create some method that outputs the array elements for you. Iterate over the array and use System.out.print() (not print*ln*) on the elements.

How do I POST XML data with curl

Have you tried url-encoding the data ? cURL can take care of that for you :

curl -H "Content-type: text/xml" --data-urlencode "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/

Why is Android Studio reporting "URI is not registered"?

I had this problem and for me it was due to creating and manipulating resource files outside Android Studio. I followed the instructions on creating new resource files and folders through Android Studio and solved the problem. You need to create a new Resource File Not directory. It will let you specify or create a directory for you if you need it. If you are creating directories for layouts for different versions, enter the info at the top including the name of the resource file you want to copy to the new folder and select Version and enter the Android version. It will create the appropriate directory with a copy of your resource in it.

Limiting the number of characters in a string, and chopping off the rest

For readability, I prefer this:

if (inputString.length() > maxLength) {
    inputString = inputString.substring(0, maxLength);
}

over the accepted answer.

int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);

How to select specified node within Xpath node sets by index with Selenium?

Here is the solution for index variable

Let's say, you have found 5 elements with same locator and you would like to perform action on each element by providing index number (here, variable is used for index as "i")

for(int i=1; i<=5; i++)
{
    string xPathWithVariable = "(//div[@class='className'])" + "[" + i + "]";
    driver.FindElement(By.XPath(xPathWithVariable)).Click();
}

It takes XPath :

(//div[@class='className'])[1]
(//div[@class='className'])[2]
(//div[@class='className'])[3]
(//div[@class='className'])[4]
(//div[@class='className'])[5]

How to draw border around a UILabel?

Using an NSAttributedString string for your labels attributedText is probably your best bet. Check out this example.

\r\n, \r and \n what is the difference between them?

All 3 of them represent the end of a line. But...

  • \r (Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line
  • \n (Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n moves to the beginning of the line.
  • \r\n (End Of Line) → a combination of \r and \n

Adding a slide effect to bootstrap dropdown

I am using the code above but I have changed the delay effect by slideToggle.

It slides the dropdown on hover with animation.

$('.navbar .dropdown').hover(function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400);
    }, function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400)
    });

Call a Vue.js component method from outside the component

Using Vue 3:

const app = createApp({})

// register an options object
app.component('my-component', {
  /* ... */
})

....

// retrieve a registered component
const MyComponent = app.component('my-component')

MyComponent.methods.greet();

https://v3.vuejs.org/api/application-api.html#component

How to set my phpmyadmin user session to not time out so quickly?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where <your_new_timeout> is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

How do I allow HTTPS for Apache on localhost?

I'd like to add something to the very good answer of @CodeWarrior, that works perfectly on Chrome, but for Firefox needs an additional step.

Since Firefox does not thrust CA Certificates that Windows does by default, you need to go on about:config, scroll down to security.enterprise_roots.enabled and change it to true.

Now your certificate should be seen as valid also on Firefox.

Of course this is only for development purposes, since ssl trust is a critical security concern and change this settings only if you know the implications.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Forcing the TCP/IP connection (by providing 127.0.0.1 instead of localhost or .) can reveal the real reason for the error. In my case, the database name specified in connection string was incorrect.

So, here is the checklist so far:

  • Make sure Named Pipe is enabled in configuration manager (don't forget to restart the server).
  • Make sure SQL Server Authentication (or Mixed Mode) is enabled.
  • Make sure your user name and password are correct.
  • Make sure the database you are connecting to exists.

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

How to horizontally align ul to center of div?

Following is a list of solutions to centering things in CSS horizontally. The snippet includes all of them.

_x000D_
_x000D_
html {_x000D_
  font: 1.25em/1.5 Georgia, Times, serif;_x000D_
}_x000D_
_x000D_
pre {_x000D_
  color: #fff;_x000D_
  background-color: #333;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
blockquote {_x000D_
  max-width: 400px;_x000D_
  background-color: #e0f0d1;_x000D_
}_x000D_
_x000D_
blockquote > p {_x000D_
  font-style: italic;_x000D_
}_x000D_
_x000D_
blockquote > p:first-of-type::before {_x000D_
  content: open-quote;_x000D_
}_x000D_
_x000D_
blockquote > p:last-of-type::after {_x000D_
  content: close-quote;_x000D_
}_x000D_
_x000D_
blockquote > footer::before {_x000D_
  content: "\2014";_x000D_
}_x000D_
_x000D_
.container,_x000D_
blockquote {_x000D_
  position: relative;_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  background-color: tomato;_x000D_
}_x000D_
_x000D_
.container::after,_x000D_
blockquote::after {_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  padding: 2px 10px;_x000D_
  border: 1px dotted #000;_x000D_
  background-color: #fff;_x000D_
}_x000D_
_x000D_
.container::after {_x000D_
  content: ".container-" attr(data-num);_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
blockquote::after {_x000D_
  content: ".quote-" attr(data-num);_x000D_
  z-index: 2;_x000D_
}_x000D_
_x000D_
.container-4 {_x000D_
  margin-bottom: 200px;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 1_x000D_
 */_x000D_
.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 2_x000D_
 */_x000D_
.container-2 {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 3_x000D_
 */_x000D_
.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 4_x000D_
 */_x000D_
.container-4 {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 5_x000D_
 */_x000D_
.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<main>_x000D_
  <h1>CSS: Horizontal Centering</h1>_x000D_
_x000D_
  <h2>Uncentered Example</h2>_x000D_
  <p>This is the scenario: We have a container with an element inside of it that we want to center. I just added a little padding and background colors so both elements are distinquishable.</p>_x000D_
_x000D_
  <div class="container  container-0" data-num="0">_x000D_
    <blockquote class="quote-0" data-num="0">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 1: Using <code>max-width</code> & <code>margin</code> (IE7)</h2>_x000D_
_x000D_
  <p>This method is widely used. The upside here is that only the element which one wants to center needs rules.</p>_x000D_
_x000D_
<pre><code>.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-1" data-num="1">_x000D_
    <blockquote class="quote  quote-1" data-num="1">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 2: Using <code>display: inline-block</code> and <code>text-align</code> (IE8)</h2>_x000D_
_x000D_
  <p>This method utilizes that <code>inline-block</code> elements are treated as text and as such they are affected by the <code>text-align</code> property. This does not rely on a fixed width which is an upside. This is helpful for when you don’t know the number of elements in a container for example.</p>_x000D_
_x000D_
<pre><code>.container-2 {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-2" data-num="2">_x000D_
    <blockquote class="quote  quote-2" data-num="2">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 3: Using <code>display: table</code> and <code>margin</code> (IE8)</h2>_x000D_
_x000D_
  <p>Very similar to the second solution but only requires to apply rules on the element that is to be centered.</p>_x000D_
_x000D_
<pre><code>.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-3" data-num="3">_x000D_
    <blockquote class="quote  quote-3" data-num="3">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 4: Using <code>translate()</code> and <code>position</code> (IE9)</h2>_x000D_
_x000D_
  <p>Don’t use as a general approach for horizontal centering elements. The downside here is that the centered element will be removed from the document flow. Notice the container shrinking to zero height with only the padding keeping it visible. This is what <i>removing an element from the document flow</i> means.</p>_x000D_
_x000D_
  <p>There are however applications for this technique. For example, it works for <b>vertically</b> centering by using <code>top</code> or <code>bottom</code> together with <code>translateY()</code>.</p>_x000D_
_x000D_
<pre><code>.container-4 {_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-4" data-num="4">_x000D_
    <blockquote class="quote  quote-4" data-num="4">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 5: Using Flexible Box Layout Module (IE10+ with vendor prefix)</h2>_x000D_
_x000D_
  <p></p>_x000D_
_x000D_
<pre><code>.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-5" data-num="5">_x000D_
    <blockquote class="quote  quote-5" data-num="5">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
</main>
_x000D_
_x000D_
_x000D_


display: flex

.container {
  display: flex;
  justify-content: center;
}

Notes:


max-width & margin

You can horizontally center a block-level element by assigning a fixed width and setting margin-right and margin-left to auto.

.container ul {
  /* for IE below version 7 use `width` instead of `max-width` */
  max-width: 800px;
  margin-right: auto;
  margin-left: auto;
}

Notes:

  • No container needed
  • Requires (maximum) width of the centered element to be known

IE9+: transform: translatex(-50%) & left: 50%

This is similar to the quirky centering method which uses absolute positioning and negative margins.

.container {
  position: relative;
}

.container ul {
  position: absolute;
  left: 50%;
  transform: translatex(-50%);
}

Notes:

  • The centered element will be removed from document flow. All elements will completely ignore of the centered element.
  • This technique allows vertical centering by using top instead of left and translateY() instead of translateX(). The two can even be combined.
  • Browser support: transform2d

IE8+: display: table & margin

Just like the first solution, you use auto values for right and left margins, but don’t assign a width. If you don’t need to support IE7 and below, this is better suited, although it feels kind of hacky to use the table property value for display.

.container ul {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

IE8+: display: inline-block & text-align

Centering an element just like you would do with regular text is possible as well. Downside: You need to assign values to both a container and the element itself.

.container {
  text-align: center;
}

.container ul {
  display: inline-block;

  /* One most likely needs to realign flow content */
  text-align: initial;
}

Notes:

  • Does not require to specify a (maximum) width
  • Aligns flow content to the center (potentially unwanted side effect)
  • Works kind of well with a dynamic number of menu items (i.e. in cases where you can’t know the width a single item will take up)

In Angular, What is 'pathmatch: full' and what effect does it have?

pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match is the prefix path

pathMatch = 'prefix' tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.

Ref: https://angular.io/guide/router#set-up-redirects

pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.

pathMatch: 'prefix' means, the first route where the path matches the start of the URL is chosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.

How do I debug Windows services in Visual Studio?

Unfortunately, if you're trying to debug something at the very start of a Windows Service operation, "attaching" to the running process won't work. I tried using Debugger.Break() within the OnStart procecdure, but with a 64-bit, Visual Studio 2010 compiled application, the break command just throws an error like this:

System error 1067 has occurred.

At that point, you need to set up an "Image File Execution" option in your registry for your executable. It takes five minutes to set up, and it works very well. Here's a Microsoft article where the details are:

How to: Launch the Debugger Automatically

JSON to PHP Array using file_get_contents

You JSON is not a valid string as P. Galbraith has told you above.

and here is the solution for it.

<?php 
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "<pre>";
print_r($data);
echo "</pre>";
?>

Use this code it will work for you.

Adding integers to an int array

An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.

int[] num = new int[5];

This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.

num[0] = 1;
num[1] = 2;

The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:

[1,2,0,0,0]

As you can see you set values in it, you don't add them to the end.

If you want to be able to create a list of numbers which you add to, you should use ArrayList.

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

create or replace PROCEDURE PROC_USER_EXP 
AS
duplicate_exp EXCEPTION;
PRAGMA EXCEPTION_INIT( duplicate_exp, -20001 );
LVCOUNT NUMBER;
BEGIN
  SELECT COUNT(*) INTO LVCOUNT FROM JOBS WHERE JOB_TITLE='President';
  IF LVCOUNT >1 THEN 
   raise_application_error( -20001, 'Duplicate president customer excetpion' );
  END IF;

  EXCEPTION 
  WHEN duplicate_exp THEN 
  DBMS_OUTPUT.PUT_LINE(sqlerrm);
END PROC_USER_EXP;

ORACLE 11g output will be like this:

Connecting to the database HR. 
ORA-20001: Duplicate president customer excetpion 
Process exited. 
Disconnecting from the database HR

How to extract the decimal part from a floating point number in C?

 #include <stdio.h>
Int main ()
{
float f=56.75;
int a=(int)f;
int result=(f-a)*100;
printf ("integer = %d\n decimal part to integer 
 =%d\n",result);
}
Output:- 
integer =56
decimal part to integer = 75

Get driving directions using Google Maps API v2

I just release my latest library for Google Maps Direction API on Android https://github.com/akexorcist/Android-GoogleDirectionLibrary

Bootstrap - Removing padding or margin when screen size is smaller

Another css that can make the margin problem is that you have direction:someValue in your css, so just remove it by setting it to initial.

For example:

body {
     direction:rtl;
 }
@media (max-width: 480px) {
    body {
     direction:initial;
    }
}

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

What is private bytes, virtual bytes, working set?

The definition of the perfmon counters has been broken since the beginning and for some reason appears to be too hard to correct.

A good overview of Windows memory management is available in the video "Mysteries of Memory Management Revealed" on MSDN: It covers more topics than needed to track memory leaks (eg working set management) but gives enough detail in the relevant topics.


To give you a hint of the problem with the perfmon counter descriptions, here is the inside story about private bytes from "Private Bytes Performance Counter -- Beware!" on MSDN:

Q: When is a Private Byte not a Private Byte?

A: When it isn't resident.

The Private Bytes counter reports the commit charge of the process. That is to say, the amount of space that has been allocated in the swap file to hold the contents of the private memory in the event that it is swapped out. Note: I'm avoiding the word "reserved" because of possible confusion with virtual memory in the reserved state which is not committed.


From "Performance Planning" on MSDN:

3.3 Private Bytes

3.3.1 Description

Private memory, is defined as memory allocated for a process which cannot be shared by other processes. This memory is more expensive than shared memory when multiple such processes execute on a machine. Private memory in (traditional) unmanaged dlls usually constitutes of C++ statics and is of the order of 5% of the total working set of the dll.

Reading in double values with scanf in c

Format specifier in printf should be %f for doubl datatypes since float datatyles eventually convert to double datatypes inside printf.

There is no provision to print float data. Please find the discussion here : Correct format specifier for double in printf

get url content PHP

Use cURL,

Check if you have it via phpinfo();

And for the code:

function getHtml($url, $post = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    } 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

What is the best open XML parser for C++?

try this one: http://www.applied-mathematics.net/tools/xmlParser.html
it's easier and faster than RapidXML or PUGXML.
TinyXML is the worst of the "simple parser".

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

Automated testing for REST Api

I collaborated with one of my coworkers to start the PyRestTest framework for this reason: https://github.com/svanoort/pyresttest

Although you can work with the tests in Python, the normal test format is in YAML.

Sample test suite for a basic REST app -- verifies that APIs respond correctly, checking HTTP status codes, though you can make it examine response bodies as well:

---
- config:
    - testset: "Tests using test app"

- test: # create entity
    - name: "Basic get"
    - url: "/api/person/"
- test: # create entity
    - name: "Get single person"
    - url: "/api/person/1/"
- test: # create entity
    - name: "Get single person"
    - url: "/api/person/1/"
    - method: 'DELETE'
- test: # create entity by PUT
    - name: "Create/update person"
    - url: "/api/person/1/"
    - method: "PUT"
    - body: '{"first_name": "Gaius","id": 1,"last_name": "Baltar","login": "gbaltar"}'
    - headers: {'Content-Type': 'application/json'}
- test: # create entity by POST
    - name: "Create person"
    - url: "/api/person/"
    - method: "POST"
    - body: '{"first_name": "Willim","last_name": "Adama","login": "theadmiral"}'
    - headers: {Content-Type: application/json}

ScriptManager.RegisterStartupScript code not working - why?

Try this code...

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);

Where UpdatePanel1 is the id for Updatepanel on your page

What's the fastest way of checking if a point is inside a polygon in python

If speed is what you need and extra dependencies are not a problem, you maybe find numba quite useful (now it is pretty easy to install, on any platform). The classic ray_tracing approach you proposed can be easily ported to numba by using numba @jit decorator and casting the polygon to a numpy array. The code should look like:

@jit(nopython=True)
def ray_tracing(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside

The first execution will take a little longer than any subsequent call:

%%time
polygon=np.array(polygon)
inside1 = [numba_ray_tracing_method(point[0], point[1], polygon) for 
point in points]

CPU times: user 129 ms, sys: 4.08 ms, total: 133 ms
Wall time: 132 ms

Which, after compilation will decrease to:

CPU times: user 18.7 ms, sys: 320 µs, total: 19.1 ms
Wall time: 18.4 ms

If you need speed at the first call of the function you can then pre-compile the code in a module using pycc. Store the function in a src.py like:

from numba import jit
from numba.pycc import CC
cc = CC('nbspatial')


@cc.export('ray_tracing',  'b1(f8, f8, f8[:,:])')
@jit(nopython=True)
def ray_tracing(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


if __name__ == "__main__":
    cc.compile()

Build it with python src.py and run:

import nbspatial

import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in 
np.linspace(0,2*np.pi,lenpoly)[:-1]]

# random points set of points to test 
N = 10000
# making a list instead of a generator to help debug
points = zip(np.random.random(N),np.random.random(N))

polygon = np.array(polygon)

%%time
result = [nbspatial.ray_tracing(point[0], point[1], polygon) for point in points]

CPU times: user 20.7 ms, sys: 64 µs, total: 20.8 ms
Wall time: 19.9 ms

In the numba code I used: 'b1(f8, f8, f8[:,:])'

In order to compile with nopython=True, each var needs to be declared before the for loop.

In the prebuild src code the line:

@cc.export('ray_tracing' , 'b1(f8, f8, f8[:,:])')

Is used to declare the function name and its I/O var types, a boolean output b1 and two floats f8 and a two-dimensional array of floats f8[:,:] as input.

Edit Jan/4/2021

For my use case, I need to check if multiple points are inside a single polygon - In such a context, it is useful to take advantage of numba parallel capabilities to loop over a series of points. The example above can be changed to:

from numba import jit, njit
import numba
import numpy as np 

@jit(nopython=True)
def pointinpolygon(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in numba.prange(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
    D = np.empty(len(points), dtype=numba.boolean) 
    for i in numba.prange(0, len(D)):
        D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
    return D    

Note: pre-compiling the above code will not enable the parallel capabilities of numba (parallel CPU target is not supported by pycc/AOT compilation) see: https://github.com/numba/numba/issues/3336

Test:


import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
polygon = np.array(polygon)
N = 10000
points = np.random.uniform(-1.5, 1.5, size=(N, 2))

For N=10000 on a 72 core machine, returns:

%%timeit
parallelpointinpolygon(points, polygon)
# 480 µs ± 8.19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Edit 17 Feb '21:

  • fixing loop to start from 0 instead of 1 (thanks @mehdi):

for i in numba.prange(0, len(D))

Edit 20 Feb '21:

Follow-up on the comparison made by @mehdi, I am adding a GPU-based method below. It uses the point_in_polygon method, from the cuspatial library:

    import numpy as np
    import cudf
    import cuspatial

    N = 100000002
    lenpoly = 1000
    polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in 
    np.linspace(0,2*np.pi,lenpoly)]
    polygon = np.array(polygon)
    points = np.random.uniform(-1.5, 1.5, size=(N, 2))


    x_pnt = points[:,0]
    y_pnt = points[:,1]
    x_poly =polygon[:,0]
    y_poly = polygon[:,1]
    result = cuspatial.point_in_polygon(
        x_pnt,
        y_pnt,
        cudf.Series([0], index=['geom']),
        cudf.Series([0], name='r_pos', dtype='int32'), 
        x_poly, 
        y_poly,
    )

Following @Mehdi comparison. For N=100000002 and lenpoly=1000 - I got the following results:

 time_parallelpointinpolygon:         161.54760098457336 
 time_mpltPath:                       307.1664695739746 
 time_ray_tracing_numpy_numba:        353.07356882095337 
 time_is_inside_sm_parallel:          37.45389246940613 
 time_is_inside_postgis_parallel:     127.13793849945068 
 time_is_inside_rapids:               4.246025562286377

point in poligon methods comparison, #poins: 10e07

hardware specs:

  • CPU Intel xeon E1240
  • GPU Nvidia GTX 1070

Notes:

  • The cuspatial.point_in_poligon method, is quite robust and powerful, it offers the ability to work with multiple and complex polygons (I guess at the expense of performance)

  • The numba methods can also be 'ported' on the GPU - it will be interesting to see a comparison which includes a porting to cuda of fastest method mentioned by @Mehdi (is_inside_sm).

How to: Install Plugin in Android Studio

2019: With Android Studio 3.4.2 started:

  1. Click on File -> Settings
  2. Find "Plugins" in the left pane of the popup window and click on it
  3. Click on the Gear in the upper right
  4. Click on "Install Plugin from Disk"
  5. Find your plugin from the file browser or drag and drop it from another window to go to it in the browse window, then click on it then click "OK"
  6. The browse window will close
  7. Click "OK" on the setting window
  8. Click "Restart" on the popup

Choosing the default value of an Enum type without having to change values

You can't, but if you want, you can do some trick. :)

    public struct Orientation
    {
        ...
        public static Orientation None = -1;
        public static Orientation North = 0;
        public static Orientation East = 1;
        public static Orientation South = 2;
        public static Orientation West = 3;
    }

usage of this struct as simple enum.
where you can create p.a == Orientation.East (or any value that you want) by default
to use the trick itself, you need to convert from int by code.
there the implementation:

        #region ConvertingToEnum
        private int val;
        static Dictionary<int, string> dict = null;

        public Orientation(int val)
        {
            this.val = val;
        }

        public static implicit operator Orientation(int value)
        {
            return new Orientation(value - 1);
        }

        public static bool operator ==(Orientation a, Orientation b)
        {
            return a.val == b.val;
        }

        public static bool operator !=(Orientation a, Orientation b)
        {
            return a.val != b.val;
        }

        public override string ToString()
        {
            if (dict == null)
                InitializeDict();
            if (dict.ContainsKey(val))
                return dict[val];
            return val.ToString();
        }

        private void InitializeDict()
        {
            dict = new Dictionary<int, string>();
            foreach (var fields in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                dict.Add(((Orientation)fields.GetValue(null)).val, fields.Name);
            }
        } 
        #endregion

T-SQL How to select only Second row from a table?

with T1 as
(
  select row_number() over(order by ID) rownum, T2.ID
  from Table2 T2
)
select ID
from T1
where rownum=2

how to sync windows time from a ntp time server in command

While the w32tm /resync in theory does the job, it only does so under certain conditions. When "down to the millisecond" matters, however, I found that Windows wouldn't actually make the adjustment; as if "oh, I'm off by 2.5 seconds, close enough bro, nothing to see or do here".

In order to truly force the resync (Windows 7):

  1. Control Panel -> Date and Time
  2. "Change date and time..." (requires Admin privileges)
  3. Add or Subtract a few minutes (I used -5 minutes)
  4. Run "cmd.exe" as administrator
  5. w32tm /resync
  6. Visually check that the seconds in the "Date and Time" control panel are ticking at the same time as your authoritative clock(s). (I used watch -n 0.1 date on a Linux machine on the network that I had SSH'd over into)

--- Rapid Method ---

  1. Run "cmd.exe" as administrator
  2. net start w32time (Time Service must be running)
  3. time 8 (where 8 may be replaced by any 'hour' value, presumably 0-23)
  4. w32tm /resync
  5. Jump to 3, as needed.

Postgresql - unable to drop database because of some auto connections to DB

Simply check what is the connection, where it's coming from. You can see all this in:

SELECT * FROM pg_stat_activity WHERE datname = 'TARGET_DB';

Perhaps it is your connection?

Invoke(Delegate)

A control or window object in Windows Forms is just a wrapper around a Win32 window identified by a handle (sometimes called HWND). Most things you do with the control will eventually result in a Win32 API call that uses this handle. The handle is owned by the thread that created it (typically the main thread), and shouldn't be manipulated by another thread. If for some reason you need to do something with the control from another thread, you can use Invoke to ask the main thread to do it on your behalf.

For instance, if you want to change the text of a label from a worker thread, you can do something like this:

theLabel.Invoke(new Action(() => theLabel.Text = "hello world from worker thread!"));

INSERT INTO @TABLE EXEC @query with SQL Server 2000

N.B. - this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ... were lifted and so it doesn't apply for those later versions.


You'll have to switch to a temp table:

CREATE TABLE #tmp (code varchar(50), mount money)
DECLARE @q nvarchar(4000)
SET @q = 'SELECT coa_code, amount FROM T_Ledger_detail'

INSERT INTO  #tmp (code, mount)
EXEC sp_executesql (@q)

SELECT * from #tmp

From the documentation:

A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.

Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:

INSERT INTO table_variable EXEC stored_procedure

SELECT select_list INTO table_variable statements.

How to find all links / pages on a website

Check out linkchecker—it will crawl the site (while obeying robots.txt) and generate a report. From there, you can script up a solution for creating the directory tree.

using scp in terminal

I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.

scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop

The username@remotecomputer is the same string you used with ssh initially.

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

I think the answers are below

List<string> aa = (from char c in source
                    select c.ToString() ).ToList();

List<string> aa2 = (from char c1 in source
                    from char c2 in source
                    select string.Concat(c1, ".", c2)).ToList();

jQuery checkbox check/uncheck

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.

printf() formatting for hex

The # part gives you a 0x in the output string. The 0 and the x count against your "8" characters listed in the 08 part. You need to ask for 10 characters if you want it to be the same.

int i = 7;

printf("%#010x\n", i);  // gives 0x00000007
printf("0x%08x\n", i);  // gives 0x00000007
printf("%#08x\n", i);   // gives 0x000007

Also changing the case of x, affects the casing of the outputted characters.

printf("%04x", 4779); // gives 12ab
printf("%04X", 4779); // gives 12AB

For a boolean field, what is the naming convention for its getter/setter?

I believe it would be:

void setCurrent(boolean current)
boolean isCurrent()

How to see tomcat is running or not

for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running

Laravel - Pass more than one variable to view

This Answer seems to be

bit helpful while declaring the large numbe of variable in the function

Laravel 5.7.*

For Example

public function index()
{
    $activePost = Post::where('status','=','active')->get()->count();

    $inActivePost = Post::where('status','=','inactive')->get()->count();

    $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

    $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

    return view('dashboard.index')->with('activePost',$activePost)->with('inActivePost',$inActivePost )->with('yesterdayPostActive',$yesterdayPostActive )->with('todayPostActive',$todayPostActive );
}

When you see the last line of the returns it not looking good

When You Project is Getting Larger its not good

So

public function index()
    {
        $activePost = Post::where('status','=','active')->get()->count();

        $inActivePost = Post::where('status','=','inactive')->get()->count();

        $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

        $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

        $viewShareVars = ['activePost','inActivePost','yesterdayPostActive','todayPostActive'];

        return view('dashboard.index',compact($viewShareVars));
    }

As You see all the variables as declared as array of $viewShareVars and Accessed in View

But My Function Becomes very Larger so i have decided to make the line as very simple

public function index()
    {
        $activePost = Post::where('status','=','active')->get()->count();

        $inActivePost = Post::where('status','=','inactive')->get()->count();

        $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

        $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

        $viewShareVars = array_keys(get_defined_vars());

        return view('dashboard.index',compact($viewShareVars));
    }

the native php function get_defined_vars() get all the defined variables from the function

and array_keys will grab the variable names

so in your view you can access all the declared variable inside the function

as {{$todayPostActive}}

Difference between Static methods and Instance methods

In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.

This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.

class A {
    int a;
    int b;

    public void setParameters(int a, int b){
        this.a = a;
        this.b = b;
    }
    public int add(){
        return this.a + this.b;
   }

    public static returnSum(int s1, int s2){
        return (s1 + s2);
    }
}

In the above example, when you call add() as:

A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3 

B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5

//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10

class B{
    int s=8;
    int t = 8;
    public addition(int s,int t){
       A.returnSum(s,t);//returns 16
    }
}

In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.

Adb over wireless without usb cable at all for not rooted phones

The question is about a non rooted device but if it is rooted the simplest way would be to:

From the terminal on your phone, do this:

su
setprop service.adb.tcp.port 5555
stop adbd
start adbd

See this answer for full details.

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

What is the difference between %g and %f in C?

E = exponent expression, simply means power(10, n) or 10 ^ n

F = fraction expression, default 6 digits precision

G = gerneral expression, somehow smart to show the number in a concise way (but really?)

See the below example,

The code

void main(int argc, char* argv[])  
{  
        double a = 4.5;
        printf("=>>>> below is the example for printf 4.5\n");
        printf("%%e %e\n",a);
        printf("%%f %f\n",a);
        printf("%%g %g\n",a);
        printf("%%E %E\n",a);
        printf("%%F %F\n",a);
        printf("%%G %G\n",a);
          
        double b = 1.79e308;
        printf("=>>>> below is the exbmple for printf 1.79*10^308\n");
        printf("%%e %e\n",b);
        printf("%%f %f\n",b);
        printf("%%g %g\n",b);
        printf("%%E %E\n",b);
        printf("%%F %F\n",b);
        printf("%%G %G\n",b);

        double d = 2.25074e-308;
        printf("=>>>> below is the example for printf 2.25074*10^-308\n");
        printf("%%e %e\n",d);
        printf("%%f %f\n",d);
        printf("%%g %g\n",d);
        printf("%%E %E\n",d);
        printf("%%F %F\n",d);
        printf("%%G %G\n",d);
}  

The output

=>>>> below is the example for printf 4.5
%e 4.500000e+00
%f 4.500000
%g 4.5
%E 4.500000E+00
%F 4.500000
%G 4.5
=>>>> below is the exbmple for printf 1.79*10^308
%e 1.790000e+308
%f 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%g 1.79e+308
%E 1.790000E+308
%F 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%G 1.79E+308
=>>>> below is the example for printf 2.25074*10^-308
%e 2.250740e-308
%f 0.000000
%g 2.25074e-308
%E 2.250740E-308
%F 0.000000
%G 2.25074E-308

Merge some list items in a Python List

On what basis should the merging take place? Your question is rather vague. Also, I assume a, b, ..., f are supposed to be strings, that is, 'a', 'b', ..., 'f'.

>>> x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> x[3:6] = [''.join(x[3:6])]
>>> x
['a', 'b', 'c', 'def', 'g']

Check out the documentation on sequence types, specifically on mutable sequence types. And perhaps also on string methods.

Windows command prompt log to a file

First method

For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.

Steps:

  1. type PowerShell in search area and click on "Windows PowerShell"

  2. If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)

  3. run the .bat file with following command

    PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt

This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.

Second method

You can use file redirection (>, >>) as suggest by Bali C above.

I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.

Clearing all cookies with JavaScript

After a bit of frustration with this myself I knocked together this function which will attempt to delete a named cookie from all paths. Just call this for each of your cookies and you should be closer to deleting every cookie then you were before.

function eraseCookieFromAllPaths(name) {
    // This function will attempt to remove a cookie from all paths.
    var pathBits = location.pathname.split('/');
    var pathCurrent = ' path=';

    // do a simple pathless delete first.
    document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;';

    for (var i = 0; i < pathBits.length; i++) {
        pathCurrent += ((pathCurrent.substr(-1) != '/') ? '/' : '') + pathBits[i];
        document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;' + pathCurrent + ';';
    }
}

As always different browsers have different behaviour but this worked for me. Enjoy.

Check if Cell value exists in Column, and then get the value of the NEXT Cell

After t.thielemans' answer, I worked that just

=VLOOKUP(A1, B:C, 2, FALSE) 

works fine and does what I wanted, except that it returns #N/A for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.

Edit (based on t.thielemans' comment):

To avoid #N/A for non-matches, do:

=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")

How to List All Redis Databases?

you can use redis-cli INFO keyspace

localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0

Take a char input from the Scanner

There is no API method to get a character from the Scanner. You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.

Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);

Just to be safe with whitespaces you could also first call trim() on the string to remove any whitespaces.

Scanner reader = new Scanner(System.in);
char c = reader.next().trim().charAt(0);

File URL "Not allowed to load local resource" in the Internet Browser

I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.

Based on your screenshot, try formatting your link like so:

<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>

(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)

What causes javac to issue the "uses unchecked or unsafe operations" warning

This comes up in Java 5 and later if you're using collections without type specifiers (e.g., Arraylist() instead of ArrayList<String>()). It means that the compiler can't check that you're using the collection in a type-safe way, using generics.

To get rid of the warning, just be specific about what type of objects you're storing in the collection. So, instead of

List myList = new ArrayList();

use

List<String> myList = new ArrayList<String>();

In Java 7 you can shorten generic instantiation by using Type Inference.

List<String> myList = new ArrayList<>();

How I can check if an object is null in ruby on rails 2?

In your example, you can simply replace null with `nil and it will work fine.

require 'erb'

template = <<EOS
<% if (@objectname != nil) then %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

Contrary to what the other poster said, you can see above that then works fine in Ruby. It's not common, but it is fine.

#blank? and #present? have other implications. Specifically, if the object responds to #empty?, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.

Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be

require 'erb'

template = <<EOS
<% if @objectname %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

If you explicitly need to check nil and not false, you can use the #nil? method, for which nil is the only object that will cause this to return true.

nil.nil?          # => true
false.nil?        # => false
Object.new.nil?   # => false

How to make a 3D scatter plot in Python?

You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.

from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random


fig = pyplot.figure()
ax = Axes3D(fig)

sequence_containing_x_vals = list(range(0, 100))
sequence_containing_y_vals = list(range(0, 100))
sequence_containing_z_vals = list(range(0, 100))

random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)

ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
pyplot.show()

The code above generates a figure like:

matplotlib 3D image