Programs & Examples On #Instance variables

In object-oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each object of the class has a separate copy.

What is an instance variable in Java?

Instance variable is the variable declared inside a class, but outside a method: something like:

class IronMan {

    /** These are all instance variables **/
    public String realName;
    public String[] superPowers;
    public int age;

    /** Getters and setters here **/
}

Now this IronMan Class can be instantiated in another class to use these variables. Something like:

class Avengers {

    public static void main(String[] a) {
        IronMan ironman = new IronMan();
        ironman.realName = "Tony Stark";
        // or
        ironman.setAge(30);
    }

}

This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.

What does @@variable mean in Ruby?

@@ denotes a class variable, i.e. it can be inherited.

This means that if you create a subclass of that class, it will inherit the variable. So if you have a class Vehicle with the class variable @@number_of_wheels then if you create a class Car < Vehicle then it too will have the class variable @@number_of_wheels

How do servlets work? Instantiation, sessions, shared variables and multithreading

As is clear from above explanations, by implementing the SingleThreadModel, a servlet can be assured thread-safety by the servlet container. The container implementation can do this in 2 ways:

1) Serializing requests (queuing) to a single instance - this is similar to a servlet NOT implementing SingleThreadModel BUT synchronizing the service/ doXXX methods; OR

2) Creating a pool of instances - which's a better option and a trade-off between the boot-up/initialization effort/time of the servlet as against the restrictive parameters (memory/ CPU time) of the environment hosting the servlet.

Ruby class instance variable vs. class variable

I believe the main (only?) different is inheritance:

class T < S
end

p T.k
=> 23

S.k = 24
p T.k
=> 24

p T.s
=> nil

Class variables are shared by all "class instances" (i.e. subclasses), whereas class instance variables are specific to only that class. But if you never intend to extend your class, the difference is purely academic.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

Ruby convert Object to Hash

Recursively convert your objects to hash using 'hashable' gem (https://rubygems.org/gems/hashable) Example

class A
  include Hashable
  attr_accessor :blist
  def initialize
    @blist = [ B.new(1), { 'b' => B.new(2) } ]
  end
end

class B
  include Hashable
  attr_accessor :id
  def initialize(id); @id = id; end
end

a = A.new
a.to_dh # or a.to_deep_hash
# {:blist=>[{:id=>1}, {"b"=>{:id=>2}}]}

How to get instance variables in Python?

Sometimes you want to filter the list based on public/private vars. E.g.

def pub_vars(self):
    """Gives the variable names of our instance we want to expose
    """
    return [k for k in vars(self) if not k.startswith('_')]

Combining CSS Pseudo-elements, ":after" the ":last-child"

Just To mention, in CSS 3

:after

should be used like this

::after

From https://developer.mozilla.org/de/docs/Web/CSS/::after :

The ::after notation was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :after introduced in CSS 2.

So it should be:

li { display: inline; list-style-type: none; }
li::after { content: ", "; }
li:last-child::before { content: "and "; }
li:last-child::after { content: "."; }

Redirect output of mongo query to a csv file

I use the following technique. It makes it easy to keep the column names in sync with the content:

var cursor = db.getCollection('Employees.Details').find({})

var header = []
var rows = []

var firstRow = true
cursor.forEach((doc) => 
{
    var cells = []
    
    if (firstRow) header.push("employee_number")
    cells.push(doc.EmpNum.valueOf())

    if (firstRow) header.push("name")
    cells.push(doc.FullName.valueOf())    

    if (firstRow) header.push("dob")
    cells.push(doc.DateOfBirth.valueOf())   
    
    row = cells.join(',')
    rows.push(row)    

    firstRow =  false
})

print(header.join(','))
print(rows.join('\n'))

Memory address of variables in Java

That is the output of Object's "toString()" implementation. If your class overrides toString(), it will print something entirely different.

Best practice multi language website

It depends on how much content your website has. At first I used a database like all other people here, but it can be time-consuming to script all the workings of a database. I don't say that this is an ideal method and especially if you have a lot of text, but if you want to do it fast without using a database, this method could work, though, you can't allow users to input data which will be used as translation-files. But if you add the translations yourself, it will work:

Let's say you have this text:

Welcome!

You can input this in a database with translations, but you can also do this:

$welcome = array(
"English"=>"Welcome!",
"German"=>"Willkommen!",
"French"=>"Bienvenue!",
"Turkish"=>"Hosgeldiniz!",
"Russian"=>"????? ??????????!",
"Dutch"=>"Welkom!",
"Swedish"=>"Välkommen!",
"Basque"=>"Ongietorri!",
"Spanish"=>"Bienvenito!"
"Welsh"=>"Croeso!");

Now, if your website uses a cookie, you have this for example:

$_COOKIE['language'];

To make it easy let's transform it in a code which can easily be used:

$language=$_COOKIE['language'];

If your cookie language is Welsh and you have this piece of code:

echo $welcome[$language];

The result of this will be:

Croeso!

If you need to add a lot of translations for your website and a database is too consuming, using an array can be an ideal solution.

How do I get the opposite (negation) of a Boolean in Python?

The accepted answer here is the most correct for the given scenario.

It made me wonder though about simply inverting a boolean value in general. It turns out the accepted solution here works as one liner, and there's another one-liner that works as well. Assuming you have a variable "n" that you know is a boolean, the easiest ways to invert it are:

n = n is False

which was my original solution, and then the accepted answer from this question:

n = not n

The latter IS more clear, but I wondered about performance and hucked it through timeit - and it turns out at n = not n is also the FASTER way to invert the boolean value.

How to call multiple JavaScript functions in onclick event?

ES6 React

<MenuItem
  onClick={() => {
    this.props.toggleTheme();
    this.handleMenuClose();
  }}
>

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

Just change your default port 8080 to something else like below example

SQL> begin
 2   dbms_xdb.sethttpport('9090');
 3   end;
 4  /

How to use ng-repeat without an html element

<table>
  <tbody>
    <tr><td>{{data[0].foo}}</td></tr>
    <tr ng-repeat="d in data[1]"><td>{{d.bar}}</td></tr>
    <tr ng-repeat="d in data[2]"><td>{{d.lol}}</td></tr>
  </tbody>
</table>

I think that this is valid :)

How to find out whether a file is at its `eof`?

fp.read() reads up to the end of the file, so after it's successfully finished you know the file is at EOF; there's no need to check. If it cannot reach EOF it will raise an exception.

When reading a file in chunks rather than with read(), you know you've hit EOF when read returns less than the number of bytes you requested. In that case, the following read call will return the empty string (not None). The following loop reads a file in chunks; it will call read at most once too many.

assert n > 0
while True:
    chunk = fp.read(n)
    if chunk == '':
        break
    process(chunk)

Or, shorter:

for chunk in iter(lambda: fp.read(n), ''):
    process(chunk)

Adding Only Untracked Files

To add all untracked files git command is

git add -A

Also if you want to get more details about various available options , you can type command

git add -i

instead of first command , with this you will get more options including option to add all untracked files as shown below :

$ git add -i warning: LF will be replaced by CRLF in README.txt. The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF in package.json.

* Commands * 1: status 2: update 3: revert 4: add untracked 5: patch 6: diff 7: quit 8: help What now> a

Disabling user input for UITextfield in swift

I like to do it like old times. You just use a custom UITextField Class like this one:

//
//  ReadOnlyTextField.swift
//  MediFormulas
//
//  Created by Oscar Rodriguez on 6/21/17.
//  Copyright © 2017 Nica Code. All rights reserved.
//

import UIKit

class ReadOnlyTextField: UITextField {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override init(frame: CGRect) {
        super.init(frame: frame)

        // Avoid keyboard to show up
        self.inputView = UIView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // Avoid keyboard to show up
        self.inputView = UIView()
    }

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // Avoid cut and paste option show up
        if (action == #selector(self.cut(_:))) {
            return false
        } else if (action == #selector(self.paste(_:))) {
            return false
        }

        return super.canPerformAction(action, withSender: sender)
    }

}

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Was able to fix the issue by updating NVIDIA device drivers to the latest (v446.14). NVIDIA drivers download link here.

Vue.js img src concatenate variable and text

if you handel this from dataBase try :

<img :src="baseUrl + 'path/path' + obj.key +'.png'">

Load a bitmap image into Windows Forms using open file dialog

It's simple. Just add:

PictureBox1.BackgroundImageLayout = ImageLayout.Zoom;

VBA Excel - Insert row below with same format including borders and frames

well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)

lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents

(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )

(grep) Regex to match non-ASCII characters?

This will match a single non-ASCII character:

[^\x00-\x7F]

This is a valid PCRE (Perl-Compatible Regular Expression).

You can also use the POSIX shorthands:

  • [[:ascii:]] - matches a single ASCII char
  • [^[:ascii:]] - matches a single non-ASCII char

[^[:print:]] will probably suffice for you.**

Remove the legend on a matplotlib figure

You could use the legend's set_visible method:

ax.legend().set_visible(False)
draw()

This is based on a answer provided to me in response to a similar question I had some time ago here

(Thanks for that answer Jouni - I'm sorry I was unable to mark the question as answered... perhaps someone who has the authority can do so for me?)

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

How to close form

Your closing your instance of the settings window right after you create it. You need to display the settings window first then wait for a dialog result. If it comes back as canceled then close the window. For Example:

private void button1_Click(object sender, EventArgs e)
{
    Settings newSettingsWindow = new Settings();

    if (newSettingsWindow.ShowDialog() == DialogResult.Cancel)
    {
        newSettingsWindow.Close();
    }
}

Remove a symlink to a directory

I had this problem with MinGW (actually Git Bash) running on a Windows Server. None of the above suggestions seemed to work. In the end a made a copy of the directory in case then deleted the soft link in Windows Explorer then deleted the item in the Recycle Bin. It made noises like it was deleting the files but didn't. Do make a backup though!

Format the date using Ruby on Rails

First you will need to convert the timestamp to an actual Ruby Date/Time. If you receive it just as a string or int from facebook, you will need to do something like this:

my_date = Time.at(timestamp_from_facebook.to_i)

Then to format it nicely in the view, you can just use to_s (for the default formatting):

<%= my_date.to_s %>

Note that if you don't put to_s, it will still be called by default if you use it in a view or in a string e.g. the following will also call to_s on the date:

<%= "Here is a date: #{my_date}" %>

or if you want the date formatted in a specific way (eg using "d/m/Y") - you can use strftime as outlined in the other answer.

Spring Boot how to hide passwords in properties file

To the already proposed solutions I can add an option to configure an external Secrets Manager such as Vault.

  1. Configure Vault Server vault server -dev (Only for DEV and not for PROD)
  2. Write secrets vault write secret/somename key1=value1 key2=value2
  3. Verify secrets vault read secret/somename

Add the following dependency to your SpringBoot project:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-vault-config</artifactId>
</dependency>

Add Vault config properties:

spring.cloud.vault.host=localhost
spring.cloud.vault.port=8200
spring.cloud.vault.scheme=http
spring.cloud.vault.authentication=token
spring.cloud.vault.token=${VAULT_TOKEN}

Pass VAULT_TOKEN as an environment variable.

Refer to the documentation here.

There is a Spring Vault project which is also can be used for accessing, storing and revoking secrets.

Dependency:

<dependency>
    <groupId>org.springframework.vault</groupId>
    <artifactId>spring-vault-core</artifactId>
</dependency>

Configuring Vault Template:

@Configuration
class VaultConfiguration extends AbstractVaultConfiguration {

  @Override
  public VaultEndpoint vaultEndpoint() {
    return new VaultEndpoint();
  }

  @Override
  public ClientAuthentication clientAuthentication() {
    return new TokenAuthentication("…");
  }
}

Inject and use VaultTemplate:

public class Example {

  @Autowired
  private VaultOperations operations;

  public void writeSecrets(String userId, String password) {
      Map<String, String> data = new HashMap<String, String>();
      data.put("password", password);
      operations.write(userId, data);
  }

  public Person readSecrets(String userId) {
      VaultResponseSupport<Person> response = operations.read(userId, Person.class);
      return response.getBody();
  }
}

Use Vault PropertySource:

@VaultPropertySource(value = "aws/creds/s3",
  propertyNamePrefix = "aws."
  renewal = Renewal.RENEW)
public class Config {

}

Usage example:

public class S3Client {

  // inject the actual values
  @Value("${aws.access_key}")
  private String awsAccessKey;
  @Value("${aws.secret_key}")
  private String awsSecretKey;

  public InputStream getFileFromS3(String filenname) {
    // …
  }
}

Alternative to google finance api

Updating answer a bit

1. Try Twelve Data API

For beginners try to run the following query with a JSON response:

https://api.twelvedata.com/time_series?symbol=AAPL&interval=1min&apikey=demo&source=docs

NO more real time Alpha Vantage API

For beginners you can try to get a JSON output from query such as

https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo

DON'T Try Yahoo Finance API (it is DEPRECATED or UNAVAILABLE NOW).

For beginners, you can generate a CSV with a simple API call:

http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=sb2b3jk

(This will generate and save a CSV for AAPL, GOOG, and MSFT)

Note that you must append the format to the query string (f=..). For an overview of all of the formats see this page.

For more examples, visit this page.

For XML and JSON-based data, you can do the following:

Don't use YQL (Yahoo Query Language)

For example:

http://developer.yahoo.com/yql/console/?q=select%20*%20from%20yahoo.finance
.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22
MSFT%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env

2. Use the webservice

For example, to get all stock quotes in XML:

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote

To get all stock quotes in JSON, just add format=JSON to the end of the URL:

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json

Alternatives:

  1. Currency API

    • 165+ real time currency rates, including few cryptos. Docs here.
  2. Financial Content API

  3. IEX

  4. Open Exchange Rates

  5. Polygon

  6. XE API

  7. Xignite API

  8. currencylayer API

  9. Other APIs - discussed at programmableWeb

Can you autoplay HTML5 videos on the iPad?

As of iOS 10, videos now can autoplay, but only of they are either muted, or have no audio track. Yay!

In short:

  • <video autoplay> elements will now honor the autoplay attribute, for elements which meet the following conditions:
    • <video> elements will be allowed to autoplay without a user gesture if their source media contains no audio tracks.
    • <video muted> elements will also be allowed to autoplay without a user gesture.
    • If a <video> element gains an audio track or becomes un-muted without a user gesture, playback will pause.
    • <video autoplay> elements will only begin playing when visible on-screen such as when they are scrolled into the viewport, made visible through CSS, and inserted into the DOM.
    • <video autoplay> elements will pause if they become non-visible, such as by being scrolled out of the viewport.

More info here: https://webkit.org/blog/6784/new-video-policies-for-ios/

Set angular scope variable in markup

You can set values from html like this. I don't think there is a direct solution from angular yet.

 <div style="visibility: hidden;">{{activeTitle='home'}}</div>

Class constants in python

You can get to SIZES by means of self.SIZES (in an instance method) or cls.SIZES (in a class method).

In any case, you will have to be explicit about where to find SIZES. An alternative is to put SIZES in the module containing the classes, but then you need to define all classes in a single module.

How to trigger event when a variable's value is changed?

You can use a property setter to raise an event whenever the value of a field is going to change.

You can have your own EventHandler delegate or you can use the famous System.EventHandler delegate.

Usually there's a pattern for this:

  1. Define a public event with an event handler delegate (that has an argument of type EventArgs).
  2. Define a protected virtual method called OnXXXXX (OnMyPropertyValueChanged for example). In this method you should check if the event handler delegate is null and if not you can call it (it means that there are one or more methods attached to the event delegation).
  3. Call this protected method whenever you want to notify subscribers that something has changed.

Here's an example

private int _age;

//#1
public event System.EventHandler AgeChanged;

//#2
protected virtual void OnAgeChanged()
{ 
     if (AgeChanged != null) AgeChanged(this,EventArgs.Empty); 
}

public int Age
{
    get
    {
         return _age;
    }

    set
    {
         //#3
         _age=value;
         OnAgeChanged();
    }
 }

The advantage of this approach is that you let any other classes that want to inherit from your class to change the behavior if necessary.

If you want to catch an event in a different thread that it's being raised you must be careful not to change the state of objects that are defined in another thread which will cause a cross thread exception to be thrown. To avoid this you can either use an Invoke method on the object that you want to change its state to make sure that the change is happening in the same thread that the event has been raised or in case that you are dealing with a Windows Form you can use a BackgourndWorker to do things in a parallel thread nice and easy.

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Seeing from your G++ version, you need to update it badly. C++11 has only been available since G++ 4.3. The most recent version is 4.7.

In versions pre-G++ 4.7, you'll have to use -std=c++0x, for more recent versions you can use -std=c++11.

list.clear() vs list = new ArrayList<Integer>();

I would suggest using list.clear() rather than allocating a new object. When you call the "new" keyword, you are creating more space in memory. In reality, it doesn't matter much. I suppose that if you know how large the list will be, it might be a good idea to create a new space but then specify how large the array will be.

The truth is, it's not going to matter unless you're doing scientific programming. In that case, you need to go learn C++.

Illegal Escape Character "\"

The character '\' is a special character and needs to be escaped when used as part of a String, e.g., "\". Here is an example of a string comparison using the '\' character:

if (invName.substring(j,k).equals("\\")) {...}

You can also perform direct character comparisons using logic similar to the following:

if (invName.charAt(j) == '\\') {...}

How to print an unsigned char in C?

This is because in this case the char type is signed on your system*. When this happens, the data gets sign-extended during the default conversions while passing the data to the function with variable number of arguments. Since 212 is greater than 0x80, it's treated as negative, %u interprets the number as a large positive number:

212 = 0xD4

When it is sign-extended, FFs are pre-pended to your number, so it becomes

0xFFFFFFD4 = 4294967252

which is the number that gets printed.

Note that this behavior is specific to your implementation. According to C99 specification, all char types are promoted to (signed) int, because an int can represent all values of a char, signed or unsigned:

6.1.1.2: If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int.

This results in passing an int to a format specifier %u, which expects an unsigned int.

To avoid undefined behavior in your program, add explicit type casts as follows:

unsigned char ch = (unsigned char)212;
printf("%u", (unsigned int)ch);


* In general, the standard leaves the signedness of char up to the implementation. See this question for more details.

Call PHP function from jQuery?

This is exactly what ajax is for. See here:

http://api.jquery.com/load/

Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.

$('#result').load('ajax/test.php');

Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).

How to check for file lock?

Here's a variation of DixonD's code that adds number of seconds to wait for file to unlock, and try again:

public bool IsFileLocked(string filePath, int secondsToWait)
{
    bool isLocked = true;
    int i = 0;

    while (isLocked &&  ((i < secondsToWait) || (secondsToWait == 0)))
    {
        try
        {
            using (File.Open(filePath, FileMode.Open)) { }
            return false;
        }
        catch (IOException e)
        {
            var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
            isLocked = errorCode == 32 || errorCode == 33;
            i++;

            if (secondsToWait !=0)
                new System.Threading.ManualResetEvent(false).WaitOne(1000);
        }
    }

    return isLocked;
}


if (!IsFileLocked(file, 10))
{
    ...
}
else
{
    throw new Exception(...);
}

Batch / Find And Edit Lines in TXT file

ghostdog74's example provided the core of what I needed, since I've never written any vbs before and needed to do that. It's not perfect, but I fleshed out the example into a full script in case anyone finds it useful.

'ReplaceText.vbs

Option Explicit

Const ForAppending = 8
Const TristateFalse = 0 ' the value for ASCII
Const Overwrite = True

Const WindowsFolder = 0
Const SystemFolder = 1
Const TemporaryFolder = 2

Dim FileSystem
Dim Filename, OldText, NewText
Dim OriginalFile, TempFile, Line
Dim TempFilename

If WScript.Arguments.Count = 3 Then
    Filename = WScript.Arguments.Item(0)
    OldText = WScript.Arguments.Item(1)
    NewText = WScript.Arguments.Item(2)
Else
    Wscript.Echo "Usage: ReplaceText.vbs <Filename> <OldText> <NewText>"
    Wscript.Quit
End If

Set FileSystem = CreateObject("Scripting.FileSystemObject")
Dim tempFolder: tempFolder = FileSystem.GetSpecialFolder(TemporaryFolder)
TempFilename = FileSystem.GetTempName

If FileSystem.FileExists(TempFilename) Then
    FileSystem.DeleteFile TempFilename
End If

Set TempFile = FileSystem.CreateTextFile(TempFilename, Overwrite, TristateFalse)
Set OriginalFile = FileSystem.OpenTextFile(Filename)

Do Until OriginalFile.AtEndOfStream
    Line = OriginalFile.ReadLine

    If InStr(Line, OldText) > 0 Then
        Line = Replace(Line, OldText, NewText)
    End If 

    TempFile.WriteLine(Line)
Loop

OriginalFile.Close
TempFile.Close

FileSystem.DeleteFile Filename
FileSystem.MoveFile TempFilename, Filename

Wscript.Quit

Install apps silently, with granted INSTALL_PACKAGES permission

you can use this in terminal or shell

adb shell install -g MyApp.apk

see more in develope google

Java - Getting Data from MySQL database

Here is what I just did right now:

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sun.javafx.runtime.VersionInfo;  

public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();

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



public static void getData () {

    try {
        Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage", 
 "root", "root");
        
 // here mynewpage is database name, root is username and password
    
Statement stmt = con.createStatement();
        System.out.println("stmt  " + stmt);
        ResultSet rs = stmt.executeQuery("select * from carsData");
        System.out.println("rs  " + rs);
        int count = 1;
        while (rs.next()) {
            String vehicleType = rs.getString("VHCL_TYPE");
            System.out.println(count  +": " + vehicleType);
            count++;

        }

        con.close();
    } catch (Exception e) {
        Logger lgr = Logger.getLogger(VersionInfo.class.getName());
        lgr.log(Level.SEVERE, e.getMessage(), e);

        System.out.println(e.getMessage());
    }
    
    
}

}

The Above code will get you the first column of the table you have.

This is the table which you might need to create in your MySQL database

CREATE TABLE
carsData
(
    VHCL_TYPE CHARACTER(10) NOT NULL,
);

How to run mvim (MacVim) from Terminal?

This works for me:

? brew link --overwrite macvim
Linking /usr/local/Cellar/macvim/8.0-146_1... 12 symlinks created

Get exit code of a background process

A simple example, similar to the solutions above. This doesn't require monitoring any process output. The next example uses tail to follow output.

$ echo '#!/bin/bash' > tmp.sh
$ echo 'sleep 30; exit 5' >> tmp.sh
$ chmod +x tmp.sh
$ ./tmp.sh &
[1] 7454
$ pid=$!
$ wait $pid
[1]+  Exit 5                  ./tmp.sh
$ echo $?
5

Use tail to follow process output and quit when the process is complete.

$ echo '#!/bin/bash' > tmp.sh
$ echo 'i=0; while let "$i < 10"; do sleep 5; echo "$i"; let i=$i+1; done; exit 5;' >> tmp.sh
$ chmod +x tmp.sh
$ ./tmp.sh
0
1
2
^C
$ ./tmp.sh > /tmp/tmp.log 2>&1 &
[1] 7673
$ pid=$!
$ tail -f --pid $pid /tmp/tmp.log
0
1
2
3
4
5
6
7
8
9
[1]+  Exit 5                  ./tmp.sh > /tmp/tmp.log 2>&1
$ wait $pid
$ echo $?
5

Where does Android emulator store SQLite database?

Simple Solution - works for both Emulator & Connected Devices

1 See the list of devices/emulators currently available.

$ adb devices

List of devices attached

G7NZCJ015313309 device emulator-5554 device

9885b6454e46383744 device

2 Run backup on your device/emulator

$ adb -s emulator-5554 backup -f ~/Desktop/data.ab -noapk com.your_app_package.app;

3 Extract data.ab

$ dd if=data.ab bs=1 skip=24 | openssl zlib -d | tar -xvf -;

You will find the database in /db folder

Reading a List from properties file and load with spring annotation @Value

In my case of a list of integers works this:

@Value("#{${my.list.of.integers}}")
private List<Integer> listOfIntegers;

Property file:

my.list.of.integers={100,200,300,400,999}

Pythonic way to combine FOR loop and IF statement

The following is a simplification/one liner from the accepted answer:

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]

for x in (x for x in xyz if x not in a):
    print(x)

12
242

Notice that the generator was kept inline. This was tested on python2.7 and python3.6 (notice the parens in the print ;) )

Where can I get a list of Ansible pre-defined variables?

Note the official docs on connection configuration variables or "behavioral" variables - which aren't listed in host vars, appears to be List of Behavioral Inventory Parameters in the Inventory documentation.

P.S. The sudo option is undocumented there (yes its sudo not ansible_sudo as you'd expect ...) and probably a couple more aren't, but thats best doc I've found on em.

How to get english language word database?

You may check *spell en-GB dictionary used by Mozilla, OpenOffice, plenty of other software.

Difference between Activity Context and Application Context

I think when everything need a screen to show ( button, dialog,layout...) we have to use context activity, and everything doesn't need a screen to show or process ( toast, service telelphone,contact...) we could use a application context

Run C++ in command prompt - Windows

Open cmd and go In Directory where file is saved. Then, For compile, g++ FileName. cpp Or gcc FileName. cpp

For Run, FileName. exe

This Is For Compile & Run Program.

Make sure, gcc compiler installed in PC or Laptop. And also path variable must be set.

Python logging not outputting anything

For anyone here that wants a super-simple answer: just set the level you want displayed. At the top of all my scripts I just put:

import logging
logging.basicConfig(level = logging.INFO)

Then to display anything at or above that level:

logging.info("Hi you just set your fleeb to level plumbus")

It is a hierarchical set of five levels so that logs will display at the level you set, or higher. So if you want to display an error you could use logging.error("The plumbus is broken").

The levels, in increasing order of severity, are DEBUG, INFO, WARNING, ERROR, and CRITICAL. The default setting is WARNING.

This is a good article containing this information expressed better than my answer:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3

getResourceAsStream returns null

Don't know if of help, but in my case I had my resource in the /src/ folder and was getting this error. I then moved the picture to the bin folder and it fixed the issue.

Warning: The method assertEquals from the type Assert is deprecated

When I use Junit4, import junit.framework.Assert; import junit.framework.TestCase; the warning info is :The type of Assert is deprecated

when import like this: import org.junit.Assert; import org.junit.Test; the warning has disappeared

possible duplicate of differences between 2 JUnit Assert classes

UnsatisfiedDependencyException: Error creating bean with name

Add @Repository annotation to the Spring Data JPA repo

How to get current SIM card number in Android?

Getting the Phone Number, IMEI, and SIM Card ID

TelephonyManager tm = (TelephonyManager) 
            getSystemService(Context.TELEPHONY_SERVICE);        

For SIM card, use the getSimSerialNumber()

    //---get the SIM card ID---
    String simID = tm.getSimSerialNumber();
    if (simID != null)
        Toast.makeText(this, "SIM card ID: " + simID, 
        Toast.LENGTH_LONG).show();

Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)

    //---get the phone number---
    String telNumber = tm.getLine1Number();
    if (telNumber != null)        
        Toast.makeText(this, "Phone number: " + telNumber, 
        Toast.LENGTH_LONG).show();

IMEI number of the phone, use the getDeviceId()

    //---get the IMEI number---
    String IMEI = tm.getDeviceId();
    if (IMEI != null)        
        Toast.makeText(this, "IMEI number: " + IMEI, 
        Toast.LENGTH_LONG).show();

Permissions needed

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Proper way to rename solution (and directories) in Visual Studio

To rename a solution:

  1. In Solution Explorer, right-click the project, select Rename, and enter a new name.

  2. In Solution Explorer, right-click the project and select Properties. On the Application tab, change the "Assembly name" and "Default namespace".

  3. In the main cs file (or any other code files), rename the namespace declaration to use the new name. For this right-click the namespace and select Refactor > Rename enter a new name. For example: namespace WindowsFormsApplication1

  4. Change the AssemblyTitle and AssemblyProduct in Properties/AssemblyInfo.cs.

    [assembly: AssemblyTitle("New Name Here")]
    [assembly: AssemblyDescription("")]
    [assembly: AssemblyConfiguration("")]
    [assembly: AssemblyCompany("")]
    [assembly: AssemblyProduct("New Name Here")]
    [assembly: AssemblyCopyright("Copyright ©  2013")]
    [assembly: AssemblyTrademark("")]
    [assembly: AssemblyCulture("")]
    
  5. Delete bin and obj directories physically.

  6. Rename the project physical folder directory.

  7. Open the SLN file (within notepad or any editor) and change the path to the project.

  8. Clean and Rebuild the project.

Compute elapsed time

Something like a "Stopwatch" object comes to my mind:

Usage:

var st = new Stopwatch();
st.start(); //Start the stopwatch
// As a test, I use the setTimeout function to delay st.stop();
setTimeout(function (){
            st.stop(); // Stop it 5 seconds later...
            alert(st.getSeconds());
            }, 5000);

Implementation:

function Stopwatch(){
  var startTime, endTime, instance = this;

  this.start = function (){
    startTime = new Date();
  };

  this.stop = function (){
    endTime = new Date();
  }

  this.clear = function (){
    startTime = null;
    endTime = null;
  }

  this.getSeconds = function(){
    if (!endTime){
    return 0;
    }
    return Math.round((endTime.getTime() - startTime.getTime()) / 1000);
  }

  this.getMinutes = function(){
    return instance.getSeconds() / 60;
  }      
  this.getHours = function(){
    return instance.getSeconds() / 60 / 60;
  }    
  this.getDays = function(){
    return instance.getHours() / 24;
  }   
}

How to use sed to replace only the first occurrence in a file?

 # sed script to change "foo" to "bar" only on the first occurrence
 1{x;s/^/first/;x;}
 1,/foo/{x;/first/s///;x;s/foo/bar/;}
 #---end of script---

or, if you prefer: Editor's note: works with GNU sed only.

sed '0,/foo/s//bar/' file 

Source

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

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

or defined by a module not included in the server configuration

Check to make sure you have mod_rewrite enabled.

From: https://webdevdoor.com/php/mod_rewrite-windows-apache-url-rewriting

  1. Find the httpd.conf file (usually you will find it in a folder called conf, config or something along those lines)
  2. Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound '#' sign from in front of the line)
  3. Also find the line ClearModuleList is uncommented then find and make sure that the line AddModule mod_rewrite.c is not commented out.

If the LoadModule rewrite_module modules/mod_rewrite.so line is missing from the httpd.conf file entirely, just add it.

Sample command

To enable the module in a standard ubuntu do this:

a2enmod rewrite
systemctl restart apache2

change text of button and disable button in iOS

Hey Namratha, If you're asking about changing the text and enabled/disabled state of a UIButton, it can be done pretty easily as follows;

[myButton setTitle:@"Normal State Title" forState:UIControlStateNormal]; // To set the title
[myButton setEnabled:NO]; // To toggle enabled / disabled

If you have created the buttons in the Interface Builder and want to access them in code, you can take advantage of the fact that they are passed in as an argument to the IBAction calls:

- (IBAction) triggerActionWithSender: (id) sender;

This can be bound to the button and you’ll get the button in the sender argument when the action is triggered. If that’s not enough (because you need to access the buttons somewhere else than in the actions), declare an outlet for the button:

@property(retain) IBOutlet UIButton *someButton;

Then it’s possible to bind the button in IB to the controller, the NIB loading code will set the property value when loading the interface.

Reading a JSP variable from JavaScript

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

Pass a variable to a PHP script running from the command line

Parameters send by index like other applications:

php myfile.php type=daily

And then you can get them like this:

<?php
    if (count($argv) == 0) 
        exit;

    foreach ($argv as $arg)
        echo $arg;
?>

How to find the Number of CPU Cores via .NET/C#?

There are several different pieces of information relating to processors that you could get:

  1. Number of physical processors
  2. Number of cores
  3. Number of logical processors.

These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):

Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.

Physical Processors:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}

Cores:

int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
    coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);

Logical Processors:

Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);

OR

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}

Processors excluded from Windows:

You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:

static void Main(string[] args)
{
    int deviceCount = 0;
    IntPtr deviceList = IntPtr.Zero;
    // GUID for processor classid
    Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");

    try
    {
        // get a list of all processor devices
        deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
        // attempt to process each item in the list
        for (int deviceNumber = 0; ; deviceNumber++)
        {
            SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
            deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);

            // attempt to read the device info from the list, if this fails, we're at the end of the list
            if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
            {
                deviceCount = deviceNumber;
                break;
            }
        }
    }
    finally
    {
        if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
    }
    Console.WriteLine("Number of cores: {0}", deviceCount);
}

[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
    [MarshalAs(UnmanagedType.LPStr)]String enumerator,
    IntPtr hwndParent,
    Int32 Flags);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
    Int32 MemberIndex,
    ref SP_DEVINFO_DATA DeviceInterfaceData);

[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
    public int cbSize;
    public Guid ClassGuid;
    public uint DevInst;
    public IntPtr Reserved;
}

private enum DIGCF
{
    DEFAULT = 0x1,
    PRESENT = 0x2,
    ALLCLASSES = 0x4,
    PROFILE = 0x8,
    DEVICEINTERFACE = 0x10,
}

Content is not allowed in Prolog SAXParserException

This error can come if there is validation error either in your wsdl or xsd file. For instance I too got the same issue while running wsdl2java to convert my wsdl file to generate the client. In one of my xsd it was defined as below

<xs:import schemaLocation="" namespace="http://MultiChoice.PaymentService/DataContracts" />

Where the schemaLocation was empty. By providing the proper data in schemaLocation resolved my problem.

<xs:import schemaLocation="multichoice.paymentservice.DataContracts.xsd" namespace="http://MultiChoice.PaymentService/DataContracts" />

Java Date cut off time information

For all the answers using Calendar, you should use it like this instead

public static Date truncateDate(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.set(Calendar.HOUR_OF_DAY, c.getActualMinimum(Calendar.HOUR_OF_DAY));
    c.set(Calendar.MINUTE, c.getActualMinimum(Calendar.MINUTE));
    c.set(Calendar.SECOND, c.getActualMinimum(Calendar.SECOND));
    c.set(Calendar.MILLISECOND, c.getActualMinimum(Calendar.MILLISECOND));
    return c.getTime();
}

But I prefer this:

public static Date truncateDate(Date date) {
    return new java.sql.Date(date.getTime());
}

Hidden Features of C#?

One of the most useful features Visual Studio has is "Make object id". It generates an id and "attaches" to the object so wherever you look at the object you will also see the id (regardless of the thread).

While debugging right click on the variable tooltip and there you have it. It also works on watched/autos/locals variables.

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

Display animated GIF in iOS

You can use SwiftGif from this link

Usage:

imageView.loadGif(name: "jeremy")

How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

The best way to deal with this (if a declaration file is not available on DefinitelyTyped) is to write declarations only for the things you use rather than the entire library. This reduces the work a lot - and additionally the compiler is there to help out by complaining about missing methods.

SQLAlchemy insert or update example

I try lots of ways and finally try this:

def db_persist(func):
    def persist(*args, **kwargs):
        func(*args, **kwargs)
        try:
            session.commit()
            logger.info("success calling db func: " + func.__name__)
            return True
        except SQLAlchemyError as e:
            logger.error(e.args)
            session.rollback()
            return False

    return persist

and :

@db_persist
def insert_or_update(table_object):
    return session.merge(table_object)

How to add a line break in an Android TextView?

The most easy way to do it is to go to values/strings (in your resource folder)

Declare a string there:

    <string name="example_string">Line 1\Line2\Line n</string>

And in your specific xml file just call the string like

    <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/example_string" />

What is the best way to give a C# auto-property an initial value?

class Person 
{    
    /// Gets/sets a value indicating whether auto 
    /// save of review layer is enabled or not
    [System.ComponentModel.DefaultValue(true)] 
    public bool AutoSaveReviewLayer { get; set; }
}

This version of the application is not configured for billing through Google Play

In the old developer console:

Settings -> Account details -> License Testing -> Gmail accounts with testing access and type here your accounts

In new developer console:

Settings -> License Testing -> Type your Gmail account, hit 'Enter' and click 'Save'.

HashMap - getting First Key value

You can try this:

 Map<String,String> map = new HashMap<>();
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key = entry.getKey();
 String value = entry.getValue();

Keep in mind, HashMap does not guarantee the insertion order. Use a LinkedHashMap to keep the order intact.

Eg:

 Map<String,String> map = new LinkedHashMap<>();
 map.put("Active","33");
 map.put("Renewals Completed","3");
 map.put("Application","15");
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key= entry.getKey();
 String value=entry.getValue();
 System.out.println(key);
 System.out.println(value);

Output:

 Active
 33

Auto height of div

Here is the Latest solution of the problem:

In your CSS file write the following class called .clearfix along with the pseudo selector :after

.clearfix:after {
content: "";
display: table;
clear: both;
}

Then, in your HTML, add the .clearfix class to your parent Div. For example:

<div class="clearfix">
    <div></div>
    <div></div>
</div>

It should work always. You can call the class name as .group instead of .clearfix , as it will make the code more semantic. Note that, it is Not necessary to add the dot or even a space in the value of Content between the double quotation "".

Source: http://css-snippets.com/page/2/

Render HTML string as real HTML in a React component

I could not get npm build to work with react-html-parser. However, in my case, I was able to successfully make use of https://reactjs.org/docs/fragments.html. I had a requirement to show few html unicode characters , but they should not be directly embedded in the JSX. Within the JSX, it had to be picked from the Component's state. Component code snippet is given below :

constructor() 
{
this.state = {
      rankMap : {"5" : <Fragment>&#9733; &#9733; &#9733; &#9733; &#9733;</Fragment> , 
                 "4" : <Fragment>&#9733; &#9733; &#9733; &#9733; &#9734;</Fragment>, 
                 "3" : <Fragment>&#9733; &#9733; &#9733; &#9734; &#9734;</Fragment> , 
                 "2" : <Fragment>&#9733; &#9733; &#9734; &#9734; &#9734;</Fragment>, 
                 "1" : <Fragment>&#9733; &#9734; &#9734; &#9734; &#9734;</Fragment>}
                };
}

render() 
{
       return (<div class="card-footer">
                    <small class="text-muted">{ this.state.rankMap["5"] }</small>
               </div>);
}

How to get index of an item in java.util.Set

you can extend LinkedHashSet adding your desired getIndex() method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.

"Invalid form control" only in Google Chrome

If you don't care about HTML5 validation (maybe you are validating in JS or on the server), you could try adding "novalidate" to the form or the input elements.

Redirecting a page using Javascript, like PHP's Header->Location

You application of js and php in totally invalid.

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

However you can do something like this

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

How to execute a java .class from the command line

You need to specify the classpath. This should do it:

java -cp . Echo "hello"

This tells java to use . (the current directory) as its classpath, i.e. the place where it looks for classes. Note than when you use packages, the classpath has to contain the root directory, not the package subdirectories. e.g. if your class is my.package.Echo and the .class file is bin/my/package/Echo.class, the correct classpath directory is bin.

Does Python SciPy need BLAS?

On Fedora, this works:

 yum install lapack lapack-devel blas blas-devel
 pip install numpy
 pip install scipy

Remember to install 'lapack-devel' and 'blas-devel' in addition to 'blas' and 'lapack' otherwise you'll get the error you mentioned or the "numpy.distutils.system_info.LapackNotFoundError" error.

C program to check little vs. big endian

Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:


The following program would determine that:

#include <stdio.h>
#include <stdint.h>

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } e = { 0x01000000 };

    return e.c[0];
}

int main(void)
{
    printf("System is %s-endian.\n",
        is_big_endian() ? "big" : "little");

    return 0;
}

You also have this approach; from Quake II:

byte    swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
    bigendien = false;

And !is_big_endian() is not 100% to be little as it can be mixed/middle.

Believe this can be checked using same approach only change value from 0x01000000 to i.e. 0x01020304 giving:

switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE

But not entirely sure about that one ...

How can I count occurrences with groupBy?

If you're open to using a third-party library, you can use the Collectors2 class in Eclipse Collections to convert the List to a Bag using a Stream. A Bag is a data structure that is built for counting.

Bag<String> counted =
        list.stream().collect(Collectors2.countBy(each -> each));

Assert.assertEquals(1, counted.occurrencesOf("World"));
Assert.assertEquals(2, counted.occurrencesOf("Hello"));

System.out.println(counted.toStringOfItemToCount());

Output:

{World=1, Hello=2}

In this particular case, you can simply collect the List directly into a Bag.

Bag<String> counted = 
        list.stream().collect(Collectors2.toBag());

You can also create the Bag without using a Stream by adapting the List with the Eclipse Collections protocols.

Bag<String> counted = Lists.adapt(list).countBy(each -> each);

or in this particular case:

Bag<String> counted = Lists.adapt(list).toBag();

You could also just create the Bag directly.

Bag<String> counted = Bags.mutable.with("Hello", "Hello", "World");

A Bag<String> is like a Map<String, Integer> in that it internally keeps track of keys and their counts. But, if you ask a Map for a key it doesn't contain, it will return null. If you ask a Bag for a key it doesn't contain using occurrencesOf, it will return 0.

Note: I am a committer for Eclipse Collections.

Installing Python 3 on RHEL

Installing from RPM is generally better, because:

  • you can install and uninstall (properly) python3.
  • the installation time is way faster. If you work in a cloud environment with multiple VMs, compiling python3 on each VMs is not acceptable.

Solution 1: Red Hat & EPEL repositories

Red Hat has added through the EPEL repository:

  • Python 3.4 for CentOS 6
  • Python 3.6 for CentOS 7

[EPEL] How to install Python 3.4 on CentOS 6

sudo yum install -y epel-release
sudo yum install -y python34

# Install pip3
sudo yum install -y python34-setuptools  # install easy_install-3.4
sudo easy_install-3.4 pip

You can create your virtualenv using pyvenv:

pyvenv /tmp/foo

[EPEL] How to install Python 3.6 on CentOS 7

With CentOS7, pip3.6 is provided as a package :)

sudo yum install -y epel-release
sudo yum install -y python36 python36-pip

You can create your virtualenv using pyvenv:

python3.6 -m venv /tmp/foo

If you use the pyvenv script, you'll get a WARNING:

$ pyvenv-3.6 /tmp/foo
WARNING: the pyenv script is deprecated in favour of `python3.6 -m venv`

Solution 2: IUS Community repositories

The IUS Community provides some up-to-date packages for RHEL & CentOS. The guys behind are from Rackspace, so I think that they are quite trustworthy...

https://ius.io/

Check the right repo for you here:

https://ius.io/setup

[IUS] How to install Python 3.6 on CentOS 6

sudo yum install -y https://repo.ius.io/ius-release-el6.rpm
sudo yum install -y python36u python36u-pip

You can create your virtualenv using pyvenv:

python3.6 -m venv /tmp/foo

[IUS] How to install Python 3.6 on CentOS 7

sudo yum install -y https://repo.ius.io/ius-release-el7.rpm
sudo yum install -y python36u python36u-pip

You can create your virtualenv using pyvenv:

python3.6 -m venv /tmp/foo

Download files from server php

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

Casting to string in JavaScript

if you are ok with null, undefined, NaN, 0, and false all casting to '' then (s ? s+'' : '') is faster.

see http://jsperf.com/cast-to-string/8

note - there are significant differences across browsers at this time.

Tomcat is web server or application server?

Tomcat is a web server (can handle HTTP requests/responses) and web container (implements Java Servlet API, also called servletcontainer) in one. Some may call it an application server, but it is definitely not an fullfledged Java EE application server (it does not implement the whole Java EE API).

See also:

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

I was getting this error because I did release that my ant release was failing because I ran out of disk space.

package R does not exist

I had: "error: package R does not exist" and assumed javac didn't have access to R.java.
So I appended %PROJ_LOC%\gen to sourcepath, and it worked! SOURCEPATH=%PROJ_LOC%\src;%PROJ_LOC%\gen

I'm not using Android Studio or Ant (or XML).

Visual Studio debugger error: Unable to start program Specified file cannot be found

I had the same problem :) Verify the "Source code" folder on the "Solution Explorer", if it doesn't contain any "source code" file then :

Right click on "Source code" > Add > Existing Item > Choose the file You want to build and run.

Good luck ;)

$lookup on ObjectId's in an array

use $unwind you will get the first object instead of array of objects

query:

db.getCollection('vehicles').aggregate([
  {
    $match: {
      status: "AVAILABLE",
      vehicleTypeId: {
        $in: Array.from(newSet(d.vehicleTypeIds))
      }
    }
  },
  {
    $lookup: {
      from: "servicelocations",
      localField: "locationId",
      foreignField: "serviceLocationId",
      as: "locations"
    }
  },
  {
    $unwind: "$locations"
  }
]);

result:

{
    "_id" : ObjectId("59c3983a647101ec58ddcf90"),
    "vehicleId" : "45680",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Isuzu/2003-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}


{
    "_id" : ObjectId("59c3983a647101ec58ddcf91"),
    "vehicleId" : "81765",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Hino/2004-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}

CMake link to external library

Set libraries search path first:

LINK_DIRECTORIES(${CMAKE_BINARY_DIR}/res)

And then just do

TARGET_LINK_LIBRARIES(GLBall mylib)

Powershell Execute remote exe with command line arguments on remote computer

$sb = ScriptBlock::Create("$command")
Invoke-Command -ScriptBlock $sb

This should work and avoid misleading the beginners.

PHP: Calling another class' method

File 1

class ClassA {

    public $name = 'A';

    public function getName(){
        return $this->name;
    }

}

File 2

include("file1.php");
class ClassB {

    public $name = 'B';

    public function getName(){
        return $this->name;
    }

    public function callA(){
        $a = new ClassA();
        return $a->getName();
    }

    public static function callAStatic(){
        $a = new ClassA();
        return $a->getName();
    }

}

$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();

Git Pull is Not Possible, Unmerged Files

Say the remote is origin and the branch is master, and say you already have master checked out, might try the following:

git fetch origin
git reset --hard origin/master

This basically just takes the current branch and points it to the HEAD of the remote branch.

WARNING: As stated in the comments, this will throw away your local changes and overwrite with whatever is on the origin.

Or you can use the plumbing commands to do essentially the same:

git fetch <remote>
git update-ref refs/heads/<branch> $(git rev-parse <remote>/<branch>)
git reset --hard

EDIT: I'd like to briefly explain why this works.

The .git folder can hold the commits for any number of repositories. Since the commit hash is actually a verification method for the contents of the commit, and not just a randomly generated value, it is used to match commit sets between repositories.

A branch is just a named pointer to a given hash. Here's an example set:

$ find .git/refs -type f
.git/refs/tags/v3.8
.git/refs/heads/master
.git/refs/remotes/origin/HEAD
.git/refs/remotes/origin/master

Each of these files contains a hash pointing to a commit:

$ cat .git/refs/remotes/origin/master
d895cb1af15c04c522a25c79cc429076987c089b

These are all for the internal git storage mechanism, and work independently of the working directory. By doing the following:

git reset --hard origin/master

git will point the current branch at the same hash value that origin/master points to. Then it forcefully changes the working directory to match the file structure/contents at that hash.

To see this at work go ahead and try out the following:

git checkout -b test-branch
# see current commit and diff by the following
git show HEAD
# now point to another location
git reset --hard <remote>/<branch>
# see the changes again
git show HEAD

Hide/Show Column in an HTML Table

The following is building on Eran's code, with a few minor changes. Tested it and it seems to work fine on Firefox 3, IE7.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script>
$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
        var index = $(this).attr('name').substr(3);
        index--;
        $('table tr').each(function() { 
            $('td:eq(' + index + ')',this).toggle();
        });
        $('th.' + $(this).attr('name')).toggle();
    });
});
</script>
<body>
<table>
<thead>
    <tr>
        <th class="col1">Header 1</th>
        <th class="col2">Header 2</th>
        <th class="col3">Header 3</th>
    </tr>
</thead>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>

<form>
    <input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br />
    <input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br />
    <input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br />
</form>
</body>
</html>

Difference between JPanel, JFrame, JComponent, and JApplet

Those classes are common extension points for Java UI designs. First off, realize that they don't necessarily have much to do with each other directly, so trying to find a relationship between them might be counterproductive.

JApplet - A base class that let's you write code that will run within the context of a browser, like for an interactive web page. This is cool and all but it brings limitations which is the price for it playing nice in the real world. Normally JApplet is used when you want to have your own UI in a web page. I've always wondered why people don't take advantage of applets to store state for a session so no database or cookies are needed.

JComponent - A base class for objects which intend to interact with Swing.

JFrame - Used to represent the stuff a window should have. This includes borders (resizeable y/n?), titlebar (App name or other message), controls (minimize/maximize allowed?), and event handlers for various system events like 'window close' (permit app to exit yet?).

JPanel - Generic class used to gather other elements together. This is more important with working with the visual layout or one of the provided layout managers e.g. gridbaglayout, etc. For example, you have a textbox that is bigger then the area you have reserved. Put the textbox in a scrolling pane and put that pane into a JPanel. Then when you place the JPanel, it will be more manageable in terms of layout.

Fixed positioning in Mobile Safari

This is how i did it. I have a nav block that is below the header once you scroll the page down it 'sticks' to the top of the window. If you scroll back to top, nav goes back in it's place I use position:fixed in CSS for non mobile platforms and iOS5. Other Mobile versions do have that 'lag' until screen stops scrolling before it's set.

// css
#sticky.stick {
    width:100%;
    height:50px;
    position: fixed;
    top: 0;
    z-index: 1;
}

// jquery 
//sticky nav
    function sticky_relocate() {
      var window_top = $(window).scrollTop();
      var div_top = $('#sticky-anchor').offset().top;

      if (window_top > div_top)
        $('#sticky').addClass('stick');
      else
        $('#sticky').removeClass('stick');
     }

$(window).scroll(function(event){

    // sticky nav css NON mobile way
       sticky_relocate();

       var st = $(this).scrollTop();

    // sticky nav iPhone android mobile way iOS<5

       if (navigator.userAgent.match(/OS 5(_\d)+ like Mac OS X/i)) {
            //do nothing uses sticky_relocate() css
       } else if ( navigator.userAgent.match(/(iPod|iPhone|iPad)/i) || navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) ) {

            var window_top = $(window).scrollTop();
            var div_top = $('#sticky-anchor').offset().top;

            if (window_top > div_top) {
                $('#sticky').css({'top' : st  , 'position' : 'absolute' });
            } else {
                $('#sticky').css({'top' : 'auto' });
            }
        };

Concatenate a vector of strings/character

Try using an empty collapse argument within the paste function:

paste(sdata, collapse = '')

Thanks to http://twitter.com/onelinetips/status/7491806343

Find if listA contains any elements not in listB

listA.Except(listB) will give you all of the items in listA that are not in listB

How to conditionally take action if FINDSTR fails to find a string

In DOS/Windows Batch most commands return an exitCode, called "errorlevel", that is a value that customarily is equal to zero if the command ends correctly, or a number greater than zero if ends because an error, with greater numbers for greater errors (hence the name).

There are a couple methods to check that value, but the original one is:

IF ERRORLEVEL value command

Previous IF test if the errorlevel returned by the previous command was GREATER THAN OR EQUAL the given value and, if this is true, execute the command. For example:

verify bad-param
if errorlevel 1 echo Errorlevel is greater than or equal 1
echo The value of errorlevel is: %ERRORLEVEL%

Findstr command return 0 if the string was found and 1 if not:

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code will copy the file if the string was NOT found in the file.

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code copy the file if the string was found. Try this:

findstr "string" file
if errorlevel 1 (
    echo String NOT found...
) else (
    echo String found
)

How to change the background color of a UIButton while it's highlighted?

Try tintColor:

_button.tintColor = [UIColor redColor];

Java: Get month Integer from Date

tl;dr

myUtilDate.toInstant()                          // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
          .atZone(                              // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object. 
              ZoneId.of( "America/Montreal" )   // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
          )                                     // Returns a `ZonedDateTime` object.
          .getMonthValue()                      // Extract a month number. Returns a `int` number.

java.time Details

The Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.

I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.

Using java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.

The Month class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.

To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.

ZoneId zoneId = ZoneId.of( "America/Montreal" );  // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth(); 
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to percent-encode URL parameters in Python?

My answer is similar to Paolo's answer.

I think module requests is much better. It's based on urllib3. You can try this:

>>> from requests.utils import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'

UIScrollView not scrolling

The answer above is correct - to make scrolling happen, it's necessary to set the content size.

If you're using interface builder a neat way to do this is with user defined runtime attributes. Eg:

enter image description here

javascript: pause setTimeout();

You can do like below to make setTimeout pausable on server side (Node.js)

const PauseableTimeout = function(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        global.clearTimeout(timerId);
        remaining -= Date.now() - start;
    };

    this.resume = function() {
        start = Date.now();
        global.clearTimeout(timerId);
        timerId = global.setTimeout(callback, remaining);
    };

    this.resume();
};

and you can check it as below

var timer = new PauseableTimeout(function() {
    console.log("Done!");
}, 3000);
setTimeout(()=>{
    timer.pause();
    console.log("setTimeout paused");
},1000);

setTimeout(()=>{
    console.log("setTimeout time complete");
},3000)

setTimeout(()=>{
    timer.resume();
    console.log("setTimeout resume again");
},5000)

S3 - Access-Control-Allow-Origin Header

  1. Set CORS configuration in Permissions settings for you S3 bucket

    <?xml version="1.0" encoding="UTF-8"?>
    <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
        <CORSRule>
            <AllowedOrigin>*</AllowedOrigin>
            <AllowedMethod>GET</AllowedMethod>
            <MaxAgeSeconds>3000</MaxAgeSeconds>
            <AllowedHeader>Authorization</AllowedHeader>
        </CORSRule>
    </CORSConfiguration> 
    
  2. S3 adds CORS headers only when http request has the Origin header.

  3. CloudFront does not forward Origin header by default

    You need to whitelist Origin header in Behavior settings for your CloudFront Distribution.

Mockito: Inject real objects into private @Autowired fields

Mockito is not a DI framework and even DI frameworks encourage constructor injections over field injections.
So you just declare a constructor to set dependencies of the class under test :

@Mock
private SomeService serviceMock;

private Demo demo;

/* ... */
@BeforeEach
public void beforeEach(){
   demo = new Demo(serviceMock);
}

Using Mockito spy for the general case is a terrible advise. It makes the test class brittle, not straight and error prone : What is really mocked ? What is really tested ?
@InjectMocks and @Spy also hurts the overall design since it encourages bloated classes and mixed responsibilities in the classes.
Please read the spy() javadoc before using that blindly (emphasis is not mine) :

Creates a spy of the real object. The spy calls real methods unless they are stubbed. Real spies should be used carefully and occasionally, for example when dealing with legacy code.

As usual you are going to read the partial mock warning: Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.

However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Insert new column into table in sqlite?

SQLite has limited ALTER TABLE support that you can use to add a column to the end of a table or to change the name of a table.

If you want to make more complex changes in the structure of a table, you will have to recreate the table. You can save existing data to a temporary table, drop the old table, create the new table, then copy the data back in from the temporary table.

For example, suppose you have a table named "t1" with columns names "a" and "c" and that you want to insert column "b" from this table. The following steps illustrate how this could be done:

BEGIN TRANSACTION;
CREATE TEMPORARY TABLE t1_backup(a,c);
INSERT INTO t1_backup SELECT a,c FROM t1;
DROP TABLE t1;
CREATE TABLE t1(a,b, c);
INSERT INTO t1 SELECT a,c FROM t1_backup;
DROP TABLE t1_backup;
COMMIT;

Now you are ready to insert your new data like so:

UPDATE t1 SET b='blah' WHERE a='key'

Iterating over a 2 dimensional python list

Ref: zip built-in function

zip() in conjunction with the * operator can be used to unzip a list

unzip_lst = zip(*mylist)
for i in unzip_lst:
    for j in i:
        print j

use regular expression in if-condition in bash

When using a glob pattern, a question mark represents a single character and an asterisk represents a sequence of zero or more characters:

if [[ $gg == ????grid* ]] ; then echo $gg; fi

When using a regular expression, a dot represents a single character and an asterisk represents zero or more of the preceding character. So ".*" represents zero or more of any character, "a*" represents zero or more "a", "[0-9]*" represents zero or more digits. Another useful one (among many) is the plus sign which represents one or more of the preceding character. So "[a-z]+" represents one or more lowercase alpha character (in the C locale - and some others).

if [[ $gg =~ ^....grid.*$ ]] ; then echo $gg; fi

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

python pandas dataframe to dictionary

mydict = dict(zip(df.id, df.value))

set default schema for a sql query

SETUSER could work, having a user, even an orphaned user in the DB with the default schema needed. But SETUSER is on the legacy not supported for ever list. So a similar alternative would be to setup an application role with the needed default schema, as long as no cross DB access is needed, this should work like a treat.

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:

JS

$(function () {
    x=3;
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        e.preventDefault();
        x = x+5;
        $('#myList li').slice(0, x).slideDown();
    });
});

CSS

#myList li{display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}

Count work days between two dates

As with DATEDIFF, I do not consider the end date to be part of the interval. The number of (for example) Sundays between @StartDate and @EndDate is the number of Sundays between an "initial" Monday and the @EndDate minus the number of Sundays between this "initial" Monday and the @StartDate. Knowing this, we can calculate the number of workdays as follows:

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2018/01/01'
SET @EndDate = '2019/01/01'

SELECT DATEDIFF(Day, @StartDate, @EndDate) -- Total Days
  - (DATEDIFF(Day, 0, @EndDate)/7 - DATEDIFF(Day, 0, @StartDate)/7) -- Sundays
  - (DATEDIFF(Day, -1, @EndDate)/7 - DATEDIFF(Day, -1, @StartDate)/7) -- Saturdays

Best regards!

How do you create a hidden div that doesn't create a line break or horizontal space?

Since the release of HTML5 one can now simply do:

<div hidden>This div is hidden</div>

Note: This is not supported by some old browsers, most notably IE < 11.

Hidden Attribute Documentation (MDN,W3C)

Detect changed input text box

I think you can use keydown too:

$('#fieldID').on('keydown', function (e) {
  //console.log(e.which);
  if (e.which === 8) {
    //do something when pressing delete
    return true;
  } else {
    //do something else
    return false;
  }
});

Google Maps V3 - How to calculate the zoom level for a given bounds

Dart Version:

  double latRad(double lat) {
    final double sin = math.sin(lat * math.pi / 180);
    final double radX2 = math.log((1 + sin) / (1 - sin)) / 2;
    return math.max(math.min(radX2, math.pi), -math.pi) / 2;
  }

  double getMapBoundZoom(LatLngBounds bounds, double mapWidth, double mapHeight) {
    final LatLng northEast = bounds.northEast;
    final LatLng southWest = bounds.southWest;

    final double latFraction = (latRad(northEast.latitude) - latRad(southWest.latitude)) / math.pi;

    final double lngDiff = northEast.longitude - southWest.longitude;
    final double lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;

    final double latZoom = (math.log(mapHeight / 256 / latFraction) / math.ln2).floorToDouble();
    final double lngZoom = (math.log(mapWidth / 256 / lngFraction) / math.ln2).floorToDouble();

    return math.min(latZoom, lngZoom);
  }

How to round an average to 2 decimal places in PostgreSQL?

Try casting your column to a numeric like:

SELECT ROUND(cast(some_column as numeric),2) FROM table

Bootstrap - floating navbar button right

In bootstrap 4 use:

<ul class="nav navbar-nav ml-auto">

This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.

Using scanner.nextLine()

or

int selection = Integer.parseInt(scanner.nextLine());

How to check whether a str(variable) is empty or not?

{
test_str1 = "" 
test_str2 = "  "
  
# checking if string is empty 
print ("The zero length string without spaces is empty ? : ", end = "") 
if(len(test_str1) == 0): 
    print ("Yes") 
else : 
    print ("No") 
  
# prints No  
print ("The zero length string with just spaces is empty ? : ", end = "") 
if(len(test_str2) == 0): 
    print ("Yes") 
else : 
    print ("No") 
}

Setting up Vim for Python

A very good plugin management system to use. The included vimrc file is good enough for python programming and can be easily configured to your needs. See http://spf13.com/project/spf13-vim/

How to fire a button click event from JavaScript in ASP.NET

document.FormName.btnSubmit.click(); 

works for me. Enjoy.

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

Render a string in HTML and preserve spaces and linebreaks

I was trying the white-space: pre-wrap; technique stated by pete but if the string was continuous and long it just ran out of the container, and didn't warp for whatever reason, didn't have much time to investigate.. but if you too are having the same problem, I ended up using the <pre> tags and the following css and everything was good to go..

pre {
font-size: inherit;
color: inherit;
border: initial;
padding: initial;
font-family: inherit;
}

How to remove the underline for anchors(links)?

Use css property,

text-decoration:none;

To remove underline from the link.

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

UTF-8 encoding in JSP page

Page encoding or anything else do not matter a lot. ISO-8859-1 is a subset of UTF-8, therefore you never have to convert ISO-8859-1 to UTF-8 because ISO-8859-1 is already UTF-8,a subset of UTF-8 but still UTF-8. Plus, all that do not mean a thing if You have a double encoding somewhere. This is my "cure all" recipe for all things encoding and charset related:

        String myString = "heartbroken ð";

//String is double encoded, fix that first.

                myString = new String(myString.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                String cleanedText = StringEscapeUtils.unescapeJava(myString);
                byte[] bytes = cleanedText.getBytes(StandardCharsets.UTF_8);
                String text = new String(bytes, StandardCharsets.UTF_8);
                Charset charset = Charset.forName("UTF-8");
                CharsetDecoder decoder = charset.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.IGNORE);
                decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                CharsetEncoder encoder = charset.newEncoder();
                encoder.onMalformedInput(CodingErrorAction.IGNORE);
                encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                try {
                    // The new ByteBuffer is ready to be read.
                    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(text));
                    // The new ByteBuffer is ready to be read.
                    CharBuffer cbuf = decoder.decode(bbuf);
                    String str = cbuf.toString();
                } catch (CharacterCodingException e) {
                    logger.error("Error Message if you want to");

                } 

#define macro for debug printing in C?

I've been stewing on how to do this for years, and finally come up with a solution. However, I didn't know that there were other solutions here already. First, at difference with Leffler's answer, I don't see his argument that debug prints should always be compiled. I'd rather not have tons of unneeded code executing in my project, when not needed, in cases where I need to test and they might not be getting optimized out.

Not compiling every time might sound worse than it is in actual practice. You do wind up with debug prints that don't compile sometimes, but it's not so hard to compile and test them before finalizing a project. With this system, if you are using three levels of debugs, just put it on debug message level three, fix your compile errors and check for any others before you finalize yer code. (Since of course, debug statements compiling are no guarantee that they are still working as intended.)

My solution provides for levels of debug detail also; and if you set it to the highest level, they all compile. If you've been using a high debug detail level recently, they all were able to compile at that time. Final updates should be pretty easy. I've never needed more than three levels, but Jonathan says he's used nine. This method (like Leffler's) can be extended to any number of levels. The usage of my method may be simpler; requiring just two statements when used in your code. I am, however, coding the CLOSE macro too - although it doesn't do anything. It might if I were sending to a file.

Against the cost the extra step of testing them to see that they will compile before delivery, is that

  1. You must trust them to get optimized out, which admittedly SHOULD happen if you have a sufficient optimization level.
  2. Furthermore, they probably won't if you make a release compile with optimization turned off for testing purposes (which is admittedly rare); and they almost certainly won't at all during debug - thereby executing dozens or hundreds of "if (DEBUG)" statements at runtime; thus slowing execution (which is my principle objection) and less importantly, increasing your executable or dll size; and hence execution and compile times. Jonathan, however, informs me his method can be made to also not compile statements at all.

Branches are actually relatively pretty costly in modern pre-fetching processors. Maybe not a big deal if your app is not a time-critical one; but if performance is an issue, then, yes, a big enough deal that I'd prefer to opt for somewhat faster-executing debug code (and possibly faster release, in rare cases, as noted).

So, what I wanted is a debug print macro that does not compile if it is not to be printed, but does if it is. I also wanted levels of debugging, so that, e.g. if I wanted performance-crucial parts of the code not to print at some times, but to print at others, I could set a debug level, and have extra debug prints kick in. I came across a way to implement debug levels that determined if the print was even compiled or not. I achieved it this way:

DebugLog.h:

// FILE: DebugLog.h
// REMARKS: This is a generic pair of files useful for debugging.  It provides three levels of 
// debug logging, currently; in addition to disabling it.  Level 3 is the most information.
// Levels 2 and 1 have progressively more.  Thus, you can write: 
//     DEBUGLOG_LOG(1, "a number=%d", 7);
// and it will be seen if DEBUG is anything other than undefined or zero.  If you write
//     DEBUGLOG_LOG(3, "another number=%d", 15);
// it will only be seen if DEBUG is 3.  When not being displayed, these routines compile
// to NOTHING.  I reject the argument that debug code needs to always be compiled so as to 
// keep it current.  I would rather have a leaner and faster app, and just not be lazy, and 
// maintain debugs as needed.  I don't know if this works with the C preprocessor or not, 
// but the rest of the code is fully C compliant also if it is.

#define DEBUG 1

#ifdef DEBUG
#define DEBUGLOG_INIT(filename) debuglog_init(filename)
#else
#define debuglog_init(...)
#endif

#ifdef DEBUG
#define DEBUGLOG_CLOSE debuglog_close
#else
#define debuglog_close(...)
#endif

#define DEBUGLOG_LOG(level, fmt, ...) DEBUGLOG_LOG ## level (fmt, ##__VA_ARGS__)

#if DEBUG == 0
#define DEBUGLOG_LOG0(...)
#endif

#if DEBUG >= 1
#define DEBUGLOG_LOG1(fmt, ...) debuglog_log (fmt, ##__VA_ARGS__)
#else
#define DEBUGLOG_LOG1(...)
#endif

#if DEBUG >= 2
#define DEBUGLOG_LOG2(fmt, ...) debuglog_log (fmt, ##__VA_ARGS__)
#else
#define DEBUGLOG_LOG2(...)
#endif

#if DEBUG == 3
#define DEBUGLOG_LOG3(fmt, ...) debuglog_log (fmt, ##__VA_ARGS__)
#else
#define DEBUGLOG_LOG3(...)
#endif

void debuglog_init(char *filename);
void debuglog_close(void);
void debuglog_log(char* format, ...);

DebugLog.cpp:

// FILE: DebugLog.h
// REMARKS: This is a generic pair of files useful for debugging.  It provides three levels of 
// debug logging, currently; in addition to disabling it.  See DebugLog.h's remarks for more 
// info.

#include <stdio.h>
#include <stdarg.h>

#include "DebugLog.h"

FILE *hndl;
char *savedFilename;

void debuglog_init(char *filename)
{
    savedFilename = filename;
    hndl = fopen(savedFilename, "wt");
    fclose(hndl);
}

void debuglog_close(void)
{
    //fclose(hndl);
}

void debuglog_log(char* format, ...)
{
    hndl = fopen(savedFilename,"at");
    va_list argptr;
    va_start(argptr, format);
    vfprintf(hndl, format, argptr);
    va_end(argptr);
    fputc('\n',hndl);
    fclose(hndl);
}

Using the macros

To use it, just do:

DEBUGLOG_INIT("afile.log");

To write to the log file, just do:

DEBUGLOG_LOG(1, "the value is: %d", anint);

To close it, you do:

DEBUGLOG_CLOSE();

although currently this isn't even necessary, technically speaking, as it does nothing. I'm still using the CLOSE right now, however, in case I change my mind about how it works, and want to leave the file open between logging statements.

Then, when you want to turn on debug printing, just edit the first #define in the header file to say, e.g.

#define DEBUG 1

To have logging statements compile to nothing, do

#define DEBUG 0

If you need info from a frequently executed piece of code (i.e. a high level of detail), you may want to write:

 DEBUGLOG_LOG(3, "the value is: %d", anint);

If you define DEBUG to be 3, logging levels 1, 2 & 3 compile. If you set it to 2, you get logging levels 1 & 2. If you set it to 1, you only get logging level 1 statements.

As to the do-while loop, since this evaluates to either a single function or nothing, instead of an if statement, the loop is not needed. OK, castigate me for using C instead of C++ IO (and Qt's QString::arg() is a safer way of formatting variables when in Qt, too — it's pretty slick, but takes more code and the formatting documentation isn't as organized as it might be - but still I've found cases where its preferable), but you can put whatever code in the .cpp file you want. It also might be a class, but then you would need to instantiate it and keep up with it, or do a new() and store it. This way, you just drop the #include, init and optionally close statements into your source, and you are ready to begin using it. It would make a fine class, however, if you are so inclined.

I'd previously seen a lot of solutions, but none suited my criteria as well as this one.

  1. It can be extended to do as many levels as you like.
  2. It compiles to nothing if not printing.
  3. It centralizes IO in one easy-to-edit place.
  4. It's flexible, using printf formatting.
  5. Again, it does not slow down debug runs, whereas always-compiling debug prints are always executed in debug mode. If you are doing computer science, and not easier to write information processing, you may find yourself running a CPU-consuming simulator, to see e.g. where the debugger stops it with an index out of range for a vector. These run extra-slowly in debug mode already. The mandatory execution of hundreds of debug prints will necessarily slow such runs down even further. For me, such runs are not uncommon.

Not terribly significant, but in addition:

  1. It requires no hack to print without arguments (e.g. DEBUGLOG_LOG(3, "got here!");); thus allowing you to use, e.g. Qt's safer .arg() formatting. It works on MSVC, and thus, probably gcc. It uses ## in the #defines, which is non-standard, as Leffler points out, but is widely supported. (You can recode it not to use ## if necessary, but you will have to use a hack such as he provides.)

Warning: If you forget to provide the logging level argument, MSVC unhelpfully claims the identifier is not defined.

You might want to use a preprocessor symbol name other than DEBUG, as some source also defines that symbol (eg. progs using ./configure commands to prepare for building). It seemed natural to me when I developed it. I developed it in an application where the DLL is being used by something else, and it's more convent to send log prints to a file; but changing it to vprintf() would work fine, too.

I hope this saves many of you grief about figuring out the best way to do debug logging; or shows you one you might prefer. I've half-heartedly been trying to figure this one out for decades. Works in MSVC 2012 & 2015, and thus probably on gcc; as well as probably working on many others, but I haven't tested it on them.

I mean to make a streaming version of this one day, too.

Note: Thanks go to Leffler, who has cordially helped me format my message better for StackOverflow.

How to strip all whitespace from string

If optimal performance is not a requirement and you just want something dead simple, you can define a basic function to test each character using the string class's built in "isspace" method:

def remove_space(input_string):
    no_white_space = ''
    for c in input_string:
        if not c.isspace():
            no_white_space += c
    return no_white_space

Building the no_white_space string this way will not have ideal performance, but the solution is easy to understand.

>>> remove_space('strip my spaces')
'stripmyspaces'

If you don't want to define a function, you can convert this into something vaguely similar with list comprehension. Borrowing from the top answer's join solution:

>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

What's the difference between xsd:include and xsd:import?

I'm interested in this as well. The only explanation I've found is that xsd:include is used for intra-namespace inclusions, while xsd:import is for inter-namespace inclusion.

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

Terminating a script in PowerShell

I used this for a reruning of a program. I don't know if it would help, but it is a simple if statement requiring only two different entry's. It worked in powershell for me.

$rerun = Read-Host "Rerun report (y/n)?"

if($rerun -eq "y") { Show-MemoryReport }
if($rerun -eq "n") { Exit }

Don't know if this helps, but i believe this would be along the lines of terminating a program after you have run it. However in this case, every defined input requires a listed and categorized output. You could also have the exit call up a new prompt line and terminate the program that way.

Best way to select random rows PostgreSQL

If you want just one row, you can use a calculated offset derived from count.

select * from table_name limit 1
offset floor(random() * (select count(*) from table_name));

Open Cygwin at a specific folder

I have created the batch file and put it to the Cygwin's /bin directory. This script was developed so it allows to install/uninstall the registry entries for opening selected folders and drives in Cygwin. For details see the link http://with-love-from-siberia.blogspot.com/2013/12/cygwin-here.html.

update: This solution does the same as early suggestions but all manipulations with Windows Registry are hidden within the script.

Perform the command to install

cyghere.bat /install

Perform the command to uninstall

cyghere.bat /uninstall

How to change the playing speed of videos in HTML5?

(Tested in Chrome while playing videos on YouTube, but should work anywhere--especially useful for speeding up online training videos).

For anyone wanting to add these as "bookmarklets" (bookmarks) to your browser, use these browser bookmark names and URLs, and add each of the following bookmarks to the top of your browser:

enter image description here

Name: 0.5x
URL:

javascript:

document.querySelector('video').playbackRate = 0.5;

Name: 1.0x
URL:

javascript:

document.querySelector('video').playbackRate = 1.0;

Name: 1.5x
URL:

javascript:

document.querySelector('video').playbackRate = 1.5;

Name: 2.0x
URL:

javascript:

document.querySelector('video').playbackRate = 2.0;

References:

  1. The main answer by Jeremy Visser
  2. Copied from my GitHub gist here: https://gist.github.com/ElectricRCAircraftGuy/0a788876da1386ca0daecbe78b4feb44#other-bookmarklets
    1. Get other bookmarklets here too, such as for aiding you on GitHub.

Is there an arraylist in Javascript?

There is no ArrayList in javascript.

There is however ArrayECMA 5.1 which has similar functionality to an "ArrayList". The majority of this answer is taken verbatim from the HTML rendering of Ecma-262 Edition 5.1, The ECMAScript Language Specification.

Defined arrays have the following methods available:

  • .toString ( )
  • .toLocaleString ( )
  • .concat ( [ item1 [ , item2 [ , … ] ] ] )
    When the concat method is called with zero or more arguments item1, item2, etc., it returns an array containing the array elements of the object followed by the array elements of each argument in order.
  • .join (separator)
    The elements of the array are converted to Strings, and these Strings are then concatenated, separated by occurrences of the separator. If no separator is provided, a single comma is used as the separator.
  • .pop ( )
    The last element of the array is removed from the array and returned.
  • .push ( [ item1 [ , item2 [ , … ] ] ] )
    The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call."
  • .reverse ( )
    The elements of the array are rearranged so as to reverse their order. The object is returned as the result of the call.
  • .shift ( )
    The first element of the array is removed from the array and returned."
  • .slice (start, end)
    The slice method takes two arguments, start and end, and returns an array containing the elements of the array from element start up to, but not including, element end (or through the end of the array if end is undefined).
  • .sort (comparefn)
    The elements of this array are sorted. The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.
  • .splice (start, deleteCount [ , item1 [ , item2 [ , … ] ] ] )
    When the splice method is called with two or more arguments start, deleteCount and (optionally) item1, item2, etc., the deleteCount elements of the array starting at array index start are replaced by the arguments item1, item2, etc. An Array object containing the deleted elements (if any) is returned.
  • .unshift ( [ item1 [ , item2 [ , … ] ] ] )
    The arguments are prepended to the start of the array, such that their order within the array is the same as the order in which they appear in the argument list.
  • .indexOf ( searchElement [ , fromIndex ] )
    indexOf compares searchElement to the elements of the array, in ascending order, using the internal Strict Equality Comparison Algorithm (11.9.6), and if found at one or more positions, returns the index of the first such position; otherwise, -1 is returned.
  • .lastIndexOf ( searchElement [ , fromIndex ] )
    lastIndexOf compares searchElement to the elements of the array in descending order using the internal Strict Equality Comparison Algorithm (11.9.6), and if found at one or more positions, returns the index of the last such position; otherwise, -1 is returned.
  • .every ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value true or false. every calls callbackfn once for each element present in the array, in ascending order, until it finds one where callbackfn returns false. If such an element is found, every immediately returns false. Otherwise, if callbackfn returned true for all elements, every will return true.
  • .some ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value true or false. some calls callbackfn once for each element present in the array, in ascending order, until it finds one where callbackfn returns true. If such an element is found, some immediately returns true. Otherwise, some returns false.
  • .forEach ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each element present in the array, in ascending order.
  • .map ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments. map calls callbackfn once for each element in the array, in ascending order, and constructs a new Array from the results.
  • .filter ( callbackfn [ , thisArg ] )
    callbackfn should be a function that accepts three arguments and returns a value that is coercible to the Boolean value true or false. filter calls callbackfn once for each element in the array, in ascending order, and constructs a new array of all the values for which callbackfn returns true.
  • .reduce ( callbackfn [ , initialValue ] )
    callbackfn should be a function that takes four arguments. reduce calls the callback, as a function, once for each element present in the array, in ascending order.
  • .reduceRight ( callbackfn [ , initialValue ] )
    callbackfn should be a function that takes four arguments. reduceRight calls the callback, as a function, once for each element present in the array, in descending order.

and also the length property.

AngularJS - Trigger when radio button is selected

Another approach is using Object.defineProperty to set valueas a getter setter property in the controller scope, then each change on the value property will trigger a function specified in the setter:

The HTML file:

<input type="radio" ng-model="value" value="one"/>
<input type="radio" ng-model="value" value="two"/>
<input type="radio" ng-model="value" value="three"/>

The javascript file:

var _value = null;
Object.defineProperty($scope, 'value', {
  get: function () {
    return _value;
  },         
  set: function (value) {
    _value = value;
    someFunction();
  }
});

see this plunker for the implementation

SQL sum with condition

Try this instead:

SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)

Explanation

Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:

The CASE expression has two formats:

  • The simple CASE expression compares an expression to a set of simple expressions to determine the result.
  • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

You want the searched CASE expression syntax:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.

Java 8 stream reverse order

How about reversing the Collection backing the stream prior?

import java.util.Collections;
import java.util.List;

public void reverseTest(List<Integer> sampleCollection) {
    Collections.reverse(sampleCollection); // remember this reverses the elements in the list, so if you want the original input collection to remain untouched clone it first.

    sampleCollection.stream().forEach(item -> {
      // you op here
    });
}

Determine the number of lines within a text file

You can launch the "wc.exe" executable (comes with UnixUtils and does not need installation) run as an external process. It supports different line count methods (like unix vs mac vs windows).

Twitter bootstrap modal-backdrop doesn't disappear

FYI in case someone runs into this still... I've spent about 3 hours to discover that the best way to do it is as follows:

$("#my-modal").modal("hide");
$("#my-modal").hide();
$('.modal-backdrop').hide();
$("body").removeClass("modal-open");

That function to close the modal is very unintuitive.

React Native: How to select the next TextInput after pressing the "next" keyboard button?

import React, { useState, useEffect, useRef, } from 'react';

const OTP = (props) => {



    const OTP = [];
    const ref_input = [];
    ref_input[0] = useRef();
    ref_input[1] = useRef();
    ref_input[2] = useRef();
    ref_input[3] = useRef();

    const focusNext = (text, index) => {
        if (index < ref_input.length - 1 && text) {
            ref_input[index + 1].current.focus();
        }
        if (index == ref_input.length - 1) {
            ref_input[index].current.blur();
        }
        OTP[index] = text;
    }
    const focusPrev = (key, index) => {
        if (key === "Backspace" && index !== 0) {
            ref_input[index - 1].current.focus();
        }
    }

    return (
        <SafeAreaView>
            <View>
                
                    <ScrollView contentInsetAdjustmentBehavior="automatic" showsVerticalScrollIndicator={false}>
                        <View style={loginScreenStyle.titleWrap}>
                            <Title style={loginScreenStyle.titleHeading}>Verify OTP</Title>
                            <Subheading style={loginScreenStyle.subTitle}>Enter the 4 digit code sent to your mobile number</Subheading>
                        </View>
                        <View style={loginScreenStyle.inputContainer}>
                            <TextInput
                                mode="flat"
                                selectionColor={Colors.primaryColor}
                                underlineColorAndroid="transparent"
                                textAlign='center'
                                maxLength={1}
                                keyboardType='numeric'
                                style={formScreenStyle.otpInputStyle}
                                autoFocus={true}
                                returnKeyType="next"
                                ref={ref_input[0]}
                                onChangeText={text => focusNext(text, 0)}
                                onKeyPress={e => focusPrev(e.nativeEvent.key, 0)}
                            />
                            <TextInput
                                mode="flat"
                                selectionColor={Colors.primaryColor}
                                underlineColorAndroid="transparent"
                                textAlign='center'
                                maxLength={1}
                                keyboardType='numeric'
                                style={formScreenStyle.otpInputStyle}
                                ref={ref_input[1]}
                                onChangeText={text => focusNext(text, 1)}
                                onKeyPress={e => focusPrev(e.nativeEvent.key, 1)}
                            />
                            <TextInput
                                mode="flat"
                                selectionColor={Colors.primaryColor}
                                underlineColorAndroid="transparent"
                                textAlign='center'
                                maxLength={1}
                                keyboardType='numeric'
                                style={formScreenStyle.otpInputStyle}
                                ref={ref_input[2]}
                                onChangeText={text => focusNext(text, 2)}
                                onKeyPress={e => focusPrev(e.nativeEvent.key, 2)}
                            />
                            <TextInput
                                mode="flat"
                                selectionColor={Colors.primaryColor}
                                underlineColorAndroid="transparent"
                                textAlign='center'
                                maxLength={1}
                                keyboardType='numeric'
                                style={formScreenStyle.otpInputStyle}
                                ref={ref_input[3]}
                                onChangeText={text => focusNext(text, 3)}
                                onKeyPress={e => focusPrev(e.nativeEvent.key, 3)}
                            />

                        </View>
                    </ScrollView>
            </View>
        </SafeAreaView >
    )
}

export default OTP;

Vba macro to copy row from table if value in table meets condition

Selects are slow and unnescsaary. The following code will be far faster:

Sub CopyRowsAcross() 
Dim i As Integer 
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1") 
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2") 

For i = 2 To ws1.Range("B65536").End(xlUp).Row 
    If ws1.Cells(i, 2) = "Your Critera" Then ws1.Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1) 
Next i 
End Sub 

is there a css hack for safari only NOT chrome?

I like to use the following method:

var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
if (isSafari) { 
  $('head').append('<link rel="stylesheet" type="text/css" href="path/to/safari.css">') 
};

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.

To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.


Prophylactic measures to prevent you getting the error again

The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.

Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.


Common syntactic mistakes that generate these errors

Mismatched parentheses, braces or brackets

If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.

{}}
## Error: unexpected '}' in "{}}"
{{}} # OK

Missing * when doing multiplication

This is a common mistake by mathematicians.

5x
Error: unexpected symbol in "5x"
5*x # OK

Not wrapping if, for, or return values in parentheses

This is a common mistake by MATLAB users. In R, if, for, return, etc., are functions, so you need to wrap their contents in parentheses.

if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK

Not using multiple lines for code

Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.

x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK

else starting on a new line

In an if-else statement, the keyword else must appear on the same line as the end of the if block.

if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"    
if(TRUE) 1 else 2 # OK
if(TRUE) 
{
  1
} else            # also OK
{
  2
}

= instead of ==

= is used for assignment and giving values to function arguments. == tests two values for equality.

if(x = 0) {}
## Error: unexpected '=' in "if(x ="    
if(x == 0) {} # OK

Missing commas between arguments

When calling a function, each argument must be separated by a comma.

c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK

Not quoting file paths

File paths are just strings. They need to be wrapped in double or single quotes.

path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK

Quotes inside strings

This is a common problem when trying to pass quoted values to the shell via system, or creating quoted xPath or sql queries.

Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.

"x"y"
## Error: unexpected symbol in ""x"y"   
"x\"y" # OK
'x"y'  # OK  

Using curly quotes

So-called "smart" quotes are not so smart for R programming.

path.expand(“~”)
## Error: unexpected input in "path.expand(“"    
path.expand("~") # OK

Using non-standard variable names without backquotes

?make.names describes what constitutes a valid variable name. If you create a non-valid variable name (using assign, perhaps), then you need to access it with backquotes,

assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK

This also applies to column names in data frames created with check.names = FALSE.

dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y`   # also OK

It also applies when passing operators and other special values to functions. For example, looking up help on %in%.

?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK

Sourcing non-R code

The source function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table.

source(textConnection("x y"))
## Error in source(textConnection("x y")) : 
##   textConnection("x y"):1:3: unexpected symbol
## 1: x y
##       ^

Corrupted RStudio desktop file

RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.


Using expression without paste in mathematical plot annotations

When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath page. Otherwise the contents should be contained inside a call to paste.

plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK

Label encoding across multiple columns in scikit-learn

import pandas as pd
from sklearn.preprocessing import LabelEncoder

train=pd.read_csv('.../train.csv')

#X=train.loc[:,['waterpoint_type_group','status','waterpoint_type','source_class']].values
# Create a label encoder object 
def MultiLabelEncoder(columnlist,dataframe):
    for i in columnlist:

        labelencoder_X=LabelEncoder()
        dataframe[i]=labelencoder_X.fit_transform(dataframe[i])
columnlist=['waterpoint_type_group','status','waterpoint_type','source_class','source_type']
MultiLabelEncoder(columnlist,train)

Here i am reading a csv from location and in function i am passing the column list i want to labelencode and the dataframe I want to apply this.

How do I request and receive user input in a .bat and use it to run a certain program?

Depending on the version of Windows you might find the use of the "Choice" option to be helpful. It is not supported in most if not all x64 versions as far as I can tell. A handy substitution called Choice.vbs along with examples of use can be found on SourceForge under the name Choice.zip

EditText, inputType values (xml)

Supplemental answer

Here is how the standard keyboard behaves for each of these input types.

enter image description here

See this answer for more details.

How can I find the first and last date in a month using PHP?

The easiest way is to use date, which lets you mix hard-coded values with ones extracted from a timestamp. If you don't give a timestamp, it assumes the current date and time.

// Current timestamp is assumed, so these find first and last day of THIS month
$first_day_this_month = date('m-01-Y'); // hard-coded '01' for first day
$last_day_this_month  = date('m-t-Y');

// With timestamp, this gets last day of April 2010
$last_day_april_2010 = date('m-t-Y', strtotime('April 21, 2010'));

date() searches the string it's given, like 'm-t-Y', for specific symbols, and it replaces them with values from its timestamp. So we can use those symbols to extract the values and formatting that we want from the timestamp. In the examples above:

  • Y gives you the 4-digit year from the timestamp ('2010')
  • m gives you the numeric month from the timestamp, with a leading zero ('04')
  • t gives you the number of days in the timestamp's month ('30')

You can be creative with this. For example, to get the first and last second of a month:

$timestamp    = strtotime('February 2012');
$first_second = date('m-01-Y 00:00:00', $timestamp);
$last_second  = date('m-t-Y 12:59:59', $timestamp); // A leap year!

See http://php.net/manual/en/function.date.php for other symbols and more details.

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

How to add custom html attributes in JSX

You can add an attribute using ES6 spread operator, e.g.

let myAttr = {'data-attr': 'value'}

and in render method:

<MyComponent {...myAttr} />

ReactJS: "Uncaught SyntaxError: Unexpected token <"

UPDATE -- use this instead:

<script type="text/babel" src="./lander.js"></script>

Add type="text/jsx" as an attribute of the script tag used to include the JavaScript file that must be transformed by JSX Transformer, like that:

<script type="text/jsx" src="./lander.js"></script>

Then you can use MAMP or some other service to host the page on localhost so that all of the inclusions work, as discussed here.

Thanks for all the help everyone!

How to jQuery clone() and change id?

This is the simplest solution working for me.

$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");

Connecting to Postgresql in a docker container from outside

I know this is late, if you used docker-compose like @Martin

These are the snippets that helped me connect to psql inside the container

docker-compose run db bash

root@de96f9358b70:/# psql -h db -U root -d postgres_db

I cannot comment because I don't have 50 reputation. So hope this helps.

How to redirect Valgrind's output to a file?

In addition to the other answers (particularly by Lekakis), some string replacements can also be used in the option --log-file= as elaborated in the Valgrind's user manual.

Four replacements were available at the time of writing:

  • %p: Prints the current process ID
    • valgrind --log-file="myFile-%p.dat" <application-name>
  • %n: Prints file sequence number unique for the current process
    • valgrind --log-file="myFile-%p-%n.dat" <application-name>
  • %q{ENV}: Prints contents of the environment variable ENV
    • valgrind --log-file="myFile-%q{HOME}.dat" <application-name>
  • %%: Prints %
    • valgrind --log-file="myFile-%%.dat" <application-name>

"for loop" with two variables?

There's two possible questions here: how can you iterate over those variables simultaneously, or how can you loop over their combination.

Fortunately, there's simple answers to both. First case, you want to use zip.

x = [1, 2, 3]
y = [4, 5, 6]

for i, j in zip(x, y):
   print(str(i) + " / " + str(j))

will output

1 / 4
2 / 5
3 / 6

Remember that you can put any iterable in zip, so you could just as easily write your exmple like:

for i, j in zip(range(x), range(y)):
    # do work here.

Actually, just realised that won't work. It would only iterate until the smaller range ran out. In which case, it sounds like you want to iterate over the combination of loops.

In the other case, you just want a nested loop.

for i in x:
    for j in y:
        print(str(i) + " / " + str(j))

gives you

1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...

You can also do this as a list comprehension.

[str(i) + " / " + str(j) for i in range(x) for j in range(y)]

Hope that helps.

Android Studio error: "Environment variable does not point to a valid JVM installation"

In my case, I had the whole variable for JAVA_HOME in quotes. I just had to remove the quotes and then it worked fine.

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

Group array items using object

I like to use the Map constructor callback for creating the groups (map keys). The second step is to populate the values of that map, and finally to extract the map's data in the desired output format:

_x000D_
_x000D_
let myArray = [{group: "one", color: "red"},{group: "two", color: "blue"},
               {group: "one", color: "green"},{group: "one", color: "black"}];

let map = new Map(myArray.map(({group}) => [group, { group, color: [] }]));
for (let {group, color} of myArray) map.get(group).color.push(color);
let result = [...map.values()];

console.log(result);

 
_x000D_
_x000D_
_x000D_

Cloning a private Github repo

In addition to MK Yung's answer: make sure you add the public key for wherever you're deploying to the deploy keys for the repo, if you don't want to receive a 403 Forbidden response.

MySQL Trigger - Storing a SELECT in a variable

As far I think I understood your question I believe that u can simply declare your variable inside "DECLARE" and then after the "begin" u can use 'select into " you variable" ' statement. the code would look like this:

DECLARE
YourVar  varchar(50);
begin 
select ID into YourVar  from table
where ...

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

I had the same problem: I have a 64 bit Windows and when I typed "java -version" in CMD-Console i received the same Error message. Try to start a 64bit-cmd(C:\Windows\SysWOW64\cmd.exe) and you will see, it works there ;)

Position Absolute + Scrolling

You need to wrap the text in a div element and include the absolutely positioned element inside of it.

<div class="container">
    <div class="inner">
        <div class="full-height"></div>
        [Your text here]
    </div>
</div>

Css:

.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }

Setting the inner div's position to relative makes the absolutely position elements inside of it base their position and height on it rather than on the .container div, which has a fixed height. Without the inner, relatively positioned div, the .full-height div will always calculate its dimensions and position based on .container.

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  border: solid 1px red;_x000D_
  height: 256px;_x000D_
  width: 256px;_x000D_
  overflow: auto;_x000D_
  float: left;_x000D_
  margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  position: relative;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 128px;_x000D_
  bottom: 0;_x000D_
  height: 100%;_x000D_
  background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="full-height">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="inner">_x000D_
    <div class="full-height">_x000D_
    </div>_x000D_
_x000D_
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
    maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
    cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
    quidem._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/M5cTN/

Postgres Error: More than one row returned by a subquery used as an expression

Technically, to repair your statement, you can add LIMIT 1 to the subquery to ensure that at most 1 row is returned. That would remove the error, your code would still be nonsense.

... 'SELECT store_key FROM store LIMIT 1' ...

Practically, you want to match rows somehow instead of picking an arbitrary row from the remote table store to update every row of your local table customer.
Your rudimentary question doesn't provide enough details, so I am assuming a text column match_name in both tables (and UNIQUE in store) for the sake of this example:

... 'SELECT store_key FROM store
     WHERE match_name = ' || quote_literal(customer.match_name)  ...

But that's an extremely expensive way of doing things.

Ideally, you should completely rewrite the statement.

UPDATE customer c
SET    customer_id = s.store_key
FROM   dblink('port=5432, dbname=SERVER1 user=postgres password=309245'
             ,'SELECT match_name, store_key FROM store')
       AS s(match_name text, store_key integer)
WHERE c.match_name = s.match_name
AND   c.customer_id IS DISTINCT FROM s.store_key;

This remedies a number of problems in your original statement.

  • Obviously, the basic problem leading to your error is fixed.

  • It's almost always better to join in additional relations in the FROM clause of an UPDATE statement than to run correlated subqueries for every individual row.

  • When using dblink, the above becomes a thousand times more important. You do not want to call dblink() for every single row, that's extremely expensive. Call it once to retrieve all rows you need.

  • With correlated subqueries, if no row is found in the subquery, the column gets updated to NULL, which is almost always not what you want.
    In my updated form, the row only gets updated if a matching row is found. Else, the row is not touched.

  • Normally, you wouldn't want to update rows, when nothing actually changes. That's expensively doing nothing (but still produces dead rows). The last expression in the WHERE clause prevents such empty updates:

     AND   c.customer_id IS DISTINCT FROM sub.store_key
    

Recursively list all files in a directory including files in symlink directories

The -L option to ls will accomplish what you want. It dereferences symbolic links.

So your command would be:

ls -LR

You can also accomplish this with

find -follow

The -follow option directs find to follow symbolic links to directories.

On Mac OS X use

find -L

as -follow has been deprecated.

Way to create multiline comments in Bash?

Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'

How to list files in an android directory?

In order to access the files, the permissions must be given in the manifest file.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Try this:

String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
    Log.d("Files", "FileName:" + files[i].getName());
}

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

Swift 4:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    var height = super.tableView(tableView, heightForRowAt: indexPath)
    if (indexPath.row == HIDDENROW) {
        height = 0.0
    }
    return height
}

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

C# convert int to string with padding zeros?

Here's a good example:

int number = 1;
//D4 = pad with 0000
string outputValue = String.Format("{0:D4}", number);
Console.WriteLine(outputValue);//Prints 0001
//OR
outputValue = number.ToString().PadLeft(4, '0');
Console.WriteLine(outputValue);//Prints 0001 as well

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

You need a SMPT Server in order for

... mail($to,$subject,$message,$headers);

to work.

You could try light weight SMTP servers like xmailer

adding text to an existing text element in javascript via DOM

The method .appendChild() is used to add a new element NOT add text to an existing element.

Example:

var p = document.createElement("p");
document.body.appendChild(p);

Reference: Mozilla Developer Network

The standard approach for this is using .innerHTML(). But if you want a alternate solution you could try using element.textContent.

Example:

document.getElementById("foo").textContent = "This is som text";

Reference: Mozilla Developer Network

How ever this is only supported in IE 9+

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

Select last row in MySQL

You can use an OFFSET in a LIMIT command:

SELECT * FROM aTable LIMIT 1 OFFSET 99

in case your table has 100 rows this return the last row without relying on a primary_key

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

Converting byte array to string in javascript

Too late to answer but if your input is in form of ASCII bytes, then you could try this solution:

function convertArrToString(rArr){
 //Step 1: Convert each element to character
 let tmpArr = new Array();
 rArr.forEach(function(element,index){
    tmpArr.push(String.fromCharCode(element));
});
//Step 2: Return the string by joining the elements
return(tmpArr.join(""));
}

function convertArrToHexNumber(rArr){
  return(parseInt(convertArrToString(rArr),16));
}

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

How do I set a variable to the output of a command in Bash?

Some may find this useful. Integer values in variable substitution, where the trick is using $(()) double brackets:

N=3
M=3
COUNT=$N-1
ARR[0]=3
ARR[1]=2
ARR[2]=4
ARR[3]=1

while (( COUNT < ${#ARR[@]} ))
do
  ARR[$COUNT]=$((ARR[COUNT]*M))
  (( COUNT=$COUNT+$N ))
done

How can a add a row to a data frame in R?

Not terribly elegant, but:

data.frame(rbind(as.matrix(df), as.matrix(de)))

From documentation of the rbind function:

For rbind column names are taken from the first argument with appropriate names: colnames for a matrix...

Peak memory usage of a linux/unix process

(This is an already answered, old question.. but just for the record :)

I was inspired by Yang's script, and came up with this small tool, named memusg. I simply increased the sampling rate to 0.1 to handle much short living processes. Instead of monitoring a single process, I made it measure rss sum of the process group. (Yeah, I write lots of separate programs that work together) It currently works on Mac OS X and Linux. The usage had to be similar to that of time:

memusg ls -alR / >/dev/null

It only shows the peak for the moment, but I'm interested in slight extensions for recording other (rough) statistics.

It's good to have such simple tool for just taking a look before we start any serious profiling.

Override body style for content in an iframe

Perhaps it's changed now, but I have used a separate stylesheet with this element:

.feedEkList iframe
{
max-width: 435px!important;
width: 435px!important;
height: 320px!important;
}

to successfully style embedded youtube iframes...see the blog posts on this page.

How can I force a long string without any blank to be wrapped?

for block elements:

_x000D_
_x000D_
<textarea style="width:100px; word-wrap:break-word;">_x000D_
  ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

for inline elements:

_x000D_
_x000D_
<span style="width:100px; word-wrap:break-word; display:inline-block;"> _x000D_
   ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</span>
_x000D_
_x000D_
_x000D_

PHP sessions default timeout

http://php.net/session.gc-maxlifetime

session.gc_maxlifetime = 1440
(1440 seconds = 24 minutes)

How to create a DB for MongoDB container on start up?

My answer is based on the one provided by @x-yuri; but my scenario it's a little bit different. I wanted an image containing the script, not bind without needing to bind-mount it.

mongo-init.sh -- don't know whether or not is need but but I ran chmod +x mongo-init.sh also:

#!/bin/bash
# https://stackoverflow.com/a/53522699
# https://stackoverflow.com/a/37811764
mongo -- "$MONGO_INITDB_DATABASE" <<EOF
  var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
  var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
  var user = '$MONGO_INITDB_USERNAME';
  var passwd = '$MONGO_INITDB_PASSWORD';

  var admin = db.getSiblingDB('admin');

  admin.auth(rootUser, rootPassword);
  db.createUser({
    user: user,
    pwd: passwd,
    roles: [
      {
        role: "root",
        db: "admin"
      }
    ]
  });
EOF

Dockerfile:

FROM mongo:3.6

COPY mongo-init.sh /docker-entrypoint-initdb.d/mongo-init.sh

CMD [ "/docker-entrypoint-initdb.d/mongo-init.sh" ]

docker-compose.yml:

version: '3'

services:
    mongodb:
        build: .
        container_name: mongodb-test
        environment:
            - MONGO_INITDB_ROOT_USERNAME=root
            - MONGO_INITDB_ROOT_PASSWORD=example
            - MONGO_INITDB_USERNAME=myproject
            - MONGO_INITDB_PASSWORD=myproject
            - MONGO_INITDB_DATABASE=myproject

    myproject:
        image: myuser/myimage
        restart: on-failure
        container_name: myproject
        environment:
            - DB_URI=mongodb
            - DB_HOST=mongodb-test
            - DB_NAME=myproject
            - DB_USERNAME=myproject
            - DB_PASSWORD=myproject
            - DB_OPTIONS=
            - DB_PORT=27017            
        ports:
            - "80:80"

After that, I went ahead and publish this Dockefile as an image to use in other projects.

note: without adding the CMD it mongo throws: unbound variable error

How to convert all tables in database to one collation?

If you want a copy-paste bash script:

var=$(mysql -e 'SELECT CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8 COLLATE utf8_czech_ci;") AS execTabs FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="zabbix" AND TABLE_TYPE="BASE TABLE"' -uroot -p )

var+='ALTER DATABASE zabbix CHARACTER SET utf8 COLLATE utf8_general_ci;'

echo $var | cut -d " " -f2- | mysql -uroot -p zabbix

Change zabbix to your database name.

JavaScript split String with white space

You can just split on the word boundary using \b. See MDN

"\b: Matches a zero-width word boundary, such as between a letter and a space."

You should also make sure it is followed by whitespace \s. so that strings like "My car isn't red" still work:

var stringArray = str.split(/\b(\s)/);

The initial \b is required to take multiple spaces into account, e.g. my car is red

EDIT: Added grouping

How to export private key from a keystore of self-signed certificate

http://anandsekar.github.io/exporting-the-private-key-from-a-jks-keystore/

public class ExportPrivateKey {
        private File keystoreFile;
        private String keyStoreType;
        private char[] password;
        private String alias;
        private File exportedFile;

        public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
                try {
                        Key key=keystore.getKey(alias,password);
                        if(key instanceof PrivateKey) {
                                Certificate cert=keystore.getCertificate(alias);
                                PublicKey publicKey=cert.getPublicKey();
                                return new KeyPair(publicKey,(PrivateKey)key);
                        }
                } catch (UnrecoverableKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyStoreException e) {
        }
        return null;
        }

        public void export() throws Exception{
                KeyStore keystore=KeyStore.getInstance(keyStoreType);
                BASE64Encoder encoder=new BASE64Encoder();
                keystore.load(new FileInputStream(keystoreFile),password);
                KeyPair keyPair=getPrivateKey(keystore,alias,password);
                PrivateKey privateKey=keyPair.getPrivate();
                String encoded=encoder.encode(privateKey.getEncoded());
                FileWriter fw=new FileWriter(exportedFile);
                fw.write(“—–BEGIN PRIVATE KEY—–\n“);
                fw.write(encoded);
                fw.write(“\n“);
                fw.write(“—–END PRIVATE KEY—–”);
                fw.close();
        }


        public static void main(String args[]) throws Exception{
                ExportPrivateKey export=new ExportPrivateKey();
                export.keystoreFile=new File(args[0]);
                export.keyStoreType=args[1];
                export.password=args[2].toCharArray();
                export.alias=args[3];
                export.exportedFile=new File(args[4]);
                export.export();
        }
}

Zero an array in C code

int arr[20] = {0};

C99 [$6.7.8/21]

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.


HTML-Tooltip position relative to mouse pointer

You can use jQuery UI plugin, following are reference URLs

Set track to TRUE for Tooltip position relative to mouse pointer eg.

_x000D_
_x000D_
$('.tooltip').tooltip({ track: true });
_x000D_
_x000D_
_x000D_

UnicodeEncodeError: 'charmap' codec can't encode characters

I fixed it by adding .encode("utf-8") to soup.

That means that print(soup) becomes print(soup.encode("utf-8")).

Add new field to every document in a MongoDB collection

Pymongo 3.9+

update() is now deprecated and you should use replace_one(), update_one(), or update_many() instead.

In my case I used update_many() and it solved my issue:

db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)

From documents

update_many(filter, update, upsert=False, array_filters=None, bypass_document_validation=False, collation=None, session=None)


filter: A query that matches the documents to update.

update: The modifications to apply.

upsert (optional): If True, perform an insert if no documents match the filter.

bypass_document_validation (optional): If True, allows the write to opt-out of document level validation. Default is False.

collation (optional): An instance of Collation. This option is only supported on MongoDB 3.4 and above.

array_filters (optional): A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+.

session (optional): a ClientSession.

How to send an email with Python?

Make sure you have granted permission for both Sender and Receiver to send email and receive email from Unknown sources(External Sources) in Email Account.

import smtplib

#Ports 465 and 587 are intended for email client to email server communication - sending email
server = smtplib.SMTP('smtp.gmail.com', 587)

#starttls() is a way to take an existing insecure connection and upgrade it to a secure connection using SSL/TLS.
server.starttls()

#Next, log in to the server
server.login("#email", "#password")

msg = "Hello! This Message was sent by the help of Python"

#Send the mail
server.sendmail("#Sender", "#Reciever", msg)

enter image description here

Decimal to Hexadecimal Converter in Java

Another possible solution:

public String DecToHex(int dec){
  char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
              'A', 'B', 'C', 'D', 'E', 'F'};
  String hex = "";
  while (dec != 0) {
      int rem = dec % 16;
      hex = hexDigits[rem] + hex;
      dec = dec / 16;
  }
  return hex;
}

Display a loading bar before the entire page is loaded

I've recently made a page loader in vanilla .js for a project, just wanted to share it as all the other answers are jQuery based. It's a plug and play, one-liner.

It automatically creates a <div> tag prepended to the <body>, with a <svg> loader. If you want to customize the color you just have to update the t variable at the beginning of the script.

var t="#106CF6",u=document.querySelector("*"),s=document.createElement("style"),a=document.createElement("aside"),m="http://www.w3.org/2000/svg",g=document.createElementNS(m,"svg"),c=document.createElementNS(m,"circle");document.head.appendChild(s),(s.innerHTML="#sailor {background:"+t+";color:"+t+";display:flex;align-items:center;justify-content:center;position:fixed;top:0;height:100vh;width:100vw;z-index:2147483647}@keyframes swell{to{transform:rotate(360deg)}}#sailor svg{animation:.3s swell infinite linear}"),a.setAttribute("id","sailor"),document.body.prepend(a),g.setAttribute("height","50"),g.setAttribute("filter","brightness(175%)"),g.setAttribute("viewBox","0 0 100 100"),a.prepend(g),c.setAttribute("cx","50"),c.setAttribute("cy","50"),c.setAttribute("r","35"),c.setAttribute("fill","none"),c.setAttribute("stroke","currentColor"),c.setAttribute("stroke-dasharray","165 57"),c.setAttribute("stroke-width","10"),g.prepend(c),(u.style.pointerEvents="none"),(u.style.userSelect="none"),(u.style.cursor="wait"),window.addEventListener("load",function(){setTimeout(function(){(u.style.pointerEvents=""),(u.style.userSelect=""),(u.style.cursor="");a.remove()},100)})

You can see the full project and documentation on the GitHub