Programs & Examples On #Discriminator

A discriminator is a column used in object-relational mapping problems to describe inheritance. It is often, but not exclusively, associated with the single table per class hierarchy approach.

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

DECLARE @new_super TABLE (
  row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  super_id   int
);

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

EF Code First "Invalid column name 'Discriminator'" but no inheritance

Old Q, but for posterity...it also also happens (.NET Core 2.1) if you have a self-referencing navigation property ("Parent" or "Children" of the same type) but the Id property name isn't what EF expects. That is, I had an "Id" property on my class called WorkflowBase, and it had an array of related child steps, which were also of type WorkflowBase, and it kept trying to associate them with a non-existent "WorkflowBaseId" (the name i suppose it prefers as a natural/conventional default). I had to explicitly configure it using HasMany(), WithOne(), and HasConstraintName() to tell it how to traverse. But I spent a few hours thinking the problem was in 'locally' mapping the object's primary key, which i attempted to fix a bunch of different ways but which was probably always working.

Programmatic equivalent of default(Type)

Slight adjustments to @Rob Fonseca-Ensor's solution: The following extension method also works on .Net Standard since I use GetRuntimeMethod instead of GetMethod.

public static class TypeExtensions
{
    public static object GetDefault(this Type t)
    {
        var defaultValue = typeof(TypeExtensions)
            .GetRuntimeMethod(nameof(GetDefaultGeneric), new Type[] { })
            .MakeGenericMethod(t).Invoke(null, null);
        return defaultValue;
    }

    public static T GetDefaultGeneric<T>()
    {
        return default(T);
    }
}

...and the according unit test for those who care about quality:

[Fact]
public void GetDefaultTest()
{
    // Arrange
    var type = typeof(DateTime);

    // Act
    var defaultValue = type.GetDefault();

    // Assert
    defaultValue.Should().Be(default(DateTime));
}

In Angular, how to add Validator to FormControl after control is created?

If you are using reactiveFormModule and have formGroup defined like this:

public exampleForm = new FormGroup({
        name: new FormControl('Test name', [Validators.required, Validators.minLength(3)]),
        email: new FormControl('[email protected]', [Validators.required, Validators.maxLength(50)]),
        age: new FormControl(45, [Validators.min(18), Validators.max(65)])
});

than you are able to add a new validator (and keep old ones) to FormControl with this approach:

this.exampleForm.get('age').setValidators([
        Validators.pattern('^[0-9]*$'),
        this.exampleForm.get('age').validator
]);
this.exampleForm.get('email').setValidators([
        Validators.email,
        this.exampleForm.get('email').validator
]);

FormControl.validator returns a compose validator containing all previously defined validators.

ORA-01653: unable to extend table by in tablespace ORA-06512

To resolve this error:

ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name

Just run this PL/SQL command for extended tablespace size automatically on-demand:

alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;

I get this error in import big dump file, just run this command without stopping import routine or restarting the database.

Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.

More info: alter_autoextend_on

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

If you have multiple tooltip configurations that you want to initialise, this works well for me.

$("body").tooltip({
    selector: '[data-toggle="tooltip"]'
});

You can then set the property on individual elements using data attributes.

Javascript foreach loop on associative array object

If the node.js or browser supported Object.entries(), it can be used as an alternative to using Object.keys() (https://stackoverflow.com/a/18804596/225291).

_x000D_
_x000D_
const h = {_x000D_
  a: 1,_x000D_
  b: 2_x000D_
};_x000D_
_x000D_
Object.entries(h).forEach(([key, value]) => console.log(value));_x000D_
// logs 1, 2
_x000D_
_x000D_
_x000D_

in this example, forEach uses Destructuring assignment of an array.

What's the PowerShell syntax for multiple values in a switch statement?

The switch doesn't appear to be case sensitive in PowerShell 5.1. All four of the $someString examples below work.

$someString = "YES"
$someString = "yes"
$someString = "yEs"
$someString = "y"

switch ($someString) {
   {"y","yes"} { "You entered Yes." }
   Default { "You didn't enter Yes."}
}

Here is my $PSVersionTable data.

Name                           Value
----                           -----
PSVersion                      5.1.17763.771
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17763.771
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

How to deserialize xml to object

Your classes should look like this

[XmlRoot("StepList")]
public class StepList
{
    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
}

public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("Desc")]
    public string Desc { get; set; }
}

Here is my testcode.

string testData = @"<StepList>
                        <Step>
                            <Name>Name1</Name>
                            <Desc>Desc1</Desc>
                        </Step>
                        <Step>
                            <Name>Name2</Name>
                            <Desc>Desc2</Desc>
                        </Step>
                    </StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
    StepList result = (StepList) serializer.Deserialize(reader);
}

If you want to read a text file you should load the file into a FileStream and deserialize this.

using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) 
{
    StepList result = (StepList) serializer.Deserialize(fileStream);
}

Where should my npm modules be installed on Mac OS X?

Second Thomas David Kehoe, with the following caveat --

If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.

So ~/.nvm/versions/node/{version}/lib/node_modules/.

Bootstrap 3 only for mobile

If you're looking to make the elements be 33.3% only on small devices and lower:

This is backwards from what Bootstrap is designed for, but you can do this:

<div class="row">
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
</div>

This will make each element 33.3% wide on small and extra small devices but 100% wide on medium and larger devices.

JSFiddle: http://jsfiddle.net/jdwire/sggt8/embedded/result/

If you're only looking to hide elements for smaller devices:

I think you're looking for the visible-xs and/or visible-sm classes. These will let you make certain elements only visible to small screen devices.

For example, if you want a element to only be visible to small and extra-small devices, do this:

<div class="visible-xs visible-sm">You're using a fairly small device.</div>

To show it only for larger screens, use this:

<div class="hidden-xs hidden-sm">You're probably not using a phone.</div>

See http://getbootstrap.com/css/#responsive-utilities-classes for more information.

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

Visual Studio: ContextSwitchDeadlock

The above solution is good in some scenarios but there is another scenario where this happens when you are unit testing and you try to "Debug Selected Tests" from the Test Explorer when you solution is not set to Debug.

In this case you need to change your solution from Release or whatever it is set to to Debug in this case. If this is the problem then changing "ContextSwitchDeadlock" won't really help you.

I missed this myself because the error message was so nasty I didn't check the obvious thing which was the Debug setting!

RecyclerView - How to smooth scroll to top of item on a certain position?

i Used Like This :

recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, new RecyclerView.State(), 5);

Create a symbolic link of directory in Ubuntu

In script is usefull something like this:

if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi

it prevents before re-create "bad" looped symlink after re-run script

How do I access my SSH public key?

If you're on Windows use the following, select all, and copy from a Notepad window:

notepad ~/.ssh/id_rsa.pub  

If you're on OS X, use:

pbcopy < ~/.ssh/id_rsa.pub

Count the cells with same color in google spreadsheet

here is a working version :

function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var range_input = book.getRange("B3:B4");
 var range_output = book.getRange("B6");
 var cell_colors = range_input.getBackgroundColors();
 var color = "#58FA58";
 var count = 0;

 for( var i in cell_colors ){
 Logger.log(cell_colors[i][0])
  if( cell_colors[i][0] == color ){ ++count }
  }
range_output.setValue(count);
 }  

SQL Error: 0, SQLState: 08S01 Communications link failure

Check your server config file /etc/mysql/my.cnf - verify bind_address is not set to 127.0.0.1. Set it to 0.0.0.0 or comment it out then restart server with:

sudo service mysql restart

Column calculated from another column?

You can use generated columns from MYSQL 5.7.

Example Usage:

ALTER TABLE tbl_test
ADD COLUMN calc_val INT 
GENERATED ALWAYS AS (((`column1` - 1) * 16) + `column2`) STORED;

VIRTUAL / STORED

  • Virtual: calculated on the fly when a record is read from a table (default)
  • Stored: calculated when a new record is inserted/updated within the table

HTML: How to limit file upload to be only images?

Edited

If things were as they SHOULD be, you could do this via the "Accept" attribute.

http://www.webmasterworld.com/forum21/6310.htm

However, browsers pretty much ignore this, so this is irrelavant. The short answer is, i don't think there is a way to do it in HTML. You'd have to check it server-side instead.

The following older post has some information that could help you with alternatives.

File input 'accept' attribute - is it useful?

How to configure WAMP (localhost) to send email using Gmail?

use stunnel on your server, to send with gmail. google it.

SQL selecting rows by most recent date with two unique columns

So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".

Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row

SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( 
    SELECT chargeId,MAX(serviceMonth) AS serviceMonth
    FROM invoice
    GROUP BY chargeId) x 
    JOIN invoice t ON x.chargeId =t.chargeId
    AND x.serviceMonth = t.serviceMonth

What are callee and caller saved registers?

Caller-Saved (AKA volatile or call-clobbered) Registers

  • The values in caller-saved registers are short term and are not preserved from call to call  
  • It holds temporary (i.e. short term) data

Callee-Saved (AKA non-volatile or call-preserved) Registers

  • The callee-saved registers hold values across calls and are long term
  • It holds non-temporary (i.e. long term) data that is used through multiple functions/calls

Python strptime() and timezones?

Ran into this exact problem.

What I ended up doing:

# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'

# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)

# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))

# set timezone
import pendulum
tz = pendulum.timezone('utc')

dt_tz = datetime(*dt_vals,tzinfo=tz)

What is the best way to trigger onchange event in react js

well since we use functions to handle an onchange event, we can do it like this:

class Form extends Component {
 constructor(props) {
  super(props);
  this.handlePasswordChange = this.handlePasswordChange.bind(this);
  this.state = { password: '' }
 }

 aForceChange() {
  // something happened and a passwordChange
  // needs to be triggered!!

  // simple, just call the onChange handler
  this.handlePasswordChange('my password');
 }

 handlePasswordChange(value) {
 // do something
 }

 render() {
  return (
   <input type="text" value={this.state.password} onChange={changeEvent => this.handlePasswordChange(changeEvent.target.value)} />
  );
 }
}

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

Pass parameter to controller from @Html.ActionLink MVC 4

You are using a wrong overload of the Html.ActionLink helper. What you think is routeValues is actually htmlAttributes! Just look at the generated HTML, you will see that this anchor's href property doesn't look as you expect it to look.

Here's what you are using:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // routeValues
    new {                                                     // htmlAttributes
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    }
)

and here's what you should use:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // controllerName
    new {                                                     // routeValues
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    },
    null                                                      // htmlAttributes
)

Also there's another very serious issue with your code. The following routeValue:

replyblogPostmodel = Model

You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel parameter from your controller action. You should use the blogPostId parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:

public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
    BlogPostModel model = repository.Get(blogPostId);
    ...
}

As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:

@Html.ActionLink(
    linkText: "Reply",
    actionName: "BlogReplyCommentAdd",
    controllerName: "Blog",
    routeValues: new {
        blogPostId = blogPostId, 
        captchaValid = Model.AddNewComment.DisplayCaptcha
    },
    htmlAttributes: null
)

Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

JBoss default password

I suggest visit Add digest auth in jmx-console and read oficial documentation for Configure admin consoles, you can add more security to your JBoss AS console and at these link explains where are the role and user/pass files that you need to change this information for your server and how you can change them. Also I recommend you quit all consoles that you don't use because they can affect to application server's performance. Also there are others links about securing jmx-console that could help you, search in jboss as community site for them (I can't put them here for my actual reputation,sorry). Never you should has the password in plain text over conf/props/ files.

Sorry for my bad English and I hope my answer be useful for you.

C# : Converting Base Class to Child Class

I'm surprised AutoMapper hasn't come up as an answer.

As is clear from all the previous answers, you cannot do the typecast. However, using AutoMapper, in a few lines of code you can have a new SkyfilterClient instantiated based on an existing NetworkClient.

In essence, you would put the following where you are currently doing your typecasting:

using AutoMapper;
...
// somewhere, your network client was declared
var existingNetworkClient = new NetworkClient();
...
// now we want to type-cast, but we can't, so we instantiate using AutoMapper
AutoMapper.Mapper.CreateMap<NetworkClient, SkyfilterClient>();
var skyfilterObject = AutoMapper.Mapper.Map<SkyfilterClient>(existingNetworkClient);

Here's a full-blown example:

  public class Vehicle
  {
    public int NumWheels { get; set; }
    public bool HasMotor { get; set; }
  }

  public class Car: Vehicle
  {
    public string Color { get; set; }
    public string SteeringColumnStyle { get; set; }
  }

  public class CarMaker
  {
    // I am given vehicles that I want to turn into cars...
    public List<Car> Convert(List<Vehicle> vehicles)
    {
      var cars = new List<Car>();
      AutoMapper.Mapper.CreateMap<Vehicle, Car>(); // Declare that we want some automagic to happen
      foreach (var vehicle in vehicles)
      {
        var car = AutoMapper.Mapper.Map<Car>(vehicle);
        // At this point, the car-specific properties (Color and SteeringColumnStyle) are null, because there are no properties in the Vehicle object to map from.
        // However, car's NumWheels and HasMotor properties which exist due to inheritance, are populated by AutoMapper.
        cars.Add(car);
      }
      return cars;
    }
  }

Create controller for partial view in ASP.NET MVC

It does not need its own controller. You can use

@Html.Partial("../ControllerName/_Testimonials.cshtml")

This allows you to render the partial from any page. Just make sure the relative path is correct.

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

Vue is not defined

I found two main problems with that implementation. First, when you import the vue.js script you use type="JavaScript" as content-type which is wrong. You should remove this type parameter because by default script tags have text/javascript as default content-type. Or, just replace the type parameter with the correct content-type which is type="text/javascript".

The second problem is that your script is embedded in the same HTML file means that it may be triggered first and probably the vue.js file was not loaded yet. You can fix this using a jQuery snippet $(function(){ /* ... */ }); or adding a javascript function as shown in this example:

_x000D_
_x000D_
// Verifies if the document is ready_x000D_
function ready(f) {_x000D_
  /in/.test(document.readyState) ? setTimeout('ready(' + f + ')', 9) : f();_x000D_
}_x000D_
_x000D_
ready(function() {_x000D_
  var demo = new Vue({_x000D_
    el: '#demo',_x000D_
    data: {_x000D_
      message: 'Hello Vue.js!'_x000D_
    }_x000D_
  })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="demo">_x000D_
  <p>{{message}}</p>_x000D_
  <input v-model="message">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python: avoid new line with print command

Utilize a trailing comma to prevent a new line from being presented:

print "this should be"; print "on the same line"

Should be:

print "this should be", "on the same line"

In addition, you can just attach the variable being passed to the end of the desired string by:

print "Nope, that is not a two. That is a", x

You can also use:

print "Nope, that is not a two. That is a %d" % x #assuming x is always an int

You can access additional documentation regarding string formatting utilizing the % operator (modulo).

Difference between OpenJDK and Adoptium/AdoptOpenJDK

In short:

  • OpenJDK has multiple meanings and can refer to:
    • free and open source implementation of the Java Platform, Standard Edition (Java SE)
    • open source repository — the Java source code aka OpenJDK project
    • prebuilt OpenJDK binaries maintained by Oracle
    • prebuilt OpenJDK binaries maintained by the OpenJDK community
  • AdoptOpenJDK — prebuilt OpenJDK binaries maintained by community (open source licensed)

Explanation:

Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.

OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.

OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.

Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.

AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.

OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.

Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".

Donald Smith, Java product manager at Oracle writes:

Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.


OpenJDK Providers and Comparison

----------------------------------------------------------------------------------------
|     Provider      | Free Builds | Free Binary   | Extended | Commercial | Permissive |
|                   | from Source | Distributions | Updates  | Support    | License    |
|--------------------------------------------------------------------------------------|
| AdoptOpenJDK      |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Amazon – Corretto |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Azul Zulu         |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| BellSoft Liberica |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| IBM               |    No       |    No         |   Yes    |   Yes      |   Yes      |
| jClarity          |    No       |    No         |   Yes    |   Yes      |   Yes      |
| OpenJDK           |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Oracle JDK        |    No       |    Yes        |   No**   |   Yes      |   No       |
| Oracle OpenJDK    |    Yes      |    Yes        |   No     |   No       |   Yes      |
| ojdkbuild         |    Yes      |    Yes        |   No     |   No       |   Yes      |
| RedHat            |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
| SapMachine        |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
----------------------------------------------------------------------------------------

Free Builds from Source - the distribution source code is publicly available and one can assemble its own build

Free Binary Distributions - the distribution binaries are publicly available for download and usage

Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle

Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)

Permissive License - the distribution license is non-protective, e.g. Apache 2.0


Which Java Distribution Should I Use?

In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.

What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.

Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).

If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.


Additional information

Time to look beyond Oracle's JDK by Stephen Colebourne

Java Is Still Free by Java Champions community (published on September 17, 2018)

Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)

Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)

Show Youtube video source into HTML5 video tag?

The <video> tag is meant to load in a video of a supported format (which may differ by browser).

YouTube embed links are not just videos, they are typically webpages that contain logic to detect what your user supports and how they can play the youtube video, using HTML5, or flash, or some other plugin based on what is available on the users PC. This is why you are having a difficult time using the video tag with youtube videos.

YouTube does offer a developer API to embed a youtube video into your page.

I made a JSFiddle as a live example: http://jsfiddle.net/zub16fgt/

And you can read more about the YouTube API here: https://developers.google.com/youtube/iframe_api_reference#Getting_Started

The Code can also be found below

In your HTML:

<div id="player"></div>

In your Javascript:

var onPlayerReady = function(event) {
    event.target.playVideo();  
};

// The first argument of YT.Player is an HTML element ID. 
// YouTube API will replace my <div id="player"> tag 
// with an iframe containing the youtube video.

var player = new YT.Player('player', {
    height: 320,
    width: 400,
    videoId : '6Dc1C77nra4',
    events : {
        'onReady' : onPlayerReady
    }
});

How do I clear the std::queue efficiently?

Using a unique_ptr might be OK.
You then reset it to obtain an empty queue and release the memory of the first queue. As to the complexity? I'm not sure - but guess it's O(1).

Possible code:

typedef queue<int> quint;

unique_ptr<quint> p(new quint);

// ...

p.reset(new quint);  // the old queue has been destroyed and you start afresh with an empty queue

AngularJS - Binding radio buttons to models with boolean values

That's an odd approach with isUserAnswer. Are you really going to send all three choices back to the server where it will loop through each one checking for isUserAnswer == true? If so, you can try this:

http://jsfiddle.net/hgxjv/4/

HTML:

<input type="radio" name="response" value="true" ng-click="setChoiceForQuestion(question1, choice)"/>

JavaScript:

$scope.setChoiceForQuestion = function (q, c) {
    angular.forEach(q.choices, function (c) {
        c.isUserAnswer = false;
    });

    c.isUserAnswer = true;
};

Alternatively, I'd recommend changing your tack:

http://jsfiddle.net/hgxjv/5/

<input type="radio" name="response" value="{{choice.id}}" ng-model="question1.userChoiceId"/>

That way you can just send {{question1.userChoiceId}} back to the server.

Call a python function from jinja2

Never saw such simple way at official docs or at stack overflow, but i was amazed when found this:

# jinja2.__version__ == 2.8
from jinja2 import Template

def calcName(n, i):
    return ' '.join([n] * i)

template = Template("Hello {{ calcName('Gandalf', 2) }}")

template.render(calcName=calcName)
# or
template.render({'calcName': calcName})

How do I tell a Python script to use a particular version

While the OP may be working on a nix platform this answer could help non-nix platforms. I have not experienced the shebang approach work in Microsoft Windows.

Rephrased: The shebang line answers your question of "within my script" but I believe only for Unix-like platforms. Even though it is the Unix shell, outside the script, that actually interprets the shebang line to determine which version of Python interpreter to call. I am not sure, but I believe that solution does not solve the problem for Microsoft Windows platform users.

In the Microsoft Windows world, the simplify the way to run a specific Python version, without environment variables setup specifically for each specific version of Python installed, is just by prefixing the python.exe with the path you want to run it from, such as C:\Python25\python.exe mymodule.py or D:\Python27\python.exe mymodule.py

However you'd need to consider the PYTHONPATH and other PYTHON... environment variables that would point to the wrong version of Python libraries.

For example, you might run: C:\Python2.5.2\python.exe mymodule

Yet, the environment variables may point to the wrong version as such:

PYTHONPATH = D:\Python27

PYTHONLIB = D:\Python27\lib

Loads of horrible fun!

So a non-virtualenv way, in Windows, would be to use a batch file that sets up the environment and calls a specific Python executable via prefixing the python.exe with the path it resides in. This way has additional details you'll have to manage though; such as using command line arguments for either of the "start" or "cmd.exe" command to "save and replace the "console" environment" if you want the console to stick around after the application exits.

Your question leads me to believe you have several Python modules, each expecting a certain version of Python. This might be solvable "within" the script by having a launching module which uses the subprocess module. Instead of calling mymodule.py you would call a module that calls your module; perhaps launch_mymodule.py

launch_mymodule.py

import sys
import subprocess
if sys.argv[2] == '272':
  env272 = {
    'PYTHONPATH': 'blabla',
    'PYTHONLIB': 'blabla', }
  launch272 = subprocess.Popen('D:\\Python272\\python.exe mymodule.py', env=env272)

if sys.argv[1] == '252'
  env252 = {
    'PYTHONPATH': 'blabla',
    'PYTHONLIB': 'blabla', }
  launch252 = subprocess.Popen('C:\\Python252\\python.exe mymodule.py', env=env252)

I have not tested this.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

How to pause a vbscript execution?

Script snip below creates a pause sub that displayes the pause text in a string and waits for the Enter key. z can be anything. Great if multilple user intervention required pauses are needed. I just keep it in my standard script template.

Pause("Press Enter to continue")

Sub Pause(strPause)
     WScript.Echo (strPause)
     z = WScript.StdIn.Read(1)
End Sub

How do I load an url in iframe with Jquery

here is Iframe in view:

<iframe class="img-responsive" id="ifmReport" width="1090" height="1200" >

    </iframe>

Load it in script:

 $('#ifmReport').attr('src', '/ReportViewer/ReportViewer.aspx');

Swap x and y axis without manually swapping values

  1. Click somewhere on the chart to select it.

  2. You should now see 3 new tabs appear at the top of the screen called "Design", "Layout" and "Format".

  3. Click on the "Design" tab.

  4. There will be a button called "Switch Row/Column" within the "data" group, click it.

CreateProcess error=206, The filename or extension is too long when running main() method

How many people sad above, there are a lot of plugins to gradle execute a by pass in this problem like:

plugins {
  id "ua.eshepelyuk.ManifestClasspath" version "1.0.0"
}

or

plugins {
  id "com.github.ManifestClasspath" version "0.1.0-RELEASE"
}

But the better solution that I found was kill the JVM process and everything is done.

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

Try this to read using Pandas:

pd.read_csv('u.item', sep='|', names=m_cols, encoding='latin-1')

What is the bower (and npm) version syntax?

Based on semver, you can use

  • Hyphen Ranges X.Y.Z - A.B.C 1.2.3-2.3.4 Indicates >=1.2.3 <=2.3.4

  • X-Ranges 1.2.x 1.X 1.2.*

  • Tilde Ranges ~1.2.3 ~1.2 Indicates allowing patch-level changes or minor version changes.

  • Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4

    Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple

    • ^1.2.x (means >=1.2.0 <2.0.0)
    • ^0.0.x (means >=0.0.0 <0.1.0)
    • ^0.0 (means >=0.0.0 <0.1.0)

What is the difference between .py and .pyc files?

"A program doesn't run any faster when it is read from a ".pyc" or ".pyo" file than when it is read from a ".py" file; the only thing that's faster about ".pyc" or ".pyo" files is the speed with which they are loaded. "

http://docs.python.org/release/1.5.1p1/tut/node43.html

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

angular-cli server - how to specify default port

You can now specify the port in the .angular-cli.json under the defaults:

"defaults": {
  "styleExt": "scss",
  "serve": {
    "port": 8080
  },
  "component": {}
}

Tested in angular-cli v1.0.6

How can I make a weak protocol reference in 'pure' Swift (without @objc)

AnyObject is the official way to use a weak reference in Swift.

class MyClass {
    weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate: AnyObject {
}

From Apple:

To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID276

Byte Array and Int conversion in Java

I took a long look at many questions like this, and found this post... I didn't like the fact that the conversion code is duplicated for each type, so I've made a generic method to perform the task:

public static byte[] toByteArray(long value, int n)
{
    byte[] ret = new byte[n];
    ret[n-1] = (byte) ((value >> (0*8) & 0xFF);   
    ret[n-2] = (byte) ((value >> (1*8) & 0xFF);   
    ...
    ret[1] = (byte) ((value >> ((n-2)*8) & 0xFF);   
    ret[0] = (byte) ((value >> ((n-1)*8) & 0xFF);   
    return ret;
}

See full post.

Can I embed a .png image into an html page?

use mod_rewrite to redirect the call to file.html to image.png without the url changing for the user

Have you tried just renaming the image.png file to file.html? I think most browser take mime header over file extension :)

Should a RESTful 'PUT' operation return something

Just as an empty Request body is in keeping with the original purpose of a GET request and empty response body is in keeping with the original purpose of a PUT request.

How can I conditionally require form inputs with AngularJS?

if you want put a input required if other is written:

   <input type='text'
   name='name'
   ng-model='person.name'/>

   <input type='text'
   ng-model='person.lastname'             
   ng-required='person.name' />  

Regards.

A quick and easy way to join array elements with a separator (the opposite of split) in Java

public String join(String[] str, String separator){
    String retval = "";
    for (String s: str){ retval+= separator + s;}
    return retval.replaceFirst(separator, "");
}

How to check if element has any children in Javascript?

You can check if the element has child nodes element.hasChildNodes(). Beware in Mozilla this will return true if the is whitespace after the tag so you will need to verify the tag type.

https://developer.mozilla.org/En/DOM/Node.hasChildNodes

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Using unset vs. setting a variable to empty

Based on the comments above, here is a simple test:

isunset() { [[ "${!1}" != 'x' ]] && [[ "${!1-x}" == 'x' ]] && echo 1; }
isset()   { [ -z "$(isunset "$1")" ] && echo 1; }

Example:

$ unset foo; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's unset
$ foo=     ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set
$ foo=bar  ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set

Autocompletion of @author in Intellij

For Intellij IDEA Community 2019.1 you will need to follow these steps :

File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */

Sys is undefined

Was having a similar issue, except that my page was consistently generating the Sys is undefined error.

For me the problem stems from the fact that I've just installed the AJAX 1.0 extension for .NET 2.0 but had already created my web project in Visual Studio.

When tried to create AJAX controls I kept encountering this error, I spotted Slace's and MadMax1138s posts here. And figured it was my web.config, I created a new project using the new "AJAX enabled web site" project type, and sure enough the web.config has a large number of customizations necessary to use the AJAX controls.

I just updated that web.config with the web.config updates I had already made myself and dropped it into my existing project and everything worked fine.

How can I check which version of Angular I'm using?

Just Run ng v in command

You will get result like

Angular CLI: 7.3.9
Node: 12.11.0
OS: win32 x64
Angular: 7.2.15
... common, compiler, compiler-cli, core, f
... language-service, platform-browser, pla
... router

Package                           Version
-------------------------------------------
@angular-devkit/architect         0.13.9
@angular-devkit/build-angular     0.13.9
@angular-devkit/build-optimizer   0.13.9
@angular-devkit/build-webpack     0.13.9
@angular-devkit/core              7.3.9
@angular-devkit/schematics        7.3.9
@angular/cli                      7.3.9
@ngtools/webpack                  7.3.9
@schematics/angular               8.0.0
@schematics/update                0.13.9
rxjs                              6.5.3
typescript                        3.1.6
webpack                           4.29.0

How to convert array to SimpleXML

a short one:

<?php

$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

results in

<?xml version="1.0"?>
<root>
  <blub>bla</blub>
  <bar>foo</bar>
  <overflow>stack</overflow>
</root>

keys and values are swapped - you could fix that with array_flip() before the array_walk. array_walk_recursive requires PHP 5. you could use array_walk instead, but you won't get 'stack' => 'overflow' in the xml then.

how to "execute" make file

You don't tend to execute the make file itself, rather you execute make, giving it the make file as an argument:

make -f pax.mk

If your make file is actually one of the standard names (like makefile or Makefile), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make man page to see which takes precedence).

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

The easiest and the correct way to do it - use Spacer()

Example:

Column(
    children: [
      SomeWidgetOnTheTop(),
      Spacer(),
      SomeCenterredBottomWidget(),
    ],
);

Mysql - delete from multiple tables with one query

You can also use following query :

DELETE FROM Student, Enrollment USING Student INNER JOIN Enrollment ON Student.studentId = Enrollment.studentId WHERE Student.studentId= 51;

How to save a base64 image to user's disk using JavaScript?

This Works

function saveBase64AsFile(base64, fileName) {
    var link = document.createElement("a");
    document.body.appendChild(link);
    link.setAttribute("type", "hidden");
    link.href = "data:text/plain;base64," + base64;
    link.download = fileName;
    link.click();  
    document.body.removeChild(link);
}

Based on the answer above but with some changes

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

This appears to fit what you are looking for: https://forums.oracle.com/forums/thread.jspa?threadID=2140801

Basically, you will need to use regular expressions as there appears to be nothing built into oracle for this.

I pulled out the example from the thread and converted it for your purposes. I suck at regex's, though, so that might need tweaked :)

SELECT  *
FROM myTable m
WHERE NOT regexp_like(m.status,'((Done^|Finished except^|In Progress^)')

grep using a character vector with multiple patterns

This should work:

grep(pattern = 'A1|A9|A6', x = myfile$Letter)

Or even more simply:

library(data.table)
myfile$Letter %like% 'A1|A9|A6'

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

The Syntax as specified by Microsoft for the dropping a column part of an ALTER statement is this

 DROP 
 {
     [ CONSTRAINT ] 
     { 
          constraint_name 
          [ WITH 
           ( <drop_clustered_constraint_option> [ ,...n ] ) 
          ] 
      } [ ,...n ]
      | COLUMN 
      {
          column_name 
      } [ ,...n ]
 } [ ,...n ]

Notice that the [,...n] appears after both the column name and at the end of the whole drop clause. What this means is that there are two ways to delete multiple columns. You can either do this:

ALTER TABLE TableName
    DROP COLUMN Column1, Column2, Column3

or this

ALTER TABLE TableName
    DROP 
        COLUMN Column1,
        COLUMN Column2,
        COLUMN Column3

This second syntax is useful if you want to combine the drop of a column with dropping a constraint:

ALTER TBALE TableName
    DROP
        CONSTRAINT DF_TableName_Column1,
        COLUMN Column1;

When dropping columns SQL Sever does not reclaim the space taken up by the columns dropped. For data types that are stored inline in the rows (int for example) it may even take up space on the new rows added after the alter statement. To get around this you need to create a clustered index on the table or rebuild the clustered index if it already has one. Rebuilding the index can be done with a REBUILD command after modifying the table. But be warned this can be slow on very big tables. For example:

ALTER TABLE Test
    REBUILD;

Multiline strings in VB.NET

Available in Visual Basic 14 as part of Visual Studio 2015 https://msdn.microsoft.com/en-us/magazine/dn890368.aspx

But not yet supported by R#. The good news is they will be supported soon! Please vote on Youtrack to notify JetBrains you need them also.

How to make a JSON call to a url?

In modern-day JS, you can get your JSON data by calling ES6's fetch() on your URL and then using ES7's async/await to "unpack" the Response object from the fetch to get the JSON data like so:

_x000D_
_x000D_
const getJSON = async url => {
  try {
    const response = await fetch(url);
    if(!response.ok) // check if response worked (no 404 errors etc...)
      throw new Error(response.statusText);

    const data = await response.json(); // get JSON from the response
    return data; // returns a promise, which resolves to this data value
  } catch(error) {
    return error;
  }
}

console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json").then(data => {
  console.log(data);
}).catch(error => {
  console.error(error);
});
_x000D_
_x000D_
_x000D_

The above method can be simplified down to a few lines if you ignore the exception/error handling (usually not recommended as this can lead to unwanted errors):

_x000D_
_x000D_
const getJSON = async url => {
  const response = await fetch(url);
  return response.json(); // get JSON from the response 
}

console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json")
  .then(data => console.log(data));
_x000D_
_x000D_
_x000D_

Pass a PHP array to a JavaScript function

Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.

drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))

This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here

$employee = array(
 "employee_id" => 10011,
   "Name" => "Nathan",
   "Skills" =>
    array(
           "analyzing",
           "documentation" =>
            array(
              "desktop",
                "mobile"
             )
        )
);

Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.

{
    "employee_id": 10011,
    "Name": "Nathan",
    "Skills": {
        "0": "analyzing",
        "documentation": [
            "desktop",
            "mobile"
        ]
    }
}

On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.

$.ajax({
        type: 'POST',
        headers: {
            "cache-control": "no-cache"
        },
        url: "employee.php",
        async: false,
        cache: false,
        data: {
            employee_id: 10011
        },
        success: function (jsonString) {
            var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
    });

How to create a oracle sql script spool file

To spool from a BEGIN END block is pretty simple. For example if you need to spool result from two tables into a file, then just use the for loop. Sample code is given below.

BEGIN

FOR x IN 
(
    SELECT COLUMN1,COLUMN2 FROM TABLE1
    UNION ALL
    SELECT COLUMN1,COLUMN2 FROM TABLEB
)    
LOOP
    dbms_output.put_line(x.COLUMN1 || '|' || x.COLUMN2);
END LOOP;

END;
/

Correct way to remove plugin from Eclipse

For some 'Eclipse Marketplace' plugins Uninstall may not work. (Ex: SonarLint v5)

So Try,

Help -> About Eclipse -> Installation details
  • search the plugin name in 'Installed Software'

  • Select plugin name and Uninstall it

Additional Detail

To fix plugin errors, after the uninstall revert back older version of plugin,

Help -> install new software..
  • Get plugin url from Google search and Add it (Example: https://eclipse-uc.sonarlint.org)

  • Select and install older versions of the Plugin. This will fix most of the plugin problems.

AutoComplete TextBox Control

Check out the AutoCompleteSource, AutoCompleteCustomSource and AutoCompleteMode properties.

textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
col.Add("Foo");
col.Add("Bar");
textBox1.AutoCompleteCustomSource = col;

Note that the designer allows you to do that without writing any code...

How to loop an object in React?

You can use it in a more compact way as:

var tifs = {1: 'Joe', 2: 'Jane'};
...

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { Object.entries(tifs).map((t,k) => <option key={k} value={t[0]}>{t[1]}</option>) }          
   </select>
)

And another slightly different flavour:

 Object.entries(tifs).map(([key,value],i) => <option key={i} value={key}>{value}</option>)  

Selecting non-blank cells in Excel with VBA

I know I'm am very late on this, but here some usefull samples:

'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select

or

'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
    .value = .value
end with

To find the last used row in column, never rely on LastCell, which is unreliable (it is not reset after deleting data). Instead, I use someting like

 lngLast = cells(rows.count,3).end(xlUp).row

SQL Server - Adding a string to a text column (concat equivalent)

To Join two string in SQL Query use function CONCAT(Express1,Express2,...)

Like....

SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable

How can I add new keys to a dictionary?

If you want to add a dictionary within a dictionary you can do it this way.

Example: Add a new entry to your dictionary & sub dictionary

dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)

Output:

{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}

NOTE: Python requires that you first add a sub

dictionary["dictionary_within_a_dictionary"] = {}

before adding entries.

Php - testing if a radio button is selected and get the value

Just simply use isset($_POST['radio']) so that whenever i click any of the radio button, the one that is clicked is set to the post.

 <form method="post" action="sample.php">
 select sex: 
 <input type="radio" name="radio" value="male">
 <input type="radio" name="radio" value="female">

 <input type="submit" value="submit">
 </form>

<?php

if (isset($_POST['radio'])){

    $Sex = $_POST['radio'];
 }
  ?>

How to implement a Map with multiple keys?

Another possile solution providing the possibility of more complicated keys can be found here: http://insidecoffe.blogspot.de/2013/04/indexable-hashmap-implementation.html

MVC Calling a view from a different controller

It is explained pretty well here: Display a view from another controller in ASP.NET MVC

To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.

When does Git refresh the list of remote branches?

The OP did not ask for cleanup for all remotes, rather for all branches of default remote.

So git fetch --prune is what should be used.

Setting git config remote.origin.prune true makes --prune automatic. In that case just git fetch will also prune stale remote branches from the local copy. See also Automatic prune with Git fetch or pull.

Note that this does not clean local branches that are no longer tracking a remote branch. See How to prune local tracking branches that do not exist on remote anymore for that.

What is the difference between localStorage, sessionStorage, session and cookies?

  1. LocalStorage

    Pros:

    1. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
    2. The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
    3. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

    Cons:

    1. It works on same-origin policy. So, data stored will only be available on the same origin.
  2. Cookies

    Pros:

    1. Compared to others, there's nothing AFAIK.

    Cons:

    1. The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
    2. The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

      Typically, the following are allowed:

      • 300 cookies in total
      • 4096 bytes per cookie
      • 20 cookies per domain
      • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)
  3. sessionStorage

    Pros:

    1. It is similar to localStorage.
    2. The data is not persistent i.e. data is only available per window (or tab in browsers like Chrome and Firefox). Data is only available during the page session. Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.

    Cons:

    1. The data is available only inside the window/tab in which it was set.
    2. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Checkout across-tabs - how to facilitate easy communication between cross-origin browser tabs.

How to detect the swipe left or Right in Android?

here is generic swipe left detector for any view in kotlin using databinding

@BindingAdapter("onSwipeLeft")
fun View.setOnSwipeLeft(runnable: Runnable) {
    setOnTouchListener(object : View.OnTouchListener {
        var x0 = 0F; var y0 = 0F; var t0 = 0L
        val defaultClickDuration = 200

        override fun onTouch(v: View?, motionEvent: MotionEvent?): Boolean {
            motionEvent?.let { event ->
                when(event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        x0 = event.x; y0 = event.y; t0 = System.currentTimeMillis()
                    }
                    MotionEvent.ACTION_UP -> {
                        val x1 = event.x; val y1 = event.y; val t1 = System.currentTimeMillis()

                        if (x0 == x1 && y0 == y1 && (t1 - t0) < defaultClickDuration) {
                            performClick()
                            return false
                        }
                        if (x0 > x1) { runnable.run() }
                    }
                    else -> {}
                }
            }
            return true
        }
    })
}

and then to use it in your layout:

app:onSwipeLeft="@{() -> viewModel.swipeLeftHandler()}"

How to build and fill pandas dataframe from for loop?

I may be wrong, but I think the accepted answer by @amit has a bug.

from pandas import DataFrame as df
x = [1,2,3]
y = [7,8,9,10]

# this gives me a syntax error at 'for' (Python 3.7)
d1 = df[[a, "A", b, "B"] for a in x for b in y]

# this works
d2 = df([a, "A", b, "B"] for a in x for b in y)

# and if you want to add the column names on the fly
# note the additional parentheses
d3 = df(([a, "A", b, "B"] for a in x for b in y), columns = ("l","m","n","o"))

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.

Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.

Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.

The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.

 &obj; //  valid
 &12;  //invalid

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

  1. Slowest and doesn't work in Python3: concatenate the items and call dict on the resulting list:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1.items() + d2.items() + d3.items())'
    
    100000 loops, best of 3: 4.93 usec per loop
    
  2. Fastest: exploit the dict constructor to the hilt, then one update:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1, **d2); d4.update(d3)'
    
    1000000 loops, best of 3: 1.88 usec per loop
    
  3. Middling: a loop of update calls on an initially-empty dict:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = {}' 'for d in (d1, d2, d3): d4.update(d)'
    
    100000 loops, best of 3: 2.67 usec per loop
    
  4. Or, equivalently, one copy-ctor and two updates:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1)' 'for d in (d2, d3): d4.update(d)'
    
    100000 loops, best of 3: 2.65 usec per loop
    

I recommend approach (2), and I particularly recommend avoiding (1) (which also takes up O(N) extra auxiliary memory for the concatenated list of items temporary data structure).

Bootstrap onClick button event

There is no show event in js - you need to bind your button either to the click event:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

A note of personal experience in addition to both Stefan Gehrig's answer and Dave None's answer (and mmmshuddup's reply):

I was having validation problems using both \n and PHP_EOL when I used the ICS validator at http://severinghaus.org/projects/icv/

I learned I had to use \r\n in order to get it to validate properly, so this was my solution:

function dateToCal($timestamp) {
  return date('Ymd\Tgis\Z', $timestamp);
}

function escapeString($string) {
  return preg_replace('/([\,;])/','\\\$1', $string);
}    

    $eol = "\r\n";
    $load = "BEGIN:VCALENDAR" . $eol .
    "VERSION:2.0" . $eol .
    "PRODID:-//project/author//NONSGML v1.0//EN" . $eol .
    "CALSCALE:GREGORIAN" . $eol .
    "BEGIN:VEVENT" . $eol .
    "DTEND:" . dateToCal($end) . $eol .
    "UID:" . $id . $eol .
    "DTSTAMP:" . dateToCal(time()) . $eol .
    "DESCRIPTION:" . htmlspecialchars($title) . $eol .
    "URL;VALUE=URI:" . htmlspecialchars($url) . $eol .
    "SUMMARY:" . htmlspecialchars($description) . $eol .
    "DTSTART:" . dateToCal($start) . $eol .
    "END:VEVENT" . $eol .
    "END:VCALENDAR";

    $filename="Event-".$id;

    // Set the headers
    header('Content-type: text/calendar; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $filename);

    // Dump load
    echo $load;

That stopped my parse errors and made my ICS files validate properly.

try/catch with InputMismatchException creates infinite loop

@Limp, your answer is right, just use .nextLine() while reading the input. Sample code:

    do {
        try {
            System.out.println("Enter first num: ");
            n1 = Integer.parseInt(input.nextLine());
            System.out.println("Enter second num: ");
            n2 = Integer.parseInt(input.nextLine());
            nQuotient = n1 / n2;
            bError = false;
        } catch (Exception e) {
            System.out.println("Error!");
        }
    } while (bError);

    System.out.printf("%d/%d = %d", n1, n2, nQuotient);

Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread. Java Homework user input issue

Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.

Setting log level of message at runtime in slf4j

Richard Fearn has the right idea, so I wrote up the full class based on his skeleton code. It's hopefully short enough to post here. Copy & paste for enjoyment. I should probably add some magic incantation, too: "This code is released to the public domain"

import org.slf4j.Logger;

public class LogLevel {

    /**
     * Allowed levels, as an enum. Import using "import [package].LogLevel.Level"
     * Every logging implementation has something like this except SLF4J.
     */

    public static enum Level {
        TRACE, DEBUG, INFO, WARN, ERROR
    }

    /**
     * This class cannot be instantiated, why would you want to?
     */

    private LogLevel() {
        // Unreachable
    }

    /**
     * Log at the specified level. If the "logger" is null, nothing is logged.
     * If the "level" is null, nothing is logged. If the "txt" is null,
     * behaviour depends on the SLF4J implementation.
     */

    public static void log(Logger logger, Level level, String txt) {
        if (logger != null && level != null) {
            switch (level) {
            case TRACE:
                logger.trace(txt);
                break;
            case DEBUG:
                logger.debug(txt);
                break;
            case INFO:
                logger.info(txt);
                break;
            case WARN:
                logger.warn(txt);
                break;
            case ERROR:
                logger.error(txt);
                break;
            }
        }
    }

    /**
     * Log at the specified level. If the "logger" is null, nothing is logged.
     * If the "level" is null, nothing is logged. If the "format" or the "argArray"
     * are null, behaviour depends on the SLF4J-backing implementation.
     */

    public static void log(Logger logger, Level level, String format, Object[] argArray) {
        if (logger != null && level != null) {
            switch (level) {
            case TRACE:
                logger.trace(format, argArray);
                break;
            case DEBUG:
                logger.debug(format, argArray);
                break;
            case INFO:
                logger.info(format, argArray);
                break;
            case WARN:
                logger.warn(format, argArray);
                break;
            case ERROR:
                logger.error(format, argArray);
                break;
            }
        }
    }

    /**
     * Log at the specified level, with a Throwable on top. If the "logger" is null,
     * nothing is logged. If the "level" is null, nothing is logged. If the "format" or
     * the "argArray" or the "throwable" are null, behaviour depends on the SLF4J-backing
     * implementation.
     */

    public static void log(Logger logger, Level level, String txt, Throwable throwable) {
        if (logger != null && level != null) {
            switch (level) {
            case TRACE:
                logger.trace(txt, throwable);
                break;
            case DEBUG:
                logger.debug(txt, throwable);
                break;
            case INFO:
                logger.info(txt, throwable);
                break;
            case WARN:
                logger.warn(txt, throwable);
                break;
            case ERROR:
                logger.error(txt, throwable);
                break;
            }
        }
    }

    /**
     * Check whether a SLF4J logger is enabled for a certain loglevel. 
     * If the "logger" or the "level" is null, false is returned.
     */

    public static boolean isEnabledFor(Logger logger, Level level) {
        boolean res = false;
        if (logger != null && level != null) {
            switch (level) {
            case TRACE:
                res = logger.isTraceEnabled();
                break;
            case DEBUG:
                res = logger.isDebugEnabled();
                break;
            case INFO:
                res = logger.isInfoEnabled();
                break;
            case WARN:
                res = logger.isWarnEnabled();
                break;
            case ERROR:
                res = logger.isErrorEnabled();
                break;
            }
        }
        return res;
    }
}

string.Replace in AngularJs

The easiest way is:

var oldstr="Angular isn't easy";
var newstr=oldstr.toString().replace("isn't","is");

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

Frequency table for a single variable

for frequency distribution of a variable with excessive values you can collapse down the values in classes,

Here I excessive values for employrate variable, and there's no meaning of it's frequency distribution with direct values_count(normalize=True)

                country  employrate alcconsumption
0           Afghanistan   55.700001            .03
1               Albania   11.000000           7.29
2               Algeria   11.000000            .69
3               Andorra         nan          10.17
4                Angola   75.699997           5.57
..                  ...         ...            ...
208             Vietnam   71.000000           3.91
209  West Bank and Gaza   32.000000               
210         Yemen, Rep.   39.000000             .2
211              Zambia   61.000000           3.56
212            Zimbabwe   66.800003           4.96

[213 rows x 3 columns]

frequency distribution with values_count(normalize=True) with no classification,length of result here is 139 (seems meaningless as a frequency distribution):

print(gm["employrate"].value_counts(sort=False,normalize=True))

50.500000   0.005618
61.500000   0.016854
46.000000   0.011236
64.500000   0.005618
63.500000   0.005618

58.599998   0.005618
63.799999   0.011236
63.200001   0.005618
65.599998   0.005618
68.300003   0.005618
Name: employrate, Length: 139, dtype: float64

putting classification we put all values with a certain range ie.

0-10 as 1,
11-20 as 2  
21-30 as 3, and so forth.
gm["employrate"]=gm["employrate"].str.strip().dropna()  
gm["employrate"]=pd.to_numeric(gm["employrate"])
gm['employrate'] = np.where(
   (gm['employrate'] <=10) & (gm['employrate'] > 0) , 1, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=20) & (gm['employrate'] > 10) , 1, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=30) & (gm['employrate'] > 20) , 2, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=40) & (gm['employrate'] > 30) , 3, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=50) & (gm['employrate'] > 40) , 4, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=60) & (gm['employrate'] > 50) , 5, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=70) & (gm['employrate'] > 60) , 6, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=80) & (gm['employrate'] > 70) , 7, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=90) & (gm['employrate'] > 80) , 8, gm['employrate']
   )
gm['employrate'] = np.where(
   (gm['employrate'] <=100) & (gm['employrate'] > 90) , 9, gm['employrate']
   )
print(gm["employrate"].value_counts(sort=False,normalize=True))

after classification we have a clear frequency distribution. here we can easily see, that 37.64% of countries have employ rate between 51-60% and 11.79% of countries have employ rate between 71-80%

5.000000   0.376404
7.000000   0.117978
4.000000   0.179775
6.000000   0.264045
8.000000   0.033708
3.000000   0.028090
Name: employrate, dtype: float64

Could not find any resources appropriate for the specified culture or the neutral culture

This error is also raised by Dotfuscation, since a resx designer file relies on reflection. If you are using Dotfuscator it will break your resx files. You must always add them as an exclusion from the obfuscation process.

Add CSS3 transition expand/collapse

OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.

<script>
        function dostuff() {
            if (document.getElementById('MyBox').style.height == "0px") {

                document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;"); 
            }
            else {
                document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;"); 
             }
        }
    </script>
    <div id="MyBox" style="height: 0px; width: 0px;">
    </div>

    <input type="button" id="buttontest" onclick="dostuff()" value="Click Me">

Convert double to float in Java

Converting from double to float will be a narrowing conversion. From the doc:

A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.

A narrowing primitive conversion from double to float is governed by the IEEE 754 rounding rules (§4.2.4). This conversion can lose precision, but also lose range, resulting in a float zero from a nonzero double and a float infinity from a finite double. A double NaN is converted to a float NaN and a double infinity is converted to the same-signed float infinity.

So it is not a good idea. If you still want it you can do it like:

double d = 3.0;
float f = (float) d;

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

How to len(generator())

Generators have no length, they aren't collections after all.

Generators are functions with a internal state (and fancy syntax). You can repeatedly call them to get a sequence of values, so you can use them in loop. But they don't contain any elements, so asking for the length of a generator is like asking for the length of a function.

if functions in Python are objects, couldn't I assign the length to a variable of this object that would be accessible to the new generator?

Functions are objects, but you cannot assign new attributes to them. The reason is probably to keep such a basic object as efficient as possible.

You can however simply return (generator, length) pairs from your functions or wrap the generator in a simple object like this:

class GeneratorLen(object):
    def __init__(self, gen, length):
        self.gen = gen
        self.length = length

    def __len__(self): 
        return self.length

    def __iter__(self):
        return self.gen

g = some_generator()
h = GeneratorLen(g, 1)
print len(h), list(h)

EOFError: end of file reached issue with Net::HTTP

I had a similar problem with a request to a non-SSL service.

This blog suggested vaguely to try URI encoding the URL that is passed to 'get': http://www.loudthinking.org/2010/02/ruby-eoferror-end-of-file-reached.html

I took a shot at it, based on desperation, and in my limiting testing this seems to have fixed it for me. My new code is:

@http = Net::HTTP.new('domain.com')  
@http = @http.start    
url = 'http://domain.com/requested_url?blah=blah&etc=1'
req = Net::HTTP::Get.new(URI.encode(url))
req.basic_auth USERNAME, API_KEY
res = @http.request(req) 

Note that I use @http.start as I want to maintain the HTTP session over multiple requests. Other than that, you might like to try the most relevant part which is: URI.encode(url) inside the get call

how to parse JSON file with GSON

In case you need to parse it from a file, I find the best solution to use a HashMap<String, String> to use it inside your java code for better manipultion.

Try out this code:

public HashMap<String, String> myMethodName() throws FileNotFoundException
{
    String path = "absolute path to your file";
    BufferedReader bufferedReader = new BufferedReader(new FileReader(path));

    Gson gson = new Gson();
    HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
    return json;
}

How to define constants in Visual C# like #define in C?

static class Constants
{
    public const int MIN_LENGTH = 5;
    public const int MIN_WIDTH  = 5; 
    public const int MIN_HEIGHT = 6;
}

// elsewhere
public CBox()
{
    length = Constants.MIN_LENGTH; 
    width  = Constants.MIN_WIDTH; 
    height = Constants.MIN_HEIGHT;  
}

Combine two tables that have no common fields

SELECT *
FROM table1, table2

This will join every row in table1 with table2 (the Cartesian product) returning all columns.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

One thing which is invariably true is that at this time, the device would be suffocating for some memory (which is usually the reason for GC to most likely get triggered).

As mentioned by almost all authors earlier, this issue surfaces when Android tries to run GC while the app is in background. In most of the cases where we observed it, user paused the app by locking their screen. This might also indicate memory leak somewhere in the application, or the device being too loaded already. So the only legitimate way to minimize it is:

  • to ensure there are no memory leaks, and
  • to reduce the memory footprint of the app in general.

How do you access the matched groups in a JavaScript regular expression?

Get all group occurrence

_x000D_
_x000D_
let m=[], s = "something format_abc  format_def  format_ghi";_x000D_
_x000D_
s.replace(/(?:^|\s)format_(.*?)(?:\s|$)/g, (x,y)=> m.push(y));_x000D_
_x000D_
console.log(m);
_x000D_
_x000D_
_x000D_

Why is the use of alloca() not considered good practice?

One issue is that it isn't standard, although it's widely supported. Other things being equal, I'd always use a standard function rather than a common compiler extension.

How to add header to a dataset in R?

this should work out,

      kable(dt) %>%
      kable_styling("striped") %>%
      add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))
#OR
kable(dt) %>%
  kable_styling(c("striped", "bordered")) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
  add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
  add_header_above(c(" ", "Group 6" = 6))

for more you can check the link

Signed to unsigned conversion in C - is it always safe?

Horrible Answers Galore

Ozgur Ozcitak

When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.

This is completely wrong.

Mats Fredriksson

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.

smh

Your addition operation causes the int to be converted to an unsigned int.

Wrong. Maybe it does and maybe it doesn't.

Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)

Wrong. It is either undefined behavior if it causes overflow or the value is preserved.

Anonymous

The value of i is converted to unsigned int ...

Wrong. Depends on the precision of an int relative to an unsigned int.

Taylor Price

As was previously answered, you can cast back and forth between signed and unsigned without a problem.

Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.

Now I can finally answer the question.

Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 [1]. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.

Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.

What is precision?

Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.

[Gotchas]

The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.

[1] The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.

Why can't I reference my class library?

If both projects are contained within the same solution, it will be more apropiate if you add the reference for the project you need, not its compiled dll.

enter image description here

How to iterate through a list of dictionaries in Jinja template?

**get id from dic value. I got the result.try the below code**
get_abstracts = s.get_abstracts(session_id)
    sessions = get_abstracts['sessions']
    abs = {}
    for a in get_abstracts['abstracts']:
        a_session_id = a['session_id']
        abs.setdefault(a_session_id,[]).append(a)
    authors = {}
    # print('authors')
    # print(get_abstracts['authors'])
    for au in get_abstracts['authors']: 
        # print(au)
        au_abs_id = au['abs_id']
        authors.setdefault(au_abs_id,[]).append(au)
 **In jinja template**
{% for s in sessions %}
          <h4><u>Session : {{ s.session_title}} - Hall : {{ s.session_hall}}</u></h4> 
            {% for a in abs[s.session_id] %}
            <hr>
                      <p><b>Chief Author :</b>  Dr. {{ a.full_name }}</p>  
               
                {% for au in authors[a.abs_id] %}
                      <p><b> {{ au.role }} :</b> Dr.{{ au.full_name }}</p>
                {% endfor %}
            {% endfor %}
        {% endfor %}

Passing parameters to addTarget:action:forControlEvents

I was creating several buttons for each phone number in an array so each button needed a different phone number to call. I used the setTag function as I was creating several buttons within a for loop:

for (NSInteger i = 0; i < _phoneNumbers.count; i++) {

    UIButton *phoneButton = [[UIButton alloc] initWithFrame:someFrame];
    [phoneButton setTitle:_phoneNumbers[i] forState:UIControlStateNormal];

    [phoneButton setTag:i];

    [phoneButton addTarget:self
                    action:@selector(call:)
          forControlEvents:UIControlEventTouchUpInside];
}

Then in my call: method I used the same for loop and an if statement to pick the correct phone number:

- (void)call:(UIButton *)sender
{
    for (NSInteger i = 0; i < _phoneNumbers.count; i++) {
        if (sender.tag == i) {
            NSString *callString = [NSString stringWithFormat:@"telprompt://%@", _phoneNumbers[i]];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callString]];
        }
    }
}

What's the difference between tilde(~) and caret(^) in package.json?

Hat matching may be considered "broken" because it wont update ^0.1.2 to 0.2.0. When the software is emerging use 0.x.y versions and hat matching will only match the last varying digit (y). This is done on purpose. The reason is that while the software is evolving the API changes rapidly: one day you have these methods and the other day you have those methods and the old ones are gone. If you don't want to break the code for people who already are using your library you go and increment the major version: e.g. 1.0.0 -> 2.0.0 -> 3.0.0. So, by the time your software is finally 100% done and full-featured it will be like version 11.0.0 and that doesn't look very meaningful, and actually looks confusing. If you were, on the other hand, using 0.1.x -> 0.2.x -> 0.3.x versions then by the time the software is finally 100% done and full-featured it is released as version 1.0.0 and it means "This release is a long-term service one, you can proceed and use this version of the library in your production code, and the author won't change everything tomorrow, or next month, and he won't abandon the package".

The rule is: use 0.x.y versioning when your software hasn't yet matured and release it with incrementing the middle digit when your public API changes (therefore people having ^0.1.0 won't get 0.2.0 update and it won't break their code). Then, when the software matures, release it under 1.0.0 and increment the leftmost digit each time your public API changes (therefore people having ^1.0.0 won't get 2.0.0 update and it won't break their code).

Given a version number MAJOR.MINOR.PATCH, increment the:

MAJOR version when you make incompatible API changes,
MINOR version when you add functionality in a backwards-compatible manner, and
PATCH version when you make backwards-compatible bug fixes.

JQuery string contains check

You can use javascript's indexOf function.

_x000D_
_x000D_
var str1 = "ABCDEFGHIJKLMNOP";_x000D_
var str2 = "DEFG";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
    console.log(str2 + " found");_x000D_
}
_x000D_
_x000D_
_x000D_

How do you get the length of a list in the JSF expression language?

You mean size() don't you?

#{MyBean.somelist.size()}

works for me (using JBoss Seam which has the Jboss EL extensions)

VirtualBox error "Failed to open a session for the virtual machine"

maybe it is caused by privilege, please try this:

#sudo chmod 755 /Applications 
#sudo chmod 755 /Applications/Virtualbox.app

How to stop Python closing immediately when executed in Microsoft Windows

Very simple:

  1. Open command prompt as an administrator.
  2. Type python.exe (provided you have given path of it in environmental variables)

Then, In the same command prompt window the python interpreter will start with >>>

This worked for me.

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

Invariant Violation: Objects are not valid as a React child

try{
    throw new Error(<p>An error occured</p>)
}catch(e){
    return (e)
}

The above code produced the error, I then rewrote it like this:

try{
    throw(<p>An error occured</p>)
}catch(e){
    return (e)
}

Take note of the removal of new Error() in the try block...

A better way to write the code in order to avoid this error message Expected an object to be thrown no-throw-literal is to pass a string into throw new Error() instead of JSX and return JSX in your catch block, something like this:

try{
    throw new Error("An error occurred")
}catch(e){
    return (
        <p>{e.message}</p>
    )
}

Remove "Using default security password" on Spring Boot

Although it works, the current solution is a little overkill as noted in some comments. So here is an alternative that works for me, using the latest Spring Boot (1.4.3).

The default security password is configured inside Spring Boot's AuthenticationManagerConfiguration class. This class has a conditional annotation to prevent from loading if a AuthenticationManager Bean is already defined.

The folllowing code works to prevent execution of the code inside AuthenticationManagerConfiguration because we define our current AuthenticationManager as a bean.

@Configuration
@EnableWebSecurity
public class MyCustomSecurityConfig extends WebSecurityConfigurerAdapter{

[...]

@Override
protected void configure(AuthenticationManagerBuilder authManager) throws Exception {
    // This is the code you usually have to configure your authentication manager.
    // This configuration will be used by authenticationManagerBean() below.
}

@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    // ALTHOUGH THIS SEEMS LIKE USELESS CODE,
    // IT'S REQUIRED TO PREVENT SPRING BOOT AUTO-CONFIGURATION
    return super.authenticationManagerBean();
}

}

Using CSS for a fade-in effect on page load

Looking forward to Web Animations in 2020.

_x000D_
_x000D_
async function moveToPosition(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        transform: `translateY(${el.getBoundingClientRect().top}px)`
      },
    ], {
      duration: durationInMs,
      easing: 'ease-in',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeIn(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        opacity: '0.5',
        offset: 0.5
      },
      {
        opacity: '1',
        offset: 1
      }
    ], {
      duration: durationInMs,
      easing: 'linear',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeInSections() {
  for (const section of document.getElementsByTagName('section')) {
    await fadeIn(section, 200);
  }
}

window.addEventListener('load', async() => {
  await moveToPosition(document.getElementById('headerContent'), 500);
  await fadeInSections();
  await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
  height: 100vh;
}

header {
  height: 20%;
}

.text-center {
  text-align: center;
}

.leading-none {
  line-height: 1;
}

.leading-3 {
  line-height: .75rem;
}

.leading-2 {
  line-height: .25rem;
}

.bg-black {
  background-color: rgba(0, 0, 0, 1);
}

.bg-gray-50 {
  background-color: rgba(249, 250, 251, 1);
}

.pt-12 {
  padding-top: 3rem;
}

.pt-2 {
  padding-top: 0.5rem;
}

.text-lightGray {
  color: lightGray;
}

.container {
  display: flex;
  /* or inline-flex */
  justify-content: space-between;
}

.container section {
  padding: 0.5rem;
}

.opacity-0 {
  opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="Web site created using create-snowpack-app" />
  <link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>

<body>
  <header class="bg-gray-50">
    <div id="headerContent">
      <h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
      <p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
    </div>
  </header>
  <div class="container">
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 1</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 2</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>

    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 3</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
  </div>
  <footer class="opacity-0">
    <h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
    <p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
  </footer>
</body>

</html>
_x000D_
_x000D_
_x000D_

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

In my case, I selected wrong RegionEndpoint. After selecting the correct RegionEndpoint, it started working :)

"Use the new keyword if hiding was intended" warning

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.

interface IShow
{
    protected void ShowData();
}

class A : IShow
{
    protected void ShowData()
    {
        Console.WriteLine("This is Class A");
    }
}

class B : A
{
    protected new void ShowData()
    {
        Console.WriteLine("This is Class B");
    }
}

Python code to remove HTML tags from a string

There's a simple way to this in any C-like language. The style is not Pythonic but works with pure Python:

def remove_html_markup(s):
    tag = False
    quote = False
    out = ""

    for c in s:
            if c == '<' and not quote:
                tag = True
            elif c == '>' and not quote:
                tag = False
            elif (c == '"' or c == "'") and tag:
                quote = not quote
            elif not tag:
                out = out + c

    return out

The idea based in a simple finite-state machine and is detailed explained here: http://youtu.be/2tu9LTDujbw

You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s

PS - If you're interested in the class(about smart debugging with python) I give you a link: https://www.udacity.com/course/software-debugging--cs259. It's free!

With arrays, why is it the case that a[5] == 5[a]?

For pointers in C, we have

a[5] == *(a + 5)

and also

5[a] == *(5 + a)

Hence it is true that a[5] == 5[a].

How to append binary data to a buffer in node.js

This is to help anyone who comes here looking for a solution that wants a pure approach. I would recommend understanding this problem because it can happen in lots of different places not just with a JS Buffer object. By understanding why the problem exists and how to solve it you will improve your ability to solve other problems in the future since this one is so fundamental.

For those of us that have to deal with these problems in other languages it is quite natural to devise a solution, but there are people who may not realize how to abstract away the complexities and implement a generally efficient dynamic buffer. The code below may have potential to be optimized further.

I have left the read method unimplemented to keep the example small in size.

The realloc function in C (or any language dealing with intrinsic allocations) does not guarantee that the allocation will be expanded in size with out moving the existing data - although sometimes it is possible. Therefore most applications when needing to store a unknown amount of data will use a method like below and not constantly reallocate, unless the reallocation is very infrequent. This is essentially how most file systems handle writing data to a file. The file system simply allocates another node and keeps all the nodes linked together, and when you read from it the complexity is abstracted away so that the file/buffer appears to be a single contiguous buffer.

For those of you who wish to understand the difficulty in just simply providing a high performance dynamic buffer you only need to view the code below, and also do some research on memory heap algorithms and how the memory heap works for programs.

Most languages will provide a fixed size buffer for performance reasons, and then provide another version that is dynamic in size. Some language systems opt for a third-party system where they keep the core functionality minimal (core distribution) and encourage developers to create libraries to solve additional or higher level problems. This is why you may question why a language does not provide some functionality. This small core functionality allows costs to be reduced in maintaining and enhancing the language, however you end up having to write your own implementations or depending on a third-party.

var Buffer_A1 = function (chunk_size) {
    this.buffer_list = [];
    this.total_size = 0;
    this.cur_size = 0;
    this.cur_buffer = [];
    this.chunk_size = chunk_size || 4096;

    this.buffer_list.push(new Buffer(this.chunk_size));
};

Buffer_A1.prototype.writeByteArrayLimited = function (data, offset, length) {
    var can_write = length > (this.chunk_size - this.cur_size) ? (this.chunk_size - this.cur_size) : length;

    var lastbuf = this.buffer_list.length - 1;

    for (var x = 0; x < can_write; ++x) {
        this.buffer_list[lastbuf][this.cur_size + x] = data[x + offset];
    }

    this.cur_size += can_write;
    this.total_size += can_write;

    if (this.cur_size == this.chunk_size) {
        this.buffer_list.push(new Buffer(this.chunk_size));
        this.cur_size = 0;
    }

    return can_write;
};

/*
    The `data` parameter can be anything that is array like. It just must
    support indexing and a length and produce an acceptable value to be
    used with Buffer.
*/
Buffer_A1.prototype.writeByteArray = function (data, offset, length) {
    offset = offset == undefined ? 0 : offset;
    length = length == undefined ? data.length : length;

    var rem = length;
    while (rem > 0) {
        rem -= this.writeByteArrayLimited(data, length - rem, rem);
    }
};

Buffer_A1.prototype.readByteArray = function (data, offset, length) {
    /*
        If you really wanted to implement some read functionality
        then you would have to deal with unaligned reads which could
        span two buffers.
    */
};

Buffer_A1.prototype.getSingleBuffer = function () {
    var obuf = new Buffer(this.total_size);
    var cur_off = 0;
    var x;

    for (x = 0; x < this.buffer_list.length - 1; ++x) {
        this.buffer_list[x].copy(obuf, cur_off);
        cur_off += this.buffer_list[x].length;
    }

    this.buffer_list[x].copy(obuf, cur_off, 0, this.cur_size);

    return obuf;
};

seek() function?

Regarding seek() there's not too much to worry about.

First of all, it is useful when operating over an open file.

It's important to note that its syntax is as follows:

fp.seek(offset, from_what)

where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:

  • 0: means your reference point is the beginning of the file
  • 1: means your reference point is the current file position
  • 2: means your reference point is the end of the file

if omitted, from_what defaults to 0.

Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek will be useful to you when you need to walk along that open file, just as a path you are traveling into.

How to convert string to long

Do this:

long l = Long.parseLong(str);

However, always check that str contains digits to prevent throwing exceptions. For instance:

String str="ABCDE";
long l = Long.parseLong(str);

would throw an exception but this

String str="1234567";
long l = Long.parseLong(str);

won't.

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

I am updating @Aliceljm answer here. Since the decimal place matters for 1,2 digit numbers, I am round off the first decimal place and keep the first decimal place. For 3 digit number, I am round off the units place and ignoring the all decimal places.

getMultiplers : function(bytes){
    var unit = 1000 ;
    if (bytes < unit) return bytes ;
    var exp = Math.floor(Math.log(bytes) / Math.log(unit));
    var pre = "kMGTPE".charAt(exp-1);
    var result = bytes / Math.pow(unit, exp);
    if(result/100 < 1)
        return (Math.round( result * 10 ) / 10) +pre;
    else
        return Math.round(result) + pre;
}

Secondary axis with twinx(): how to add to legend?

You can easily add a second legend by adding the line:

ax2.legend(loc=0)

You'll get this:

enter image description here

But if you want all labels on one legend then you should do something like this:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10

fig = plt.figure()
ax = fig.add_subplot(111)

lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')

# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

Which will give you this:

enter image description here

Phone number formatting an EditText in Android

If you're only interested in international numbers and you'd like to be able to show the flag of the country that matches the country code in the input, I wrote a small library for that:

https://github.com/tfcporciuncula/phonemoji

Here's how it looks:

library demo

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I use jQuery for this:

jQuery('li').wrapInner('<span class="li_content" />');

& with some CSS:

li { color: red; }
li span.li_content { color: black; }

maybe overkill, but handy if you're coding for a CMS and you don't want to ask your editors to put an extra span in every list-items.

Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

Creating a new column based on if-elif-else condition

enter image description here

Lets say above one is your original dataframe and you want to add a new column 'old'

If age greater than 50 then we consider as older=yes otherwise False

step 1: Get the indexes of rows whose age greater than 50

row_indexes=df[df['age']>=50].index

step 2: Using .loc we can assign a new value to column

df.loc[row_indexes,'elderly']="yes"

same for age below less than 50

row_indexes=df[df['age']<50].index

df[row_indexes,'elderly']="no"

Using Pairs or 2-tuples in Java

Create a class that describes the concept you're actually modeling and use that. It can just store two Set<Long> and provide accessors for them, but it should be named to indicate what exactly each of those sets is and why they're grouped together.

How to reload or re-render the entire page using AngularJS

For the record, to force angular to re-render the current page, you can use:

$route.reload();

According to AngularJS documentation:

Causes $route service to reload the current route even if $location hasn't changed.

As a result of that, ngView creates new scope, reinstantiates the controller.

How to delete row based on cell value

If you're file isn't too big you can always sort by the column that has the - and once they're all together just highlight and delete. Then re-sort back to what you want.

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

For setting java properties on Windows app server:

  • configure tomcat > run as admin
  • then add Java opts:

  • restart service.

When does System.gc() do something?

The only example I can think of where it makes sense to call System.gc() is when profiling an application to search for possible memory leaks. I believe the profilers call this method just before taking a memory snapshot.

How to write inline if statement for print?

The 'else' statement is mandatory. You can do stuff like this :

>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>> 

EDIT:

Or, depending of your needs, you may try:

>>> if b: print(a)

Moving from position A to position B slowly with animation

I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.

$("#Friends").animate( {top:
  "-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );

Split large string in n-size chunks in JavaScript

Surprise! You can use split to split.

var parts = "1234567890 ".split(/(.{2})/).filter(O=>O)

Results in [ '12', '34', '56', '78', '90', ' ' ]

Get the current date in java.sql.Date format

Simply in one line:

java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());

Get Enum from Description attribute

public static class EnumEx
{
    public static T GetValueFromDescription<T>(string description) where T : Enum
    {
        foreach(var field in typeof(T).GetFields())
        {
            if (Attribute.GetCustomAttribute(field,
            typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentException("Not found.", nameof(description));
        // Or return default(T);
    }
}

Usage:

var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");

Bootstrap: How to center align content inside column?

You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="centerBlock">
                <img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
            </div>
        </div>
        <div class="col-sm-8 col-md-8 col-lg-8">
            Some content not important at this moment
        </div>
    </div>
</div>


// CSS

.centerBlock {
  display: table;
  margin: auto;
}

Simple JavaScript problem: onClick confirm not preventing default action

I use this, works like a charm. No need to have any functions, just inline with your link(s)

onclick="javascript:return confirm('Are you sure you want to delete this comment?')"

Difference between del, remove, and pop on lists

Already answered quite well by others. This one from my end :)

remove vs pop vs del

Evidently, pop is the only one which returns the value, and remove is the only one which searches the object, while del limits itself to a simple deletion.

Inserting a tab character into text using C#

Using Microsoft Winform controls, it is impossible to solve correctly your problem without an little workaround that I will explain below.

PROBLEM

The problem in using simply "\t" or vbTab is that when more than one TextBox are displayed and that alignment must be respected for all TextBox, the ONLY "\t" or vbTab solution will display something that is NOT ALWAYS correctly aligned.

Example in VB.Net:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    TextBox1.Text = "Bernard" + vbTab + "32"
    TextBox2.Text = "Luc" + vbTab + "47"
    TextBox3.Text = "François-Victor" + vbTab + "12"
End Sub

will display

enter image description here

as you can see, age value for François-Victor is shifted to the right and is not aligned with age value of two others TextBox.

SOLUTION

To solve this problem, you must set Tabs position using a specific SendMessage() user32.dll API function as shown below.

Public Class Form1

    Public Declare Function SendMessage _
        Lib "user32" Alias "SendMessageA" _
        ( ByVal hWnd As IntPtr _
        , ByVal wMsg As Integer _
        , ByVal wParam As Integer _
        , ByVal lParam() As Integer _
        ) As Integer

    Private Const EM_SETTABSTOPS As Integer = &HCB

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim tabs() As Integer = {4 * 25}

        TextBox1.Text = "Bernard" + vbTab + "32"
        SendMessage(TextBox1.Handle, EM_SETTABSTOPS, 1, tabs)
        TextBox2.Text = "Luc" + vbTab + "47"
        SendMessage(TextBox2.Handle, EM_SETTABSTOPS, 1, tabs)
        TextBox3.Text = "François-Victor" + vbTab + "12"
        SendMessage(TextBox3.Handle, EM_SETTABSTOPS, 1, tabs)
    End Sub

End Class

and following Form will be displayed

enter image description here

You can see that now, all value are correctly aligned :-)

REMARKS

Multiline property of the TextBox must be set to True. If this properties is set to False, the Tab is positioned as before.

How AcceptsTab property is assigned is not important (I have tested).

This question has already be treated on StackOverflow

Caution: the mesure Unit for Tab position is not character but something that seems to be 1/4 of character. That is why I multiply the length by 4.

C# SOLUTION

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

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, uint[] lParam);
        private const int EM_SETTABSTOPS = 0x00CB;
        private const char vbTab = '\t';

        public Form1()
        {
            InitializeComponent();

            var tabs = new uint[] { 25 * 4 };

            textBox1.Text = "Bernard" + vbTab + "32";
            SendMessage(textBox1.Handle, EM_SETTABSTOPS, 1, tabs);
            textBox2.Text = "Luc" + vbTab + "47";
            SendMessage(textBox2.Handle, EM_SETTABSTOPS, 1, tabs);
            textBox3.Text = "François-Victor" + vbTab + "12";
            SendMessage(textBox3.Handle, EM_SETTABSTOPS, 1, tabs);
        }
    }
}

How can I build multiple submit buttons django form?

You can also do like this,

 <form method='POST'>
    {{form1.as_p}}
    <button type="submit" name="btnform1">Save Changes</button>
    </form>
    <form method='POST'>
    {{form2.as_p}}
    <button type="submit" name="btnform2">Save Changes</button>
    </form>

CODE

if request.method=='POST' and 'btnform1' in request.POST:
    do something...
if request.method=='POST' and 'btnform2' in request.POST:
    do something...

Find and replace strings in vim on multiple lines

To answer this question:

:40,50s/foo/bar/g

replace foo with bar in these lines between the 40th line and the 50th line(inclusive), when execute this command you can currently in any line.

:50,40s/foo/bar/g

also works, vim will ask you for comfirm and then do the replacement for you as if you have input the first command.

:,50s/foo/bar/g

replace foo with bar in these lines between the line you are currently in and the 50th line(inclusive). (if you are in a line AFTER the 50th line vim will ask for confirm again)

To clearity the difference between vim and the vrapper plugin of Eclipse:

Note that in varpper

:,50s/foo/bar/g command will NOT work.

:50,40s/foo/bar/g will work without asking for comfirmation.

(For Vrapper Version 0.74.0 or older).

What does it mean when an HTTP request returns status code 0?

It should be noted that an ajax file upload exceeding the client_max_body_size directive for nginx will return this error code.

Using OR in SQLAlchemy

or_() function can be useful in case of unknown number of OR query components.

For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_() function we must do something like this:

query = Book.query
if filter.title and filter.author:
    query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
    query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
    query = query.filter(Book.author.ilike(filter.author))

With or_() function it can be rewritten to:

query = Book.query
not_null_filters = []
if filter.title:
    not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
    not_null_filters.append(Book.author.ilike(filter.author))

if len(not_null_filters) > 0:
    query = query.filter(or_(*not_null_filters))

Difference between TCP and UDP?

From the Skullbox article:

TCP (Transmission Control Protocol) is the most commonly used protocol on the Internet. The reason for this is because TCP offers error correction. When the TCP protocol is used there is a "guaranteed delivery." This is due largely in part to a method called "flow control." Flow control determines when data needs to be re-sent, and stops the flow of data until previous packets are successfully transferred. This works because if a packet of data is sent, a collision may occur. When this happens, the client re-requests the packet from the server until the whole packet is complete and is identical to its original.

UDP (User Datagram Protocol) is anther commonly used protocol on the Internet. However, UDP is never used to send important data such as webpages, database information, etc; UDP is commonly used for streaming audio and video. Streaming media such as Windows Media audio files (.WMA) , Real Player (.RM), and others use UDP because it offers speed! The reason UDP is faster than TCP is because there is no form of flow control or error correction. The data sent over the Internet is affected by collisions, and errors will be present. Remember that UDP is only concerned with speed. This is the main reason why streaming media is not high quality.

1) TCP is connection oriented and reliable where as UDP is connection less and unreliable.

2) TCP needs more processing at network interface level where as in UDP it’s not.

3) TCP uses, 3 way handshake, congestion control, flow control and other mechanism to make sure the reliable transmission.

4) UDP is mostly used in cases where the packet delay is more serious than packet loss.

How to get hostname from IP (Linux)?

In order to use nslookup, host or gethostbyname() then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

This issue can occur when there is a .git directory underneath one of the subdirectories. To fix it, check if there are other .git directories there, and remove them and try again.

Get year, month or day from numpy datetime64

This is how I do it.

import numpy as np

def dt2cal(dt):
    """
    Convert array of datetime64 to a calendar array of year, month, day, hour,
    minute, seconds, microsecond with these quantites indexed on the last axis.

    Parameters
    ----------
    dt : datetime64 array (...)
        numpy.ndarray of datetimes of arbitrary shape

    Returns
    -------
    cal : uint32 array (..., 7)
        calendar array with last axis representing year, month, day, hour,
        minute, second, microsecond
    """

    # allocate output 
    out = np.empty(dt.shape + (7,), dtype="u4")
    # decompose calendar floors
    Y, M, D, h, m, s = [dt.astype(f"M8[{x}]") for x in "YMDhms"]
    out[..., 0] = Y + 1970 # Gregorian Year
    out[..., 1] = (M - Y) + 1 # month
    out[..., 2] = (D - M) + 1 # dat
    out[..., 3] = (dt - D).astype("m8[h]") # hour
    out[..., 4] = (dt - h).astype("m8[m]") # minute
    out[..., 5] = (dt - m).astype("m8[s]") # second
    out[..., 6] = (dt - s).astype("m8[us]") # microsecond
    return out

It's vectorized across arbitrary input dimensions, it's fast, its intuitive, it works on numpy v1.15.4, it doesn't use pandas.

I really wish numpy supported this functionality, it's required all the time in application development. I always get super nervous when I have to roll my own stuff like this, I always feel like I'm missing an edge case.

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

In swift 4.2 I used following code to show and hide code using NSNotification

 @objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardheight = keyboardSize.height
        print(keyboardheight)
    }
}

Sort a List of Object in VB.NET

If you need a custom string sort, you can create a function that returns a number based on the order you specify.

For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:

Private Function sortpictures(s As String) As Integer
    If Regex.IsMatch(s, "FRONT") Then
        Return 0
    ElseIf Regex.IsMatch(s, "SIDE") Then
        Return 1
    ElseIf Regex.IsMatch(s, "CLASP") Then
        Return 2
    Else
        Return 3
    End If
End Function

Then I call the sort function like this:

list.Sort(Function(elA As String, elB As String)
                  Return sortpictures(elA).CompareTo(sortpictures(elB))
              End Function)

Disabling the long-running-script message in Internet Explorer

This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.

Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.

The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.

Breaking up a loop with timers is relatively straightforward:

var i=0;
(function () {
    for (; i < 6000000; i++) {
        /*
            Normal processing here
        */

        // Every 100,000 iterations, take a break
        if ( i > 0 && i % 100000 == 0) {
            // Manually increment `i` because we break
            i++;
            // Set a timer for the next iteration 
            window.setTimeout(arguments.callee);
            break;
        }
    }
})();

Show a number to two decimal places

$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

It will return 5.98 without rounding the number.

How to get city name from latitude and longitude coordinates in Google Maps?

import org.json.JSONObject

fun parseLocation(response: String): GeoLocation? {

val geoCodes by lazy { doubleArrayOf(0.0, 0.0) }

val jObj = JSONObject(response)
if (jObj.has(KEY_RESULTS)) {

    val jArrResults = jObj.getJSONArray(KEY_RESULTS)
    for (i in 0 until jArrResults.length()) {
        val jObjResult = jArrResults.getJSONObject(i)
        //getting latitude and longitude
        if (jObjResult.has(KEY_GEOMETRY)) {
            val jObjGeometry = jObjResult.getJSONObject(KEY_GEOMETRY)

            if (jObjGeometry.has(KEY_LOCATION)) {
                val jObjLocation = jObjGeometry.getJSONObject(KEY_LOCATION)
                if (jObjLocation.has(KEY_LAT)) {
                    geoCodes[0] = jObjLocation.getDouble(KEY_LAT)
                }

                if (jObjLocation.has(KEY_LNG)) {
                    geoCodes[1] = jObjLocation.getDouble(KEY_LNG)
                }
            }
        }

        var administrativeAreaLevel1: String? = null

        //getting city
        if (jObjResult.has(KEY_ADDRESS_COMPONENTS)) {

            val jArrAddressComponents = jObjResult.getJSONArray(KEY_ADDRESS_COMPONENTS)
            for (i in 0 until jArrAddressComponents.length()) {

                val jObjAddressComponents = jArrAddressComponents.getJSONObject(i)
                if (jObjAddressComponents.has(KEY_TYPES)) {

                    val jArrTypes = jObjAddressComponents.getJSONArray(KEY_TYPES)
                    for (j in 0 until jArrTypes.length()) {

                        when (jArrTypes.getString(j)) {

                            VALUE_LOCALITY, VALUE_POSTAL_TOWN -> {
                                return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
                            }

                            ADMINISTRATIVE_AREA_LEVEL_1 -> {
                                administrativeAreaLevel1 = jObjAddressComponents.getString(KEY_LONG_NAME)
                            }

                            else -> {
                            }
                        }
                    }
                }
            }

            for (i in 0 until jArrAddressComponents.length()) {

                val jObjAddressComponents = jArrAddressComponents.getJSONObject(i)
                if (jObjAddressComponents.has(KEY_TYPES)) {

                    val jArrTypes = jObjAddressComponents.getJSONArray(KEY_TYPES)

                    val typeList = ArrayList<String>()
                    for (j in 0 until jArrTypes.length()) {
                        typeList.add(jArrTypes.getString(j))
                    }

                    if (typeList.contains(VALUE_SUBLOCALITY)) {
                        var hasSubLocalityLevel = false
                        typeList.forEach { type ->
                            if (type.contains(VALUE_SUBLOCALITY_LEVEL)) {
                                hasSubLocalityLevel = true

                                if (type == VALUE_SUBLOCALITY_LEVEL_1) {
                                    return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
                                }
                            }
                        }
                        if (!hasSubLocalityLevel) {
                            return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
                        }
                    }
                }
            }
        }

        if (geoCodes.isNotEmpty()) return GeoLocation(administrativeAreaLevel1, geoCodes = *geoCodes)
     }
   }
return null
}

data class GeoLocation(val latitude: Double = 0.0, val longitude: Double = 0.0, val city: String? = null) : Parcelable {

constructor(city: String? = null, vararg geoCodes: Double) : this(geoCodes[0], geoCodes[1], city)

constructor(source: Parcel) : this(source.readDouble(), source.readDouble(), source.readString())

companion object {
    @JvmField
    val CREATOR = object : Parcelable.Creator<GeoLocation> {

        override fun createFromParcel(source: Parcel) = GeoLocation(source)

        override fun newArray(size: Int): Array<GeoLocation?> = arrayOfNulls(size)
    }
}

override fun writeToParcel(dest: Parcel, flags: Int) {
    dest.writeDouble(latitude)
    dest.writeDouble(longitude)
    dest.writeString(city)
}

override fun describeContents() = 0
}

How can I round a number in JavaScript? .toFixed() returns a string?

You can simply use a '+' to convert the result to a number.

var x = 22.032423;
x = +x.toFixed(2); // x = 22.03

How can I change default dialog button text color in android 5

Kotlin 2020: Very simple method

After dialog.show() use:

dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(requireContext(), R.color.yourColor))

Run an exe from C# code

using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process.Start("C:\\");
    }
}

If your application needs cmd arguments, use something like this:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        LaunchCommandLineApp();
    }

    /// <summary>
    /// Launch the application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
        // For the example
        const string ex1 = "C:\\";
        const string ex2 = "C:\\Dir";

        // Use ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "dcm2jpg.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

        try
        {
            // Start the process with the info we specified.
            // Call WaitForExit and then the using statement will close.
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch
        {
             // Log error.
        }
    }
}

Trying to start a service on boot on Android

How to start service on device boot(autorun app, etc.)

For first: since version Android 3.1+ you don't receive BOOT_COMPLETE if user never started your app at least once or user "force closed" application. This was done to prevent malware automatically register service. This security hole was closed in newer versions of Android.

Solution:

Create app with activity. When user run it once app can receive BOOT_COMPLETE broadcast message.

For second: BOOT_COMPLETE is sent before external storage is mounted. If app is installed to external storage it won't receive BOOT_COMPLETE broadcast message.

In this case there is two solution:

  1. Install your app to internal storage
  2. Install another small app in internal storage. This app receives BOOT_COMPLETE and run second app on external storage.

If your app already installed in internal storage then code below can help you understand how to start service on device boot.


In Manifest.xml

Permission:

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

Register your BOOT_COMPLETED receiver:

<receiver android:name="org.yourapp.OnBoot">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

Register your service:

<service android:name="org.yourapp.YourCoolService" />

In receiver OnBoot.java:

public class OnBoot extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        // Create Intent
        Intent serviceIntent = new Intent(context, YourCoolService.class);
        // Start service
        context.startService(serviceIntent);

    }

 }

For HTC you maybe need also add in Manifest this code if device don't catch RECEIVE_BOOT_COMPLETED:

<action android:name="android.intent.action.QUICKBOOT_POWERON" />

Receiver now look like this:

<receiver android:name="org.yourapp.OnBoot">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    </intent-filter>
</receiver>

How to test BOOT_COMPLETED without restart emulator or real device? It's easy. Try this:

adb -s device-or-emulator-id shell am broadcast -a android.intent.action.BOOT_COMPLETED

How to get device id? Get list of connected devices with id's:

adb devices

adb in ADT by default you can find in:

adt-installation-dir/sdk/platform-tools

Enjoy! )

How to find all positions of the maximum value in a list?

You can also use the numpy package:

import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))

This will return an numpy array of all the indices that contain the max value

if you want to turn this to a list:

maximum_indices_list = maximum_indices.tolist()

Check if a number is int or float

You can use modulo to determine if x is an integer numerically. The isinstance(x, int) method only determines if x is an integer by type:

def isInt(x):
    if x%1 == 0:
        print "X is an integer"
    else:
        print "X is not an integer"

C++ Singleton design pattern

It is indeed probably allocated from the heap, but without the sources there is no way of knowing.

The typical implementation (taken from some code I have in emacs already) would be:

Singleton * Singleton::getInstance() {
    if (!instance) {
        instance = new Singleton();
    };
    return instance;
};

...and rely on the program going out of scope to clean up afterwards.

If you work on a platform where cleanup must be done manually, I'd probably add a manual cleanup routine.

Another issue with doing it this way is that it isn't thread-safe. In a multithreaded environment, two threads could get through the "if" before either has a chance to allocate the new instance (so both would). This still isn't too big of a deal if you are relying on program termination to clean up anyway.

Determine the number of lines within a text file

try {
    string path = args[0];
    FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);
    int i;
    string s = "";
    while ((i = fh.ReadByte()) != -1)
        s = s + (char)i;

    //its for reading number of paragraphs
    int count = 0;
    for (int j = 0; j < s.Length - 1; j++) {
            if (s.Substring(j, 1) == "\n")
                count++;
    }

    Console.WriteLine("The total searches were :" + count);

    fh.Close();

} catch(Exception ex) {
    Console.WriteLine(ex.Message);
}         

How to style the menu items on an Android action bar

I know its an old post, but just in case anyone is looking here. I added this to my style.xml and it worked for me.

<!-- This is the main theme parent -->
<style name="MyTabStyle">
    <item name="android:actionBarTabTextStyle">@style/MyTabTextStyle</item>
</style>

<style name="MyTabTextStyle" parent="@android:style/Widget.ActionBar.TabText">
    <item name="android:textAppearance">@android:style/TextAppearance.Medium</item>
    <item name="android:textSize">14sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@color/pressed_skylogtheme</item>
</style>

repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

In your pom.xml you should add distributionManagement configuration to where to deploy.

In the following example I have used file system as the locations.

<distributionManagement>
       <repository>
         <id>internal.repo</id>
         <name>Internal repo</name>
         <url>file:///home/thara/testesb/in</url>
       </repository>
   </distributionManagement>

you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :

mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in

How to call a method in MainActivity from another class?

You can make this method static.

public static void startChronometer(){
        mChronometer.start();
        showElapsedTime();
    } 

you can call this function in other class as below:

MainActivity.startChronometer();

OR

You can make an object of the main class in second class like,

MainActivity mActivity = new MainActivity();
mActivity.startChronometer();

C++ static virtual members?

Like others have said, there are 2 important pieces of information:

  1. there is no this pointer when making a static function call and
  2. the this pointer points to the structure where the virtual table, or thunk, are used to look up which runtime method to call.

A static function is determined at compile time.

I showed this code example in C++ static members in class; it shows that you can call a static method given a null pointer:

struct Foo
{
    static int boo() { return 2; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo* pFoo = NULL;
    int b = pFoo->boo(); // b will now have the value 2
    return 0;
}

Redirect all output to file using Bash on Linux?

I had trouble with a crashing program *cough PHP cough* Upon crash the shell it was ran in reports the crash reason, Segmentation fault (core dumped)

To avoid this output not getting logged, the command can be run in a subshell that will capture and direct these kind of output:

sh -c 'your_command' > your_stdout.log 2> your_stderr.err
# or
sh -c 'your_command' > your_stdout.log 2>&1

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

Check whether a table contains rows or not sql server 2005

Fast:

SELECT TOP (1) CASE 
        WHEN **NOT_NULL_COLUMN** IS NULL
            THEN 'empty table'
        ELSE 'not empty table'
        END AS info
FROM **TABLE_NAME**

Angular Material: mat-select not selecting default

The solution for me was:

<mat-form-field>
  <mat-select #monedaSelect  formControlName="monedaDebito" [attr.disabled]="isLoading" [placeholder]="monedaLabel | async ">
  <mat-option *ngFor="let moneda of monedasList" [value]="moneda.id">{{moneda.detalle}}</mat-option>
</mat-select>

TS:

@ViewChild('monedaSelect') public monedaSelect: MatSelect;
this.genericService.getOpciones().subscribe(res => {

  this.monedasList = res;
  this.monedaSelect._onChange(res[0].id);


});

Using object: {id: number, detalle: string}

How can I force a hard reload in Chrome for Android

Keyboard shortcuts such as Ctrl+Shift+R work on Android too, you just need a keyboard capable of sending these keys. I used Hacker's Keyboard to send Ctrl+Shift+R, which did a hard reload on my phone.

Where are the recorded macros stored in Notepad++?

Hit F6

Insert::

npp_open $(PLUGINS_CONFIG_DIR)\..\..\shortcuts.xml

Click OK

You now have the file opened in your editor.


Before altering things checkout the related docs:

Replace new lines with a comma delimiter with Notepad++?

This might sound strange but you can remove next line by copying the whole text and pasting it in firefox search bar, and then re-pasting it in notepad++

step 1

step 2

How to remove leading zeros from alphanumeric text?

       String s="0000000000046457657772752256266542=56256010000085100000";      
    String removeString="";

    for(int i =0;i<s.length();i++){
      if(s.charAt(i)=='0')
        removeString=removeString+"0";
      else 
        break;
    }

    System.out.println("original string - "+s);

    System.out.println("after removing 0's -"+s.replaceFirst(removeString,""));

Checking if a field contains a string

Here's what you have to do if you are connecting MongoDB through Python

db.users.find({"username": {'$regex' : '.*' + 'Son' + '.*'}})

you may also use a variable name instead of 'Son' and therefore the string concatenation.

How to use ConfigurationManager

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

How to calculate the median of an array?

Use Arrays.sort and then take the middle element (in case the number n of elements in the array is odd) or take the average of the two middle elements (in case n is even).

  public static long median(long[] l)
  {
    Arrays.sort(l);
    int middle = l.length / 2;
    if (l.length % 2 == 0)
    {
      long left = l[middle - 1];
      long right = l[middle];
      return (left + right) / 2;
    }
    else
    {
      return l[middle];
    }
  }

Here are some examples:

  @Test
  public void evenTest()
  {
    long[] l = {
        5, 6, 1, 3, 2
    };
    Assert.assertEquals((3 + 4) / 2, median(l));
  }

  @Test
  public oddTest()
  {
    long[] l = {
        5, 1, 3, 2, 4
    };
    Assert.assertEquals(3, median(l));
  }

And in case your input is a Collection, you might use Google Guava to do something like this:

public static long median(Collection<Long> numbers)
{
  return median(Longs.toArray(numbers)); // requires import com.google.common.primitives.Longs;
}

Call function with setInterval in jQuery?

jQuery is just a set of helpers/libraries written in Javascript. You can still use all Javascript features, so you can call whatever functions, also from inside jQuery callbacks. So both possibilities should be okay.

Appending output of a Batch file To log file

It's also possible to use java Foo | tee -a some.log. it just prints to stdout as well. Like:

user at Computer in ~
$ echo "hi" | tee -a foo.txt
hi

user at Computer in ~
$ echo "hello" | tee -a foo.txt
hello

user at Computer in ~
$ cat foo.txt
hi
hello

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

Dynamic loading of images in WPF

In code to load resource in the executing assembly where my image 'Freq.png' was in the folder "Icons" and defined as "Resource".

        this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
             + Assembly.GetExecutingAssembly().GetName().Name 
             + ";component/" 
             + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function if anybody would like it...

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage:

        this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

Real/physical iPhone 6 Plus resolution is 1920x1080 but in Xcode you make your interface for 2208x1242 resolution (736x414 points) and on device it is automatically scaled down to 1920x1080 pixels.

iPhone resolutions quick reference:

Device          Points    Pixels     Scale  Physical Pixels   PPI   Ratio   Size
iPhone XS Max   896x414   2688x1242  3x     2688x1242         458   19.5:9  6.5"
iPhone XR       896x414   1792x828   2x     1792x828          326   19.5:9  6.1"
iPhone X        812x375   2436x1125  3x     2436x1125         458   19.5:9  5.8"
iPhone 6 Plus   736x414   2208x1242  3x     1920x1080         401   16:9    5.5"
iPhone 6        667x375   1334x750   2x     1334x750          326   16:9    4.7"
iPhone 5        568x320   1136x640   2x     1136x640          326   16:9    4.0"
iPhone 4        480x320   960x640    2x     960x640           326   3:2     3.5"
iPhone 3GS      480x320   480x320    1x     480x320           163   3:2     3.5"

iPhone resolutions

Using Case/Switch and GetType to determine the object

One approach is to add a pure virtual GetNodeType() method to NodeDTO and override it in the descendants so that each descendant returns actual type.

Checking if an object is a given type in Swift

as? won't always give you the expected result because as doesn't test if a data type is of a specific kind but only if a data type can be converted to or represented as specific kind.

Consider this code for example:

func handleError ( error: Error ) {
    if let nsError = error as? NSError {

Every data type conforming to the Error protocol can be converted to a NSError object, so this will always succeed. Yet that doesn't mean that error is in fact a NSError object or a subclass of it.

A correct type check would be:

func handleError ( error: Error ) {
    if type(of: error) == NSError.self {

However, this checks for the exact type only. If you want to also include subclass of NSError, you should use:

func handleError ( error: Error ) {
    if error is NSError.Type {

How to convert string values from a dictionary, into int/float datatypes?

for sub in the_list:
    for key in sub:
        sub[key] = int(sub[key])

Gives it a casting as an int instead of as a string.

Python Remove last 3 characters of a string

It doesn't work as you expect because strip is character based. You need to do this instead:

foo = foo.replace(' ', '')[:-3].upper()

A general tree implementation?

node = { 'parent':0, 'left':0, 'right':0 }
import copy
root = copy.deepcopy(node)
root['parent'] = -1
left = copy

just to show another thought on implementation if you stick to the "OOP"

class Node:
    def __init__(self,data):
        self.data = data
        self.child = {}
    def append(self, title, child):
        self.child[title] = child

CEO = Node( ('ceo', 1000) )
CTO = ('cto',100)
CFO = ('cfo', 10)
CEO.append('left child', CTO)
CEO.append('right child', CFO)

print CEO.data
print ' ', CEO.child['left child']
print ' ', CEO.child['right child']

Understanding checked vs unchecked exceptions in Java

Checked - Prone to happen. Checked in Compile time.

Eg.. FileOperations

UnChecked - Due to Bad data. Checked in Run time.

Eg..

String s = "abc";
Object o = s;
Integer i = (Integer) o;

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at Sample.main(Sample.java:9)

Here exception is due to bad data and in no way it can be determined during compile time.

Lightweight Javascript DB for use in Node.js

NeDB seems to be what you are looking for. From the blurb:

Embedded persistent database for Node.js, written in Javascript, with no dependency (except npm modules of course). You can think of it as a SQLite for Node.js projects, which can be used with a simple require statement. The API is a subset of MongoDB's. You can use it as a persistent or an in-memory only datastore.

python: after installing anaconda, how to import pandas

  1. Another alternative is to use Pycharm IDE. For each project, you can set the Project Interpreter in Settings.

  2. For example, if anaconda is installed in /home/user/anaconda2/bin/python, you can select the Project Interpreter and set to this folder.

  3. Since the whole project is set to Anaconda's path, you can import any module which is packaged within Anaconda.

How to set max and min value for Y axis

window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx ,{
          type: 'line',
          data: yourData,
          options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true,
                        min: 0,
                        max: 500    
                    }
                  }]
               }
            }
});

I configure with 'options' in v2.

You should read documentation: http://www.chartjs.org/docs/#scales-linear-scale

Close/kill the session when the browser or tab is closed

I do it like this:

$(window).bind('unload', function () {
    if(event.clientY < 0) {  
        alert('Thank you for using this app.');
        endSession(); // here you can do what you want ...
    }  
    });
window.onbeforeunload = function () {
    $(window).unbind('unload');
    //If a string is returned, you automatically ask the 
    //user if he wants to logout or not...
    //return ''; //'beforeunload event'; 
    if (event.clientY < 0) {
        alert('Thank you for using this service.');
        endSession();
    }  
}