Programs & Examples On #Prng

PRNG - Pseudorandom number generator, A pseudorandom number generator (PRNG), also known as a deterministic random bit generator (DRBG),[1] is an algorithm for generating a sequence of numbers that approximates the properties of random numbers.

The APR based Apache Tomcat Native library was not found on the java.library.path

not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib

The native lib is expected in one of the following locations

/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib

and not in

tomcat/lib

The files in tomcat/lib are all jar file and are added by tomcat to the classpath so that they are available to your application.

The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar, for linux it could be a .so file, for windows it could be a .dll file.

Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.

Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.

org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms

EDIT

The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.

If you are troubling with running your servlet then after the run on sever command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.

It should be something like that

http://localhost:8080/<your-context-name>/<your-servlet-name>

EDIT 2

Try to call your servlet using the following url

http://localhost:8080/com.filecounter/FileCounter

Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF.

It is better to configure your servlets there using servlet-name servlet-class and url-mapping. It could look like that:

  <servlet>
    <description></description>
    <display-name>File counter - My first servlet</display-name>
    <servlet-name>file_counter</servlet-name>
    <servlet-class>com.filecounter.FileCounter</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>file_counter</servlet-name>
    <url-pattern>/FileFounter</url-pattern>
  </servlet-mapping>

In eclipse dynamic web project the default context name is the same as your project name.

http://localhost:8080/<your-context-name>/FileCounter

will work too.

How do I generate a SALT in Java for Salted-Hash?

Inspired from this post and that post, I use this code to generate and verify hashed salted passwords. It only uses JDK provided classes, no external dependency.

The process is:

  • you create a salt with getNextSalt
  • you ask the user his password and use the hash method to generate a salted and hashed password. The method returns a byte[] which you can save as is in a database with the salt
  • to authenticate a user, you ask his password, retrieve the salt and hashed password from the database and use the isExpectedPassword method to check that the details match
/**
 * A utility class to hash passwords and check passwords vs hashed values. It uses a combination of hashing and unique
 * salt. The algorithm used is PBKDF2WithHmacSHA1 which, although not the best for hashing password (vs. bcrypt) is
 * still considered robust and <a href="https://security.stackexchange.com/a/6415/12614"> recommended by NIST </a>.
 * The hashed value has 256 bits.
 */
public class Passwords {

  private static final Random RANDOM = new SecureRandom();
  private static final int ITERATIONS = 10000;
  private static final int KEY_LENGTH = 256;

  /**
   * static utility class
   */
  private Passwords() { }

  /**
   * Returns a random salt to be used to hash a password.
   *
   * @return a 16 bytes random salt
   */
  public static byte[] getNextSalt() {
    byte[] salt = new byte[16];
    RANDOM.nextBytes(salt);
    return salt;
  }

  /**
   * Returns a salted and hashed password using the provided hash.<br>
   * Note - side effect: the password is destroyed (the char[] is filled with zeros)
   *
   * @param password the password to be hashed
   * @param salt     a 16 bytes salt, ideally obtained with the getNextSalt method
   *
   * @return the hashed password with a pinch of salt
   */
  public static byte[] hash(char[] password, byte[] salt) {
    PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
    Arrays.fill(password, Character.MIN_VALUE);
    try {
      SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
      return skf.generateSecret(spec).getEncoded();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
      throw new AssertionError("Error while hashing a password: " + e.getMessage(), e);
    } finally {
      spec.clearPassword();
    }
  }

  /**
   * Returns true if the given password and salt match the hashed value, false otherwise.<br>
   * Note - side effect: the password is destroyed (the char[] is filled with zeros)
   *
   * @param password     the password to check
   * @param salt         the salt used to hash the password
   * @param expectedHash the expected hashed value of the password
   *
   * @return true if the given password and salt match the hashed value, false otherwise
   */
  public static boolean isExpectedPassword(char[] password, byte[] salt, byte[] expectedHash) {
    byte[] pwdHash = hash(password, salt);
    Arrays.fill(password, Character.MIN_VALUE);
    if (pwdHash.length != expectedHash.length) return false;
    for (int i = 0; i < pwdHash.length; i++) {
      if (pwdHash[i] != expectedHash[i]) return false;
    }
    return true;
  }

  /**
   * Generates a random password of a given length, using letters and digits.
   *
   * @param length the length of the password
   *
   * @return a random password
   */
  public static String generateRandomPassword(int length) {
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      int c = RANDOM.nextInt(62);
      if (c <= 9) {
        sb.append(String.valueOf(c));
      } else if (c < 36) {
        sb.append((char) ('a' + c - 10));
      } else {
        sb.append((char) ('A' + c - 36));
      }
    }
    return sb.toString();
  }
}

How do I create directory if it doesn't exist to create a file?

You can use following code

  DirectoryInfo di = Directory.CreateDirectory(path);

Importing CSV File to Google Maps

We have now (jan2017) a csv layer import inside Google Maps itself.enter image description here

Google Maps > "Your Places" > "Open in My Maps"

Notepad++ cached files location

I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.

Query comparing dates in SQL

please try with below query

select id,numbers_from,created_date,amount_numbers,SMS_text 
from Test_Table
where 
convert(datetime, convert(varchar(10), created_date, 102))  <= convert(datetime,'2013-04-12')

UIButton Image + Text IOS

I encountered the same problem, and I fix it by creating a new subclass of UIButton and overriding the layoutSubviews: method as below :

-(void)layoutSubviews {
    [super layoutSubviews];

    // Center image
    CGPoint center = self.imageView.center;
    center.x = self.frame.size.width/2;
    center.y = self.imageView.frame.size.height/2;
    self.imageView.center = center;

    //Center text
    CGRect newFrame = [self titleLabel].frame;
    newFrame.origin.x = 0;
    newFrame.origin.y = self.imageView.frame.size.height + 5;
    newFrame.size.width = self.frame.size.width;

    self.titleLabel.frame = newFrame;
    self.titleLabel.textAlignment = UITextAlignmentCenter;

}

I think that the Angel García Olloqui's answer is another good solution, if you place all of them manually with interface builder but I'll keep my solution since I don't have to modify the content insets for each of my button.

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

Model Binding to a List MVC 4

~Controller

namespace ListBindingTest.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<String> tmp = new List<String>();
            tmp.Add("one");
            tmp.Add("two");
            tmp.Add("Three");
            return View(tmp);
        }

        [HttpPost]
        public ActionResult Send(IList<String> input)
        {
            return View(input);
        }    
    }
}

~ Strongly Typed Index View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
    <div>
    @using(Html.BeginForm("Send", "Home", "POST"))
    {
        @Html.EditorFor(x => x)
        <br />
        <input type="submit" value="Send" />
    }
    </div>
</body>
</html>

~ Strongly Typed Send View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
    <div>
    @foreach(var element in @Model)
    {
        @element
        <br />
    }
    </div>
</body>
</html>

This is all that you had to do man, change his MyViewModel model to IList.

How to get first and last day of week in Oracle?

SQL> var P_YEARWEEK varchar2(6)
SQL> exec :P_YEARWEEK := '201118'

PL/SQL procedure successfully completed.

SQL> with t as
  2  ( select substr(:P_YEARWEEK,1,4) year
  3         , substr(:P_YEARWEEK,5,2) week
  4      from dual
  5  )
  6  select year
  7       , week
  8       , trunc(to_date(year,'yyyy'),'yyyy')                              january_1
  9       , trunc(trunc(to_date(year,'yyyy'),'yyyy'),'iw')                  monday_week_1
 10       , trunc(trunc(to_date(year,'yyyy'),'yyyy'),'iw') + (week - 1) * 7 start_of_the_week
 11       , trunc(trunc(to_date(year,'yyyy'),'yyyy'),'iw') + week  * 7 - 1  end_of_the_week
 12    from t
 13  /

YEAR WE JANUARY_1           MONDAY_WEEK_1       START_OF_THE_WEEK   END_OF_THE_WEEK
---- -- ------------------- ------------------- ------------------- -------------------
2011 18 01-01-2011 00:00:00 27-12-2010 00:00:00 25-04-2011 00:00:00 01-05-2011 00:00:00

1 row selected.

Regards,
Rob.

How do I abort/cancel TPL Tasks?

Like this post suggests, this can be done in the following way:

int Foo(CancellationToken token)
{
    Thread t = Thread.CurrentThread;
    using (token.Register(t.Abort))
    {
        // compute-bound work here
    }
}

Although it works, it's not recommended to use such approach. If you can control the code that executes in task, you'd better go with proper handling of cancellation.

How do I make a relative reference to another workbook in Excel?

Using =worksheetname() and =Indirect() function, and naming the worksheets in the parent Excel file with the name of the externally referenced Excel file. Each externally referenced excel file were in their own folders with same name. These sub-folders were only to create more clarity.


What I did was as follows:-

|----Column B---------------|----Column C------------|

R2) Parent folder --------> "C:\TEMP\Excel\"

R3) Sub folder name ---> =worksheetname()

R5) Full path --------------> ="'"&C2&C3&"["&C3&".xlsx]Sheet1'!$A$1"

R7) Indirect function-----> =INDIRECT(C5,TRUE)

In the main file, I had say, 5 worksheets labeled as Ext-1, Ext-2, Ext-3, Ext-4, Ext-5. Copy pasted the above formulas into all the five worksheets. Opened all the respectively named Excel files in the background. For some reason the results were not automatically computing, hence had to force a change by editing any cell. Volla, the value in cell A1 of each externally referenced Excel file were in the Main file.

Java: int[] array vs int array[]

No, there is no difference. But I prefer using int[] array as it is more readable.

How to use Checkbox inside Select Option

I started from @vitfo answer but I want to have <option> inside <select> instead of checkbox inputs so i put together all the answers to make this, there is my code, I hope it will help someone.

_x000D_
_x000D_
$(".multiple_select").mousedown(function(e) {_x000D_
    if (e.target.tagName == "OPTION") _x000D_
    {_x000D_
      return; //don't close dropdown if i select option_x000D_
    }_x000D_
    $(this).toggleClass('multiple_select_active'); //close dropdown if click inside <select> box_x000D_
});_x000D_
$(".multiple_select").on('blur', function(e) {_x000D_
    $(this).removeClass('multiple_select_active'); //close dropdown if click outside <select>_x000D_
});_x000D_
 _x000D_
$('.multiple_select option').mousedown(function(e) { //no ctrl to select multiple_x000D_
    e.preventDefault(); _x000D_
    $(this).prop('selected', $(this).prop('selected') ? false : true); //set selected options on click_x000D_
    $(this).parent().change(); //trigger change event_x000D_
});_x000D_
_x000D_
 _x000D_
 $("#myFilter").on('change', function() {_x000D_
      var selected = $("#myFilter").val().toString(); //here I get all options and convert to string_x000D_
      var document_style = document.documentElement.style;_x000D_
      if(selected !== "")_x000D_
        document_style.setProperty('--text', "'Selected: "+selected+"'");_x000D_
      else_x000D_
        document_style.setProperty('--text', "'Select values'");_x000D_
 });
_x000D_
:root_x000D_
{_x000D_
 --text: "Select values";_x000D_
}_x000D_
.multiple_select_x000D_
{_x000D_
 height: 18px;_x000D_
 width: 90%;_x000D_
 overflow: hidden;_x000D_
 -webkit-appearance: menulist;_x000D_
 position: relative;_x000D_
}_x000D_
.multiple_select::before_x000D_
{_x000D_
 content: var(--text);_x000D_
 display: block;_x000D_
  margin-left: 5px;_x000D_
  margin-bottom: 2px;_x000D_
}_x000D_
.multiple_select_active_x000D_
{_x000D_
 overflow: visible !important;_x000D_
}_x000D_
.multiple_select option_x000D_
{_x000D_
 display: none;_x000D_
    height: 18px;_x000D_
 background-color: white;_x000D_
}_x000D_
.multiple_select_active option_x000D_
{_x000D_
 display: block;_x000D_
}_x000D_
_x000D_
.multiple_select option::before {_x000D_
  content: "\2610";_x000D_
}_x000D_
.multiple_select option:checked::before {_x000D_
  content: "\2611";_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select id="myFilter" class="multiple_select" multiple>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
  <option>D</option>_x000D_
  <option>E</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

FileSystemWatcher Changed event is raised twice

I know this is an old issue, but had the same problem and none of the above solution really did the trick for the problem I was facing. I have created a dictionary which maps the file name with the LastWriteTime. So if the file is not in the dictionary will go ahead with the process other wise check to see when was the last modified time and if is different from what it is in the dictionary run the code.

    Dictionary<string, DateTime> dateTimeDictionary = new Dictionary<string, DateTime>(); 

        private void OnChanged(object source, FileSystemEventArgs e)
            {
                if (!dateTimeDictionary.ContainsKey(e.FullPath) || (dateTimeDictionary.ContainsKey(e.FullPath) && System.IO.File.GetLastWriteTime(e.FullPath) != dateTimeDictionary[e.FullPath]))
                {
                    dateTimeDictionary[e.FullPath] = System.IO.File.GetLastWriteTime(e.FullPath);

                    //your code here
                }
            }

Is there a "null coalescing" operator in JavaScript?

Too much talk, there are two items here:

  1. Logical OR

const foo = '' || 'default string';

console.log(foo); // output is 'default string'

  1. Nullish coalescing operator

const foo = '' ?? 'default string';

console.log(foo); // output is empty string i.e. ''

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

In my case, this problem was caused by broken IIS bindings. Specifically, my 'http' binding had been deleted. Recreating it fixed the problem.

How to manage local vs production settings in Django?

The problem with most of these solutions is that you either have your local settings applied before the common ones, or after them.

So it's impossible to override things like

  • the env-specific settings define the addresses for the memcached pool, and in the main settings file this value is used to configure the cache backend
  • the env-specific settings add or remove apps/middleware to the default one

at the same time.

One solution can be implemented using "ini"-style config files with the ConfigParser class. It supports multiple files, lazy string interpolation, default values and a lot of other goodies. Once a number of files have been loaded, more files can be loaded and their values will override the previous ones, if any.

You load one or more config files, depending on the machine address, environment variables and even values in previously loaded config files. Then you just use the parsed values to populate the settings.

One strategy I have successfully used has been:

  • Load a default defaults.ini file
  • Check the machine name, and load all files which matched the reversed FQDN, from the shortest match to the longest match (so, I loaded net.ini, then net.domain.ini, then net.domain.webserver01.ini, each one possibly overriding values of the previous). This account also for developers' machines, so each one could set up its preferred database driver, etc. for local development
  • Check if there is a "cluster name" declared, and in that case load cluster.cluster_name.ini, which can define things like database and cache IPs

As an example of something you can achieve with this, you can define a "subdomain" value per-env, which is then used in the default settings (as hostname: %(subdomain).whatever.net) to define all the necessary hostnames and cookie things django needs to work.

This is as DRY I could get, most (existing) files had just 3 or 4 settings. On top of this I had to manage customer configuration, so an additional set of configuration files (with things like database names, users and passwords, assigned subdomain etc) existed, one or more per customer.

One can scale this as low or as high as necessary, you just put in the config file the keys you want to configure per-environment, and once there's need for a new config, put the previous value in the default config, and override it where necessary.

This system has proven reliable and works well with version control. It has been used for long time managing two separate clusters of applications (15 or more separate instances of the django site per machine), with more than 50 customers, where the clusters were changing size and members depending on the mood of the sysadmin...

Disable scrolling on `<input type=number>`

While trying to solve this for myself, I noticed that it's actually possible to retain the scrolling of the page and focus of the input while disabling number changes by attempting to re-fire the caught event on the parent element of the <input type="number"/> on which it was caught, simply like this:

e.target.parentElement.dispatchEvent(e);

However, this causes an error in browser console, and is probably not guaranteed to work everywhere (I only tested on Firefox), since it is intentionally invalid code.

Another solution which works nicely at least on Firefox and Chromium is to temporarily make the <input> element readOnly, like this:

function handleScroll(e) {
  if (e.target.tagName.toLowerCase() === 'input'
    && (e.target.type === 'number')
    && (e.target === document.activeElement)
    && !e.target.readOnly
  ) {
      e.target.readOnly = true;
      setTimeout(function(el){ el.readOnly = false; }, 0, e.target);
  }
}
document.addEventListener('wheel', function(e){ handleScroll(e); });

One side effect that I've noticed is that it may cause the field to flicker for a split-second if you have different styling for readOnly fields, but for my case at least, this doesn't seem to be an issue.

Similarly, (as explained in James' answer) instead of modifying the readOnly property, you can blur() the field and then focus() it back, but again, depending on styles in use, some flickering might occur.

Alternatively, as mentioned in other comments here, you can just call preventDefault() on the event instead. Assuming that you only handle wheel events on number inputs which are in focus and under the mouse cursor (that's what the three conditions above signify), negative impact on user experience would be close to none.

What is declarative programming?

It depends on how you submit the answer to the text. Overall you can look at the programme at a certain view but it depends what angle you look at the problem. I will get you started with the programme: Dim Bus, Car, Time, Height As Integr

Again it depends on what the problem is an overall. You might have to shorten it due to the programme. Hope this helps and need the feedback if it does not. Thank You.

Why are static variables considered evil?

I find static variables more convenient to use. And I presume that they are efficient too (Please correct me if I am wrong) because if I had to make 10,000 calls to a function within a class, I would be glad to make the method static and use a straightforward class.methodCall() on it instead of cluttering the memory with 10,000 instances of the class, Right?

I see what you think, but a simple Singleton pattern will do the same without having to instantiate 10 000 objects.

static methods can be used, but only for functions that are related to the object domain and do not need or use internal properties of the object.

ex:

public class WaterContainer {
    private int size;
    private int brand;
    ...etc

    public static int convertToGallon(int liters)...

    public static int convertToLiters(int gallon)...

}

Defining lists as global variables in Python

Yes, you need to use global foo if you are going to write to it.

foo = []

def bar():
    global foo
    ...
    foo = [1]

How do you make sure email you send programmatically is not automatically marked as spam?

I hate to tell you, but I and others may be using white-list defaults to control our filtering of spam.

This means that all e-mail from an unknown source is automatically spam and diverted into a spam folder. (I don't let my e-mail service delete spam, because I want to always review the arrivals for false positives, something that is pretty easy to do by a quick scan of the folder.)

I even have e-mail from myself go to the spam bucket because (1) I usually don't send e-mail to myself and (2) there are spammers that fake my return address in spam sent to me.

So to get out of the spam designation, I have to consider that your mail might be legitimate (from sender and subject information) and open it first in plaintext (my default for all incoming mail, spam or not) to see if it is legitimate. My spam folder will not use any links in e-mails so I am protected against tricky image links and other misbehavior.

If I want future arrivals from the same source to go to my in box and not be diverted for spam review, I will specify that to my e-mail client. For those organizations that use bulk-mail forwarders and unique sender addresses per mail piece, that's too bad. They never get my approval and always show up in my spam folder, and if I'm busy I will never look at them.

Finally, if an e-mail is not legible in plaintext, even when sent as HTML, I am likely to just delete it unless it is something that I know is of interest to me by virtue of the source and previous valuable experiences.

As you can see, it is ultimately under an users control and there is no automated act that will convince such a system that your mail is legitimate from its structure alone. In this case, you need to play nice, don't do anything that is similar to phishing, and make it easy for users willing to trust your mail to add you to their white list.

How can I protect my .NET assemblies from decompilation?

We use {SmartAssembly} for .NET protection of an enterprise level distributed application, and it has worked great for us.

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

in my case i did following

$mail = new PHPMailer;
$mail->isSMTP();            
$mail->Host = '<YOUR HOST>';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '<USERNAME>';
$mail->Password = '<PASSWORD>';
$mail->SMTPSecure = '';
$mail->smtpConnect([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    ]
]);
$mail->smtpClose();

$mail->From = '<[email protected]>';
$mail->FromName = '<MAIL FROM NAME>';

$mail->addAddress("<[email protected]>", '<SEND TO>');

$mail->isHTML(true);
$mail->Subject= '<SUBJECTHERE>';
$mail->Body =  '<h2>Test Mail</h2>';
$isSend = $mail->send();

Can not connect to local PostgreSQL

This really looks like a file permissions error. Unix domain sockets are files and have user permissions just like any other. It looks as though the OSX user attempting to access the database does not have file permissions to access the socket file. To confirm this I've done some tests on Ubuntu and psql to try to generate the same error (included below).

You need to check the permissions on the socket file and its directories /var and /var/pgsql_socket. Your Rails app (OSX user) must have execute (x) permissions on these directories (preferably grant everyone permissions) and the socket should have full permissions (wrx). You can use ls -lAd <file> to check these, and if any of them are a symlink you need to check the file or dir the link points to.

You can change the permissions on the dir for youself, but the socket is configured by postgres in postgresql.conf. This can be found in the same directory as pg_hba.conf (You'll have to figure out which one). Once you've set the permissions you will need to restart postgresql.

# postgresql.conf should contain...
unix_socket_directory = '/var/run/postgresql'       # dont worry if yours is different
#unix_socket_group = ''                             # default is fine here
#unix_socket_permissions = 0777                     # check this one and uncomment if necessary.

EDIT:

I've done a quick search on google which you may wish to look into to see if it is relavent. This might well result in any attempt to find your config file failing.

http://www.postgresqlformac.com/server/howto_edit_postgresql_confi.html


Error messages:

User not found in pg_hba.conf

psql: FATAL:  no pg_hba.conf entry for host "[local]", user "couling", database "main", SSL off

User failed password auth:

psql: FATAL:  password authentication failed for user "couling"

Missing unix socket file:

psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Unix socket exists, but server not listening to it.

psql: could not connect to server: Connection refused
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Bad file permissions on unix socket file:

psql: could not connect to server: Permission denied
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

How do I get the difference between two Dates in JavaScript?

Thanks @Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin. Here's the simplified end solution:

    // don't update end date if there's already an end date but not an old start date
    if (!oldEnd || oldBegin) {
        var selectedDateSpan = 1800000; // 30 minutes
        if (oldEnd) {
            selectedDateSpan = oldEnd - oldBegin;
        }

       newEnd = new Date(newBegin.getTime() + selectedDateSpan));
    }

Remove ':hover' CSS behavior from element

I also had this problem, my solution was to have an element above the element i dont want a hover effect on:

_x000D_
_x000D_
.no-hover {_x000D_
  position: relative;_x000D_
  opacity: 0.65 !important;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.no-hover::before {_x000D_
  content: '';_x000D_
  background-color: transparent;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  z-index: 60;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<button class="btn btn-primary">hover</button>_x000D_
<span class="no-hover">_x000D_
  <button class="btn btn-primary ">no hover</button>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How can I print a quotation mark in C?

you should use escape character like this:

printf("\"");

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

I have done the following steps to get rid of this issue. Login into the MySQL in your machine using (sudo mysql -p -u root) and hit the following queries.

1. CREATE USER 'jack'@'localhost' IDENTIFIED WITH mysql_native_password BY '<<any password>>';

2. GRANT ALL PRIVILEGES ON *.* TO 'jack'@'localhost';

3. SELECT user,plugin,host FROM mysql.user WHERE user = 'root';
+------+-------------+-----------+
| user | plugin      | host      |

+------+-------------+-----------+

| root | auth_socket | localhost |

+------+-------------+-----------+

4. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '<<any password>>';

5. FLUSH PRIVILEGES;

Please try it once if you are still getting the error. I hope this code will help you a lot !!

what is reverse() in Django

There is a doc for that

https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls

it can be used to generate an URL for a given view

main advantage is that you do not hard code routes in your code.

jQuery, get html of a whole element

You can clone it to get the entire contents, like this:

var html = $("<div />").append($("#div1").clone()).html();

Or make it a plugin, most tend to call this "outerHTML", like this:

jQuery.fn.outerHTML = function() {
  return jQuery('<div />').append(this.eq(0).clone()).html();
};

Then you can just call:

var html = $("#div1").outerHTML();

Creating a JSON dynamically with each input value using jquery

I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.

Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.

See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.

In your case:

var array = [];
$("input[class=email]").each(function() {
    array.push({
        title: $(this).attr("title"),
        email: $(this).val()
    });
});
// then to get the JSON string
var jsonString = JSON.stringify(array);

Nth word in a string variable

No expensive forks, no pipes, no bashisms:

$ set -- $STRING
$ eval echo \${$N}
three

But beware of globbing.

How can I change Eclipse theme?

Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins folder.

When you have done that go to

Window -> Preferences -> General -> Appearance

And change the theme from GTK (or what ever it is currently) to Dark Juno (or Dark).

That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.

Eclipse Color Themes

This adds a "Color Theme" menu item under

Window -> Preferences -> Appearance

Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark

double free or corruption (!prev) error in c program

Change this line

double *ptr = malloc(sizeof(double *) * TIME);

to

double *ptr = malloc(sizeof(double) * TIME);

Convert char array to single int?

If you are using C++11, you should probably use stoi because it can distinguish between an error and parsing "0".

try {
    int number = std::stoi("1234abc");
} catch (std::exception const &e) {
    // This could not be parsed into a number so an exception is thrown.
    // atoi() would return 0, which is less helpful if it could be a valid value.
}

It should be noted that "1234abc" is implicitly converted from a char[] to a std:string before being passed to stoi().

how to use getSharedPreferences in android

First get the instance of SharedPreferences using

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();

Above lines will write username and password to preference

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

SQLite - UPSERT *not* INSERT or REPLACE

Updates from Bernhardt:

You can indeed do an upsert in SQLite, it just looks a little different than you are used to. It would look something like:

INSERT INTO table_name (id, column1, column2) 
VALUES ("youruuid", "value12", "value2")
ON CONFLICT(id) DO UPDATE 
SET column1 = "value1", column2 = "value2"

Java for loop multiple variables

change this line

for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){ 

to

for(int a = 0, b = 1; a<cards.length-1, b=a+1; a++){

DataSet panel (Report Data) in SSRS designer is gone

With a .rdl, .rdlc or similar file selected, you can either:

  • Click View -> Report Data or...
  • Use the keyboard shortcut CTRL + ALT + D

Example

Get The Current Domain Name With Javascript (Not the path, etc.)

I'm new to JavaScript, but cant you just use: document.domain ?

Example:

<p id="ourdomain"></p>

<script>
var domainstring = document.domain;
document.getElementById("ourdomain").innerHTML = (domainstring);
</script>

Output:

domain.com

or

www.domain.com

Depending on what you use on your website.

Google Maps API v3: Can I setZoom after fitBounds?

In this function, you need to dynamically add metadata to store the geometry type only because the function accepts any geometry.

"fitGeometries" is a JSON function extending a map object.

"geometries" is an generic javascript array not an MVCArray().

geometry.metadata = { type: "point" };
var geometries = [geometry];

fitGeometries: function (geometries) {
    // go and determine the latLngBounds...
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < geometries.length; i++) {
        var geometry = geometries[i];
        switch (geometry.metadata.type)
        {
            case "point":
                var point = geometry.getPosition();
                bounds.extend(point);
                break;
            case "polyline":
            case "polygon": // Will only get first path
                var path = geometry.getPath();
                for (var j = 0; j < path.getLength(); j++) {
                    var point = path.getAt(j);
                    bounds.extend(point);
                }
                break;
        }
    }
    this.getMap().fitBounds(bounds);
},

JPA eager fetch does not join

Two things occur to me.

First, are you sure you mean ManyToOne for address? That means multiple people will have the same address. If it's edited for one of them, it'll be edited for all of them. Is that your intent? 99% of the time addresses are "private" (in the sense that they belong to only one person).

Secondly, do you have any other eager relationships on the Person entity? If I recall correctly, Hibernate can only handle one eager relationship on an entity but that is possibly outdated information.

I say that because your understanding of how this should work is essentially correct from where I'm sitting.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.

Proxy Error

The proxy server received an invalid response from an upstream server.
 The proxy server could not handle the request GET /lin/Campaignn.jsp.

As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.

How do I set the time zone of MySQL?

To set the standard time zone at MariaDB you have to go to the 50-server.cnf file.

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Then you can enter the following entry in the mysqld section.

default-time-zone='+01:00'

Example:

#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]

# this is only for the mysqld standalone daemon
[mysqld]

#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking

### Default timezone ###
default-time-zone='+01:00'

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.

The change must be made via the configuration file, otherwise the MariaDB server will reset the mysql tables after a restart!

How do I schedule jobs in Jenkins?

Try this.

20 4 * * *

Check the below Screenshot

enter image description here

Referred URL - https://www.lenar.io/jenkins-schedule-build-periodically/

How to get Maven project version to the bash command line

I am using a one-liner in my unix shell ...

cat pom.xml | grep "" | head -n 1 | sed -e "s/version//g" | sed -e "s/\s*[<>/]*//g"

You can hide this line in a shell script or as an alias.

Extracting just Month and Year separately from Pandas Datetime column

Thanks to jaknap32, I wanted to aggregate the results according to Year and Month, so this worked:

df_join['YearMonth'] = df_join['timestamp'].apply(lambda x:x.strftime('%Y%m'))

Output was neat:

0    201108
1    201108
2    201108

Python: How to keep repeating a program until a specific input is obtained?

Easier way:

#required_number = 18

required_number=input("Insert a number: ")
while required_number != 18
    print("Oops! Something is wrong")
    required_number=input("Try again: ")
if required_number == '18'
    print("That's right!")

#continue the code

How to use jQuery in chrome extension?

Its very easy just do the following:

add the following line in your manifest.json

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",

Now you are free to load jQuery directly from url

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

Source: google doc

How to change row color in datagridview?

int counter = gridEstimateSales.Rows.Count;

for (int i = 0; i < counter; i++)
{
    if (i == counter-1)
    {
        //this is where your LAST LINE code goes
        //row.DefaultCellStyle.BackColor = Color.Yellow;
        gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.Red;
    }
    else
    {
        //this is your normal code NOT LAST LINE
        //row.DefaultCellStyle.BackColor = Color.Red;
        gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.White;
    }
}

Rounded corners for <input type='text' /> using border-radius.htc for IE

Writing from phone, but curvycorners is really good, since it adds it's own borders only if browser doesn't support it by default. In other words, browsers which already support some CSS3 will use their own system to provide corners.
https://code.google.com/p/curvycorners/

The Android emulator is not starting, showing "invalid command-line parameter"

NickC is correct. It is also worth pointing out that the SDK location is set in Eclipse > Window menu > Preferences > Android. If your folders are different you can check the 8.3 format of any folder with dir foldername /x at the command prompt.

Python Flask, how to set content type

I like and upvoted @Simon Sapin's answer. I ended up taking a slightly different tack, however, and created my own decorator:

from flask import Response
from functools import wraps

def returns_xml(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        r = f(*args, **kwargs)
        return Response(r, content_type='text/xml; charset=utf-8')
    return decorated_function

and use it thus:

@app.route('/ajax_ddl')
@returns_xml
def ajax_ddl():
    xml = 'foo'
    return xml

I think this is slightly more comfortable.

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

the problem might be that networkservice has no read rights

salution:

rightclick your upload folder -> poperty's -> security ->Edit -> add -> type :NETWORK SERVICE -> check box full control allow-> press ok or apply

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

The easiest way is to change imdb.py setting allow_pickle=True to np.load at the line where imdb.py throws error.

SQL query to find third highest salary in company

Below query will give accurate answer. Follow and give me comments:

select top 1 salary from (
select DISTINCT  top 3 salary from Table(table name) order by salary  ) as comp
order by personid salary 

php static function

In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() never refers to $this.

Static functions are associated with the class, not an instance of the class. As such, $this is not available from a static context ($this isn't pointing to any object).

Passing ArrayList from servlet to JSP

In the servlet code, with the instruction request.setAttribute("servletName", categoryList), you save your list in the request object, and use the name "servletName" for refering it.
By the way, using then name "servletName" for a list is quite confusing, maybe it's better call it "list" or something similar: request.setAttribute("list", categoryList)
Anyway, suppose you don't change your serlvet code, and store the list using the name "servletName". When you arrive to your JSP, it's necessary to retrieve the list from the request, and for that you just need the request.getAttribute(...) method.

<%  
// retrieve your list from the request, with casting 
ArrayList<Category> list = (ArrayList<Category>) request.getAttribute("servletName");

// print the information about every category of the list
for(Category category : list) {
    out.println(category.getId());
    out.println(category.getName());
    out.println(category.getMainCategoryId());
}
%>

How to truncate milliseconds off of a .NET DateTime

Here is an extension method based on a previous answer that will let you truncate to any resolution...

Usage:

DateTime myDateSansMilliseconds = myDate.Truncate(TimeSpan.TicksPerSecond);
DateTime myDateSansSeconds = myDate.Truncate(TimeSpan.TicksPerMinute)

Class:

public static class DateTimeUtils
{
    /// <summary>
    /// <para>Truncates a DateTime to a specified resolution.</para>
    /// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
    /// </summary>
    /// <param name="date">The DateTime object to truncate</param>
    /// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
    /// <returns>Truncated DateTime</returns>
    public static DateTime Truncate(this DateTime date, long resolution)
    {
        return new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
    }
}

Java, List only subdirectories from a directory, not files

ArrayList<File> directories = new ArrayList<File>(
    Arrays.asList(
        new File("your/path/").listFiles(File::isDirectory)
    )
);

Margin on child element moves parent element

An alternative solution I found before I knew the correct answer was to add a transparent border to the parent element.

Your box will use extra pixels though...

.parent {
    border:1px solid transparent;
}

AndroidStudio SDK directory does not exists

If you have set the ANDROID_HOME variable, just remove or comment that line in local.properties file. It is the solution for me

Convert SVG to image (JPEG, PNG, etc.) in the browser

I recently discovered a couple of image tracing libraries for JavaScript that indeed are able to build an acceptable approximation to the bitmap, both size and quality. I'm developing this JavaScript library and CLI :

https://www.npmjs.com/package/svg-png-converter

Which provides unified API for all of them, supporting browser and node, non depending on DOM, and a Command line tool.

For converting logos/cartoon/like images it does excellent job. For photos / realism some tweaking is needed since the output size can grow a lot.

It has a playground although right now I'm working on a better one, easier to use, since more features has been added:

https://cancerberosgx.github.io/demos/svg-png-converter/playground/#

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Formatting code snippets for blogging on Blogger

I rolled my own in F# (see this question), but it still isn't perfect (I just do regexps, so I don't recognise classes or method names etc.).

Basically, from what I can tell, the blogger editor will sometimes eat your angle brackets if you switch between Compose and HTML mode. So you have to paste into HTML mode then save directly. (I may be wrong on this, just tried now and it seems to work - browser dependent?)

It's horrible when you have generics!

How to search file text for a pattern and replace it with a given value

If you need to do substitutions across line boundaries, then using ruby -pi -e won't work because the p processes one line at a time. Instead, I recommend the following, although it could fail with a multi-GB file:

ruby -e "file='translation.ja.yml'; IO.write(file, (IO.read(file).gsub(/\s+'$/, %q('))))"

The is looking for white space (potentially including new lines) following by a quote, in which case it gets rid of the whitespace. The %q(')is just a fancy way of quoting the quote character.

Jquery insert new row into table at a certain index

You can use .eq() and .after() like this:

$('#my_table > tbody > tr').eq(i-1).after(html);

The indexes are 0 based, so to be the 4th row, you need i-1, since .eq(3) would be the 4th row, you need to go back to the 3rd row (2) and insert .after() that.

How to run a SQL query on an Excel table?

If you have GDAL/OGR compiled with the against the Expat library, you can use the XLSX driver to read .xlsx files, and run SQL expressions from a command prompt. For example, from a osgeo4w shell in the same directory as the spreadsheet, use the ogrinfo utility:

ogrinfo -dialect sqlite -sql "SELECT name, count(*) FROM sheet1 GROUP BY name" Book1.xlsx

will run a SQLite query on sheet1, and output the query result in an unusual form:

INFO: Open of `Book1.xlsx'
      using driver `XLSX' successful.

Layer name: SELECT
Geometry: None
Feature Count: 36
Layer SRS WKT:
(unknown)
name: String (0.0)
count(*): Integer (0.0)
OGRFeature(SELECT):0
  name (String) = Red
  count(*) (Integer) = 849

OGRFeature(SELECT):1
  name (String) = Green
  count(*) (Integer) = 265
...

Or run the same query using ogr2ogr to make a simple CSV file:

$ ogr2ogr -f CSV out.csv -dialect sqlite \
          -sql "SELECT name, count(*) FROM sheet1 GROUP BY name" Book1.xlsx

$ cat out.csv
name,count(*)
Red,849
Green,265
...

To do similar with older .xls files, you would need the XLS driver, built against the FreeXL library, which is not really common (e.g. not from OSGeo4w).

Change color of Back button in navigation bar

You can use like this one. Place it inside AppDelegate.swift.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        UINavigationBar.appearance().translucent = false
        UINavigationBar.appearance().barTintColor = UIColor(rgba: "#2c8eb5")
        UINavigationBar.appearance().tintColor = UIColor.whiteColor()
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]

        return true
    }

SQL Joins Vs SQL Subqueries (Performance)?

I would EXPECT the first query to be quicker, mainly because you have an equivalence and an explicit JOIN. In my experience IN is a very slow operator, since SQL normally evaluates it as a series of WHERE clauses separated by "OR" (WHERE x=Y OR x=Z OR...).

As with ALL THINGS SQL though, your mileage may vary. The speed will depend a lot on indexes (do you have indexes on both ID columns? That will help a lot...) among other things.

The only REAL way to tell with 100% certainty which is faster is to turn on performance tracking (IO Statistics is especially useful) and run them both. Make sure to clear your cache between runs!

What is "with (nolock)" in SQL Server?

The simplest answer is a simple question - do you need your results to be repeatable? If yes then NOLOCKS is not appropriate under any circumstances

If you don't need repeatability then nolocks may be useful, especially if you don't have control over all processes connecting to the target database.

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

In my case it was because the file was minified with wrong scope. Use Array!

app.controller('StoreController', ['$http', function($http) {
    ...
}]);

Coffee syntax:

app.controller 'StoreController', Array '$http', ($http) ->
  ...

In Python, how do I create a string of n characters in one line of code?

if you just want any letters:

 'a'*10  # gives 'aaaaaaaaaa'

if you want consecutive letters (up to 26):

 ''.join(['%c' % x for x in range(97, 97+10)])  # gives 'abcdefghij'

How to find the size of integer array

int len=sizeof(array)/sizeof(int);

Should work.

List of foreign keys and the tables they reference in Oracle DB

Try this:

select * from all_constraints where r_constraint_name in (select constraint_name 
from all_constraints where table_name='YOUR_TABLE_NAME');

Changing the "tick frequency" on x or y axis in matplotlib?

I like this solution (from the Matplotlib Plotting Cookbook):

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]

tick_spacing = 1

fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.show()

This solution give you explicit control of the tick spacing via the number given to ticker.MultipleLocater(), allows automatic limit determination, and is easy to read later.

What is the best way to remove the first element from an array?

Simplest way is probably as follows - you basically need to construct a new array that is one element smaller, then copy the elements you want to keep to the right positions.

int n=oldArray.length-1;
String[] newArray=new String[n];
System.arraycopy(oldArray,1,newArray,0,n);

Note that if you find yourself doing this kind of operation frequently, it could be a sign that you should actually be using a different kind of data structure, e.g. a linked list. Constructing a new array every time is an O(n) operation, which could get expensive if your array is large. A linked list would give you O(1) removal of the first element.

An alternative idea is not to remove the first item at all, but just increment an integer that points to the first index that is in use. Users of the array will need to take this offset into account, but this can be an efficient approach. The Java String class actually uses this method internally when creating substrings.

Jquery Open in new Tab (_blank)

Replace this line:

$(this).target = "_blank";

With:

$( this ).attr( 'target', '_blank' );

That will set its HREF to _blank.

ERROR 1064 (42000) in MySQL

Do you have a specific database selected like so:

USE database_name

Except for that I can't think of any reason for this error.

Environment variables in Jenkins

The quick and dirty way, you can view the available environment variables from the below link.

http://localhost:8080/env-vars.html/

Just replace localhost with your Jenkins hostname, if its different

How to access a RowDataPacket object

Solution

Just do: JSON.stringify(results)

Project with path ':mypath' could not be found in root project 'myproject'

Remove all the texts in android/settings.gradle and paste the below code

rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned

Display HTML snippets in HTML

It's vey simple .... Use this xmp code

    <xmp id="container">

&lt;xmp &gt;

    <p>a paragraph</p>

    &lt;/xmp &gt;

</xmp>

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

if you need to add a date-time to your backup file name (Centos7) use the following:

/usr/bin/mysqldump -u USER -pPASSWD DBNAME | gzip > ~/backups/db.$(date +%F.%H%M%S).sql.gz

this will create the file: db.2017-11-17.231537.sql.gz

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

I find the answer. 1/First put in the presets, i have this example "Output format MPEG2 DVD HQ"

-vcodec mpeg2video -vstats_file MFRfile.txt -r 29.97 -s 352x480 -aspect 4:3 -b 4000k -mbd rd -trellis -mv0 -cmp 2 -subcmp 2 -acodec mp2 -ab 192k -ar 48000 -ac 2

If you want a report includes the commands -vstats_file MFRfile.txt into the presets like the example. this can make a report which it's ubicadet in the folder source of your file Source. you can put any name if you want , i solved my problem "i write many times in this forum" reading a complete .docx about mpeg properties. finally i can do my progress bar reading this txt file generated.

Regards.

Java 8 optional: ifPresent return object orElseThrow exception

Two options here:

Replace ifPresent with map and use Function instead of Consumer

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object
            .map(obj -> {
                String result = "result";
                //some logic with result and return it
                return result;
            })
            .orElseThrow(MyCustomException::new);
}

Use isPresent:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    if (object.isPresent()) {
        String result = "result";
        //some logic with result and return it
        return result;
    } else {
        throw new MyCustomException();
    }
}

Return current date plus 7 days

If it's 7 days from now that you're looking for, just put:

$date = strtotime("+7 day", time());
echo date('M d, Y', $date);

CSS rule to apply only if element has BOTH classes

Below applies to all tags with the following two classes

.abc.xyz {  
  width: 200px !important;
}

applies to div tags with the following two classes

div.abc.xyz {  
  width: 200px !important;
}

If you wanted to modify this using jQuery

$(document).ready(function() {
  $("div.abc.xyz").width("200px");
});

Specifying content of an iframe instead of the src attribute to a page

You can .write() the content into the iframe document. Example:

<iframe id="FileFrame" src="about:blank"></iframe>

<script type="text/javascript">
   var doc = document.getElementById('FileFrame').contentWindow.document;
   doc.open();
   doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
   doc.close();
</script>

What does the question mark and the colon (?: ternary operator) mean in objective-c?

That's just the usual ternary operator. If the part before the question mark is true, it evaluates and returns the part before the colon, otherwise it evaluates and returns the part after the colon.

a?b:c

is like

if(a)
    b;
else
    c;

List all tables in postgresql information_schema

For listing your tables use:

SELECT table_name FROM information_schema.tables WHERE table_schema='public'

It will only list tables that you create.

Google Maps API v3: InfoWindow not sizing correctly

I know that lots of other people have found solutions that worked for their particular case, but since none of them worked for my particular case, I thought this might be helpful to someone else.

Some details:

I'm using google maps API v3 on a project where inline CSS is something we really, really want to avoid. My infowindows were working for everything except for IE11, where the width was not calculated correctly. This resulted in div overflows, which triggered scrollbars.

I had to do three things:

  1. Remove all display: inline-block style rules from anything inside of the infowindow content (I replaced with display: block) - I got the idea to try this from a thread (which I can't find anymore) where someone was having the same problem with IE6.

  2. Pass the content as a DOM node instead of as a string. I am using jQuery, so I could do this by replacing: infowindow.setContent(infoWindowDiv.html()); with infowindow.setContent($(infoWindowDiv.html())[0]); This turned out to be easiest for me, but there are lots of other ways to get the same result.

  3. Use the "setMaxWidth" hack - set the MaxWidth option in the constructor - setting the option later doesn't work. If you don't really want a max width, just set it to a very large number.

I don't know why these worked, and I'm not sure if a subset of them would work. I know that none of them work for all of my use cases individually, and that 2 + 3 doesn't work. I didn't have time to test 1 + 2 or 1 + 3.

How to make rectangular image appear circular with CSS

Following worked for me:

CSS

.round {
  border-radius: 50%;
  overflow: hidden;
  width: 30px;
  height: 30px;
  background: no-repeat 50%;
  object-fit: cover;
}
.round img {
   display: block;
   height: 100%;
   width: 100%;
}

HTML

<div class="round">
   <img src="test.png" />
</div>

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I tried "validating" de *.jsp and *.xml files in eclipse with the validate tool.

"right click on directory/file ->- validate" and it worked!

Using eclipse juno.

Hope it helps!

javascript function wait until another function to finish

In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.

Here is an example I have just written to demonstrate how you could do it using deferreds/promises.

Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.

Hope this helps!

$(function(){
    function1().done(function(){
        // function1 is done, we can now call function2
        console.log('function1 is done!');

        function2().done(function(){
            //function2 is done
            console.log('function2 is done!');
        });
    });
});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}

function function2(){
    var dfrd1 = $.Deferred();
    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function2 is done!');
        dfrd1.resolve();
    }, 2000);
    return dfrd1.promise();
}

Overlaying a DIV On Top Of HTML 5 Video

There you go , i hope this helps

http://jsfiddle.net/kNMnr/

here is the CSS also

#video_box{
    float:left;
}
#video_overlays {
position:absolute;
float:left;
    width:640px;
    min-height:370px;
    background-color:#000;
    z-index:300000;
}

How can I reduce the waiting (ttfb) time

I would suggest you read this article and focus more on how to optimize the overall response to the user request (either a page, a search result etc.)

A good argument for this is the example they give about using gzip to compress the page. Even though ttfb is faster when you do not compress, the overall experience of the user is worst because it takes longer to download content that is not zipped.

What Java ORM do you prefer, and why?

SimpleORM, because it is straight-forward and no-magic. It defines all meta data structures in Java code and is very flexible.

SimpleORM provides similar functionality to Hibernate by mapping data in a relational database to Java objects in memory. Queries can be specified in terms of Java objects, object identity is aligned with database keys, relationships between objects are maintained and modified objects are automatically flushed to the database with optimistic locks.

But unlike Hibernate, SimpleORM uses a very simple object structure and architecture that avoids the need for complex parsing, byte code processing etc. SimpleORM is small and transparent, packaged in two jars of just 79K and 52K in size, with only one small and optional dependency (Slf4j). (Hibernate is over 2400K plus about 2000K of dependent Jars.) This makes SimpleORM easy to understand and so greatly reduces technical risk.

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

You may need to add a JDK (Java Development Kit) to the installed JRE's within Eclipse

Go to Window->Preferences->Java->Installed JRE's

In the Name column if you do not have a JDK as your default, then you will need to add it.

Click the "Add" Button and locate the JDK on your machine. You may find it in this location: C:\Program Files\Java\jdk1.x.y
Where x and y are numbers.

If there are no JDK's installed on your machine then download and install the Java SE (Standard Edition) from the Oracle website.

Then do the steps above again. Be sure that it is set as the default JRE to use.

Then go back to the Projects->Generate Javadoc... dialog

Now it should work.

Good Luck.

Sql script to find invalid email addresses

select
    email 
from loginuser where
patindex ('%[ &'',":;!+=\/()<>]*%', email) > 0  -- Invalid characters
or patindex ('[@.-_]%', email) > 0   -- Valid but cannot be starting character
or patindex ('%[@.-_]', email) > 0   -- Valid but cannot be ending character
or email not like '%@%.%'   -- Must contain at least one @ and one .
or email like '%..%'        -- Cannot have two periods in a row
or email like '%@%@%'       -- Cannot have two @ anywhere
or email like '%.@%' or email like '%@.%' -- Cant have @ and . next to each other
or email like '%.cm' or email like '%.co' -- Unlikely. Probably typos 
or email like '%.or' or email like '%.ne' -- Missing last letter

This worked for me. Had to apply rtrim and ltrim to avoid false positives.

Source: http://sevenwires.blogspot.com/2008/09/sql-how-to-find-invalid-email-in-sql.html

Postgres version:

select user_guid, user_guid email_address, creation_date, email_verified, active
from user_data where
length(substring (email_address from '%[ &'',":;!+=\/()<>]%')) > 0  -- Invalid characters
or length(substring (email_address from '[@.-_]%')) > 0   -- Valid but cannot be starting character
or length(substring (email_address from '%[@.-_]')) > 0   -- Valid but cannot be ending character
or email_address not like '%@%.%'   -- Must contain at least one @ and one .
or email_address like '%..%'        -- Cannot have two periods in a row
or email_address like '%@%@%'       -- Cannot have two @ anywhere
or email_address like '%.@%' or email_address like '%@.%' -- Cant have @ and . next to each other
or email_address like '%.cm' or email_address like '%.co' -- Unlikely. Probably typos 
or email_address like '%.or' or email_address like '%.ne' -- Missing last letter
;

Use grep --exclude/--include syntax to not grep through certain files

If you search non-recursively you can use glop patterns to match the filenames.

grep "foo" *.{html,txt}

includes html and txt. It searches in the current directory only.

To search in the subdirectories:

   grep "foo" */*.{html,txt}

In the subsubdirectories:

   grep "foo" */*/*.{html,txt}

Connecting PostgreSQL 9.2.1 with Hibernate

Yes by using spring-boot with hibernate configuration files we can persist the data to the database. keep hibernating .cfg.xml in your src/main/resources folder for reading the configurations related to database.

enter image description here

Java dynamic array sizes?

You can use ArrayList:

import java.util.ArrayList;
import java.util.Iterator;

...

ArrayList<String> arr = new ArrayList<String>();
arr.add("neo");
arr.add("morpheus");
arr.add("trinity");
Iterator<String> foreach = arr.iterator();
while (foreach.hasNext()) System.out.println(foreach.next());

How to set environment variables in Jenkins?

In my case, I needed to add the JMETER_HOME environment variable to be available via my Ant build scripts across all projects on my Jenkins server (Linux), in a way that would not interfere with my local build environment (Windows and Mac) in the build.xml script. Setting the environment variable via Manage Jenkins - Configure System - Global properties was the easiest and least intrusive way to accomplish this. No plug-ins are necessary.

Manage Jenkins Global Properties


The environment variable is then available in Ant via:

<property environment="env" />
<property name="jmeter.home" value="${env.JMETER_HOME}" />

This can be verified to works by adding:

<echo message="JMeter Home: ${jmeter.home}"/>

Which produces:

JMeter Home: ~/.jmeter

How to use mongoimport to import csv

you will most likely need to authenticate if you're working in production sort of environments. You can use something like this to authenticate against the correct database with appropriate credentials.

mongoimport -d db_name -c collection_name --type csv --file filename.csv --headerline --host hostname:portnumber --authenticationDatabase admin --username 'iamauser' --password 'pwd123'

How to create a new schema/new user in Oracle Database 11g?

SQL> select Username from dba_users
  2  ;

USERNAME
------------------------------
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL
MDSYS

USERNAME
------------------------------
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

16 rows selected.

SQL> create user testdb identified by password;

User created.

SQL> select username from dba_users;

USERNAME
------------------------------
TESTDB
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL

USERNAME
------------------------------
MDSYS
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

17 rows selected.

SQL> grant create session to testdb;

Grant succeeded.

SQL> create tablespace testdb_tablespace
  2  datafile 'testdb_tabspace.dat'
  3  size 10M autoextend on;

Tablespace created.

SQL> create temporary tablespace testdb_tablespace_temp
  2  tempfile 'testdb_tabspace_temp.dat'
  3  size 5M autoextend on;

Tablespace created.

SQL> drop user testdb;

User dropped.

SQL> create user testdb
  2  identified by password
  3  default tablespace testdb_tablespace
  4  temporary tablespace testdb_tablespace_temp;

User created.

SQL> grant create session to testdb;

Grant succeeded.

SQL> grant create table to testdb;

Grant succeeded.

SQL> grant unlimited tablespace to testdb;

Grant succeeded.

SQL>

HTTP test server accepting GET/POST requests

You can run the actual Ken Reitz's httpbin server locally (under docker or on bare metal):

https://github.com/postmanlabs/httpbin

Run dockerized

docker pull kennethreitz/httpbin
docker run -p 80:80 kennethreitz/httpbin

Run directly on your machine

## install dependencies
pip3 install gunicorn decorator httpbin werkzeug Flask flasgger brotlipy gevent meinheld six pyyaml

## start the server
gunicorn -b 0.0.0.0:8000 httpbin:app -k gevent

Now you have your personal httpbin instance running on http://0.0.0.0:8000 (visible to all of your LAN)

How to use zIndex in react-native

You cannot achieve the desired solution with CSS z-index either, as z-index is only relative to the parent element. So if you have parents A and B with respective children a and b, b's z-index is only relative to other children of B and a's z-index is only relative to other children of A.

The z-index of A and B are relative to each other if they share the same parent element, but all of the children of one will share the same relative z-index at this level.

Django error - matching query does not exist

your line raising the error is here:

comment = Comment.objects.get(pk=comment_id)

you try to access a non-existing comment.

from django.shortcuts import get_object_or_404

comment = get_object_or_404(Comment, pk=comment_id)

Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.

Ok up to here I suppose you are aware of this.

Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.

Other users go to addresses from their history, (same if data have been deleted since it may happens).

How to find the duration of difference between two dates in java?

It worked for me can try with this, hope it will be helpful . Let me know if any concern .

Date startDate = java.util.Calendar.getInstance().getTime(); //set your start time
Date endDate = java.util.Calendar.getInstance().getTime(); // set  your end time

long duration = endDate.getTime() - startDate.getTime();


long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

Toast.makeText(MainActivity.this, "Diff"
        + duration + diffInDays + diffInHours + diffInMinutes + diffInSeconds, Toast.LENGTH_SHORT).show(); **// Toast message for android .**

System.out.println("Diff" + duration + diffInDays + diffInHours + diffInMinutes + diffInSeconds); **// Print console message for Java .**

Connection to SQL Server Works Sometimes

I had the exact issue, tried several soultion didnt work , lastly restarted the system , it worked fine.

JavaFX "Location is required." even though it is in the same package

If your problem is not Maven related and you get the same NullPointerException running this in a browser (while running it from the IDE is fine), try this:

-> Netbeans -> Right-Click Project -> Properties -> Build -> Deployment -> Check "Request unrestricted access (Enable signing, self-signed)"

This is due to the @FXML Annotation needing permission to inject the value from the FXML markup (see http://docs.oracle.com/javafx/2/fxml_get_started/fxml_deployment.htm )

I was running my App on JDK8u31 and it would never run without the certificate in Chrome / Firefox / IE.

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

After placing the jar file in desired location, you need to add the jar file by right click on

Project --> properties --> Java Build Path --> Libraries --> Add Jar.

Disable eslint rules for folder

To ignore some folder from eslint rules we could create the file .eslintignore in root directory and add there the path to the folder we want omit (the same way as for .gitignore).

Here is the example from the ESLint docs on Ignoring Files and Directories:

# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default

# Ignore built files except build/index.js
build/*
!build/index.js

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

Is it a bad practice to use an if-statement without curly braces?

I agree with most answers in the fact that it is better to be explicit in your code and use braces. Personally I would adopt a set of coding standards and ensure that everyone on the team knows them and conforms. Where I work we use coding standards published by IDesign.net for .NET projects.

Get checkbox value in jQuery

$('.class[value=3]').prop('checked', true);

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

How to restore/reset npm configuration to default values?

For what it's worth, you can reset to default the value of a config entry with npm config delete <key> (or npm config rm <key>, but the usage of npm config rm is not mentioned in npm help config).

Example:

# set registry value
npm config set registry "https://skimdb.npmjs.com/registry"
# revert change back to default
npm config delete registry

specifying goal in pom.xml

I am facing same Issue after run my build.

The error message tell us to specify your goal

Jenkins Issue related to goal for build

So I specify the goal Ex:-test.

Now It's running fine

Is it possible to install another version of Python to Virtualenv?

First of all, Thank you DTing for awesome answer. It's pretty much perfect.

For those who are suffering from not having GCC access in shared hosting, Go for ActivePython instead of normal python like Scott Stafford mentioned. Here are the commands for that.

wget http://downloads.activestate.com/ActivePython/releases/2.7.13.2713/ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

tar -zxvf ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

cd ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785

./install.sh

It will ask you path to python directory. Enter

../../.localpython

Just replace above as Step 1 in DTing's answer and go ahead with Step 2 after that. Please note that ActivePython package URL may change with new release. You can always get new URL from here : http://www.activestate.com/activepython/downloads

Based on URL you need to change the name of tar and cd command based on file received.

Change Orientation of Bluestack : portrait/landscape mode

Here are the step:

  1. Install the Nova theme in bluestack
  2. go into Nova setting -> look and feel -> screen orientation -> Force Portrait -> go to Home screen

You are done! :)

How to change line width in ggplot?

Line width in ggplot2 can be changed with argument lwd= in geom_line().

geom_line(aes(x=..., y=..., color=...), lwd=1.5)

How to copy a row from one SQL Server table to another

Alternative syntax:

INSERT tbl (Col1, Col2, ..., ColN)
  SELECT Col1, Col2, ..., ColN
  FROM Tbl2
  WHERE ...

The select query can (of course) include expressions, case statements, constants/literals, etc.

Using current time in UTC as default value in PostgreSQL

Wrap it in a function:

create function now_utc() returns timestamp as $$
  select now() at time zone 'utc';
$$ language sql;

create temporary table test(
  id int,
  ts timestamp without time zone default now_utc()
);

Where does Android app package gets installed on phone

System apps installed /system/app/ or /system/priv-app. Other apps can be installed in /data/app or /data/preload/.

Connect to your android mobile with USB and run the following commands. You will see all the installed packages.

$ adb shell 

$ pm list packages -f

What is the difference between dim and set in vba

Dim: you are defining a variable (here: r is a variable of type Range)

Set: you are setting the property (here: set the value of r to Range("A1") - this is not a type, but a value).

You have to use set with objects, if r were a simple type (e.g. int, string), then you would just write:

Dim r As Integer
r=5

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

Python urllib2: Receive JSON response from url

If the URL is returning valid JSON-encoded data, use the json library to decode that:

import urllib2
import json

response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
data = json.load(response)   
print data

Getting assembly name

You can use the AssemblyName class to get the assembly name, provided you have the full name for the assembly:

AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().FullName).Name

or

AssemblyName.GetAssemblyName(e.Source).Name

MSDN Reference - AssemblyName Class

g++ undefined reference to typeinfo

I've got same error when my interface (with all pure virtual functions) needed one more function and I forgot to "null" it.

I had

class ICommProvider { public: /** * @brief If connection is established, it sends the message into the server. * @param[in] msg - message to be send * @return 0 if success, error otherwise */ virtual int vaSend(const std::string &msg) = 0; /** * @brief If connection is established, it is waiting will server response back. * @param[out] msg is the message received from server * @return 0 if success, error otherwise */ virtual int vaReceive(std::string &msg) = 0; virtual int vaSendRaw(const char *buff, int bufflen) = 0; virtual int vaReceiveRaw(char *buff, int bufflen) = 0; /** * @bief Closes current connection (if needed) after serving * @return 0 if success, error otherwise */ virtual int vaClose(); };

Last vaClose is not virtual so compiled did not know where to get implementation for it and thereby got confused. my message was:

...TCPClient.o:(.rodata+0x38): undefined reference to `typeinfo for ICommProvider'

Simple change from

virtual int vaClose();

to

virtual int vaClose() = 0;

fixed the problem. hope it helps

store and retrieve a class object in shared preference

You can use Complex Preferences Android - by Felipe Silvestre library to store your custom objects. Basically, it's using GSON mechanism to store objects.

To save object into prefs:

User user = new User();
user.setName("Felipe");
user.setAge(22); 
user.setActive(true); 

ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(
     this, "mypref", MODE_PRIVATE);
complexPreferences.putObject("user", user);
complexPreferences.commit();

And to retrieve it back:

ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(this, "mypref", MODE_PRIVATE);
User user = complexPreferences.getObject("user", User.class);

Tomcat Server Error - Port 8080 already in use

I would suggest to end java.exe or javaw.exe process from task manager and try again. This will not end the entire eclipse application but will free the port.

Eventviewer eventid for lock and unlock

The event IDs to look for in pre-Vista Windows are 528, 538, and 680. 528 usually stands for successful unlock of workstation.

The codes for newer Windows versions differ, see below answers for more infos.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

I used following logic and it worked for me like marvel:

CONVERT(TIME, DATEADD(MINUTE, DATEDIFF(MINUTE, AP.Time_IN, AP.Time_OUT), 0)) 

Is it possible to declare two variables of different types in a for loop?

I think best approach is xian's answer.

but...


# Nested for loop

This approach is dirty, but can solve at all version.

so, I often use it in macro functions.

for(int _int=0, /* make local variable */ \
    loopOnce=true; loopOnce==true; loopOnce=false)

    for(char _char=0; _char<3; _char++)
    {
        // do anything with
        // _int, _char
    }

Additional 1.

It can also be used to declare local variables and initialize global variables.

float globalFloat;

for(int localInt=0, /* decalre local variable */ \
    _=1;_;_=0)

    for(globalFloat=2.f; localInt<3; localInt++) /* initialize global variable */
    {
        // do.
    }

Additional 2.

Good example : with macro function.

(If best approach can't be used because it is a for-loop-macro)

#define for_two_decl(_decl_1, _decl_2, cond, incr) \
for(_decl_1, _=1;_;_=0)\
    for(_decl_2; (cond); (incr))


    for_two_decl(int i=0, char c=0, i<3, i++)
    {
        // your body with
        // i, c
    }

# If-statement trick

if (A* a=nullptr);
else
    for(...) // a is visible

If you want initialize to 0 or nullptr, you can use this trick.

but I don't recommend this because of hard reading.

and it seems like bug.

How to resume Fragment from BackStack if exists

Easier solution will be changing this line

ft.replace(R.id.content_frame, A); to ft.add(R.id.content_frame, A);

And inside your XML layout please use

  android:background="@color/white"
  android:clickable="true"
  android:focusable="true"

Clickable means that it can be clicked by a pointer device or be tapped by a touch device.

Focusable means that it can gain the focus from an input device like a keyboard. Input devices like keyboards cannot decide which view to send its input events to based on the inputs itself, so they send them to the view that has focus.

How do I execute a file in Cygwin?

Apparently, gcc doesn't behave like the one described in The C Programming language, where it says that the command cc helloworld.c produces a file called a.out which can be run by typing a.out on the prompt.

A Unix hasn't behaved in that way by default (so you can just write the executable name without ./ at the front) in a long time. It's called a.exe, because else Windows won't execute it, as it gets file types from the extension.

Unable to compile simple Java 10 / Java 11 project with Maven

As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the maven-compiler-plugin:3.8.0 to specify a release of either 9,10,11 without any explicit dependencies.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <release>11</release>  <!--or <release>10</release>-->
    </configuration>
</plugin>

Note:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- release notes.


Edit [30.12.2018]

In fact, you can make use of the same version of maven-compiler-plugin while compiling the code against JDK/12 as well.

More details and a sample configuration in how to Compile and execute a JDK preview feature with Maven.

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Font awesome use SVG icons. So, you can resize it for your requirment.

just use CSS class for that,

    .large-icon{
       font-size:10em;
       //or
      font-size:200%;
      //or
      font-size:50px;
    }

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

Note: With ConcurrentMap you can use the more efficient

values.putIfAbsent(NoteColumns.CREATED_DATE, now);

I prefer the less verbose solution and avoid methods like IsTrue or IsFalse or their like.

How can I list all collections in the MongoDB shell?

Try:

help // To show all help methods
show dbs  // To show all dbs
use dbname  // To select your db
show collections // To show all collections in selected db

Action Bar's onClick listener for the Home button

Fixed: no need to use a setOnMenuItemClickListener. Just pressing the button, it creates and launches the activity through the intent.

Thanks a lot everybody for your help!

A Simple, 2d cross-platform graphics library for c or c++?

One neat engine I came across is Angel-Engine. Info from the project site:

  • Cross-Platform functionality (Windows and Mac)
  • Actors (game objects with color, shape, responses, attributes, etc.)
  • Texturing with Transparency
  • "Animations" (texture swapping at defined intervals)
  • Rigid-Body Physics
    • A clever programmer can do soft-body physics with it
  • Sound
  • Text Rendering with multiple fonts
  • Particle Systems
  • Some basic AI (state machine and pathfinding)
  • Config File Processing
  • Logging
  • Input from a mouse, keyboard, or Xbox 360 controller
    • Binding inputs from a config file
  • Python Scripting
    • In-Game Console

Some users (including me) have succesfully (without any major problems) compiled it under linux.

Creating a triangle with for loops

Try this one in Java

for (int i = 6, k = 0; i > 0 && k < 6; i--, k++) {
    for (int j = 0; j < i; j++) {
        System.out.print(" ");
    }
    for (int j = 0; j < k; j++) {
        System.out.print("*");
    }
    for (int j = 1; j < k; j++) {
        System.out.print("*");
    }
    System.out.println();
}

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

A crude way would be to call dumpbin with the headers option from the Visual Studio tools on each DLL and look for the appropriate output:

dumpbin /headers my32bit.dll

PE signature found

File Type: DLL

FILE HEADER VALUES
             14C machine (x86)
               1 number of sections
        45499E0A time date stamp Thu Nov 02 03:28:10 2006
               0 file pointer to symbol table
               0 number of symbols
              E0 size of optional header
            2102 characteristics
                   Executable
                   32 bit word machine
                   DLL

OPTIONAL HEADER VALUES
             10B magic # (PE32)

You can see a couple clues in that output that it is a 32 bit DLL, including the 14C value that Paul mentions. Should be easy to look for in a script.

sudo echo "something" >> /etc/privilegedFile doesn't work

The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user.

Try the following code snippet:

sudo sh -c "echo 'something' >> /etc/privilegedfile"

jQuery creating objects

You can always make it a function

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')
}

writeObject('blue') ? enter image description here

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

How to get the entire document HTML as a string?

The correct way is actually:

webBrowser1.DocumentText

How do you convert a time.struct_time object into a datetime object?

Like this:

>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)

How to check for an undefined or null variable in JavaScript?

I have done this using this method

save the id in some variable

var someVariable = document.getElementById("someId");

then use if condition

if(someVariable === ""){
 //logic
} else if(someVariable !== ""){
 //logic
}

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

Mapping composite keys using EF code first

Through Configuration, you can do this:

Model1
{
    int fk_one,
    int fk_two
}

Model2
{
    int pk_one,
    int pk_two,
}

then in the context config

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Model1>()
            .HasRequired(e => e.Model2)
            .WithMany(e => e.Model1s)
            .HasForeignKey(e => new { e.fk_one, e.fk_two })
            .WillCascadeOnDelete(false);
    }
}

Alter column in SQL Server

I think you want this syntax:

ALTER TABLE tb_TableName  
add constraint cnt_Record_Status Default '' for Record_Status

Based on some of your comments, I am going to guess that you might already have null values in your table which is causing the alter of the column to not null to fail. If that is the case, then you should run an UPDATE first. Your script will be:

update tb_TableName
set Record_Status  = ''
where Record_Status is null

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

See SQL Fiddle with demo

Refused to apply inline style because it violates the following Content Security Policy directive

You can use in Content-security-policy add "img-src 'self' data:;" And Use outline CSS.Don't use Inline CSS.It's secure from attackers.

Arithmetic overflow error converting numeric to data type numeric

I feel I need to clarify one very important thing, for others (like my co-worker) who came across this thread and got the wrong information.

The answer given ("Try decimal(9,2) or decimal(10,2) or whatever.") is correct, but the reason ("increase the number of digits before the decimal") is wrong.

decimal(p,s) and numeric(p,s) both specify a Precision and a Scale. The "precision" is not the number of digits to the left of the decimal, but instead is the total precision of the number.

For example: decimal(2,1) covers 0.0 to 9.9, because the precision is 2 digits (00 to 99) and the scale is 1. decimal(4,1) covers 000.0 to 999.9 decimal(4,2) covers 00.00 to 99.99 decimal(4,3) covers 0.000 to 9.999

Difference between natural join and inner join

A natural join is just a shortcut to avoid typing, with a presumption that the join is simple and matches fields of the same name.

SELECT
  *
FROM
  table1
NATURAL JOIN
  table2
    -- implicitly uses `room_number` to join

Is the same as...

SELECT
  *
FROM
  table1
INNER JOIN
  table2
    ON table1.room_number = table2.room_number

What you can't do with the shortcut format, however, is more complex joins...

SELECT
  *
FROM
  table1
INNER JOIN
  table2
    ON (table1.room_number = table2.room_number)
    OR (table1.room_number IS NULL AND table2.room_number IS NULL)

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

try ToString method for your desirer format use

DateTime.Now.ToString("yyyy-MM-dd"); 


OR you can use it with your variable of DateTime type

dt.ToString("yyyy-MM-dd");


where dt is a DateTime variable

Failed to load AppCompat ActionBar with unknown error in android studio

in android 3.0.0 canary 6 you must change all 2.6.0 beta2 to beta1 (appcompat,design,supportvector)

Copy every nth line from one sheet to another

In A1 of your new sheet, put this:

=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)

... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.

If you want to copy the nth line but multiple columns, use the formula:

=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)

This can be copied right too.

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

Origin is not allowed by Access-Control-Allow-Origin

If you get this in Angular.js, then make sure you escape your port number like this:

var Project = $resource(
    'http://localhost\\:5648/api/...', {'a':'b'}, {
        update: { method: 'PUT' }
    }
);

See here for more info on it.

How to calculate modulus of large numbers?

/* The algorithm is from the book "Discrete Mathematics and Its
   Applications 5th Edition" by Kenneth H. Rosen.
   (base^exp)%mod
*/

int modular(int base, unsigned int exp, unsigned int mod)
{
    int x = 1;
    int power = base % mod;

    for (int i = 0; i < sizeof(int) * 8; i++) {
        int least_sig_bit = 0x00000001 & (exp >> i);
        if (least_sig_bit)
            x = (x * power) % mod;
        power = (power * power) % mod;
    }

    return x;
}

Convert Base64 string to an image file?

That's an old thread, but in case you want to upload the image having same extension-

    $image = $request->image;
    $imageInfo = explode(";base64,", $image);
    $imgExt = str_replace('data:image/', '', $imageInfo[0]);      
    $image = str_replace(' ', '+', $imageInfo[1]);
    $imageName = "post-".time().".".$imgExt;
    Storage::disk('public_feeds')->put($imageName, base64_decode($image));

You can create 'public_feeds' in laravel's filesystem.php-

   'public_feeds' => [
        'driver' => 'local',
        'root'   => public_path() . '/uploads/feeds',
    ],

Why do you need to put #!/bin/bash at the beginning of a script file?

The operating system takes default shell to run your shell script. so mentioning shell path at the beginning of script, you are asking the OS to use that particular shell. It is also useful for portability.

SQL Row_Number() function in Where Clause

Select * from 
(
    Select ROW_NUMBER() OVER ( order by Id) as 'Row_Number', * 
    from tbl_Contact_Us
) as tbl
Where tbl.Row_Number = 5

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

remap is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:

:map and :noremap are recursive and non-recursive versions of the various mapping commands. For example, if we run:

:map j gg           (moves cursor to first line)
:map Q j            (moves cursor to first line)
:noremap W j        (moves cursor down one line)

Then:

  • j will be mapped to gg.
  • Q will also be mapped to gg, because j will be expanded for the recursive mapping.
  • W will be mapped to j (and not to gg) because j will not be expanded for the non-recursive mapping.

Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.

For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map and :noremap), one that works in normal mode (:nmap and :nnoremap), one in visual mode (:vmap and :vnoremap) and so on.

For more guidance on this, see:

:help :map
:help :noremap
:help recursive_mapping
:help :map-modes

How can I avoid running ActiveRecord callbacks?

# for rails 3
  if !ActiveRecord::Base.private_method_defined? :update_without_callbacks
    def update_without_callbacks
      attributes_with_values = arel_attributes_values(false, false, attribute_names)
      return false if attributes_with_values.empty?
      self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).arel.update(attributes_with_values)
    end
  end

Extract a substring according to a pattern

Another method to extract a substring

library(stringr)
substring <- str_extract(string, regex("(?<=:).*"))
#[1] "E001" "E002" "E003
  • (?<=:): look behind the colon (:)

How do I append a node to an existing XML file in java

You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));

Element root = document.getDocumentElement();

for (Server newServer : Collection<Server> bunchOfNewServers){
  Element server = Document.createElement("server");
  /* create and setup the server node...*/

 root.appendChild(server);
}

/* use whatever method to output DOM to XML (for example, using transformer like you did).*/

How to connect to SQL Server from command prompt with Windows authentication

After some tries, these are the samples I am using in order to connect:

Specifying the username and the password:

sqlcmd -S 211.11.111.111 -U NotSA -P NotTheSaPassword

Specifying the DB as well:

sqlcmd -S 211.11.111.111 -d SomeSpecificDatabase -U NotSA -P NotTheSaPassword

Get the row(s) which have the max value in groups using groupby

Realizing that "applying" "nlargest" to groupby object works just as fine:

Additional advantage - also can fetch top n values if required:

In [85]: import pandas as pd

In [86]: df = pd.DataFrame({
    ...: 'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
    ...: 'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
    ...: 'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
    ...: 'count' : [3,2,5,8,10,1,2,2,7]
    ...: })

## Apply nlargest(1) to find the max val df, and nlargest(n) gives top n values for df:
In [87]: df.groupby(["sp", "mt"]).apply(lambda x: x.nlargest(1, "count")).reset_index(drop=True)
Out[87]:
   count  mt   sp  val
0      3  S1  MM1    a
1      5  S3  MM1   cb
2      8  S3  MM2   mk
3     10  S4  MM2   bg
4      7  S2  MM4  uyi

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

So upon finding that there could be a missing package in the buildpath, thus the red x against the main project, to remove this:

1) go into "Configure Buildpath" of project 2) Java Build Path -> Source Tab - you should see the red x against the missing package/file. if it no longer exists, just "remove" it.

red X begone! :)

How to get div height to auto-adjust to background size?

How about this :)

_x000D_
_x000D_
.fixed-centered-covers-entire-page{_x000D_
    margin:auto;_x000D_
    background-image: url('https://i.imgur.com/Ljd0YBi.jpg');_x000D_
    background-repeat: no-repeat;background-size:cover;_x000D_
    background-position: 50%;_x000D_
    background-color: #fff;_x000D_
    left:0;_x000D_
    right:0;_x000D_
    top:0;_x000D_
    bottom:0;_x000D_
    z-index:-1;_x000D_
    position:fixed;_x000D_
}
_x000D_
<div class="fixed-centered-covers-entire-page"></div>
_x000D_
_x000D_
_x000D_

Demo: http://jsfiddle.net/josephmcasey/KhPaF/

HTML Agility pack - parsing tables

How about something like: Using HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    Console.WriteLine("Found: " + table.Id);
    foreach (HtmlNode row in table.SelectNodes("tr")) {
        Console.WriteLine("row");
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            Console.WriteLine("cell: " + cell.InnerText);
        }
    }
}

Note that you can make it prettier with LINQ-to-Objects if you want:

var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
            from row in table.SelectNodes("tr").Cast<HtmlNode>()
            from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
            select new {Table = table.Id, CellText = cell.InnerText};

foreach(var cell in query) {
    Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}

Removing a non empty directory programmatically in C or C++

Many unix-like systems (Linux, the BSDs, and OS X, at the very least) have the fts functions for directory traversal.

To recursively delete a directory, perform a depth-first traversal (without following symlinks) and remove every visited file:

int recursive_delete(const char *dir)
{
    int ret = 0;
    FTS *ftsp = NULL;
    FTSENT *curr;

    // Cast needed (in C) because fts_open() takes a "char * const *", instead
    // of a "const char * const *", which is only allowed in C++. fts_open()
    // does not modify the argument.
    char *files[] = { (char *) dir, NULL };

    // FTS_NOCHDIR  - Avoid changing cwd, which could cause unexpected behavior
    //                in multithreaded programs
    // FTS_PHYSICAL - Don't follow symlinks. Prevents deletion of files outside
    //                of the specified directory
    // FTS_XDEV     - Don't cross filesystem boundaries
    ftsp = fts_open(files, FTS_NOCHDIR | FTS_PHYSICAL | FTS_XDEV, NULL);
    if (!ftsp) {
        fprintf(stderr, "%s: fts_open failed: %s\n", dir, strerror(errno));
        ret = -1;
        goto finish;
    }

    while ((curr = fts_read(ftsp))) {
        switch (curr->fts_info) {
        case FTS_NS:
        case FTS_DNR:
        case FTS_ERR:
            fprintf(stderr, "%s: fts_read error: %s\n",
                    curr->fts_accpath, strerror(curr->fts_errno));
            break;

        case FTS_DC:
        case FTS_DOT:
        case FTS_NSOK:
            // Not reached unless FTS_LOGICAL, FTS_SEEDOT, or FTS_NOSTAT were
            // passed to fts_open()
            break;

        case FTS_D:
            // Do nothing. Need depth-first search, so directories are deleted
            // in FTS_DP
            break;

        case FTS_DP:
        case FTS_F:
        case FTS_SL:
        case FTS_SLNONE:
        case FTS_DEFAULT:
            if (remove(curr->fts_accpath) < 0) {
                fprintf(stderr, "%s: Failed to remove: %s\n",
                        curr->fts_path, strerror(curr->fts_errno));
                ret = -1;
            }
            break;
        }
    }

finish:
    if (ftsp) {
        fts_close(ftsp);
    }

    return ret;
}

How to change max_allowed_packet size

Set the max allowed packet size using MySql Workbench and restart the serverMysql Workbench

Partly cherry-picking a commit with Git

Assuming the changes you want are at the head of the branch you want the changes from, use git checkout

for a single file :

git checkout branch_that_has_the_changes_you_want path/to/file.rb

for multiple files just daisy chain :

git checkout branch_that_has_the_changes_you_want path/to/file.rb path/to/other_file.rb

difference between variables inside and outside of __init__()

class foo(object):
    mStatic = 12

    def __init__(self):
        self.x = "OBj"

Considering that foo has no access to x at all (FACT)

the conflict now is in accessing mStatic by an instance or directly by the class .

think of it in the terms of Python's memory management :

12 value is on the memory and the name mStatic (which accessible from the class)

points to it .

c1, c2 = foo(), foo() 

this line makes two instances , which includes the name mStatic that points to the value 12 (till now) .

foo.mStatic = 99 

this makes mStatic name pointing to a new place in the memory which has the value 99 inside it .

and because the (babies) c1 , c2 are still following (daddy) foo , they has the same name (c1.mStatic & c2.mStatic ) pointing to the same new value .

but once each baby decides to walk alone , things differs :

c1.mStatic ="c1 Control"
c2.mStatic ="c2 Control"

from now and later , each one in that family (c1,c2,foo) has its mStatica pointing to different value .

[Please, try use id() function for all of(c1,c2,foo) in different sates that we talked about , i think it will make things better ]

and this is how our real life goes . sons inherit some beliefs from their father and these beliefs still identical to father's ones until sons decide to change it .

HOPE IT WILL HELP

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

I ran into this in a Web App on Azure when attempting to connect to Blob Storage. The problem turned out to be that I had missed deploying a connection string for the blob storage so it was still pointing at the storage emulator. There must be some retry logic built into the client because I saw about 3 attempts. The /devstorageaccount1 here is a dead giveaway.

enter image description here

Fixed by properly setting the connection string in Azure.

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

  • try to do the Telnet to see any firewall issue
  • perform tracert/traceroute to find number of hops

Use Expect in a Bash script to provide a password to an SSH command

Another way that I found useful to use a small Expect script from a Bash script is as follows.

...
Bash script start
Bash commands
...
expect - <<EOF
spawn your-command-here
expect "some-pattern"
send "some-command"
...
...
EOF
...
More Bash commands
...

This works because ...If the string "-" is supplied as a filename, standard input is read instead...

link button property to open in new tab?

From the docs:

Use the LinkButton control to create a hyperlink-style button on the Web page. The LinkButton control has the same appearance as a HyperLink control, but has the same functionality as a Button control. If you want to link to another Web page when the control is clicked, consider using the HyperLink control.

As this isn't actually performing a link in the standard sense, there's no Target property on the control (the HyperLink control does have a Target) - it's attempting to perform a PostBack to the server from a text link.

Depending on what you are trying to do you could either:

  1. Use a HyperLink control, and set the Target property
  2. Provide a method to the OnClientClick property that opens a new window to the correct place.
  3. In your code that handles the PostBack add some JavaScript to fire on PageLoad that will open a new window correct place.

PL/SQL block problem: No data found error

When you are selecting INTO a variable and there are no records returned you should get a NO DATA FOUND error. I believe the correct way to write the above code would be to wrap the SELECT statement with it's own BEGIN/EXCEPTION/END block. Example:

...
v_final_grade NUMBER;
v_letter_grade CHAR(1);
BEGIN

    BEGIN
    SELECT final_grade
      INTO v_final_grade
      FROM enrollment
     WHERE student_id = v_student_id
       AND section_id = v_section_id;

    EXCEPTION
      WHEN NO_DATA_FOUND THEN
        v_final_grade := NULL;
    END;

    CASE -- outer CASE
      WHEN v_final_grade IS NULL THEN
      ...

A non-blocking read on a subprocess.PIPE in Python

Use select & read(1).

import subprocess     #no new requirements
def readAllSoFar(proc, retVal=''): 
  while (select.select([proc.stdout],[],[],0)[0]!=[]):   
    retVal+=proc.stdout.read(1)
  return retVal
p = subprocess.Popen(['/bin/ls'], stdout=subprocess.PIPE)
while not p.poll():
  print (readAllSoFar(p))

For readline()-like:

lines = ['']
while not p.poll():
  lines = readAllSoFar(p, lines[-1]).split('\n')
  for a in range(len(lines)-1):
    print a
lines = readAllSoFar(p, lines[-1]).split('\n')
for a in range(len(lines)-1):
  print a

Descending order by date filter in AngularJs

see w3schools samples: https://www.w3schools.com/angular/angular_filters.asp https://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_orderby_click

then add the "reverse" flag:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<p>Click the table headers to change the sorting order:</p>

<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:reverse">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Carl',country:'Sweden'},
        {name:'Margareth',country:'England'},
        {name:'Hege',country:'Norway'},
        {name:'Joe',country:'Denmark'},
        {name:'Gustav',country:'Sweden'},
        {name:'Birgit',country:'Denmark'},
        {name:'Mary',country:'England'},
        {name:'Kai',country:'Norway'}
        ];

    $scope.reverse=false;
    $scope.orderByMe = function(x) {

        if($scope.myOrderBy == x) {
            $scope.reverse=!$scope.reverse;
        }
        $scope.myOrderBy = x;
    }
});
</script>

</body>
</html>

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

if it is standalone program, download mysql connector jar and add it to your classpath.

if it is a maven project, add below dependency and run your program.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>

Calculate last day of month in JavaScript

I recently had to do something similar, this is what I came up with:

/**
* Returns a date set to the begining of the month
* 
* @param {Date} myDate 
* @returns {Date}
*/
function beginningOfMonth(myDate){    
  let date = new Date(myDate);
  date.setDate(1)
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);   
  return date;     
}

/**
 * Returns a date set to the end of the month
 * 
 * @param {Date} myDate 
 * @returns {Date}
 */
function endOfMonth(myDate){
  let date = new Date(myDate);
  date.setMonth(date.getMonth() +1)
  date.setDate(0);
  date.setHours(23);
  date.setMinutes(59);
  date.setSeconds(59);
  return date;
}

Pass it in a date, and it will return a date set to either the beginning of the month, or the end of the month.

The begninngOfMonth function is fairly self-explanatory, but what's going in in the endOfMonth function is that I'm incrementing the month to the next month, and then using setDate(0) to roll back the day to the last day of the previous month which is a part of the setDate spec:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate https://www.w3schools.com/jsref/jsref_setdate.asp

I then set the hour/minutes/seconds to the end of the day, so that if you're using some kind of API that is expecting a date range you'll be able to capture the entirety of that last day. That part might go beyond what the original post is asking for but it could help someone else looking for a similar solution.

Edit: You can also go the extra mile and set milliseconds with setMilliseconds() if you want to be extra precise.

How can I get the MAC and the IP address of a connected client in PHP?

In windows, If the user is using your script locally, it will be very simple :

<?php
// get all the informations about the client's network
 $ipconfig =   shell_exec ("ipconfig/all"));  
 // display those informations   
 echo $ipconfig;
/*  
  look for the value of "physical adress"  and use substr() function to 
  retrieve the adress from this long string.
  here in my case i'm using a french cmd.
  you can change the numbers according adress mac position in the string.
*/
 echo   substr(shell_exec ("ipconfig/all"),1821,18); 
?>

Cannot run Eclipse; JVM terminated. Exit code=13

simply install 64 bit version of JAVA from http://java.com/en/download/manual.jsp

and uninstall older version if prompted by the 64 bit installer

Using AND/OR in if else PHP statement

AND and OR are just syntactic sugar for && and ||, like in JavaScript, or other C styled syntax languages.

It appears AND and OR have lower precedence than their C style equivalents.

What's the key difference between HTML 4 and HTML 5?

You'll want to check HTML5 Differences from HTML4: W3C Working Group Note 9 December 2014 for the complete differences. There are many new elements and element attributes. Some elements were removed and others have different semantic value than before.

There are also APIs defined, such as the use of canvas, to help build the next generation of web apps and make sure implementations are standardized.

rand() between 0 and 1

In my case (I'm using VS 2017) works fine the following simple code:

#include "pch.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

int main()
{
    srand(time(NULL));

    for (int i = 1000; i > 0; i--) //try it thousand times
    {
        int randnum = (double)rand() / ((double)RAND_MAX + 1);
        std::cout << " rnum: " << rand()%2 ;
    }
} 

Ternary operators in JavaScript without an "else"

You could write

x = condition ? true : x;

So that x is unmodified when the condition is false.

This then is equivalent to

if (condition) x = true

EDIT:

!defaults.slideshowWidth 
      ? defaults.slideshowWidth = obj.find('img').width()+'px' 
      : null 

There are a couple of alternatives - I'm not saying these are better/worse - merely alternatives

Passing in null as the third parameter works because the existing value is null. If you refactor and change the condition, then there is a danger that this is no longer true. Passing in the exising value as the 2nd choice in the ternary guards against this:

!defaults.slideshowWidth = 
      ? defaults.slideshowWidth = obj.find('img').width()+'px' 
      : defaults.slideshowwidth 

Safer, but perhaps not as nice to look at, and more typing. In practice, I'd probably write

defaults.slideshowWidth = defaults.slideshowWidth 
               || obj.find('img').width()+'px'

How to parse XML using vba

Often it is easier to parse without VBA, when you don't want to enable macros. This can be done with the replace function. Enter your start and end nodes into cells B1 and C1.

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: =REPLACE(A1,1,FIND(A2,A1)+LEN(A2)-1,"")
Cell E1: =REPLACE(A4,FIND(A3,A4),LEN(A4)-FIND(A3,A4)+1,"")

And the result line E1 will have your parsed value:

Cell A1: {your XML here}
Cell B1: <X>
Cell C1: </X>
Cell D1: 24.365<X><Y>78.68</Y></PointN>
Cell E1: 24.365

MySQL case sensitive query

To improve James' excellent answer:

It's better to put BINARY in front of the constant instead:

SELECT * FROM `table` WHERE `column` = BINARY 'value'

Putting BINARY in front of column will prevent the use of any index on that column.