Programs & Examples On #Aegis

Aegis is one of the data-binding standards supported by Apache CXF web service framework. tag Aegis can be used for programming related problems of configuring and development of Apache CXF framework.

Handle spring security authentication exceptions with @ExceptionHandler

In case of Spring Boot and @EnableResourceServer, it is relatively easy and convenient to extend ResourceServerConfigurerAdapter instead of WebSecurityConfigurerAdapter in the Java configuration and register a custom AuthenticationEntryPoint by overriding configure(ResourceServerSecurityConfigurer resources) and using resources.authenticationEntryPoint(customAuthEntryPoint()) inside the method.

Something like this:

@Configuration
@EnableResourceServer
public class CommonSecurityConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(customAuthEntryPoint());
    }

    @Bean
    public AuthenticationEntryPoint customAuthEntryPoint(){
        return new AuthFailureHandler();
    }
}

There's also a nice OAuth2AuthenticationEntryPoint that can be extended (since it's not final) and partially re-used while implementing a custom AuthenticationEntryPoint. In particular, it adds "WWW-Authenticate" headers with error-related details.

Hope this will help someone.

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<

Very simple question that you can solved it easily ,

Please follow my step : change < to ( and >; to );

Just use: (

     );

enter code here

` CREATE TABLE information (
-> id INT(11) NOT NULL AUTO_INCREMENT,
-> name VARCHAR(30) NOT NULL,
-> age INT(10) NOT NULL,
-> salary INT(100) NOT NULL,
-> address VARCHAR(100) NOT NULL,
-> PRIMARY KEY(id)
-> );`

String vs. StringBuilder

String concatenation will cost you more. In Java, You can use either StringBuffer or StringBuilder based on your need. If you want a synchronized, and thread safe implementation, go for StringBuffer. This will be faster than the String concatenation.

If you do not need synchronized or Thread safe implementation, go for StringBuilder. This will be faster than String concatenation and also faster than StringBuffer as their is no synchorization overhead.

How to use comparison operators like >, =, < on BigDecimal

This thread has plenty of answers stating that the BigDecimal.compareTo(BigDecimal) method is the one to use to compare BigDecimal instances. I just wanted to add for anymore not experienced with using the BigDecimal.compareTo(BigDecimal) method to be careful with how you are creating your BigDecimal instances. So, for example...

  • new BigDecimal(0.8) will create a BigDecimal instance with a value which is not exactly 0.8 and which has a scale of 50+,
  • new BigDecimal("0.8") will create a BigDecimal instance with a value which is exactly 0.8 and which has a scale of 1

... and the two will be deemed to be unequal according to the BigDecimal.compareTo(BigDecimal) method because their values are unequal when the scale is not limited to a few decimal places.

First of all, be careful to create your BigDecimal instances with the BigDecimal(String val) constructor or the BigDecimal.valueOf(double val) method rather than the BigDecimal(double val) constructor. Secondly, note that you can limit the scale of BigDecimal instances prior to comparing them by means of the BigDecimal.setScale(int newScale, RoundingMode roundingMode) method.

LINQ: Select an object and change some properties without creating a new object

There shouldn't be any LINQ magic keeping you from doing this. Don't use projection though that'll return an anonymous type.

User u = UserCollection.FirstOrDefault(u => u.Id == 1);
u.FirstName = "Bob"

That will modify the real object, as well as:

foreach (User u in UserCollection.Where(u => u.Id > 10)
{
    u.Property = SomeValue;
}

/usr/bin/ld: cannot find

Add -L/opt/lib to your compiler parameters, this makes the compiler and linker search that path for libcalc.so in that folder.

Warning: Found conflicts between different versions of the same dependent assembly

This warning means that two projects reference the same assembly (e.g. System.Windows.Forms) but the two projects require different versions. You have a few options:

  1. Recompile all projects to use the same versions (e.g. move all to .Net 3.5). This is the preferred option because all code is running with the versions of dependencies they were compiled with.

  2. Add a binding redirect. This will suppress the warning. However, your .Net 2.0 projects will (at runtime) be bound to the .Net 3.5 versions of dependent assemblies such as System.Windows.Forms. You can quickly add a binding redirect by double-clicking on error in Visual Studio.

  3. Use CopyLocal=true. I'm not sure if this will suppress the warning. It will, like option 2 above, mean that all projects will use the .Net 3.5 version of System.Windows.Forms.

Here are a couple of ways to identify the offending reference(s):

  • You can use a utility such as the one found at https://gist.github.com/1553265
  • Another simple method is to set Build output verbosity (Tools, Options, Projects and Solutions, Build and Run, MSBuild project build output verbosity, Detailed) and after building, search the output window for the warning, and look at the text just above it. (Hat tip to pauloya who suggested this in the comments on this answer).

How can I create numbered map markers in Google Maps V3?

Unfortunately it's not very easy. You could create your own custom marker based on the OverlayView class (an example) and put your own HTML in it, including a counter. This will leave you with a very basic marker, that you can't drag around or add shadows easily, but it is very customisable.

Alternatively, you could add a label to the default marker. This will be less customisable but should work. It also keeps all the useful things the standard marker does.

You can read more about the overlays in Google's article Fun with MVC Objects.

Edit: if you don't want to create a JavaScript class, you could use Google's Chart API. For example:

Numbered marker:

http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000

Text marker:

http://chart.apis.google.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|foo

This is the quick and easy route, but it's less customisable, and requires a new image to be downloaded by the client for each marker.

Write-back vs Write-Through caching?

Write-Back is a more complex one and requires a complicated Cache Coherence Protocol(MOESI) but it is worth it as it makes the system fast and efficient.

The only benefit of Write-Through is that it makes the implementation extremely simple and no complicated cache coherency protocol is required.

Convert spark DataFrame column to python list

Let's create the dataframe in question

df_test = spark.createDataFrame(
    [
        (1, 5),
        (2, 9),
        (3, 3),
        (4, 1),
    ],
    ['mvv', 'count']
)
df_test.show()

Which gives

+---+-----+
|mvv|count|
+---+-----+
|  1|    5|
|  2|    9|
|  3|    3|
|  4|    1|
+---+-----+

and then apply rdd.flatMap(f).collect() to get the list

test_list = df_test.select("mvv").rdd.flatMap(list).collect()
print(type(test_list))
print(test_list)

which gives

<type 'list'>
[1, 2, 3, 4]

What is Domain Driven Design?

I do not want to repeat others' answers, so, in short I explain some common misunderstanding

  • Practical resource: PATTERNS, PRINCIPLES, AND PRACTICES OF DOMAIN-DRIVEN DESIGN by Scott Millett
  • It is a methodology for complicated business systems. It takes all the technical matters out when communicating with business experts
  • It provides an extensive understanding of (simplified and distilled model of) business across the whole dev team.
  • it keeps business model in sync with code model by using ubiquitous language (the language understood by the whole dev team, business experts, business analysts, ...), which is used for communication within the dev team or dev with other teams
  • It has nothing to do with Project Management. Although it can be perfectly used in project management methods like Agile.
  • You should avoid using it all across your project

    DDD stresses the need to focus the most effort on the core subdomain. The core subdomain is the area of your product that will be the difference between it being a success and it being a failure. It’s the product’s unique selling point, the reason it is being built rather than bought.

    Basically, it is because it takes too much time and effort. So, it is suggested to break down the whole domain into subdomain and just apply it in those with high business value. (ex not in generic subdomain like email, ...)

  • It is not object oriented programming. It is mostly problem solving approach and (sometimes) you do not need to use OO patterns (such as Gang of Four) in your domain models. Simply because it can not be understood by Business Experts (they do not know much about Factory, Decorator, ...). There are even some patterns in DDD (such as The Transaction Script, Table Module) which are not 100% in line with OO concepts.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

Some files where missing at your local repository. Usually under ${user.home}/.m2/repository/

Neets answer solves the problem. However if you dont want do download all the dependencies to your local repository again you could add the missing dependency to a project of yours and compile it.

Use the maven repository website to find the dependency. In your case http://mvnrepository.com/artifact/org.apache.maven.plugins/maven-resources-plugin/2.5 was missing.

Copy the listed XML to the pom.xml file of your project. In this case

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.5</version>
</dependency>

Run mvn compile in the root folder of the pom.xml. Maven will download all missing dependencies. After the download you can remove the added dependency.

Now you should be able to import the maven project or update the project without the error.

How to print a percentage value in python?

format supports a percentage floating point precision type:

>>> print "{0:.0%}".format(1./3)
33%

If you don't want integer division, you can import Python3's division from __future__:

>>> from __future__ import division
>>> 1 / 3
0.3333333333333333

# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%

# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%

Where is web.xml in Eclipse Dynamic Web Project

When you open Eclipse you should click File ? New ? Dynamic Web Project, and make sure you checked Generate web.xml, as described above.

If you have already created the project, you should go to the WebContent/WEB-INF folder, open web.xml, and put the following lines:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>Application Name </display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

jQuery callback for multiple ajax calls

Ok, this is old but please let me contribute my solution :)

function sync( callback ){
    syncCount--;
    if ( syncCount < 1 ) callback();
}
function allFinished(){ .............. }

window.syncCount = 2;

$.ajax({
    url: 'url',
    success: function(data) {
        sync( allFinished );
    }
});
someFunctionWithCallback( function(){ sync( allFinished ); } )

It works also with functions that have a callback. You set the syncCount and you call the function sync(...) in the callback of every action.

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

This command should work if the others did not solve the problem:

sudo asterisk -&

NuGet Packages are missing

Comment out the following code from .csproj

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
  <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Costura.Fody.2.0.1\build\Costura.Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Costura.Fody.2.0.1\build\Costura.Fody.targets'))" />
<Error Condition="!Exists('..\packages\Fody.3.1.3\build\Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Fody.3.1.3\build\Fody.targets'))" />

How to get keyboard input in pygame?

Just fyi, if you're trying to ensure the ship doesn't go off of the screen with

location-=1
if location==-1:
    location=0

you can probably better use

location -= 1
location = max(0, location)

This way if it skips -1 your program doesn't break

HTML Button Close Window

November 2019: onclick="self.close()" still works in Chrome while Edge gives a warning that must be confirmed before it will close.

On the other hand the solution onclick="window.open('', '_self', ''); window.close();" works in both.

Check If array is null or not in php

if array is look like this [null] or [null, null] or [null, null, null, ...]

you can use implode:

implode is use for convert array to string.

if(implode(null,$arr)==null){
     //$arr is empty
}else{
     //$arr has some value rather than null
}

How to make a Java thread wait for another thread's output?

A lot of correct answers but without a simple example.. Here is an easy and simple way how to use CountDownLatch:

//inside your currentThread.. lets call it Thread_Main
//1
final CountDownLatch latch = new CountDownLatch(1);

//2
// launch thread#2
new Thread(new Runnable() {
    @Override
    public void run() {
        //4
        //do your logic here in thread#2

        //then release the lock
        //5
        latch.countDown();
    }
}).start();

try {
    //3 this method will block the thread of latch untill its released later from thread#2
    latch.await();
} catch (InterruptedException e) {
    e.printStackTrace();
}

//6
// You reach here after  latch.countDown() is called from thread#2

VSCode Change Default Terminal

I just type following keywords in the opened terminal;

  1. powershell
  2. bash
  3. cmd
  4. node
  5. python (or python3)

See details in the below image. (VSCode version 1.19.1 - windows 10 OS) enter image description here

It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)

How can I alter a primary key constraint using SQL syntax?

In my case, I want to add a column to a Primary key (column4). I used this script to add column4

ALTER TABLE TableA
DROP CONSTRAINT [PK_TableA]

ALTER TABLE TableA
ADD CONSTRAINT [PK_TableA] PRIMARY KEY (
    [column1] ASC,
    [column2] ASC, 
    [column3] ASC,
    [column4] ASC
)

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

I've deleted mysql.sock file and it worked. Putting the rights on it didn't work at all. Neither restarting, or whatever ...

Python - How to concatenate to a string in a for loop?

That's not how you do it.

>>> ''.join(['first', 'second', 'other'])
'firstsecondother'

is what you want.

If you do it in a for loop, it's going to be inefficient as string "addition"/concatenation doesn't scale well (but of course it's possible):

>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
...    s += item
...
>>> s
'firstsecondother'

How to read a text file into a list or an array with Python

You will have to split your string into a list of values using split()

So,

lines = text_file.read().split(',')

EDIT: I didn't realise there would be so much traction to this. Here's a more idiomatic approach.

import csv
with open('filename.csv', 'r') as fd:
    reader = csv.reader(fd)
    for row in reader:
        # do something

'mvn' is not recognized as an internal or external command,

Add maven directory /bin to System variables under the name Path.

To check this, you can echo %PATH%

How to restore the dump into your running mongodb

For mongoDB database restore use this command here

mongorestore --db databasename --drop dump file path

How to add external library in IntelliJ IDEA?

A better way in long run is to integrate Gradle in your project environment. Its a build tool for Java, and now being used a lot in the android development space.

You will need to make a .gradle file and list your library dependencies. Then, all you would need to do is import the project in IntelliJ using Gradle.

Cheers

how I can show the sum of in a datagridview column?

Fast and clean way using LINQ

int total = dataGridView1.Rows.Cast<DataGridViewRow>()
                .Sum(t => Convert.ToInt32(t.Cells[1].Value));

verified on VS2013

Reading specific XML elements from XML file

Alternatively, you can use XPath query via XPathSelectElements method:

var document = XDocument.Parse(yourXmlAsString);
var words = document.XPathSelectElements("//word[./category[text() = 'verb']]");

How to access array elements in a Django template?

You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

I had the same issue, and the solution is very simple, just change to git bash from cmd or other windows command line tools. Windows sometimes does not work well with git npm dependencies.

How can I account for period (AM/PM) using strftime?

Try replacing %H (Hour on a 24-hour clock) with %I (Hour on a 12-hour clock) ?

How do I scroll to an element within an overflowed Div?

I've adjusted Glenn Moss' answer to account for the fact that overflow div might not be at the top of the page.

parentDiv.scrollTop(parentDiv.scrollTop() + (innerListItem.position().top - parentDiv.position().top) - (parentDiv.height()/2) + (innerListItem.height()/2)  )

I was using this on a google maps application with a responsive template. On resolution > 800px, the list was on the left side of the map. On resolution < 800 the list was below the map.

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

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

Like this:

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

Correct way of using log4net (logger naming)

Instead of naming my invoking class, I started using the following:

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

This worked for me. bundle config --global build.snappy --with-opt-dir="$(brew --prefix snappy)"

Freeze the top row for an html table only (Fixed Table Header Scrolling)

Using css zebra styling

Copy paste this example and see the header fixed.

       <style>
       .zebra tr:nth-child(odd){
       background:white;
       color:black;
       }

       .zebra tr:nth-child(even){
       background: grey;
       color:black;
       }

      .zebra tr:nth-child(1) {
       background:black;
       color:yellow;
       position: fixed;
       margin:-30px 0px 0px 0px;
       }
       </style>


   <DIV  id= "stripped_div"

         class= "zebra"
         style = "
            border:solid 1px red;
            height:15px;
            width:200px;
            overflow-x:none;
            overflow-y:scroll;
            padding:30px 0px 0px 0px;"
            >

                <table>
                   <tr >
                       <td>Name:</td>
                       <td>Age:</td>
                   </tr>
                    <tr >
                       <td>Peter</td>
                       <td>10</td>
                   </tr>
                </table>

    </DIV>

Notice the top padding of of 30px in the div leaves space that is utilized by the 1st row of stripped data ie tr:nth-child(1) that is "fixed position" and formatted to a margin of -30px

How can I change the default Django date template format?

In order to change date format in the views.py and then assign it to template.

# get the object details 
home = Home.objects.get(home_id=homeid)

# get the start date
_startDate = home.home_startdate.strftime('%m/%d/%Y')

# assign it to template 
return render_to_response('showme.html' 
                                        {'home_startdate':_startDate},   
                                         context_instance=RequestContext(request) )  

Alter a SQL server function to accept new optional parameter

The way to keep SELECT dbo.fCalculateEstimateDate(647) call working is:

ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100)  AS
   Declare @Result varchar(100)
   SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
   Return @Result
Begin
End

CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100)  AS
Begin
  <Function Body>
End

Iterator Loop vs index loop

The special thing about iterators is that they provide the glue between algorithms and containers. For generic code, the recommendation would be to use a combination of STL algorithms (e.g. find, sort, remove, copy) etc. that carries out the computation that you have in mind on your data structure (vector, list, map etc.), and to supply that algorithm with iterators into your container.

Your particular example could be written as a combination of the for_each algorithm and the vector container (see option 3) below), but it's only one out of four distinct ways to iterate over a std::vector:

1) index-based iteration

for (std::size_t i = 0; i != v.size(); ++i) {
    // access element as v[i]

    // any code including continue, break, return
}

Advantages: familiar to anyone familiar with C-style code, can loop using different strides (e.g. i += 2).

Disadvantages: only for sequential random access containers (vector, array, deque), doesn't work for list, forward_list or the associative containers. Also the loop control is a little verbose (init, check, increment). People need to be aware of the 0-based indexing in C++.

2) iterator-based iteration

for (auto it = v.begin(); it != v.end(); ++it) {
    // if the current index is needed:
    auto i = std::distance(v.begin(), it); 

    // access element as *it

    // any code including continue, break, return
}

Advantages: more generic, works for all containers (even the new unordered associative containers, can also use different strides (e.g. std::advance(it, 2));

Disadvantages: need extra work to get the index of the current element (could be O(N) for list or forward_list). Again, the loop control is a little verbose (init, check, increment).

3) STL for_each algorithm + lambda

std::for_each(v.begin(), v.end(), [](T const& elem) {
     // if the current index is needed:
     auto i = &elem - &v[0];

     // cannot continue, break or return out of the loop
});

Advantages: same as 2) plus small reduction in loop control (no check and increment), this can greatly reduce your bug rate (wrong init, check or increment, off-by-one errors).

Disadvantages: same as explicit iterator-loop plus restricted possibilities for flow control in the loop (cannot use continue, break or return) and no option for different strides (unless you use an iterator adapter that overloads operator++).

4) range-for loop

for (auto& elem: v) {
     // if the current index is needed:
     auto i = &elem - &v[0];

    // any code including continue, break, return
}

Advantages: very compact loop control, direct access to the current element.

Disadvantages: extra statement to get the index. Cannot use different strides.

What to use?

For your particular example of iterating over std::vector: if you really need the index (e.g. access the previous or next element, printing/logging the index inside the loop etc.) or you need a stride different than 1, then I would go for the explicitly indexed-loop, otherwise I'd go for the range-for loop.

For generic algorithms on generic containers I'd go for the explicit iterator loop unless the code contained no flow control inside the loop and needed stride 1, in which case I'd go for the STL for_each + a lambda.

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

Rails: How can I rename a database column in a Ruby on Rails migration?

Generate the migration file:

rails g migration FixName

# Creates db/migrate/xxxxxxxxxx.rb

Edit the migration to do your will.

class FixName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

How to compare only date components from DateTime in EF?

you can use DbFunctions.TruncateTime() method for this.

e => DbFunctions.TruncateTime(e.FirstDate.Value) == DbFunctions.TruncateTime(SecondDate);

How to convert php array to utf8?

There is an easy way

array_walk_recursive(
  $array,
  function (&$entry) {
    $entry = mb_convert_encoding(
        $entry,
        'UTF-8'
    );
  }
);

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

How do I show running processes in Oracle DB?

This one shows SQL that is currently "ACTIVE":-

select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/

This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:

select
  object_name, 
  object_type, 
  session_id, 
  type,         -- Type or system/user lock
  lmode,        -- lock mode in which session holds lock
  request, 
  block, 
  ctime         -- Time since current mode was granted
from
  v$locked_object, all_objects, v$lock
where
  v$locked_object.object_id = all_objects.object_id AND
  v$lock.id1 = all_objects.object_id AND
  v$lock.sid = v$locked_object.session_id
order by
  session_id, ctime desc, object_name
/

This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.

COLUMN percent FORMAT 999.99 

SELECT sid, to_char(start_time,'hh24:mi:ss') stime, 
message,( sofar/totalwork)* 100 percent 
FROM v$session_longops
WHERE sofar/totalwork < 1
/

Is it possible to create a File object from InputStream

Since Java 7, you can do it in one line even without using any external libraries:

Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

See the API docs.

How can I implement prepend and append with regular JavaScript?

If you want to insert a raw HTML string no matter how complex, you can use: insertAdjacentHTML, with appropriate first argument:

'beforebegin' Before the element itself. 'afterbegin' Just inside the element, before its first child. 'beforeend' Just inside the element, after its last child. 'afterend' After the element itself.

Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.

An example of usage:

document.getElementById("foo").insertAdjacentHTML("beforeBegin",
          "<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");

DEMO

Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.

Why Git is not allowing me to commit even after configuration?

You're setting the global git options, but the local checkout possibly has overrides set. Try setting them again with git config --local <setting> <value>. You can look at the .git/config file in your local checkout to see what local settings the checkout has defined.

Get index of a row of a pandas dataframe as an integer

The nature of wanting to include the row where A == 5 and all rows upto but not including the row where A == 8 means we will end up using iloc (loc includes both ends of slice).

In order to get the index labels we use idxmax. This will return the first position of the maximum value. I run this on a boolean series where A == 5 (then when A == 8) which returns the index value of when A == 5 first happens (same thing for A == 8).

Then I use searchsorted to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc.

i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]

enter image description here


numpy

you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.

def find_between(df, col, v1, v2):
    vals = df[col].values
    mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
    idx = df.index.values
    i1, i2 = idx.searchsorted([mx1, mx2])
    return df.iloc[i1:i2]

find_between(df, 'A', 5, 8)

enter image description here


timing
enter image description here

What regex will match every character except comma ',' or semi-colon ';'?

Use character classes. A character class beginning with caret will match anything not in the class.

[^,;]

How can I create an array/list of dictionaries in python?

I assume that motifWidth contains an integer.

In Python, lists do not change size unless you tell them to. Hence, Python throws an exception when you try to change an element that isn't there. I believe you want:

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})

For what it's worth, when asking questions in the future, it would help if you included the stack trace showing the error that you're getting rather than just saying "it isn't working". That would help us directly figure out the cause of the problem, rather than trying to puzzle it out from your code.

Hope that helps!

Python dictionary replace values

I think this may help you solve your issue.

Imagine you have a dictionary like this:

dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}

And you want to change values by this one:

dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}

You can use code bellow to change values of dic0 properly respected to dic0t01 without worrying yourself about indexes in dictionary:

for x, y in dic0.items():
    dic0[x] = dic0to1[y]

Now you have:

>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}

How do I call a JavaScript function on page load?

function yourfunction() { /* do stuff on page load */ }

window.onload = yourfunction;

Or with jQuery if you want:

$(function(){
   yourfunction();
});

If you want to call more than one function on page load, take a look at this article for more information:

How to remove &quot; from my Json in javascript?

Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from

result.replace(/&quot;/g,'"')

to

result.replace(/&#34;/g,'"')

Instead of this I use that:

result.replace(/(&quot\;)/g,"\"")

By this notation it works.

How to wrap text using CSS?

The better option if you cannot control user input, it is to establish the css property, overflow:hidden, so if the string is superior to the width, it will not deform the design.

Edited:

I like the answer: "word-wrap: break-word", and for those browsers that do not support it, for example, IE6 or IE7, I would use my solution.

Python write line by line to a text file

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

How to convert a string with comma-delimited items to a list in Python?

Just to add on to the existing answers: hopefully, you'll encounter something more like this in the future:

>>> word = 'abc'
>>> L = list(word)
>>> L
['a', 'b', 'c']
>>> ''.join(L)
'abc'

But what you're dealing with right now, go with @Cameron's answer.

>>> word = 'a,b,c'
>>> L = word.split(',')
>>> L
['a', 'b', 'c']
>>> ','.join(L)
'a,b,c'

Angular 2 http post params and body

Seems like you use Angular 4.3 version, I also faced with same problem. Use Angular 4.0.1 and post with code by @trichetricheand and it will work. I am also not sure how to solve it on Angular 4.3 :S

Selenium WebDriver How to Resolve Stale Element Reference Exception?

This worked for me (source here):

 /**
     * Attempts to click on an element multiple times (to avoid stale element
     * exceptions caused by rapid DOM refreshes)
     *
     * @param d
     *            The WebDriver
     * @param by
     *            By element locator
     */
    public static void dependableClick(WebDriver d, By by)
    {
        final int MAXIMUM_WAIT_TIME = 10;
        final int MAX_STALE_ELEMENT_RETRIES = 5;

        WebDriverWait wait = new WebDriverWait(d, MAXIMUM_WAIT_TIME);
        int retries = 0;
        while (true)
        {
            try
            {
                wait.until(ExpectedConditions.elementToBeClickable(by)).click();

                return;
            }
            catch (StaleElementReferenceException e)
            {
                if (retries < MAX_STALE_ELEMENT_RETRIES)
                {
                    retries++;
                    continue;
                }
                else
                {
                    throw e;
                }
            }
        }
    }

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

function timeago(date) {
    var seconds = Math.floor((new Date() - date) / 1000);
    if(Math.round(seconds/(60*60*24*365.25)) >= 2) return Math.round(seconds/(60*60*24*365.25)) + " years ago";
    else if(Math.round(seconds/(60*60*24*365.25)) >= 1) return "1 year ago";
    else if(Math.round(seconds/(60*60*24*30.4)) >= 2) return Math.round(seconds/(60*60*24*30.4)) + " months ago";
    else if(Math.round(seconds/(60*60*24*30.4)) >= 1) return "1 month ago";
    else if(Math.round(seconds/(60*60*24*7)) >= 2) return Math.round(seconds/(60*60*24*7)) + " weeks ago";
    else if(Math.round(seconds/(60*60*24*7)) >= 1) return "1 week ago";
    else if(Math.round(seconds/(60*60*24)) >= 2) return Math.round(seconds/(60*60*24)) + " days ago";
    else if(Math.round(seconds/(60*60*24)) >= 1) return "1 day ago";
    else if(Math.round(seconds/(60*60)) >= 2) return Math.round(seconds/(60*60)) + " hours ago";
    else if(Math.round(seconds/(60*60)) >= 1) return "1 hour ago";
    else if(Math.round(seconds/60) >= 2) return Math.round(seconds/60) + " minutes ago";
    else if(Math.round(seconds/60) >= 1) return "1 minute ago";
    else if(seconds >= 2)return seconds + " seconds ago";
    else return seconds + "1 second ago";
}

How to upgrade safely php version in wamp server

One important step is missing in all answers. I successfully upgraded with following steps:

  • stop apache service with wamp stack manager.
  • rename your wampstack/php dir to wampstack/php_old
  • copy new php dir to wampstack/
  • replace wampstack/php/php.ini by wampstack/php_old/php.ini
  • test and fix any error with php -v (for example missing extensions)
  • [optional] update php version in wampstack/properties.ini
  • Replace wampstack/apache/bin/php7ts.dll by wampstack/php/php7ts.dll
    • This is not mentioned in the other answers but you need this to use the right php version in apache!
  • start apache service

Converting dictionary to JSON

json.dumps() returns the JSON string representation of the python dict. See the docs

You can't do r['rating'] because r is a string, not a dict anymore

Perhaps you meant something like

r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))

How do I use a pipe to redirect the output of one command to the input of another?

This should work:

for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i

If running in a batch file, you need to use %%i instead of just %i (in both places).

How to fix the "508 Resource Limit is reached" error in WordPress?

I've already encountered this error and this is the best solution I've found:

In your root folder (probably called public_html)please add this code to your .htaccess file...

REPLACE the 00.00.00.000 with YOUR IP address. If you don't know your IP address buzz over to What Is My IP - The IP Address Experts Since 1999

#By Marky WP Root Directory to deny entry for WP-Login & xmlrpc
<Files wp-login.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>
<Files xmlrpc.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

In your wp-admin folder please add this code to your .htaccess file...

#By Marky WP Admin Folder to deny entry for entire admin folder
order deny,allow
deny from all
allow from 00.00.00.000
<Files index.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

From: https://www.quora.com/I-am-using-shared-hosting-and-my-I-O-usage-is-full-after-every-minute-What-is-this-I-O-usage-in-cPanel-How-can-I-reduce-it

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

This will be solve your problem:

if(!$scope.$$phase) {
  //TODO
}

Split a vector into chunks

I need a function that takes the argument of a data.table (in quotes) and another argument that is the upper limit on the number of rows in the subsets of that original data.table. This function produces whatever number of data.tables that upper limit allows for:

library(data.table)    
split_dt <- function(x,y) 
    {
    for(i in seq(from=1,to=nrow(get(x)),by=y)) 
        {df_ <<- get(x)[i:(i + y)];
            assign(paste0("df_",i),df_,inherits=TRUE)}
    rm(df_,inherits=TRUE)
    }

This function gives me a series of data.tables named df_[number] with the starting row from the original data.table in the name. The last data.table can be short and filled with NAs so you have to subset that back to whatever data is left. This type of function is useful because certain GIS software have limits on how many address pins you can import, for example. So slicing up data.tables into smaller chunks may not be recommended, but it may not be avoidable.

Measuring text height to be drawn on Canvas ( Android )

If anyone still has problem, this is my code.

I have a custom view which is square (width = height) and I want to assign a character to it. onDraw() shows how to get height of character, although I'm not using it. Character will be displayed in the middle of view.

public class SideBarPointer extends View {

    private static final String TAG = "SideBarPointer";

    private Context context;
    private String label = "";
    private int width;
    private int height;

    public SideBarPointer(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    private void init() {
//        setBackgroundColor(0x64FF0000);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        height = this.getMeasuredHeight();
        width = this.getMeasuredWidth();

        setMeasuredDimension(width, width);
    }

    protected void onDraw(Canvas canvas) {
        float mDensity = context.getResources().getDisplayMetrics().density;
        float mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;

        Paint previewPaint = new Paint();
        previewPaint.setColor(0x0C2727);
        previewPaint.setAlpha(200);
        previewPaint.setAntiAlias(true);

        Paint previewTextPaint = new Paint();
        previewTextPaint.setColor(Color.WHITE);
        previewTextPaint.setAntiAlias(true);
        previewTextPaint.setTextSize(90 * mScaledDensity);
        previewTextPaint.setShadowLayer(5, 1, 2, Color.argb(255, 87, 87, 87));

        float previewTextWidth = previewTextPaint.measureText(label);
//        float previewTextHeight = previewTextPaint.descent() - previewTextPaint.ascent();
        RectF previewRect = new RectF(0, 0, width, width);

        canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
        canvas.drawText(label, (width - previewTextWidth)/2, previewRect.top - previewTextPaint.ascent(), previewTextPaint);

        super.onDraw(canvas);
    }

    public void setLabel(String label) {
        this.label = label;
        Log.e(TAG, "Label: " + label);

        this.invalidate();
    }
}

Convert string into Date type on Python

Use datetime.datetime.strptime:

>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-10', '%Y-%m-%d')
>>> date.isoweekday()
5

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

Returning anonymous type in C#

Another option could be using automapper: You will be converting to any type from your anonymous returned object as long public properties matches. The key points are, returning object, use linq and autommaper. (or use similar idea returning serialized json, etc. or use reflection..)

using System.Linq;
using System.Reflection;
using AutoMapper;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var data = GetData();

            var firts = data.First();

            var info = firts.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).First(p => p.Name == "Name");
            var value = info.GetValue(firts);

            Assert.AreEqual(value, "One");
        }


        [TestMethod]
        public void TestMethod2()
        {
            var data = GetData();

            var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
            var mapper = config.CreateMapper();

            var users = data.Select(mapper.Map<User>).ToArray();

            var firts = users.First();

            Assert.AreEqual(firts.Name, "One");

        }

        [TestMethod]
        public void TestMethod3()
        {
            var data = GetJData();


            var users = JsonConvert.DeserializeObject<User[]>(data);

            var firts = users.First();

            Assert.AreEqual(firts.Name, "One");

        }

        private object[] GetData()
        {

            return new[] { new { Id = 1, Name = "One" }, new { Id = 2, Name = "Two" } };
        }

        private string GetJData()
        {

            return JsonConvert.SerializeObject(new []{ new { Id = 1, Name = "One" }, new { Id = 2, Name = "Two" } }, Formatting.None);
        }

        public class User
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    }

}

MSIE and addEventListener Problem in Javascript?

In IE you have to use attachEvent rather than the standard addEventListener.

A common practice is to check if the addEventListener method is available and use it, otherwise use attachEvent:

if (el.addEventListener){
  el.addEventListener('click', modifyText, false); 
} else if (el.attachEvent){
  el.attachEvent('onclick', modifyText);
}

You can make a function to do it:

function bindEvent(el, eventName, eventHandler) {
  if (el.addEventListener){
    el.addEventListener(eventName, eventHandler, false); 
  } else if (el.attachEvent){
    el.attachEvent('on'+eventName, eventHandler);
  }
}
// ...
bindEvent(document.getElementById('myElement'), 'click', function () {
  alert('element clicked');
});

You can run an example of the above code here.

The third argument of addEventListener is useCapture; if true, it indicates that the user wishes to initiate event capturing.

Find a value in an array of objects in Javascript

Considering you have following snippet:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

You can use the following function to search for items

const search = what => array.find(element => element.name === what);

And you can check whether the item was found or not.

if (search("string 1")) {
    console.log(search.value, search.other);
} else {
    console.log('No result found');
}

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

How to write header row with csv.DictWriter?

Another way to do this would be to add before adding lines in your output, the following line :

output.writerow(dict(zip(dr.fieldnames, dr.fieldnames)))

The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.

How can I see what has changed in a file before committing to git?

For me git add -p is the most useful way (and intended I think by git developers?) to review all unstaged changes (it shows the diff for each file), choose a good set of changes that ought to go with a commit, then when you have staged all of those, then use git commit, and repeat for the next commit. Then you can make each commit be a useful or meaningful set of changes even if they took place in various files. I would also suggest creating a new branch for each ticket or similar activity, and switch between them using checkout (perhaps using git stash if you don't want to commit before switching), though if you are doing many quick changes this may be a pain. Don't forget to merge often.

Query to check index on a table

Simply you can find index name and column names of a particular table using below command

SP_HELPINDEX 'tablename'

It work's for me

Spring JSON request getting 406 (not Acceptable)

There is another case where this status will be returned: if the Jackson mapper cannot figure out how to serialize your bean. For example, if you have two accessor methods for the same boolean property, isFoo() and getFoo().

What's happening is that Spring's MappingJackson2HttpMessageConverter calls Jackson's StdSerializerProvider to see if it can convert your object. At the bottom of the call chain, StdSerializerProvider._createAndCacheUntypedSerializer throws a JsonMappingException with an informative message. However, this exception is swallowed by StdSerializerProvider._createAndCacheUntypedSerializer, which tells Spring that it can't convert the object. Having run out of converters, Spring reports that it's not being given an Accept header that it can use, which of course is bogus when you're giving it */*.

There is a bug for this behavior, but it was closed as "cannot reproduce": the method that's being called doesn't declare that it can throw, so swallowing exceptions is apparently an appropriate solution (yes, that was sarcasm). Unfortunately, Jackson doesn't have any logging ... and there are a lot of comments in the codebase wishing it did, so I suspect this isn't the only hidden gotcha.

PostgreSQL JOIN data from 3 tables

Maybe the following is what you are looking for:

SELECT name, pathfilename
  FROM table1
  NATURAL JOIN table2
  NATURAL JOIN table3
  WHERE name = 'John';

How do I pass a variable to the layout using Laravel' Blade templating?

$data['title'] = $this->layout->title = 'The Home Page';
$this->layout->content = View::make('home', $data);

I've done this so far because I needed in both the view and master file. It seems if you don't use $this->layout->title it won't be available in the master layout. Improvements welcome!

How to install a python library manually

I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.

In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so extension), and add that directory to your PYTHONPATH environmental variable e.g., add

export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH

or similar line in your shell configuration file.

A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local. Assuming QuickFix knows to put the Python files in the appropriate site-packages, when you do make install, it should install the files to ~/.local/lib/pythonX.Y/site-packages, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.

If, on the other hand, it did provide a setup.py file, simply run

python setup.py install --user

for Python 2.6+.

How to sum up an array of integers in C#

It depends on how you define better. If you want the code to look cleaner, you can use .Sum() as mentioned in other answers. If you want the operation to run quickly and you have a large array, you can make it parallel by breaking it into sub sums and then sum the results.

How to view log output using docker-compose run?

If you want to see output logs from all the services in your terminal.

docker-compose logs -t -f --tail <no of lines> 

Eg.: Say you would like to log output of last 5 lines from all service

docker-compose logs -t -f --tail 5

If you wish to log output from specific services then it can be done as below:

docker-compose logs -t -f --tail <no of lines> <name-of-service1> <name-of-service2> ... <name-of-service N>

Usage:

Eg. say you have API and portal services then you can do something like below :

docker-compose logs -t -f --tail 5 portal api

Where 5 represents last 5 lines from both logs.

Ref: https://docs.docker.com/v17.09/engine/admin/logging/view_container_logs/

Adding script tag to React/JSX

You can use npm postscribe to load script in react component

postscribe('#mydiv', '<script src="https://use.typekit.net/foobar.js"></script>')

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).

If you cannot find it this way, try the menu: View/Properties Window.

Or try the F4 key.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

Go to Start and search for cmd. Right click on it, properties then set the Target path in quotes. This worked fine for me.

How to pass a URI to an intent?

The Uri.parse(extras.getString("imageUri")) was causing an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.putExtra(java.lang.String, android.os.Parcelable)' on a null object reference 

So I changed to the following:

intent.putExtra("imageUri", imageUri)

and

Uri uri = (Uri) getIntent().get("imageUri");

This solved the problem.

How to set a transparent background of JPanel?

As Thrasgod correctly showed in his answer, the best way is to use the paintComponent, but also if the case is to have a semi transparent JPanel (or any other component, really) and have something not transparent inside. You have to also override the paintChildren method and set the alfa value to 1. In my case I extended the JPanel like that:

public class TransparentJPanel extends JPanel {

private float panelAlfa;
private float childrenAlfa;

public TransparentJPanel(float panelAlfa, float childrenAlfa) {
    this.panelAlfa = panelAlfa;
    this.childrenAlfa = childrenAlfa;
}

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(getBackground());
    g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, panelAlfa));
    super.paintComponent(g2d);

}

@Override
protected void paintChildren(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(getBackground());
    g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_ATOP, childrenAlfa));
  
    super.paintChildren(g); 
}
 //getter and setter
}

And in my project I only need to instantiate Jpanel jp = new TransparentJPanel(0.3f, 1.0f);, if I want only the Jpanel transparent. You could, also, mess with the JPanel shape using g2d.fillRoundRect and g2d.drawRoundRect, but it's not in the scope of this question.

Extracting Nupkg files using command line

You can also use the NuGet command line, by specifying a local host as part of an install. For example if your package is stored in the current directory

nuget install MyPackage -Source %cd% -OutputDirectory packages

will unpack it into the target directory.

What are the differences among grep, awk & sed?

Grep is useful if you want to quickly search for lines that match in a file. It can also return some other simple information like matching line numbers, match count, and file name lists.

Awk is an entire programming language built around reading CSV-style files, processing the records, and optionally printing out a result data set. It can do many things but it is not the easiest tool to use for simple tasks.

Sed is useful when you want to make changes to a file based on regular expressions. It allows you to easily match parts of lines, make modifications, and print out results. It's less expressive than awk but that lends it to somewhat easier use for simple tasks. It has many more complicated operators you can use (I think it's even turing complete), but in general you won't use those features.

Select the first row by group

What about

DT <- data.table(test)
setkey(DT, id)

DT[J(unique(id)), mult = "first"]

Edit

There is also a unique method for data.tables which will return the the first row by key

jdtu <- function() unique(DT)

I think, if you are ordering test outside the benchmark, then you can removing the setkey and data.table conversion from the benchmark as well (as the setkey basically sorts by id, the same as order).

set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]
DT <- data.table(DT, key = 'id')
ju <- function() test[!duplicated(test$id),]

jdt <- function() DT[J(unique(id)),mult = 'first']


 library(rbenchmark)
benchmark(ju(), jdt(), replications = 5)
##    test replications elapsed relative user.self sys.self 
## 2 jdt()            5    0.01        1      0.02        0        
## 1  ju()            5    0.05        5      0.05        0         

and with more data

** Edit with unique method**

set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
DT <- data.table(test, key = 'id')
       test replications elapsed relative user.self sys.self 
2  jdt()            5    0.09     2.25      0.09     0.00    
3 jdtu()            5    0.04     1.00      0.05     0.00      
1   ju()            5    0.22     5.50      0.19     0.03        

The unique method is fastest here.

How do I block comment in Jupyter notebook?

I have not yet managed to find the best way possible. Since I am using a keyboard with Finnish layout, some of the answers do not work for me (e.g. user5036413's answer).

However, in the meantime, I have come up with a solution that at least helps me not to comment each and every line one by one. I am using Chrome browser in MS Windows and I have not checked other possibilities though.

The solution:
It uses the fact that you can have multiple line cursors in an Ipython Notebook.

Press the Alt button and keep holding it. The cursor should change its shape into a big plus sign. The next step is, using your mouse, to point to the beginning of the first line you want to comment and while holding the Alt button pull down your mouse until the last line you want to comment. Finally, you can release the Alt button and then use the # character to comment. Voila! You have now commented multiple lines.

Escape a string for a sed replace pattern

The only three literal characters which are treated specially in the replace clause are / (to close the clause), \ (to escape characters, backreference, &c.), and & (to include the match in the replacement). Therefore, all you need to do is escape those three characters:

sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"

Example:

$ export REPLACE="'\"|\\/><&!"
$ echo fooKEYWORDbar | sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"
foo'"|\/><&!bar

How to apply `git diff` patch without Git installed?

git diff > patchfile

and

patch -p1 < patchfile

work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile if you need handle file adds, deletes and renames.


EDIT December 2015

Latest versions of patch command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).

So provided one uses current/latest version of patch there is no need to use git to be able to apply its diff as a patch.

PHP: How do I display the contents of a textfile on my page?

Here, try this (assuming it's a small file!):

<?php
echo file_get_contents( "filename.php" ); // get the contents, and echo it out.
?>

Documentation is here.

How to read a file in reverse order?

I don't think this has been mentioned before, but using deque from collections and reverse works for me:

from collections import deque

fs = open("test.txt","rU")
fr = deque(fs)
fr.reverse()  # reverse in-place, returns None

for li in fr:
   print li

fs.close()

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I had the same problem but I solved in other way (becouse at right click on project folder no Maven tab apears only if I do that on pom.xml I can see a Maven tab):

So I tink that you get that error because the IDE (Eclipse) didn`t import the dependecies from Maven. Since you are using Spring framework and you probably have STS allready installed right-click on project folder Spring Tools -> Update Maven Dependecies.

I`m using Eclipse JUNO m2eclipse 1.3.0 Spring IDEE 3.1

File upload along with other object in Jersey restful web service

I used file upload example from,

http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/

in my resource class i have below method

@POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response  attachupload(@FormDataParam("file") byte[] is,
@FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("fileName") String flename){
attachService.saveAttachment(flename,is);
}

in my attachService.java i have below method

 public void saveAttachment(String flename,  byte[] is) {
            // TODO Auto-generated method stub
         attachmentDao.saveAttachment(flename,is);

        }

in Dao i have

attach.setData(is);
attach.setFileName(flename);

in my HBM mapping is like

<property name="data" type="binary" >
            <column name="data" />
</property>

This working for all type of files like .PDF,.TXT, .PNG etc.,

Create Hyperlink in Slack

In addition to the ?ShiftU/CtrlShiftU solution, you can also add a link quickly by doing the following:

  1. Copy a URL to the clipboard
  2. Select the text in a slack message you are writing that you want to be a link
  3. Press ?V on Mac or CtrlV

I couldn't find it documented anywhere, but it works, and seems very handy.

Unicode character for "X" cancel / close?

&times; is better than &#10006; as &#10006; behaves strangely in Edge and Internet explorer (tested in IE11). It doesn't get the right color and is replaced by an "emoji"

Do you need to dispose of objects and set them to null?

I have to answer, too. The JIT generates tables together with the code from it's static analysis of variable usage. Those table entries are the "GC-Roots" in the current stack frame. As the instruction pointer advances, those table entries become invalid and so ready for garbage collection. Therefore: If it is a scoped variable, you don't need to set it to null - the GC will collect the object. If it is a member or a static variable, you have to set it to null

javascript - pass selected value from popup window to parent window input box

From your code

<input type=button value="Select" onClick="sendValue(this.form.details);"

Im not sure that your this.form.details valid or not.

IF it's valid, have a look in window.opener.document.getElementById('details').value = selvalue;

I can't found an input's id contain details I'm just found only id=sku1 (recommend you to add " like id="sku1").

And from your id it's hardcode. Let's see how to do with dynamic when a child has callback to update some textbox on the parent Take a look at here.

First page.

<html>
<head>
<script>
    function callFromDialog(id,data){ //for callback from the dialog
        document.getElementById(id).value = data;
        // do some thing other if you want
    }

    function choose(id){
        var URL = "secondPage.html?id=" + id + "&dummy=avoid#";
        window.open(URL,"mywindow","menubar=1,resizable=1,width=350,height=250")
    }
</script>
</head>
<body>
<input id="tbFirst" type="text" /> <button onclick="choose('tbFirst')">choose</button>
<input id="tbSecond" type="text" /> <button onclick="choose('tbSecond')">choose</button>
</body>
</html>

Look in function choose I'm sent an id of textbox to the popup window (don't forget to add dummy data at last of URL param like &dummy=avoid#)

Popup Page

<html>
<head>
<script>
    function goSelect(data){
        var idFromCallPage = getUrlVars()["id"];
        window.opener.callFromDialog(idFromCallPage,data); //or use //window.opener.document.getElementById(idFromCallPage).value = data;
        window.close();
    }


    function getUrlVars(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
</script>
</head>
<body>
<a href="#" onclick="goSelect('Car')">Car</a> <br />
<a href="#" onclick="goSelect('Food')">Food</a> <br />
</body>
</html>

I have add function getUrlVars for get URL param that the parent has pass to child.

Okay, when select data in the popup, for this case it's will call function goSelect

In that function will get URL param to sent back.

And when you need to sent back to the parent just use window.opener and the name of function like window.opener.callFromDialog

By fully is window.opener.callFromDialog(idFromCallPage,data);

Or if you want to use window.opener.document.getElementById(idFromCallPage).value = data; It's ok too.

Intellij reformat on file save

If it's about Prettier, just use a File Watcher :

references => Tools => File Watchers => click + to add a new watcher => Prettier

https://prettier.io/docs/en/webstorm.html#running-prettier-on-save-using-file-watcher

git - pulling from specific branch

Here are the steps to pull a specific or any branch,

1.clone the master(you need to provide username and password)

       git clone <url>

2. the above command will clone the repository and you will be master branch now

       git checkout <branch which is present in the remote repository(origin)>

3. The above command will checkout to the branch you want to pull and will be set to automatically track that branch

4.If for some reason it does not work like that, after checking out to that branch in your local system, just run the below command

       git pull origin <branch>

Force HTML5 youtube video

Inline tag is used to add another src of document to the current html element.

In your case an video of a youtube and we need to specify the html type(4 or 5) to the browser externally to the link

so add ?html=5 to the end of the link.. :)

Right align text in android TextView

Below works for me:

<TextView
    android:id="@+id/tv_username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sarah" />

<TextView
    android:id="@+id/tv_distance"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/tv_username"
    android:layout_alignParentEnd="true"
    android:layout_toEndOf="@+id/tv_username"
    android:text="San Marco"
    android:textAlignment="viewEnd" />

Please note the android:layout_alignParentEnd and android:textAlignment settings of the second TextView.

How to disable submit button once it has been clicked?

Another solution i´ve used is to move the button instead of disabling it. In that case you don´t have those "disable" problems. Finally what you really want is people not to press twice, if the button is not there they can´t do it.

You may also replace it with another button.

while-else-loop

Am I missing something?

Doesn't this hypothetical code

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
} else {
    dataColLinker.set(rowIndex, value);
}

mean the same thing as this?

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
}
dataColLinker.set(rowIndex, value);

or this?

if (rowIndex >= dataColLinker.size()) {
    do {
        dataColLinker.add(value);
    } while(rowIndex >= dataColLinker.size());
} else {
    dataColLinker.set(rowIndex, value);
}

(The latter makes more sense ... I guess). Either way, it is obvious that you can rewrite the loop so that the "else test" is not repeated inside the loop ... as I have just done.


FWIW, this is most likely a case of premature optimization. That is, you are probably wasting your time optimizing code that doesn't need to be optimized:

  • For all you know, the JIT compiler's optimizer may have already moved the code around so that the "else" part is no longer in the loop.

  • Even if it hasn't, the chances are that the particular thing you are trying to optimize is not a significant bottleneck ... even if it might be executed 600,000 times.

My advice is to forget this problem for now. Get the program working. When it is working, decide if it runs fast enough. If it doesn't then profile it, and use the profiler output to decide where it is worth spending your time optimizing.

Two Decimal places using c#

Your question is asking to display two decimal places. Using the following String.format will help:

String.Format("{0:.##}", Debitvalue)

this will display then number with up to two decimal places(e.g. 2.10 would be shown as 2.1 ).

Use "{0:.00}", if you want always show two decimal places(e.g. 2.10 would be shown as 2.10 )

Or if you want the currency symbol displayed use the following:

String.Format("{0:C}", Debitvalue)

Insert current date/time using now() in a field using MySQL/PHP

Like Pekka said, it should work this way. I can't reproduce the problem with this self-contained example:

<?php
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $pdo->exec('
        CREATE TEMPORARY TABLE soFoo (
            id int auto_increment,
            first int,
            last int,
            whenadded DATETIME,
            primary key(id)
        )
    ');
    $pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,1,Now())');
    $pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,2,Now())');
    $pdo->exec('INSERT INTO soFoo (first,last,whenadded) VALUES (0,3,Now())');

    foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $row ) {
        echo join(' | ', $row), "\n";
    }

Which (currently) prints

1 | 0 | 1 | 2012-03-23 16:00:18
2 | 0 | 2 | 2012-03-23 16:00:18
3 | 0 | 3 | 2012-03-23 16:00:18

And here's (almost) the same script using a TIMESTAMP field and DEFAULT CURRENT_TIMESTAMP:

<?php
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $pdo->exec('
        CREATE TEMPORARY TABLE soFoo (
            id int auto_increment,
            first int,
            last int,
            whenadded TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            primary key(id)
        )
    ');
    $pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,1)');
    $pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,2)');
    sleep(1);
    $pdo->exec('INSERT INTO soFoo (first,last) VALUES (0,3)');

    foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $row ) {
        echo join(' | ', $row), "\n";
    }

Conveniently, the timestamp is converted to the same datetime string representation as in the first example - at least with my PHP/PDO/mysqlnd version.

How do I redirect with JavaScript?

You may need to explain your question a little more.

When you say "redirect", to most people that suggest changing the location of the HTML page:

window.location = url;

When you say "redirect to function" - it doesn't really make sense. You can call a function or you can redirect to another page.
You can even redirect and have a function called when the new page loads.

How to get year/month/day from a date object?

var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

newdate = year + "/" + month + "/" + day;

or you can set new date and give the above values

How to show text in combobox when no item selected?

One line after form InitializeComponent();

cbo_MyDropBox.Text = "Select a server...";

You only need it once right? All you need to do if a pick is mandatory is check if the box index != -1. Could anyone elaborate why the other answers jump through hoops to get this going?

The only thing I'm missing here is having just this initial text grayed out. If you really want that just use a label in front and turn it off once the index is changed.

How to convert a char to a String?

I've tried the suggestions but ended up implementing it as follows

editView.setFilters(new InputFilter[]{new InputFilter()
        {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend)
            {
                String prefix = "http://";

                //make sure our prefix is visible
                String destination = dest.toString();

                //Check If we already have our prefix - make sure it doesn't
                //get deleted
                if (destination.startsWith(prefix) && (dstart <= prefix.length() - 1))
                {
                    //Yep - our prefix gets modified - try preventing it.
                    int newEnd = (dend >= prefix.length()) ? dend : prefix.length();

                    SpannableStringBuilder builder = new SpannableStringBuilder(
                            destination.substring(dstart, newEnd));
                    builder.append(source);
                    if (source instanceof Spanned)
                    {
                        TextUtils.copySpansFrom(
                                (Spanned) source, 0, source.length(), null, builder, newEnd);
                    }

                    return builder;
                }
                else
                {
                    //Accept original replacement (by returning null)
                    return null;
                }
            }
        }});

What's the u prefix in a Python string?

All strings meant for humans should use u"".

I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u"" syntax. The "" syntax is for byte arrays, only.

Before the bashing begins, let me explain. Most Python programs start out with using "" for strings. But then they need to support documentation off the Internet, so they start using "".decode and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of "" for strings. In this case, Unicode does act like a virus and will wreak havoc.

But, if you follow my rule, you won't have this infection (because you will already be infected).

How can I get the SQL of a PreparedStatement?

Using prepared statements, there is no "SQL query" :

  • You have a statement, containing placeholders
    • it is sent to the DB server
    • and prepared there
    • which means the SQL statement is "analysed", parsed, some data-structure representing it is prepared in memory
  • And, then, you have bound variables
    • which are sent to the server
    • and the prepared statement is executed -- working on those data

But there is no re-construction of an actual real SQL query -- neither on the Java side, nor on the database side.

So, there is no way to get the prepared statement's SQL -- as there is no such SQL.


For debugging purpose, the solutions are either to :

  • Ouput the code of the statement, with the placeholders and the list of data
  • Or to "build" some SQL query "by hand".

How to examine processes in OS X's Terminal?

Using top and ps is okay, but I find that using htop is far better & clearer than the standard tools Mac OS X uses. My fave use is to hit the T key while it is running to view processes in tree view (see screenshot). Shows you what processes are co-dependent on other processes.

htop on OSX

You can install it from Homebrew using:

brew install htop

And if you have Xcode and related tools such as git installed on your system and you want to install the latest development code from the official source repository—just follow these steps.

First clone the source code from the htop GitHub repository:

git clone [email protected]:hishamhm/htop.git

Now go into the repository directory:

cd htop

Run autogen.sh:

./autogen.sh

Run this configure command:

./configure

Once the configure process completes, run make:

make

Finally install it by running sudo make install:

sudo make install

Best way to retrieve variable values from a text file?

A simple way of reading variables from a text file using the standard library:

# Get vars from conf file
var = {}
with open("myvars.conf") as conf:
        for line in conf:
                if ":" in line:
                        name, value = line.split(":")
                        var[name] = str(value).rstrip()
globals().update(var)

How to resize Twitter Bootstrap modal dynamically based on the content

For Bootstrap 2 Auto adjust model height dynamically

  //Auto adjust modal height on open 
  $('#modal').on('shown',function(){
     var offset = 0;
     $(this).find('.modal-body').attr('style','max-height:'+($(window).height()-offset)+'px !important;');
  });

How to get the location of the DLL currently executing?

If you're working with an asp.net application and you want to locate assemblies when using the debugger, they are usually put into some temp directory. I wrote the this method to help with that scenario.

private string[] GetAssembly(string[] assemblyNames)
{
    string [] locations = new string[assemblyNames.Length];


    for (int loop = 0; loop <= assemblyNames.Length - 1; loop++)       
    {
         locations[loop] = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.ManifestModule.Name == assemblyNames[loop]).Select(a => a.Location).FirstOrDefault();
    }
    return locations;
}

For more details see this blog post http://nodogmablog.bryanhogan.net/2015/05/finding-the-location-of-a-running-assembly-in-net/

If you can't change the source code, or redeploy, but you can examine the running processes on the computer use Process Explorer. I written a detailed description here.

It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.

I've written a full description of how do this for a dll inside IIS - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/

Check if a variable exists in a list in Bash

Assuming TARGET variable can be only 'binomial' or 'regression', then following would do:

# Check for modeling types known to this script
if [ $( echo "${TARGET}" | egrep -c "^(binomial|regression)$" ) -eq 0 ]; then
    echo "This scoring program can only handle 'binomial' and 'regression' methods now." >&2
    usage
fi

You could add more strings into the list by separating them with a | (pipe) character.

Advantage of using egrep, is that you could easily add case insensitivity (-i), or check more complex scenarios with a regular expression.

Get child node index

Could you do something like this:

var index = Array.prototype.slice.call(element.parentElement.children).indexOf(element);

https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement

How to check if a process is running via a batch script

I like the WMIC and TASKLIST tools but they are not available in home/basic editions of windows.Another way is to use QPROCESS command available on almost every windows machine (for the ones that have terminal services - I think only win XP without SP2 , so practialy every windows machine):

@echo off
:check_process
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1
:: QPROCESS can display only the first 12 symbols of the running process
:: If other tool is used the line bellow could be deleted
set process_to_check=%process_to_check:~0,12%

QPROCESS * | find /i "%process_to_check%" >nul 2>&1 && (
    echo process %process_to_check%  is running
) || (
    echo process %process_to_check%  is not running
)
endlocal

QPROCESS command is not so powerful as TASKLIST and is limited in showing only 12 symbols of process name but should be taken into consideration if TASKLIST is not available.

More simple usage where it uses the name if the process as an argument (the .exe suffix is mandatory in this case where you pass the executable name):

@echo off
:check_process
setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
:: .exe suffix is mandatory
set "process_to_check=%~1"


QPROCESS "%process_to_check%" >nul 2>&1 && (
    echo process %process_to_check%  is running
) || (
    echo process %process_to_check%  is not running
)
endlocal

The difference between two ways of QPROCESS usage is that the QPROCESS * will list all processes while QPROCESS some.exe will filter only the processes for the current user.

Using WMI objects through windows script host exe instead of WMIC is also an option.It should on run also on every windows machine (excluding the ones where the WSH is turned off but this is a rare case).Here bat file that lists all processes through WMI classes and can be used instead of QPROCESS in the script above (it is a jscript/bat hybrid and should be saved as .bat):

@if (@X)==(@Y) @end /* JSCRIPT COMMENT **


@echo off
cscript //E:JScript //nologo "%~f0"
exit /b

************** end of JSCRIPT COMMENT **/


var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes =  new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
    var process=processes.item();
    WScript.Echo( process.processID + "   " + process.Name );
}

And a modification that will check if a process is running:

@if (@X)==(@Y) @end /* JSCRIPT COMMENT **


@echo off
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running
set process_to_check=%~1

cscript //E:JScript //nologo "%~f0" | find /i "%process_to_check%" >nul 2>&1 && (
    echo process %process_to_check%  is running
) || (
    echo process %process_to_check%  is not running
)

exit /b

************** end of JSCRIPT COMMENT **/


var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes =  new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
    var process=processes.item();
    WScript.Echo( process.processID + "   " + process.Name );
}

The two options could be used on machines that have no TASKLIST.

The ultimate technique is using MSHTA . This will run on every windows machine from XP and above and does not depend on windows script host settings. the call of MSHTA could reduce a little bit the performance though (again should be saved as bat):

@if (@X)==(@Y) @end /* JSCRIPT COMMENT **
@echo off

setlocal
if "%~1" equ "" echo pass the process name as forst argument && exit /b 1
:: first argument is the process you want to check if running

set process_to_check=%~1


mshta "about:<script language='javascript' src='file://%~dpnxf0'></script>" | find /i "%process_to_check%" >nul 2>&1 && (
    echo process %process_to_check%  is running
) || (
    echo process %process_to_check%  is not running
)
endlocal
exit /b
************** end of JSCRIPT COMMENT **/


   var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);


   var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
   var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
   var processes =  new Enumerator(colProcess);
   for (;!processes.atEnd();processes.moveNext()) {
    var process=processes.item();
    fso.Write( process.processID + "   " + process.Name + "\n");
   }
   close();

"unary operator expected" error in Bash if condition

You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.

It goes by this syntax: ${VARIABLE:-default}.

The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.

If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".

Multiple Image Upload PHP form with one input

Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";

        $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
        $lastid= $connection->insert_id;
        foreach ($_FILES["file"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK ){
                $name = $lastid.$_FILES['file']['name'][$key];
                $target_dir = "photo/";
                $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
                move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
            }
        }

And how to fetch

$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());


  if($result->num_rows > 0) {
      while($r = mysqli_fetch_assoc($result)){
        $eventid= $r['id'];
        $sqli="select id,image from photos where eventid='".$eventid."'";
        $resulti=mysqli_query($connection,$sqli);
        $image_json_array = array();
        while($row = mysqli_fetch_assoc($resulti)){
            $image_id = $row['id'];
            $image_name = $row['image'];
            $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
        }
        $msg1[] = array ("imagelist" => $image_json_array);

      }

in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})

Why is 22 the default port number for SFTP?

Not authoritative, but interesting: 21 is FTP, 23 is telnet. 22 is SSH...something in between (that can take the place of both).

How to explain callbacks in plain english? How are they different from calling one function from another function?

I am going to try to keep this dead simple. A "callback" is any function that is called by another function which takes the first function as a parameter. A lot of the time, a "callback" is a function that is called when something happens. That something can be called an "event" in programmer-speak.

Imagine this scenario: you are expecting a package in a couple of days. The package is a gift for your neighbor. Therefore, once you get the package, you want it brought over to the neighbors. You are out of town, and so you leave instructions for your spouse.

You could tell them to get the package and bring it to the neighbors. If your spouse was as stupid as a computer, they would sit at the door and wait for the package until it came (NOT DOING ANYTHING ELSE) and then once it came they would bring it over to the neighbors. But there's a better way. Tell your spouse that ONCE they receive the package, they should bring it over the neighbors. Then, they can go about life normally UNTIL they receive the package.

In our example, the receiving of the package is the "event" and the bringing it to the neighbors is the "callback". Your spouse "runs" your instructions to bring the package over only when the package arrives. Much better!

This kind of thinking is obvious in daily life, but computers don't have the same kind of common sense. Consider how programmers normally write to a file:

fileObject = open(file)
# now that we have WAITED for the file to open, we can write to it
fileObject.write("We are writing to the file.")
# now we can continue doing the other, totally unrelated things our program does

Here, we WAIT for the file to open, before we write to it. This "blocks" the flow of execution, and our program cannot do any of the other things it might need to do! What if we could do this instead:

# we pass writeToFile (A CALLBACK FUNCTION!) to the open function
fileObject = open(file, writeToFile)
# execution continues flowing -- we don't wait for the file to be opened
# ONCE the file is opened we write to it, but while we wait WE CAN DO OTHER THINGS!

It turns out we do this with some languages and frameworks. It's pretty cool! Check out Node.js to get some real practice with this kind of thinking.

How to hide command output in Bash

You can redirect stdout to /dev/null.

yum install nano > /dev/null

Or you can redirect both stdout and stderr,

yum install nano &> /dev/null.

But if the program has a quiet option, that's even better.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

You need to set the error_reporting value in a .htaccess file. Since there is a parse error, it never runs the error_reporting() function in your PHP code.

Try this in a .htaccess file (assuming you can use one):

php_flag display_errors 1
php_value error_reporting 30719

I think 30719 corresponds to E_ALL but I may be wrong.

Edit Update: http://php.net/manual/en/errorfunc.constants.php

int error_reporting ([ int $level ] )
---
32767   E_ALL (integer)     
All errors and warnings, as supported, except of   level E_STRICT prior to PHP 5.4.0.   32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP   5.2.x, 2047 previously

Convert timestamp in milliseconds to string formatted time in Java

    long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
    long seconds = TimeUnit.MILLISECONDS
            .toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
    long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours)
            - TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);
    return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);

In LINQ, select all values of property X where X != null

There is no way to skip a check if it exists.

Converting Stream to String and back...what are we missing?

I have just tested this and works fine.

string test = "Testing 1-2-3";

// convert string to stream
byte[] byteArray = Encoding.ASCII.GetBytes(test);
MemoryStream stream = new MemoryStream(byteArray);

// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

If stream has already been written to, you might want to seek to the beginning before first before reading out the text: stream.Seek(0, SeekOrigin.Begin);

How to convert answer into two decimal point

For formatting options, see this

Dim v1 as Double = Val(txtD.Text) / Val(txtC.Text) *
                   Val(txtF.Text) / Val(txtE.Text)
txtA.text = v1.ToString("N2");

To show only file name without the entire directory path

just hoping to be helpful to someone as old problems seem to come back every now and again and I always find good tips here.

My problem was to list in a text file all the names of the "*.txt" files in a certain directory without path and without extension from a Datastage 7.5 sequence.

The solution we used is:

ls /home/user/new/*.txt | xargs -n 1 basename | cut -d '.' -f1 > name_list.txt

Can you force a React component to rerender without calling setState?

I Avoided forceUpdate by doing following

WRONG WAY : do not use index as key

this.state.rows.map((item, index) =>
   <MyComponent cell={item} key={index} />
)

CORRECT WAY : Use data id as key, it can be some guid etc

this.state.rows.map((item) =>
   <MyComponent item={item} key={item.id} />
)

so by doing such code improvement your component will be UNIQUE and render naturally

Logging framework incompatibility

Just to help those in a similar situation to myself...

This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556

The workaround is exclude the component and then manually depends on the correct, or patched version.

EG.

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>0.8</version>
    <exclusions>
        <exclusion>
            <!-- NOTE: Version 4.2 has bundled slf4j -->
            <groupId>edu.ucar</groupId>
            <artifactId>netcdf</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <!-- Patched version 4.2-min does not bundle slf4j -->
    <groupId>edu.ucar</groupId>
    <artifactId>netcdf</artifactId>
    <version>4.2-min</version>
</dependency>

Spring-Security-Oauth2: Full authentication is required to access this resource

setting management.security.enabled=false in application.properties resolved the issue for me.

JPA Native Query select and cast object

You might want to try one of the following ways:

  • Using the method createNativeQuery(sqlString, resultClass)

    Native queries can also be defined dynamically using the EntityManager.createNativeQuery() API.

    String sql = "SELECT USER.* FROM USER_ AS USER WHERE ID = ?";
    
    Query query = em.createNativeQuery(sql, User.class);
    query.setParameter(1, id);
    User user = (User) query.getSingleResult();
    
  • Using the annotation @NamedNativeQuery

    Native queries are defined through the @NamedNativeQuery and @NamedNativeQueries annotations, or <named-native-query> XML element.

    @NamedNativeQuery(
        name="complexQuery",
        query="SELECT USER.* FROM USER_ AS USER WHERE ID = ?",
        resultClass=User.class
    )
    public class User { ... }
    
    Query query = em.createNamedQuery("complexQuery", User.class);
    query.setParameter(1, id);
    User user = (User) query.getSingleResult();
    

You can read more in the excellent open book Java Persistence (available in PDF).

-------
NOTE: With regard to use of getSingleResult(), see Why you should never use getSingleResult() in JPA.

How to get a list column names and datatypes of a table in PostgreSQL?

Below will list all the distinct data types of all the table in the provided schema name.

\copy (select distinct data_type, column_name from information_schema.columns where table_name in (SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema' and schemaname = '<Your schema name>')) to 'datatypes.csv'  delimiter as ',' CSV header

How to develop a soft keyboard for Android?

Create Custom Key Board for Own EditText

Download Entire Code

In this post i Created Simple Keyboard which contains Some special keys like ( France keys ) and it's supported Capital letters and small letters and Number keys and some Symbols .

package sra.keyboard;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

public class Main extends Activity implements OnTouchListener, OnClickListener,
  OnFocusChangeListener {
 private EditText mEt, mEt1; // Edit Text boxes
 private Button mBSpace, mBdone, mBack, mBChange, mNum;
 private RelativeLayout mLayout, mKLayout;
 private boolean isEdit = false, isEdit1 = false;
 private String mUpper = "upper", mLower = "lower";
 private int w, mWindowWidth;
 private String sL[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
   "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
   "x", "y", "z", "ç", "à", "é", "è", "û", "î" };
 private String cL[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
   "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
   "X", "Y", "Z", "ç", "à", "é", "è", "û", "î" };
 private String nS[] = { "!", ")", "'", "#", "3", "$", "%", "&", "8", "*",
   "?", "/", "+", "-", "9", "0", "1", "4", "@", "5", "7", "(", "2",
   "\"", "6", "_", "=", "]", "[", "<", ">", "|" };
 private Button mB[] = new Button[32];

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  try {
   setContentView(R.layout.main);
   // adjusting key regarding window sizes
   setKeys();
   setFrow();
   setSrow();
   setTrow();
   setForow();
   mEt = (EditText) findViewById(R.id.xEt);
   mEt.setOnTouchListener(this);
   mEt.setOnFocusChangeListener(this);
   mEt1 = (EditText) findViewById(R.id.et1);

   mEt1.setOnTouchListener(this);
   mEt1.setOnFocusChangeListener(this);
   mEt.setOnClickListener(this);
   mEt1.setOnClickListener(this);
   mLayout = (RelativeLayout) findViewById(R.id.xK1);
   mKLayout = (RelativeLayout) findViewById(R.id.xKeyBoard);

  } catch (Exception e) {
   Log.w(getClass().getName(), e.toString());
  }

 }

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  if (v == mEt) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  if (v == mEt1) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  return true;
 }

 @Override
 public void onClick(View v) {

  if (v == mBChange) {

   if (mBChange.getTag().equals(mUpper)) {
    changeSmallLetters();
    changeSmallTags();
   } else if (mBChange.getTag().equals(mLower)) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  } else if (v != mBdone && v != mBack && v != mBChange && v != mNum) {
   addText(v);

  } else if (v == mBdone) {

   disableKeyboard();

  } else if (v == mBack) {
   isBack(v);
  } else if (v == mNum) {
   String nTag = (String) mNum.getTag();
   if (nTag.equals("num")) {
    changeSyNuLetters();
    changeSyNuTags();
    mBChange.setVisibility(Button.INVISIBLE);

   }
   if (nTag.equals("ABC")) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  }

 }

 @Override
 public void onFocusChange(View v, boolean hasFocus) {
  if (v == mEt && hasFocus == true) {
   isEdit = true;
   isEdit1 = false;

  } else if (v == mEt1 && hasFocus == true) {
   isEdit = false;
   isEdit1 = true;

  }

 }

 private void addText(View v) {
  if (isEdit == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt.append(b);

   }
  }

  if (isEdit1 == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt1.append(b);

   }

  }

 }

 private void isBack(View v) {
  if (isEdit == true) {
   CharSequence cc = mEt.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt.setText("");
     mEt.append(cc.subSequence(0, cc.length() - 1));
    }

   }
  }

  if (isEdit1 == true) {
   CharSequence cc = mEt1.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt1.setText("");
     mEt1.append(cc.subSequence(0, cc.length() - 1));
    }
   }
  }
 }
 private void changeSmallLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < sL.length; i++)
   mB[i].setText(sL[i]);
  mNum.setTag("12#");
 }
 private void changeSmallTags() {
  for (int i = 0; i < sL.length; i++)
   mB[i].setTag(sL[i]);
  mBChange.setTag("lower");
  mNum.setTag("num");
 }
 private void changeCapitalLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < cL.length; i++)
   mB[i].setText(cL[i]);
  mBChange.setTag("upper");
  mNum.setText("12#");

 }

 private void changeCapitalTags() {
  for (int i = 0; i < cL.length; i++)
   mB[i].setTag(cL[i]);
  mNum.setTag("num");

 }

 private void changeSyNuLetters() {

  for (int i = 0; i < nS.length; i++)
   mB[i].setText(nS[i]);
  mNum.setText("ABC");
 }

 private void changeSyNuTags() {
  for (int i = 0; i < nS.length; i++)
   mB[i].setTag(nS[i]);
  mNum.setTag("ABC");
 }

 // enabling customized keyboard
 private void enableKeyboard() {

  mLayout.setVisibility(RelativeLayout.VISIBLE);
  mKLayout.setVisibility(RelativeLayout.VISIBLE);

 }

 // Disable customized keyboard
 private void disableKeyboard() {
  mLayout.setVisibility(RelativeLayout.INVISIBLE);
  mKLayout.setVisibility(RelativeLayout.INVISIBLE);

 }

 private void hideDefaultKeyboard() {
  getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

 }

 private void setFrow() {
  w = (mWindowWidth / 13);
  w = w - 15;
  mB[16].setWidth(w);
  mB[22].setWidth(w + 3);
  mB[4].setWidth(w);
  mB[17].setWidth(w);
  mB[19].setWidth(w);
  mB[24].setWidth(w);
  mB[20].setWidth(w);
  mB[8].setWidth(w);
  mB[14].setWidth(w);
  mB[15].setWidth(w);
  mB[16].setHeight(50);
  mB[22].setHeight(50);
  mB[4].setHeight(50);
  mB[17].setHeight(50);
  mB[19].setHeight(50);
  mB[24].setHeight(50);
  mB[20].setHeight(50);
  mB[8].setHeight(50);
  mB[14].setHeight(50);
  mB[15].setHeight(50);

 }

 private void setSrow() {
  w = (mWindowWidth / 10);
  mB[0].setWidth(w);
  mB[18].setWidth(w);
  mB[3].setWidth(w);
  mB[5].setWidth(w);
  mB[6].setWidth(w);
  mB[7].setWidth(w);
  mB[26].setWidth(w);
  mB[9].setWidth(w);
  mB[10].setWidth(w);
  mB[11].setWidth(w);
  mB[26].setWidth(w);

  mB[0].setHeight(50);
  mB[18].setHeight(50);
  mB[3].setHeight(50);
  mB[5].setHeight(50);
  mB[6].setHeight(50);
  mB[7].setHeight(50);
  mB[9].setHeight(50);
  mB[10].setHeight(50);
  mB[11].setHeight(50);
  mB[26].setHeight(50);
 }

 private void setTrow() {
  w = (mWindowWidth / 12);
  mB[25].setWidth(w);
  mB[23].setWidth(w);
  mB[2].setWidth(w);
  mB[21].setWidth(w);
  mB[1].setWidth(w);
  mB[13].setWidth(w);
  mB[12].setWidth(w);
  mB[27].setWidth(w);
  mB[28].setWidth(w);
  mBack.setWidth(w);

  mB[25].setHeight(50);
  mB[23].setHeight(50);
  mB[2].setHeight(50);
  mB[21].setHeight(50);
  mB[1].setHeight(50);
  mB[13].setHeight(50);
  mB[12].setHeight(50);
  mB[27].setHeight(50);
  mB[28].setHeight(50);
  mBack.setHeight(50);

 }

 private void setForow() {
  w = (mWindowWidth / 10);
  mBSpace.setWidth(w * 4);
  mBSpace.setHeight(50);
  mB[29].setWidth(w);
  mB[29].setHeight(50);

  mB[30].setWidth(w);
  mB[30].setHeight(50);

  mB[31].setHeight(50);
  mB[31].setWidth(w);
  mBdone.setWidth(w + (w / 1));
  mBdone.setHeight(50);

 }

 private void setKeys() {
  mWindowWidth = getWindowManager().getDefaultDisplay().getWidth(); // getting
  // window
  // height
  // getting ids from xml files
  mB[0] = (Button) findViewById(R.id.xA);
  mB[1] = (Button) findViewById(R.id.xB);
  mB[2] = (Button) findViewById(R.id.xC);
  mB[3] = (Button) findViewById(R.id.xD);
  mB[4] = (Button) findViewById(R.id.xE);
  mB[5] = (Button) findViewById(R.id.xF);
  mB[6] = (Button) findViewById(R.id.xG);
  mB[7] = (Button) findViewById(R.id.xH);
  mB[8] = (Button) findViewById(R.id.xI);
  mB[9] = (Button) findViewById(R.id.xJ);
  mB[10] = (Button) findViewById(R.id.xK);
  mB[11] = (Button) findViewById(R.id.xL);
  mB[12] = (Button) findViewById(R.id.xM);
  mB[13] = (Button) findViewById(R.id.xN);
  mB[14] = (Button) findViewById(R.id.xO);
  mB[15] = (Button) findViewById(R.id.xP);
  mB[16] = (Button) findViewById(R.id.xQ);
  mB[17] = (Button) findViewById(R.id.xR);
  mB[18] = (Button) findViewById(R.id.xS);
  mB[19] = (Button) findViewById(R.id.xT);
  mB[20] = (Button) findViewById(R.id.xU);
  mB[21] = (Button) findViewById(R.id.xV);
  mB[22] = (Button) findViewById(R.id.xW);
  mB[23] = (Button) findViewById(R.id.xX);
  mB[24] = (Button) findViewById(R.id.xY);
  mB[25] = (Button) findViewById(R.id.xZ);
  mB[26] = (Button) findViewById(R.id.xS1);
  mB[27] = (Button) findViewById(R.id.xS2);
  mB[28] = (Button) findViewById(R.id.xS3);
  mB[29] = (Button) findViewById(R.id.xS4);
  mB[30] = (Button) findViewById(R.id.xS5);
  mB[31] = (Button) findViewById(R.id.xS6);
  mBSpace = (Button) findViewById(R.id.xSpace);
  mBdone = (Button) findViewById(R.id.xDone);
  mBChange = (Button) findViewById(R.id.xChange);
  mBack = (Button) findViewById(R.id.xBack);
  mNum = (Button) findViewById(R.id.xNum);
  for (int i = 0; i < mB.length; i++)
   mB[i].setOnClickListener(this);
  mBSpace.setOnClickListener(this);
  mBdone.setOnClickListener(this);
  mBack.setOnClickListener(this);
  mBChange.setOnClickListener(this);
  mNum.setOnClickListener(this);

 }

}

Checking whether a variable is an integer or not

A simple way to do this is to directly check if the remainder on division by 1 is 0 or not.

if this_variable % 1 == 0:
    list.append(this_variable)
else:
    print 'Not an Integer!'

Making sure at least one checkbox is checked

Check this.

You can't access form inputs via their name. Use document.getElements methods instead.

React Native Change Default iOS Simulator Device

Get device list with this command

xcrun simctl list devices

Console

== Devices ==
-- iOS 13.5 --
    iPhone 6s (9981E5A5-48A8-4B48-B203-1C6E73243E83) (Shutdown) 
    iPhone 8 (FC540A6C-F374-4113-9E71-1291790C8C4C) (Shutting Down) 
    iPhone 8 Plus (CAC37462-D873-4EBB-9D71-7C6D0C915C12) (Shutdown) 
    iPhone 11 (347EFE28-9B41-4C1A-A4C3-D99B49300D8B) (Shutting Down) 
    iPhone 11 Pro (5AE964DC-201C-48C9-BFB5-4506E3A0018F) (Shutdown) 
    iPhone 11 Pro Max (48EE985A-39A6-426C-88A4-AA1E4AFA0133) (Shutdown) 
    iPhone SE (2nd generation) (48B78183-AFD7-4832-A80E-AF70844222BA) (Shutdown) 
    iPad Pro (9.7-inch) (2DEF27C4-6A18-4477-AC7F-FB31CCCB3960) (Shutdown) 
    iPad (7th generation) (36A4AF6B-1232-4BCB-B74F-226E025225E4) (Shutdown) 
    iPad Pro (11-inch) (2nd generation) (79391BD7-0E55-44C8-B1F9-AF92A1D57274) (Shutdown) 
    iPad Pro (12.9-inch) (4th generation) (ED90A31F-6B20-4A6B-9EE9-CF22C01E8793) (Shutdown) 
    iPad Air (3rd generation) (41AD1CF7-CB0D-4F18-AB1E-6F8B6261AD33) (Shutdown) 
-- tvOS 13.4 --
    Apple TV 4K (51925935-97F4-4242-902F-041F34A66B82) (Shutdown) 
-- watchOS 6.2 --
    Apple Watch Series 5 - 40mm (7C50F2E9-A52B-4E0D-8B81-A811FE995502) (Shutdown) 
    Apple Watch Series 5 - 44mm (F7D8C256-DC9F-4FDC-8E65-63275C222B87) (Shutdown) 

Select Simulator string without ID here is an example.

iPad Pro (12.9-inch) (4th generation)

Final command

iPhone

• iPhone 6s

react-native run-ios --simulator="iPhone 6s"

• iPhone 8

react-native run-ios --simulator="iPhone 8"

• iPhone 8 Plus

react-native run-ios --simulator="iPhone 8 Plus"

• iPhone 11

react-native run-ios --simulator="iPhone 11"

• iPhone 11 Pro

react-native run-ios --simulator="iPhone 11 Pro"

• iPhone 11 Pro Max

react-native run-ios --simulator="iPhone 11 Pro Max"

• iPhone SE (2nd generation)

react-native run-ios --simulator="iPhone SE (2nd generation)"

iPad

• iPad Pro (9.7-inch)

react-native run-ios --simulator="iPad Pro (9.7-inch)"

• iPad (7th generation)

react-native run-ios --simulator="iPad (7th generation)"

• iPad Pro (11-inch) (2nd generation)

react-native run-ios --simulator="iPad Pro (11-inch) (2nd generation)"

• iPad Pro (12.9-inch) 4th generation

react-native run-ios --simulator="iPad Pro (12.9-inch) (4th generation)"

• iPad Air (3rd generation)

react-native run-ios --simulator="iPad Air (3rd generation)"

Download a file by jQuery.Ajax

Ok, based on ndpu's code heres an improved (I think) version of ajax_download;-

function ajax_download(url, data) {
    var $iframe,
        iframe_doc,
        iframe_html;

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                    " style='display: none' src='about:blank'></iframe>"
                   ).appendTo("body");
    }

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;
    }

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url +"'>" 

    Object.keys(data).forEach(function(key){
        iframe_html += "<input type='hidden' name='"+key+"' value='"+data[key]+"'>";

    });

        iframe_html +="</form></body></html>";

    iframe_doc.open();
    iframe_doc.write(iframe_html);
    $(iframe_doc).find('form').submit();
}

Use this like this;-

$('#someid').on('click', function() {
    ajax_download('/download.action', {'para1': 1, 'para2': 2});
});

The params are sent as proper post params as if coming from an input rather than as a json encoded string as per the previous example.

CAVEAT: Be wary about the potential for variable injection on those forms. There might be a safer way to encode those variables. Alternatively contemplate escaping them.

Is there a program to decompile Delphi?

Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.

So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.

Should I use pt or px?

px ? Pixels

All of these answers seem to be incorrect. Contrary to intuition, in CSS the px is not pixels. At least, not in the simple physical sense.

Read this article from the W3C, EM, PX, PT, CM, IN…, about how px is a "magical" unit invented for CSS. The meaning of px varies by hardware and resolution. (That article is fresh, last updated 2014-10.)

My own way of thinking about it: 1 px is the size of a thin line intended by a designer to be barely visible.

To quote that article:

The px unit is the magic unit of CSS. It is not related to the current font and also not related to the absolute units. The px unit is defined to be small but visible, and such that a horizontal 1px wide line can be displayed with sharp edges (no anti-aliasing). What is sharp, small and visible depends on the device and the way it is used: do you hold it close to your eyes, like a mobile phone, at arms length, like a computer monitor, or somewhere in between, like a book? The px is thus not defined as a constant length, but as something that depends on the type of device and its typical use.

To get an idea of the appearance of a px, imagine a CRT computer monitor from the 1990s: the smallest dot it can display measures about 1/100th of an inch (0.25mm) or a little more. The px unit got its name from those screen pixels.

Nowadays there are devices that could in principle display smaller sharp dots (although you might need a magnifier to see them). But documents from the last century that used px in CSS still look the same, no matter what the device. Printers, especially, can display sharp lines with much smaller details than 1px, but even on printers, a 1px line looks very much the same as it would look on a computer monitor. Devices change, but the px always has the same visual appearance.

That article gives some guidance about using pt vs px vs em, to answer this Question.

How to send a POST request with BODY in swift

There are few changes I would like to notify. You can access request, JSON, error from response object from now on.

        let urlstring = "Add URL String here"
        let parameters: [String: AnyObject] = [
            "IdQuiz" : 102,
            "IdUser" : "iosclient",
            "User" : "iosclient",
            "List": [
                [
                    "IdQuestion" : 5,
                    "IdProposition": 2,
                    "Time" : 32
                ],
                [
                    "IdQuestion" : 4,
                    "IdProposition": 3,
                    "Time" : 9
                ]
            ]
        ]

        Alamofire.request(.POST, urlstring, parameters: parameters, encoding: .JSON).responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
            response.result.error
        }

Why would $_FILES be empty when uploading files to PHP?

I was struggling with the same problem and testing everything, not getting error reporting and nothing seemed to be wrong. I had error_reporting(E_ALL) But suddenly I realized that I had not checked the apache log and voilà! There was a syntax error on the script...! (a missing "}" )

So, even though this is something evident to be checked, it can be forgotten... In my case (linux) it is at:

/var/log/apache2/error.log

Function pointer as a member of a C struct

The pointer str is never allocated. It should be malloc'd before use.

Android: Align button to bottom-right of screen using FrameLayout?

Two ways to do this:

1) Using a Frame Layout

android:layout_gravity="bottom|right"

2) Using a Relative Layout

android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" 

Error message "Linter pylint is not installed"

  1. Open a terminal (ctrl+~)
  2. Run the command pip install pylint

If that doesn't work: On the off chance you've configured a non-default Python path for your editor, you'll need to match that Python's install location with the pip executable you're calling from the terminal.

This is an issue because the Python extension's settings enable Pylint by default. If you'd rather turn off linting, you can instead change this setting from true to false in your user or workspace settings:

"python.linting.pylintEnabled": false

Typescript es6 import module "File is not a module error"

In addition to A. Tim's answer there are times when even that doesn't work, so you need to:

  1. Rewrite the import string, using the intellisense. Sometimes this fixes the issue
  2. Restart VS Code

How To: Best way to draw table in console app (C#)

This is an improvement to a previous answer. It adds support for values with varying lengths and rows with a varying number of cells. For example:

+------------------------------------------------------------------------------+
¦Identifier¦     Type¦               Description¦  CPU Credit Use¦Hours¦Balance¦
+----------+---------+--------------------------+----------------+-----+-------+
¦ i-1234154¦ t2.small¦       This is an example.¦         3263.75¦  360¦
+----------+---------+--------------------------+----------------+-----+
¦ i-1231412¦ t2.small¦  This is another example.¦         3089.93¦
+----------------------------------------------------------------+

Here is the code:

public class ArrayPrinter
{
    const string TOP_LEFT_JOINT = "+";
    const string TOP_RIGHT_JOINT = "+";
    const string BOTTOM_LEFT_JOINT = "+";
    const string BOTTOM_RIGHT_JOINT = "+";
    const string TOP_JOINT = "-";
    const string BOTTOM_JOINT = "-";
    const string LEFT_JOINT = "+";
    const string JOINT = "+";
    const string RIGHT_JOINT = "¦";
    const char HORIZONTAL_LINE = '-';
    const char PADDING = ' ';
    const string VERTICAL_LINE = "¦";

    private static int[] GetMaxCellWidths(List<string[]> table)
    {
        int maximumCells = 0;
        foreach (Array row in table)
        {
            if (row.Length > maximumCells)
                maximumCells = row.Length;
        }

        int[] maximumCellWidths = new int[maximumCells];
        for (int i = 0; i < maximumCellWidths.Length; i++)
            maximumCellWidths[i] = 0;

        foreach (Array row in table)
        {
            for (int i = 0; i < row.Length; i++)
            {
                if (row.GetValue(i).ToString().Length > maximumCellWidths[i])
                    maximumCellWidths[i] = row.GetValue(i).ToString().Length;
            }
        }

        return maximumCellWidths;
    }

    public static string GetDataInTableFormat(List<string[]> table)
    {
        StringBuilder formattedTable = new StringBuilder();
        Array nextRow = table.FirstOrDefault();
        Array previousRow = table.FirstOrDefault();

        if (table == null || nextRow == null)
            return String.Empty;

        // FIRST LINE:
        int[] maximumCellWidths = GetMaxCellWidths(table);
        for (int i = 0; i < nextRow.Length; i++)
        {
            if (i == 0 && i == nextRow.Length - 1)
                formattedTable.Append(String.Format("{0}{1}{2}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
            else if (i == 0)
                formattedTable.Append(String.Format("{0}{1}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
            else if (i == nextRow.Length - 1)
                formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
            else
                formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
        }

        int rowIndex = 0;
        int lastRowIndex = table.Count - 1;
        foreach (Array thisRow in table)
        {
            // LINE WITH VALUES:
            int cellIndex = 0;
            int lastCellIndex = thisRow.Length - 1;
            foreach (object thisCell in thisRow)
            {
                string thisValue = thisCell.ToString().PadLeft(maximumCellWidths[cellIndex], PADDING);

                if (cellIndex == 0 && cellIndex == lastCellIndex)
                    formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
                else if (cellIndex == 0)
                    formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));
                else if (cellIndex == lastCellIndex)
                    formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
                else
                    formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));

                cellIndex++;
            }

            previousRow = thisRow;

            // SEPARATING LINE:
            if (rowIndex != lastRowIndex)
            {
                nextRow = table[rowIndex + 1];

                int maximumCells = Math.Max(previousRow.Length, nextRow.Length);
                for (int i = 0; i < maximumCells; i++)
                {
                    if (i == 0 && i == maximumCells - 1)
                    {
                        formattedTable.Append(String.Format("{0}{1}{2}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
                    }
                    else if (i == 0)
                    {
                        formattedTable.Append(String.Format("{0}{1}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                    }
                    else if (i == maximumCells - 1)
                    {
                        if (i > previousRow.Length)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
                        else if (i > nextRow.Length)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
                        else if (i > previousRow.Length - 1)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
                        else if (i > nextRow.Length - 1)
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
                        else
                            formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
                    }
                    else
                    {
                        if (i > previousRow.Length)
                            formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                        else if (i > nextRow.Length)
                            formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                        else
                            formattedTable.Append(String.Format("{0}{1}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
                    }
                }
            }

            rowIndex++;
        }

        // LAST LINE:
        for (int i = 0; i < previousRow.Length; i++)
        {
            if (i == 0)
                formattedTable.Append(String.Format("{0}{1}", BOTTOM_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
            else if (i == previousRow.Length - 1)
                formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
            else
                formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
        }

        return formattedTable.ToString();
    }
}

Compare two Timestamp in java

From : http://download.oracle.com/javase/6/docs/api/java/sql/Timestamp.html#compareTo(java.sql.Timestamp)

public int compareTo(Timestamp ts)

Compares this Timestamp object to the given Timestamp object. Parameters: ts - the Timestamp object to be compared to this Timestamp object Returns: the value 0 if the two Timestamp objects are equal; a value less than 0 if this Timestamp object is before the given argument; and a value greater than 0 if this Timestamp object is after the given argument. Since: 1.4

How to disable the resize grabber of <textarea>?

<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>

Just an example

HTML5 Video // Completely Hide Controls

There are two ways to hide video tag controls

  1. Remove the controls attribute from the video tag.

  2. Add the css to the video tag

    video::-webkit-media-controls-panel {
    display: none !important;
    opacity: 1 !important;}
    

Java, Simplified check if int array contains int

You can use java.util.Arrays class to transform the array T[?] in a List<T> object with methods like contains:

Arrays.asList(int[] array).contains(int key);

Can I have multiple :before pseudo-elements for the same element?

If your main element has some child elements or text, you could make use of it.

Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).

Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.

This element will start acting like his owner is your main element.

HTML

<div class="circle">
    <span>Some text</span>
</div>

CSS

.circle {
    position: relative; /* or absolute/fixed */
}

.circle:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle:after {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

.circle span {
    /* not relative/absolute/fixed */
}

.circle span:before {
    position: absolute;
    content: "";
    /* more styles: width, height, etc */
}

How do I make a Windows batch script completely silent?

To suppress output, use redirection to NUL.

There are two kinds of output that console commands use:

  • standard output, or stdout,

  • standard error, or stderr.

Of the two, stdout is used more often, both by internal commands, like copy, and by console utilities, or external commands, like find and others, as well as by third-party console programs.

>NUL suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied. message of the copy command. An alternative syntax is 1>NUL. So,

COPY file1 file2 >NUL

or

COPY file1 file2 1>NUL

or

>NUL COPY file1 file2

or

1>NUL COPY file1 file2

suppresses all of COPY's standard output.

To suppress error messages, which are typically printed to stderr, use 2>NUL instead. So, to suppress a File Not Found message that DEL prints when, well, the specified file is not found, just add 2>NUL either at the beginning or at the end of the command line:

DEL file 2>NUL

or

2>NUL DEL file

Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:

IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"

StringIO in Python3

Roman Shapovalov's code should work in Python 3.x as well as Python 2.6/2.7. Here it is again with the complete example:

import io
import numpy
x = "1 3\n 4.5 8"
numpy.genfromtxt(io.BytesIO(x.encode()))

Output:

array([[ 1. ,  3. ],
       [ 4.5,  8. ]])

Explanation for Python 3.x:

  • numpy.genfromtxt takes a byte stream (a file-like object interpreted as bytes instead of Unicode).
  • io.BytesIO takes a byte string and returns a byte stream. io.StringIO, on the other hand, would take a Unicode string and and return a Unicode stream.
  • x gets assigned a string literal, which in Python 3.x is a Unicode string.
  • encode() takes the Unicode string x and makes a byte string out of it, thus giving io.BytesIO a valid argument.

The only difference for Python 2.6/2.7 is that x is a byte string (assuming from __future__ import unicode_literals is not used), and then encode() takes the byte string x and still makes the same byte string out of it. So the result is the same.


Since this is one of SO's most popular questions regarding StringIO, here's some more explanation on the import statements and different Python versions.

Here are the classes which take a string and return a stream:

  • io.BytesIO (Python 2.6, 2.7, and 3.x) - Takes a byte string. Returns a byte stream.
  • io.StringIO (Python 2.6, 2.7, and 3.x) - Takes a Unicode string. Returns a Unicode stream.
  • StringIO.StringIO (Python 2.x) - Takes a byte string or Unicode string. If byte string, returns a byte stream. If Unicode string, returns a Unicode stream.
  • cStringIO.StringIO (Python 2.x) - Faster version of StringIO.StringIO, but can't take Unicode strings which contain non-ASCII characters.

Note that StringIO.StringIO is imported as from StringIO import StringIO, then used as StringIO(...). Either that, or you do import StringIO and then use StringIO.StringIO(...). The module name and class name just happen to be the same. It's similar to datetime that way.

What to use, depending on your supported Python versions:

  • If you only support Python 3.x: Just use io.BytesIO or io.StringIO depending on what kind of data you're working with.

  • If you support both Python 2.6/2.7 and 3.x, or are trying to transition your code from 2.6/2.7 to 3.x: The easiest option is still to use io.BytesIO or io.StringIO. Although StringIO.StringIO is flexible and thus seems preferred for 2.6/2.7, that flexibility could mask bugs that will manifest in 3.x. For example, I had some code which used StringIO.StringIO or io.StringIO depending on Python version, but I was actually passing a byte string, so when I got around to testing it in Python 3.x it failed and had to be fixed.

    Another advantage of using io.StringIO is the support for universal newlines. If you pass the keyword argument newline='' into io.StringIO, it will be able to split lines on any of \n, \r\n, or \r. I found that StringIO.StringIO would trip up on \r in particular.

    Note that if you import BytesIO or StringIO from six, you get StringIO.StringIO in Python 2.x and the appropriate class from io in Python 3.x. If you agree with my previous paragraphs' assessment, this is actually one case where you should avoid six and just import from io instead.

  • If you support Python 2.5 or lower and 3.x: You'll need StringIO.StringIO for 2.5 or lower, so you might as well use six. But realize that it's generally very difficult to support both 2.5 and 3.x, so you should consider bumping your lowest supported version to 2.6 if at all possible.

What are -moz- and -webkit-?

What are -moz- and -webkit-?

CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes.


Why do different browsers add different prefixes for the same effect?

A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:

Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.

Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.

Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid.

The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.


UPDATE AS OF THE YEAR 2016

As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.

As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016,

Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.

For example, just a few years ago, to set a rounded corner on a box you had to write:

-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;

But now that browsers have come to fully support this feature, you really only need the standardized version:

border-radius: 10px 5px;

Finding the right rules for all browsers

As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.

You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.

Input:

a {
  column-count: 3;
  column-gap: 10px;
  column-fill: auto;
}

Output:

a {
  -webkit-column-count: 3;
     -moz-column-count: 3;
          column-count: 3;
  -webkit-column-gap: 10px;
     -moz-column-gap: 10px;
          column-gap: 10px;
  -webkit-column-fill: auto;
     -moz-column-fill: auto;
          column-fill: auto;
}

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

How do I import an SQL file using the command line in MySQL?

For Windows OS, you can use the below command to import data from an SQL dump.

C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u<> -p<> DBName < filelocation\query.sql

Where -u is the username, and -p is the MySQL password. Then enter your password and wait for data to import.

How to drop column with constraint?

Here's another way to drop a default constraint with an unknown name without having to first run a separate query to get the constraint name:

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'__ColumnName__'
                        AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)

jQuery - setting the selected value of a select control via its text description

$("#myselect option:contains('YourTextHere')").val();

will return the value of the first option containing your text description. Tested this and works.

Loading all images using imread from a given folder

import glob
cv_img = []
for img in glob.glob("Path/to/dir/*.jpg"):
    n= cv2.imread(img)
    cv_img.append(n)`

Why is &#65279; appearing in my HTML?

If you are using Notepad++, "Menu" >> "Encoding" >> "Convert to UTF-8" your "include" files.

Build Maven Project Without Running Unit Tests

If you call your classes tests Maven seems to run them automatically, at least they did for me. Rename the classes and Maven will just go through to verification without running them.

java.lang.RuntimeException: Unable to start activity ComponentInfo

Dear You have used two Intent launcher in your Manifest. Make only one Activity as launcher: Your manifest activity is :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.th.mybook"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainTabPanel"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="MyBookActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.ALTERNATIVE" />
            </intent-filter>
        </activity>
    </application>
</manifest>

now write code will be ( i have made your 'MyActivityBook' your default activity launcher. Copy and paste it on your manifest.

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="org.th.mybook"
        android:versionCode="1"
        android:versionName="1.0" >
        <uses-sdk android:minSdkVersion="8" />
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:name=".MainTabPanel"
                android:label="@string/app_name" >

            </activity>
            <activity
                android:name="MyBookActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>

and Second error may be if you copy paste old code then please update com.example.packagename.FILE_NAME

hope this will work !

ScriptManager.RegisterStartupScript code not working - why?

Off the top of my head:

  • Use GetType() instead of typeof(Page) in order to bind the script to your actual page class instead of the base class,
  • Pass a key constant instead of Page.UniqueID, which is not that meaningful since it's supposed to be used by named controls,
  • End your Javascript statement with a semicolon,
  • Register the script during the PreRender phase:

protected void Page_PreRender(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "YourUniqueScriptKey", 
        "alert('This pops up');", true);
}

Pandas DataFrame to List of Lists

Maybe something changed but this gave back a list of ndarrays which did what I needed.

list(df.values)

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

how to auto select an input field and the text in it on page load

Let the input text field automatically get focus when the page loads:

<form action="/action_page.php">
  <input type="text" id="fname" name="fname" autofocus>
  <input type="submit">
</form>

Source : https://www.w3schools.com/tags/att_input_autofocus.asp

How to get all checked checkboxes

In IE9+, Chrome or Firefox you can do:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

Specifying Font and Size in HTML table

This worked for me and also worked with bootstrap tables

<style>
    .table td, .table th {
        font-size: 10px;
    }
</style>

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

How to execute a command in a remote computer?

I use the little utility which comes with PureMPI.net called execcmd.exe. Its syntax is as follows:

execcmd \\yourremoteserver <your command here>

Doesn't get any simpler than this :)

Convert a number range to another range, maintaining ratio

I didn't dig up the BNF for this, but the Arduino documentation had a great example of the function and it's breakdown. I was able to use this in Python by simply adding a def renaming to remap (cause map is a built-in) and removing the type casts and curly braces (ie just remove all the 'long's).

Original

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

Python

def remap(x, in_min, in_max, out_min, out_max):
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

https://www.arduino.cc/en/reference/map

Include another JSP file

You can use Include Directives

<%
 if(request.getParameter("p")!=null)
 { 
   String p = request.getParameter("p");
%>    

<%@include file="<%="includes/" + p +".jsp"%>"%>

<% 
 }
%>

or JSP Include Action

<%
 if(request.getParameter("p")!=null)
 { 
   String p = request.getParameter("p");
%>    

<jsp:include page="<%="includes/"+p+".jsp"%>"/>

<% 
 }
%>

the different is include directive includes a file during the translation phase. while JSP Include Action includes a file at the time the page is requested

I recommend Spring MVC Framework as your controller to manipulate things. use url pattern instead of parameter.

example:

www.yourwebsite.com/products

instead of

www.yourwebsite.com/?p=products

Watch this video Spring MVC Framework

What is the use of printStackTrace() method in Java?

See image here

printStackTrace() tells at what line you are getting error any why are you getting error.

Example:

 java.lang.ArithmeticException: / by zero
    at MinNumber.main(MinNumber.java:8) 

No matching bean of type ... found for dependency

I have similar trouble in test config, because of using AOP. I added this line of code in spring-config.xml

<aop:config proxy-target-class="true"/>

And it works !

How to obtain the location of cacerts of the default java installation?

Under Linux, to find the location of $JAVA_HOME:

readlink -f /usr/bin/java | sed "s:bin/java::"

the cacerts are under lib/security/cacerts:

$(readlink -f /usr/bin/java | sed "s:bin/java::")lib/security/cacerts

Under mac OS X , to find $JAVA_HOME run:

/usr/libexec/java_home

the cacerts are under Home/lib/security/cacerts:

$(/usr/libexec/java_home)/lib/security/cacerts

UPDATE (OS X with JDK)

above code was tested on computer without JDK installed. With JDK installed, as pR0Ps said, it's at

$(/usr/libexec/java_home)/jre/lib/security/cacerts

Error converting data types when importing from Excel to SQL Server 2008

When Excel finds mixed data types in same column it guesses what is the right format for the column (the majority of the values determines the type of the column) and dismisses all other values by inserting NULLs. But Excel does it far badly (e.g. if a column is considered text and Excel finds a number then decides that the number is a mistake and insert a NULL instead, or if some cells containing numbers are "text" formatted, one may get NULL values into an integer column of the database).

Solution:

  1. Create a new excel sheet with the name of the columns in the first row
  2. Format the columns as text
  3. Paste the rows without format (use CVS format or copy/paste in Notepad to get only text)

Note that formatting the columns on an existing Excel sheet is not enough.

Click in OK button inside an Alert (Selenium IDE)

Use the Alert Interface, First switchTo() to alert and then either use accept() to click on OK or use dismiss() to CANCEL it

Alert alert_box = driver.switchTo().alert();
alert_box.accept(); 

or

Alert alert_box = driver.switchTo().alert();
alert_box.dismiss(); 

Tomcat manager/html is not available?

After entering the roles and users in tomcat-users still if does not work make sure your tomact server location point to the right server location

TypeError: 'int' object is not subscriptable

You can't do something like that: (int(sumall[0])+int(sumall[1]))

That's because sumall is an int and not a list or dict.

So, summ + sumd will be you're lucky number

How to get a thread and heap dump of a Java process on Windows that's not running in a console

Maybe jcmd?

Jcmd utility is used to send diagnostic command requests to the JVM, where these requests are useful for controlling Java Flight Recordings, troubleshoot, and diagnose JVM and Java Applications.

The jcmd tool was introduced with Oracle's Java 7 and is particularly useful in troubleshooting issues with JVM applications by using it to identify Java processes' IDs (akin to jps), acquiring heap dumps (akin to jmap), acquiring thread dumps (akin to jstack), viewing virtual machine characteristics such as system properties and command-line flags (akin to jinfo), and acquiring garbage collection statistics (akin to jstat). The jcmd tool has been called "a swiss-army knife for investigating and resolving issues with your JVM application" and a "hidden gem."

Here’s the process you’ll need to use in invoking the jcmd:

  1. Go to jcmd <pid> GC.heap_dump <file-path>
  2. In which
  3. pid: is a Java Process Id, for which the heap dump will be captured Also, the
  4. file-path: is a file path in which the heap dump is be printed.

Check it out for more information about taking Java heap dump.

Mock functions in Go

Considering unit test is the domain of this question, highly recommend you to use monkey. This Package make you to mock test without changing your original source code. Compare to other answer, it's more "non-intrusive".

main

type AA struct {
 //...
}
func (a *AA) OriginalFunc() {
//...
}

mock test

var a *AA

func NewFunc(a *AA) {
 //...
}

monkey.PatchMethod(reflect.TypeOf(a), "OriginalFunc", NewFunc)

Bad side is:

  • Reminded by Dave.C, This method is unsafe. So don't use it outside of unit test.
  • Is non-idiomatic Go.

Good side is:

  • Is non-intrusive. Make you do things without changing the main code. Like Thomas said.
  • Make you change behavior of package (maybe provided by third party) with least code.

Convert a timedelta to days, hours and minutes

I used the following:

delta = timedelta()
totalMinute, second = divmod(delta.seconds, 60)
hour, minute = divmod(totalMinute, 60)
print(f"{hour}h{minute:02}m{second:02}s")

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

Had the same error when installing PhantomJS on Ubuntu 14.04 64bit with gcc-4.8 (CXXABI_1.3.7)

Upgrading to gcc-4.9 (CXXABI_1.3.8) fixed the issue. HOWTO: https://askubuntu.com/questions/466651/how-do-i-use-the-latest-gcc-4-9-on-ubuntu-14-04

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

What is the difference between the kernel space and the user space?

The really simplified answer is that the kernel runs in kernel space, and normal programs run in user space. User space is basically a form of sand-boxing -- it restricts user programs so they can't mess with memory (and other resources) owned by other programs or by the OS kernel. This limits (but usually doesn't entirely eliminate) their ability to do bad things like crashing the machine.

The kernel is the core of the operating system. It normally has full access to all memory and machine hardware (and everything else on the machine). To keep the machine as stable as possible, you normally want only the most trusted, well-tested code to run in kernel mode/kernel space.

The stack is just another part of memory, so naturally it's segregated right along with the rest of memory.

Video file formats supported in iPhone

The short answer is the iPhone supports H.264 video, High profile and AAC audio, in container formats .mov, .mp4, or MPEG Segment .ts. MPEG Segment files are used for HTTP Live Streaming.

  • For maximum compatibility with Android and desktop browsers, use H.264 + AAC in an .mp4 container.
  • For extended length videos longer than 10 minutes you must use HTTP Live Streaming, which is H.264 + AAC in a series of small .ts container files (see App Store Review Guidelines rule 2.5.7).

Video

On the iPhone, H.264 is the only game in town. [1]

There are several different feature tiers or "profiles" available in H.264. All modern iPhones (3GS and above) support the High profile. These profiles are basically three different levels of algorithm "tricks" used to compress the video. More tricks give better compression, but require more CPU or dedicated hardware to decode. This is a table that lists the differences between the different profiles.

[1] Interestingly, Apple's own Facetime uses the newer H.265 (HEVC) video codec. However right now (August 2017) there is no Apple-provided library that gives access to a HEVC codec to developers. This is expected to change at some point.

In talking about what video format the iPhone supports, a distinction should be made between what the hardware can support, and what the (much lower) limits are for playback when streaming over a network.

The only data given about hardware video support by Apple about the current generation of iPhones (SE, 6S, 6S Plus, 7, 7 Plus) is that they support

4K [3840x2160] video recording at 30 fps

1080p [1920x1080] HD video recording at 30 fps or 60 fps.

Obviously the phone can play back what it can record, so we can guess that 3840x2160 at 30 fps and 1920x1080 at 60 fps represent design limits of the phone. In addition, the screen size on the 6S Plus and 7 Plus is 1920x1080. So if you're interested in playback on the phone, it doesn't make sense to send over more pixels then the screen can draw.

However, streaming video is a different matter. Since networks are slow and video is huge, it's typical to use lower resolutions, bitrates, and frame rates than the device's theoretical maximum.

The most detailed document giving recommendations for streaming is TN2224 Best Practices for Creating and Deploying HTTP Live Streaming Media for Apple Devices. Figure 3 in that document gives a table of recommended streaming parameters:

Table of Apple recommended video encoding settings This table is from May 2016.

As you can see, Apple recommends the relatively low resolution of 768x432 as the highest recommended resolution for streaming over a cellular network. Of course this is just a recommendation and YMMV.

Audio

The question is about video, but that video generally has one or more audio tracks with it. The iPhone supports a few audio formats, but the most modern and by far most widely used is AAC. The iPhone 7 / 7 Plus, 6S Plus / 6S, SE all support AAC bitrates of 8 to 320 Kbps.

Container

The audio and video tracks go inside a container. The purpose of the container is to combine (interleave) the different tracks together, to store metadata, and to support seeking. The iPhone supports

  1. QuickTime .mov,
  2. MP4, and
  3. MPEG-TS.

The .mov and .mp4 file formats are closely related (.mp4 is in fact based on .mov), however .mp4 is an ISO standard that has much wider support.

As noted above, you have to use MPEG-TS for videos longer than 10 minutes.