Programs & Examples On #Show sql

Why am I getting Unknown error in line 1 of pom.xml?

You just need a latest Eclipse or Spring tool suite 4.5 and above.Nothing else.refresh project and it works

How to log SQL statements in Spring Boot?

You just need to set spring.jpa.show-sql=true in application.properties for example you may reffer this https://github.com/007anwar/ConfigServerRepo/blob/master/application.yaml

Can't Autowire @Repository annotated interface in Spring Boot

In SpringBoot, the JpaRepository are not auto-enabled by default. You have to explicitly add

@EnableJpaRepositories("packages")
@EntityScan("packages")

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

In my case I just ignored the following in application.properties file:

# Hibernate

#spring.jpa.hibernate.ddl-auto=update

It works for me....

Spring Boot Multiple Datasource

I think you can find it usefull

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources

It shows how to define multiple datasources & assign one of them as primary.

Here is a rather full example, also contains distributes transactions - if you need it.

http://fabiomaffioletti.me/blog/2014/04/15/distributed-transactions-multiple-databases-spring-boot-spring-data-jpa-atomikos/

What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.

Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:

http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html

Hope these helps.

Unable to get spring boot to automatically create database schema

Abderrahmane response is correct: add ?createDatabaseIfNotExist=true in the url property. It seems that ddl-auto won't do anything.

How do I get the day of week given a date?

Using Canlendar Module

import calendar
a=calendar.weekday(year,month,day)
days=["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]
print(days[a])

Add custom headers to WebView resource requests - android

This works for me:

  1. First you need to create method, which will be returns your headers you want to add to request:

    private Map<String, String> getCustomHeaders()
    {
        Map<String, String> headers = new HashMap<>();
        headers.put("YOURHEADER", "VALUE");
        return headers;
    }
    
  2. Second you need to create WebViewClient:

    private WebViewClient getWebViewClient()
    {
    
        return new WebViewClient()
        {
    
        @Override
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
        {
            view.loadUrl(request.getUrl().toString(), getCustomHeaders());
            return true;
        }
    
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url, getCustomHeaders());
            return true;
        }
    };
    }
    
  3. Add WebViewClient to your WebView:

    webView.setWebViewClient(getWebViewClient());
    

Hope this helps.

DTO pattern: Best way to copy properties between two objects

I had an application that I needed to convert from a JPA entity to DTO, and I thought about it and finally came up using org.springframework.beans.BeanUtils.copyProperties for copying simple properties and also extending and using org.springframework.binding.convert.service.DefaultConversionService for converting complex properties.

In detail my service was something like this:

@Service("seedingConverterService")
public class SeedingConverterService extends DefaultConversionService implements ISeedingConverterService  {
    @PostConstruct
    public void init(){
        Converter<Feature,FeatureDTO> featureConverter = new Converter<Feature, FeatureDTO>() {

            @Override
            public FeatureDTO convert(Feature f) {
                FeatureDTO dto = new FeatureDTO();
                //BeanUtils.copyProperties(f, dto,"configurationModel");
                BeanUtils.copyProperties(f, dto);
                dto.setConfigurationModelId(f.getConfigurationModel()==null?null:f.getConfigurationModel().getId());
                return dto;
            }
        };

        Converter<ConfigurationModel,ConfigurationModelDTO> configurationModelConverter = new Converter<ConfigurationModel,ConfigurationModelDTO>() {
            @Override
            public ConfigurationModelDTO convert(ConfigurationModel c) {
                ConfigurationModelDTO dto = new ConfigurationModelDTO();
                //BeanUtils.copyProperties(c, dto, "features");
                BeanUtils.copyProperties(c, dto);
                dto.setAlgorithmId(c.getAlgorithm()==null?null:c.getAlgorithm().getId());
                List<FeatureDTO> l = c.getFeatures().stream().map(f->featureConverter.convert(f)).collect(Collectors.toList());
                dto.setFeatures(l);
                return dto;
            }
        };
        addConverter(featureConverter);
        addConverter(configurationModelConverter);
    }
}

How do I run a shell script without using "sh" or "bash" commands?

Here is my backup script that will give you the idea and the automation:

Server: Ubuntu 16.04 PHP: 7.0 Apache2, Mysql etc...

# Make Shell Backup Script - Bash Backup Script
    nano /home/user/bash/backupscript.sh
        #!/bin/bash
        # Backup All Start
        mkdir /home/user/backup/$(date +"%Y-%m-%d")
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_rest.zip /etc -x "*apache2*" -x "*php*" -x "*mysql*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_apache2.zip /etc/apache2
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_php.zip /etc/php
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_mysql.zip /etc/mysql
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_rest.zip /var/www -x "*html*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_html.zip /var/www/html
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/home_user.zip /home/user -x "*backup*"
        # Backup All End
        echo "Backup Completed Successfully!"
        echo "Location: /home/user/backup/$(date +"%Y-%m-%d")"

    chmod +x /home/user/bash/backupscript.sh
    sudo ln -s /home/user/bash/backupscript.sh /usr/bin/backupscript

change /home/user to your user directory and type: backupscript anywhere on terminal to run the script! (assuming that /usr/bin is in your path)

assignment operator overloading in c++

this might be helpful:

// Operator overloading in C++
//assignment operator overloading
#include<iostream>
using namespace std;

class Employee
{
private:
int idNum;
double salary;
public:
Employee ( ) {
    idNum = 0, salary = 0.0;
}

void setValues (int a, int b);
void operator= (Employee &emp );

};

void Employee::setValues ( int idN , int sal )
{

salary = sal; idNum = idN;

}

void Employee::operator = (Employee &emp)  // Assignment operator overloading function
{
salary = emp.salary;
}

int main ( )
{

Employee emp1;
emp1.setValues(10,33);
Employee emp2;
emp2 = emp1; // emp2 is calling object using assignment operator

}

How to measure elapsed time in Python?

based on the contextmanager solution given by https://stackoverflow.com/a/30024601/5095636, hereunder the lambda free version, as flake8 warns on the usage of lambda as per E731:

from contextlib import contextmanager
from timeit import default_timer

@contextmanager
def elapsed_timer():
    start_time = default_timer()

    class _Timer():
      start = start_time
      end = default_timer()
      duration = end - start

    yield _Timer

    end_time = default_timer()
    _Timer.end = end_time
    _Timer.duration = end_time - start_time

test:

from time import sleep

with elapsed_timer() as t:
    print("start:", t.start)
    sleep(1)
    print("end:", t.end)

t.start
t.end
t.duration

change background image in body

If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:

<script>
  const meta = document.querySelector('[property="og:image"]');
  const body = document.querySelector("body");
  body.style.background = `url(${meta.content})`;
</script>

The above uses document.querySelector and Attribute Selectors to assign meta the first Open Graph image it selects. A similar task is performed to get the body. Finally, string interpolation is used to assign body the background.style the value of the path to the Open Graph image.

If you want the image to cover the entire viewport and stay fixed set background-size like so:

body.style.background = `url(${meta.content}) center center no-repeat fixed`;
body.style.backgroundSize = 'cover';

Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload event, thereby reducing perceived latency.

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

I have the same problem and fix by add "new." before the field is updated. And I post full trigger here for someone to want to write a trigger

DELIMITER $$

USE `nc`$$

CREATE
    TRIGGER `nhachung_province_count_update` BEFORE UPDATE ON `nhachung` 
    FOR EACH ROW BEGIN

    DECLARE slug_province VARCHAR(128);
    DECLARE slug_district VARCHAR(128);

    IF old.status!=new.status THEN  /* neu doi status */
        IF new.status="Y" THEN
            UPDATE province SET `count`=`count`+1 WHERE id = new.district_id;
        ELSE 
            UPDATE province SET `count`=`count`-1 WHERE id = new.district_id;
        END IF;
    ELSEIF old.province_id!=new.province_id THEN /* neu doi province_id + district_id */

        UPDATE province SET `count`=`count`+1 WHERE id = new.province_id; /* province_id */
        UPDATE province SET `count`=`count`-1 WHERE id = old.province_id;
        UPDATE province SET `count`=`count`+1 WHERE id = new.district_id; /* district_id */
        UPDATE province SET `count`=`count`-1 WHERE id = old.district_id;

        SET slug_province = ( SELECT slug FROM province WHERE id= new.province_id LIMIT 0,1 );
        SET slug_district = ( SELECT slug FROM province WHERE id= new.district_id LIMIT 0,1 );
        SET new.prov_dist_url=CONCAT(slug_province, "/", slug_district);

    ELSEIF old.district_id!=new.district_id THEN 

        UPDATE province SET `count`=`count`+1 WHERE id = new.district_id;
        UPDATE province SET `count`=`count`-1 WHERE id = old.district_id;

        SET slug_province = ( SELECT slug FROM province WHERE id= new.province_id LIMIT 0,1 );
        SET slug_district = ( SELECT slug FROM province WHERE id= new.district_id LIMIT 0,1 );
        SET new.prov_dist_url=CONCAT(slug_province, "/", slug_district);

    END IF;


    END;
$$

DELIMITER ;

Hope this help someone

How can I add a .npmrc file?

There are a few different points here:

  1. Where is the .npmrc file created.
  2. How can you download private packages

Running npm config ls -l will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc. But if you have never logged in (using npm login) it will be empty. Simply log in to create it.

Another thing is #2. You can actually do that by putting a .npmrc file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:

; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Pointers

HTTP 401 - what's an appropriate WWW-Authenticate header value?

No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.

You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.

Factorial using Recursion in Java

IMHO, the key for understanding recursion-related actions is:

  1. First, we dive into stack recursively, and with every call we somehow modify a value (e.g. n-1 in func(n-1);) which determines whether the recursion should go deeper and deeper.
  2. Once recursionStopCondition is met (e.g. n == 0), the recursions stops, and methods do actual work and return values to the caller method in upper stacks, thus bubbling to the top of the stack.
  3. It is important to catch the value returned from deeper stack, somehow modify it (multiplying by n in your case), and then return this modified value topwards the stack. The common mistake is that the value from the deepest stack frame is returned straight to the top of the stack, so that all method invocations are ignored.

Surely, methods can do useful work before they dive into recursion (from the top to the bottom of the stack), or on the way back.

How to avoid scientific notation for large numbers in JavaScript?

one more possible solution:

function toFix(i){
 var str='';
 do{
   let a = i%10;
   i=Math.trunc(i/10);
   str = a+str;
 }while(i>0)
 return str;
}

jQuery remove options from select

find() takes a selector, not a value. This means you need to use it in the same way you would use the regular jQuery function ($('selector')).

Therefore you need to do something like this:

$(this).find('[value="X"]').remove();

See the jQuery find docs.

How to change Hash values?

You can collect the values, and convert it from Array to Hash again.

Like this:

config = Hash[ config.collect {|k,v| [k, v.upcase] } ]

ASP.NET Custom Validator Client side & Server Side validation not firing

Also check that you are not using validation groups as that validation wouldnt fire if the validationgroup property was set and not explicitly called via

 Page.Validate({Insert validation group name here});

Specifying Style and Weight for Google Fonts

Here's the issue: You can't specify font weights that don't exist in the font set from Google. Click on the SEE SPECIMEN link below the font, then scroll down to the STYLES section. There you'll see each of the "styles" available for that particular font. Sadly Google doesn't list the CSS font weights for each style. Here's how the names map to CSS font weight numbers:

Thin            100     
Extra Light     200
Light           300
Regular         400
Medium          500
Semi-Bold       600
Bold            700
Extra-Bold      800
Black           900

Note that very few fonts come in all 9 weights.

How do I add an active class to a Link from React Router?

The answer by Vijey has a bit of a problem when you're using react-redux for state management and some of the parent components are 'connected' to the redux store. The activeClassName is applied to Link only when the page is refreshed, and is not dynamically applied as the current route changes.

This is to do with the react-redux's connect function, as it suppresses context updates. To disable suppression of context updates, you can set pure: false when calling the connect() method like this:

//your component which has the custom NavLink as its child. 
//(this component may be the any component from the list of 
//parents and grandparents) eg., header

function mapStateToProps(state) {
  return { someprops: state.someprops }
}

export default connect(mapStateToProps, null, null, {
  pure: false
})(Header);

Check the issue here: reactjs#470

Check pure: false documentation here: docs

How do I get the Back Button to work with an AngularJS ui-router state machine?

The Back button wasn't working for me as well, but I figured out that the problem was that I had html content inside my main page, in the ui-view element.

i.e.

<div ui-view>
     <h1> Hey Kids! </h1>
     <!-- More content -->
</div>

So I moved the content into a new .html file, and marked it as a template in the .js file with the routes.

i.e.

   .state("parent.mystuff", {
        url: "/mystuff",
        controller: 'myStuffCtrl',
        templateUrl: "myStuff.html"
    })

Copy files from one directory into an existing directory

Depending on some details you might need to do something like this:

r=$(pwd)
case "$TARG" in
    /*) p=$r;;
    *) p="";;
    esac
cd "$SRC" && cp -r . "$p/$TARG"
cd "$r"

... this basically changes to the SRC directory and copies it to the target, then returns back to whence ever you started.

The extra fussing is to handle relative or absolute targets.

(This doesn't rely on subtle semantics of the cp command itself ... about how it handles source specifications with or without a trailing / ... since I'm not sure those are stable, portable, and reliable beyond just GNU cp and I don't know if they'll continue to be so in the future).

Sending and receiving data over a network using TcpClient

Be warned - this is a very old and cumbersome "solution".

By the way, you can use serialization technology to send strings, numbers or any objects which are support serialization (most of .NET data-storing classes & structs are [Serializable]). There, you should at first send Int32-length in four bytes to the stream and then send binary-serialized (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter) data into it.

On the other side or the connection (on both sides actually) you definetly should have a byte[] buffer which u will append and trim-left at runtime when data is coming.

Something like that I am using:

namespace System.Net.Sockets
{
    public class TcpConnection : IDisposable
    {
        public event EvHandler<TcpConnection, DataArrivedEventArgs> DataArrive = delegate { };
        public event EvHandler<TcpConnection> Drop = delegate { };

        private const int IntSize = 4;
        private const int BufferSize = 8 * 1024;

        private static readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
        private readonly TcpClient _tcpClient;
        private readonly object _droppedRoot = new object();
        private bool _dropped;
        private byte[] _incomingData = new byte[0];
        private Nullable<int> _objectDataLength;

        public TcpClient TcpClient { get { return _tcpClient; } }
        public bool Dropped { get { return _dropped; } }

        private void DropConnection()
        {
            lock (_droppedRoot)
            {
                if (Dropped)
                    return;

                _dropped = true;
            }

            _tcpClient.Close();
            _syncContext.Post(delegate { Drop(this); }, null);
        }

        public void SendData(PCmds pCmd) { SendDataInternal(new object[] { pCmd }); }
        public void SendData(PCmds pCmd, object[] datas)
        {
            datas.ThrowIfNull();
            SendDataInternal(new object[] { pCmd }.Append(datas));
        }
        private void SendDataInternal(object data)
        {
            if (Dropped)
                return;

            byte[] bytedata;

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();

                try { bf.Serialize(ms, data); }
                catch { return; }

                bytedata = ms.ToArray();
            }

            try
            {
                lock (_tcpClient)
                {
                    TcpClient.Client.BeginSend(BitConverter.GetBytes(bytedata.Length), 0, IntSize, SocketFlags.None, EndSend, null);
                    TcpClient.Client.BeginSend(bytedata, 0, bytedata.Length, SocketFlags.None, EndSend, null);
                }
            }
            catch { DropConnection(); }
        }
        private void EndSend(IAsyncResult ar)
        {
            try { TcpClient.Client.EndSend(ar); }
            catch { }
        }

        public TcpConnection(TcpClient tcpClient)
        {
            _tcpClient = tcpClient;
            StartReceive();
        }

        private void StartReceive()
        {
            byte[] buffer = new byte[BufferSize];

            try
            {
                _tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, DataReceived, buffer);
            }
            catch { DropConnection(); }
        }

        private void DataReceived(IAsyncResult ar)
        {
            if (Dropped)
                return;

            int dataRead;

            try { dataRead = TcpClient.Client.EndReceive(ar); }
            catch
            {
                DropConnection();
                return;
            }

            if (dataRead == 0)
            {
                DropConnection();
                return;
            }

            byte[] byteData = ar.AsyncState as byte[];
            _incomingData = _incomingData.Append(byteData.Take(dataRead).ToArray());
            bool exitWhile = false;

            while (exitWhile)
            {
                exitWhile = true;

                if (_objectDataLength.HasValue)
                {
                    if (_incomingData.Length >= _objectDataLength.Value)
                    {
                        object data;
                        BinaryFormatter bf = new BinaryFormatter();

                        using (MemoryStream ms = new MemoryStream(_incomingData, 0, _objectDataLength.Value))
                            try { data = bf.Deserialize(ms); }
                            catch
                            {
                                SendData(PCmds.Disconnect);
                                DropConnection();
                                return;
                            }

                        _syncContext.Post(delegate(object T)
                        {
                            try { DataArrive(this, new DataArrivedEventArgs(T)); }
                            catch { DropConnection(); }
                        }, data);

                        _incomingData = _incomingData.TrimLeft(_objectDataLength.Value);
                        _objectDataLength = null;
                        exitWhile = false;
                    }
                }
                else
                    if (_incomingData.Length >= IntSize)
                    {
                        _objectDataLength = BitConverter.ToInt32(_incomingData.TakeLeft(IntSize), 0);
                        _incomingData = _incomingData.TrimLeft(IntSize);
                        exitWhile = false;
                    }
            }
            StartReceive();
        }


        public void Dispose() { DropConnection(); }
    }
}

That is just an example, you should edit it for your use.

IndentationError expected an indented block

If you are using a mac and sublime text 3, this is what you do.

Go to your /Packages/User/ and create a file called Python.sublime-settings.

Typically /Packages/User is inside your ~/Library/Application Support/Sublime Text 3/Packages/User/Python.sublime-settings if you are using mac os x.

Then you put this in the Python.sublime-settings.

{
    "tab_size": 4,
    "translate_tabs_to_spaces": false
}

Credit goes to Mark Byer's answer, sublime text 3 docs and python style guide.

This answer is mostly for readers who had the same issue and stumble upon this and are using sublime text 3 on Mac OS X.

How can I stream webcam video with C#?

You could just use VideoLAN. VideoLAN will work as a server (or you can wrap your own C# application around it for more control). There are also .NET wrappers for the viewer that you can use and thus embed in your C# client.

Random integer in VB.NET

As has been pointed out many times, the suggestion to write code like this is problematic:

Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
    Dim Generator As System.Random = New System.Random()
    Return Generator.Next(Min, Max)
End Function

The reason is that the constructor for the Random class provides a default seed based on the system's clock. On most systems, this has limited granularity -- somewhere in the vicinity of 20 ms. So if you write the following code, you're going to get the same number a bunch of times in a row:

Dim randoms(1000) As Integer
For i As Integer = 0 to randoms.Length - 1
    randoms(i) = GetRandom(1, 100)
Next

The following code addresses this issue:

Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
    ' by making Generator static, we preserve the same instance '
    ' (i.e., do not create new instances with the same seed over and over) '
    ' between calls '
    Static Generator As System.Random = New System.Random()
    Return Generator.Next(Min, Max)
End Function

I threw together a simple program using both methods to generate 25 random integers between 1 and 100. Here's the output:

Non-static: 70 Static: 70
Non-static: 70 Static: 46
Non-static: 70 Static: 58
Non-static: 70 Static: 19
Non-static: 70 Static: 79
Non-static: 70 Static: 24
Non-static: 70 Static: 14
Non-static: 70 Static: 46
Non-static: 70 Static: 82
Non-static: 70 Static: 31
Non-static: 70 Static: 25
Non-static: 70 Static: 8
Non-static: 70 Static: 76
Non-static: 70 Static: 74
Non-static: 70 Static: 84
Non-static: 70 Static: 39
Non-static: 70 Static: 30
Non-static: 70 Static: 55
Non-static: 70 Static: 49
Non-static: 70 Static: 21
Non-static: 70 Static: 99
Non-static: 70 Static: 15
Non-static: 70 Static: 83
Non-static: 70 Static: 26
Non-static: 70 Static: 16
Non-static: 70 Static: 75

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

How do Python functions handle the types of the parameters that you pass in?

Python doesn't care what you pass in to its functions. When you call my_func(a,b), the param1 and param2 variables will then hold the values of a and b. Python doesn't know that you are calling the function with the proper types, and expects the programmer to take care of that. If your function will be called with different types of parameters, you can wrap code accessing them with try/except blocks and evaluate the parameters in whatever way you want.

notifyDataSetChange not working from custom adapter

I had the same problem using ListAdapter

I let Android Studio implement methods for me and this is what I got:

public class CustomAdapter implements ListAdapter {
    ...
    @Override
    public void registerDataSetObserver(DataSetObserver observer) {

    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {

    }
    ...
}

The problem is that these methods do not call super implementations so notifyDataSetChange is never called.

Either remove these overrides manually or add super calls and it should work again.

@Override
public void registerDataSetObserver(DataSetObserver observer) {
    super.registerDataSetObserver(observer);
}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    super.unregisterDataSetObserver(observer);
}

Border for an Image view in Android?

Following is my simplest solution to this lengthy trouble.

<FrameLayout
    android:layout_width="112dp"
    android:layout_height="112dp"
    android:layout_marginLeft="16dp" <!-- May vary according to your needs -->
    android:layout_marginRight="16dp" <!-- May vary according to your needs -->
    android:layout_centerVertical="true">
    <!-- following imageView acts as the boarder which sitting in the background of our main container ImageView -->
    <ImageView
        android:layout_width="112dp"
        android:layout_height="112dp"
        android:background="#000"/>
    <!-- following imageView holds the image as the container to our image -->
    <!-- layout_margin defines the width of our boarder, here it's 1dp -->
    <ImageView
        android:layout_width="110dp"
        android:layout_height="110dp"
        android:layout_margin="1dp"
        android:id="@+id/itemImageThumbnailImgVw"
        android:src="@drawable/banana"
        android:background="#FFF"/> </FrameLayout>

In the following answer I've explained it well enough, please have a look at that too!

I hope this will be helpful to someone else out there!

An efficient way to Base64 encode a byte array?

    public void ProcessRequest(HttpContext context)
    {
        string constring = ConfigurationManager.ConnectionStrings["SQL_Connection_String"].ConnectionString;
        SqlConnection conn = new SqlConnection(constring);
        conn.Open();
        SqlCommand cmd = new SqlCommand("select image1 from TestGo where TestId=1", conn);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        MemoryStream str = new MemoryStream();

        context.Response.Clear();
        Byte[] bytes = (Byte[])dr[0];
        string d = System.Text.Encoding.Default.GetString(bytes);
        byte[] bytes2 = Convert.FromBase64String(d);
        //context.Response.Write(d);
        Image img = Image.FromStream(new MemoryStream(bytes2));
        img.Save(context.Response.OutputStream, ImageFormat.Png);
        context.Response.Flush();
        str.WriteTo(context.Response.OutputStream);
        str.Dispose();
        str.Close();
        conn.Close();
        context.Response.End();
    }

calling a java servlet from javascript

var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
  window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

For any case set overflow-x to hidden and I prefer to set max-height in order to limit the expansion of the height of the div. Your code should looks like this:

overflow-y: scroll;
overflow-x: hidden;
max-height: 450px;

C++ compile error: has initializer but incomplete type

` Please include either of these:

`#include<sstream>`

using std::istringstream; 

Jquery to get the id of selected value from dropdown

First set a custom attribute into your option for example nameid (you can set non-standardized attribute of an HTML element, it's allowed):

'<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'

then you can easily get attribute value using jquery .attr() :

$('option:selected').attr("nameid")

For Example:

<select id="jobSel" class="longcombo" onchange="GetNameId">
    <option nameid="32" value="1">test1</option>
    <option nameid="67" value="1">test2</option>
    <option nameid="45" value="1">test3</option>    
    </select>    

Jquery:

function GetNameId(){
   alert($('#jobSel option:selected').attr("nameid"));
}

How do I change the color of radio buttons?

you can use the checkbox hack as explained in css tricks

http://css-tricks.com/the-checkbox-hack/

working example of radio button:

http://codepen.io/Angelata/pen/Eypnq

input[type=radio]:checked ~ .check {}
input[type=radio]:checked ~ .check .inside{}

Works in IE9+, Firefox 3.5+, Safari 1.3+, Opera 6+, Chrome anything.

KeyListener, keyPressed versus keyTyped

You should use keyPressed if you want an immediate effect, and keyReleased if you want the effect after you release the key. You cannot use keyTyped because F5 is not a character. keyTyped is activated only when an character is pressed.

Create table with jQuery - append

this is most better

html

<div id="here_table"> </div>

jQuery

$('#here_table').append( '<table>' );

for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' +  i + '</tr>' );

    for(ii=0;ii<3;ii++)
    {
    $('#here_table').append( '<td>' + 'result' +  i + '</tr>' );
    }
}

$('#here_table').append(  '</table>' );

Spring application context external properties?

You can use file prefix to load the external application context file some thing like this

  <context:property-placeholder location="file:///C:/Applications/external/external.properties"/>

difference between System.out.println() and System.err.println()

System.out.println("wassup"); refers to when you have to output a certain result pertaining to the proper input given by the user whereas System.err.println("duh, that's wrong); is a reference to show that the input provided is wrong or there is some other error.

Most of the IDEs show this in red color (System.err.print).

scale Image in an UIButton to AspectFit?

Swift 5.0

 myButton2.contentMode = .scaleAspectFit
 myButton2.contentHorizontalAlignment = .fill
 myButton2.contentVerticalAlignment = .fill

How do I read the file content from the Internal storage - Android App

To read a file from internal storage:

Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read(). Then close the stream with close().

code::

StringBuilder sb = new StringBuilder();
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();
        } catch(OutOfMemoryError om){
            om.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }
        String result = sb.toString();

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

First, you have to learn to think like a Language Lawyer.

The C++ specification does not make reference to any particular compiler, operating system, or CPU. It makes reference to an abstract machine that is a generalization of actual systems. In the Language Lawyer world, the job of the programmer is to write code for the abstract machine; the job of the compiler is to actualize that code on a concrete machine. By coding rigidly to the spec, you can be certain that your code will compile and run without modification on any system with a compliant C++ compiler, whether today or 50 years from now.

The abstract machine in the C++98/C++03 specification is fundamentally single-threaded. So it is not possible to write multi-threaded C++ code that is "fully portable" with respect to the spec. The spec does not even say anything about the atomicity of memory loads and stores or the order in which loads and stores might happen, never mind things like mutexes.

Of course, you can write multi-threaded code in practice for particular concrete systems – like pthreads or Windows. But there is no standard way to write multi-threaded code for C++98/C++03.

The abstract machine in C++11 is multi-threaded by design. It also has a well-defined memory model; that is, it says what the compiler may and may not do when it comes to accessing memory.

Consider the following example, where a pair of global variables are accessed concurrently by two threads:

           Global
           int x, y;

Thread 1            Thread 2
x = 17;             cout << y << " ";
y = 37;             cout << x << endl;

What might Thread 2 output?

Under C++98/C++03, this is not even Undefined Behavior; the question itself is meaningless because the standard does not contemplate anything called a "thread".

Under C++11, the result is Undefined Behavior, because loads and stores need not be atomic in general. Which may not seem like much of an improvement... And by itself, it's not.

But with C++11, you can write this:

           Global
           atomic<int> x, y;

Thread 1                 Thread 2
x.store(17);             cout << y.load() << " ";
y.store(37);             cout << x.load() << endl;

Now things get much more interesting. First of all, the behavior here is defined. Thread 2 could now print 0 0 (if it runs before Thread 1), 37 17 (if it runs after Thread 1), or 0 17 (if it runs after Thread 1 assigns to x but before it assigns to y).

What it cannot print is 37 0, because the default mode for atomic loads/stores in C++11 is to enforce sequential consistency. This just means all loads and stores must be "as if" they happened in the order you wrote them within each thread, while operations among threads can be interleaved however the system likes. So the default behavior of atomics provides both atomicity and ordering for loads and stores.

Now, on a modern CPU, ensuring sequential consistency can be expensive. In particular, the compiler is likely to emit full-blown memory barriers between every access here. But if your algorithm can tolerate out-of-order loads and stores; i.e., if it requires atomicity but not ordering; i.e., if it can tolerate 37 0 as output from this program, then you can write this:

           Global
           atomic<int> x, y;

Thread 1                            Thread 2
x.store(17,memory_order_relaxed);   cout << y.load(memory_order_relaxed) << " ";
y.store(37,memory_order_relaxed);   cout << x.load(memory_order_relaxed) << endl;

The more modern the CPU, the more likely this is to be faster than the previous example.

Finally, if you just need to keep particular loads and stores in order, you can write:

           Global
           atomic<int> x, y;

Thread 1                            Thread 2
x.store(17,memory_order_release);   cout << y.load(memory_order_acquire) << " ";
y.store(37,memory_order_release);   cout << x.load(memory_order_acquire) << endl;

This takes us back to the ordered loads and stores – so 37 0 is no longer a possible output – but it does so with minimal overhead. (In this trivial example, the result is the same as full-blown sequential consistency; in a larger program, it would not be.)

Of course, if the only outputs you want to see are 0 0 or 37 17, you can just wrap a mutex around the original code. But if you have read this far, I bet you already know how that works, and this answer is already longer than I intended :-).

So, bottom line. Mutexes are great, and C++11 standardizes them. But sometimes for performance reasons you want lower-level primitives (e.g., the classic double-checked locking pattern). The new standard provides high-level gadgets like mutexes and condition variables, and it also provides low-level gadgets like atomic types and the various flavors of memory barrier. So now you can write sophisticated, high-performance concurrent routines entirely within the language specified by the standard, and you can be certain your code will compile and run unchanged on both today's systems and tomorrow's.

Although to be frank, unless you are an expert and working on some serious low-level code, you should probably stick to mutexes and condition variables. That's what I intend to do.

For more on this stuff, see this blog post.

Use awk to find average of a column

Your specific error is with line 11:

awk 'BEGIN{sum+=$2}'

This is a line where awk is invoked, and its BEGIN block is specified - but you are already within a awk script, so you do not need to specify awk. Also you want to run sum+=$2 on each line of input, so you do not want it within a BEGIN block. Hence the line should simply read:

sum+=$2

You also do not need the lines:

x=sum
read name

the first just creates a synonym to sum named x and I'm not sure what the second does, but neither are needed.

This would make your awk script:

#!/bin/awk

### This script currently prints the total number of rows processed.
### You must edit this script to print the average of the 2nd column
### instead of the number of rows.

# This block of code is executed for each line in the file
{
    sum+=$2
    # The script should NOT print out a value for each line
}
# The END block is processed after the last line is read
END {
    # NR is a variable equal to the number of rows in the file
    print "Average: " sum/ NR
    # Change this to print the Average instead of just the number of rows
}

Jonathan Leffler's answer gives the awk one liner which represents the same fixed code, with the addition of checking that there are at least 1 lines of input (this stops any divide by zero error). If

(WAMP/XAMP) send Mail using SMTP localhost

I prefer using PHPMailer script to send emails from localhost as it lets me use my Gmail account as SMTP. You can find the PHPMailer from http://phpmailer.worxware.com/ . Help regarding how to use gmail as SMTP or any other SMTP can be found at http://www.mittalpatel.co.in/php_send_mail_from_localhost_using_gmail_smtp . Hope this helps!

ASP.NET - How to write some html in the page? With Response.Write?

You can go with the literal control of ASP.net or you can use panels or the purpose.

Use '=' or LIKE to compare strings in SQL?

LIKE and the equality operator have different purposes, they don't do the same thing:
= is much faster, whereas LIKE can interpret wildcards. Use = wherever you can and LIKE wherever you must.

SELECT * FROM user WHERE login LIKE 'Test%';

Sample matches:

TestUser1
TestUser2
TestU
Test

python how to pad numpy array with zeros

I know I'm a bit late to this, but in case you wanted to perform relative padding (aka edge padding), here's how you can implement it. Note that the very first instance of assignment results in zero-padding, so you can use this for both zero-padding and relative padding (this is where you copy the edge values of the original array into the padded array).

def replicate_padding(arr):
    """Perform replicate padding on a numpy array."""
    new_pad_shape = tuple(np.array(arr.shape) + 2) # 2 indicates the width + height to change, a (512, 512) image --> (514, 514) padded image.
    padded_array = np.zeros(new_pad_shape) #create an array of zeros with new dimensions
    
    # perform replication
    padded_array[1:-1,1:-1] = arr        # result will be zero-pad
    padded_array[0,1:-1] = arr[0]        # perform edge pad for top row
    padded_array[-1, 1:-1] = arr[-1]     # edge pad for bottom row
    padded_array.T[0, 1:-1] = arr.T[0]   # edge pad for first column
    padded_array.T[-1, 1:-1] = arr.T[-1] # edge pad for last column
    
    #at this point, all values except for the 4 corners should have been replicated
    padded_array[0][0] = arr[0][0]     # top left corner
    padded_array[-1][0] = arr[-1][0]   # bottom left corner
    padded_array[0][-1] = arr[0][-1]   # top right corner 
    padded_array[-1][-1] = arr[-1][-1] # bottom right corner

    return padded_array

Complexity Analysis:

The optimal solution for this is numpy's pad method. After averaging for 5 runs, np.pad with relative padding is only 8% better than the function defined above. This shows that this is fairly an optimal method for relative and zero-padding padding.


#My method, replicate_padding
start = time.time()
padded = replicate_padding(input_image)
end = time.time()
delta0 = end - start

#np.pad with edge padding
start = time.time()
padded = np.pad(input_image, 1, mode='edge')
end = time.time()
delta = end - start


print(delta0) # np Output: 0.0008790493011474609 
print(delta)  # My Output: 0.0008130073547363281
print(100*((delta0-delta)/delta)) # Percent difference: 8.12316715542522%

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

You can use IN operator as below

select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)

iframe to Only Show a Certain Part of the Page

Somehow I fiddled around and some how I got it to work:

<iframe src="http://www.example.com#inside" width="100%" height="100%" align="center" ></iframe>

I think this is the first time this code has been posted so share it

Set cURL to use local virtual hosts

EDIT: While this is currently accepted answer, readers might find this other answer by user John Hart more adapted to their needs. It uses an option which, according to user Ken, was introduced in version 7.21.3 (which was released in December 2010, i.e. after this initial answer).


In your edited question, you're using the URL as the host name, whereas it needs to be the host name only.

Try:

curl -H 'Host: project1.loc' http://127.0.0.1/something

where project1.loc is just the host name and 127.0.0.1 is the target IP address.

(If you're using curl from a library and not on the command line, make sure you don't put http:// in the Host header.)

TCP vs UDP on video stream

Usually a video stream is somewhat fault tolerant. So if some packages get lost (due to some router along the way being overloaded, for example), then it will still be able to display the content, but with reduced quality.

If your live stream was using TCP/IP, then it would be forced to wait for those dropped packages before it could continue processing newer data.

That's doubly bad:

  • old data be re-transmitted (that's probably for a frame that was already displayed and therefore worthless) and
  • new data can't arrive until after old data was re-transmitted

If your goal is to display as up-to-date information as possible (and for a live-stream you usually want to be up-to-date, even if your frames look a bit worse), then TCP will work against you.

For a recorded stream the situation is slightly different: you'll probably be buffering a lot more (possibly several minutes!) and would rather have data re-transmitted than have some artifacts due to lost packages. In this case TCP is a good match (this could still be implemented in UDP, of course, but TCP doesn't have as much drawbacks as for the live stream case).

GROUP_CONCAT ORDER BY

Try

SELECT li.clientid, group_concat(li.views ORDER BY li.views) AS views,
       group_concat(li.percentage ORDER BY li.percentage) 
FROM table_views li 
GROUP BY client_id

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function%5Fgroup-concat

Reasons for using the set.seed function

basically set.seed() function will help to reuse the same set of random variables , which we may need in future to again evaluate particular task again with same random varibales

we just need to declare it before using any random numbers generating function.

Checking for empty queryset in Django

You could also use this:

if(not(orgs)): #if orgs is empty else: #if orgs is not empty

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:

sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh

open new terminal and validate environment is clean from old RVM settings (should be no output):

env | grep rvm

if there was output, try to open new terminal, if it does not help then restart your computer.

install RVM:

\curl -L https://get.rvm.io | 
  bash -s stable --ruby --autolibs=enable --auto-dotfiles

If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

Validate email with a regex in jQuery

This regex can help you to check your email-address according to all the criteria which gmail.com used.

var re = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;

var emailFormat = re.test($("#email").val()); // This return result in Boolean type

if (emailFormat) {}

Razor View throwing "The name 'model' does not exist in the current context"

You are likely to use in the code a variable named model.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

you have to use echo before base_url() function. otherwise it woudn't print the base url.

How to put multiple statements in one line?

I recommend not doing this...

What you are describing is not a comprehension.

PEP 8 Style Guide for Python Code, which I do recommend, has this to say on compound statements:

  • Compound statements (multiple statements on the same line) are generally discouraged.

Yes:

      if foo == 'blah':
          do_blah_thing()
      do_one()
      do_two()
      do_three()

Rather not:

      if foo == 'blah': do_blah_thing()
      do_one(); do_two(); do_three()

Here is a sample comprehension to make the distinction:

>>> [i for i in xrange(10) if i == 9]
[9]

Can you split/explode a field in a MySQL query?

If you need get table from string with delimiters:

SET @str = 'function1;function2;function3;function4;aaa;bbbb;nnnnn';
SET @delimeter = ';';
SET @sql_statement = CONCAT('SELECT '''
                ,REPLACE(@str, @delimeter, ''' UNION ALL SELECT ''')
                ,'''');
SELECT @sql_statement;
SELECT 'function1' UNION ALL SELECT 'function2' UNION ALL SELECT 'function3' UNION ALL SELECT 'function4' UNION ALL SELECT 'aaa' UNION ALL SELECT 'bbbb' UNION ALL SELECT 'nnnnn'

How to convert timestamps to dates in Bash?

I have written a script that does this myself:

#!/bin/bash
LANG=C
if [ -z "$1" ]; then
    if [  "$(tty)" = "not a tty" ]; then
            p=`cat`;
    else
            echo "No timestamp given."
            exit
    fi
else
    p=$1
fi
echo $p | gawk '{ print strftime("%c", $0); }'

How to restart Postgresql

Try this as root (maybe you can use sudo or su):

/etc/init.d/postgresql restart

Without any argument the script also gives you a hint on how to restart a specific version

[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]

Similarly, in case you have it, you can also use the service tool:

[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]

Please, pay attention to the optional [version ...] trailing argument. That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.

Finally, in case you are running systemd, then you can use systemctl like this:

[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...

You can replace status with stop, start or restart as well as other actions. Please refer to the documentation for full details. In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12 and reload v13 you can run:

systemctl stop postgresql-12.service
systemctl reload postgresql-13.service

Thanks to @Jojo for pointing me to this very one. Finally Keep in mind that root permissions may be needed for non-informative tasks as in the other cases seen earlier.

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

Use another text editor

env EDITOR=nano crontab -e 

or

env EDITOR=code crontab -e 

std::queue iteration

you can save the original queue to a temporary queue. Then you simply do your normal pop on the temporary queue to go through the original one, for example:

queue tmp_q = original_q; //copy the original queue to the temporary queue

while (!tmp_q.empty())
{
    q_element = tmp_q.front();
    std::cout << q_element <<"\n";
    tmp_q.pop();
} 

At the end, the tmp_q will be empty but the original queue is untouched.

Set transparent background using ImageMagick and commandline prompt

Yep. Had this same problem too. Here's the command I ran and it worked perfectly: convert transparent-img1.png transparent-img2.png transparent-img3.png -channel Alpha favicon.ico

Find specific string in a text file with VBS script

Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:

Option Explicit

Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript


Main()

Sub Main()

Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false

Do until objInputFile.AtEndOfStream
    tmpStr = objInputFile.ReadLine
    If foundStrMatch(tmpStr)=true Then
        If foundFirstMatch = false Then
            index = getIndex(tmpStr)
            foundFirstMatch = true
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
        If index = getIndex(tmpStr) Then
            text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
        ElseIf index < getIndex(tmpStr) Then
            index = getIndex(tmpStr)
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
    Else
        text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
    End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub


Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
    textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
    textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function


Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
    getIndex = CInt(char1 & char2)
Else
    getIndex = CInt(char1)
End If
End Function

Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
    foundStrMatch = true
Else
    foundStrMatch = false
End If
End Function

This is the original txt file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

And this is the result I'm expecting

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

how to split the ng-repeat data with three columns using bootstrap

All of these answers seem massively over engineered.

By far the simplest method would be to set up the input divs in a col-md-4 column bootstrap, then bootstrap will automatically format it into 3 columns due to the 12 column nature of bootstrap:

<div class="col-md-12">
    <div class="control-group" ng-repeat="oneExt in configAddr.ext">
        <div class="col-md-4">
            <input type="text" name="macAdr{{$index}}"
                   id="macAddress" ng-model="oneExt.newValue" value="" />
        </div>
    </div>
</div>

Is there a method to generate a UUID with go language

For Windows, I did recently this:

// +build windows

package main

import (
    "syscall"
    "unsafe"
)

var (
    modrpcrt4 = syscall.NewLazyDLL("rpcrt4.dll")
    procUuidCreate = modrpcrt4.NewProc("UuidCreate")
)

const (
    RPC_S_OK = 0
)

func NewUuid() ([]byte, error) {
    var uuid [16]byte
    rc, _, e := syscall.Syscall(procUuidCreate.Addr(), 1,
             uintptr(unsafe.Pointer(&uuid[0])), 0, 0)
    if int(rc) != RPC_S_OK {
        if e != 0 {
            return nil, error(e)
        } else {
            return nil, syscall.EINVAL
        }
    }
    return uuid[:], nil
}

Eclipse Java Missing required source folder: 'src'

Right-Click Project --> Build Path --> Configure Build Path-->source-->(Select missing folder or path)-->Add Folder-->Apply-->Ok

Capture Signature using HTML5 and iPad

The options already listed are very good, however here a few more on this topic that I've researched and came across.

1) http://perfectionkills.com/exploring-canvas-drawing-techniques/
2) http://mcc.id.au/2010/signature.html
3) https://zipso.net/a-simple-touchscreen-sketchpad-using-javascript-and-html5/

And as always you may want to save the canvas to image:
http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/

good luck and happy signing

Android Button setOnClickListener Design

You can use array to handle several button click listener in android like this: here i am setting button click listener for n buttons by using array as:

Button btn[] = new Button[n]; 

NOTE: n is a constant positive integer

Code example:

//class androidMultipleButtonActions 
package a.b.c.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class androidMultipleButtonActions extends Activity implements OnClickListener{
    Button btn[] = new Button[3];

    public void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        btn[0] = (Button) findViewById(R.id.Button1);
        btn[1] = (Button) findViewById(R.id.Button2);
        btn[2] = (Button) findViewById(R.id.Button3);
        for(int i=0; i<3; i++){
            btn[i].setOnClickListener(this);
        }           
    }

    public void onClick(View v) {
        if(v == findViewById(R.id.Button1)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button2)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button3)){
            //do here what u wanna do.
        }
    }
}

Note: First write an main.xml file if u dont know how to write please mail to: [email protected]

How to append strings using sprintf?

A snprintfcat() wrapper for snprintf():

size_t 
snprintfcat(
    char* buf,
    size_t bufSize,
    char const* fmt,
    ...)
{
    size_t result;
    va_list args;
    size_t len = strnlen( buf, bufSize);

    va_start( args, fmt);
    result = vsnprintf( buf + len, bufSize - len, fmt, args);
    va_end( args);

    return result + len;
}

How can I do factory reset using adb in android?

Warning

From @sidharth: "caused my lava iris alfa to go into a bootloop :("


For my Motorola Nexus 6 running Android Marshmallow 6.0.1 I did:

adb devices       # Check the phone is running
adb reboot bootloader
# Wait a few seconds
fastboot devices  # Check the phone is in bootloader
fastboot -w       # Wipe user data

Storing images in SQL Server?

I fell into this dilemma once, and researched quite a bit on google for opinions. What I found was that indeed many see saving images to disk better for larger images, while mySQL allows for easier access, specially from languages like PHP.

I found a similar question

MySQL BLOB vs File for Storing Small PNG Images?

My final verdict was that for things such as a profile picture, just a small square image that needs to be there per user, mySQL would be better than storing a bunch of thumbs in the hdd, while for photo albums and things like that, folders/image files are better.

Hope it helps

How can I find the number of days between two Date objects in Ruby?

Subtract the beginning date from the end date:

endDate - beginDate 

Java Ordered Map

I have used Simple Hash map, linked list and Collections to sort a Map by values.

import java.util.*;
import java.util.Map.*;
public class Solution {

    public static void main(String[] args) {
        // create a simple hash map and insert some key-value pairs into it
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("Python", 3);
        map.put("C", 0);
        map.put("JavaScript", 4);
        map.put("C++", 1);
        map.put("Golang", 5);
        map.put("Java", 2);
        // Create a linked list from the above map entries
        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
        // sort the linked list using Collections.sort()
        Collections.sort(list, new Comparator<Entry<String, Integer>>(){
        @Override
         public int compare(Entry<String, Integer> m1, Entry<String, Integer> m2) {
        return m1.getValue().compareTo(m2.getValue());
        }
      });
      for(Entry<String, Integer> value: list) {
         System.out.println(value);
     }
   }
}

The output is:

C=0
C++=1
Java=2
Python=3
JavaScript=4
Golang=5

Generate a random date between two other dates

Conceptually it's quite simple. Depending on which language you're using you will be able to convert those dates into some reference 32 or 64 bit integer, typically representing seconds since epoch (1 January 1970) otherwise known as "Unix time" or milliseconds since some other arbitrary date. Simply generate a random 32 or 64 bit integer between those two values. This should be a one liner in any language.

On some platforms you can generate a time as a double (date is the integer part, time is the fractional part is one implementation). The same principle applies except you're dealing with single or double precision floating point numbers ("floats" or "doubles" in C, Java and other languages). Subtract the difference, multiply by random number (0 <= r <= 1), add to start time and done.

Merging 2 branches together in GIT

merge is used to bring two (or more) branches together.

a little example:

# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"

# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"

# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"

so now there are three separate branches (namely A B and C) with different heads

to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:

# create an octopus merge
$ git merge B C

your history will then look something like this:

…-o-o-x-------A
      |\     /|
      | B---/ |
       \     /
        C---/

if you want to merge across repository/computer borders, have a look at git pull command, e.g. from the pc with branch A (this example will create two new commits):

# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C

How to view the stored procedure code in SQL Server Management Studio

Use this query:

SELECT object_definition(object_id) AS [Proc Definition]
FROM sys.objects 
WHERE type='P'

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

I guess this document might serve as a not so short introduction : n3055

The whole massacre began with the move semantics. Once we have expressions that can be moved and not copied, suddenly easy to grasp rules demanded distinction between expressions that can be moved, and in which direction.

From what I guess based on the draft, the r/l value distinction stays the same, only in the context of moving things get messy.

Are they needed? Probably not if we wish to forfeit the new features. But to allow better optimization we should probably embrace them.

Quoting n3055:

  • An lvalue (so-called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object. [Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue.]
  • An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references. [Example: The result of calling a function whose return type is an rvalue reference is an xvalue.]
  • A glvalue (“generalized” lvalue) is an lvalue or an xvalue.
  • An rvalue (so-called, historically, because rvalues could appear on the right-hand side of an assignment expression) is an xvalue, a temporary object or subobject thereof, or a value that is not associated with an object.
  • A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [Example: The result of calling a function whose return type is not a reference is a prvalue]

The document in question is a great reference for this question, because it shows the exact changes in the standard that have happened as a result of the introduction of the new nomenclature.

Sending Multipart File as POST parameters with RestTemplate requests

I had this issue and found a much simpler solution than using a ByteArrayResource.

Simply do

public void loadInvoices(MultipartFile invoices, String channel) throws IOException {

    init();

    Resource invoicesResource = invoices.getResource();

    LinkedMultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("file", invoicesResource);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
    httpHeaders.set("channel", channel);

    HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parts, httpHeaders);

    String url = String.format("%s/rest/inbound/invoices/upload", baseUrl);

    restTemplate.postForEntity(url, httpEntity, JobData.class);
}

It works, and no messing around with the file system or byte arrays.

Twitter Bootstrap 3: how to use media queries?

keep in mind that avoiding text scaling is the main reason responsive layouts exist. the entire logic behind responsive sites is to create functional layouts that effectively display your content so its easily readable and usable on multiple screen sizes.

Although It is necessary to scale text in some cases, be careful not to miniaturise your site and miss the point.

heres an example anyway.

@media(min-width:1200px){

    h1 {font-size:34px}

}
@media(min-width:992px){

    h1 {font-size:32px}

}
@media(min-width:768px){

    h1 {font-size:28px}

}
@media(max-width:767px){

    h1 {font-size:26px}

}

Also keep in mind the 480 viewport has been dropped in bootstrap 3.

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

Parsing PDF files (especially with tables) with PDFBox

ObjectExtractor oe = new ObjectExtractor(document);

SpreadsheetExtractionAlgorithm sea = new SpreadsheetExtractionAlgorithm(); // Tabula algo.

Page page = oe.extract(1); // extract only the first page

for (int y = 0; y < sea.extract(page).size(); y++) {
  System.out.println("table: " + y);
  Table table = sea.extract(page).get(y);

  for (int i = 0; i < table.getColCount(); i++) {
    for (int x = 0; x < table.getRowCount(); x++) {
      System.out.println("col:" + i + "/lin:x" + x + " >>" + table.getCell(x, i).getText());
    }
  }
}

Resource from src/main/resources not found after building with maven

I think assembly plugin puts the file on class path. The location will be different in in the JAR than you see on disk. Unpack the resulting JAR and look where the file is located there.

Why not inherit from List<T>?

Wow, your post has an entire slew of questions and points. Most of the reasoning you get from Microsoft is exactly on point. Let's start with everything about List<T>

  • List<T> is highly optimized. Its main usage is to be used as a private member of an object.
  • Microsoft did not seal it because sometimes you might want to create a class that has a friendlier name: class MyList<T, TX> : List<CustomObject<T, Something<TX>> { ... }. Now it's as easy as doing var list = new MyList<int, string>();.
  • CA1002: Do not expose generic lists: Basically, even if you plan to use this app as the sole developer, it's worthwhile to develop with good coding practices, so they become instilled into you and second nature. You are still allowed to expose the list as an IList<T> if you need any consumer to have an indexed list. This lets you change the implementation within a class later on.
  • Microsoft made Collection<T> very generic because it is a generic concept... the name says it all; it is just a collection. There are more precise versions such as SortedCollection<T>, ObservableCollection<T>, ReadOnlyCollection<T>, etc. each of which implement IList<T> but not List<T>.
  • Collection<T> allows for members (i.e. Add, Remove, etc.) to be overridden because they are virtual. List<T> does not.
  • The last part of your question is spot on. A Football team is more than just a list of players, so it should be a class that contains that list of players. Think Composition vs Inheritance. A Football team has a list of players (a roster), it isn't a list of players.

If I were writing this code, the class would probably look something like so:

public class FootballTeam
{
    // Football team rosters are generally 53 total players.
    private readonly List<T> _roster = new List<T>(53);

    public IList<T> Roster
    {
        get { return _roster; }
    }

    // Yes. I used LINQ here. This is so I don't have to worry about
    // _roster.Length vs _roster.Count vs anything else.
    public int PlayerCount
    {
        get { return _roster.Count(); }
    }

    // Any additional members you want to expose/wrap.
}

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
   Forms!FormA.ToDoOnLoad
End Sub

Form A:

Public Sub Form_Load()
    ToDoOnLoad
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub

String escape into XML

Another take based on John Skeet's answer that doesn't return the tags:

void Main()
{
    XmlString("Brackets & stuff <> and \"quotes\"").Dump();
}

public string XmlString(string text)
{
    return new XElement("t", text).LastNode.ToString();
} 

This returns just the value passed in, in XML encoded format:

Brackets &amp; stuff &lt;&gt; and "quotes"

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

Capture HTML Canvas as gif/jpg/png/pdf?

if you want to emebed the canvas you can use this snippet

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id=canvas width=200 height=200></canvas>
    <iframe id='img' width=200 height=200></iframe>
    <script>
        window.onload = function() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            context.fillStyle = "green";
            context.fillRect(50, 50, 100, 100);
            document.getElementById('img').src = canvas.toDataURL("image/jpeg");
            console.log(canvas.toDataURL("image/jpeg"));
        }
    </script>
</body>
</html>

How to store token in Local or Session Storage in Angular 2?

import { Injectable,OpaqueToken } from '@angular/core'; export const localStorage = new OpaqueToken('localStorage');

Place these lines in the top of the file, it should resolve the issue.

C# List<> Sort by x then y

Do keep in mind that you don't need a stable sort if you compare all members. The 2.0 solution, as requested, can look like this:

 public void SortList() {
     MyList.Sort(delegate(MyClass a, MyClass b)
     {
         int xdiff = a.x.CompareTo(b.x);
         if (xdiff != 0) return xdiff;
         else return a.y.CompareTo(b.y);
     });
 }

Do note that this 2.0 solution is still preferable over the popular 3.5 Linq solution, it performs an in-place sort and does not have the O(n) storage requirement of the Linq approach. Unless you prefer the original List object to be untouched of course.

ALTER TABLE on dependent column

If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:

ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]

For more info see the comments by the brilliant Aaron Bertrand on this answer.

jQuery get html of container including the container itself

var x = $('#container').get(0).outerHTML;

UPDATE : This is now supported by Firefox as of FireFox 11 (March 2012)

As others have pointed out, this will not work in FireFox. If you need it to work in FireFox, then you might want to take a look at the answer to this question : In jQuery, are there any function that similar to html() or text() but return the whole content of matched component?

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

I'm using vs2012 and i think the update KB2781514 changed some setting. All my System.Web.Http in my MVC4 project changed to false and i keeping received this message. I had changed the All file in this project in publish property but its not working. Finally I have to change Copy Local = true one by one and solved this problem.

Returning the product of a list

import operator
reduce(operator.mul, list, 1)

MySql Table Insert if not exist otherwise update

Try using this:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...

The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...

File path for project files?

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")

base directory + your filename

How to copy a folder via cmd?

xcopy  "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i

Probably the problem is the space.Try with quotes.

How to pass a variable to the SelectCommand of a SqlDataSource?

Try this instead, remove the SelectCommand property and SelectParameters:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:itematConnectionString %>">

Then in the code behind do this:

SqlDataSource1.SelectParameters.Add("userId", userId.ToString());

SqlDataSource1.SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"

While this worked for me, the following code also works:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
    SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"></asp:SqlDataSource>


SqlDataSource1.SelectParameters.Add("userid", DbType.Guid, userId.ToString());

How to install PHP mbstring on CentOS 6.2

I have experienced the same issue before. In my case, I needed to install php-mbstring extension on GoDaddy VPS server. None of above solutions did work for me.

What I've found is to install PHP extensions using WHM (Web Hosting Manager) of GoDaddy. Anyone who use GoDaddy VPS server can access this page with the following address.

http://{Your_Server_IP_Address}:2087

On this page, you can easily find Easy Apache software that can help you to install/upgrade php components and extensions. You can select currently installed profile and customize and then provision the profile. Everything with Easy Apache is explanatory.

I remember that I did very similar things for HostGator server, but I don't remember how actually I did for profile update.

Edit: When you have got the server which supports Web Hosting Manager, then you can add/update/remove php extensions on WHM. On godaddy servers, it's even recommended to update PHP ini settings on WHM.

Accurate way to measure execution times of php scripts

You can use the microtime function for this. From the documentation:

microtime — Return current Unix timestamp with microseconds


If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Example usage:

$start = microtime(true);
while (...) {

}
$time_elapsed_secs = microtime(true) - $start;

Different color for each bar in a bar chart; ChartJS

If you're not able to use NewChart.js you just need to change the way to set the color using array instead. Find the helper iteration inside Chart.js:

Replace this line:

fillColor : dataset.fillColor,

For this one:

fillColor : dataset.fillColor[index],

The resulting code:

//Iterate through each of the datasets, and build this into a property of the chart
  helpers.each(data.datasets,function(dataset,datasetIndex){

    var datasetObject = {
      label : dataset.label || null,
      fillColor : dataset.fillColor,
      strokeColor : dataset.strokeColor,
      bars : []
    };

    this.datasets.push(datasetObject);

    helpers.each(dataset.data,function(dataPoint,index){
      //Add a new point for each piece of data, passing any required data to draw.
      datasetObject.bars.push(new this.BarClass({
        value : dataPoint,
        label : data.labels[index],
        datasetLabel: dataset.label,
        strokeColor : dataset.strokeColor,
        //Replace this -> fillColor : dataset.fillColor,
        // Whith the following:
        fillColor : dataset.fillColor[index],
        highlightFill : dataset.highlightFill || dataset.fillColor,
        highlightStroke : dataset.highlightStroke || dataset.strokeColor
      }));
    },this);

  },this);

And in your js:

datasets: [
                {
                  label: "My First dataset",
                  fillColor: ["rgba(205,64,64,0.5)", "rgba(220,220,220,0.5)", "rgba(24,178,235,0.5)", "rgba(220,220,220,0.5)"],
                  strokeColor: "rgba(220,220,220,0.8)",
                  highlightFill: "rgba(220,220,220,0.75)",
                  highlightStroke: "rgba(220,220,220,1)",
                  data: [2000, 1500, 1750, 50]
                }
              ]

How to set alignment center in TextBox in ASP.NET?

You can use:

<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>

Or this:

textbox.Style["text-align"] = "center"; //right, left

What is a deadlock?

A deadlock occurs when there is a circular chain of threads or processes which each hold a locked resource and are trying to lock a resource held by the next element in the chain. For example, two threads that hold respectively lock A and lock B, and are both trying to acquire the other lock.

Count how many rows have the same value

If you want to have the result for all values of NUM:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
GROUP BY `NUM`

Or just for one specific:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
WHERE `NUM`=1

HTML5 Email Validation

A bit late for the party, but this regular expression helped me to validate email type input in the client side. Though, we should always do verification in server side also.

<input type="email" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$">

You can find more regex of all kinds here.

How can I install a previous version of Python 3 in macOS using homebrew?

To solve this with homebrew, you can temporarily backdate homebrew-core and set the HOMEBREW_NO_AUTO_UPDATE variable to hold it in place:

cd `brew --repo homebrew/core`
git checkout f2a764ef944b1080be64bd88dca9a1d80130c558
export HOMEBREW_NO_AUTO_UPDATE=1
brew install python

I don't recommend permanently backdating homebrew-core, as you will miss out on security patches, but it is useful for testing purposes.

You can also extract old versions of homebrew formulae into your own tap (tap_owner/tap_name) using the brew extract command:

brew extract python tap_owner/tap_name --version=3.6.5

How do I make the first letter of a string uppercase in JavaScript?

There are already so many good answers, but you can also use a simple CSS transform:

text-transform: capitalize;

_x000D_
_x000D_
div.c {
  text-transform: capitalize;
}
_x000D_
<h2>text-transform: capitalize:</h2>
<div class="c">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
_x000D_
_x000D_
_x000D_

Selecting text in an element (akin to highlighting with your mouse)

Added jQuery.browser.webkit to the "else if" for Chrome. Could not get this working in Chrome 23.

Made this script below for selecting the content in a <pre> tag that has the class="code".

jQuery( document ).ready(function() {
    jQuery('pre.code').attr('title', 'Click to select all');
    jQuery( '#divFoo' ).click( function() {
        var refNode = jQuery( this )[0];
        if ( jQuery.browser.msie ) {
            var range = document.body.createTextRange();
            range.moveToElementText( refNode );
            range.select();
        } else if ( jQuery.browser.mozilla || jQuery.browser.opera  || jQuery.browser.webkit ) {
            var selection = refNode.ownerDocument.defaultView.getSelection();
            console.log(selection);
            var range = refNode.ownerDocument.createRange();
            range.selectNodeContents( refNode );
            selection.removeAllRanges();
            selection.addRange( range );
        } else if ( jQuery.browser.safari ) {
            var selection = refNode.ownerDocument.defaultView.getSelection();
            selection.setBaseAndExtent( refNode, 0, refNode, 1 );
        }
    } );
} );

JQuery Ajax POST in Codeigniter

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class UserController extends CI_Controller {

        public function verifyUser()    {
            $userName =  $_POST['userName'];
            $userPassword =  $_POST['userPassword'];
            $status = array("STATUS"=>"false");
            if($userName=='admin' && $userPassword=='admin'){
                $status = array("STATUS"=>"true");  
            }
            echo json_encode ($status) ;    
        }
    }


function makeAjaxCall(){
    $.ajax({
        type: "post",
        url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
        cache: false,               
        data: $('#userForm').serialize(),
        success: function(json){                        
        try{        
            var obj = jQuery.parseJSON(json);
            alert( obj['STATUS']);


        }catch(e) {     
            alert('Exception while request..');
        }       
        },
        error: function(){                      
            alert('Error while request..');
        }
 });
}

How to load all the images from one of my folder into my web page, using Jquery/Javascript

This is the way to add more file extentions, in the example given by Roy M J in the top of this page.

var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J   

In this example I have added more contains.

JavaScript operator similar to SQL "like"

No, there isn't any.

The list of comparison operators are listed here.

Comparison Operators

For your requirement the best option would be regular expressions.

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

The most likely explanations for that error are:

  1. The file you are attempting to load is not an executable file. CreateProcess requires you to provide an executable file. If you wish to be able to open any file with its associated application then you need ShellExecute rather than CreateProcess.
  2. There is a problem loading one of the dependencies of the executable, i.e. the DLLs that are linked to the executable. The most common reason for that is a mismatch between a 32 bit executable and a 64 bit DLL, or vice versa. To investigate, use Dependency Walker's profile mode to check exactly what is going wrong.

Reading down to the bottom of the code, I can see that the problem is number 1.

How to center icon and text in a android button with width set to "fill parent"

<style name="captionOnly">
    <item name="android:background">@null</item>
    <item name="android:clickable">false</item>
    <item name="android:focusable">false</item>
    <item name="android:minHeight">0dp</item>
    <item name="android:minWidth">0dp</item>
</style>

<FrameLayout
   style="?android:attr/buttonStyle"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" >

    <Button
       style="@style/captionOnly"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center"
       android:drawableLeft="@android:drawable/ic_delete"
       android:gravity="center"
       android:text="Button Challenge" />
</FrameLayout>

Put the FrameLayout in LinearLayout and set orientation to Horizontal.

Phone: numeric keyboard for text input

As of mid-2015, I believe this is the best solution:

<input type="number" pattern="[0-9]*" inputmode="numeric">

This will give you the numeric keypad on both Android and iOS:

enter image description here

It also gives you the expected desktop behavior with the up/down arrow buttons and keyboard friendly up/down arrow key incrementing:

enter image description here

Try it in this code snippet:

_x000D_
_x000D_
<form>_x000D_
  <input type="number" pattern="[0-9]*" inputmode="numeric">_x000D_
  <button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

By combining both type="number" and pattern="[0-9]*, we get a solution that works everywhere. And, its forward compatible with the future HTML 5.1 proposed inputmode attribute.

Note: Using a pattern will trigger the browser's native form validation. You can disable this using the novalidate attribute, or you can customize the error message for a failed validation using the title attribute.


If you need to be able to enter leading zeros, commas, or letters - for example, international postal codes - check out this slight variant.


Credits and further reading:

http://www.smashingmagazine.com/2015/05/form-inputs-browser-support-issue/ http://danielfriesen.name/blog/2013/09/19/input-type-number-and-ios-numeric-keypad/

C++ callback using class member

If you have callbacks with different parameters you can use templates as follows:
// compile with: g++ -std=c++11 myTemplatedCPPcallbacks.cpp -o myTemplatedCPPcallbacksApp

#include <functional>     // c++11

#include <iostream>        // due to: cout


using std::cout;
using std::endl;

class MyClass
{
    public:
        MyClass();
        static void Callback(MyClass* instance, int x);
    private:
        int private_x;
};

class OtherClass
{
    public:
        OtherClass();
        static void Callback(OtherClass* instance, std::string str);
    private:
        std::string private_str;
};

class EventHandler
{

    public:
        template<typename T, class T2>
        void addHandler(T* owner, T2 arg2)
        {
            cout << "\nHandler added..." << endl;
            //Let's pretend an event just occured
            owner->Callback(owner, arg2);
         }   

};

MyClass::MyClass()
{
    EventHandler* handler;
    private_x = 4;
    handler->addHandler(this, private_x);
}

OtherClass::OtherClass()
{
    EventHandler* handler;
    private_str = "moh ";
    handler->addHandler(this, private_str );
}

void MyClass::Callback(MyClass* instance, int x)
{
    cout << " MyClass::Callback(MyClass* instance, int x) ==> " 
         << 6 + x + instance->private_x << endl;
}

void OtherClass::Callback(OtherClass* instance, std::string private_str)
{
    cout << " OtherClass::Callback(OtherClass* instance, std::string private_str) ==> " 
         << " Hello " << instance->private_str << endl;
}

int main(int argc, char** argv)
{
    EventHandler* handler;
    handler = new EventHandler();
    MyClass* myClass = new MyClass();
    OtherClass* myOtherClass = new OtherClass();
}

H2 database error: Database may be already in use: "Locked by another process"

Ran into a similar issue the solution for me was to run fuser -k 'filename.db' on the file that had a lock associated with it.

Hope this helps!

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

Escaping curly brackets AND using string interpolation makes for an interesting challenge. You need to use quadruple brackets to escape the string interpolation parsing and string.format parsing.

Escaping Brackets: String Interpolation $("") and String.Format

string localVar = "dynamic";
string templateString = $@"<h2>{0}</h2><div>this is my {localVar} template using a {{{{custom tag}}}}</div>";
string result = string.Format(templateString, "String Interpolation");

// OUTPUT: <h2>String Interpolation</h2><div>this is my dynamic template using a {custom tag}</div>

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

How to find the number of days between two dates

Get No of Days between two days

DECLARE @date1 DATE='2015-01-01',
 @date2 DATE='2019-01-01',
 @Total int=null

SET @Total=(SELECT DATEDIFF(DAY, @date1, @date2))
PRINT @Total

Hibernate: "Field 'id' doesn't have a default value"

Sometimes changes made to the model or to the ORM may not reflect accurately on the database even after an execution of SchemaUpdate.

If the error actually seems to lack a sensible explanation, try recreating the database (or at least creating a new one) and scaffolding it with SchemaExport.

memory error in python

you could try to create the same script that popups that error, dividing the script into several script by importing from external script. Example, hello.py expect an error Memory error, so i divide hello.py into several scripts h.py e.py ll.py o.py all of them have to get into a folder "hellohello" into that folder create init.py into init write import h,e,ll,o and then on ide you write import hellohello

Get all Attributes from a HTML element with Javascript/jQuery

You can use this simple plugin as $('#some_id').getAttributes();

(function($) {
    $.fn.getAttributes = function() {
        var attributes = {}; 

        if( this.length ) {
            $.each( this[0].attributes, function( index, attr ) {
                attributes[ attr.name ] = attr.value;
            } ); 
        }

        return attributes;
    };
})(jQuery);

Java: Detect duplicates in ArrayList?

With Java 8+ you can use Stream API:

boolean areAllDistinct(List<Block> blocksList) {
    return blocksList.stream().map(Block::getNum).distinct().count() == blockList.size();
}

C++ multiline string literal

Well ... Sort of. The easiest is to just use the fact that adjacent string literals are concatenated by the compiler:

const char *text =
  "This text is pretty long, but will be "
  "concatenated into just a single string. "
  "The disadvantage is that you have to quote "
  "each part, and newlines must be literal as "
  "usual.";

The indentation doesn't matter, since it's not inside the quotes.

You can also do this, as long as you take care to escape the embedded newline. Failure to do so, like my first answer did, will not compile:

const char *text2 =
  "Here, on the other hand, I've gone crazy \
and really let the literal span several lines, \
without bothering with quoting each line's \
content. This works, but you can't indent.";

Again, note those backslashes at the end of each line, they must be immediately before the line ends, they are escaping the newline in the source, so that everything acts as if the newline wasn't there. You don't get newlines in the string at the locations where you had backslashes. With this form, you obviously can't indent the text since the indentation would then become part of the string, garbling it with random spaces.

How to change the application launcher icon on Flutter?

When a new Flutter app is created, it has a default launcher icon. To customize this icon, you might want to check out the flutter_launcher_icons package.

Alternatively, you can do it manually using the following steps. This step covers replacing these placeholder icons with your app’s icons:

Android

  1. Review the Material Design product icons guidelines for icon design.

  2. In the <app dir>/android/app/src/main/res/ directory, place your icon files in folders named using configuration qualifiers. The default mipmap- folders demonstrate the correct naming convention.

  3. In AndroidManifest.xml, update the application tag’s android:icon attribute to reference icons from the previous step (for example, <application android:icon="@mipmap/ic_launcher" ...).

  4. To verify that the icon has been replaced, run your app and inspect the app icon in the Launcher.

iOS

  1. Review the iOS App Icon guidelines.
  2. In the Xcode project navigator, select Assets.xcassets in the Runner folder. Update the placeholder icons with your own app icons.
  3. Verify the icon has been replaced by running your app using a flutter run.

Is it bad practice to use break to exit a loop in Java?

The JLS specifies a break is an abnormal termination of a loop. However, just because it is considered abnormal does not mean that it is not used in many different code examples, projects, products, space shuttles, etc. The JVM specification does not state either an existence or absence of a performance loss, though it is clear code execution will continue after the loop.

However, code readability can suffer with odd breaks. If you're sticking a break in a complex if statement surrounded by side effects and odd cleanup code, with possibly a multilevel break with a label(or worse, with a strange set of exit conditions one after the other), it's not going to be easy to read for anyone.

If you want to break your loop by forcing the iteration variable to be outside the iteration range, or by otherwise introducing a not-necessarily-direct way of exiting, it's less readable than break.

However, looping extra times in an empty manner is almost always bad practice as it takes extra iterations and may be unclear.

Async always WaitingForActivation

I overcome this issue with if anybody interested. In myMain method i called my readasync method like

Dispatcher.BeginInvoke(new ThreadStart(() => ReadData()));

Everything is fine for me now.

Regular Expressions- Match Anything

(.*?) matches anything - I've been using it for years.

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

This is a DependencyObject for attaching to a ComboBox.

It records the currently selected item when the dropdown is opened, and then fires SelectionChanged event if the same index is still selected when the dropdown is closed. It may need to be modified for it to work with Keyboard selection.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Web.UI.WebControls;

namespace MyNamespace 
{
    public class ComboAlwaysFireSelection : DependencyObject
    {
        public static readonly DependencyProperty ActiveProperty = DependencyProperty.RegisterAttached(
            "Active",
            typeof(bool),
            typeof(ComboAlwaysFireSelection),
            new PropertyMetadata(false, ActivePropertyChanged));

        private static void ActivePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = d as ComboBox;
            if (element == null) 
                return;

            if ((e.NewValue as bool?).GetValueOrDefault(false))
            {
                element.DropDownClosed += ElementOnDropDownClosed;
                element.DropDownOpened += ElementOnDropDownOpened;
            }
            else
            {
                element.DropDownClosed -= ElementOnDropDownClosed;
                element.DropDownOpened -= ElementOnDropDownOpened;
            }
        }

        private static void ElementOnDropDownOpened(object sender, EventArgs eventArgs)
        {
            _selectedIndex = ((ComboBox) sender).SelectedIndex;
        }

        private static int _selectedIndex;

        private static void ElementOnDropDownClosed(object sender, EventArgs eventArgs)
        {
            var comboBox = ((ComboBox) sender);
            if (comboBox.SelectedIndex == _selectedIndex)
            {
                comboBox.RaiseEvent(new SelectionChangedEventArgs(Selector.SelectionChangedEvent, new ListItemCollection(), new ListItemCollection()));
            }
        }

        [AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)]
        [AttachedPropertyBrowsableForType(typeof(ComboBox))]
        public static bool GetActive(DependencyObject @object)
        {
            return (bool)@object.GetValue(ActiveProperty);
        }

        public static void SetActive(DependencyObject @object, bool value)
        {
            @object.SetValue(ActiveProperty, value);
        }
    }
}

and add your namespace prefix to make it accessible.

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:ut="clr-namespace:MyNamespace" ></UserControl>

and then you need to attach it like so

<ComboBox ut:ComboAlwaysFireSelection.Active="True" />

How can I solve equations in Python?

Python may be good, but it isn't God...

There are a few different ways to solve equations. SymPy has already been mentioned, if you're looking for analytic solutions.

If you're happy to just have a numerical solution, Numpy has a few routines that can help. If you're just interested in solutions to polynomials, numpy.roots will work. Specifically for the case you mentioned:

>>> import numpy
>>> numpy.roots([2,-6])
array([3.0])

For more complicated expressions, have a look at scipy.fsolve.

Either way, you can't escape using a library.

Combining INSERT INTO and WITH/CTE

Yep:

WITH tab (
  bla bla
)

INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (  BatchID,                                                        AccountNo,
APartyNo,
SourceRowID)    

SELECT * FROM tab

Note that this is for SQL Server, which supports multiple CTEs:

WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y

Teradata allows only one CTE and the syntax is as your example.

Why does intellisense and code suggestion stop working when Visual Studio is open?

I've dealt with this for as long as Visual Studio existed. And yes, even in the current version it still fails (especially for large projects.)

I want to share small free tool that my friend and I wrote to address this exact same issue. You basically close your solution, drag its folder into the icon for this tool and it will reset all intermediary files for you. (Read the text manual inside if you want to know which ones. It's not just one file.)

I use it to clean up all my VS projects. So here you go:

enter image description here

jQuery DIV click, with anchors

If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).

$("div.clickable").click(
function()
{
    window.location = $(this).attr("url");
    return false;
});

See event.preventDefault() vs. return false for details on return false vs. preventDefault.

How to measure time taken between lines of code in python?

You can try this as well:

from time import perf_counter

t0 = perf_counter()

...

t1 = perf_counter()
time_taken = t1 - t0

Check list of words in another string

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

Slidedown and slideup layout with animation

Create two animation xml under res/anim folder

slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

<translate
    android:duration="1000"
    android:fromYDelta="0"
    android:toYDelta="100%" />
</set>

slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

<translate
    android:duration="1000"
    android:fromYDelta="100%"
    android:toYDelta="0" />
</set>

Load animation Like bellow Code and start animation when you want According to your Requirement

//Load animation 
Animation slide_down = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.slide_down);

Animation slide_up = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.slide_up);

// Start animation
linear_layout.startAnimation(slide_down); 

How to list all files in a directory and its subdirectories in hadoop hdfs

Have you tried this:

import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;

public class cat{
    public static void main (String [] args) throws Exception{
        try{
            FileSystem fs = FileSystem.get(new Configuration());
            FileStatus[] status = fs.listStatus(new Path("hdfs://test.com:9000/user/test/in"));  // you need to pass in your hdfs path

            for (int i=0;i<status.length;i++){
                BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(status[i].getPath())));
                String line;
                line=br.readLine();
                while (line != null){
                    System.out.println(line);
                    line=br.readLine();
                }
            }
        }catch(Exception e){
            System.out.println("File not found");
        }
    }
}

How to use the DropDownList's SelectedIndexChanged event

I think this is the culprit:

cmd = new SqlCommand(query, con);

DataTable dt = Select(query);

cmd.ExecuteNonQuery();

ddtype.DataSource = dt;

I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":

cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();

Or you can create a DataTable as explained here:

cmd = new SqlCommand(query, con);

SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);

ddtype.DataSource = listTable;

Converting characters to integers in Java

Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

How to Increase Import Size Limit in phpMyAdmin

If you are using WHM/Cpanel then in order to change that "Max: 50MiB" limit in the import section of phpmyadmin, you will have to change two values in WHM (Web Host Manager).

Step 1) Go to Tweak settings, find the "cPanel PHP Max upload size" change it according to your needs. Save changes.

Step 2) Go to Tweak settings, find the "cPanel PHP Max POST size" change it according to your needs. Save changes.

Go back to your phpMyadmin. The value should have changed.

enter image description here

enter image description here

enter image description here

How to read file contents into a variable in a batch file?

To get all the lines of the file loaded into the variable, Delayed Expansion is needed, so do the following:

SETLOCAL EnableDelayedExpansion

for /f "Tokens=* Delims=" %%x in (version.txt) do set Build=!Build!%%x

There is a problem with some special characters, though especially ;, % and !

How to match hyphens with Regular Expression?

use "\p{Pd}" without quotes to match any type of hyphen. The '-' character is just one type of hyphen which also happens to be a special character in Regex.

Wait for a process to finish

FreeBSD and Solaris have this handy pwait(1) utility, which does exactly, what you want.

I believe, other modern OSes also have the necessary system calls too (MacOS, for example, implements BSD's kqueue), but not all make it available from command-line.

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

ContextLoaderListener has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml

You can customize this by using

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>

on web.xml, or remove this listener if you don't need one.

What's "this" in JavaScript onclick?

In JavaScript this refers to the element containing the action. For example, if you have a function called hide():

function hide(element){
   element.style.display = 'none';
}

Calling hide with this will hide the element. It returns only the element clicked, even if it is similar to other elements in the DOM.

For example, you may have this clicking a number in the HTML below will only hide the bullet point clicked.

<ul>
  <li class="bullet" onclick="hide(this);">1</li>
  <li class="bullet" onclick="hide(this);">2</li>
  <li class="bullet" onclick="hide(this);">3</li>
  <li class="bullet" onclick="hide(this);">4</li>
</ul>

Closing Excel Application Process in C# after Data Access

Killing Excel is not always easy; see this article: 50 Ways to Kill Excel

This article takes the best advice from Microsoft (MS Knowlege Base Article) on how to get Excel to quit nicely, but then also makes sure about it by killing the process if necessary. I like having a second parachute.

Make sure to Close any open workbooks, Quit the application and Release the xlApp object. Finally check to see if the process is still alive and if so then kill it.

This article also makes sure that we don't kill all Excel processes but only kills the exact process that was started.

See also Get Process from Window Handle

Here is the code I use: (works every time)

Sub UsingExcel()

    'declare process; will be used later to attach the Excel process
    Dim XLProc As Process

    'call the sub that will do some work with Excel
    'calling Excel in a separate routine will ensure that it is 
    'out of scope when calling GC.Collect
    'this works better especially in debug mode
    DoOfficeWork(XLProc)

    'Do garbage collection to release the COM pointers
    'http://support.microsoft.com/kb/317109
    GC.Collect()
    GC.WaitForPendingFinalizers()

    'I prefer to have two parachutes when dealing with the Excel process
    'this is the last answer if garbage collection were to fail
    If Not XLProc Is Nothing AndAlso Not XLProc.HasExited Then
        XLProc.Kill()
    End If

End Sub

'http://msdn.microsoft.com/en-us/library/ms633522%28v=vs.85%29.aspx
<System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, _
    ByRef lpdwProcessId As Integer) As Integer
End Function

Private Sub ExcelWork(ByRef XLProc As Process)

    'start the application using late binding
    Dim xlApp As Object = CreateObject("Excel.Application")

    'or use early binding
    'Dim xlApp As Microsoft.Office.Interop.Excel

    'get the window handle
    Dim xlHWND As Integer = xlApp.hwnd

    'this will have the process ID after call to GetWindowThreadProcessId
    Dim ProcIdXL As Integer = 0

    'get the process ID
    GetWindowThreadProcessId(xlHWND, ProcIdXL)

    'get the process
    XLProc = Process.GetProcessById(ProcIdXL)


    'do some work with Excel here using xlApp

    'be sure to save and close all workbooks when done

    'release all objects used (except xlApp) using NAR(x)


    'Quit Excel 
    xlApp.quit()

    'Release
    NAR(xlApp)

End Sub

Private Sub NAR(ByVal o As Object)
    'http://support.microsoft.com/kb/317109
    Try
        While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
        End While
    Catch
    Finally
        o = Nothing
    End Try
End Sub

How to refer to relative paths of resources when working with a code repository

import os
cwd = os.getcwd()
path = os.path.join(cwd, "my_file")
f = open(path)

You also try to normalize your cwd using os.path.abspath(os.getcwd()). More info here.

Background images: how to fill whole div if image is small and vice versa

Resize the image to fit the div size.
With CSS3 you can do this:

/* with CSS 3 */
#yourdiv {  
    background: url('bgimage.jpg') no-repeat;
    background-size: 100%;
}

How Do you Stretch a Background Image in a Web Page:

About opacity

#yourdiv {
    opacity: 0.4;
    filter: alpha(opacity=40); /* For IE8 and earlier */
}

Or look at CSS Image Opacity / Transparency

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

This happens when saving an object when Hibernate thinks it needs to save an object that is associated with the one you are saving.

I had this problem and did not want to save changes to the referenced object so I wanted the cascade type to be NONE.

The trick is to ensure that the ID and VERSION in the referenced object is set so that Hibernate does not think that the referenced object is a new object that needs saving. This worked for me.

Look through all of the relationships in the class you are saving to work out the associated objects (and the associated objects of the associated objects) and ensure that the ID and VERSION is set in all objects of the object tree.

How to use Utilities.sleep() function

Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.

Here is an example :

function delsheets(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
  for (pa=numbofsheet-1;pa>0;--pa){ 
    ss.setActiveSheet(ss.getSheets()[pa]);
    var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
    Utilities.sleep(200);// pause in the loop for 200 milliseconds
  }
  ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}

How do you calculate program run time in python?

You might want to take a look at the timeit module:

http://docs.python.org/library/timeit.html

or the profile module:

http://docs.python.org/library/profile.html

There are some additionally some nice tutorials here:

http://www.doughellmann.com/PyMOTW/profile/index.html

http://www.doughellmann.com/PyMOTW/timeit/index.html

And the time module also might come in handy, although I prefer the later two recommendations for benchmarking and profiling code performance:

http://docs.python.org/library/time.html

How to set commands output as a variable in a batch file

I found this thread on that there Interweb thing. Boils down to:

@echo off 
setlocal enableextensions 
for /f "tokens=*" %%a in ( 
'VER' 
) do ( 
set myvar=%%a 
) 
echo/%%myvar%%=%myvar% 
pause 
endlocal 

You can also redirect the output of a command to a temporary file, and then put the contents of that temporary file into your variable, likesuchashereby. It doesn't work with multiline input though.

cmd > tmpFile 
set /p myvar= < tmpFile 
del tmpFile 

Credit to the thread on Tom's Hardware.

How do I encode a JavaScript object as JSON?

All major browsers now include native JSON encoding/decoding.

// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject); 

// To decode (This produces an object)
var obj = JSON.parse(json_str);

Note that only valid JSON data will be encoded. For example:

var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"

Valid JSON types are: objects, strings, numbers, arrays, true, false, and null.

Some JSON resources:

What does map(&:name) mean in Ruby?

It's equivalent to

def tag_names
  @tag_names || tags.map { |tag| tag.name }.join(' ')
end

How to detect control+click in Javascript from an onclick div attribute?

Try this code,

$('#1').on('mousedown',function(e) {
   if (e.button==0 && e.ctrlKey) {
       alert('is Left Click');
   } else if (e.button==2 && e.ctrlKey){
       alert('is Right Click');
   }
});

Sorry I added e.ctrlKey.

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

If you are installing first time then please try login with username and password as root

Missing maven .m2 folder

Use mvn -X or mvn --debug to find out from which different locations Maven reads settings.xml. This switch activates debug logging. Just check the first lines of mvn --debug | findstr /i /c:using /c:reading.


Right, Maven uses the Java system property user.home as location for the .m2 folder.

But user.home does not always resolve to %USERPROFILE%\.m2. If you have moved the location of your Desktop folder to another place, user.home might resolve to the parent directory of this new Desktop folder. This happens when using Windows Vista or a more recent Windows together with Java 7 or any older Java version.

The blog post Java’s “user.home” is Wrong on Windows describes it very well and gives links to the official bug reports. The bug is marked as resolved in Java 8. The comment of the blog's visitor Lars proposes a nice workaround.

What is difference between sleep() method and yield() method of multi threading?

sleep()causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode). yield()basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.

Regex to check with starts with http://, https:// or ftp://

Unless there is some compelling reason to use a regex, I would just use String.startsWith:

bool matches = test.startsWith("http://")
            || test.startsWith("https://") 
            || test.startsWith("ftp://");

I wouldn't be surprised if this is faster, too.

Passing a Bundle on startActivity()?

You can use the Bundle from the Intent:

Bundle extras = myIntent.getExtras();
extras.put*(info);

Or an entire bundle:

myIntent.putExtras(myBundle);

Is this what you're looking for?

Windows 8.1 gets Error 720 on connect VPN

I had the same problem. Most posted solutions would not work. I ran sfc /scannow and it reported that some errors could not be fixed. To address that problem I ran the command

Dism /Online /Cleanup-Image /RestoreHealth

Ironically, I later found the WAN errors had gone away, the 720 VPN error went away and my VPN worked.

Hard to believe that the WAN errors were corrected by this rather esoteric command, but it's worth a try.

How to remove foreign key constraint in sql server?

firstly use

show create table table_name;

to see the descriptive structure of your table.

There you may see constraints respective to foreign keys you used in that table. First delete the respective constraint with

alter table table_name drop constraint constraint_name;

and then delete the respective foreign keys or column you wanted...GoodLuck!!

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

Holy molly, I had to do all this in order for it to work. A picture is worth a thousand words.

  • If you get this error while archiving then continue reading.

    Enter image description here

  • Go to your app and click on the general tab. Under the signing section, uncheck "Automatically manage signing". As soon as you do that you will get a status of red error as shown below.

    Enter image description here

  • Now here's the tricky part. You need to uncheck "Automatically manage Signing" in both the targets under your project. This step is very important.

    Enter image description here

  • Now go under "build settings" tab of each of those targets and set "iOS Developer" under code signing identity. Do the same steps for your "PROJECT".

    Enter image description here

  • Now do Xcode ? Product ? Clean. Close your project in Xcode and reopen it again.

  • After this go to the general tab of each of your targets and check "Automatically manage signing" and under team drop down select your developer account

    Enter image description here

  • Do an archive of your project again and everything should work.

Really, Apple? Was this supposed to make our lives easier?

bash export command

Follow These step to Remove " bash export command not found." Terminal open error fix>>>>>>

open terminal and type : root@someone:~# nano ~/.bashrc

After Loading nano: remove the all 'export PATH = ...........................' lines and press ctrl+o to save file and press ctrl+e to exit.

Now the Terminal opening error will be fixed.........

Update multiple rows using select statement

You can use alias to improve the query:

UPDATE t1
   SET t1.Value = t2.Value
  FROM table1 AS t1
         INNER JOIN 
       table2 AS t2
         ON t1.ID = t2.ID

What does "ulimit -s unlimited" do?

ulimit -s unlimited lets the stack grow unlimited.

This may prevent your program from crashing if you write programs by recursion, especially if your programs are not tail recursive (compilers can "optimize" those), and the depth of recursion is large.

printf with std::string?

printf accepts a variable number of arguments. Those can only have Plain Old Data (POD) types. Code that passes anything other than POD to printf only compiles because the compiler assumes you got your format right. %s means that the respective argument is supposed to be a pointer to a char. In your case it is an std::string not const char*. printf does not know it because the argument type goes lost and is supposed to be restored from the format parameter. When turning that std::string argument into const char* the resulting pointer will point to some irrelevant region of memory instead of your desired C string. For that reason your code prints out gibberish.

While printf is an excellent choice for printing out formatted text, (especially if you intend to have padding), it can be dangerous if you haven't enabled compiler warnings. Always enable warnings because then mistakes like this are easily avoidable. There is no reason to use the clumsy std::cout mechanism if the printf family can do the same task in a much faster and prettier way. Just make sure you have enabled all warnings (-Wall -Wextra) and you will be good. In case you use your own custom printf implementation you should declare it with the __attribute__ mechanism that enables the compiler to check the format string against the parameters provided.

How to take the first N items from a generator or list?

@Shaikovsky's answer is excellent (…and heavily edited since I posted this answer), but I wanted to clarify a couple of points.

[next(generator) for _ in range(n)]

This is the most simple approach, but throws StopIteration if the generator is prematurely exhausted.


On the other hand, the following approaches return up to n items which is preferable in many circumstances:

List: [x for _, x in zip(range(n), records)]

Generator: (x for _, x in zip(range(n), records))

Random number generator only generating one random number

For ease of re-use throughout your application a static class may help.

public static class StaticRandom
{
    private static int seed;

    private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
        (() => new Random(Interlocked.Increment(ref seed)));

    static StaticRandom()
    {
        seed = Environment.TickCount;
    }

    public static Random Instance { get { return threadLocal.Value; } }
}

You can use then use static random instance with code such as

StaticRandom.Instance.Next(1, 100);

How to convert between bytes and strings in Python 3?

In python3, there is a bytes() method that is in the same format as encode().

str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True

I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode and decode, and without having to prefex b in front of quotes.

Increasing the timeout value in a WCF service

In addition to the binding timeouts (which are in Timespans), You may also need this as well. This is in seconds.

<system.web>
    <httpRuntime executionTimeout="600"/><!-- = 10 minutes -->

OpenCV - Apply mask to a color image

Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).

This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.

apply mask and get a customized background

# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np

# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))

# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8)  # mask is only 
for i in circles[0, :]:
    cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)

# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)

# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)

# combine foreground+background
final = cv2.bitwise_or(fg, bk)

Note: It is better to use the opencv methods because they are optimized.

How to implement a confirmation (yes/no) DialogPreference?

Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.

Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).

Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).

You can then add it to your preferences.xml like any other Preference. Example:

<com.example.myapp.YesNoPreference
    android:dialogMessage="Are you sure you want to revert all settings to their default values?"
    android:key="com.example.myapp.pref_reset_settings_key"
    android:summary="Revert all settings to their default values."
    android:title="Reset Settings" />

Which looks like this:

screenshot

How can I lookup a Java enum from its String value?

Use the valueOf method which is automatically created for each Enum.

Verbosity.valueOf("BRIEF") == Verbosity.BRIEF

For arbitrary values start with:

public static Verbosity findByAbbr(String abbr){
    for(Verbosity v : values()){
        if( v.abbr().equals(abbr)){
            return v;
        }
    }
    return null;
}

Only move on later to Map implementation if your profiler tells you to.

I know it's iterating over all the values, but with only 3 enum values it's hardly worth any other effort, in fact unless you have a lot of values I wouldn't bother with a Map it'll be fast enough.

ERROR 1148: The used command is not allowed with this MySQL version

SpringBoot 2.1 with Default MySQL connector

To Solve this please follow the instructions

1. SET GLOBAL local_infile = 1;

to set this global variable please follow the instruction provided in MySQL documentation https://dev.mysql.com/doc/refman/8.0/en/load-data-local.html

2. Change the MySQL Connector String

allowLoadLocalInfile=true Example : jdbc:mysql://localhost:3306/xxxx?useSSL=false&useUnicode=yes&characterEncoding=UTF-8&allowLoadLocalInfile=true

JTable won't show column headers

Put your JTable inside a JScrollPane. Try this:

add(new JScrollPane(scrTbl));

How can I ssh directly to a particular directory?

In my very specific case, I just wanted to execute a command in a remote host, inside a specific directory from a Jenkins slave machine:

ssh myuser@mydomain
cd /home/myuser/somedir 
./commandThatMustBeRunInside_somedir
exit

But my machine couldn't perform the ssh (it couldn't allocate a pseudo-tty I suppose) and kept me giving the following error:

Pseudo-terminal will not be allocated because stdin is not a terminal

I could get around this issue passing "cd to dir + my command" as a parameter of the ssh command (to not have to allocate a Pseudo-terminal) and by passing the option -T to explicitly tell to the ssh command that I didn't need pseudo-terminal allocation.

ssh -T myuser@mydomain "cd /home/myuser/somedir; ./commandThatMustBeRunInside_somedir"

How do I output text without a newline in PowerShell?

While it may not work in your case (since you're providing informative output to the user), create a string that you can use to append output. When it's time to output it, just output the string.

Ignoring of course that this example is silly in your case but useful in concept:

$output = "Enabling feature XYZ......."
Enable-SPFeature...
$output += "Done"
Write-Output $output

Displays:

Enabling feature XYZ.......Done

document.getElementById(id).focus() is not working for firefox or chrome

I know this may be an esoteric use-case but I struggled with getting an input to take focus when using Angular 2 framework. Calling focus() simply did not work not matter what I did.

Ultimately I realized angular was suppressing it because I had not set an [(ngModel)] on the input. Setting one solved it. Hope it helps someone.

jQuery animate scroll

I just use:

_x000D_
_x000D_
$('body').animate({ 'scrollTop': '-=-'+<yourValueScroll>+'px' }, 2000);
_x000D_
_x000D_
_x000D_

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

I ran into this problem and try using the flag -noverify which really works. It is because of the new bytecode verifier. So the flag should really work. I am using JDK 1.7.

Note: This would not work if you are using JDK 1.8

how to refresh Select2 dropdown menu after ajax loading different content?

It's common for other components to be listening to the change event, or for custom event handlers to be attached that may have side effects. Select2 does not have a custom event (like select2:update) that can be triggered other than change. You can rely on jQuery's event namespacing to limit the scope to Select2 though by triggering the *change.select2 event.

$('#state').trigger('change.select2'); // Notify only Select2 of changes

What does the @ symbol before a variable name mean in C#?

It allows you to use a C# keyword as a variable. For example:

class MyClass
{
   public string name { get; set; }
   public string @class { get; set; }
}

How to convert a string to a date in sybase

102 is the rule of thumb, convert (varchar, creat_tms, 102) > '2011'

Using CSS for a fade-in effect on page load

In response to @A.M.K's question about how to do transitions without jQuery. A very simple example I threw together. If I had time to think this through some more, I might be able to eliminate the JavaScript code altogether:

<style>
    body {
        background-color: red;
        transition: background-color 2s ease-in;
    }
</style>

<script>
    window.onload = function() {
        document.body.style.backgroundColor = '#00f';
    }
</script>

<body>
    <p>test</p>
</body>

Remove all stylings (border, glow) from textarea

If you want to remove EVERYTHING :

textarea {
    border: none;
    background-color: transparent;
    resize: none;
    outline: none;
}

jQuery disable a link

unbind() was deprecated in jQuery 3, use the off() method instead:

$("a").off("click");

How can I make my layout scroll both horizontally and vertically?

Since other solutions are old and either poorly-working or not working at all, I've modified NestedScrollView, which is stable, modern and it has all you expect from a scroll view. Except for horizontal scrolling.

Here's the repo: https://github.com/ultimate-deej/TwoWayNestedScrollView

I've made no changes, no "improvements" to the original NestedScrollView expect for what was absolutely necessary. The code is based on androidx.core:core:1.3.0, which is the latest stable version at the time of writing.

All of the following works:

  • Lift on scroll (since it's basically a NestedScrollView)
  • Edge effects in both dimensions
  • Fill viewport in both dimensions

Maintaining the final state at end of a CSS3 animation

IF NOT USING THE SHORT HAND VERSION: Make sure the animation-fill-mode: forwards is AFTER the animation declaration or it will not work...

animation-fill-mode: forwards;
animation-name: appear;
animation-duration: 1s;
animation-delay: 1s;

vs

animation-name: appear;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-delay: 1s;

Using margin:auto to vertically-align a div

If you know the height of the div you want to center, you can position it absolutely within its parent and then set the top value to 50%. That will put the top of the child div 50% of the way down its parent, i.e. too low. Pull it back up by setting its margin-top to half its height. So now you have the vertical midpoint of the child div sitting at the vertical midpoint of the parent - vertically centered!

Example:

_x000D_
_x000D_
.black {_x000D_
    position:absolute;_x000D_
    top:0;_x000D_
    bottom:0;_x000D_
    left:0;_x000D_
    right:0;_x000D_
    background:rgba(0,0,0,.5);_x000D_
}_x000D_
.message {_x000D_
    background:yellow;_x000D_
    width:200px;_x000D_
    margin:auto auto;_x000D_
    padding:10px;_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    margin-top: -25px;_x000D_
    height: 50px;_x000D_
}
_x000D_
<div class="black">_x000D_
    <div class="message">_x000D_
        This is a popup message._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/yWnZ2/2/

A hex viewer / editor plugin for Notepad++?

There is an old plugin called HEX Editor here.

According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.

php search array key and get value

Here is an example straight from PHP.net

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

in the foreach you can do a comparison of each key to something that you are looking for

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

I'm all for good names, and I often write about the importance of taking great care when choosing names for things. For this very same reason, I am wary of metaphors when naming things. In the original question, "factory" and "synchronizer" look like good names for what they seem to mean. However, "shepherd" and "nanny" are not, because they are based on metaphors. A class in your code can't be literally a nanny; you call it a nanny because it looks after some other things very much like a real-life nanny looks after babies or kids. That's OK in informal speech, but not OK (in my opinion) for naming classes in code that will have to be maintained by who knows whom who knows when.

Why? Because metaphors are culture dependent and often individual dependent as well. To you, naming a class "nanny" can be very clear, but maybe it's not that clear to somebody else. We shouldn't rely on that, unless you're writing code that is only for personal use.

In any case, convention can make or break a metaphor. The use of "factory" itself is based on a metaphor, but one that has been around for quite a while and is currently fairly well known in the programming world, so I would say it's safe to use. However, "nanny" and "shepherd" are unacceptable.

Find full path of the Python interpreter?

There are a few alternate ways to figure out the currently used python in Linux is:

  1. which python command.
  2. command -v python command
  3. type python command

Similarly On Windows with Cygwin will also result the same.

kuvivek@HOSTNAME ~
$ which python
/usr/bin/python

kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4        /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz

kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3

kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python

kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)

If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.

>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>

If you are not sure of the actual path of the python command and is available in your system, Use the following command.

pi@osboxes:~ $ which python
/usr/bin/python
pi@osboxes:~ $ readlink -f $(which python)
/usr/bin/python2.7
pi@osboxes:~ $ 
pi@osboxes:~ $ which python3
/usr/bin/python3
pi@osboxes:~ $ 
pi@osboxes:~ $ readlink -f $(which python3)
/usr/bin/python3.7
pi@osboxes:~ $ 

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

IntelliJ sometimes gets confused all by itself, even without the external changes Korgen described (though that is a good way to consistently reproduce it).

Click File -> Synchronize, and IntelliJ should see that everything is okay again.

If that doesn't work, IntelliJ's caches might be corrupt (this used to happen a lot more often than it does now); in that case, regenerate them by

Clicking File -> Invalidate Caches and restarting the IDE

(though loading the project will take a while while the caches are recreated).