Programs & Examples On #Tintcolor

In iOS 7, tint color is a property of UIView. iOS 7 apps often use a tint to define a key color that indicates interactivity and selection state for UI elements throughout the app.

How can I color a UIImage in Swift?

Here is swift 3 version of H R's solution.

func overlayImage(color: UIColor) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
    let context = UIGraphicsGetCurrentContext()

    color.setFill()

    context!.translateBy(x: 0, y: self.size.height)
    context!.scaleBy(x: 1.0, y: -1.0)

    context!.setBlendMode(CGBlendMode.colorBurn)
    let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
    context!.draw(self.cgImage!, in: rect)

    context!.setBlendMode(CGBlendMode.sourceIn)
    context!.addRect(rect)
    context!.drawPath(using: CGPathDrawingMode.fill)

    let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return coloredImage
}

Changing tab bar item image and text color iOS

Swift 3

First of all, make sure you have added the BOOLEAN key "View controller-based status bar appearance" to Info.plist, and set the value to "NO".

Appdelegate.swift

Insert code somewhere after "launchOptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {"

  1. Change the color of the tab bar itself with RGB color value:

UITabBar.appearance().barTintColor = UIColor(red: 0.145, green: 0.592, blue: 0.804, alpha: 1.00)

OR one of the default UI colors:

UITabBar.appearance().barTintColor = UIColor.white)


  1. Change the text color of the tab items:

The selected item

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .selected)

The inactive items

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.black], for: .normal)

  1. To change the color of the image, I believe the easiest approach is to make to separate images, one for each state.

If you don´t make the icons from scratch, alternating black and white versions are relatively easy to make in Photoshop.


Adobe Photoshop (almost any version will do)

Make sure your icon image has transparent background, and the icon itself is solid black (or close).

Open the image file, save it under a different file name (e.g. exampleFilename-Inverted.png)

In the "Adjustments" submenu on the "Image" menu:

Click "Invert"

You now have a negative of your original icon.

In XCode, set one of the images as "Selected Image" under the Tab Bar Properties in your storyboard, and specify the "inactive" version under "Bar Item" image.

Ta-Da

Change color of Back button in navigation bar

Lets try this code:

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

    let navigationBarAppearace = UINavigationBar.appearance()
    navigationBarAppearace.tintColor = UIColor.whiteColor()  // Back buttons and such
    navigationBarAppearace.barTintColor = UIColor.purpleColor()  // Bar's background color
    navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]  // Title's text color

    self.window?.backgroundColor = UIColor.whiteColor()
    return true
}

NavigationBar bar, tint, and title text color in iOS 8

In AppDelegate.swift, in application(_:didFinishLaunchingWithOptions:) I put the following:

UINavigationBar.appearance().barTintColor = UIColor(red: 234.0/255.0, green: 46.0/255.0, blue: 73.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]

(For Swift 4 or earlier use NSAttributedStringKey instead of NSAttributedString.Key)

For titleTextAttributes, the docs say:

You can specify the font, text color, text shadow color, and text shadow offset for the title in the text attributes dictionary

Add swipe to delete UITableViewCell

Swift 4

@available(iOS 11.0, *)    
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            let action =  UIContextualAction(style: .normal, title: "", handler: { (action,view,completionHandler ) in
                //do stuff
                completionHandler(true)
                let data:NSDictionary = self.conversations[indexPath.row] as! NSDictionary
                print(data)
                let alert:UIAlertController = UIAlertController(title: "", message: "are you sure want to delete ?", preferredStyle: .alert)

                alert.addAction(UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.cancel, handler: { (action) in
                }))
                self.present(alert, animated: true, completion: nil)
            })
            action.image = UIImage(named: "")
            action.backgroundColor = UIColor(red: 0/255, green: 148/255, blue: 204/255, alpha: 1.0)
            let confrigation = UISwipeActionsConfiguration(actions: [action])

            return confrigation
        }

How can I change image tintColor in iOS and WatchKit

Try this

http://robots.thoughtbot.com/designing-for-ios-blending-modes

or

- (void)viewDidLoad
{
[super viewDidLoad];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 300, 50)];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:13];
label.text = @"These checkmarks use the same gray checkmark image with a tintColor applied to the image view";
[self.view addSubview:label];

[self _createImageViewAtY:100 color:[UIColor purpleColor]];
}

- (void)_createImageViewAtY:(int)y color:(UIColor *)color {
UIImage *image = [[UIImage imageNamed:@"gray checkmark.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect frame = imageView.frame;
frame.origin.x = 100;
frame.origin.y = y;
imageView.frame = frame;

if (color)
    imageView.tintColor = color;

[self.view addSubview:imageView];
}

Changing Tint / Background color of UITabBar

I have been able to make it work by subclassing a UITabBarController and using private classes:

@interface UITabBarController (private)
- (UITabBar *)tabBar;
@end

@implementation CustomUITabBarController


- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 48);
    UIView *v = [[UIView alloc] initWithFrame:frame];
    [v setBackgroundColor:kMainColor];
    [v setAlpha:0.5];
    [[self tabBar] addSubview:v];
    [v release];

}
@end

WPF ListView turn off selection

Further to the solution above... I would use a MultiTrigger to allow the MouseOver highlights to continue to work after selection such that your ListViewItem's style will be:

        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Style.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsSelected" Value="True" />
                            <Condition Property="IsMouseOver" Value="False" />
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Background" Value="{x:Null}" />
                            <Setter Property="BorderBrush" Value="{x:Null}" />
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                </Style.Triggers>
            </Style>
        </ListView.ItemContainerStyle>

pypi UserWarning: Unknown distribution option: 'install_requires'

This is a warning from distutils, and is a sign that you do not have setuptools installed. Installing it from http://pypi.python.org/pypi/setuptools will remove the warning.

How to create User/Database in script for Docker Postgres

You need to have the database running before you create the users. For this you need multiple processes. You can either start postgres in a subshell (&) in the shell script, or use a tool like supervisord to run postgres and then run any initialization scripts.

A guide to supervisord and docker https://docs.docker.com/articles/using_supervisord/

Change app language programmatically in Android

Just handle in method

@Override public void onConfigurationChanged(android.content.res.Configuration newConfig).

Follow the Link

I think it is useful

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

How to test if list element exists?

rlang::has_name() can do this too:

foo = list(a = 1, bb = NULL)
rlang::has_name(foo, "a")  # TRUE
rlang::has_name(foo, "b")  # FALSE. No partial matching
rlang::has_name(foo, "bb")  # TRUE. Handles NULL correctly
rlang::has_name(foo, "c")  # FALSE

As you can see, it inherently handles all the cases that @Tommy showed how to handle using base R and works for lists with unnamed items. I would still recommend exists("bb", where = foo) as proposed in another answer for readability, but has_name is an alternative if you have unnamed items.

Convert row names into first column

You can both remove row names and convert them to a column by reference (without reallocating memory using ->) using setDT and its keep.rownames = TRUE argument from the data.table package

library(data.table)
setDT(df, keep.rownames = TRUE)[]
#    rn     VALUE  ABS_CALL DETECTION     P.VALUE
# 1:  1 1007_s_at  957.7292         P 0.004862793
# 2:  2   1053_at  320.6327         P 0.031335632
# 3:  3    117_at  429.8423         P 0.017000453
# 4:  4    121_at 2395.7364         P 0.011447358
# 5:  5 1255_g_at  116.4936         A 0.397993682
# 6:  6   1294_at  739.9271         A 0.066864977

As mentioned by @snoram, you can give the new column any name you want, e.g. setDT(df, keep.rownames = "newname") would add "newname" as the rows column.

Twitter Bootstrap add active class to li

$(function() {
// Highlight the active nav link.
var url = window.location.pathname;
var filename = url.substr(url.lastIndexOf('/') + 1);
$('.navbar a[href$="' + filename + '"]').parent().addClass("active");

});

For more details Click Here!

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can use it like this:

In Mvc:

@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});

In Html:

<input type="text" name="Id" data_val_number="10"/>

Connection string using Windows Authentication

This is shorter and works

<connectionStrings>      
<add name="DBConnection"
             connectionString="data source=SERVER\INSTANCE;
       Initial Catalog=MyDB;Integrated Security=SSPI;"
             providerName="System.Data.SqlClient" />
</connectionStrings> 

Persist Security Info not needed

How to convert "0" and "1" to false and true

Or if the Boolean value is not been returned, you can do something like this:

bool boolValue = (returnValue == "1");

ActionBarActivity: cannot be resolved to a type

I was also following the instructions on http://developer.android.com/training/basics/actionbar/setting-up.html

and even though I did everything in the tutorial, as soon as "extends Action" is changed to "extends ActionBarActivity" all sorts of errors appear in Eclipse, including the "ActionBarActivitycannot be resolved to a type"

None of the above solutions worked for me, but what did work is adding this line to the top:

import android.support.v7.app.ActionBarActivity;

How to run a command in the background on Windows?

If you take 5 minutes to download visual studio and make a Console Application for this, your problem is solved.

using System;
using System.Linq;
using System.Diagnostics;
using System.IO;

namespace BgRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting: " + String.Join(" ", args));
            String arguments = String.Join(" ", args.Skip(1).ToArray());
            String command = args[0];

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(command);
            p.StartInfo.Arguments = arguments;
            p.StartInfo.WorkingDirectory = Path.GetDirectoryName(command);
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.Start();
        }
    }
}

Examples of usage:

BgRunner.exe php/php-cgi -b 9999
BgRunner.exe redis/redis-server --port 3000
BgRunner.exe nginx/nginx

How does @synchronized lock/unlock in Objective-C?

It just associates a semaphore with every object, and uses that.

What is an Endpoint?

The term Endpoint was initially used for WCF services. Later even though this word is being used synonymous to API resources, REST recommends to call these URI (URI[s] which understand HTTP verbs and follow REST architecture) as "Resource".

In a nutshell, a Resource or Endpoint is kind of an entry point to a remotely hosted application which lets the users to communicate to it via HTTP protocol.

How to log SQL statements in Spring Boot?

Settings to avoid

You should not use this setting:

spring.jpa.show-sql=true 

The problem with show-sql is that the SQL statements are printed in the console, so there is no way to filter them, as you'd normally do with a Logging framework.

Using Hibernate logging

In your log configuration file, if you add the following logger:

<logger name="org.hibernate.SQL" level="debug"/>

Then, Hibernate will print the SQL statements when the JDBC PreparedStatement is created. That's why the statement will be logged using parameter placeholders:

INSERT INTO post (title, version, id) VALUES (?, ?, ?)

If you want to log the bind parameter values, just add the following logger as well:

<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="trace"/>

Once you set the BasicBinder logger, you will see that the bind parameter values are logged as well:

DEBUG [main]: o.h.SQL - insert into post (title, version, id) values (?, ?, ?)
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [1] as [VARCHAR] - [High-Performance Java Persistence, part 1]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [2] as [INTEGER] - [0]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [3] as [BIGINT] - [1]

Using datasource-proxy

The datasource-proxy OSS framework allows you to proxy the actual JDBC DataSource, as illustrated by the following diagram:

DataSource-Proxy

You can define the dataSource bean that will be used by Hibernate as follows:

@Bean
public DataSource dataSource(DataSource actualDataSource) {
    SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener();
    loggingListener.setQueryLogEntryCreator(new InlineQueryLogEntryCreator());
    return ProxyDataSourceBuilder
        .create(actualDataSource)
        .name(DATA_SOURCE_PROXY_NAME)
        .listener(loggingListener)
        .build();
}

Notice that the actualDataSource must be the DataSource defined by the [connection pool][2] you are using in your application.

Next, you need to set the net.ttddyy.dsproxy.listener log level to debug in your logging framework configuration file. For instance, if you're using Logback, you can add the following logger:

<logger name="net.ttddyy.dsproxy.listener" level="debug"/>

Once you enable datasource-proxy, the SQl statement are going to be logged as follows:

Name:DATA_SOURCE_PROXY, Time:6, Success:True,
Type:Prepared, Batch:True, QuerySize:1, BatchSize:3,
Query:["insert into post (title, version, id) values (?, ?, ?)"],
Params:[(Post no. 0, 0, 0), (Post no. 1, 0, 1), (Post no. 2, 0, 2)]

Throughput and bandwidth difference?

The bandwidth of a link is the theoretical maximum amount of data that could be sent over that channel without regard to practical considerations. For example, you could pump 10^9 bits per second down a Gigabit Ethernet link over a Cat-6e or fiber optic cable. Unfortunately this would be a completely unformatted stream of bits.

To make it actually useful there's a start of frame sequence which precedes any actual data bits, a frame check sequence at the end for error detection and an idle period between transmitted frames. All of those occupy what is referred to as "bit times" meaning the amount of time it takes to transmit one bit over the line. This is all necessary overhead, but is subtracted from the total bandwidth of the link.

And this is only for the lowest level protocol which is stuffing raw data out onto the wire. Once you start adding in the MAC addresses, an IP header and a TCP or UDP header, then you've added even more overhead.

Check out http://en.wikipedia.org/wiki/Ethernet_frame. Similar problems exist for other transmission media.

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Background

Invariant's answer is a good resource for how everything was started and what was the state of JavaFX on embedded and mobile in beginning of 2014. But, a lot has changed since then and the users who stumble on this thread do not get the updated information.

Most of my points are related to Invariant's answer, so I would suggest to go through it first.

Current Status of JavaFX on Mobile / Embedded

UPDATE

JavaFXPorts has been deprecated. Gluon Mobile now uses GraalVM underneath. There are multiple advantages of using GraalVM. Please check this blogpost from Gluon. The IDE plugins have been updated to use Gluon Client plugins which leverages GraalVM to AOT compile applications for Android/iOS.

Old answer with JavaFXPorts

Some bad news first:

Now, some good news:

  • JavaFX still runs on Android, iOS and most of the Embedded devices
  • JavaFXPorts SDK for android, iOS and embedded devices can be downloaded from here
  • JavaFXPorts project is still thriving and it is easier than ever to run JavaFX on mobile devices, all thanks to the IDE plugins that is built on top of these SDKs and gets you started in a few minutes without the hassle of installing any SDK
  • JavaFX 3D is now supported on mobile devices
  • GluonVM to replace RoboVM enabling Java 9 support for mobile developers. Yes, you heard it right.
  • Mobile Project has been launched by Oracle to support JDK on all major mobile platforms. It should support JavaFX as well ;)

How to get started

If you are not the DIY kind, I would suggest to install the IDE plugin on your favourite IDE and get started.

Most of the documentation on how to get started can be found here and some of the samples can be found here.

When is it appropriate to use C# partial classes?

Aside from the other answers...

I've found them helpful as a stepping-stone in refactoring god-classes. If a class has multiple responsibilities (especially if it's a very large code-file) then I find it beneficial to add 1x partial class per-responsibility as a first-pass for organizing and then refactoring the code.

This helps greatly because it can help with making the code much more readable without actually effecting the executing behavior. It also can help identify when a responsibility is easy to refactor out or is tightly tangled with other aspects.

However--to be clear--this is still bad code, at the end of development you still want one responsibility per-class (NOT per partial class). It's just a stepping-stone :)

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

Python function pointer

It's much nicer to be able to just store the function itself, since they're first-class objects in python.

import mypackage

myfunc = mypackage.mymodule.myfunction
myfunc(parameter1, parameter2)

But, if you have to import the package dynamically, then you can achieve this through:

mypackage = __import__('mypackage')
mymodule = getattr(mypackage, 'mymodule')
myfunction = getattr(mymodule, 'myfunction')

myfunction(parameter1, parameter2)

Bear in mind however, that all of that work applies to whatever scope you're currently in. If you don't persist them somehow, you can't count on them staying around if you leave the local scope.

How to subtract X day from a Date object in Java?

Java 8 and later

With Java 8's date time API change, Use LocalDate

LocalDate date = LocalDate.now().minusDays(300);

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

Importing from a relative path in Python

EDIT Nov 2014 (3 years later):

Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:

from ..Common import Common

As a caveat, this will only work if you run your python as a module, from outside of the package. For example:

python -m Proj

Original hacky way

This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.

You can add Common/ to your sys.path (the list of paths python looks at to import things):

import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common

os.path.dirname(__file__) just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.

Add an index (numeric ID) column to large data frame

Well, if I understand you correctly. You can do something like the following.

To show it, I first create a data.frame with your example

df <- 
scan(what = character(), sep = ",", text =
"001, 34, 3, aa.com
002, 4, 4, aa.com
034, 3, 3, aa.com
001, 12, 4, bb.com
002, 1, 3, bb.com
034, 2, 2, cc.com")

df <- as.data.frame(matrix(df, 6, 4, byrow = TRUE))
colnames(df) <- c("user_id", "number_of_logins", "number_of_images", "web")  

You can then run one of the following lines to add a column (at the end of the data.frame) with the row number as the generated user id. The second lines simply adds leading zeros.

df$generated_uid  <- 1:nrow(df)
df$generated_uid2 <- sprintf("%03d", 1:nrow(df))

If you absolutely want the generated user id to be the first column, you can add the column like so:

df <- cbind("generated_uid3" = sprintf("%03d", 1:nrow(df)), df)

or simply rearrage the columns.

Where is adb.exe in windows 10 located?

You'll find it in the AppData folder if you choose to install it in the default location. Otherwise, it will be located at the folder where you installed your Android SDK/platform-tools folder.

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

Remove blue border from css custom-styled button in Chrome

I just remove the outline from all the tags in the page by selecting all and applying outline:none to everything:)

*:focus {outline:none}

As bagofcole mentioned, you might need to add !important as well, so the style will look like this:

*:focus {outline:none !important}

Remove menubar from Electron app

When you package your app the default menu won't be there anymore, if this is bugging you during development then you can call setMenu(null) on the browser window as suggested by @TonyVincent.

What is the difference between a string and a byte string?

The Python languages includes str and bytes as standard "Built-in Types". In other words, they are both classes. I don't think it's worthwhile trying to rationalize why Python has been implemented this way.

Having said that, str and bytes are very similar to one another. Both share most of the same methods. The following methods are unique to the str class:

casefold
encode
format
format_map
isdecimal
isidentifier
isnumeric
isprintable

The following methods are unique to the bytes class:

decode
fromhex
hex

how to read System environment variable in Spring applicationContext

You can mention your variable attributes in a property file and define environment specific property files like local.properties, production.propertied etc.

Now based on the environment, one of these property file can be read in one the listeners invoked at startup, like the ServletContextListener.

The property file will contain the the environment specific values for various keys.

Sample "local.propeties"

db.logsDataSource.url=jdbc:mysql://localhost:3306/logs
db.logsDataSource.username=root
db.logsDataSource.password=root

db.dataSource.url=jdbc:mysql://localhost:3306/main
db.dataSource.username=root
db.dataSource.password=root

Sample "production.properties"

db.logsDataSource.url=jdbc:mariadb://111.111.111.111:3306/logs
db.logsDataSource.username=admin
db.logsDataSource.password=xyzqer

db.dataSource.url=jdbc:mysql://111.111.111.111:3306/carsinfo
db.dataSource.username=admin
db.dataSource.password=safasf@mn

For using these properties file, you can make use of REsource as mentioned below

        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        ResourceLoader resourceLoader = new DefaultResourceLoader();

        Resource resource = resourceLoader.getResource("classpath:"+System.getenv("SERVER_TYPE")+"DB.properties");
        configurer.setLocation(resource);
        configurer.postProcessBeanFactory(beanFactory);

SERVER_TYPE can be defined as the environment variable with appropriate values for local and production environment.

With these changes the appplicationContext.xml will have the following changes

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
 <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="${db.dataSource.url}" />
  <property name="username" value="${db.dataSource.username}" />
  <property name="password" value="${db.dataSource.password}" />

Hope this helps .

Explain the "setUp" and "tearDown" Python methods used in test cases

You can use these to factor out code common to all tests in the test suite.

If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

For example:

class TurretTest(unittest.TestCase):

    def setUp(self):
        self.turret_factory = TurretFactory()
        self.turret = self.turret_factory.CreateTurret()

    def test_turret_is_on_by_default(self):
        self.assertEquals(True, self.turret.is_on())

    def test_turret_turns_can_be_turned_off(self):
        self.turret.turn_off()
        self.assertEquals(False, self.turret.is_on())

Test if numpy array contains only zeros

This will work.

def check(arr):
    if np.all(arr == 0):
        return True
    return False

What does it mean "No Launcher activity found!"

I fixed the problem by adding activity block in the application tag. I created the project using wizard, I don't know why my AdroidManifest.xml file was not containing application block? I added the application block:

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".ToDoListActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And I get the desired output on the emulator.

How to add new contacts in android

Here I am posting a piece of code that i use to add a new contact. It works fine for me. I hope it will help you.

 String DisplayName = "XYZ";
 String MobileNumber = "123456";
 String HomeNumber = "1111";
 String WorkNumber = "2222";
 String emailID = "[email protected]";
 String company = "bad";
 String jobTitle = "abcd";

 ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();

 ops.add(ContentProviderOperation.newInsert(
 ContactsContract.RawContacts.CONTENT_URI)
     .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
     .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
     .build());

 //------------------------------------------------------ Names
 if (DisplayName != null) {
     ops.add(ContentProviderOperation.newInsert(
     ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
         .withValue(
     ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
     DisplayName).build());
 }

 //------------------------------------------------------ Mobile Number                     
 if (MobileNumber != null) {
     ops.add(ContentProviderOperation.
     newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
         .build());
 }

 //------------------------------------------------------ Home Numbers
 if (HomeNumber != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, HomeNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
         .build());
 }

 //------------------------------------------------------ Work Numbers
 if (WorkNumber != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
         .build());
 }

 //------------------------------------------------------ Email
 if (emailID != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
         .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
         .build());
 }

 //------------------------------------------------------ Organization
 if (!company.equals("") && !jobTitle.equals("")) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
         .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
         .build());
 }

 // Asking the Contact provider to create a new contact                 
 try {
     getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
 } catch (Exception e) {
     e.printStackTrace();
     Toast.makeText(myContext, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
 } 

Here is the code. Integrate it according to your need. I hope it will help.

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

It says it all IsNullOrEmpty() does not include white spacing while IsNullOrWhiteSpace() does!

IsNullOrEmpty() If string is:
-Null
-Empty

IsNullOrWhiteSpace() If string is:
-Null
-Empty
-Contains White Spaces Only

C# how to use enum with switch

The correct answer is already given, nevertheless here is the better way (than switch):

private Dictionary<Operator, Func<int, int, double>> operators =
    new Dictionary<Operator, Func<int, int, double>>
    {
        { Operator.PLUS, ( a, b ) => a + b },
        { Operator.MINUS, ( a, b ) => a - b },
        { Operator.MULTIPLY, ( a, b ) => a * b },
        { Operator.DIVIDE ( a, b ) => (double)a / b },
    };

public double Calculate( int left, int right, Operator op )
{
    return operators.ContainsKey( op ) ? operators[ op ]( left, right ) : 0.0;
}

What is the standard exception to throw in Java for not supported/implemented operations?

If you create a new (not yet implemented) function in NetBeans, then it generates a method body with the following statement:

throw new java.lang.UnsupportedOperationException("Not supported yet.");

Therefore, I recommend to use the UnsupportedOperationException.

possible EventEmitter memory leak detected

I prefer to hunt down and fix problems instead of suppressing logs whenever possible. After a couple days of observing this issue in my app, I realized I was setting listeners on the req.socket in an Express middleware to catch socket io errors that kept popping up. At some point, I learned that that was not necessary, but I kept the listeners around anyway. I just removed them and the error you are experiencing went away. I verified it was the cause by running requests to my server with and without the following middleware:

socketEventsHandler(req, res, next) {
        req.socket.on("error", function(err) {
            console.error('------REQ ERROR')
            console.error(err.stack)
        });
        res.socket.on("error", function(err) {
            console.error('------RES ERROR')
            console.error(err.stack)
        });
        next();
    }

Removing that middleware stopped the warning you are seeing. I would look around your code and try to find anywhere you may be setting up listeners that you don't need.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

On CentOS Linux, Python3.6, I edited this file (make a backup copy first)

/usr/lib/python3.6/site-packages/certifi/cacert.pem

to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

How to copy a selection to the OS X clipboard

You can use MacVim when you're on a Mac to easily access the clipboard using the standard OS keys.

It's also fully backward compatible with normal Vim, so I don't even have to have a separate .vimrc.

What is href="#" and why is it used?

The href attribute defines the URL of the resource of a link. If the anchor tag does not have href tag then it will not become hyperlink. The href attribute have the following values:

1. Absolute path: move to another site like href="http://www.google.com"
2. Relative path: move to another page within the site like herf ="defaultpage.aspx"
3. Move to an element with a specified id within the page like href="#bottom"
4. href="javascript:void(0)", it does not move anywhere.
5. href="#" , it does not move anywhere but scroll on the top of the current page.
6. href= "" , it will load the current page but some browsers causes forbidden errors.

Note: When we do not need to specified any url inside a anchor tag then use 
<a href="javascript:void(0)">Test1</a>

Visual Studio 2017 - Git failed with a fatal error

I opened Credential Manager in Windows (not Visual Studio), selected "Windows Credentials", found my git:https//stash....com Generic Credential, clicked the bubble arrow down to make visible the User name and Password fields with Edit button. Clicked Edit, and put in my correct password there. Then started work right after that, no need to close anything.

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.

First we create "Parent" object function

function Parent(){

}

Then add a prototype to "Parent" object function

 Parent.prototype = {
 primitive : 1,
 object : {
    one : 1
   }
}

Create "Child" object function

function Child(){

}

Assign child prototype (Make child prototype inherit from parent prototype)

Child.prototype = Object.create(Parent.prototype);

Assign proper "Child" prototype constructor

Child.prototype.constructor = Child;

Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects

Child.prototype.changeProps = function(){
    this.primitive = 2;
    this.object.one = 2;
};

Initiate Parent (dad) and Child (son) objects.

var dad = new Parent();
var son = new Child();

Call Child (son) changeProps method

son.changeProps();

Check the results.

Parent primitive property did not change

console.log(dad.primitive); /* 1 */

Child primitive property changed (rewritten)

console.log(son.primitive); /* 2 */

Parent and Child object.one properties changed

console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */

Working example here http://jsbin.com/xexurukiso/1/edit/

More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Convert string to JSON Object

Quick answer, this eval work:

eval('var obj = {"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}')

React - changing an uncontrolled input

An update for this. For React Hooks use const [name, setName] = useState(" ")

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

#include<iostream>
using namespace std;
void expand(int);
int main()
{
    int num;
    cout<<"Enter a number : ";
    cin>>num;
    expand(num);
}
void expand(int value)
{
    const char * const ones[20] = {"zero", "one", "two", "three","four","five","six","seven",
    "eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen",
    "eighteen","nineteen"};
    const char * const tens[10] = {"", "ten", "twenty", "thirty","forty","fifty","sixty","seventy",
    "eighty","ninety"};

    if(value<0)
    {
        cout<<"minus ";
        expand(-value);
    }
    else if(value>=1000)
    {
        expand(value/1000);
        cout<<" thousand";
        if(value % 1000)
        {
            if(value % 1000 < 100)
            {
                cout << " and";
            }
            cout << " " ;
            expand(value % 1000);
        }
    }
    else if(value >= 100)
    {
        expand(value / 100);
        cout<<" hundred";
        if(value % 100)
        {
            cout << " and ";
            expand (value % 100);
        }
    }
    else if(value >= 20)
    {
        cout << tens[value / 10];
        if(value % 10)
        {
            cout << " ";
            expand(value % 10);
        }
    }
    else
    {
        cout<<ones[value];
    }
    return;
}

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Here is the documentation for Collections.

Set keyboard caret position in html textbox

HTMLInputElement.setSelectionRange( selectionStart, selectionEnd );

// References
var e = document.getElementById( "helloworldinput" );

// Move caret to beginning on focus
e.addEventListener( "focus", function( event )
{
    // References
    var e = event.target;

    // Action
    e.setSelectionRange( 0, 0 );            // Doesn’t work for focus event
    
    window.setTimeout( function()
    {
        e.setSelectionRange( 0, 0 );        // Works
        //e.setSelectionRange( 1, 1 );      // Move caret to second position
        //e.setSelectionRange( 1, 2 );      // Select second character

    }, 0 );

}, false );

Browser compatibility (only for types: text, search, url, tel and password): https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange#Specifications

How to store values from foreach loop into an array?

<?php 
$items = array();
$count = 0;
foreach($group_membership as $i => $username) { 
 $items[$count++] = $username; 
} 
print_r($items); 
?>

Updating to latest version of CocoaPods?

Using CocoaPods with a Gemfile

With a Gemfile setup, you run bundle install to install, or bundle update to update within your Gemfile's constraints. From here on in however, you will need to remember to run bundle exec before any terminal commands that have come in via bundler. Given that CocoaPods is included in the above this means any time you would write pod XX YY you need to do bundle exec pod XX YY.

Doing it without bundle exec will bypass your Gemfile's specific versioning and will use the latest version of the library within RubyGems. This could potentially be the exact same version, but it can often not. If you are including CocoaPods plugins then they may also not be run.

This means you can be sure that foundational tooling for projects are versioned just like your personal libraries.

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

Turn Pandas Multi-Index into column

I ran into Karl's issue as well. I just found myself renaming the aggregated column then resetting the index.

df = pd.DataFrame(df.groupby(['arms', 'success'])['success'].sum()).rename(columns={'success':'sum'})

enter image description here

df = df.reset_index()

enter image description here

jQuery event to trigger action when a div is made visible

Use jQuery Waypoints :

$('#contentDiv').waypoint(function() {
   alert('do something');
});

Other examples on the site of jQuery Waypoints.

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

JavaScript "cannot read property "bar" of undefined

Just check for it before you pass to your function. So you would pass:

thing.foo ? thing.foo.bar : undefined

Go To Definition: "Cannot navigate to the symbol under the caret."

Just do it:

  • Close Visual Studio
  • Go to project folder and delete .user file (may be hidden)
  • Open Visual Studio

Spring MVC: How to return image in @ResponseBody?

I think you maybe need a service to store file upload and get that file. Check more detail from here

1) Create a Storage Sevice

@Service
public class StorageService {

Logger log = LoggerFactory.getLogger(this.getClass().getName());
private final Path rootLocation = Paths.get("upload-dir");

public void store(MultipartFile file) {
    try {
        Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
    } catch (Exception e) {
        throw new RuntimeException("FAIL!");
    }
}

public Resource loadFile(String filename) {
    try {
        Path file = rootLocation.resolve(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new RuntimeException("FAIL!");
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException("FAIL!");
    }
}

public void deleteAll() {
    FileSystemUtils.deleteRecursively(rootLocation.toFile());
}

public void init() {
    try {
        Files.createDirectory(rootLocation);
    } catch (IOException e) {
        throw new RuntimeException("Could not initialize storage!");
    }
}
}

2) Create Rest Controller to upload and get file

@Controller
public class UploadController {

@Autowired
StorageService storageService;

List<String> files = new ArrayList<String>();

@PostMapping("/post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
    String message = "";
    try {
        storageService.store(file);
        files.add(file.getOriginalFilename());

        message = "You successfully uploaded " + file.getOriginalFilename() + "!";
        return ResponseEntity.status(HttpStatus.OK).body(message);
    } catch (Exception e) {
        message = "FAIL to upload " + file.getOriginalFilename() + "!";
        return      ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
    }
}

@GetMapping("/getallfiles")
public ResponseEntity<List<String>> getListFiles(Model model) {
    List<String> fileNames = files
            .stream().map(fileName -> MvcUriComponentsBuilder
                    .fromMethodName(UploadController.class, "getFile", fileName).build().toString())
            .collect(Collectors.toList());

    return ResponseEntity.ok().body(fileNames);
}

@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
    Resource file = storageService.loadFile(filename);
    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
            .body(file);
}

}

Delete last commit in bitbucket

By now, cloud bitbucket (I'm not sure which version) allows to revert a commit from the file system as follows (I do not see how to revert from the Bitbucket interface in the Chrome browser).

-backup your entire directory to secure the changes you inadvertently committed

-select checked out directory

-right mouse button: tortoise git menu

-repo-browser (the menu option 'revert' only undoes the uncommited changes)

-press the HEAD button

-select the uppermost line (the last commit)

-right mouse button: revert change by this commit

-after it undid the changes on the file system, press commit

-this updates GIT with a message 'Revert (your previous message). This reverts commit so-and-so'

-select 'commit and push'.

Gson and deserializing an array of objects with arrays in it

Use your bean class like this, if your JSON data starts with an an array object. it helps you.

Users[] bean = gson.fromJson(response,Users[].class);

Users is my bean class.

Response is my JSON data.

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

If you came here searching OpenID Connect (OIDC): OAuth 2.0 != OIDC

I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)

OAuth 2.0 Access Tokens##

For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)

For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).

OIDC ID Tokens##

OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud claim in ID Tokens. (openid-connect-core-1.0)

aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.

furthermore OIDC specifies the azp claim that is used in conjunction with aud when aud has more than one value.

azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.

How to change the server port from 3000?

If you don't have bs-config.json, you can change the port inside the lite-server module. Go to node_modules/lite-server/lib/config-defaults.js in your project, then add the port in "modules.export" like this.

module.export {
    port :8000, // to any available port
    ...
}

Then you can restart the server.

Python string to unicode

Decode it with the unicode-escape codec:

>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…

This is because for a non-unicode string the \u2026 is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'). You need to decode the escapes, and the unicode-escape codec can do that for you.

Note that you can get unicode to recognise it in the same way by specifying the codec argument:

>>> unicode(a, 'unicode-escape')
u'Hello\u2026'

But the a.decode() way is nicer.

PL/SQL, how to escape single quote in a string?

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

How to git clone a specific tag

git clone -b 13.1rc1-Gotham  --depth 1  https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Counting objects: 17977, done.
remote: Compressing objects: 100% (13473/13473), done.
Receiving objects:  36% (6554/17977), 19.21 MiB | 469 KiB/s    

Will be faster than :

git clone https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Reusing existing pack: 281705, done.
remote: Counting objects: 533, done.
remote: Compressing objects: 100% (177/177), done.
Receiving objects:  14% (40643/282238), 55.46 MiB | 578 KiB/s

Or

git clone -b 13.1rc1-Gotham  https://github.com/xbmc/xbmc.git
Cloning into 'xbmc'...
remote: Reusing existing pack: 281705, done.
remote: Counting objects: 533, done.
remote: Compressing objects: 100% (177/177), done.
Receiving objects:  12% (34441/282238), 20.25 MiB | 461 KiB/s

nodemon command is not recognized in terminal for node js server

You can run your node app by simply typing nodemon It First run index.js You can put your entry point in that file easily.

If you have not installed nodemon then you first you have to install it by

npm install -g nodemon

If you got any permission error then use

sudo npm install -g nodemon

You can check nodemon exists or not by

nodemon -v

Using JAXB to unmarshal/marshal a List<String>

I have encountered this pattern a few times, I found that the easiest way is to define an inner class with JaxB annotations. (anyways, you'll probably want to define the root tag name)

so your code would look something like this

@GET
@Path("/test2")
public Object test2(){
   MyResourceWrapper wrapper = new MyResourceWrapper();
   wrapper .add("a");
   wrapper .add("b");
   return wrapper ;
}

@XmlRootElement(name="MyResource")
private static class MyResourceWrapper {
       @XmlElement(name="Item")
       List<String> list=new ArrayList<String>();
       MyResourceWrapper (){}

       public void add(String s){ list.add(s);}
 }

if you work with javax.rs (jax-rs) I'd return Response object with the wrapper set as its entity

Determine whether a key is present in a dictionary

My answer is "neither one".

I believe the most "Pythonic" way to do things is to NOT check beforehand if the key is in a dictionary and instead just write code that assumes it's there and catch any KeyErrors that get raised because it wasn't.

This is usually done with enclosing the code in a try...except clause and is a well-known idiom usually expressed as "It's easier to ask forgiveness than permission" or with the acronym EAFP, which basically means it is better to try something and catch the errors instead for making sure everything's OK before doing anything. Why validate what doesn't need to be validated when you can handle exceptions gracefully instead of trying to avoid them? Because it's often more readable and the code tends to be faster if the probability is low that the key won't be there (or whatever preconditions there may be).

Of course, this isn't appropriate in all situations and not everyone agrees with the philosophy, so you'll need to decide for yourself on a case-by-case basis. Not surprisingly the opposite of this is called LBYL for "Look Before You Leap".

As a trivial example consider:

if 'name' in dct:
    value = dct['name'] * 3
else:
    logerror('"%s" not found in dictionary, using default' % name)
    value = 42

vs

try:
    value = dct['name'] * 3
except KeyError:
    logerror('"%s" not found in dictionary, using default' % name)
    value = 42

Although in the case it's almost exactly the same amount of code, the second doesn't spend time checking first and is probably slightly faster because of it (try...except block isn't totally free though, so it probably doesn't make that much difference here).

Generally speaking, testing in advance can often be much more involved and the savings gain from not doing it can be significant. That said, if 'name' in dict: is better for the reasons stated in the other answers.

If you're interested in the topic, this message titled "EAFP vs LBYL (was Re: A little disappointed so far)" from the Python mailing list archive probably explains the difference between the two approached better than I have here. There's also a good discussion about the two approaches in the book Python in a Nutshell, 2nd Ed by Alex Martelli in chapter 6 on Exceptions titled Error-Checking Strategies. (I see there's now a newer 3rd edition, publish in 2017, which covers both Python 2.7 and 3.x).

Check if an element is a child of a parent

If you are only interested in the direct parent, and not other ancestors, you can just use parent(), and give it the selector, as in target.parent('div#hello').

Example: http://jsfiddle.net/6BX9n/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parent('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

Or if you want to check to see if there are any ancestors that match, then use .parents().

Example: http://jsfiddle.net/6BX9n/1/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parents('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

Programmatically create a UIView with color gradient

My solution is to create UIView subclass with CAGradientLayer accessible as a readonly property. This will allow you to customize your gradient how you want and you don't need to handle layout changes yourself. Subclass implementation:

@interface GradientView : UIView

@property (nonatomic, readonly) CAGradientLayer *gradientLayer;

@end

@implementation GradientView

+ (Class)layerClass
{
    return [CAGradientLayer class];
}

- (CAGradientLayer *)gradientLayer
{
    return (CAGradientLayer *)self.layer;
}

@end

Usage:

self.iconBackground = [GradientView new];
[self.background addSubview:self.iconBackground];
self.iconBackground.gradientLayer.colors = @[(id)[UIColor blackColor].CGColor, (id)[UIColor whiteColor].CGColor];
self.iconBackground.gradientLayer.startPoint = CGPointMake(1.0f, 1.0f);
self.iconBackground.gradientLayer.endPoint = CGPointMake(0.0f, 0.0f);

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I also had this issue and it arose because I re-made the project and then forgot to re-link it by reference in a dependent project.

Thus it was linking by reference to the old project instead of the new one.

It is important to know that there is a bug in re-adding a previously linked project by reference. You've got to manually delete the reference in the vcxproj and only then can you re-add it. This is a known issue in Visual studio according to msdn.

Failed to find 'ANDROID_HOME' environment variable

For those having a portable SDK edition on windows, simply add the 2 following path to your system.

F:\ADT_SDK\sdk\platforms
F:\ADT_SDK\sdk\platform-tools

This worked for me.

How do I drop a foreign key constraint only if it exists in sql server?

Ok, I know I'm late to the party, but here is the syntax I think is best. Add a schema name if needed to the OBJECT_ID clause.

IF OBJECTPROPERTY(OBJECT_ID(N'My_FK_name'),'IsConstraint') =1
ALTER TABLE dbo.TableName DROP CONSTRAINT My_FK_name

How to delete projects in Intellij IDEA 14?

Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like

'C:/xxxxxx/pom.xml' already exists in VFS

Here is what I found would work.

  1. Remove module
  2. File -> Invalidate Cache (at this point the Intelli IDEA wants to restart)
  3. Close project
  4. Delete the folder form system explorer.
  5. Now you can create a project with same name as before.

Html5 Full screen video

You can use html5 video player which has full screen playback option. This is a very good html5 player to have a look.
http://sublimevideo.net/

Is there a 'box-shadow-color' property?

You could use a CSS pre-processor to do your skinning. With Sass you can do something similar to this:

_theme1.scss:

$theme-primary-color: #a00;
$theme-secondary-color: #d00;
// etc.

_theme2.scss:

$theme-primary-color: #666;
$theme-secondary-color: #ccc;
// etc.

styles.scss:

// import whichever theme you want to use
@import 'theme2';

-webkit-box-shadow: inset 0px 0px 2px $theme-primary-color;
-moz-box-shadow: inset 0px 0px 2px $theme-primary-color;

If it's not site wide theming but class based theming you need, then you can do this: http://codepen.io/jjenzz/pen/EaAzo

Converting dict to OrderedDict

If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:

from collections import OrderedDict

order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)

What is the difference between gravity and layout_gravity in Android?

Gravity is used to set text alignment in views but layout_gravity is use to set views it self. Lets take an example if you want to align text written in editText then use gravity and you want align this editText or any button or any view then use layout_gravity, So its very simple.

Rails raw SQL example

I know this is old... But I was having the same problem today and found a solution:

Model.find_by_sql

If you want to instantiate the results:

Client.find_by_sql("
  SELECT * FROM clients
  INNER JOIN orders ON clients.id = orders.client_id
  ORDER BY clients.created_at desc
")
# => [<Client id: 1, first_name: "Lucas" >, <Client id: 2, first_name: "Jan">...]

Model.connection.select_all('sql').to_hash

If you just want a hash of values:

Client.connection.select_all("SELECT first_name, created_at FROM clients
   WHERE id = '1'").to_hash
# => [
  {"first_name"=>"Rafael", "created_at"=>"2012-11-10 23:23:45.281189"},
  {"first_name"=>"Eileen", "created_at"=>"2013-12-09 11:22:35.221282"}
]

Result object:

select_all returns a result object. You can do magic things with it.

result = Post.connection.select_all('SELECT id, title, body FROM posts')
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

Sources:

  1. ActiveRecord - Findinig by SQL.
  2. Ruby on Rails - Active Record Result .

good example of Javadoc

How about the JDK source code?

Number of rows affected by an UPDATE in PL/SQL

SQL%ROWCOUNT can also be used without being assigned (at least from Oracle 11g).

As long as no operation (updates, deletes or inserts) has been performed within the current block, SQL%ROWCOUNT is set to null. Then it stays with the number of line affected by the last DML operation:

say we have table CLIENT

create table client (
  val_cli integer
 ,status varchar2(10)
)
/

We would test it this way:

begin
  dbms_output.put_line('Value when entering the block:'||sql%rowcount);

  insert into client 
            select 1, 'void' from dual
  union all select 4, 'void' from dual
  union all select 1, 'void' from dual
  union all select 6, 'void' from dual
  union all select 10, 'void' from dual;  
  dbms_output.put_line('Number of lines affected by previous DML operation:'||sql%rowcount);

  for val in 1..10
    loop
      update client set status = 'updated' where val_cli = val;
      if sql%rowcount = 0 then
        dbms_output.put_line('no client with '||val||' val_cli.');
      elsif sql%rowcount = 1 then
        dbms_output.put_line(sql%rowcount||' client updated for '||val);
      else -- >1
        dbms_output.put_line(sql%rowcount||' clients updated for '||val);
      end if;
  end loop;  
end;

Resulting in:

Value when entering the block:
Number of lines affected by previous DML operation:5
2 clients updated for 1
no client with 2 val_cli.
no client with 3 val_cli.
1 client updated for 4
no client with 5 val_cli.
1 client updated for 6
no client with 7 val_cli.
no client with 8 val_cli.
no client with 9 val_cli.
1 client updated for 10

The APK file does not exist on disk

If you just want to know the conclusion, please go to the last section. Thanks.

Usually when building project fails, some common tricks you could try:

  • Build -> Clean Project
  • Check Build Variants
  • Restart Android Studio (as you mentioned)

But to be more specific to your problem - when Android Studio could not find the APK file on disk. It means that Android Studio has actually successfully built the project, and also generated the APK, however, for some reason, Android Studio is not able to find the file.

In this case, please check the printed directory according to the log. It's helpful.

For example:

With Android Studio 2.0 Preview (build 143.2443734).

  1. Checkout to a specific commit (so that it's detached from head): git checkout [commit_hash]
  2. Run project
  3. Android Studio tells: The APK file /Users/MyApplicationName/app/build/outputs/apk/app-debug-HEAD.apk does not exist on disk
  4. Go to the directory, there is a file actually named: app-debug-(HEAD.apk (with an extra parenthesis)
  5. Run git branch

    *(HEAD detached at 1a2bfff)

So here you could see, due to my gradle build script's mistake, file naming is somehow wrong.

Above example is just one scenario which could lead to the same issue, but not necessary to be the same root cause as yours.

As a result, I strongly recommend you to check the directory (to find the difference), and check your build.gradle script (you may change the apk name there, something like below):

applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def newFileName = "whatever you want to name it";
            def apk = output.outputFile;
            output.outputFile = new File(apk.parentFile, newFileName);
        }
    }

Passing an array using an HTML form hidden element

You can use serialize and base64_encode from the client side. After that, then use unserialize and base64_decode on the server side.

Like:

On the client side, use:

    $postvalue = array("a", "b", "c");
    $postvalue = base64_encode(serialize($array));

   // Your form hidden input
   <input type="hidden" name="result" value="<?php echo $postvalue; ?>">

On the server side, use:

    $postvalue = unserialize(base64_decode($_POST['result']));
    print_r($postvalue) // Your desired array data will be printed here

Can an AWS Lambda function call another

Since this question was asked, Amazon has released Step Functions (https://aws.amazon.com/step-functions/).

One of the core principles behind AWS Lambda is that you can focus more on business logic and less on the application logic that ties it all together. Step functions allows you to orchestrate complex interactions between functions without having to write the code to do it.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Try to use the latest com.fasterxml.jackson.core/jackson-databind. I upgraded it to 2.9.4 and it works now.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.4</version>
</dependency>

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

D3.js: How to get the computed width and height for an arbitrary element?

Once I faced with the issue when I did not know which the element currently stored in my variable (svg or html) but I needed to get it width and height. I created this function and want to share it:

function computeDimensions(selection) {
  var dimensions = null;
  var node = selection.node();

  if (node instanceof SVGGraphicsElement) { // check if node is svg element
    dimensions = node.getBBox();
  } else { // else is html element
    dimensions = node.getBoundingClientRect();
  }
  console.log(dimensions);
  return dimensions;
}

Little demo in the hidden snippet below. We handle click on the blue div and on the red svg circle with the same function.

_x000D_
_x000D_
var svg = d3.select('svg')
  .attr('width', 50)
  .attr('height', 50);

function computeDimensions(selection) {
    var dimensions = null;
  var node = selection.node();

  if (node instanceof SVGElement) {
    dimensions = node.getBBox();
  } else {
    dimensions = node.getBoundingClientRect();
  }
  console.clear();
  console.log(dimensions);
  return dimensions;
}

var circle = svg
    .append("circle")
    .attr("r", 20)
    .attr("cx", 30)
    .attr("cy", 30)
    .attr("fill", "red")
    .on("click", function() { computeDimensions(circle); });
    
var div = d3.selectAll("div").on("click", function() { computeDimensions(div) });
_x000D_
* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  background: #ffd;
}

.div {
  display: inline-block;
  background-color: blue;
  margin-right: 30px;
  width: 30px;
  height: 30px;
}
_x000D_
<h3>
  Click on blue div block or svg circle
</h3>
<svg></svg>
<div class="div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Calculate the date yesterday in JavaScript

If you want to both get the date for yesterday and format that date in a human readable format, consider creating a custom DateHelper object that looks something like this :

_x000D_
_x000D_
var DateHelper = {_x000D_
    addDays : function(aDate, numberOfDays) {_x000D_
        aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays_x000D_
        return aDate;                                  // Return the date_x000D_
    },_x000D_
    format : function format(date) {_x000D_
        return [_x000D_
           ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes_x000D_
           ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes_x000D_
           date.getFullYear()                          // Get full year_x000D_
        ].join('/');                                   // Glue the pieces together_x000D_
    }_x000D_
}_x000D_
_x000D_
// With this helper, you can now just use one line of readable code to :_x000D_
// ---------------------------------------------------------------------_x000D_
// 1. Get the current date_x000D_
// 2. Subtract 1 day_x000D_
// 3. Format it_x000D_
// 4. Output it_x000D_
// ---------------------------------------------------------------------_x000D_
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -1));
_x000D_
_x000D_
_x000D_

(see also this Fiddle)

How do HashTables deal with collisions?

It will use the equals method to see if the key is present even and especially if there are more than one element in the same bucket.

recyclerview No adapter attached; skipping layout

This happens because the actual inflated layout is different from that which is being referred by you while finding the recyclerView. By default when you create the fragment, the onCreateView method appears as follows: return inflater.inflate(R.layout.<related layout>,container.false);

Instead of that, separately create the view and use that to refer to recyclerView View view= inflater.inflate(R.layout.<related layout>,container.false); recyclerview=view.findViewById(R.id.<recyclerView ID>); return view;

Grep only the first match and stop

You can use below command if you want to print entire line and file name if the occurrence of particular word in current directory you are searching.

grep -m 1 -r "Not caching" * | head -1

How can I set the PATH variable for javac so I can manually compile my .java works?

Follow the steps given here

http://www.javaandme.com/

after setting variable, just navigate to your java file directory in your cmd and type javac "xyx.java"

or if you don't navigate to the directory, then simply specify the full path of java file

javac "/xyz.java"

Convert laravel object to array

If you want to get only ID in array, can use array_map:

    $data = array_map(function($object){
        return $object->ID;
    }, $data);

With that, return an array with ID in every pos.

Using variables inside a bash heredoc

As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.

Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE

Demo: https://ideone.com/rMF2XA

Note that any of the quoting mechanisms -- \____HERE or "____HERE" or '____HERE' -- will disable all variable interpolation, and turn the here-document into a piece of literal text.

A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.

local=$(uname)
ssh -t remote <<:
    echo "$local is the value from the host which ran the ssh command"
    # Prevent here doc from expanding locally; remote won't see backslash
    remote=\$(uname)
    # Same here
    echo "\$remote is the value from the host we ssh:ed to"
:

PHP - Failed to open stream : No such file or directory

There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.

Let's consider that we are troubleshooting the following line:

require "/path/to/file"


Checklist


1. Check the file path for typos

  • either check manually (by visually checking the path)
  • or move whatever is called by require* or include* to its own variable, echo it, copy it, and try accessing it from a terminal:

    $path = "/path/to/file";
    
    echo "Path : $path";
    
    require "$path";
    

    Then, in a terminal:

    cat <file path pasted>
    


2. Check that the file path is correct regarding relative vs absolute path considerations

  • if it is starting by a forward slash "/" then it is not referring to the root of your website's folder (the document root), but to the root of your server.
    • for example, your website's directory might be /users/tony/htdocs
  • if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the current working directory.
    • thus, not relative to the path of your web site's root, or to the file where you are typing
    • for that reason, always use absolute file paths

Best practices :

In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :

  1. use require __DIR__ . "/relative/path/from/current/file". The __DIR__ magic constant returns the directory of the current file.
  2. define a SITE_ROOT constant yourself :

    • at the root of your web site's directory, create a file, e.g. config.php
    • in config.php, write

      define('SITE_ROOT', __DIR__);
      
    • in every file where you want to reference the site root folder, include config.php, and then use the SITE_ROOT constant wherever you like :

      require_once __DIR__."/../config.php";
      ...
      require_once SITE_ROOT."/other/file.php";
      

These 2 practices also make your application more portable because it does not rely on ini settings like the include path.


3. Check your include path

Another way to include files, neither relatively nor purely absolutely, is to rely on the include path. This is often the case for libraries or frameworks such as the Zend framework.

Such an inclusion will look like this :

include "Zend/Mail/Protocol/Imap.php"

In that case, you will want to make sure that the folder where "Zend" is, is part of the include path.

You can check the include path with :

echo get_include_path();

You can add a folder to it with :

set_include_path(get_include_path().":"."/path/to/new/folder");


4. Check that your server has access to that file

It might be that all together, the user running the server process (Apache or PHP) simply doesn't have permission to read from or write to that file.

To check under what user the server is running you can use posix_getpwuid :

$user = posix_getpwuid(posix_geteuid());

var_dump($user);

To find out the permissions on the file, type the following command in the terminal:

ls -l <path/to/file>

and look at permission symbolic notation


5. Check PHP settings

If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.

Three settings could be relevant :

  1. open_basedir
    • If this is set PHP won't be able to access any file outside of the specified directory (not even through a symbolic link).
    • However, the default behavior is for it not to be set in which case there is no restriction
    • This can be checked by either calling phpinfo() or by using ini_get("open_basedir")
    • You can change the setting either by editing your php.ini file or your httpd.conf file
  2. safe mode
    • if this is turned on restrictions might apply. However, this has been removed in PHP 5.4. If you are still on a version that supports safe mode upgrade to a PHP version that is still being supported.
  3. allow_url_fopen and allow_url_include
    • this applies only to including or opening files through a network process such as http:// not when trying to include files on the local file system
    • this can be checked with ini_get("allow_url_include") and set with ini_set("allow_url_include", "1")


Corner cases

If none of the above enabled to diagnose the problem, here are some special situations that could happen :


1. The inclusion of library relying on the include path

It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :

require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php"

But then you still get the same kind of error.

This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.

For example, the Zend framework file mentioned before could have the following include :

include "Zend/Mail/Protocol/Exception.php" 

which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.

In such a case, the only practical solution is to add the directory to your include path.


2. SELinux

If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.

To check whether SELinux is enabled on your system, run the sestatus command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.

To check whether SELinux policies are the reason for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.

setenforce 0

If you no longer have the problem with SELinux turned off, then this is the root cause.

To solve it, you will have to configure SELinux accordingly.

The following context types will be necessary :

  • httpd_sys_content_t for files that you want your server to be able to read
  • httpd_sys_rw_content_t for files on which you want read and write access
  • httpd_log_t for log files
  • httpd_cache_t for the cache directory

For example, to assign the httpd_sys_content_t context type to your website root directory, run :

semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?"
restorecon -Rv /path/to/root

If your file is in a home directory, you will also need to turn on the httpd_enable_homedirs boolean :

setsebool -P httpd_enable_homedirs 1

In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. Here is a tutorial specifically on configuring SELinux for a web server.


3. Symfony

If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app's cache hasn't been reset, either because app/cache has been uploaded, or that cache hasn't been cleared.

You can test and fix this by running the following console command:

cache:clear


4. Non ACSII characters inside Zip file

Apparently, this error can happen also upon calling zip->close() when some files inside the zip have non-ASCII characters in their filename, such as "é".

A potential solution is to wrap the file name in utf8_decode() before creating the target file.

Credits to Fran Cano for identifying and suggesting a solution to this issue

JOptionPane Input to int

// sample code for addition using JOptionPane

import javax.swing.JOptionPane;

public class Addition {

    public static void main(String[] args) {

        String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");

        String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");

        int num1 = Integer.parseInt(firstNumber);
        int num2 = Integer.parseInt(secondNumber);
        int sum = num1 + num2;
        JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
    }
}

How to set default value to the input[type="date"]

Here are three statements for three different dates in the form with three type=date fields.

$inv_date is the current date:

$inv_date = date("Y-m-d");

$inv_date_from is the first day of the current month:

$inv_date_from = date("Y") . "-" . date("m") . "-" . "01";

$inv_date_to is the last day of the month:

$inv_date_to = date("Y-m-t", strtotime(date("Y-m-t")));

I hope this helps :)

Check if XML Element exists

You can validate that and much more by using an XML schema language, like XSD.

If you mean conditionally, within code, then XPath is worth a look as well.

Getting attributes of Enum's value

    public enum DataFilters
    {
        [Display(Name= "Equals")]
        Equals = 1,// Display Name and Enum Name are same 
        [Display(Name= "Does Not Equal")]
        DoesNotEqual = 2, // Display Name and Enum Name are different             
    }

Now it will produce error in this case 1 "Equals"

public static string GetDisplayName(this Enum enumValue)
    {
        var enumMember = enumValue.GetType().GetMember(enumValue.ToString()).First();
        return enumMember.GetCustomAttribute<DisplayAttribute>() != null ? enumMember.GetCustomAttribute<DisplayAttribute>().Name : enumMember.Name;
    }

so if it is same return enum name rather than display name because enumMember.GetCustomAttribute() gets null if displayname and enum name are same.....

Java JDBC connection status

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

Case statement with multiple values in each 'when' block

In a case statement, a , is the equivalent of || in an if statement.

case car
   when 'toyota', 'lexus'
      # code
end

Some other things you can do with a Ruby case statement

How to get the position of a character in Python?

Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last '.', in this case use rfind:

path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15

in my case, I use the following, which works whatever the complete file name is:

filename_without_extension = complete_name[:complete_name.rfind('.')]

extract digits in a simple way from a python string

The simplest way to extract a number from a string is to use regular expressions and findall.

>>> import re
>>> s = '300 gm'
>>> re.findall('\d+', s)
['300']
>>> s = '300 gm 200 kgm some more stuff a number: 439843'
>>> re.findall('\d+', s)
['300', '200', '439843']

It might be that you need something more complex, but this is a good first step.

Note that you'll still have to call int on the result to get a proper numeric type (rather than another string):

>>> map(int, re.findall('\d+', s))
[300, 200, 439843]

How to select only date from a DATETIME field in MySQL?

You can use select DATE(time) from appointment_details for date only

or

You can use select TIME(time) from appointment_details for time only

Virtualenv Command Not Found

I had same problem on Mac OS X El Capitan.

When I installed virtualenv like that sudo pip3 install virtualenv I didn't have virtualenv under my command line.

I solved this problem by following those steps:

  1. Uninstall previous installations.
  2. Switch to super user account prior to virtualenv installation by calling sudo su
  3. Install virtualenv by calling pip3 install virtualenv
  4. Finally you should be able to access virtualenv from both user and super user account.

Convert a SQL Server datetime to a shorter date format

For any versions of SQL Server: dateadd(dd, datediff(dd, 0, getdate()), 0)

Correct way to convert size in bytes to KB, MB, GB in JavaScript

const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

function niceBytes(x){

  let l = 0, n = parseInt(x, 10) || 0;

  while(n >= 1024 && ++l){
      n = n/1024;
  }
  //include a decimal point and a tenths-place digit if presenting 
  //less than ten of KB or greater units
  return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}

Results:

niceBytes(435)                 // 435 bytes
niceBytes(3398)                // 3.3 KB
niceBytes(490398)              // 479 KB
niceBytes(6544528)             // 6.2 MB
niceBytes(23483023)            // 22 MB
niceBytes(3984578493)          // 3.7 GB
niceBytes(30498505889)         // 28 GB
niceBytes(9485039485039445)    // 8.4 PB

Set the table column width constant regardless of the amount of text in its cells?

You need to write this inside the corresponding CSS

table-layout:fixed;

How to keep two folders automatically synchronized?

You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed. If you are looking for the more advanced solution, I would suggest checking Resilio Connect. It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.

Adding n hours to a date in Java?

tl;dr

myJavaUtilDate.toInstant()
              .plusHours( 8 )

Or…

myJavaUtilDate.toInstant()                // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
              .plus(                      // Do the math, adding a span of time to our moment, our `Instant`. 
                  Duration.ofHours( 8 )   // Specify a span of time unattached to the timeline.
               )                          // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.

Using java.time

The java.time framework built into Java 8 and later supplants the old Java.util.Date/.Calendar classes. Those old classes are notoriously troublesome. Avoid them.

Use the toInstant method newly added to java.util.Date to convert from the old type to the new java.time type. An Instant is a moment on the time line in UTC with a resolution of nanoseconds.

Instant instant = myUtilDate.toInstant();

You can add hours to that Instant by passing a TemporalAmount such as Duration.

Duration duration = Duration.ofHours( 8 );
Instant instantHourLater = instant.plus( duration );

To read that date-time, generate a String in standard ISO 8601 format by calling toString.

String output = instantHourLater.toString();

You may want to see that moment through the lens of some region’s wall-clock time. Adjust the Instant into your desired/expected time zone by creating a ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Alternatively, you can call plusHours to add your count of hours. Being zoned means Daylight Saving Time (DST) and other anomalies will be handled on your behalf.

ZonedDateTime later = zdt.plusHours( 8 );

You should avoid using the old date-time classes including java.util.Date and .Calendar. But if you truly need a java.util.Date for interoperability with classes not yet updated for java.time types, convert from ZonedDateTime via Instant. New methods added to the old classes facilitate conversion to/from java.time types.

java.util.Date date = java.util.Date.from( later.toInstant() );

For more discussion on converting, see my Answer to the Question, Convert java.util.Date to what “java.time” type?.


About java.time

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

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

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

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

Where to obtain the java.time classes?

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

How to terminate a window in tmux?

By default
<Prefix> & for killing a window
<Prefix> x for killing a pane
And you can add config info

vi ~/.tmux.conf
bind-key X kill-session

then
<Prefix> X for killing a session

Vue template or render function not defined yet I am using neither?

I had this script in app.js in laravel which automatically adds all components in the component folder.

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key)))

To make it work just add default

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Check if string contains only whitespace

str.isspace() returns False for a valid and empty string

>>> tests = ['foo', ' ', '\r\n\t', '']
>>> print([s.isspace() for s in tests])
[False, True, True, False]

Therefore, checking with not will also evaluate None Type and '' or "" (empty string)

>>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]

When to use cla(), clf() or close() for clearing a plot in matplotlib?

plt.cla() means clear current axis

plt.clf() means clear current figure

also, there's plt.gca() (get current axis) and plt.gcf() (get current figure)

Read more here: Matplotlib, Pyplot, Pylab etc: What's the difference between these and when to use each?

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

Differences between ConstraintLayout and RelativeLayout

In addition to @dhaval-jivani answer.

I've updated the project github project to latest version of constraint layout v.1.1.0-beta3

I've measured and compared the time of onCreate method and time between a start of onCreate and end of execution of last preformDraw method which visible in CPU monitor. All test were done on Samsung S5 mini with android 6.0.1 Here results:

Fresh start (first screen opening after application launch)

Relative Layout

OnCreate: 123ms

Last preformDraw time - OnCreate time: 311.3ms

Constraint Layout

OnCreate: 120.3ms

Last preformDraw time - OnCreate time: 310ms

Besides that, I've checked performance test from this article , here the code and found that on loop counts less than 100 constraint layout variant is faster during execution of inflating, measure, and layout then variants with Relative Layout. And on old Android devices, like Samsung S3 with Android 4.3, the difference is bigger.

As a conclusion I agree with comments from the article:

Does it worth to refactor old views switch on it from RelativeLayout or LinearLayout?

As always: It depends

I wouldn’t refactor anything unless you either have a performance problem with your current layout hierarchy or you want to make significant changes to the layout anyway. Though I haven’t measured it lately, I haven’t found any performance issues in the last releases. So I think you should be safe to use it. but – as I’v said – don’t just migrate for the sake of migrating. Only do so, if there’s a need for and benefit from it. For new layouts, though, I nearly always use ConstraintLayout. It’s so much better compare to what we had before.

How to read the Stock CPU Usage data

More about "load average" showing CPU load over 1 minute, 5 minutes and 15 minutes

Linux, Mac, and other Unix-like systems display “load average” numbers. These numbers tell you how busy your system’s CPU, disk, and other resources are. They’re not self-explanatory at first, but it’s easy to become familiar with them.

WIKI: example, one can interpret a load average of "1.73 0.60 7.98" on a single-CPU system as:

during the last minute, the system was overloaded by 73% on average (1.73 runnable processes, so that 0.73 processes had to wait for a turn for a single CPU system on average).
during the last 5 minutes, the CPU was idling 40% of the time on average.
during the last 15 minutes, the system was overloaded 698% on average (7.98 runnable processes, so that 6.98 processes had to wait for a turn for a single CPU system on average) if dual core mean: 798% - 200% = 598%. 

You probably have a system with multiple CPUs or a multi-core CPU. The load average numbers work a bit differently on such a system. For example, if you have a load average of 2 on a single-CPU system, this means your system was overloaded by 100 percent — the entire period of time, one process was using the CPU while one other process was waiting. On a system with two CPUs, this would be complete usage — two different processes were using two different CPUs the entire time. On a system with four CPUs, this would be half usage — two processes were using two CPUs, while two CPUs were sitting idle.

To understand the load average number, you need to know how many CPUs your system has. A load average of 6.03 would indicate a system with a single CPU was massively overloaded, but it would be fine on a computer with 8 CPUs.

more info : Link

C - error: storage size of ‘a’ isn’t known

Say it like this: struct xyx a;

Why does the 'int' object is not callable error occur when using the sum() function?

This means that somewhere else in your code, you have something like:

sum = 0

Which shadows the builtin sum (which is callable) with an int (which isn't).

In Firebase, is there a way to get the number of children of a node without loading all the node data?

Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).

The 'trick' here is to use the node priority to as the vote count...

The data is:

vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote

,"vote": {
  ".read" : true
  ,".write" : true
  ,"$issue" : {
    "user" : {
      "$user" : {
        ".validate" : "!data.exists() && 
             newData.val()==data.parent().parent().child('count').getPriority()+1 &&
             newData.val()==newData.GetPriority()" 

user can only vote once && count must be one higher than current count && data value must be same as priority.

      }
    }
    ,"count" : {
      ".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
             newData.getPriority()==data.getPriority()+1 "
    }

count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.

  }
}

Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.

<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
  window.fb = new Firebase('https:...vote/iss1/');
  window.fb.child('count').once('value', function (dss) {
    votes = dss.getPriority();
    for (var i=1;i<10;i++) vote(dss,i+votes);
  } );

function vote(dss,count)
{
  var user='user/zz' + count; // replace with auth.id or whatever
  window.fb.child(user).setWithPriority(count,count);
  window.fb.child('count').setWithPriority(user,count);
}
</script>

The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)

The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).

How To Get The Current Year Using Vba

Year(Date)

Year(): Returns the year portion of the date argument.
Date: Current date only.

Explanation of both of these functions from here.

Bootstrap 3 dropdown select

I'd like to extend the paulalexandru's answer and put here complete solution that works generally with bootstrap dropdowns and updating main button's content and also the value from selected option.

The bootstrap dropdown is defined this way:

<div class="btn-group" role="group">
  <button type="button" data-toggle="dropdown" value="1" class="btn btn-default btn-sm dropdown-toggle">
    Option 1 <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li><a href="#" data-value="1">Option 1</a></li>
    <li><a href="#" data-value="2">Option 2</a></li>
    <li><a href="#" data-value="3">Option 3</a></li>
  </ul>
</div> 

Additional to standard bootstrap dropdown code, there is data-value attribute for storing the values in every dropdown option (in <a> element).

Now the JS code. I crated function that handle the dropdowns:

function dropdownToggle() {
    // select the main dropdown button element
    var dropdown = $(this).parent().parent().prev();

    // change the CONTENT of the button based on the content of selected option
    dropdown.html($(this).html() + '&nbsp;</i><span class="caret"></span>');

    // change the VALUE of the button based on the data-value property of selected option
    dropdown.val($(this).prop('data-value'));
}

And of course we need to add event listener:

$(document).ready(function(){
    $('.dropdown-menu a').on('click', dropdownToggle);
}

How do I fix MSB3073 error in my post-build event?

I solved it by doing the following:

In Visual studio I went in Project -> Project Dependencies

I selected the XXX.Test solution and told it that it also depends on the XXX solution to make the post-build events in the XXX.Test solution not generate this error (exit with code 4).

How to generate JAXB classes from XSD?

In Eclipse, right click on the xsd file you want to get --> Generate --> Java... --> Generator: "Schema to JAXB Java Classes".

I just faced the same problem, I had a bunch of xsd files, only one of them being the XML Root Element and it worked well what I explained above in Eclipse

Group By Multiple Columns

.GroupBy(x => x.Column1 + " " + x.Column2)

ReferenceError: $ is not defined

jQuery is a JavaScript library, The purpose of jQuery is to make code much easier to use JavaScript.

The jQuery syntax is tailor-made for selecting, A $ sign to define/access jQuery.

Its in declaration sequence must be on top then any other script included which uses jQuery

Correct position to jQuery declaration :

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    console.log('hi from jQuery!');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
_x000D_
_x000D_
_x000D_

Above example will work perfectly because jQuery library is initialized before any other library which is using jQuery functions, including $

But if you apply it somewhere else, jQuery functions will not initialize in browser DOM and it will not able to identify any code related to jQuery, and its code starts with $ sign, so you will receive $ is not a function error.

Incorrect position for jQuery declaration:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    console.log('hi from jQuery!');_x000D_
});
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Above code will not work because, jQuery is not declared on the top of any library which uses jQuery ready function.

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

C# Version... note that I am getting color strings in this format #FF12AE34, and need to cut out the #FF.

    private string GetSmartShadeColorByBase(string s, float percent)
    {
        if (string.IsNullOrEmpty(s))
            return "";
        var r = s.Substring(3, 2);
        int rInt = int.Parse(r, NumberStyles.HexNumber);
        var g = s.Substring(5, 2);
        int gInt = int.Parse(g, NumberStyles.HexNumber);
        var b = s.Substring(7, 2);
        int bInt = int.Parse(b, NumberStyles.HexNumber);

        var t = percent < 0 ? 0 : 255;
        var p = percent < 0 ? percent*-1 : percent;

        int newR = Convert.ToInt32(Math.Round((t - rInt) * p) + rInt);
        var newG = Convert.ToInt32(Math.Round((t - gInt) * p) + gInt);
        var newB = Convert.ToInt32(Math.Round((t - bInt) * p) + bInt);

        return String.Format("#{0:X2}{1:X2}{2:X2}", newR, newG, newB);
    }

Indirectly referenced from required .class file

Have you Googled for "weblogic ExpressionMap"? Do you know what it is and what it does?

Looks like you definitely need to be compiling alongside Weblogic and with Weblogic's jars included in your Eclipse classpath, if you're not already.

If you're not already working with Weblogic, then you need to find out what in the world is referencing it. You might need to do some heavy-duty grepping on your jars, classfiles, and/or source files looking for which ones include the string "weblogic".

If I had to include something that was relying on this Weblogic class, but couldn't use Weblogic, I'd be tempted to try to reverse-engineer a compatible class. Create your own weblogic.utils.expressions.ExpressionMap class; see if everything compiles; use any resultant errors or warnings at compile-time or runtime to give you clues as to what methods and other members need to be in this class. Make stub methods that do nothing or return null if possible.

How to determine total number of open/active connections in ms sql server 2005

MS SQL knowledge based - How to know open SQL database connection(s) and occupied on which host.

Using below query you will find list database, Host name and total number of open connection count, based on that you will have idea, which host has occupied SQL connection.

SELECT DB_NAME(dbid) as DBName, hostname ,COUNT(dbid) as NumberOfConnections
FROM sys.sysprocesses with (nolock) 
WHERE dbid > 0 
and len(hostname) > 0 
--and DB_NAME(dbid)='master' /* Open this line to filter Database by Name */
Group by DB_NAME(dbid),hostname
order by DBName

Get Hard disk serial Number

I have used the following method in a project and it's working successfully.

private string identifier(string wmiClass, string wmiProperty)
//Return a hardware identifier
{
    string result = "";
    System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
    System.Management.ManagementObjectCollection moc = mc.GetInstances();
    foreach (System.Management.ManagementObject mo in moc)
    {
        //Only get the first one
        if (result == "")
        {
            try
            {
                result = mo[wmiProperty].ToString();
                break;
            }
            catch
            {
            }
        }
    }
    return result;
}

you can call the above method as mentioned below,

string modelNo = identifier("Win32_DiskDrive", "Model");
string manufatureID = identifier("Win32_DiskDrive", "Manufacturer");
string signature = identifier("Win32_DiskDrive", "Signature");
string totalHeads = identifier("Win32_DiskDrive", "TotalHeads");

If you need a unique identifier, use a combination of these IDs.

How to update a value in a json file and save it through node.js

For those looking to add an item to a json collection

function save(item, path = './collection.json'){
    if (!fs.existsSync(path)) {
        fs.writeFile(path, JSON.stringify([item]));
    } else {
        var data = fs.readFileSync(path, 'utf8');  
        var list = (data.length) ? JSON.parse(data): [];
        if (list instanceof Array) list.push(item)
        else list = [item]  
        fs.writeFileSync(path, JSON.stringify(list));
    }
}

Android ImageView Fixing Image Size

I had the same issue and this helped me.

<ImageView
    android:id="@+id/image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitXY"
    />

Turning off eslint rule for a specific file

You can just put this for example at the top of the file:

/* eslint-disable no-console */

Comparing HTTP and FTP for transferring files

I just benchmarked a file transfer over both FTP and HTTP :

  • over two very good server connections
  • using the same 1GB .zip file
  • under the same network conditions (tested one after the other)

The result:

  • using FTP: 6 minutes
  • using HTTP: 4 minutes
  • using a concurrent http downloader software (fdm): 1 minute

So, basically under a "real life" situation:

1) HTTP is faster than FTP when downloading one big file.

2) HTTP can use parallel chunk download which makes it 6x times faster than FTP depending on the network conditions.

How do I dump the data of some SQLite3 tables?

Review of other possible solutions

Include only INSERTs

sqlite3 database.db3 .dump | grep '^INSERT INTO "tablename"'

Easy to implement but it will fail if any of your columns include new lines

SQLite insert mode

for t in $(sqlite3 $DB .tables); do
    echo -e ".mode insert $t\nselect * from $t;"
done | sqlite3 $DB > backup.sql

This is a nice and customizable solution, but it doesn't work if your columns have blob objects like 'Geometry' type in spatialite

Diff the dump with the schema

sqlite3 some.db .schema > schema.sql
sqlite3 some.db .dump > dump.sql
grep -v -f schema.sql dump > data.sql

Not sure why, but is not working for me

Another (new) possible solution

Probably there is not a best answer to this question, but one that is working for me is grep the inserts taking into account that be new lines in the column values with an expression like this

grep -Pzo "(?s)^INSERT.*\);[ \t]*$"

To select the tables do be dumped .dump admits a LIKE argument to match the table names, but if this is not enough probably a simple script is better option

TABLES='table1 table2 table3'

echo '' > /tmp/backup.sql
for t in $TABLES ; do
    echo -e ".dump ${t}" | sqlite3 database.db3 | grep -Pzo "(?s)^INSERT.*?\);$" >> /tmp/backup.sql
done

or, something more elaborated to respect foreign keys and encapsulate all the dump in only one transaction

TABLES='table1 table2 table3'

echo 'BEGIN TRANSACTION;' > /tmp/backup.sql
echo '' >> /tmp/backup.sql
for t in $TABLES ; do
    echo -e ".dump ${t}" | sqlite3 $1 | grep -Pzo "(?s)^INSERT.*?\);$" | grep -v -e 'PRAGMA foreign_keys=OFF;' -e 'BEGIN TRANSACTION;' -e 'COMMIT;' >> /tmp/backup.sql
done

echo '' >> /tmp/backup.sql
echo 'COMMIT;' >> /tmp/backup.sql

Take into account that the grep expression will fail if ); is a string present in any of the columns

To restore it (in a database with the tables already created)

sqlite3 -bail database.db3 < /tmp/backup.sql

ASP.NET Core - Swashbuckle not creating swagger.json file

After watching the answers and checking the recommendations, I end up having no clue what was going wrong.

I literally tried everything. So if you end up in the same situation, understand that the issue might be something else, completely irrelevant from swagger.

In my case was a OData exception.

Here's the procedure:

1) Navigate to the localhost:xxxx/swagger
2) Open Developer tools
3) Click on the error shown in the console and you will see the inner exception that is causing the issue.

How to use boolean 'and' in Python

The correct operator to be used are the keywords 'or' and 'and', which in your example, the correct way to express this would be:

if i == 5 and ii == 10:
    print "i is 5 and ii is 10"

You can refer the details in the "Boolean Operations" section in the language reference.

How to view table contents in Mysql Workbench GUI?

Open a connection to your server first (SQL IDE) from the home screen. Then use the context menu in the schema tree to run a query that simply selects rows from the selected table. The LIMIT attached to that is to avoid reading too many rows by accident. This limit can be switched off (or adjusted) in the preferences dialog.

enter image description here

This quick way to select rows is however not very flexible. Normally you would run a query (File / New Query Tab) in the editor with additional conditions, like a sort order:

enter image description here

How to get the list of all installed color schemes in Vim?

Just for convenient reference as I see that there are a lot of people searching for this topic and are too laz... sorry, busy, to check themselves (including me). Here a list of the default set of colour schemes for Vim 7.4:

blue.vim
darkblue.vim,
delek.vim
desert.vim
elflord.vim
evening.vim
industry.vim                                                                                                                                                 
koehler.vim                                                                                                                                                  
morning.vim                                                                                                                                                  
murphy.vim                                                                                                                                                   
pablo.vim                                                                                                                                                    
peachpuff.vim                                                                                                                                                
ron.vim                                                                                                                                                      
shine.vim                                                                                                                                                    
slate.vim                                                                                                                                                    
torte.vim                                                                                                                                                    
zellner.vim 

Splitting a Java String by the pipe symbol using split("|")

You could also use the apache library and do this:

StringUtils.split(test, "|");

Alternative to mysql_real_escape_string without connecting to DB

Well, according to the mysql_real_escape_string function reference page: "mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which escapes the following characters: \x00, \n, \r, \, ', " and \x1a."

With that in mind, then the function given in the second link you posted should do exactly what you need:

function mres($value)
{
    $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
    $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");

    return str_replace($search, $replace, $value);
}

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

Importing a function from a class in another file?

It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.

For example:

def run():
    print "this does nothing"

def chooser():
    return "run"

def main():
    '''works just like:
    run()'''
    eval(chooser())()

The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.

How to parse JSON to receive a Date object in JavaScript?

I've not used .Net for things like this. If you were able to get it to print something like the following out it should work.

Note, unless you're parsing that JSON string by some other means or only expect users to have modern browers with a built in JSON parser you need to use a JS framework or JSON2 to parse the JSON string outputted by the server into a real JSON object.

// JSON received from server is in string format
var jsonString = '{"date":1251877601000}';

//use JSON2 or some JS library to parse the string
var jsonObject =  JSON.parse( jsonString );

//now you have your date!
alert( new Date(jsonObject.date) );

Wiki Link

Modern browsers, such as Firefox 3.5 and Internet Explorer 8, include special features for parsing JSON. As native browser support is more efficient and secure than eval(), it is expected that native JSON support will be included in the next ECMAScript standard.[6]


Link to JSON2 file

Live Example

SQL Server: IF EXISTS ; ELSE

I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_a
AS
(
    SELECT [id] [id]
    , MAX([value]) [value]
    FROM table_a
    GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN  cte_table_a
ON table_b.id = cte_table_a.id

Maximum number of rows in an MS Access database engine table?

It's been some years since I last worked with Access but larger database files always used to have more problems and be more prone to corruption than smaller files.

Unless the database file is only being accessed by one person or stored on a robust network you may find this is a problem before the 2GB database size limit is reached.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

Check out startOfDay([offset]). That gets what you are looking for without the pesky time constraints and its built in as of 4.3.x. It also has variants like endOfDay, startOfWeek, startOfMonth, etc.

How to make a window always stay on top in .Net?

The following code makes the window always stay on top as well as make it frameless.

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace StayOnTop
{
    public partial class Form1 : Form
    {
        private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        private const UInt32 SWP_NOSIZE = 0x0001;
        private const UInt32 SWP_NOMOVE = 0x0002;
        private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        public Form1()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            TopMost = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetWindowPos(this.Handle, HWND_TOPMOST, 100, 100, 300, 300, TOPMOST_FLAGS);
        }

        protected override void WndProc(ref Message m)
        {
            const int RESIZE_HANDLE_SIZE = 10;

            switch (m.Msg)
            {
                case 0x0084/*NCHITTEST*/ :
                    base.WndProc(ref m);

                    if ((int)m.Result == 0x01/*HTCLIENT*/)
                    {
                        Point screenPoint = new Point(m.LParam.ToInt32());
                        Point clientPoint = this.PointToClient(screenPoint);
                        if (clientPoint.Y <= RESIZE_HANDLE_SIZE)
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)13/*HTTOPLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)12/*HTTOP*/ ;
                            else
                                m.Result = (IntPtr)14/*HTTOPRIGHT*/ ;
                        }
                        else if (clientPoint.Y <= (Size.Height - RESIZE_HANDLE_SIZE))
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)10/*HTLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)2/*HTCAPTION*/ ;
                            else
                                m.Result = (IntPtr)11/*HTRIGHT*/ ;
                        }
                        else
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)16/*HTBOTTOMLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)15/*HTBOTTOM*/ ;
                            else
                                m.Result = (IntPtr)17/*HTBOTTOMRIGHT*/ ;
                        }
                    }
                    return;
            }
            base.WndProc(ref m);
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style |= 0x20000; // <--- use 0x20000
                return cp;
            }
        }
    }
}

How do I drop a function if it already exists?

Here's my take on this:

if(object_id(N'[dbo].[fn_Nth_Pos]', N'FN')) is not null
    drop function [dbo].[fn_Nth_Pos];
GO
CREATE FUNCTION [dbo].[fn_Nth_Pos]
(
    @find char, --char to find
    @search varchar(max), --string to process   
    @nth int --occurrence   
)
RETURNS int
AS
BEGIN
    declare @pos int --position of nth occurrence
    --init
    set @pos = 0

    while(@nth > 0)
    begin       
        set @pos = charindex(@find,@search,@pos+1)
        set @nth = @nth - 1
    end 

    return @pos
END
GO

--EXAMPLE
declare @files table(name varchar(max));

insert into @files(name) values('abc_1_2_3_4.gif');
insert into @files(name) values('zzz_12_3_3_45.gif');

select
    f.name,
    dbo.fn_Nth_Pos('_', f.name, 1) as [1st],
    dbo.fn_Nth_Pos('_', f.name, 2) as [2nd],
    dbo.fn_Nth_Pos('_', f.name, 3) as [3rd],
    dbo.fn_Nth_Pos('_', f.name, 4) as [4th]
from 
    @files f;

Recommended method for escaping HTML in Java

Nice short method:

public static String escapeHTML(String s) {
    StringBuilder out = new StringBuilder(Math.max(16, s.length()));
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c > 127 || c == '"' || c == '\'' || c == '<' || c == '>' || c == '&') {
            out.append("&#");
            out.append((int) c);
            out.append(';');
        } else {
            out.append(c);
        }
    }
    return out.toString();
}

Based on https://stackoverflow.com/a/8838023/1199155 (the amp is missing there). The four characters checked in the if clause are the only ones below 128, according to http://www.w3.org/TR/html4/sgml/entities.html

How do I make an asynchronous GET request in PHP?

Try:

//Your Code here
$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
}
else if ($pid)
{
echo("Bye")  
}
else
{
     //Do Post Processing
}

This will NOT work as an apache module, you need to be using CGI.

Display open transactions in MySQL

By using this query you can see all open transactions.

List All:

SHOW FULL PROCESSLIST  

if you want to kill a hang transaction copy transaction id and kill transaction by using this command:

KILL <id>    // e.g KILL 16543

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

How to solve npm error "npm ERR! code ELIFECYCLE"

This solution is for Windows users.

You can open the node.js installer and give the installer some time to compute space requirements and then click next and click remove. This will remove node.js from your computer and again reopen the installer and install it in this path - C:\Windows\System32

or

Cleaning Cache and Node_module will work. Follow this steps:

  • npm cache clean --force
  • delete node_modules folder
  • delete package-lock.json file
  • npm install

How to add an item to a drop down list in ASP.NET?

Try following code;

DropDownList1.Items.Add(new ListItem(txt_box1.Text));

Remove the legend on a matplotlib figure

you have to add the following lines of code:

ax = gca()
ax.legend_ = None
draw()

gca() returns the current axes handle, and has that property legend_

What is the difference between Amazon SNS and Amazon SQS?

SNS is a distributed publish-subscribe system. Messages are pushed to subscribers as and when they are sent by publishers to SNS.

SQS is distributed queuing system. Messages are not pushed to receivers. Receivers have to poll or pull messages from SQS. Messages can't be received by multiple receivers at the same time. Any one receiver can receive a message, process and delete it. Other receivers do not receive the same message later. Polling inherently introduces some latency in message delivery in SQS unlike SNS where messages are immediately pushed to subscribers. SNS supports several end points such as email, SMS, HTTP end point and SQS. If you want unknown number and type of subscribers to receive messages, you need SNS.

You don't have to couple SNS and SQS always. You can have SNS send messages to email, SMS or HTTP end point apart from SQS. There are advantages to coupling SNS with SQS. You may not want an external service to make connections to your hosts (a firewall may block all incoming connections to your host from outside).

Your end point may just die because of heavy volume of messages. Email and SMS maybe not your choice of processing messages quickly. By coupling SNS with SQS, you can receive messages at your pace. It allows clients to be offline, tolerant to network and host failures. You also achieve guaranteed delivery. If you configure SNS to send messages to an HTTP end point or email or SMS, several failures to send message may result in messages being dropped.

SQS is mainly used to decouple applications or integrate applications. Messages can be stored in SQS for a short duration of time (maximum 14 days). SNS distributes several copies of messages to several subscribers. For example, let’s say you want to replicate data generated by an application to several storage systems. You could use SNS and send this data to multiple subscribers, each replicating the messages it receives to different storage systems (S3, hard disk on your host, database, etc.).

LocalDate to java.util.Date and vice versa simplest conversion?

I solved this question with solution below

  import org.joda.time.LocalDate;
  Date myDate = new Date();
  LocalDate localDate = LocalDate.fromDateFields(myDate);
  System.out.println("My date using Date" Nov 18 11:23:33 BRST 2016);
  System.out.println("My date using joda.time LocalTime" 2016-11-18);

In this case localDate print your date in this format "yyyy-MM-dd"

How to return the current timestamp with Moment.js?

moment().unix() you will get a unix timestamp

moment().valueOf() you will get a full timestamp

How can I solve ORA-00911: invalid character error?

The option(s) to resolve this Oracle error are:

Option #1 This error occurs when you try to use a special character in a SQL statement. If a special character other than $, _, and # is used in the name of a column or table, the name must be enclosed in double quotations.

Option #2 This error may occur if you've pasted your SQL into your editor from another program. Sometimes there are non-printable characters that may be present. In this case, you should try retyping your SQL statement and then re-execute it.

Option #3 This error occurs when a special character is used in a SQL WHERE clause and the value is not enclosed in single quotations.

For example, if you had the following SQL statement:

SELECT * FROM suppliers WHERE supplier_name = ?;

Jquery: How to check if the element has certain css class/style

if ($("element class or id name").css("property") == "value") {
    your code....
}

Difference between "enqueue" and "dequeue"

Enqueue means to add an element, dequeue to remove an element.

var stackInput= []; // First stack
var stackOutput= []; // Second stack

// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
  return stackInput.push(item);
}

function dequeue(stackInput, stackOutput) {
  // Reverse the stack such that the first element of the output stack is the
  // last element of the input stack. After that, pop the top of the output to
  // get the first element that was ever pushed into the input stack
  if (stackOutput.length <= 0) {
    while(stackInput.length > 0) {
      var elementToOutput = stackInput.pop();
      stackOutput.push(elementToOutput);
    }
  }

  return stackOutput.pop();
}

Set value of hidden input with jquery

You should use val instead of value.

<script type="text/javascript" language="javascript">
$(document).ready(function () { 
    $('input[name="testing"]').val('Work!');
});
</script>

Timeout jQuery effects

I just figured it out below:

$(".notice")
   .fadeIn( function() 
   {
      setTimeout( function()
      {
         $(".notice").fadeOut("fast");
      }, 2000);
   });

I will keep the post for other users!

Reverting single file in SVN to a particular revision

The best way is to:

svn merge -c -RevisionToUndo ^/trunk

This will undo all files of the revision than simply revert those file you don't like to undo. Don't forget the dash (-) as prefix for the revision.

svn revert File1 File2

Now commit the changes back.

Open file in a relative location in Python

Try this:

from pathlib import Path

data_folder = Path("/relative/path")
file_to_open = data_folder / "file.pdf"

f = open(file_to_open)

print(f.read())

Python 3.4 introduced a new standard library for dealing with files and paths called pathlib. It works for me!

How to open an external file from HTML

If your web server is IIS, you need to make sure that the new Office 2007 (I see the xlsx suffix) mime types are added to the list of mime types in IIS, otherwise it will refuse to serve the unknown file type.

Here's one link to tell you how:

Configuring IIS 6 for Office 2007

How to make div appear in front of another?

You can set the z-index in css

<div style="z-index: -1"></div>

How to convert an Array to a Set in Java

In Java 10:

String[] strs = {"A", "B"};
Set<String> set = Set.copyOf(Arrays.asList(strs));

Set.copyOf returns an unmodifiable Set containing the elements of the given Collection.

 The given Collection must not be null, and it must not contain any null elements.

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

To extend on rk rk's solution: In case you want the format to include the time, you can add the toTimeString() to your string, and then strip the GMT part, as follows:

var d = new Date('2013-03-10T02:00:00Z');
var fd = d.toLocaleDateString() + ' ' + d.toTimeString().substring(0, d.toTimeString().indexOf("GMT"));

Viewing full output of PS command

Sorry to be late to the party but just found this solution to the problem.

The lines are truncated because ps insists on using the value of $COLUMNS, even if the output is not the screen at that moment. Which is a bug, IMHO. But easy to work around, just make ps think you have a superwide screen, i.e. set COLUMNS high for the duration of the ps command. An example:

$ ps -edalf                 # truncates lines to screen width
$ COLUMNS=1000 ps -edalf    # wraps lines regardless of screen width

I hope this is still useful to someone. All the other ideas seemed much too complicated :)

Pass react component as props

As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:

https://reactjs.org/docs/composition-vs-inheritance.html

Make sure you are actually passing a component and not an object (this tripped me up initially).

The code is simply this:

const Parent = () => { 
  return (
    <Child  componentToPassDown={<SomeComp />}  />
  )
}

const Child = ({ componentToPassDown }) => { 
  return (
    <>
     {componentToPassDown}  
    </>
  )
}

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

I ran into the same situation where commands such as git diff origin or git diff origin master produced the error reported in the question, namely Fatal: ambiguous argument...

To resolve the situation, I ran the command

git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master

to set refs/remotes/origin/HEAD to point to the origin/master branch.

Before running this command, the output of git branch -a was:

* master
  remotes/origin/master

After running the command, the error no longer happened and the output of git branch -a was:

* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

(Other answers have already identified that the source of the error is HEAD not being set for origin. But I thought it helpful to provide a command which may be used to fix the error in question, although it may be obvious to some users.)


Additional information:

For anybody inclined to experiment and go back and forth between setting and unsetting refs/remotes/origin/HEAD, here are some examples.

To unset:
git remote set-head origin --delete

To set:
(additional ways, besides the way shown at the start of this answer)
git remote set-head origin master to set origin/head explicitly
OR
git remote set-head origin --auto to query the remote and automatically set origin/HEAD to the remote's current branch.

References:

  • This SO Answer
  • This SO Comment and its associated answer
  • git remote --help see set-head description
  • git symbolic-ref --help

Preferred method to store PHP arrays (json_encode vs serialize)

I've tested this very thoroughly on a fairly complex, mildly nested multi-hash with all kinds of data in it (string, NULL, integers), and serialize/unserialize ended up much faster than json_encode/json_decode.

The only advantage json have in my tests was it's smaller 'packed' size.

These are done under PHP 5.3.3, let me know if you want more details.

Here are tests results then the code to produce them. I can't provide the test data since it'd reveal information that I can't let go out in the wild.

JSON encoded in 2.23700618744 seconds
PHP serialized in 1.3434419632 seconds
JSON decoded in 4.0405561924 seconds
PHP unserialized in 1.39393305779 seconds

serialized size : 14549
json_encode size : 11520
serialize() was roughly 66.51% faster than json_encode()
unserialize() was roughly 189.87% faster than json_decode()
json_encode() string was roughly 26.29% smaller than serialize()

//  Time json encoding
$start = microtime( true );
for($i = 0; $i < 10000; $i++) {
    json_encode( $test );
}
$jsonTime = microtime( true ) - $start;
echo "JSON encoded in $jsonTime seconds<br>";

//  Time serialization
$start = microtime( true );
for($i = 0; $i < 10000; $i++) {
    serialize( $test );
}
$serializeTime = microtime( true ) - $start;
echo "PHP serialized in $serializeTime seconds<br>";

//  Time json decoding
$test2 = json_encode( $test );
$start = microtime( true );
for($i = 0; $i < 10000; $i++) {
    json_decode( $test2 );
}
$jsonDecodeTime = microtime( true ) - $start;
echo "JSON decoded in $jsonDecodeTime seconds<br>";

//  Time deserialization
$test2 = serialize( $test );
$start = microtime( true );
for($i = 0; $i < 10000; $i++) {
    unserialize( $test2 );
}
$unserializeTime = microtime( true ) - $start;
echo "PHP unserialized in $unserializeTime seconds<br>";

$jsonSize = strlen(json_encode( $test ));
$phpSize = strlen(serialize( $test ));

echo "<p>serialized size : " . strlen(serialize( $test )) . "<br>";
echo "json_encode size : " . strlen(json_encode( $test )) . "<br></p>";

//  Compare them
if ( $jsonTime < $serializeTime )
{
    echo "json_encode() was roughly " . number_format( ($serializeTime / $jsonTime - 1 ) * 100, 2 ) . "% faster than serialize()";
}
else if ( $serializeTime < $jsonTime )
{
    echo "serialize() was roughly " . number_format( ($jsonTime / $serializeTime - 1 ) * 100, 2 ) . "% faster than json_encode()";
} else {
    echo 'Unpossible!';
}
    echo '<BR>';

//  Compare them
if ( $jsonDecodeTime < $unserializeTime )
{
    echo "json_decode() was roughly " . number_format( ($unserializeTime / $jsonDecodeTime - 1 ) * 100, 2 ) . "% faster than unserialize()";
}
else if ( $unserializeTime < $jsonDecodeTime )
{
    echo "unserialize() was roughly " . number_format( ($jsonDecodeTime / $unserializeTime - 1 ) * 100, 2 ) . "% faster than json_decode()";
} else {
    echo 'Unpossible!';
}
    echo '<BR>';
//  Compare them
if ( $jsonSize < $phpSize )
{
    echo "json_encode() string was roughly " . number_format( ($phpSize / $jsonSize - 1 ) * 100, 2 ) . "% smaller than serialize()";
}
else if ( $phpSize < $jsonSize )
{
    echo "serialize() string was roughly " . number_format( ($jsonSize / $phpSize - 1 ) * 100, 2 ) . "% smaller than json_encode()";
} else {
    echo 'Unpossible!';
}

what do these symbolic strings mean: %02d %01d?

The answer from Alexander refers to complete docs...

Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.

space between divs - display table-cell

You can use border-spacing property:

HTML:

<div class="table">
    <div class="row">
        <div class="cell">Cell 1</div>
        <div class="cell">Cell 2</div>
    </div>
</div>

CSS:

.table {
  display: table;
  border-collapse: separate;
  border-spacing: 10px;
}

.row { display:table-row; }

.cell {
  display:table-cell;
  padding:5px;
  background-color: gold;
}

JSBin Demo

Any other option?

Well, not really.

Why?

  • margin property is not applicable to display: table-cell elements.
  • padding property doesn't create space between edges of the cells.
  • float property destroys the expected behavior of table-cell elements which are able to be as tall as their parent element.

Eclipse : Failed to connect to remote VM. Connection refused.

Sometimes the port which you are trying to access, gets occupied and won't be released. Try some tools to find whether the port is in use or not. I also faced the same issue. I tried giving different port numbers but unfortunately it didn't work. I tried restarting the system (not the application server), and it worked :)

How do I check particular attributes exist or not in XML?

You can use the GetNamedItem method to check and see if the attribute is available. If null is returned, then it isn't available. Here is your code with that check in place:

foreach (XmlNode xNode in nodeListName)
{
    if(xNode.ParentNode.Attributes.GetNamedItem("split") != null )
    {
        if(xNode.ParentNode.Attributes["split"].Value != "")
        {
            parentSplit = xNode.ParentNode.Attributes["split"].Value;
        }
    }  
}

How can I check if mysql is installed on ubuntu?

Multiple ways of searching for the program.

Type mysql in your terminal, see the result.

Search the /usr/bin, /bin directories for the binary.

Type apt-cache show mysql to see if it is installed

locate mysql

How to execute VBA Access module?

You're not running a module -- you're running subroutines/functions that happen to be stored in modules.

If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).

Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:

  SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
  FROM MyTable;

That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.

Subroutines (i.e., code that returns no value) are not callable from within SQL statements.

How to add `style=display:"block"` to an element using jQuery?

$("#YourElementID").css("display","block");

Edit: or as dave thieben points out in his comment below, you can do this as well:

$("#YourElementID").css({ display: "block" });

Java: Finding the highest value in an array

You can use a function that accepts a array and finds the max value in it. i made it generic so it could also accept other data types

public static <T extends Comparable<T>> T findMax(T[] array){       
    T max = array[0];
    for(T data: array){
        if(data.compareTo(max)>0)
            max =data;                
    }
    return max;
}

How do I get column names to print in this C# program?

Print datatable rows with column

Here is solution 

DataTable datatableinfo= new DataTable();

// Fill data table 

//datatableinfo=fill by function or get data from database

//Print data table with rows and column


for (int j = 0; j < datatableinfo.Rows.Count; j++)
{
    for (int i = 0; i < datatableinfo.Columns.Count; i++)    
        {    
            Console.Write(datatableinfo.Columns[i].ColumnName + " ");    
            Console.WriteLine(datatableinfo.Rows[j].ItemArray[i]+" "); 
        }
}


Ouput :
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

Increment a Integer's int value?

All the primitive wrapper objects are immutable.

I'm maybe late to the question but I want to add and clarify that when you do playerID++, what really happens is something like this:

playerID = Integer.valueOf( playerID.intValue() + 1);

Integer.valueOf(int) will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

How can I create a correlation matrix in R?

Have a look at qtlcharts. It allows you to create interactive correlation matrices:

library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)

enter image description here

It's more impressive when you correlate more variables, like in the package's vignette: enter image description here

"Field has incomplete type" error

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

At some point, the compiler needs to know the details of A.

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}

How to check if an array is empty?

Your test:

if (numberSet.length < 2) {
    return 0;
}

should be done before you allocate an array of that length in the below statement:

int[] differenceArray = new int[numberSet.length-1];

else you are already creating an array of size -1, when the numberSet.length = 0. That is quite odd. So, move your if statement as the first statement in your method.

Map HTML to JSON

Thank you @Gorge Reith. Working off the solution provided by @George Reith, here is a function that furthers (1) separates out the individual 'hrefs' links (because they might be useful), (2) uses attributes as keys (since attributes are more descriptive), and (3) it's usable within Node.js without needing Chrome by using the 'jsdom' package:

const jsdom = require('jsdom') // npm install jsdom provides in-built Window.js without needing Chrome


// Function to map HTML DOM attributes to inner text and hrefs
function mapDOM(html_string, json) {
    treeObject = {}

    // IMPT: use jsdom because of in-built Window.js
    // DOMParser() does not provide client-side window for element access if coding in Nodejs
    dom = new jsdom.JSDOM(html_string)
    document = dom.window.document
    element = document.firstChild

    // Recursively loop through DOM elements and assign attributes to inner text object
    // Why attributes instead of elements? 1. attributes more descriptive, 2. usually important and lesser
    function treeHTML(element, object) {
        var nodeList = element.childNodes;
        if (nodeList != null) {
           if (nodeList.length) {
               object[element.nodeName] = []  // IMPT: empty [] array for non-text recursivable elements (see below)
               for (var i = 0; i < nodeList.length; i++) {
                   // if final text
                   if (nodeList[i].nodeType == 3) {
                       if (element.attributes != null) {
                           for (var j = 0; j < element.attributes.length; j++) {
                                if (element.attributes[j].nodeValue !== '' && 
                                    nodeList[i].nodeValue !== '') {
                                    if (element.attributes[j].name === 'href') { // separate href
                                        object[element.attributes[j].name] = element.attributes[j].nodeValue;
                                    } else {
                                        object[element.attributes[j].nodeValue] = nodeList[i].nodeValue;
                                    }

                                }
                           }
                       }
                   // else if non-text then recurse on recursivable elements
                   } else {
                       object[element.nodeName].push({}); // if non-text push {} into empty [] array
                       treeHTML(nodeList[i], object[element.nodeName][object[element.nodeName].length -1]);
                   }
               }
           }
        }
    }
    treeHTML(element, treeObject);

    return (json) ? JSON.stringify(treeObject) : treeObject;
}

Try-catch block in Jenkins pipeline script

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.

Commenting multiple lines in DOS batch file

break||(
 code that cannot contain non paired closing bracket
)

While the goto solution is a good option it will not work within brackets (including FOR and IF commands).But this will. Though you should be careful about closing brackets and invalid syntax for FOR and IF commands because they will be parsed.

Update

The update in the dbenham's answer gave me some ideas. First - there are two different cases where we can need multi line comments - in a bracket's context where GOTO cannot be used and outside it. Inside brackets context we can use another brackets if there's a condition which prevents the code to be executed.Though the code thede will still be parsed and some syntax errors will be detected (FOR,IF ,improperly closed brackets, wrong parameter expansion ..).So if it is possible it's better to use GOTO.

Though it is not possible to create a macro/variable used as a label - but is possible to use macros for bracket's comments.Still two tricks can be used make the GOTO comments more symetrical and more pleasing (at least for me). For this I'll use two tricks - 1) you can put a single symbol in front of a label and goto will still able to find it (I have no idea why is this.My guues it is searching for a drive). 2) you can put a single : at the end of a variable name and a replacement/subtring feature will be not triggered (even under enabled extensions). Wich combined with the macros for brackets comments can make the both cases to look almost the same.

So here are the examples (in the order I like them most):

With rectangular brackets:

@echo off

::GOTO comment macro
set "[:=goto :]%%"
::brackets comment macros
set "[=rem/||(" & set "]=)"

::testing
echo not commented 1

%[:%
  multi 
  line
  comment outside of brackets
%:]%

echo not commented 2

%[:%
  second multi 
  line
  comment outside of brackets
%:]%

::GOTO macro cannot be used inside for
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %[%
        multi line
        comment
    %]%
    echo second not commented line of the %%a execution
)

With curly brackets:

@echo off

::GOTO comment macro
set "{:=goto :}%%"
::brackets comment macros
set "{=rem/||(" & set "}=)"

::testing
echo not commented 1

%{:%
  multi 
  line
  comment outside of brackets
%:}%

echo not commented 2

%{:%
  second multi 
  line
  comment outside of brackets
%:}%

::GOTO macro cannot be used inside for loop
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %{%
        multi line
        comment
    %}%
    echo second not commented line of the %%a execution
)

With parentheses:

@echo off

::GOTO comment macro
set "(:=goto :)%%"
::brackets comment macros
set "(=rem/||(" & set ")=)"

::testing
echo not commented 1

%(:%
  multi 
  line
  comment outside of brackets
%:)%

echo not commented 2

%(:%
  second multi 
  line
  comment outside of brackets
%:)%

::GOTO macro cannot be used inside for loop
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %(%
        multi line
        comment
    %)%
    echo second not commented line of the %%a execution
)

Mixture between powershell and C styles (< cannot be used because the redirection is with higher prio.* cannot be used because of the %*) :

@echo off

::GOTO comment macro
set "/#:=goto :#/%%"
::brackets comment macros
set "/#=rem/||(" & set "#/=)"

::testing
echo not commented 1

%/#:%
  multi 
  line
  comment outside of brackets
%:#/%

echo not commented 2

%/#:%
  second multi 
  line
  comment outside of brackets
%:#/%

::GOTO macro cannot be used inside for loop
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %/#%
        multi line
        comment
    %#/%
    echo second not commented line of the %%a execution
)

To emphase that's a comment (thought it is not so short):

@echo off

::GOTO comment macro
set "REM{:=goto :}REM%%"
::brackets comment macros
set "REM{=rem/||(" & set "}REM=)"

::testing
echo not commented 1

%REM{:%
  multi 
  line
  comment outside of brackets
%:}REM%

echo not commented 2

%REM{:%
  second multi 
  line
  comment outside of brackets
%:}REM%

::GOTO macro cannot be used inside for
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %REM{%
        multi line
        comment
    %}REM%
    echo second not commented line of the %%a execution
)

how to zip a folder itself using java

Have you tried Zeroturnaround Zip library? It's really neat! Zip a folder is just a one liner:

ZipUtil.pack(new File("D:\\reports\\january\\"), new File("D:\\reports\\january.zip"));

(thanks to Oleg Šelajev for the example)