Programs & Examples On #Android fonts

There are different fonts available to use programmatically and also using the device setting, Generally programmers do use fonts in a way that keeping the font file in assets folder and then passing the font as resource to textviews.

How to set default font family for entire Android app

Try this library, its lightweight and easy to implement

https://github.com/sunnag7/FontStyler

<com.sunnag.fontstyler.FontStylerView
              android:textStyle="bold"
              android:text="@string/about_us"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingTop="8dp"
              app:fontName="Lato-Bold"
              android:textSize="18sp"
              android:id="@+id/textView64" />

How to add external fonts to android application

The easiest way to accomplish this is to package the desired font(s) with your application. To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets. You might, for example, create assets/fonts/ and put your TTF files in there.

Then, you need to tell your widgets to use that font. Unfortunately, you can no longer use layout XML for this, since the XML does not know about any fonts you may have tucked away as an application asset. Instead, you need to make the change in Java code, by calling Typeface.createFromAsset(getAssets(), “fonts/HandmadeTypewriter.ttf”), then taking the created Typeface object and passing it to your TextView via setTypeface().

For more reference here is the tutorial where I got this:

http://www.androidguys.com/2008/08/18/fun-with-fonts/

Android - Using Custom Font

  • Open your project and select Project on the top left
  • app --> src --> main
  • right click to main and create directory name it as assets
  • right click to assest and create new directory name it fonts
  • you need to find free fonts like free fonts
  • give it to your Textview and call it in your Activity class
  • copy your fonts inside the fonts folder
  • TextView txt = (TextView) findViewById(R.id.txt_act_spalsh_welcome); Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Aramis Italic.ttf"); txt.setTypeface(font);

name of the font must be correct and have fun

Is it possible to set a custom font for entire of application?

in api 26 with build.gradle 3.0.0 and higher you can create a font directory in res and use this line in your style

<item name="android:fontFamily">@font/your_font</item>

for change build.gradle use this in your build.gradle dependecies

classpath 'com.android.tools.build:gradle:3.0.0'

Compute mean and standard deviation by group for multiple variables in a data.frame

I add the dplyr solution.

set.seed(1)
df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

library(dplyr)
df %>% group_by(ID) %>% summarise_each(funs(mean, sd))

#      ID Obs_1_mean Obs_2_mean Obs_3_mean  Obs_1_sd  Obs_2_sd  Obs_3_sd
#   (int)      (dbl)      (dbl)      (dbl)     (dbl)     (dbl)     (dbl)
# 1     1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
# 2     2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
# 3     3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

Calculate the date yesterday in JavaScript

"Date.now() - 86400000" won't work on the Daylight Saving end day (which has 25 hours that day)

Another option is to use Closure:

var d = new goog.date.Date();
d.add(new goog.date.Interval(0, 0, -1));

Creating java date object from year,month,day

Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use

c.set(year, month - 1, day, 0, 0);  

jQuery creating objects

I actually found a better way using the jQuery approach

var box = {

config:{
 color: 'red'
},

init:function(config){
 $.extend(this.config,config);
}

};

var myBox = box.init({
 color: blue
});

Writing a dict to txt file and reading it back?

Hi there is a way to write and read the dictionary to file you can turn your dictionary to JSON format and read and write quickly just do this :

To write your date:

 import json

 your_dictionary = {"some_date" : "date"}
 f = open('destFile.txt', 'w+')
 f.write(json.dumps(your_dictionary))

and to read your data:

 import json

 f = open('destFile.txt', 'r')
 your_dictionary = json.loads(f.read())

Return Index of an Element in an Array Excel VBA

Here's another way:

Option Explicit

' Just a little test stub. 
Sub Tester()

    Dim pList(500) As Integer
    Dim i As Integer

    For i = 0 To UBound(pList)

        pList(i) = 500 - i

    Next i

    MsgBox "Value 18 is at array position " & FindInArray(pList, 18) & "."
    MsgBox "Value 217 is at array position " & FindInArray(pList, 217) & "."
    MsgBox "Value 1001 is at array position " & FindInArray(pList, 1001) & "."

End Sub

Function FindInArray(pList() As Integer, value As Integer)

    Dim i As Integer
    Dim FoundValueLocation As Integer

    FoundValueLocation = -1

    For i = 0 To UBound(pList)

        If pList(i) = value Then

            FoundValueLocation = i
            Exit For

        End If

    Next i

    FindInArray = FoundValueLocation

End Function

How to read specific lines from a file (by line number)?

You can do this very simply with this syntax that someone already mentioned, but it's by far the easiest way to do it:

inputFile = open("lineNumbers.txt", "r")
lines = inputFile.readlines()
print (lines[0])
print (lines[2])

How can I find the current OS in Python?

I usually use sys.platform (docs) to get the platform. sys.platform will distinguish between linux, other unixes, and OS X, while os.name is "posix" for all of them.

For much more detailed information, use the platform module. This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution.

Get file name from URL

If you are using Spring, there is a helper to handle URIs. Here is the solution:

List<String> pathSegments = UriComponentsBuilder.fromUriString(url).build().getPathSegments();
String filename = pathSegments.get(pathSegments.size()-1);

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

I have just one more thing to say about this. With the same HTTP Error code, you can still have several different errors, as one of them has been posted here at the original question's description. For example: after I've edited the Web.Config file of an ASP.NET project, I had

Error Code 0x8007000d

"Only one <configSections> element allowed. It must be the first child element of the root <configuration> element "

As it says, you must NOT insert your own XML stuff before the <configSections> part of the Web.Config file. After I've inserted my snippet after the end tag of <configSections>, it worked just fine.

What is the difference between DBMS and RDBMS?

DBMS: is a software system that allows Defining, Creation, Querying, Update, and Administration of data stored in data files.

Features:

  • Normal book keeping system, Flat files, MS Excel, FoxPRO, XML, etc.
  • Less or No provision for: Constraints, Security, ACID rules, users, etc.

RDBMS: is a DBMS that is based on Relational model that stores data in tabular form.

  • SQL Server, Sybase, Oracle, MySQL, IBM DB2, MS Access, etc.

Features:

  • Database, with Tables having relations maintained by FK
  • DDL, DML
  • Data Integrity & ACID rules
  • Multiple User Access
  • Backup & Restore
  • Database Administration

Sending images using Http Post

Version 4.3.5 Updated Code

  • httpclient-4.3.5.jar
  • httpcore-4.3.2.jar
  • httpmime-4.3.5.jar

Since MultipartEntity has been deprecated. Please see the code below.

String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);

HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);

if (career != null)
    builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
    builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
    builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
    builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
    builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
    builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
    builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());

post.setEntity(builder.build());

try {
    responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
//  System.out.println("Response from Server ==> " + responseBody);

    JSONObject object = new JSONObject(responseBody);
    Boolean success = object.optBoolean("success");
    String message = object.optString("error");

    if (!success) {
        responseBody = message;
    } else {
        responseBody = "success";
    }

} catch (Exception e) {
    e.printStackTrace();
} finally {
    client.getConnectionManager().shutdown();
}

Default settings Raspberry Pi /etc/network/interfaces

These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

WCF timeout exception detailed investigation

I'm having a very similar problem. In the past, this has been related to serialization problems. If you are still having this problem, can you verify that you can correctly serialize the objects you are returning. Specifically, if you are using Linq-To-Sql objects that have relationships, there are known serialization problems if you put a back reference on a child object to the parent object and mark that back reference as a DataMember.

You can verify serialization by writing a console app that serializes and deserializes your objects using the DataContractSerializer on the server side and whatever serialization methods your client uses. For example, in our current application, we have both WPF and Compact Framework clients. I wrote a console app to verify that I can serialize using a DataContractSerializer and deserialize using an XmlDesserializer. You might try that.

Also, if you are returning Linq-To-Sql objects that have child collections, you might try to ensure that you have eagerly loaded them on the server side. Sometimes, because of lazy loading, the objects being returned are not populated and may cause the behavior you are seeing where the request is sent to the service method multiple times.

If you have solved this problem, I'd love to hear how because I'm stuck with it too. I have verified that my issue is not serialization so I'm at a loss.

UPDATE: I'm not sure if it will help you any but the Service Trace Viewer Tool just solved my problem after 5 days of very similar experience to yours. By setting up tracing and then looking at the raw XML, I found the exceptions that were causing my serialization problems. It was related to Linq-to-SQL objects that occasionally had more child objects than could be successfully serialized. Adding the following to your web.config file should enable tracing:

<sharedListeners>
    <add name="sharedListener"
         type="System.Diagnostics.XmlWriterTraceListener"
         initializeData="c:\Temp\servicetrace.svclog" />
  </sharedListeners>
  <sources>
    <source name="System.ServiceModel" switchValue="Verbose, ActivityTracing" >
      <listeners>
        <add name="sharedListener" />
      </listeners>
    </source>
    <source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
      <listeners>
        <add name="sharedListener" />
      </listeners>
    </source>
  </sources>

The resulting file can be opened with the Service Trace Viewer Tool or just in IE to examine the results.

Failed to load resource: net::ERR_INSECURE_RESPONSE

Offering another potential solution to this error.

If you have a frontend application that makes API calls to the backend, make sure you reference the domain name that the certificate has been issued to.

e.g.

https://example.com/api/etc

and not

https://123.4.5.6/api/etc

In my case, I was making API calls to a secure server with a certificate, but using the IP instead of the domain name. This threw a Failed to load resource: net::ERR_INSECURE_RESPONSE.

SQL Server: Attach incorrect version 661

SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).

The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).

How to set a reminder in Android?

You can use AlarmManager in coop with notification mechanism Something like this:

Intent intent = new Intent(ctx, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
// time of of next reminder. Unix time.
long timeMs =...
if (Build.VERSION.SDK_INT < 19) {
    am.set(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
} else {
    am.setExact(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
}

It starts alarm.

public class ReminderBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(...)
                .setContentTitle(..)
                .setContentText(..);
        Intent intentToFire = new Intent(context, Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentToFire, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        NotificationManagerCompat.from(this);.notify((int) System.currentTimeMillis(), builder.build());
    }
}

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Try using the passive command before using ls.

From FTP client, to check if the FTP server supports passive mode, after login, type quote PASV.

Following are connection examples to a vsftpd server with passive mode on and off

vsftpd with pasv_enable=NO:

# ftp localhost
Connected to localhost.localdomain.
220 (vsFTPd 2.3.5)
Name (localhost:john): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quote PASV
550 Permission denied.
ftp> 

vsftpd with pasv_enable=YES:

# ftp localhost
Connected to localhost.localdomain.
220 (vsFTPd 2.3.5)
Name (localhost:john): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quote PASV
227 Entering Passive Mode (127,0,0,1,173,104).
ftp> 

Retrieving parameters from a URL

The url you are referring is a query type and I see that the request object supports a method called arguments to get the query arguments. You may also want try self.request.get('def') directly to get your value from the object..

Does C# have extension properties?

No, they don't exist.

I know that the C# team was considering them at one point (or at least Eric Lippert was) - along with extension constructors and operators (those may take a while to get your head around, but are cool...) However, I haven't seen any evidence that they'll be part of C# 4.


EDIT: They didn't appear in C# 5, and as of July 2014 it doesn't look like it's going to be in C# 6 either.

Eric Lippert, the Principal Developer on the C# compiler team at Microsoft thru November 2012, blogged about this in October of 2009:

How to find and restore a deleted file in a Git repository

I've got this solution.

  1. Get the id of the commit where the file was deleted using one of the ways below.

    • git log --grep=*word*
    • git log -Sword
    • git log | grep --context=5 *word*
    • git log --stat | grep --context=5 *word* # recommended if you hardly remember anything
  2. You should get something like:

commit bfe68bd117e1091c96d2976c99b3bcc8310bebe7 Author: Alexander Orlov Date: Thu May 12 23:44:27 2011 +0200

replaced deprecated GWT class
- gwtI18nKeySync.sh, an outdated (?, replaced by a Maven goal) I18n generation script

commit 3ea4e3af253ac6fd1691ff6bb89c964f54802302 Author: Alexander Orlov Date: Thu May 12 22:10:22 2011 +0200

3. Now using the commit id bfe68bd117e1091c96d2976c99b3bcc8310bebe7 do:

git checkout bfe68bd117e1091c96d2976c99b3bcc8310bebe7^1 yourDeletedFile.java

As the commit id references the commit where the file was already deleted you need to reference the commit just before bfe68b which you can do by appending ^1. This means: give me the commit just before bfe68b.

How to mark a method as obsolete or deprecated?

Add an annotation to the method using the keyword Obsolete. Message argument is optional but a good idea to communicate why the item is now obsolete and/or what to use instead.
Example:

[System.Obsolete("use myMethodB instead")]
void myMethodA()

Date Comparison using Java

Date long getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}

iterating over each character of a String in ruby 1.8.6 (each_char)

there is really a problem in 1.8.6. and it's ok after this edition

in 1.8.6,you can add this:

requre 'jcode'

Nullable type as a generic parameter possible?

Change the return type to Nullable<T>, and call the method with the non nullable parameter

static void Main(string[] args)
{
    int? i = GetValueOrNull<int>(null, string.Empty);
}


public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
    object columnValue = reader[columnName];

    if (!(columnValue is DBNull))
        return (T)columnValue;

    return null;
}

Using fonts with Rails asset pipeline

Here is a repo the demonstrates serving a custom font with Rails 5.2 that works on Heroku. It goes further and optimizes serving the fonts to be as fast as possible according to https://www.webpagetest.org/

https://github.com/nzoschke/edgecors

To start I picked pieces from answers above. For Rails 5.2+ you shouldn't need extra asset pipeline config.

Asset Pipeline and SCSS

  • Place fonts in app/assets/fonts
  • Place the @font-face declaration in an scss file and use the font-url helper

From app/assets/stylesheets/welcome.scss:

@font-face {
  font-family: 'Inconsolata';
  src: font-url('Inconsolata-Regular.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

body {
  font-family: "Inconsolata";
  font-weight: bold;
}

Serve from CDN with CORS

I'm using CloudFront, added with the Heroku Edge addon.

First configure a CDN prefix and default Cache-Control headers in production.rb:

Rails.application.configure do
  # e.g. https://d1unsc88mkka3m.cloudfront.net
  config.action_controller.asset_host = ENV["EDGE_URL"]

  config.public_file_server.headers = {
    'Cache-Control' => 'public, max-age=31536000'
  }
end

If you try to access the font from the herokuapp.com URL to the CDN URL, you will get a CORS error in your browser:

Access to font at 'https://d1unsc88mkka3m.cloudfront.net/assets/Inconsolata-Regular.ttf' from origin 'https://edgecors.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. edgecors.herokuapp.com/ GET https://d1unsc88mkka3m.cloudfront.net/assets/Inconsolata-Regular.ttf net::ERR_FAILED

So configure CORS to allow access to the font from Heroku to the CDN URL:

module EdgeCors
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2

    config.middleware.insert_after ActionDispatch::Static, Rack::Deflater

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins %w[
          http://edgecors.herokuapp.com
          https://edgecors.herokuapp.com
        ]
        resource "*", headers: :any, methods: [:get, :post, :options]
      end
    end
  end
end

Serve gzip Font Asset

The asset pipeline builds a .ttf.gz file but doesn't serve it. This monkey patch changes the asset pipeline gzip whitelist to a blacklist:

require 'action_dispatch/middleware/static'

ActionDispatch::FileHandler.class_eval do
  private

    def gzip_file_path(path)
      return false if ['image/png', 'image/jpeg', 'image/gif'].include? content_type(path)
      gzip_path = "#{path}.gz"
      if File.exist?(File.join(@root, ::Rack::Utils.unescape_path(gzip_path)))
        gzip_path
      else
        false
      end
    end
end

The ultimate result is a custom font file in app/assets/fonts served from a long-lived CloudFront cache.

How to select the row with the maximum value in each group

Another option is slice

library(dplyr)
group %>%
     group_by(Subject) %>%
     slice(which.max(pt))
#    Subject    pt Event
#    <dbl> <dbl> <dbl>
#1       1     5     2
#2       2    17     2
#3       3     5     2

How to edit log message already committed in Subversion?

I found a nice implementation of the server side pre-rev-prop-change hook at the svnforum: https://www.svnforum.org/forum/opensource-subversion-forums/scripts-contributions/8571-pre-revprop-change-shell-script-allows-commiters-to-change-own-log-within-x-hours

It implements

  • user checking, that is only own commit messages can be edited.
  • Svn admin override; admin can edit anything.
  • time stamp comparison: only commits that are younger than certain time can be edited

Grab it from there and edit at will. I'd rather not copy it here since I am not the original author and there is no copyright notice that would allow me to do it.

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:

>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'

This will almost certainly be faster than the conversion to and from a date.

How to keep the console window open in Visual C++?

Another option:

#ifdef _WIN32
#define MAINRET system("pause");return 0
#else
#define MAINRET return 0
#endif

In main:

int main(int argc, char* argv[]) {
    MAINRET;
}

Remove an item from a dictionary when its key is unknown

A simple comparison between del and pop():

import timeit
code = """
results = {'A': 1, 'B': 2, 'C': 3}
del results['A']
del results['B']
"""
print timeit.timeit(code, number=100000)
code = """
results = {'A': 1, 'B': 2, 'C': 3}
results.pop('A')
results.pop('B')
"""
print timeit.timeit(code, number=100000)

result:

0.0329667857143
0.0451040902256

So, del is faster than pop().

How do I use the lines of a file as arguments of a command?

If all you need to do is to turn file arguments.txt with contents

arg1
arg2
argN

into my_command arg1 arg2 argN then you can simply use xargs:

xargs -a arguments.txt my_command

You can put additional static arguments in the xargs call, like xargs -a arguments.txt my_command staticArg which will call my_command staticArg arg1 arg2 argN

?: ?? Operators Instead Of IF|ELSE

the ?: is the itinerary operator. (believe i spelled that properly) and it's simple to use. as in a boolean predicate ? iftrue : ifalse; But you must have a rvalue/lvalue as in rvalue = predicate ? iftrue: iffalse;

ex int i = x < 7 ? x : 7;

if x was less than 7, i would get assigned x, if not i would be 7.

you can also use it in a return, as in return x < 7 ? x : 7;

again, as above , this would have the same affect.

so, Source = Source == value ? Source : string.Empty; i believe is what your trying to acheive.

Unloading classes in java?

Classloaders can be a tricky problem. You can especially run into problems if you're using multiple classloaders and don't have their interactions clearly and rigorously defined. I think in order to actually be able to unload a class youlre going go have to remove all references to any classes(and their instances) you're trying to unload.

Most people needing to do this type of thing end up using OSGi. OSGi is really powerful and surprisingly lightweight and easy to use,

curl: (6) Could not resolve host: application

In my case, it was a missing line break that added unneeded parameters due to a bad copy and paste.

I followed a guide at https://pytorch.org/docs/stable/notes/windows.html#include-optional-components which looks like this when you copy it right here without any editing:

REM Make sure you have 7z and curl installed.

REM Download MKL files

curl https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z -k -O 7z x -aoa mkl_2020.0.166.7z -omkl

Output:

C:\Users\Admin>curl "https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z" -k -O 7z x
-aoa mkl_2020.0.166.7z -omkl   
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                               Dload  Upload   Total   Spent    Left  Speed 
100  103M  100  103M  0     0  5063k      0  0:00:21  0:00:21 --:--:-- 5629k
0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0curl: (6) Could not resolve host: 7z
0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0curl: (6) Could not resolve host: x 
curl: (6) Could not resolve host: mkl_2020.0.166.7z

There is actually a line break before "7z", with "7z" as the executable (and before, in addition to adding curl to your user PATH, you need to add 7z to the user PATH as well, for example with setx PATH "%PATH%;C:\Program Files\7-Zip\"):

REM Download MKL files

curl https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z -k -O

7z x -aoa mkl_2020.0.166.7z -omkl

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

just write "java -d64 -version" or d32 and if you have It installed it will give a response with current version installed

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I've resolved the issue. It was due to the SQL browser service.

Solution to such problem is one among below -

  • Check the spelling of the SQL Server instance name that is specified in the connection string.

  • Use the SQL Server Surface Area Configuration tool to enable SQL Server to accept remote connections over the TCP or named pipes protocols. For more information about the SQL Server Surface Area Configuration Tool, see Surface Area Configuration for Services and Connections.

  • Make sure that you have configured the firewall on the server instance of SQL Server to open ports for SQL Server and the SQL Server Browser port (UDP 1434).

  • Make sure that the SQL Server Browser service is started on the server.

link - http://www.microsoft.com/products/ee/transform.aspx?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=-1

How do I remove the height style from a DIV using jQuery?

to remove the height:

$('div#someDiv').css('height', '');
$('div#someDiv').css('height', null);

like John pointed out, set height to auto:

$('div#someDiv').css('height', 'auto');

(checked with jQuery 1.4)

Show pop-ups the most elegant way

Based on my experience with AngularJS modals so far I believe that the most elegant approach is a dedicated service to which we can provide a partial (HTML) template to be displayed in a modal.

When we think about it modals are kind of AngularJS routes but just displayed in modal popup.

The AngularUI bootstrap project (http://angular-ui.github.com/bootstrap/) has an excellent $modal service (used to be called $dialog prior to version 0.6.0) that is an implementation of a service to display partial's content as a modal popup.

Maven: Failed to read artifact descriptor

If you're using eclipse, right click on project -> properties -> Maven and make sure that the "Resolve dependencies from workspace projects" is not clicked.

Hope this helps.

How to escape braces (curly brackets) in a format string in .NET

[TestMethod]
public void BraceEscapingTest()
{
    var result = String.Format("Foo {{0}}", "1,2,3");  //"1,2,3" is not parsed
    Assert.AreEqual("Foo {0}", result);

    result = String.Format("Foo {{{0}}}", "1,2,3");
    Assert.AreEqual("Foo {1,2,3}", result);

    result = String.Format("Foo {0} {{bar}}", "1,2,3");
    Assert.AreEqual("Foo 1,2,3 {bar}", result);

    result = String.Format("{{{0:N}}}", 24); //24 is not parsed, see @Guru Kara answer
    Assert.AreEqual("{N}", result);

    result = String.Format("{0}{1:N}{2}", "{", 24, "}");
    Assert.AreEqual("{24.00}", result);

    result = String.Format("{{{0}}}", 24.ToString("N"));
    Assert.AreEqual("{24.00}", result);
}

How to change heatmap.2 color range in R?

I got the color range to be asymmetric simply by changing the symkey argument to FALSE

symm=F,symkey=F,symbreaks=T, scale="none"

Solved the color issue with colorRampPalette with the breaks argument to specify the range of each color, e.g.

colors = c(seq(-3,-2,length=100),seq(-2,0.5,length=100),seq(0.5,6,length=100))

my_palette <- colorRampPalette(c("red", "black", "green"))(n = 299)

Altogether

heatmap.2(as.matrix(SeqCountTable), col=my_palette, 
    breaks=colors, density.info="none", trace="none", 
        dendrogram=c("row"), symm=F,symkey=F,symbreaks=T, scale="none")

builder for HashMap

I had a similar requirement a while back. Its nothing to do with Guava but you can do something like this to be able to cleanly construct a Map using a fluent builder.

Create a base class that extends Map.

public class FluentHashMap<K, V> extends LinkedHashMap<K, V> {
    private static final long serialVersionUID = 4857340227048063855L;

    public FluentHashMap() {}

    public FluentHashMap<K, V> delete(Object key) {
        this.remove(key);
        return this;
    }
}

Then create the fluent builder with methods that suit your needs:

public class ValueMap extends FluentHashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public ValueMap() {}

    public ValueMap withValue(String key, String val) {
        super.put(key, val);
        return this;
    }

... Add withXYZ to suit...

}

You can then implement it like this:

ValueMap map = new ValueMap()
      .withValue("key 1", "value 1")
      .withValue("key 2", "value 2")
      .withValue("key 3", "value 3")

Get current URL with jQuery?

See purl.js. This will really help and can also be used, depending on jQuery. Use it like this:

$.url().param("yourparam");

Most efficient conversion of ResultSet to JSON?

First pre-generate column names, second use rs.getString(i) instead of rs.getString(column_name).

The following is an implementation of this:

    /*
     * Convert ResultSet to a common JSON Object array
     * Result is like: [{"ID":"1","NAME":"Tom","AGE":"24"}, {"ID":"2","NAME":"Bob","AGE":"26"}, ...]
     */
    public static List<JSONObject> getFormattedResult(ResultSet rs) {
        List<JSONObject> resList = new ArrayList<JSONObject>();
        try {
            // get column names
            ResultSetMetaData rsMeta = rs.getMetaData();
            int columnCnt = rsMeta.getColumnCount();
            List<String> columnNames = new ArrayList<String>();
            for(int i=1;i<=columnCnt;i++) {
                columnNames.add(rsMeta.getColumnName(i).toUpperCase());
            }

            while(rs.next()) { // convert each object to an human readable JSON object
                JSONObject obj = new JSONObject();
                for(int i=1;i<=columnCnt;i++) {
                    String key = columnNames.get(i - 1);
                    String value = rs.getString(i);
                    obj.put(key, value);
                }
                resList.add(obj);
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return resList;
    }

How should I copy Strings in Java?

Second case is also inefficient in terms of String pool, you have to explicitly call intern() on return reference to make it intern.

SQL WHERE condition is not equal to?

I was just solving this problem. If you use <> or is not in on a variable, that is null, it will result in false. So instead of <> 1, you must check it like this:

 AND (isdelete is NULL or isdelete = 0)

Why must wait() always be in synchronized block

What is the potential damage if it was possible to invoke wait() outside a synchronized block, retaining it's semantics - suspending the caller thread?

Let's illustrate what issues we would run into if wait() could be called outside of a synchronized block with a concrete example.

Suppose we were to implement a blocking queue (I know, there is already one in the API :)

A first attempt (without synchronization) could look something along the lines below

class BlockingQueue {
    Queue<String> buffer = new LinkedList<String>();

    public void give(String data) {
        buffer.add(data);
        notify();                   // Since someone may be waiting in take!
    }

    public String take() throws InterruptedException {
        while (buffer.isEmpty())    // don't use "if" due to spurious wakeups.
            wait();
        return buffer.remove();
    }
}

This is what could potentially happen:

  1. A consumer thread calls take() and sees that the buffer.isEmpty().

  2. Before the consumer thread goes on to call wait(), a producer thread comes along and invokes a full give(), that is, buffer.add(data); notify();

  3. The consumer thread will now call wait() (and miss the notify() that was just called).

  4. If unlucky, the producer thread won't produce more give() as a result of the fact that the consumer thread never wakes up, and we have a dead-lock.

Once you understand the issue, the solution is obvious: Use synchronized to make sure notify is never called between isEmpty and wait.

Without going into details: This synchronization issue is universal. As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.


A paragraph from the link posted by @Willie summarizes it quite well:

You need an absolute guarantee that the waiter and the notifier agree about the state of the predicate. The waiter checks the state of the predicate at some point slightly BEFORE it goes to sleep, but it depends for correctness on the predicate being true WHEN it goes to sleep. There's a period of vulnerability between those two events, which can break the program.

The predicate that the producer and consumer need to agree upon is in the above example buffer.isEmpty(). And the agreement is resolved by ensuring that the wait and notify are performed in synchronized blocks.


This post has been rewritten as an article here: Java: Why wait must be called in a synchronized block

Jquery how to find an Object by attribute in an Array

One more solution:

function firstOrNull(array, expr) {
  for (var i = 0; i < array.length; i++) {
    if (expr(array[i]))
      return array[i];
    }
  return null;
}

Using: firstOrNull([{ a: 1, b: 2 }, { a: 3, b: 3 }], function(item) { return item.a === 3; });

This function don't executes for each element from the array (it's valuable for large arrays)

Disabling buttons on react native

I was able to fix this by putting a conditional in the style property.

const startQuizDisabled = () => props.deck.cards.length === 0;

<TouchableOpacity
  style={startQuizDisabled() ? styles.androidStartQuizDisable : styles.androidStartQuiz}
  onPress={startQuiz}
  disabled={startQuizDisabled()}
>
  <Text 
    style={styles.androidStartQuizBtn} 
  >Start Quiz</Text>
</TouchableOpacity>

const styles = StyleSheet.create({
androidStartQuiz: {
    marginTop:25,
    backgroundColor: "green",
    padding: 10,
    borderRadius: 5,
    borderWidth: 1
},
androidStartQuizDisable: {
    marginTop:25,
    backgroundColor: "green",
    padding: 10,
    borderRadius: 5,
    borderWidth: 1,
    opacity: 0.4
},
androidStartQuizBtn: {
    color: "white",
    fontSize: 24
}
})

Output array to CSV in Ruby

If anyone is interested, here are some one-liners (and a note on loss of type information in CSV):

require 'csv'

rows = [[1,2,3],[4,5]]                    # [[1, 2, 3], [4, 5]]

# To CSV string
csv = rows.map(&:to_csv).join             # "1,2,3\n4,5\n"

# ... and back, as String[][]
rows2 = csv.split("\n").map(&:parse_csv)  # [["1", "2", "3"], ["4", "5"]]

# File I/O:
filename = '/tmp/vsc.csv'

# Save to file -- answer to your question
IO.write(filename, rows.map(&:to_csv).join)

# Read from file
# rows3 = IO.read(filename).split("\n").map(&:parse_csv)
rows3 = CSV.read(filename)

rows3 == rows2   # true
rows3 == rows    # false

Note: CSV loses all type information, you can use JSON to preserve basic type information, or go to verbose (but more easily human-editable) YAML to preserve all type information -- for example, if you need date type, which would become strings in CSV & JSON.

Make Vim show ALL white spaces as a character

highlight search

:set hlsearch 

in .vimrc that is

and search for space tabs and carriage returns

/ \|\t\|\r

or search for all whitespace characters

/\s

of search for all non white space characters (the whitespace characters are not shown, so you see the whitespace characters between words, but not the trailing whitespace characters)

/\S

to show all trailing white space characters - at the end of the line

/\s$

python: urllib2 how to send cookie with urlopen request

Maybe using cookielib.CookieJar can help you. For instance when posting to a page containing a form:

import urllib2
import urllib
from cookielib import CookieJar

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("https://page.com/login.php", data_encoded)
content = response.read()

EDIT:

After Piotr's comment I'll elaborate a bit. From the docs:

The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses. CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.

So whatever requests you make with your CookieJar instance, all cookies will be handled automagically. Kinda like your browser does :)

I can only speak from my own experience and my 99% use-case for cookies is to receive a cookie and then need to send it with all subsequent requests in that session. The code above handles just that, and it does so transparently.

How to generate a Dockerfile from an image?

Update Dec 2018 to BMW's answer

chenzj/dfimage - as described on hub.docker.com regenerates Dockerfile from other images. So you can use it as follows:

docker pull chenzj/dfimage
alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage"
dfimage IMAGE_ID > Dockerfile

How do I search for an object by its ObjectId in the mongo console?

I think you better write something like this:

db.getCollection('Blog').find({"_id":ObjectId("58f6724e97990e9de4f17c23")})

Replace non-numeric with empty string

Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:

phoneNumber  = Regex.Replace(phoneNumber, "\\D", String.Empty);

Android: keeping a background service alive (preventing process death)

Keep your service footprint small, this reduces the probability of Android closing your application. You can't prevent it from being killed because if you could then people could easily create persistent spyware

Bootstrap 4 File Input

For changing the language of the file browser:
As an alternate to what ZimSystem mentioned (override the CSS), a more elegant solution is suggested by the bootstrap docs: build your custom bootstrap styles by adding languages in SCSS
Read about it here: https://getbootstrap.com/docs/4.0/components/forms/#file-browser

Note: you need to have the lang attribute properly set in your document for this to work

For updating the value on file selection:
You could do it with inline js like this:

   <label class="custom-file">
      <input type="file" id="myfile" class="custom-file-input" onchange="$(this).next().after().text($(this).val().split('\\').slice(-1)[0])">
      <span class="custom-file-control"></span>
   </label>

Note: the .split('\\').slice(-1)[0] part removes the C:\fakepath\ prefix

How to create a simple http proxy in node.js?

Here's a more optimized version of Mike's answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing url = and it will automatically set HTTP and HTTPS stuff without manually doing it.

var express = require('express')
var app = express()
var https = require('https');
var http = require('http');
const { response } = require('express');


app.use('/', function(clientRequest, clientResponse) {
    var url;
    url = 'https://www.google.com'
    var parsedHost = url.split('/').splice(2).splice(0, 1).join('/')
    var parsedPort;
    var parsedSSL;
    if (url.startsWith('https://')) {
        parsedPort = 443
        parsedSSL = https
    } else if (url.startsWith('http://')) {
        parsedPort = 80
        parsedSSL = http
    }
    var options = { 
      hostname: parsedHost,
      port: parsedPort,
      path: clientRequest.url,
      method: clientRequest.method,
      headers: {
        'User-Agent': clientRequest.headers['user-agent']
      }
    };  
  
    var serverRequest = parsedSSL.request(options, function(serverResponse) { 
      var body = '';   
      if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) {
        serverResponse.on('data', function(chunk) {
          body += chunk;
        }); 
  
        serverResponse.on('end', function() {
          // Make changes to HTML files when they're done being read.
          body = body.replace(`example`, `Cat!` );
  
          clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers);
          clientResponse.end(body);
        }); 
      }   
      else {
        serverResponse.pipe(clientResponse, {
          end: true
        }); 
        clientResponse.contentType(serverResponse.headers['content-type'])
      }   
    }); 
  
    serverRequest.end();
  });    


  app.listen(3000)
  console.log('Running on 0.0.0.0:3000')

enter image description here

enter image description here

MySQL the right syntax to use near '' at line 1 error

INSERT INTO wp_bp_activity
            (
            user_id,
             component,
             `type`,
             `action`,
             content,
             primary_link,
             item_id,
             secondary_item_id,
             date_recorded,
             hide_sitewide,
             mptt_left,
             mptt_right
             )
             VALUES(
             1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
             )

Core dump file is not generated

If you call daemon() and then daemonize a process, by default the current working directory will change to /. So if your program is a daemon then you should be looking for a core in / directory and not in the directory of the binary.

How to modify JsonNode in Java?

I think you can just cast to ObjectNode and use put method. Like this

ObjectNode o = (ObjectNode) jsonNode; o.put("value", "NO");

how to use concatenate a fixed string and a variable in Python

Try:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]

The + operator is overridden in python to concatenate strings.

How to call a method after a delay in Android

If you use RxAndroid then thread and error handling becomes much easier. Following code executes after a delay

   Observable.timer(delay, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(aLong -> {
           // Execute code here
        }, Throwable::printStackTrace);

Open source PDF library for C/C++ application?

jagpdf seems to be one of them. It is written in C++ but provides a C API.

How to determine if OpenSSL and mod_ssl are installed on Apache2

Usually, when you compile your apache2 server (or install it by packages facility stuff), you can check any directive that're available to be used by tapping this command:

~# $(which httpd) -L | grep SSL # on RHEL/CentOS/Fedora
~# $(which apache2) -L | grep SSL # on Ubuntu/Debian

If you don't see any SSL* directive, it means that you don't have apache2 with mod_ssl compiled.

Hopes it helps ;)

CSS Background image not loading

I'd like to share my debugging process because I was stuck on this issue for at least an hour. Image could not be found when running local host. To add some context, I am styling within a rails app in the following directory:

apps/assets/stylesheets/main.scss

I wanted to render background image in header tag. The following was my original implementation.

header {
    text-align: center;
    background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
              url('../images/header.jpg') no-repeat;
              background-blend-mode: multiply;
              background-size: cover;
}

...as a result I was getting the following error in rails server and the console in Chrome dev tools, respectively:

ActionController::RoutingError (No route matches [GET] "/images/header.jpg")
GET http://localhost:3000/images/header.jpg 404 (Not Found)

I tried different variations of the url:

url('../images/header.jpg') # DID NOT WORK
url('/../images/header.jpg') # DID NOT WORK
url('./../images/header.jpg') # DID NOT WORK

and it still did not work. At that point, I was very confused...I decided to move the image folder from the assets directory (which is the default) to within the stylesheets directory, and tried the following variations of the url:

url('/images/header.jpg') # DID NOT WORK
url('./images/header.jpg') # WORKED
url('images/header.jpg') # WORKED

I no longer got the console and rails server error. But the image still was not showing for some reason. After temporarily giving up, I found out the solution to this was to add a height property in order for the image to be shown...

header {
    text-align: center;
    height: 390px;
    background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
              url('images/header.jpg') no-repeat;
              background-blend-mode: multiply;
              background-size: cover;
}

Unfortunately, I am still not sure why the 3 initial url attempts with "../images/header.jpg" did not work on localhost, or when I should or shouldn't be adding a period at the beginning of the url.

It might have something to do with how the default link tag is setup in application.html.erb, or maybe it's a .scss vs .css thing. Or, maybe that's just how the background property with url() works (the image needs to be within same directory as the css file)? Anyhow, this is how I solved the issue with CSS background image not loading on localhost.

Angularjs: input[text] ngChange fires while the value is changing

Override the default input onChange behavior (call the function only when control loss focus and value was change)

NOTE: ngChange is not similar to the classic onChange event it firing the event while the value is changing This directive stores the value of the element when it gets the focus
On blurs it checks whether the new value has changed and if so it fires the event

@param {String} - function name to be invoke when the "onChange" should be fired

@example < input my-on-change="myFunc" ng-model="model">

angular.module('app', []).directive('myOnChange', function () { 
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            myOnChange: '='
        },
        link: function (scope, elm, attr) {
            if (attr.type === 'radio' || attr.type === 'checkbox') {
                return;
            }
            // store value when get focus
            elm.bind('focus', function () {
                scope.value = elm.val();

            });

            // execute the event when loose focus and value was change
            elm.bind('blur', function () {
                var currentValue = elm.val();
                if (scope.value !== currentValue) {
                    if (scope.myOnChange) {
                        scope.myOnChange();
                    }
                }
            });
        }
    };
});

Font.createFont(..) set color and size (java.awt.Font)

To set the color of a font, you must first initialize the color by doing this:

Color maroon = new Color (128, 0, 0);

Once you've done that, you then put:

Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string

Note: The 1 represents the type of font and this can be used to replace Font.PLAIN and the 25 represents the size of your font.

PHP class not found but it's included

As a more systematic and structured solution you could define folders where your classes are stored and create an autoloader (__autoload()) which will search the class files in defined places:

require_once("../settings.php");
define('DIR_CLASSES', '/path/to/the/classes/folder/'); // this can be inside your settings.php

$user = new User();
$user->createUser($_POST["username"], $_POST["email"], $_POST["password"]);

function __autoload($classname) { 
    if(file_exists(DIR_CLASSES . 'class' . $classname . '.php')) {
        include_once(DIR_CLASSES . 'class' . $classname . '.php'); // looking for the class in the project's classes folder
    } else {
        include_once($classname . '.php'); // looking for the class in include_path
    }
} 

Scroll RecyclerView to show selected item on top

If you want to scroll automatic without show scroll motion then you need to write following code:

mRecyclerView.getLayoutManager().scrollToPosition(position);

If you want to display scroll motion then you need to add following code. =>Step 1: You need to declare SmoothScroller.

RecyclerView.SmoothScroller smoothScroller = new
                LinearSmoothScroller(this.getApplicationContext()) {
                    @Override
                    protected int getVerticalSnapPreference() {
                        return LinearSmoothScroller.SNAP_TO_START;
                    }
                };

=>step 2: You need to add this code any event you want to perform scroll to specific position. =>First you need to set target position to SmoothScroller.

smoothScroller.setTargetPosition(position);

=>Then you need to set SmoothScroller to LayoutManager.

mRecyclerView.getLayoutManager().startSmoothScroll(smoothScroller);

String concatenation with Groovy

I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X} as I find it makes it more readable.

Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:

@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*

def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

That gives me the following output on my machine:

Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
    * JRE: 1.6.0_31
    * Total Memory: 81.0625 MB
    * Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64) 

Options
=======
* Warm Up: Auto 
* CPU Time Measurement: Off

String adder               539
GString template           245
Readable GString template  244
StringBuilder              318
StringBuffer               370

So with readability and speed in it's favour, I'd recommend templating ;-)

NB: If you add toString() to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder and StringBuffer beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion

Adding these tests (as it has been asked in the comments)

  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }

Now we get the results:

String adder                        514
GString template                    267
Readable GString template           269
GString template toString           478
Readable GString template toString  480
StringBuilder                       321
StringBuffer                        369

So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...

But still lots more readable.

Edit after comment by ruralcoder below

Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:

@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )

def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
  'StringBuffer with Allocation' {
    new StringBuffer( 512 ).append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

gives

Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
    * JRE: 1.7.0_21
    * Total Memory: 467.375 MB
    * Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)

Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On

                                    user  system  cpu  real

String adder                         630       0  630   647
GString template                      29       0   29    31
Readable GString template             32       0   32    33
GString template toString            429       0  429   443
Readable GString template toString   428       1  429   441
StringBuilder                        383       1  384   396
StringBuffer                         395       1  396   409
StringBuffer with Allocation         277       0  277   286

Remove element by id

This one actually comes from Firefox... for once, IE was ahead of the pack and allowed the removal of an element directly.

This is just my assumption, but I believe the reason that you must remove a child through the parent is due to an issue with the way Firefox handled the reference.

If you call an object to commit hari-kari directly, then immediately after it dies, you are still holding that reference to it. This has the potential to create several nasty bugs... such as failing to remove it, removing it but keeping references to it that appear valid, or simply a memory leak.

I believe that when they realized the issue, the workaround was to remove an element through its parent because when the element is gone, you are now simply holding a reference to the parent. This would stop all that unpleasantness, and (if closing down a tree node by node, for example) would 'zip-up' rather nicely.

It should be an easily fixable bug, but as with many other things in web programming, the release was probably rushed, leading to this... and by the time the next version came around, enough people were using it that changing this would lead to breaking a bunch of code.

Again, all of this is simply my guesswork.

I do, however, look forward to the day when web programming finally gets a full spring cleaning, all these strange little idiosyncracies get cleaned up, and everyone starts playing by the same rules.

Probably the day after my robot servant sues me for back wages.

call a function in success of datatable ajax call

You can use dataSrc :

Here is a typical example of datatables.net

var table = $('#example').DataTable( {
    "ajax": {
            "type" : "GET",
            "url" : "ajax.php",
            "dataSrc": function ( json ) {
                //Make your callback here.
                alert("Done!");
                return json.data;
            }       
            },
    "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }

        ]
    } );

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

How to know if a Fragment is Visible?

Try this if you have only one Fragment

if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                    //TODO: Your Code Here
                }

Compile error: package javax.servlet does not exist

The possible solution (Tested on ubuntu)

  1. Open Terminal type geany .bashrc
  2. Go to the top and paste this
    export CLASSPATH=$CLASSPATH:/web/apache-tomcat-8.5.39/lib/servlet-api.jar
  3. Now save and close
  4. Try running the program now.

Cassandra cqlsh - connection refused

Check for correct IP address in the cassandra.yaml file. Majority of times the error is due to incorrect IP address of your system also the username and password too.

After doing so initiate cqlsh by the command :-

cqlsh 10.31.79.1 -u cassandra -p cassandra

Access to file download dialog in Firefox

I had the same problem, I wanted no access of Save Dialogue.

Below code can help:

    FirefoxProfile fp = new FirefoxProfile();
    fp.setPreference("browser.download.folderList",2);
    fp.setPreference("browser.download.manager.showWhenStarting",false);
    fp.setPreference("browser.helperApps.alwaysAsk.force", false);
    // Below you have to set the content-type of downloading file(I have set simple CSV file)
    fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

According to the file type which is being downloaded, You need to specify content types.

You can specify multiple content-types separated with ' ; '

e.g:

    fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv;application/vnd.ms-excel;application/msword");

How do I create a multiline Python string with inline variables?

The common way is the format() function:

>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'

It works fine with a multi-line format string:

>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.

You can also pass a dictionary with variables:

>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'

The closest thing to what you asked (in terms of syntax) are template strings. For example:

>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'

I should add though that the format() function is more common because it's readily available and it does not require an import line.

What is the point of "Initial Catalog" in a SQL Server connection string?

If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.

Equal sized table cells to fill the entire width of the containing table

You don't even have to set a specific width for the cells, table-layout: fixed suffices to spread the cells evenly.

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid hotpink;_x000D_
    vertical-align: middle;_x000D_
    word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that for table-layout to work the table styled element must have a width set (100% in my example).

python dictionary sorting in descending order based on values

Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.

If you already have a dictionary, a counter can easily be formed by:

c = Counter(d['123'])

as an example from your data.

The most_common function allows easy access to descending order of the items in the counter

The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html

Unable to Cast from Parent Class to Child Class

As of C# 7.0, you can use the is keyword to do this :

With those class defined :

class Base { /* Define base class */ }
class Derived : Base { /* Define derived class */ }

You can then do somehting like :

void Funtion(Base b)
{
    if (b is Derived d)
    {
        /* Do something with d which is now a variable of type Derived */
    }
}

Which would be equivalent to :

void Funtion(Base b)
{
    Defined d;
    if (b is Derived)
    {
        d = (Defined)b;
        /* Do something with d */
    }
}

You could now call :

Function(new Derived()); // Will execute code defined in if

As well as

Function(new Base()); // Won't execute code defined in if

That way you can be sure that your downcast will be valid and won't throw an exception !

Splitting comma separated string in a PL/SQL stored proc

I use apex_util.string_to_table to parse strings, but you can use a different parser if you wish. Then you can insert the data as in this example:

declare
  myString varchar2(2000) :='0.75, 0.64, 0.56, 0.45';
  myAmount varchar2(2000) :='0.25, 0.5, 0.65, 0.8';
  v_array1 apex_application_global.vc_arr2;
  v_array2 apex_application_global.vc_arr2;
begin

  v_array1 := apex_util.string_to_table(myString, ', ');
  v_array2 := apex_util.string_to_table(myAmount, ', ');

  forall i in 1..v_array1.count
     insert into mytable (a, b) values (v_array1(i), v_array2(i));
end;

Apex_util is available from Oracle 10G onwards. Prior to this it was called htmldb_util and was not installed by default. If you can't use that you could use the string parser I wrote many years ago and posted here.

Include an SVG (hosted on GitHub) in MarkDown

Just like this worked for me on Github.

![Imgae Caption](ImageAddressOnGitHub.svg)

or

<img src="ImageAddressOnGitHub.svg">

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

In addition to adding these attributes to your Id column:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

in your migration you should change your CreateTable to add the defaultValueSQL property to your column i.e.:

Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"),

This will prevent you from having to manually touch your database which, as you pointed out in the comments, is something you want to avoid with Code First.

How to view the SQL queries issued by JPA?

With Spring Boot simply add: spring.jpa.show-sql=true to application.properties. This will show the query but without the actual parameters (you will see ? instead of each parameter).

Ascending and Descending Number Order in java

Why are you using array and bothering with the first question of number of wanted numbers ?

Prefer an ArrayList associated with a corresponding comparator:

List numbers = new Arraylist();
//add read numbers (int (with autoboxing if jdk>=5) or Integer directly) into it

//Initialize the associated comparator reversing order. (since Integer implements Comparable)
Comparator comparator = Collections.reverseOrder();

//Sort the list
Collections.sort(numbers,comparator);

Python string class like StringBuilder in C#?

Using method 5 from above (The Pseudo File) we can get very good perf and flexibility

from cStringIO import StringIO

class StringBuilder:
     _file_str = None

     def __init__(self):
         self._file_str = StringIO()

     def Append(self, str):
         self._file_str.write(str)

     def __str__(self):
         return self._file_str.getvalue()

now using it

sb = StringBuilder()

sb.Append("Hello\n")
sb.Append("World")

print sb

jQuery $("#radioButton").change(...) not firing during de-selection

This normally works for me:

if ($("#r1").is(":checked")) {}

Split function in oracle to comma separated values with automatic sequence

Oracle Setup:

CREATE OR REPLACE FUNCTION split_String(
  i_str    IN  VARCHAR2,
  i_delim  IN  VARCHAR2 DEFAULT ','
) RETURN SYS.ODCIVARCHAR2LIST DETERMINISTIC
AS
  p_result       SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST();
  p_start        NUMBER(5) := 1;
  p_end          NUMBER(5);
  c_len CONSTANT NUMBER(5) := LENGTH( i_str );
  c_ld  CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
  IF c_len > 0 THEN
    p_end := INSTR( i_str, i_delim, p_start );
    WHILE p_end > 0 LOOP
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
      p_start := p_end + c_ld;
      p_end := INSTR( i_str, i_delim, p_start );
    END LOOP;
    IF p_start <= c_len + 1 THEN
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start + 1 );
    END IF;
  END IF;
  RETURN p_result;
END;
/

Query

SELECT ROWNUM AS ID,
       COLUMN_VALUE AS Data
FROM   TABLE( split_String( 'A,B,C,D' ) );

Output:

ID DATA
-- ----
 1 A
 2 B
 3 C
 4 D

How do I correctly use "Not Equal" in MS Access?

Like this

SELECT DISTINCT Table1.Column1
FROM Table1
WHERE NOT EXISTS( SELECT * FROM Table2
    WHERE Table1.Column1 = Table2.Column1  )

You want NOT EXISTS, not "Not Equal"


By the way, you rarely want to write a FROM clause like this:

FROM Table1, Table2

as this means "FROM all combinations of every row in Table1 with every row in Table2..." Usually that's a lot more result rows than you ever want to see. And in the rare case that you really do want to do that, the more accepted syntax is:

FROM Table1 CROSS JOIN Table2

col align right

How about this? Bootstrap 4

<div class="row justify-content-end">
    <div class="col-3">
        The content is positioned as if there was
        "col-9" classed div appending this one.
    </div>
</div>

Given an array of numbers, return array of products of all other numbers (no division)

One more solution, Using division. with twice traversal. Multiply all the elements and then start dividing it by each element.

Git submodule head 'reference is not a tree' error

Your branch may not be up to date, a simple solution but try git fetch

How to allow download of .json file with ASP.NET

If you want to manually add support to your site, you can just add the following to your web.config in the system.webServer section:

<staticContent>
    <mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>

This will add a "local" configuration under IIS. This does not work in IIS6, but does work in IIS7 and newer.

Set specific precision of a BigDecimal

The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.

Some examples in Clojure.

(.scale     0.00123M) ; 5
(.precision 0.00123M) ; 3

(In Clojure, The M designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

But you can't decrease the scale in the exact same way:

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.

So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!

It is easy to decrease the precision:

(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M

But it is not obvious how to increase the precision:

(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)

For the skeptical, this is not just a matter of trailing zeros not being displayed:

(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6 
; (same as above, still unexpected)

FWIW, Clojure is careful with trailing zeros and will show them:

4.0000M ; 4.0000M
(.precision 4.0000M) ; 5

Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:

(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M

So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?

So, best I can tell, if you want to change precision, you'll need to do these steps:

  1. Lookup the current precision.
  2. Lookup the current scale.
  3. Calculate the scale change.
  4. Set the new scale

These steps, as Clojure code:

(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M

I know, this is a lot of steps just to change the precision!

Why doesn't BigDecimal already provide this? Did I overlook something?

Bootstrap 3: Keep selected tab on page refresh

This one use HTML5 localStorage to store active tab

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
   $('#navtab-container a[href="' + activeTab + '"]').tab('show');
}

ref: http://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp

Verilog generate/genvar in an always block

To put it simply, you don't use generate inside an always process, you use generate to create a parametrized process or instantiate particular modules, where you can combine if-else or case. So you can move this generate and crea a particular process or an instantiation e.g.,

module #(
parameter XLEN = 64,
parameter USEIP = 0
)
(
 input clk,
input rstn,
input [XLEN-1:0] opA,
input [XLEN-1:0] opB,
input [XLEN-1:0] opR,
input en
);

generate 
case(USEIP)
0:begin
always @(posedge clk or negedge rstn)
begin
if(!rstn)
begin
 opR <= '{default:0};
end
else
begin
if(en)
 opR <= opA+opB;
else
opR <= '{default:0};
end
end
end
1:begin
  superAdder #(.XLEN(XLEN)) _adder(.clk(clk),.rstm(rstn), .opA(opA), .opB(opB), .opR(opR), .en(en));
end
endcase

endmodule

How to define a preprocessor symbol in Xcode

As an addendum, if you are using this technique to define strings in your target, this is how I had to define and use them:

In Build Settings -> Preprocessor Macros, and yes backslashes are critical in the definition:

APPURL_NSString=\@\"www.foobar.org\"

And in the source code:

objectManager.client.baseURL = APPURL_NSString;

How to get Django and ReactJS to work together?

The first approach is building separate Django and React apps. Django will be responsible for serving the API built using Django REST framework and React will consume these APIs using the Axios client or the browser's fetch API. You'll need to have two servers, both in development and production, one for Django(REST API) and the other for React (to serve static files).

The second approach is different the frontend and backend apps will be coupled. Basically you'll use Django to both serve the React frontend and to expose the REST API. So you'll need to integrate React and Webpack with Django, these are the steps that you can follow to do that

First generate your Django project then inside this project directory generate your React application using the React CLI

For Django project install django-webpack-loader with pip:

pip install django-webpack-loader

Next add the app to installed apps and configure it in settings.py by adding the following object

WEBPACK_LOADER = {
    'DEFAULT': {
            'BUNDLE_DIR_NAME': '',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
        }
}

Then add a Django template that will be used to mount the React application and will be served by Django

{ % load render_bundle from webpack_loader % }

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Django + React </title>
  </head>
  <body>
    <div id="root">
     This is where React will be mounted
    </div>
    { % render_bundle 'main' % }
  </body>
</html>

Then add an URL in urls.py to serve this template

from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [

    url(r'^', TemplateView.as_view(template_name="main.html")),

]

If you start both the Django and React servers at this point you'll get a Django error saying the webpack-stats.json doesn't exist. So next you need to make your React application able to generate the stats file.

Go ahead and navigate inside your React app then install webpack-bundle-tracker

npm install webpack-bundle-tracker --save

Then eject your Webpack configuration and go to config/webpack.config.dev.js then add

var BundleTracker  = require('webpack-bundle-tracker');
//...

module.exports = {

    plugins: [
          new BundleTracker({path: "../", filename: 'webpack-stats.json'}),
    ]
}

This add BundleTracker plugin to Webpack and instruct it to generate webpack-stats.json in the parent folder.

Make sure also to do the same in config/webpack.config.prod.js for production.

Now if you re-run your React server the webpack-stats.json will be generated and Django will be able to consume it to find information about the Webpack bundles generated by React dev server.

There are some other things to. You can find more information from this tutorial.

How to overwrite existing files in batch?

If destination file is read only use /y/r

xcopy /y/r source.txt dest.txt

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

Is div inside list allowed?

If you look at xhtml1-strict.dtd, you'll see

<!ELEMENT li %Flow;>
<!ENTITY % Flow "(#PCDATA | %block; | form | %inline; | %misc;)*">
<!ENTITY % block
     "p | %heading; | div | %lists; | %blocktext; | fieldset | table">

Thus div, p etc. can be inside li (according to XHTML 1.0 Strict DTD from w3.org).

convert NSDictionary to NSString

Above Solutions will only convert dictionary into string but you can't convert back that string to dictionary. For that it is the better way.

Convert to String

NSError * err;
NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:yourDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData   encoding:NSUTF8StringEncoding];
NSLog(@"%@",myString);

Convert Back to Dictionary

NSError * err;
NSData *data =[myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * response;
if(data!=nil){
 response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

This is similar to some of the other answers, but is compact and avoids the conversion to dictionary if you already have a list.

Given a ComboBox "combobox" on a windows form and a class SomeClass with the string type property Name,

List<SomeClass> list = new List<SomeClass>();

combobox.DisplayMember = "Name";
combobox.DataSource = list;

Which means that combobox.SelectedItem is a SomeClass object from list, and each item in combobox will be displayed using its property Name.

You can read the selected item using

SomeClass someClass = (SomeClass)combobox.SelectedItem;

jQuery / Javascript code check, if not undefined

I generally like the shorthand version:

if (!!wlocation) { window.location = wlocation; }

String concatenation in MySQL

Use concat() function instead of + like this:

select concat(firstname, lastname) as "Name" from test.student

Why I've got no crontab entry on OS X when using vim?

Other option is not to use crontab -e at all. Instead I used:

(crontab -l && echo "1 1  * * *  /path/to/my/script.sh") | crontab -

Notice that whatever you print before | crontab - will replace the entire crontab file, so use crontab -l && echo "<your new schedule>" to get the previous content and the new schedule.

How to convert POJO to JSON and vice versa?

Take below reference to convert a JSON into POJO and vice-versa

Let's suppose your JSON schema looks like:

{
  "type":"object",
  "properties": {
    "dataOne": {
      "type": "string"
    },
    "dataTwo": {
      "type": "integer"
    },
    "dataThree": {
      "type": "boolean"
    }
  }
}

Then to covert into POJO, your need to decleare some classes as explained in below style:

==================================
package ;
public class DataOne
{
    private String type;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
}

==================================
package ;
public class DataTwo
{
    private String type;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
}

==================================
package ;
public class DataThree
{
    private String type;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
}

==================================
package ;
public class Properties
{
    private DataOne dataOne;

    private DataTwo dataTwo;

    private DataThree dataThree;

    public void setDataOne(DataOne dataOne){
        this.dataOne = dataOne;
    }
    public DataOne getDataOne(){
        return this.dataOne;
    }
    public void setDataTwo(DataTwo dataTwo){
        this.dataTwo = dataTwo;
    }
    public DataTwo getDataTwo(){
        return this.dataTwo;
    }
    public void setDataThree(DataThree dataThree){
        this.dataThree = dataThree;
    }
    public DataThree getDataThree(){
        return this.dataThree;
    }
}

==================================
package ;
public class Root
{
    private String type;

    private Properties properties;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
    public void setProperties(Properties properties){
        this.properties = properties;
    }
    public Properties getProperties(){
        return this.properties;
    }
}

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

The solution (at least on OSX) is:

  1. Download the latest chromedriver file.
  2. Unzip the downloaded file.
  3. Search the location of the old chromedriver file on your computer and replace it with the new chromedriver file.
  4. Right-click the chromedriver file and click open. Do not double click as Mac will not open it the proper way.
  5. Once the file runs for the first time, you can close it and the update will have taken place.

What does SQL clause "GROUP BY 1" mean?

That means sql group by 1st column in your select clause, we always use this GROUP BY 1 together with ORDER BY 1, besides you can also use like this GROUP BY 1,2,3.., of course it is convenient for us but you need to pay attention to that condition the result may be not what you want if some one has modified your select columns, and it's not visualized

How to automatically add user account AND password with a Bash script?

The code below worked in Ubuntu 14.04. Try before you use it in other versions/linux variants.

# quietly add a user without password
adduser --quiet --disabled-password --shell /bin/bash --home /home/newuser --gecos "User" newuser

# set password
echo "newuser:newpassword" | chpasswd

Android - java.lang.SecurityException: Permission Denial: starting Intent

You need to set android:exported="true" in your AndroidManifest.xml file where you declare this Activity:

<activity
    android:name="com.example.lib.MainActivity"
    android:label="LibMain" 
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" >
        </action>
    </intent-filter>
</activity>

SQL Query - Change date format in query to DD/MM/YYYY

If you have a Date (or Datetime) column, look at http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

 SELECT DATE_FORMAT(datecolumn,'%d/%m/%Y') FROM ...

Should do the job for MySQL, for SqlServer I'm sure there is an analog function. If you have a VARCHAR column, you might have at first to convert it to a date, see STR_TO_DATE for MySQL.

Inserting line breaks into PDF

I have simply replaced the "\n" with "<br>" tag. Worked fine. It seems TCPDF render the text as HTML

$strText = str_replace("\n","<br>",$strText);
$pdf->MultiCell($width, $height,$strText, 0, 'J', 0, 1, '', '', true, null, true);

Grep regex NOT containing string

grep matches, grep -v does the inverse. If you need to "match A but not B" you usually use pipes:

grep "${PATT}" file | grep -v "${NOTPATT}"

How to display svg icons(.svg files) in UI using React Component?

if you have .svg or an image locally. first you have to install the loader needed for svg and file-loader for images. Then you have to import your icon or image first for example:

import logo from './logos/myLogo.svg' ;
import image from './images/myimage.png';

const temp = (
     <div>
         <img src={logo} />
         <img src={image} />
     </div>
);

ReactDOM.render(temp,document.getElementByID("app"));

Happy Coding :")

resources from react website and worked for me after many searches: https://create-react-app.dev/docs/adding-images-fonts-and-files/

git stash changes apply to new branch?

Since you've already stashed your changes, all you need is this one-liner:

  • git stash branch <branchname> [<stash>]

From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):

Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.

This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.

How can I parse a YAML file from a Linux shell script?

My use case may or may not be quite the same as what this original post was asking, but it's definitely similar.

I need to pull in some YAML as bash variables. The YAML will never be more than one level deep.

YAML looks like so:

KEY:                value
ANOTHER_KEY:        another_value
OH_MY_SO_MANY_KEYS: yet_another_value
LAST_KEY:           last_value

Output like-a dis:

KEY="value"
ANOTHER_KEY="another_value"
OH_MY_SO_MANY_KEYS="yet_another_value"
LAST_KEY="last_value"

I achieved the output with this line:

sed -e 's/:[^:\/\/]/="/g;s/$/"/g;s/ *=/=/g' file.yaml > file.sh
  • s/:[^:\/\/]/="/g finds : and replaces it with =", while ignoring :// (for URLs)
  • s/$/"/g appends " to the end of each line
  • s/ *=/=/g removes all spaces before =

Get each line from textarea

You could use PHP constant:

$array = explode(PHP_EOL, $text);

additional notes:
1. For me this is the easiest and the safest way because it is cross platform compatible (Windows/Linux etc.)
2. It is better to use PHP CONSTANT whenever you can for faster execution

How to solve javax.net.ssl.SSLHandshakeException Error?

I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..

ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...

Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )

In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..

I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...

P.S I cant get source code before the weekend since external SSH is disabled in my office :(

Restore the mysql database from .frm files

Just might be useful for someone:

I could only recover frm files after a disaster, at least I could get the table structure from FRM files by doing the following:

1- create some dummy tables with at least one column and SAME NAME with frm files in a new mysql database.

2-stop mysql service

3- copy and paste the old frm files to newly created table's frm files, it should ask you if you want to overwrite or not for each. replace all.

4-start mysql service, and you have your table structure...

regards. anybudy

How to find if element with specific id exists or not

Use typeof for elements checks.

if(typeof(element) === 'undefined')
{
// then field does not exist
}

'cannot find or open the pdb file' Visual Studio C++ 2013

Try go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically.

PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for.[...]

See Cannot find or open the PDB file in Visual Studio C++ 2010

using OR and NOT in solr query

Solr currently checks for a "pure negative" query and inserts *:* (which matches all documents) so that it works correctly.

-foo is transformed by solr into (*:* -foo)

The big caveat is that Solr only checks to see if the top level query is a pure negative query! So this means that a query like bar OR (-foo) is not changed since the pure negative query is in a sub-clause of the top level query. You need to transform this query yourself into bar OR (*:* -foo)

You may check the solr query explanation to verify the query transformation:

?q=-title:foo&debug=query

is transformed to

(+(-title:foo +MatchAllDocsQuery(*:*))

How to show and update echo on same line

This is vary useful please try it and change as required.

#!/bin/bash
for load in $(seq 1 100); do
    echo -ne "$load % downloded ...\r"
    sleep 1
done
echo "100"
echo "Loaded ..."

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.

Note, also, that your usage of .filter() was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each() loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:

$(".buttonClick").click(function () {

    $("input[type=text]").each(function () {
        var validated =  true;
        if(this.value.length < 8)
            validated = false;
        if(!/\d/.test(this.value))
            validated = false;
        if(!/[a-z]/.test(this.value))
            validated = false;
        if(!/[A-Z]/.test(this.value))
            validated = false;
        if(/[^0-9a-zA-Z]/.test(this.value))
            validated = false;
        $('div').text(validated ? "pass" : "fail");
        // use DOM traversal to select the correct div for this input above
    });
});

Working demo

equivalent of rm and mv in windows .cmd

If you want to see a more detailed discussion of differences for the commands, see the Details about Differences section, below.

From the LeMoDa.net website1 (archived), specifically the Windows and Unix command line equivalents page (archived), I found the following2. There's a better/more complete table in the next edit.

Windows command     Unix command
rmdir               rmdir
rmdir /s            rm -r
move                mv

I'm interested to hear from @Dave and @javadba to hear how equivalent the commands are - how the "behavior and capabilities" compare, whether quite similar or "woefully NOT equivalent".

All I found out was that when I used it to try and recursively remove a directory and its constituent files and subdirectories, e.g.

(Windows cmd)>rmdir /s C:\my\dirwithsubdirs\

gave me a standard Windows-knows-better-than-you-do-are-you-sure message and prompt

dirwithsubdirs, Are you sure (Y/N)?

and that when I typed Y, the result was that my top directory and its constituent files and subdirectories went away.


Edit

I'm looking back at this after finding this answer. I retried each of the commands, and I'd change the table a little bit.

Windows command     Unix command
rmdir               rmdir
rmdir /s /q         rm -r
rmdir /s /q         rm -rf
rmdir /s            rm -ri
move                mv
del <file>          rm <file>

If you want the equivalent for

rm -rf

you can use

rmdir /s /q

or, as the author of the answer I sourced described,

But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply ECHO the needed response and pipe the value into the command.

echo y | rmdir /s


Details about Differences

I tested each of the commands using Windows CMD and Cygwin (with its bash).

Before each test, I made the following setup.

Windows CMD

>mkdir this_directory
>echo some text stuff > this_directory/some.txt
>mkdir this_empty_directory

Cygwin bash

$ mkdir this_directory
$ echo "some text stuff" > this_directory/some.txt
$ mkdir this_empty_directory

That resulted in the following file structure for both.

base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

Here are the results. Note that I'll not mark each as CMD or bash; the CMD will have a > in front, and the bash will have a $ in front.

RMDIR

>rmdir this_directory
The directory is not empty.

>tree /a /f .
Folder PATH listing for volume Windows
Volume serial number is ¦¦¦¦¦¦¦¦ ¦¦¦¦:¦¦¦¦
base
+---this_directory
|       some.txt
|
\---this_empty_directory

> rmdir this_empty_directory

>tree /a /f .
base
\---this_directory
        some.txt
$ rmdir this_directory
rmdir: failed to remove 'this_directory': Directory not empty

$ tree --charset=ascii
base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

2 directories, 1 file

$ rmdir this_empty_directory

$ tree --charset=ascii
base
`-- this_directory
    `-- some.txt

RMDIR /S /Q and RM -R ; RM -RF

>rmdir /s /q this_directory

>tree /a /f
base
\---this_empty_directory

>rmdir /s /q this_empty_directory

>tree /a /f
base
No subfolders exist
$ rm -r this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -r this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files
$ rm -rf this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -rf this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files

RMDIR /S AND RM -RI Here, we have a bit of a difference, but they're pretty close.

>rmdir /s this_directory
this_directory, Are you sure (Y/N)? y

>tree /a /f
base
\---this_empty_directory

>rmdir /s this_empty_directory
this_empty_directory, Are you sure (Y/N)? y

>tree /a /f
base
No subfolders exist
$ rm -ri this_directory
rm: descend into directory 'this_directory'? y
rm: remove regular file 'this_directory/some.txt'? y
rm: remove directory 'this_directory'? y

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -ri this_empty_directory
rm: remove directory 'this_empty_directory'? y

$ tree --charset=ascii
base
0 directories, 0 files

I'M HOPING TO GET A MORE THOROUGH MOVE AND MV TEST


Notes

  1. I know almost nothing about the LeMoDa website, other than the fact that the info is

Copyright © Ben Bullock 2009-2018. All rights reserved.

(archived copyright notice)

and that there seem to be a bunch of useful programming tips along with some humour (yes, the British spelling) and information on how to fix Japanese toilets. I also found some stuff talking about the "Ibaraki Report", but I don't know if that is the website.

I think I shall go there more often; it's quite useful. Props to Ben Bullock, whose email is on his page. If he wants me to remove this info, I will.

I will include the disclaimer (archived) from the site:

Disclaimer Please read the following disclaimer before using any of the computer program code on this site.

There Is No Warranty For The Program, To The Extent Permitted By Applicable Law. Except When Otherwise Stated In Writing The Copyright Holders And/Or Other Parties Provide The Program “As Is” Without Warranty Of Any Kind, Either Expressed Or Implied, Including, But Not Limited To, The Implied Warranties Of Merchantability And Fitness For A Particular Purpose. The Entire Risk As To The Quality And Performance Of The Program Is With You. Should The Program Prove Defective, You Assume The Cost Of All Necessary Servicing, Repair Or Correction.

In No Event Unless Required By Applicable Law Or Agreed To In Writing Will Any Copyright Holder, Or Any Other Party Who Modifies And/Or Conveys The Program As Permitted Above, Be Liable To You For Damages, Including Any General, Special, Incidental Or Consequential Damages Arising Out Of The Use Or Inability To Use The Program (Including But Not Limited To Loss Of Data Or Data Being Rendered Inaccurate Or Losses Sustained By You Or Third Parties Or A Failure Of The Program To Operate With Any Other Programs), Even If Such Holder Or Other Party Has Been Advised Of The Possibility Of Such Damages.


  1. Actually, I found the information with a Google search for "cmd equivalent of rm"

https://www.google.com/search?q=cmd+equivalent+of+rm

The information I'm sharing came up first.

CSS ''background-color" attribute not working on checkbox inside <div>

My solution

Initially posted here.

_x000D_
_x000D_
input[type="checkbox"] {_x000D_
  cursor: pointer;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  outline: 0;_x000D_
  background: lightgray;_x000D_
  height: 16px;_x000D_
  width: 16px;_x000D_
  border: 1px solid white;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked {_x000D_
  background: #2aa1c0;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:hover {_x000D_
  filter: brightness(90%);_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled {_x000D_
  background: #e6e6e6;_x000D_
  opacity: 0.6;_x000D_
  pointer-events: none;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:after {_x000D_
  content: '';_x000D_
  position: relative;_x000D_
  left: 40%;_x000D_
  top: 20%;_x000D_
  width: 15%;_x000D_
  height: 40%;_x000D_
  border: solid #fff;_x000D_
  border-width: 0 2px 2px 0;_x000D_
  transform: rotate(45deg);_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked:after {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled:after {_x000D_
  border-color: #7b7b7b;_x000D_
}
_x000D_
<input type="checkbox"><br>_x000D_
<input type="checkbox" checked><br>_x000D_
<input type="checkbox" disabled><br>_x000D_
<input type="checkbox" disabled checked><br>
_x000D_
_x000D_
_x000D_

Angular.js programmatically setting a form field to dirty

Since AngularJS 1.3.4 you can use $setDirty() on fields (source). For example, for each field with error and marked required you can do the following:

angular.forEach($scope.form.$error.required, function(field) {
    field.$setDirty();
});

How do I know which version of Javascript I'm using?

Click on this link to see which version your BROWSER is using: http://jsfiddle.net/Ac6CT/

You should be able filter by using script tags to each JS version.

<script type="text/javascript">
  var jsver = 1.0;
</script>
<script language="Javascript1.1">
  jsver = 1.1;
</script>
<script language="Javascript1.2">
  jsver = 1.2;
</script>
<script language="Javascript1.3">
  jsver = 1.3;
</script>
<script language="Javascript1.4">
  jsver = 1.4;
</script>
<script language="Javascript1.5">
  jsver = 1.5;
</script>
<script language="Javascript1.6">
  jsver = 1.6;
</script>
<script language="Javascript1.7">
  jsver = 1.7;
</script>
<script language="Javascript1.8">
  jsver = 1.8;
</script>
<script language="Javascript1.9">
  jsver = 1.9;
</script>

<script type="text/javascript">
  alert(jsver);
</script>

My Chrome reports 1.7

Blatantly stolen from: http://javascript.about.com/library/bljver.htm

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

In case anyone gets the same error I did: “Requirements installation failed with status: 1.” here's what to do:

Install Homebrew (for some reason might not work automatically) with this command:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then proceed to install rvm again using

curl -sSL https://get.rvm.io | bash -s stable --ruby

Quit and reopen Terminal and then:

rvm install 2.2
rvm use 2.2 --default

How to vertically align <li> elements in <ul>?

I assume that since you're using an XML declaration, you're not worrying about IE or older browsers.

So you can use display:table-cell and display:table-row like so:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        .toolbar ul {
            display:table-row;
        }
        .toolbar ul li
        {
            display: table-cell;
            height: 100px;
            list-style-type: none;
            margin: 10px;
            vertical-align: middle;
        }
        .toolbar ul li a {
            display:table-cell;
            vertical-align: middle;
            height:100px;
            border: solid 1px black;
        }
        .toolbar ul li.button a {
            height:50px;
            border: solid 1px black;
        }
    </style>
</head>
<body>
    <div class="toolbar">
        <ul>
            <li><a href="#">first item<br />
                first item<br />
                first item</a></li>
            <li><a href="#">second item</a></li>
            <li><a href="#">last item</a></li>
            <li class="button"><a href="#">button<br />
                button</a></li>
        </ul>
    </div>
</body>
</html>

Error sending json in POST to web API service

It require to include Content-Type:application/json in web api request header section when not mention any content then by default it is Content-Type:text/plain passes to request.

Best way to test api on postman tool.

How to download file in swift?

Here is the Swift 4 version:

static func loadFileAsync(url: URL, completion: @escaping (String?, Error?) -> Void)
{
    let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

    if FileManager().fileExists(atPath: destinationUrl.path)
    {
        completion(destinationUrl.path, nil)
    }
    else
    {
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        let task = session.dataTask(with: request, completionHandler:
        {
            data, response, error in
            if error == nil
            {
                if let response = response as? HTTPURLResponse
                {
                    if response.statusCode == 200
                    {
                        if let data = data
                        {
                            if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
                            {
                                completion(destinationUrl.path, error)
                            }
                            else
                            {
                                completion(destinationUrl.path, error)
                            }
                        }
                        else
                        {
                            completion(destinationUrl.path, error)
                        }
                    }
                }
            }
            else
            {
                completion(destinationUrl.path, error)
            }
        })
        task.resume()
    }
}

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

SystemError: Parent module '' not loaded, cannot perform relative import

if you just run the main.py under the app, just import like

from mymodule import myclass

if you want to call main.py on other folder, use:

from .mymodule import myclass

for example:

+-- app
¦   +-- __init__.py
¦   +-- main.py
¦   +-- mymodule.py
+-- __init__.py
+-- run.py

main.py

from .mymodule import myclass

run.py

from app import main
print(main.myclass)

So I think the main question of you is how to call app.main.

Convert List<String> to List<Integer> directly

Using lambda:

strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());

Printing the correct number of decimal points with cout

with templates

#include <iostream>

// d = decimal places
template<int d> 
std::ostream& fixed(std::ostream& os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

int main(){
    double d = 122.345;
    std::cout << fixed<2> << d;
}

similar for scientific as well, with a width option also (useful for columns)

// d = decimal places
template<int d> 
std::ostream& f(std::ostream &os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

// w = width, d = decimal places
template<int w, int d> 
std::ostream& f(std::ostream &os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    os.width(w);
    return os; 
}

// d = decimal places
template<int d> 
std::ostream& e(std::ostream &os){
    os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

// w = width, d = decimal places
template<int w, int d> 
std::ostream& e(std::ostream &os){
    os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
    os.precision(d); 
    os.width(w);
    return os; 
}

int main(){
    double d = 122.345;
    std::cout << f<10,2> << d << '\n'
        << e<10,2> << d << '\n';
}

Can angularjs routes have optional parameter values?

It looks like Angular has support for this now.

From the latest (v1.2.0) docs for $routeProvider.when(path, route):

path can contain optional named groups with a question mark (:name?)

Killing a process using Java

Accidentally i stumbled upon another way to do a force kill on Unix (for those who use Weblogic). This is cheaper and more elegant than running /bin/kill -9 via Runtime.exec().

import weblogic.nodemanager.util.Platform;
import weblogic.nodemanager.util.ProcessControl;
...
ProcessControl pctl = Platform.getProcessControl();
pctl.killProcess(pid);

And if you struggle to get the pid, you can use reflection on java.lang.UNIXProcess, e.g.:

Process proc = Runtime.getRuntime().exec(cmdarray, envp);
if (proc instanceof UNIXProcess) {
    Field f = proc.getClass().getDeclaredField("pid");
    f.setAccessible(true);
    int pid = f.get(proc);
}

Compare two objects in Java with possible null values

boolean compare(String str1, String str2) {
  return (str1==null || str2==null) ? str1 == str2 : str1.equals(str2);
}

Func delegate with no return type

All of the Func delegates take at least one parameter

That's not true. They all take at least one type argument, but that argument determines the return type.

So Func<T> accepts no parameters and returns a value. Use Action or Action<T> when you don't want to return a value.

What is a C++ delegate?

The need for C++ delegate implementations are a long lasting embarassment to the C++ community. Every C++ programmer would love to have them, so they eventually use them despite the facts that:

  1. std::function() uses heap operations (and is out of reach for serious embedded programming).

  2. All other implementations make concessions towards either portability or standard conformity to larger or lesser degrees (please verify by inspecting the various delegate implementations here and on codeproject). I have yet to see an implementation which does not use wild reinterpret_casts, Nested class "prototypes" which hopefully produce function pointers of the same size as the one passed in by the user, compiler tricks like first forward declare, then typedef then declare again, this time inheriting from another class or similar shady techniques. While it is a great accomplishment for the implementers who built that, it is still a sad testimoney on how C++ evolves.

  3. Only rarely is it pointed out, that now over 3 C++ standard revisions, delegates were not properly addressed. (Or the lack of language features which allow for straightforward delegate implementations.)

  4. With the way C++11 lambda functions are defined by the standard (each lambda has anonymous, different type), the situation has only improved in some use cases. But for the use case of using delegates in (DLL) library APIs, lambdas alone are still not usable. The common technique here, is to first pack the lambda into a std::function and then pass it across the API.

R legend placement in a plot

Building on @P-Lapointe solution, but making it extremely easy, you could use the maximum values from your data using max() and then you re-use those maximum values to set the legend xy coordinates. To make sure you don't get beyond the borders, you set up ylim slightly over the maximum values.

a=c(rnorm(1000))
b=c(rnorm(1000))
par(mfrow=c(1,2))
plot(a,ylim=c(0,max(a)+1))
legend(x=max(a)+0.5,legend="a",pch=1)
plot(a,b,ylim=c(0,max(b)+1),pch=2)
legend(x=max(b)-1.5,y=max(b)+1,legend="b",pch=2)

enter image description here

Issue with background color in JavaFX 8

Try this one in your css document,

-fx-background-color : #ffaadd;

or

-fx-base : #ffaadd; 

Also, you can set background color on your object with this code directly.

yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

Difference between Fact table and Dimension table?

In Data Warehouse Modeling, a star schema and a snowflake schema consists of Fact and Dimension tables.

Fact Table:

  • It contains all the primary keys of the dimension and associated facts or measures(is a property on which calculations can be made) like quantity sold, amount sold and average sales.

Dimension Tables:

  • Dimension tables provides descriptive information for all the measurements recorded in fact table.
  • Dimensions are relatively very small as comparison of fact table.
  • Commonly used dimensions are people, products, place and time.

enter image description here

image source

How to add "Maven Managed Dependencies" library in build path eclipse?

  • Install M2E plugin.
  • Right click your project and select Configure -> Convert to Maven project.

enter image description here

  • Then a pom.xml file will show up in your project. Double click the pom.xml, select Dependency tab to add the jars your project depends on.

How to generate access token using refresh token through google drive API?

It's an old question but seems to me it wasn't completely answered, and I needed this information too so I'll post my answer.

If you want to use the Google Api Client Library, then you just need to have an access token that includes the refresh token in it, and then - even though the access token will expire after an hour - the library will refresh the token for you automatically.

In order to get an access token with a refresh token, you just need to ask for the offline access type (for example in PHP: $client->setAccessType("offline");) and you will get it. Just keep in mind you will get the access token with the refresh token only in the first authorization, so make sure to save that access token in the first time, and you will be able to use it anytime.

Hope that helps anyone :-)

Vector erase iterator

As a modification to crazylammer's answer, I often use:

your_vector_type::iterator it;
for( it = res.start(); it != res.end();)
{
    your_vector_type::iterator curr = it++;
    if (something)
        res.erase(curr);
}

The advantage of this is that you don't have to worry about forgetting to increment your iterator, making it less bug prone when you have complex logic. Inside the loop, curr will never be equal to res.end(), and it will be at the next element regardless of if you erase it from your vector.

implement addClass and removeClass functionality in angular2

You can basically switch the class using [ngClass]

for example

<button [ngClass]="{'active': selectedItem === 'item1'}" (click)="selectedItem = 'item1'">Button One</button>
<button [ngClass]="{'active': selectedItem === 'item2'}" (click)="selectedItem = 'item2'">Button Two</button>

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

jquery will provide you with this and more ...

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

np.append needs the array as the first argument and the list you want to append as the second:

mean_data = np.append(mean_data, [ur, ua, np.mean(data[samepoints,-1])])

TypeError: string indices must be integers, not str // working with dict

time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

for info in courses[time1][course]:

As you're going through each dictionary, you must add another nest.

Remove #N/A in vlookup result

To avoid errors in any excel function, use the Error Handling functions that start with IS* in Excel. Embed your function with these error handing functions and avoid the undesirable text in your results. More info in OfficeTricks Page

How to work on UAC when installing XAMPP

You can press ok and it will continue the insallation.

Otherwise, see Trying to reinstall XAMPP on windows 7, getting error messag...

What does a Status of "Suspended" and high DiskIO means from sp_who2?

This is a very broad question, so I am going to give a broad answer.

  1. A query gets suspended when it is requesting access to a resource that is currently not available. This can be a logical resource like a locked row or a physical resource like a memory data page. The query starts running again, once the resource becomes available. 
  2. High disk IO means that a lot of data pages need to be accessed to fulfill the request.

That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.

The entity name must immediately follow the '&' in the entity reference

Just in case someone from Blogger arrives, I had this problem when using Beautify extension in VSCode. Don´t use it, don´t beautify it.

What is the size limit of a post request?

For developers who cannot change php configuration because of the webhosting. (My settings 256MB max size, 1000 max variables)

I got the same issue that just 2 out of 5 big data objects (associative arrays) with substructures were received on the server side.

I find out that the whole substructure is being "flattened" in the post request. So, one object becomes a hundreds of literal variables. At the end, instead of 5 Object variables it is in reality sending dozens of hundreds elementar variables.

Solution in this case is to serialize each of the substructures into String. Then it is received on the server as 5 String variables. Example: {variable1:JSON.stringify(myDataObject1),variable2:JSON.stringify(myDataObject2)...}

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

How to use bitmask?

Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45

unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));

The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.

Trusting all certificates using HttpClient over HTTPS

I'm adding a response for those that use the httpclient-4.5, and probably works for 4.4 as well.

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.fluent.ContentResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;



public class HttpClientUtils{

public static HttpClient getHttpClientWithoutSslValidation_UsingHttpClient_4_5_2() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new NoopHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); 
        return httpclient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
}

Loading DLLs at runtime in C#

Activator.CreateInstance() returns an object, which doesn't have an Output method.

It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.

Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?

If you absolutely want to load the assembly via Assembly.Load, you will have to go via reflection to call any members on c

Something like type.GetMethod("Output").Invoke(c, null); should do it.

Uncaught ReferenceError: $ is not defined error in jQuery

The MVC 5 stock install puts javascript references in the _Layout.cshtml file that is shared in all pages. So the javascript files were below the main content and document.ready function where all my $'s were.

BOTTOM PART OF _Layout.cshtml:

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

</body>
</html>

I moved them above the @RenderBody() and all was fine.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

</body>
</html>

Concatenate text files with Windows command line, dropping leading lines

Use the FOR command to echo a file line by line, and with the 'skip' option to miss a number of starting lines...

FOR /F "skip=1" %i in (file2.txt) do @echo %i

You could redirect the output of a batch file, containing something like...

FOR /F %%i in (file1.txt) do @echo %%i
FOR /F "skip=1" %%i in (file2.txt) do @echo %%i

Note the double % when a FOR variable is used within a batch file.

How to get the unique ID of an object which overrides hashCode()?

I had the same issue and was not satisfied with any of the answers so far since none of them guaranteed unique IDs.

I too wanted to print object IDs for debugging purposed. I knew there must be some way to do it, because in the Eclipse debugger, it specifies unique IDs for each object.

I came up with a solution based on the fact that the "==" operator for objects only returns true if the two objects are actually the same instance.

import java.util.HashMap;
import java.util.Map;

/**
 *  Utility for assigning a unique ID to objects and fetching objects given
 *  a specified ID
 */
public class ObjectIDBank {

    /**Singleton instance*/
    private static ObjectIDBank instance;

    /**Counting value to ensure unique incrementing IDs*/
    private long nextId = 1;

    /** Map from ObjectEntry to the objects corresponding ID*/
    private Map<ObjectEntry, Long> ids = new HashMap<ObjectEntry, Long>();

    /** Map from assigned IDs to their corresponding objects */
    private Map<Long, Object> objects = new HashMap<Long, Object>();

    /**Private constructor to ensure it is only instantiated by the singleton pattern*/
    private ObjectIDBank(){}

    /**Fetches the singleton instance of ObjectIDBank */
    public static ObjectIDBank instance() {
        if(instance == null)
            instance = new ObjectIDBank();

        return instance;
    }

    /** Fetches a unique ID for the specified object. If this method is called multiple
     * times with the same object, it is guaranteed to return the same value. It is also guaranteed
     * to never return the same value for different object instances (until we run out of IDs that can
     * be represented by a long of course)
     * @param obj The object instance for which we want to fetch an ID
     * @return Non zero unique ID or 0 if obj == null
     */
    public long getId(Object obj) {

        if(obj == null)
            return 0;

        ObjectEntry objEntry = new ObjectEntry(obj);

        if(!ids.containsKey(objEntry)) {
            ids.put(objEntry, nextId);
            objects.put(nextId++, obj);
        }

        return ids.get(objEntry);
    }

    /**
     * Fetches the object that has been assigned the specified ID, or null if no object is
     * assigned the given id
     * @param id Id of the object
     * @return The corresponding object or null
     */
    public Object getObject(long id) {
        return objects.get(id);
    }


    /**
     * Wrapper around an Object used as the key for the ids map. The wrapper is needed to
     * ensure that the equals method only returns true if the two objects are the same instance
     * and to ensure that the hash code is always the same for the same instance.
     */
    private class ObjectEntry {
        private Object obj;

        /** Instantiates an ObjectEntry wrapper around the specified object*/
        public ObjectEntry(Object obj) {
            this.obj = obj;
        }


        /** Returns true if and only if the objects contained in this wrapper and the other
         * wrapper are the exact same object (same instance, not just equivalent)*/
        @Override
        public boolean equals(Object other) {
            return obj == ((ObjectEntry)other).obj;
        }


        /**
         * Returns the contained object's identityHashCode. Note that identityHashCode values
         * are not guaranteed to be unique from object to object, but the hash code is guaranteed to
         * not change over time for a given instance of an Object.
         */
        @Override
        public int hashCode() {
            return System.identityHashCode(obj);
        }
    }
}

I believe that this should ensure unique IDs throughout the lifetime of the program. Note, however, that you probably don't want to use this in a production application because it maintains references to all of the objects for which you generate IDs. This means that any objects for which you create an ID will never be garbage collected.

Since I'm using this for debug purposes, I'm not too concerned with the memory being freed.

You could modify this to allow clearing Objects or removing individual objects if freeing memory is a concern.

How do I insert values into a Map<K, V>?

There are two issues here.

Firstly, you can't use the [] syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.

data.put is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:

public class Data {
     public static void main(String[] args) {
         Map<String, String> data = new HashMap<String, String>();
         data.put("John", "Taxi Driver");
         data.put("Mark", "Professional Killer");
     }
 }

If you want to initialize a map as a static field of a class then you can use Map.of, since Java 9:

public class Data {
    private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}

Before Java 9, you can use a static initializer block to accomplish the same thing:

public class Data {
    private static final Map<String, String> DATA = new HashMap<>();

    static {
        DATA.put("John", "Taxi Driver");
    }
}

How to make links in a TextView clickable?

I added this line to the TextView: android:autoLink="web"
Below is an example of usage in a layout file.

layout.xml sample

    <TextView
        android:id="@+id/txtLostpassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:autoLink="email"
        android:gravity="center"
        android:padding="20px"
        android:text="@string/lostpassword"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView
        android:id="@+id/txtDefaultpassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:autoLink="web"
        android:gravity="center"
        android:padding="20px"
        android:text="@string/defaultpassword"
        android:textAppearance="?android:attr/textAppearanceSmall" />

string.xml

<string name="lostpassword">If you lost your password please contact <a href="mailto:[email protected]?Subject=Lost%20Password" target="_top">[email protected]</a></string>

<string name="defaultpassword">User Guide <a href="http://www.cleverfinger.com.au/user-guide/">http://www.cleverfinger.com.au/user-guide/</a></string>

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Regards Örvar

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

Starting from support library version 24.0.0 you can call FragmentTransaction.commitNow() method which commits this transaction synchronously instead of calling commit() followed by executePendingTransactions()

What is the best way to programmatically detect porn images?

short answer: use a moderator ;)

Long answer: I dont think there's a project for this cause what is porn? Only legs, full nudity, midgets etc. Its subjective.

How to open the Google Play Store directly from my Android application?

try this

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.example.android"));
startActivity(intent);

SQL query: Delete all records from the table except latest N?

If your id is incremental then use something like

delete from table where id < (select max(id) from table)-N

Class 'DOMDocument' not found

If compiling from source with --disable-all then DOMDocument support can be enabled with
--enable-dom

Example:

./configure --disable-all --enable-dom

Tested and working for Centos7 and PHP7

Filter array to have unique values

Filtering an array to contain unique values can be achieved using the JavaScript Set and Array.from method, as shown below:

Array.from(new Set(arrayOfNonUniqueValues));

Set

The Set object lets you store unique values of any type, whether primitive values or object references.

Return value A new Set object.

Array.from()

The Array.from() method creates a new Array instance from an array-like or iterable object.

Return value A new Array instance.

Example Code:

_x000D_
_x000D_
const array = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"]_x000D_
_x000D_
const uniqueArray = Array.from(new Set(array));_x000D_
_x000D_
console.log("uniqueArray: ", uniqueArray);
_x000D_
_x000D_
_x000D_

iPhone 5 CSS media query

/* iPad */
@media screen and (min-device-width: 768px) {
    /* ipad-portrait */
    @media screen and (max-width: 896px) { 
        .logo{
            display: none !important;
        }
    }
    /* ipad-landscape */
    @media screen and (min-width: 897px) { 

    }
}
/* iPhone */
@media screen and (max-device-width: 480px) {
    /* iphone-portrait */
    @media screen and (max-width: 400px) { 

    }
    /* iphone-landscape */
    @media screen and (min-width: 401px) { 

    }
}

make a header full screen (width) css

The best way to make the header full screen is set height to be 100vh

#header{
height: 100vh;
}

Explaining the 'find -mtime' command

To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.

find . -mtime -1 -ls

Jenkins Git Plugin: How to build specific tag?

I did something like this and it worked :

Source Code Management

 Git    
    Repositories    


 Advance

Name: ref
Refspec : +refs/tags/*:refs/remotes/origin/tags/* 

 Branches to build  
 Branch Specifier (blank for 'any') : v0.9.5.2

enter image description here

Jenkins log confirmed that it was getting the source from the tag

Checking out Revision 0b4d6e810546663e931cccb45640583b596c24b9 (v0.9.5.2)

Why does JPA have a @Transient annotation?

If you just want a field won't get persisted, both transient and @Transient work. But the question is why @Transient since transient already exists.

Because @Transient field will still get serialized!

Suppose you create a entity, doing some CPU-consuming calculation to get a result and this result will not save in database. But you want to sent the entity to other Java applications to use by JMS, then you should use @Transient, not the JavaSE keyword transient. So the receivers running on other VMs can save their time to re-calculate again.

Angular 2 - Redirect to an external URL and open in a new tab

Another possible solution is:

const link = document.createElement('a');
link.target = '_blank';
link.href = 'https://www.google.es';
link.setAttribute('visibility', 'hidden');
link.click();

Is there any "font smoothing" in Google Chrome?

I will say before all that this will not always works, i have tested this with sans-serif font and external fonts like open sans

Sometimes, when you use huge fonts, try to approximate to font-size:49px and upper

font-size:48px

This is a header text with a size of 48px (font-size:48px; in the element that contains the text).

But, if you up the 48px to font-size:49px; (and 50px, 60px, 80px, etc...), something interesting happens

font-size:49px

The text automatically get smooth, and seems really good

For another side...

If you are looking for small fonts, you can try this, but isn't very effective.

To the parent of the text, just apply the next css property: -webkit-backface-visibility: hidden;

You can transform something like this:

-webkit-backface-visibility: visible;

To this:

-webkit-backface-visibility: hidden;

(the font is Kreon)

Consider that when you are not putting that property, -webkit-backface-visibility: visible; is inherit

But be careful, that practice will not give always good results, if you see carefully, Chrome just make the text look a little bit blurry.

Another interesting fact:

-webkit-backface-visibility: hidden; will works too when you transform a text in Chrome (with the -webkit-transform property, that includes rotations, skews, etc)

Without

Without -webkit-backface-visibility: hidden;

With

With -webkit-backface-visibility: hidden;

Well, I don't know why that practices works, but it does for me. Sorry for my weird english.

How to filter a data frame

Another method utilizing the dplyr package:

library(dplyr)
df <- mtcars %>%
        filter(mpg > 25)

Without the chain (%>%) operator:

library(dplyr)
df <- filter(mtcars, mpg > 25)

Bower: ENOGIT Git is not installed or not in the PATH

In Linux:

if you dont have installed git use:

sudo apt-get update
sudo apt-get install git

with command which git you will know the directory where is and then add in path if it is not in that enviroment variable.

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

In bootstrap 3, this works well for me:

.btn-link.btn-anchor {
    outline: none !important;
    padding: 0;
    border: 0;
    vertical-align: baseline;
}

Used like:

<button type="button" class="btn-link btn-anchor">My Button</button>

Demo

Display QImage with QtGui

As far as I know, QPixmap is used for displaying images and QImage for reading them. There are QPixmap::convertFromImage() and QPixmap::fromImage() functions to convert from QImage.

How to use java.String.format in Scala?

In scala , for string Interpolation we have $ that saves the day and make our life much easy:

For Example: You want to define a function that takes input name and age and says Hello With the name and says its age. That can be written like this:

def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is $age"

Hence , When you call this function: like this :

funcStringInterpolationDemo("Shivansh",22)

Its output would be :

Hey ! my name is Shivansh and my age is 22

You can write the code to change it in the same line, like if you want to add 10 years to the age !

then function could be :

def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is ${age+10}"

And now the output would be :

Hey ! my name is Shivansh and my age is 32

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

static_cast vs dynamic_cast vs reinterpret_cast internals view on a downcast/upcast

In this answer, I want to compare these three mechanisms on a concrete upcast/downcast example and analyze what happens to the underlying pointers/memory/assembly to give a concrete understanding of how they compare.

I believe that this will give a good intuition on how those casts are different:

  • static_cast: does one address offset at runtime (low runtime impact) and no safety checks that a downcast is correct.

  • dyanamic_cast: does the same address offset at runtime like static_cast, but also and an expensive safety check that a downcast is correct using RTTI.

    This safety check allows you to query if a base class pointer is of a given type at runtime by checking a return of nullptr which indicates an invalid downcast.

    Therefore, if your code is not able to check for that nullptr and take a valid non-abort action, you should just use static_cast instead of dynamic cast.

    If an abort is the only action your code can take, maybe you only want to enable the dynamic_cast in debug builds (-NDEBUG), and use static_cast otherwise, e.g. as done here, to not slow down your fast runs.

  • reinterpret_cast: does nothing at runtime, not even the address offset. The pointer must point exactly to the correct type, not even a base class works. You generally don't want this unless raw byte streams are involved.

Consider the following code example:

main.cpp

#include <iostream>

struct B1 {
    B1(int int_in_b1) : int_in_b1(int_in_b1) {}
    virtual ~B1() {}
    void f0() {}
    virtual int f1() { return 1; }
    int int_in_b1;
};

struct B2 {
    B2(int int_in_b2) : int_in_b2(int_in_b2) {}
    virtual ~B2() {}
    virtual int f2() { return 2; }
    int int_in_b2;
};

struct D : public B1, public B2 {
    D(int int_in_b1, int int_in_b2, int int_in_d)
        : B1(int_in_b1), B2(int_in_b2), int_in_d(int_in_d) {}
    void d() {}
    int f2() { return 3; }
    int int_in_d;
};

int main() {
    B2 *b2s[2];
    B2 b2{11};
    D *dp;
    D d{1, 2, 3};

    // The memory layout must support the virtual method call use case.
    b2s[0] = &b2;
    // An upcast is an implicit static_cast<>().
    b2s[1] = &d;
    std::cout << "&d           " << &d           << std::endl;
    std::cout << "b2s[0]       " << b2s[0]       << std::endl;
    std::cout << "b2s[1]       " << b2s[1]       << std::endl;
    std::cout << "b2s[0]->f2() " << b2s[0]->f2() << std::endl;
    std::cout << "b2s[1]->f2() " << b2s[1]->f2() << std::endl;

    // Now for some downcasts.

    // Cannot be done implicitly
    // error: invalid conversion from ‘B2*’ to ‘D*’ [-fpermissive]
    // dp = (b2s[0]);

    // Undefined behaviour to an unrelated memory address because this is a B2, not D.
    dp = static_cast<D*>(b2s[0]);
    std::cout << "static_cast<D*>(b2s[0])            " << dp           << std::endl;
    std::cout << "static_cast<D*>(b2s[0])->int_in_d  " << dp->int_in_d << std::endl;

    // OK
    dp = static_cast<D*>(b2s[1]);
    std::cout << "static_cast<D*>(b2s[1])            " << dp           << std::endl;
    std::cout << "static_cast<D*>(b2s[1])->int_in_d  " << dp->int_in_d << std::endl;

    // Segfault because dp is nullptr.
    dp = dynamic_cast<D*>(b2s[0]);
    std::cout << "dynamic_cast<D*>(b2s[0])           " << dp           << std::endl;
    //std::cout << "dynamic_cast<D*>(b2s[0])->int_in_d " << dp->int_in_d << std::endl;

    // OK
    dp = dynamic_cast<D*>(b2s[1]);
    std::cout << "dynamic_cast<D*>(b2s[1])           " << dp           << std::endl;
    std::cout << "dynamic_cast<D*>(b2s[1])->int_in_d " << dp->int_in_d << std::endl;

    // Undefined behaviour to an unrelated memory address because this
    // did not calculate the offset to get from B2* to D*.
    dp = reinterpret_cast<D*>(b2s[1]);
    std::cout << "reinterpret_cast<D*>(b2s[1])           " << dp           << std::endl;
    std::cout << "reinterpret_cast<D*>(b2s[1])->int_in_d " << dp->int_in_d << std::endl;
}

Compile, run and disassemble with:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
setarch `uname -m` -R ./main.out
gdb -batch -ex "disassemble/rs main" main.out

where setarch is used to disable ASLR to make it easier to compare runs.

Possible output:

&d           0x7fffffffc930
b2s[0]       0x7fffffffc920
b2s[1]       0x7fffffffc940
b2s[0]->f2() 2
b2s[1]->f2() 3
static_cast<D*>(b2s[0])            0x7fffffffc910
static_cast<D*>(b2s[0])->int_in_d  1
static_cast<D*>(b2s[1])            0x7fffffffc930
static_cast<D*>(b2s[1])->int_in_d  3
dynamic_cast<D*>(b2s[0])           0
dynamic_cast<D*>(b2s[1])           0x7fffffffc930
dynamic_cast<D*>(b2s[1])->int_in_d 3
reinterpret_cast<D*>(b2s[1])           0x7fffffffc940
reinterpret_cast<D*>(b2s[1])->int_in_d 32767

Now, as mentioned at: https://en.wikipedia.org/wiki/Virtual_method_table in order to support the virtual method calls efficiently, the memory data structure of D has to look something like:

B1:
  +0: pointer to virtual method table of B1
  +4: value of int_in_b1

B2:
  +0: pointer to virtual method table of B2
  +4: value of int_in_b2

D:
  +0: pointer to virtual method table of D (for B1)
  +4: value of int_in_b1
  +8: pointer to virtual method table of D (for B2)
 +12: value of int_in_b2
 +16: value of int_in_d

The key fact is that the memory data structure of D contains inside it memory structure compatible with that of B1 and that of B2 internally.

Therefore we reach the critical conclusion:

an upcast or downcast only needs to shift the pointer value by a value known at compile time

This way, when D gets passed to the base type array, the type cast actually calculates that offset and points something that looks exactly like a valid B2 in memory:

b2s[1] = &d;

except that this one has the vtable for D instead of B2, and therefore all virtual calls work transparently.

Now, we can finally get back to type casting and the analysis of our concrete example.

From the stdout output we see:

&d           0x7fffffffc930
b2s[1]       0x7fffffffc940

Therefore, the implicit static_cast done there did correctly calculate the offset from the full D data structure at 0x7fffffffc930 to the B2 like one which is at 0x7fffffffc940. We also infer that what lies between 0x7fffffffc930 and 0x7fffffffc940 is likely be the B1 data and vtable.

Then, on the downcast sections, it is now easy to understand how the invalid ones fail and why:

  • static_cast<D*>(b2s[0]) 0x7fffffffc910: the compiler just went up 0x10 at compile time bytes to try and go from a B2 to the containing D

    But because b2s[0] was not a D, it now points to an undefined memory region.

    The disassembly is:

    49          dp = static_cast<D*>(b2s[0]);
       0x0000000000000fc8 <+414>:   48 8b 45 d0     mov    -0x30(%rbp),%rax
       0x0000000000000fcc <+418>:   48 85 c0        test   %rax,%rax
       0x0000000000000fcf <+421>:   74 0a   je     0xfdb <main()+433>
       0x0000000000000fd1 <+423>:   48 8b 45 d0     mov    -0x30(%rbp),%rax
       0x0000000000000fd5 <+427>:   48 83 e8 10     sub    $0x10,%rax
       0x0000000000000fd9 <+431>:   eb 05   jmp    0xfe0 <main()+438>
       0x0000000000000fdb <+433>:   b8 00 00 00 00  mov    $0x0,%eax
       0x0000000000000fe0 <+438>:   48 89 45 98     mov    %rax,-0x68(%rbp)
    

    so we see that GCC does:

    • check if pointer is NULL, and if yes return NULL
    • otherwise, subtract 0x10 from it to reach the D which does not exist
  • dynamic_cast<D*>(b2s[0]) 0: C++ actually found that the cast was invalid and returned nullptr!

    There is no way this can be done at compile time, and we will confirm that from the disassembly:

    59          dp = dynamic_cast<D*>(b2s[0]);
       0x00000000000010ec <+706>:   48 8b 45 d0     mov    -0x30(%rbp),%rax
       0x00000000000010f0 <+710>:   48 85 c0        test   %rax,%rax
       0x00000000000010f3 <+713>:   74 1d   je     0x1112 <main()+744>
       0x00000000000010f5 <+715>:   b9 10 00 00 00  mov    $0x10,%ecx
       0x00000000000010fa <+720>:   48 8d 15 f7 0b 20 00    lea    0x200bf7(%rip),%rdx        # 0x201cf8 <_ZTI1D>
       0x0000000000001101 <+727>:   48 8d 35 28 0c 20 00    lea    0x200c28(%rip),%rsi        # 0x201d30 <_ZTI2B2>
       0x0000000000001108 <+734>:   48 89 c7        mov    %rax,%rdi
       0x000000000000110b <+737>:   e8 c0 fb ff ff  callq  0xcd0 <__dynamic_cast@plt>
       0x0000000000001110 <+742>:   eb 05   jmp    0x1117 <main()+749>
       0x0000000000001112 <+744>:   b8 00 00 00 00  mov    $0x0,%eax
       0x0000000000001117 <+749>:   48 89 45 98     mov    %rax,-0x68(%rbp)
    

    First there is a NULL check, and it returns NULL if th einput is NULL.

    Otherwise, it sets up some arguments in the RDX, RSI and RDI and calls __dynamic_cast.

    I don't have the patience to analyze this further now, but as others said, the only way for this to work is for __dynamic_cast to access some extra RTTI in-memory data structures that represent the class hierarchy.

    It must therefore start from the B2 entry for that table, then walk this class hierarchy until it finds that the vtable for a D typecast from b2s[0].

    This is why reinterpret cast is potentially expensive! Here is an example where a one liner patch converting a dynamic_cast to a static_cast in a complex project reduced runtime by 33%!.

  • reinterpret_cast<D*>(b2s[1]) 0x7fffffffc940 this one just believes us blindly: we said there is a D at address b2s[1], and the compiler does no offset calculations.

    But this is wrong, because D is actually at 0x7fffffffc930, what is at 0x7fffffffc940 is the B2-like structure inside D! So trash gets accessed.

    We can confirm this from the horrendous -O0 assembly that just moves the value around:

    70          dp = reinterpret_cast<D*>(b2s[1]);
       0x00000000000011fa <+976>:   48 8b 45 d8     mov    -0x28(%rbp),%rax
       0x00000000000011fe <+980>:   48 89 45 98     mov    %rax,-0x68(%rbp)
    

Related questions:

Tested on Ubuntu 18.04 amd64, GCC 7.4.0.

How to convert image to byte array

Sample code to change an image into a byte array

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
   using (var ms = new MemoryStream())
   {
      imageIn.Save(ms,imageIn.RawFormat);
      return  ms.ToArray();
   }
}

C# Image to Byte Array and Byte Array to Image Converter Class

How do you detect/avoid Memory leaks in your (Unmanaged) code?

Paul Nettle's mmgr is a long time favourite tool of mine. You include mmgr.h in your source files, define TEST_MEMORY, and it delivers a textfile full of memory problems that occurred during a run of your app.

ld cannot find an existing library

It is Debian convention to separate shared libraries into their runtime components (libmagic1: /usr/lib/libmagic.so.1 ? libmagic.so.1.0.0) and their development components (libmagic-dev: /usr/lib/libmagic.so ? …).

Because the library's soname is libmagic.so.1, that's the string that gets embedded into the executable so that's the file that is loaded when the executable is run.

However, because the library is specified as -lmagic to the linker, it looks for libmagic.so, which is why it is needed for development.

See Diego E. Pettenò: Linkers and names for details on how this all works on Linux.


In short, you should apt-get install libmagic-dev. This will not only give you libmagic.so but also other files necessary for compiling like /usr/include/magic.h.

pass parameter by link_to ruby on rails

Maybe try this:

<%= link_to "Add to cart", 
            :controller => "car", 
            :action => "add_to_cart", 
            :car => car.attributes %>

But I'd really like to see where the car object is getting setup for this page (i.e., the rest of the view).

What are the differences between the different saving methods in Hibernate?

Be aware that if you call an update on an detached object, there will always be an update done in the database whether you changed the object or not. If it is not what you want you should use Session.lock() with LockMode.None.

You should call update only if the object was changed outside the scope of your current session (when in detached mode).

Make selected block of text uppercase

I'm using the change-case extension and it works fine. I defined the shortcuts:

{ 
  "key": "ctrl+shift+u", 
  "command": "extension.changeCase.upper", 
  "when": "editorTextFocus" 
},
{ 
  "key": "ctrl+u",
  "command": "extension.changeCase.lower", 
  "when": "editorTextFocus" 
},

How to return a boolean method in java?

public boolean verifyPwd(){
        if (!(pword.equals(pwdRetypePwd.getText()))){
                  txtaError.setEditable(true);
                  txtaError.setText("*Password didn't match!");
                  txtaError.setForeground(Color.red);
                  txtaError.setEditable(false);
                  return false;
           }
        else {
            addNewUser();
            return true;
        }
}