Programs & Examples On #Publickeytoken

How do I find the PublicKeyToken for a particular dll?

Assembly.LoadFile(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\system.data.dll").FullName

Will result in

System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

class << self idiom in Ruby

I found a super simple explanation about class << self , Eigenclass and different type of methods.

In Ruby, there are three types of methods that can be applied to a class:

  1. Instance methods
  2. Singleton methods
  3. Class methods

Instance methods and class methods are almost similar to their homonymous in other programming languages.

class Foo  
  def an_instance_method  
    puts "I am an instance method"  
  end  
  def self.a_class_method  
    puts "I am a class method"  
  end  
end

foo = Foo.new

def foo.a_singleton_method
  puts "I am a singletone method"
end

Another way of accessing an Eigenclass(which includes singleton methods) is with the following syntax (class <<):

foo = Foo.new

class << foo
  def a_singleton_method
    puts "I am a singleton method"
  end
end

now you can define a singleton method for self which is the class Foo itself in this context:

class Foo
  class << self
    def a_singleton_and_class_method
      puts "I am a singleton method for self and a class method for Foo"
    end
  end
end

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

This workaround worked for me. I edited the serverInfo.properties file as given below:

server.info=Apache Tomcat/8.0.0
server.number=8.0.0.0
server.built=Oct 6 2016 20:15:31 UTC

ImportError: No module named BeautifulSoup

On Ubuntu 14.04 I installed it from apt-get and it worked fine:

sudo apt-get install python-beautifulsoup

Then just do:

from BeautifulSoup import BeautifulSoup

MySQL - Cannot add or update a child row: a foreign key constraint fails

Hope this will assist anyone having the same error while importing CSV data into related tables. In my case the parent table was OK, but I got the error while importing data to the child table containing the foreign key. After temporarily removing the foregn key constraint on the child table, I managed to import the data and was suprised to find some of the values in the FK column having values of 0 (obviously this had been causing the error since the parent table did not have such values in its PK column). The cause was that, the data in my CSV column preceeding the FK column contained commas (which I was using as a field delimeter). Changing the delimeter for my CSV file solved the problem.

System.Net.WebException: The remote name could not be resolved:

Open the hosts file located at : **C:\windows\system32\drivers\etc**.

Hosts file is for what?

Add the following at end of this file :

YourServerIP YourDNS

Example:

198.168.1.1 maps.google.com

Flutter - Wrap text on overflow, like insert ellipsis or fade

You can do it like that

Expanded(
   child: Text(
   'Text',
   overflow: TextOverflow.ellipsis,
   maxLines: 1
   )
)

Export SQL query data to Excel

For anyone coming here looking for how to do this in C#, I have tried the following method and had success in dotnet core 2.0.3 and entity framework core 2.0.3

First create your model class.

public class User
{  
    public string Name { get; set; }  
    public int Address { get; set; }  
    public int ZIP { get; set; }  
    public string Gender { get; set; }  
} 

Then install EPPlus Nuget package. (I used version 4.0.5, probably will work for other versions as well.)

Install-Package EPPlus -Version 4.0.5

The create ExcelExportHelper class, which will contain the logic to convert dataset to Excel rows. This class do not have dependencies with your model class or dataset.

public class ExcelExportHelper
    {
        public static string ExcelContentType
        {
            get
            { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
        }

        public static DataTable ListToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dataTable = new DataTable();

            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }

                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

        public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
        {

            byte[] result = null;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
                int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

                if (showSrNo)
                {
                    DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                    dataColumn.SetOrdinal(0);
                    int index = 1;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        item[0] = index;
                        index++;
                    }
                }


                // add the content into the Excel file  
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);

                // autofit width of cells with small content  
                int columnIndex = 1;
                foreach (DataColumn column in dataTable.Columns)
                {
                    int maxLength;
                    ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
                    try
                    {
                        maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
                    }
                    catch (Exception) //nishanc
                    {
                        maxLength = columnCells.Max(cell => (cell.Value +"").ToString().Length);
                    }

                    //workSheet.Column(columnIndex).AutoFit();
                    if (maxLength < 150)
                    {
                        //workSheet.Column(columnIndex).AutoFit();
                    }


                    columnIndex++;
                }

                // format header - bold, yellow on black  
                using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                {
                    r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    r.Style.Font.Bold = true;
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    r.Style.Fill.BackgroundColor.SetColor(Color.Brown);
                }

                // format cells - add borders  
                using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                {
                    r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

                    r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                }

                // removed ignored columns  
                for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
                {
                    if (i == 0 && showSrNo)
                    {
                        continue;
                    }
                    if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
                    {
                        workSheet.DeleteColumn(i + 1);
                    }
                }

                if (!String.IsNullOrEmpty(heading))
                {
                    workSheet.Cells["A1"].Value = heading;
                   // workSheet.Cells["A1"].Style.Font.Size = 20;

                    workSheet.InsertColumn(1, 1);
                    workSheet.InsertRow(1, 1);
                    workSheet.Column(1).Width = 10;
                }

                result = package.GetAsByteArray();
            }

            return result;
        }

        public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
        {
            return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
        }
    }

Now add this method where you want to generate the excel file, probably for a method in the controller. You can pass parameters for your stored procedure as well. Note that the return type of the method is FileContentResult. Whatever query you execute, important thing is you must have the results in a List.

[HttpPost]
public async Task<FileContentResult> Create([Bind("Id,StartDate,EndDate")] GetReport getReport)
{
    DateTime startDate = getReport.StartDate;
    DateTime endDate = getReport.EndDate;

    // call the stored procedure and store dataset in a List.
    List<User> users = _context.Reports.FromSql("exec dbo.SP_GetEmpReport @start={0}, @end={1}", startDate, endDate).ToList();
    //set custome column names
    string[] columns = { "Name", "Address", "ZIP", "Gender"};
    byte[] filecontent = ExcelExportHelper.ExportExcel(users, "Users", true, columns);
    // set file name.
    return File(filecontent, ExcelExportHelper.ExcelContentType, "Report.xlsx"); 
}

More details can be found here

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

How do I accomplish an if/else in mustache.js?

Your else statement should look like this (note the ^):

{{^avatar}}
 ...
{{/avatar}}

In mustache this is called 'Inverted sections'.

How to subtract/add days from/to a date?

Just subtract a number:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

Since the Date class only has days, you can just do basic arithmetic on it.

If you want to use POSIXlt for some reason, then you can use it's slots:

> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"

How to force link from iframe to be opened in the parent window

I found the best solution was to use the base tag. Add the following to the head of the page in the iframe:

<base target="_parent">

This will load all links on the page in the parent window. If you want your links to load in a new window, use:

<base target="_blank">

Browser Support

How do I convert a String object into a Hash object?

This short little snippet will do it, but I can't see it working with a nested hash. I think it's pretty cute though

STRING.gsub(/[{}:]/,'').split(', ').map{|h| h1,h2 = h.split('=>'); {h1 => h2}}.reduce(:merge)

Steps 1. I eliminate the '{','}' and the ':' 2. I split upon the string wherever it finds a ',' 3. I split each of the substrings that were created with the split, whenever it finds a '=>'. Then, I create a hash with the two sides of the hash I just split apart. 4. I am left with an array of hashes which I then merge together.

EXAMPLE INPUT: "{:user_id=>11, :blog_id=>2, :comment_id=>1}" RESULT OUTPUT: {"user_id"=>"11", "blog_id"=>"2", "comment_id"=>"1"}

Load a WPF BitmapImage from a System.Drawing.Bitmap

It took me some time to get the conversion working both ways, so here are the two extension methods I came up with:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

public static class BitmapConversion {

    public static Bitmap ToWinFormsBitmap(this BitmapSource bitmapsource) {
        using (MemoryStream stream = new MemoryStream()) {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(bitmapsource));
            enc.Save(stream);

            using (var tempBitmap = new Bitmap(stream)) {
                // According to MSDN, one "must keep the stream open for the lifetime of the Bitmap."
                // So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.
                return new Bitmap(tempBitmap);
            }
        }
    }

    public static BitmapSource ToWpfBitmap(this Bitmap bitmap) {
        using (MemoryStream stream = new MemoryStream()) {
            bitmap.Save(stream, ImageFormat.Bmp);

            stream.Position = 0;
            BitmapImage result = new BitmapImage();
            result.BeginInit();
            // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
            // Force the bitmap to load right now so we can dispose the stream.
            result.CacheOption = BitmapCacheOption.OnLoad;
            result.StreamSource = stream;
            result.EndInit();
            result.Freeze();
            return result;
        }
    }
}

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

Is Laravel really this slow?

Yes - Laravel IS really that slow. I built a POC app for this sake. Simple router, with a login form. I could only get 60 RPS with 10 concurrent connections on a $20 digital ocean server (few GB ram);

Setup:

2gb RAM
Php7.0
apache2.4
mysql 5.7
memcached server (for laravel session)

I ran optimizations, composer dump autoload etc, and it actually lowered the RPS to 43-ish.

The problem is the app responds in 200-400ms. I ran AB test from the local machine laravel was on (ie, not through web traffic); and I got only 112 RPS; with 200ms faster response time with an average of 300ms.

Comparatively, I tested my production PHP Native app running a few million requests a day on a AWS t2.medium (x3, load balanced). When I AB'd 25 concurrent connections from my local machine to that over web, through ELB, I got roughly 1200 RPS. Huge difference on a machine with load vs a laravel "login" page.

These are pages with Sessions (elasticache / memcached), Live DB lookups (cached queries via memcached), Assets pulled over CDNs, etc, etc, etc.

What I can tell, laravel sticks about 200-300ms load over things. Its fine for PHP Generated views, after all, that type of delay is tolerable on load. However, for PHP views that use Ajax/JS to handle small updates, it begins to feel sluggish.

I cant imagine what this system would look like with a multi tenant app while 200 bots crawl 100 pages each all at the same time.

Laravel is great for simple apps. Lumen is tolerable if you dont need to do anything fancy that would require middleware nonsense (IE, no multi tenant apps and custom domains, etc);

However, I never like starting with something that can bind and cause 300ms load for a "hello world" post.

If youre thinking "Who cares?"

.. Write a predictive search that relies on quick queries to respond to autocomplete suggestions across a few hundred thousand results. That 200-300ms lag will drive your users absolutely insane.

How can I easily convert DataReader to List<T>?

I would (and have) started to use Dapper. To use your example would be like (written from memory):

public List<CustomerEntity> GetCustomerList()
{
    using (DbConnection connection = CreateConnection())
    {
        return connection.Query<CustomerEntity>("procToReturnCustomers", commandType: CommandType.StoredProcedure).ToList();
    }
}

CreateConnection() would handle accessing your db and returning a connection.

Dapper handles mapping datafields to properties automatically. It also supports multiple types and result sets and is very fast.

Query returns IEnumerable hence the ToList().

How can I return to a parent activity correctly?

You declared activity A with the standard launchMode in the Android manifest. According to the documentation, that means the following:

The system always creates a new instance of the activity in the target task and routes the intent to it.

Therefore, the system is forced to recreate activity A (i.e. calling onCreate) even if the task stack is handled correctly.

To fix this problem you need to change the manifest, adding the following attribute to the A activity declaration:

android:launchMode="singleTop"

Note: calling finish() (as suggested as solution before) works only when you are completely sure that the activity B instance you are terminating lives on top of an instance of activity A. In more complex workflows (for instance, launching activity B from a notification) this might not be the case and you have to correctly launch activity A from B.

How can I recursively find all files in current and subfolders based on wildcard matching?

Default way to search for recursive file, and available in most cases is

find . -name "filepattern"

It starts recursive traversing for filename or pattern from within current directory where you are positioned. With find command, you can use wildcards, and various switches, to see full list of options, type

man find

or if man pages aren't available at your system

find --help

However, there are more modern and faster tools then find, which are traversing your whole filesystem and indexing your files, one such common tool is locate or slocate/mlocate, you should check manual of your OS on how to install it, and once it's installed it needs to initiate database, if install script don't do it for you, it can be done manually by typing

sudo updatedb

And, to use it to look for some particular file type

locate filename

Or, to look for filename or patter from within current directory, you can type:

 pwd | xargs -n 1 -I {} locate "filepattern"

It will look through its database of files and quickly print out path names that match pattern that you have typed. To see full list of locate's options, type: locate --help or man locate

Additionally you can configure locate to update it's database on scheduled times via cron job, so sample cron which updates db at 1AM would look like:

0 1 * * * updatedb

These cron jobs need to be configured by root, since updatedb needs root privilege to traverse whole filesystem.

How do I compare two variables containing strings in JavaScript?

You can use javascript dedicate string compare method string1.localeCompare(string2). it will five you -1 if the string not equals, 0 for strings equal and 1 if string1 is sorted after string2.

<script>
    var to_check=$(this).val();
    var cur_string=$("#0").text();
    var to_chk = "that";
    var cur_str= "that";
    if(to_chk.localeCompare(cur_str) == 0){
        alert("both are equal");
        $("#0").attr("class","correct");    
    } else {
        alert("both are not equal");
        $("#0").attr("class","incorrect");
    }
</script>

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

Note: I had the same problem, and it was because the referenced field was in a different collation in the 2 different tables (they had exact same type).

Make sure all your referenced fields have the same type AND the same collation!

Using HttpClient and HttpPost in Android with post parameters

You can actually send it as JSON the following way:

// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);

How to create cross-domain request?

In fact, there is nothing to do in Angular2 regarding cross domain requests. CORS is something natively supported by browsers. This link could help you to understand how it works:

To be short, in the case of cross domain request, the browser automatically adds an Origin header in the request. There are two cases:

  • Simple requests. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.
  • Preflighted requests. When the "simple requests" use case doesn't apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.

So in fact most of work must be done on the server side to return the CORS headers. The main one is the Access-Control-Allow-Origin one.

200 OK HTTP/1.1
(...)
Access-Control-Allow-Origin: *

To debug such issues, you can use developer tools within browsers (Network tab).

Regarding Angular2, simply use the Http object like any other requests (same domain for example):

return this.http.get('https://angular2.apispark.net/v1/companies/')
           .map(res => res.json()).subscribe(
  ...
);

What's the C# equivalent to the With statement in VB?

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

how to open Jupyter notebook in chrome on windows

For those who still have trouble launching Chrome automatically from cmd, try replacing

# c.NotebookApp.browser =''

in the file jupyter_notebook_config.py with

import webbrowser
webbrowser.register('chrome', None, webbrowser.GenericBrowser('C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'))
c.NotebookApp.browser = 'chrome'

or the appropriate location, there shouldn't be need to install anything via pip.

Ref: https://support.anaconda.com/customer/en/portal/articles/2925919-change-default-browser-in-jupyter-notebook

"Bitmap too large to be uploaded into a texture"

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    ///*
    if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK && null != data){



        uri = data.getData();

        String[] prjection ={MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(uri,prjection,null,null,null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(prjection[0]);

        ImagePath = cursor.getString(columnIndex);

        cursor.close();

        FixBitmap = BitmapFactory.decodeFile(ImagePath);

        ShowSelectedImage = (ImageView)findViewById(R.id.imageView);

      //  FixBitmap = new BitmapDrawable(ImagePath);
        int nh = (int) ( FixBitmap.getHeight() * (512.0 / FixBitmap.getWidth()) );
        FixBitmap = Bitmap.createScaledBitmap(FixBitmap, 512, nh, true);

       // ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath));

        ShowSelectedImage.setImageBitmap(FixBitmap);

    }
}

This code is work

Counting unique values in a column in pandas dataframe like in Qlik?

To count unique values in column, say hID of dataframe df, use:

len(df.hID.unique())

Android check internet connection

No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE permission and just make a connected method

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

You can also use requestRouteToHost if you have a particualr host and connection type (wifi/mobile) in mind.

You will also need:

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

in your android manifest.

for more detail go here

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

How can I hide an HTML table row <tr> so that it takes up no space?

If display: none; doesn't work, how about setting height: 0; instead? In conjunction with a negative margin (equal to, or greater than, the height of the top and bottom borders, if any) to further remove the element? I don't imagine that position: absolute; top: 0; left: -4000px; would work, but it might be worth a try.

For my part, using display: none works fine.

'App not Installed' Error on Android

for me the cause was that i had multiple builds using different build variants on same phone:

enter image description here

what happened was that some of these builds were built by me, another one was sent to me by another developer.. trying to install the developers while i had other builds (built by me) caused the above error.

so the fix was simple: delete all the builds on my phone (regardless of build variant).. then install the apk sent by my peer.. and it worked like a charm

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

I have a similar problem with IIS 7, Win 7 Enterprise Pack. I have changed the application Pool as in @Kirk answer :

Change the Application Pool mode to one that has Classic pipeline enabled".but no luck for me.

Adding one more step worked for me. I have changed the my website's .NET Frameworkis v2.0 to .NET Frameworkis v4.0. in ApplicationPool

AngularJS ui-router login authentication

First you'll need a service that you can inject into your controllers that has some idea of app authentication state. Persisting auth details with local storage is a decent way to approach it.

Next, you'll need to check the state of auth right before state changes. Since your app has some pages that need to be authenticated and others that don't, create a parent route that checks auth, and make all other pages that require the same be a child of that parent.

Finally, you'll need some way to tell if your currently logged in user can perform certain operations. This can be achieved by adding a 'can' function to your auth service. Can takes two parameters: - action - required - (ie 'manage_dashboards' or 'create_new_dashboard') - object - optional - object being operated on. For example, if you had a dashboard object, you may want to check to see if dashboard.ownerId === loggedInUser.id. (Of course, information passed from the client should never be trusted and you should always verify this on the server before writing it to your database).

angular.module('myApp', ['ngStorage']).config([
   '$stateProvider',
function(
   $stateProvider
) {
   $stateProvider
     .state('home', {...}) //not authed
     .state('sign-up', {...}) //not authed
     .state('login', {...}) //not authed
     .state('authed', {...}) //authed, make all authed states children
     .state('authed.dashboard', {...})
}])
.service('context', [
   '$localStorage',
function(
   $localStorage
) {
   var _user = $localStorage.get('user');
   return {
      getUser: function() {
         return _user;
      },
      authed: function() {
         return (_user !== null);
      },
      // server should return some kind of token so the app 
      // can continue to load authenticated content without having to
      // re-authenticate each time
      login: function() {
         return $http.post('/login.json').then(function(reply) {
            if (reply.authenticated === true) {
               $localStorage.set(_userKey, reply.user);
            }
         });
      },
      // this request should expire that token, rendering it useless
      // for requests outside of this session
      logout: function() {
         return $http.post('logout.json').then(function(reply) {
            if (reply.authenticated === true) {
               $localStorage.set(_userKey, reply.user);
            }
         });
      },
      can: function(action, object) {
         if (!this.authed()) {
            return false;
         }

         var user = this.getUser();

         if (user && user.type === 'admin') {
             return true;
         }

         switch(action) {
            case 'manage_dashboards':
               return (user.type === 'manager');
         }

         return false;


      }
   }
}])
.controller('AuthCtrl', [
   'context', 
   '$scope', 
function(
   context, 
   $scope
) {
   $scope.$root.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
      //only require auth if we're moving to another authed page
      if (toState && toState.name.indexOf('authed') > -1) {
         requireAuth();
      }
   });

   function requireAuth() {
      if (!context.authed()) {
         $state.go('login');
      }
   }
}]

** DISCLAIMER: The above code is pseudo-code and comes with no guarantees **

How to open a new tab in GNOME Terminal from command line?

I don't have gnome-terminal installed but you should be able to do this by using a DBUS call on the command-line using dbus-send.

std::wstring VS std::string

So, every reader here now should have a clear understanding about the facts, the situation. If not, then you must read paercebal's outstandingly comprehensive answer [btw: thanks!].

My pragmatical conclusion is shockingly simple: all that C++ (and STL) "character encoding" stuff is substantially broken and useless. Blame it on Microsoft or not, that will not help anyway.

My solution, after in-depth investigation, much frustration and the consequential experiences is the following:

  1. accept, that you have to be responsible on your own for the encoding and conversion stuff (and you will see that much of it is rather trivial)

  2. use std::string for any UTF-8 encoded strings (just a typedef std::string UTF8String)

  3. accept that such an UTF8String object is just a dumb, but cheap container. Do never ever access and/or manipulate characters in it directly (no search, replace, and so on). You could, but you really just really, really do not want to waste your time writing text manipulation algorithms for multi-byte strings! Even if other people already did such stupid things, don't do that! Let it be! (Well, there are scenarios where it makes sense... just use the ICU library for those).

  4. use std::wstring for UCS-2 encoded strings (typedef std::wstring UCS2String) - this is a compromise, and a concession to the mess that the WIN32 API introduced). UCS-2 is sufficient for most of us (more on that later...).

  5. use UCS2String instances whenever a character-by-character access is required (read, manipulate, and so on). Any character-based processing should be done in a NON-multibyte-representation. It is simple, fast, easy.

  6. add two utility functions to convert back & forth between UTF-8 and UCS-2:

    UCS2String ConvertToUCS2( const UTF8String &str );
    UTF8String ConvertToUTF8( const UCS2String &str );
    

The conversions are straightforward, google should help here ...

That's it. Use UTF8String wherever memory is precious and for all UTF-8 I/O. Use UCS2String wherever the string must be parsed and/or manipulated. You can convert between those two representations any time.

Alternatives & Improvements

  • conversions from & to single-byte character encodings (e.g. ISO-8859-1) can be realized with help of plain translation tables, e.g. const wchar_t tt_iso88951[256] = {0,1,2,...}; and appropriate code for conversion to & from UCS2.

  • if UCS-2 is not sufficient, than switch to UCS-4 (typedef std::basic_string<uint32_t> UCS2String)

ICU or other unicode libraries?

For advanced stuff.

Getting the closest string match

The problem is hard to implement if the input data is too large (say millions of strings). I used elastic search to solve this.

Quick start : https://www.elastic.co/guide/en/elasticsearch/client/net-api/6.x/elasticsearch-net.html

Just insert all the input data into DB and you can search any string based on any edit distance quickly. Here is a C# snippet which will give you a list of results sorted by edit distance (smaller to higher)

var res = client.Search<ClassName>(s => s
    .Query(q => q
    .Match(m => m
        .Field(f => f.VariableName)
        .Query("SAMPLE QUERY")
        .Fuzziness(Fuzziness.EditDistance(5))
    )
));

HashMap and int as key

For somebody who is interested in a such map because you want to reduce footprint of autoboxing in Java of wrappers over primitives types, I would recommend to use Eclipse collections. Trove isn't supported any more, and I believe it is quite unreliable library in this sense (though it is quite popular anyway) and couldn't be compared with Eclipse collections.

import org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap;

public class Check {
    public static void main(String[] args) {
        IntObjectHashMap map = new IntObjectHashMap();

        map.put(5,"It works");
        map.put(6,"without");
        map.put(7,"boxing!");

        System.out.println(map.get(5));
        System.out.println(map.get(6));
        System.out.println(map.get(7));
    }
}

In this example above IntObjectHashMap.

As you need int->object mapping, also consider usage of YourObjectType[] array or List<YourObjectType> and access values by index, as map is, by nature, an associative array with int type as index.

Android EditText Max Length

For me this solution works:

edittext.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

What are the differences between JSON and JSONP?

JSONP is essentially, JSON with extra code, like a function call wrapped around the data. It allows the data to be acted on during parsing.

Calling a Sub and returning a value

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

iTunes Connect: How to choose a good SKU?

As others have noted, "SKU" stands for stock keeping unit. Here's what I find currently (3 February 2017) in the Apple documentation regarding the "SKU Number:"

SKU Number

A unique ID for your app in the Apple system that is not seen by users. You can use letters, numbers, hyphens, periods, and underscores. The SKU can’t
start with a hyphen, period, or underscore. Use a value that is meaningful to your organization. Can’t be edited after saving the iTunes Connect record.

(internet archive link:) iTunes Connect Properties

setOnItemClickListener on custom ListView

If in the listener you get the root layout of the item (say itemLayout), and you gave some id's to the textviews, you can then get them with something like itemLayout.findViewById(R.id.textView1).

Color picker utility (color pipette) in Ubuntu

I recommend GPick:

sudo apt-get install gpick

Applications -> Graphics -> GPick

It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.

If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.

It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.

How to use Bootstrap in an Angular project?

add the following lines in your html page

<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

Linux command to print directory structure in the form of a tree

This command works to display both folders and files.

find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"

Example output:

.
 |-trace.pcap
 |-parent
 | |-chdir1
 | | |-file1.txt
 | |-chdir2
 | | |-file2.txt
 | | |-file3.sh
 |-tmp
 | |-json-c-0.11-4.el7_0.x86_64.rpm

Source: Comment from @javasheriff here. Its submerged as a comment and posting it as answer helps users spot it easily.

How to get the Power of some Integer in Swift language?

little detail more

   infix operator ^^ { associativity left precedence 160 }
   func ^^ (radix: Int, power: Int) -> Int {
       return Int(pow(CGFloat(radix), CGFloat(power)))
   }

swift - Binary Expressions

How to add parameters to HttpURLConnection using POST using NameValuePair

Parameters to HttpURLConnection using POST using NameValuePair with OutPut

        try {
        URL url = new URL("https://yourUrl.com");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");

        conn.setRequestProperty("Content-Type", "application/json");

        JSONObject data = new JSONObject();
        data.put("key1", "value1");
        data.put("key2", "value2");

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data.toString());
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

How to plot vectors in python using matplotlib

In order to match the vector lenght and angle with the x,y coordinates of the plot, you can use to following options to plt.quiver:

plt.figure(figsize=(5,2), dpi=100)
plt.quiver(0,0,250,100, angles='xy', scale_units='xy', scale=1)
plt.xlim(0,250)
plt.ylim(0,100)

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

How to know which version of Symfony I have?

From inside your Symfony project, you can get the value in PHP this way:

$symfony_version = \Symfony\Component\HttpKernel\Kernel::VERSION;

using mailto to send email with an attachment

If you are using c# on the desktop, you can use SimpleMapi. That way it will be sent using the default mail client, and the user has the option of reviewing the message before sending, just like mailto:.

To use it you add the Simple-MAPI.NET package (it's 13Kb), and run:

var mapi = new SimpleMapi();
mapi.AddRecipient(null, address, false);
mapi.Attach(path);
//mapi.Logon(ParentForm.Handle);    //not really necessary
mapi.Send(subject, body, true);

CASE in WHERE, SQL Server

You can simplify to:

WHERE a.Country = COALESCE(NULLIF(@Country,0), a.Country);

How to manipulate arrays. Find the average. Beginner Java

Well, to calculate the average of an array, you can consider using for loop instead of while loop.

So as per your question let me assume an array as arrNumbers ( here i'm considering the same array elements as in your question )

int arrNumbers[] = new int[]{1, 3, 2, 5, 8};
int sum = 0;

for(int a = 0; a < arrNumbers.length; a++)
{
   sum = sum + arrNumbers[a];
}

double average = sum / arrNumbers.length;

System.out.println("Average is: " + average);

You can use scanner class as well. It's left to you.

How to search contents of multiple pdf files?

There is another utility called ripgrep-all, which is based on ripgrep.

It can handle more than just PDF documents, like Office documents and movies, and the author claims it is faster than pdfgrep.

Command syntax for recursively searching the current directory, and the second one limits to PDF files only:

rga 'pattern' .
rga --type pdf 'pattern' .

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Look at https://stackoverflow.com/a/4726838/2963099

Turn off pre compiled headers:

Project Properties -> C++ -> Precompiled Headers

set Precompiled Header to "Not Using Precompiled Header".

How to Get True Size of MySQL Database?

if you want to find it in MB do this

SELECT table_schema                                        "DB Name", 
   Round(Sum(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" 
FROM   information_schema.tables 
GROUP  BY table_schema; 

How do I capture the output of a script if it is being ran by the task scheduler?

You can write to a log file on the lines that you want to output like this:

@echo off
echo Debugging started >C:\logfile.txt
echo More stuff
echo Debugging stuff >>C:\logfile.txt
echo Hope this helps! >>C:\logfile.txt

This way you can choose which commands to output if you don't want to trawl through everything, just get what you need to see. The > will output it to the file specified (creating the file if it doesn't exist and overwriting it if it does). The >> will append to the file specified (creating the file if it doesn't exist but appending to the contents if it does).

How can I access getSupportFragmentManager() in a fragment?

My Parent Activity extends AppCompatActivity so I had to cast my context to AppCompatActivity instead of just Activity.

eg.

FragmentAddProduct fragmentAddProduct = FragmentAddProduct.newInstance();
FragmentTransaction fragmentTransaction = ((AppCompatActivity)mcontext).getSupportFragmentManager().beginTransaction();

ASP.Net MVC 4 Form with 2 submit buttons/actions

With HTML5 you can use button[formaction]:

<form action="Edit">
  <button type="submit">Submit</button> <!-- Will post to default action "Edit" -->
  <button type="submit" formaction="Validate">Validate</button> <!-- Will override default action and post to "Validate -->
</form>

How can I change the color of my prompt in zsh (different from normal text)?

Here's an example of how to set a red prompt:

PS1=$'\e[0;31m$ \e[0m'

The magic is the \e[0;31m (turn on red foreground) and \e[0m (turn off character attributes). These are called escape sequences. Different escape sequences give you different results, from absolute cursor positioning, to color, to being able to change the title bar of your window, and so on.

For more on escape sequences, see the wikipedia entry on ANSI escape codes

Javascript: How to pass a function with string parameters as a parameter to another function

Me, I'd do it something like this:

HTML:

onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"

JS:

function myfunction(params)
{
  var path = params.path;

  /* do stuff */

  // on ok condition 
  params.ok(params.okArgs);

  // on cancel condition
  params.cancel(params.cancelArgs);  
}

But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.

Find the server name for an Oracle database

If you don't have access to the v$ views (as suggested by Quassnoi) there are two alternatives

select utl_inaddr.get_host_name from dual

and

select sys_context('USERENV','SERVER_HOST') from dual

Personally I'd tend towards the last as it doesn't require any grants/privileges which makes it easier from stored procedures.

How to make a smaller RatingBar?

The default RatingBar widget is sorta' lame.

The source makes reference to style "?android:attr/ratingBarStyleIndicator" in addition to the "?android:attr/ratingBarStyleSmall" that you're already familiar with. ratingBarStyleIndicator is slightly smaller but it's still pretty ugly and the comments note that these styles "don't support interaction".

You're probably better-off rolling your own. There's a decent-looking guide at http://kozyr.zydako.net/2010/05/23/pretty-ratingbar/ showing how to do this. (I haven't done it myself yet, but will be attempting in a day or so.)

Good luck!

p.s. Sorry, was going to post a link to the source for you to poke around in but I'm a new user and can't post more than 1 URL. If you dig your way through the source tree, it's located at frameworks/base/core/java/android/widget/RatingBar.java

Declaring static constants in ES6 classes?

class Whatever {
    static get MyConst() { return 10; }
}

let a = Whatever.MyConst;

Seems to work for me.

AJAX cross domain call

after doing some research, the only "solution" to this problem is to call:

if($.browser.mozilla)
   netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');

this will ask an user if he allows a website to continue. After he confirmed that, all ajax calls regardless of it's datatype will get executed.

This works for mozilla browsers, in IE < 8, an user has to allow a cross domain call in a similar way, some version need to get configured within browser options.

chrome/safari: I didn't find a config flag for those browsers so far.

using JSONP as datatype would be nice, but in my case I don't know if a domain I need to access supports data in that format.

Another shot is to use HTML5 postMessage which works cross-domain aswell, but I can't afford to doom my users to HTML5 browsers.

How to set underline text on textview?

Following are the some approaches for underlined text in android:

1st Approach

You can define your string in strings.xml

<string name="your_string"><u>Underlined text</u></string>

And use that string in your xml file

<TextView
            android:id="@+id/txt_underlined"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/your_string"/>

Or you can use that string in your Activity/Fragment

txtView.setText(R.string.your_string);

2nd Approach

To underline the text in TextView, you can use SpannableString

String text="Underlined Text";
SpannableString content = new SpannableString(text);
content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
txtView.setText(content);

3rd Approach

You can make use of setPaintFlags method of TextView to underline the text of TextView.

txtView.setPaintFlags(mTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
txtView.setText("Underlined Text");

4th Approach

Make use of Html.fromHtml(htmlString);

String htmlString="<u>Underlined Text</u>";
txtView.setText(Html.fromHtml(htmlString));

Or

txtView.setText(Html.fromHtml("<u>underlined</u> text"));

Note:

If you have added this line android:textAllCaps="true" in your layout, then none of the above will work. For that, you have to define your string in Caps and then any of the above approach.

Completely Remove MySQL Ubuntu 14.04 LTS

The following works:

sudo apt-get --purge remove mysql-client mysql-server mysql-common
sudo apt-get autoremove

send mail from linux terminal in one line

mail can represent quite a couple of programs on a linux system. What you want behind it is either sendmail or postfix. I recommend the latter.

You can install it via your favorite package manager. Then you have to configure it, and once you have done that, you can send email like this:

 echo "My message" | mail -s subject [email protected]

See the manual for more information.

As far as configuring postfix goes, there's plenty of articles on the internet on how to do it. Unless you're on a public server with a registered domain, you generally want to forward the email to a SMTP server that you can send email from.

For gmail, for example, follow http://rtcamp.com/tutorials/linux/ubuntu-postfix-gmail-smtp/ or any other similar tutorial.

What is the difference between include and require in Ruby?

From Programming Ruby 1.9

We’ll make a couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include. Second, a Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they’ll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior.

How to add "active" class to Html.ActionLink in ASP.NET MVC

Extension:

public static MvcHtmlString LiActionLink(this HtmlHelper html, string text, string action, string controller)
{
    var context = html.ViewContext;
    if (context.Controller.ControllerContext.IsChildAction)
        context = html.ViewContext.ParentActionViewContext;
    var routeValues = context.RouteData.Values;
    var currentAction = routeValues["action"].ToString();
    var currentController = routeValues["controller"].ToString();

    var str = String.Format("<li role=\"presentation\"{0}>{1}</li>",
        currentAction.Equals(action, StringComparison.InvariantCulture) &&
        currentController.Equals(controller, StringComparison.InvariantCulture) ?
        " class=\"active\"" :
        String.Empty, html.ActionLink(text, action, controller).ToHtmlString()
    );
    return new MvcHtmlString(str);
}

Usage:

<ul class="nav navbar-nav">
    @Html.LiActionLink("About", "About", "Home")
    @Html.LiActionLink("Contact", "Contact", "Home")
</ul>

Use CSS to automatically add 'required field' asterisk to form inputs

What you need is :required selector - it will select all fields with 'required' attribute (so no need to add any additional classes). Then - style inputs according to your needs. You can use ':after' selector and add asterisk in the way suggested among other answers

java comparator, how to sort by integer?

One simple way is

Comparator<Dog> ageAscendingComp = ...;
Comparator<Dog> ageDescendingComp = Collections.reverseOrder(ageAscendingComp);
// then call the sort method

On a side note, Dog should really not implement Comparator. It means you have to do strange things like

Collections.sort(myList, new Dog("Rex", 4));
// ^-- why is a new dog being made? What are we even sorting by?!
Collections.sort(myList, myList.get(0));
// ^-- or perhaps more confusingly

Rather you should make Compartors as separate classes.

eg.

public class DogAgeComparator implments Comparator<Dog> {
    public int compareTo(Dog d1, Dog d2) {
        return d1.getAge() - d2.getAge();
    }
}

This has the added benefit that you can use the name of the class to say how the Comparator will sort the list. eg.

Collections.sort(someDogs, new DogNameComparator());
// now in name ascending order

Collections.sort(someDogs, Collections.reverseOrder(new DogAgeComparator()));
// now in age descending order

You should also not not have Dog implement Comparable. The Comparable interface is used to denote that there is some inherent and natural way to order these objects (such as for numbers and strings). Now this is not the case for Dog objects as sometimes you may wish to sort by age and sometimes you may wish to sort by name.

docker unauthorized: authentication required - upon push with successful login

You'll need to log in to Docker.

Step 1: log in to docker hub

Based on @KaraPirinc's comment, in Docker version 17 in order to log in:

docker login -u username --password-stdin

Then enter your password when asked.

Step 2: create a repository in the docker hub.

Let's say "mysqlserver:sql".

docker push <user username>/mysqlserver:sql

performSelector may cause a leak because its selector is unknown

Because you are using ARC you must be using iOS 4.0 or later. This means you could use blocks. If instead of remembering the selector to perform you instead took a block, ARC would be able to better track what is actually going on and you wouldn't have to run the risk of accidentally introducing a memory leak.

simple HTTP server in Java using only Java SE API

Since Java SE 6, there's a builtin HTTP server in Sun Oracle JRE. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.

Here's a kickoff example copypasted from their docs (to all people trying to edit it nonetheless, because it's an ugly piece of code, please don't, this is a copy paste, not mine, moreover you should never edit quotations unless they have changed in the original source). You can just copy'n'paste'n'run it on Java 6+.

package com.stackoverflow.q3732109;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class Test {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/test", new MyHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

}

Noted should be that the response.length() part in their example is bad, it should have been response.getBytes().length. Even then, the getBytes() method must explicitly specify the charset which you then specify in the response header. Alas, albeit misguiding to starters, it's after all just a basic kickoff example.

Execute it and go to http://localhost:8000/test and you'll see the following response:

This is the response


As to using com.sun.* classes, do note that this is, in contrary to what some developers think, absolutely not forbidden by the well known FAQ Why Developers Should Not Write Programs That Call 'sun' Packages. That FAQ concerns the sun.* package (such as sun.misc.BASE64Encoder) for internal usage by the Oracle JRE (which would thus kill your application when you run it on a different JRE), not the com.sun.* package. Sun/Oracle also just develop software on top of the Java SE API themselves like as every other company such as Apache and so on. Using com.sun.* classes is only discouraged (but not forbidden) when it concerns an implementation of a certain Java API, such as GlassFish (Java EE impl), Mojarra (JSF impl), Jersey (JAX-RS impl), etc.

How to check queue length in Python

Yes we can check the length of queue object created from collections.

from collections import deque
class Queue():
    def __init__(self,batchSize=32):
        #self.batchSie = batchSize
        self._queue = deque(maxlen=batchSize)

    def enqueue(self, items):
        ''' Appending the items to the queue'''
        self._queue.append(items)

    def dequeue(self):
        '''remoe the items from the top if the queue becomes full '''
        return self._queue.popleft()

Creating an object of class

q = Queue(batchSize=64)
q.enqueue([1,2])
q.enqueue([2,3])
q.enqueue([1,4])
q.enqueue([1,22])

Now retrieving the length of the queue

#check the len of queue
print(len(q._queue)) 
#you can print the content of the queue
print(q._queue)
#Can check the content of the queue
print(q.dequeue())
#Check the length of retrieved item 
print(len(q.dequeue()))

check the results in attached screen shot

enter image description here

Hope this helps...

ASP.NET Identity DbContext confusion

I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.

Codeigniter unset session

Instead of use set_userdata you should use set_flashdata.

According to CI user guide:

CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: "record 2 deleted").

http://ellislab.com/codeigniter/user-guide/libraries/sessions.html

How to change the color of a button?

The RIGHT way...

The following methods actually work.

if you wish - using a theme
By default a buttons color is android:colorAccent. So, if you create a style like this...

<style name="Button.White" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@android:color/white</item>
</style>

You can use it like this...

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Button.White"
    />

alternatively - using a tint
You can simply add android:backgroundTint for API Level 21 and higher, or app:backgroundTint for API Level 7 and higher.

For more information, see this blog.

The problem with the accepted answer...

If you replace the background with a color you will loose the effect of the button, and the color will be applied to the entire area of the button. It will not respect the padding, shadow, and corner radius.

JSON.parse unexpected token s

Because JSON has a string data type (which is practically anything between " and "). It does not have a data type that matches something

The character encoding of the plain text document was not declared - mootool script

In my case in ASP MVC it was a method in controller that was returning null to View because of a wrong if statement.

if (condition)
{
    return null;
}

Condition fixed and I returned View, Problem fixed. There was nothing with encoding but I don't know why that was my error.

return View(result); // result is View's model

Highcharts - redraw() vs. new Highcharts.chart

var newData = [1,2,3,4,5,6,7];
var chart = $('#chartjs').highcharts();
chart.series[0].setData(newData, true);

Explanation:
Variable newData contains value that want to update in chart. Variable chart is an object of a chart. setData is a method provided by highchart to update data.

Method setData contains two parameters, in first parameter we need to pass new value as array and second param is Boolean value. If true then chart updates itself and if false then we have to use redraw() method to update chart (i.e chart.redraw();)

http://jsfiddle.net/NxEnH/8/

Comparing strings by their alphabetical order

String.compareTo might or might not be what you need.

Take a look at this link if you need localized ordering of strings.

how to stop a running script in Matlab

if you are running your matlab on linux, you can terminate the matlab by command in linux consule. first you should find the PID number of matlab by this code:

top

then you can use this code to kill matlab: kill

example: kill 58056

Could not open ServletContext resource

I think currently the application-context.xml file is into src/main/resources AND the social.properties file is into src/main/java... so when you package (mvn package) or when you run tomcat (mvn tomcat:run) your social.properties disappeared (I know you said when you checked into the .war the files are here... but your exception says the opposite).

The solution is simply to put all your configuration files (application-context.xml and social.properties) into src/main/resources to follow the maven standard structure.

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

mysql.exe->Run as administrator or go to following path C:\wamp\bin\mysql\mysql5.5.24\bin and than right click on mysql.exe go to properties and than select tab as Compatibility and see the bottom of dialog box in privilege level and just check the Run this program as an administrator and then click apply ok.finished now you open success phpMyadmin. bye

MySQL: Fastest way to count number of rows

This is the best query able to get the fastest results.

SELECT SQL_CALC_FOUND_ROWS 1 FROM `orders`;
SELECT FOUND_ROWS();

In my benchmark test: 0.448s

enter image description here

This query takes 4.835s

SELECT SQL_CALC_FOUND_ROWS * FROM `orders`;
SELECT FOUND_ROWS();

enter image description here

count * takes 25.675s

SELECT count(*) FROM `orders`;

enter image description here

How long to brute force a salted SHA-512 hash? (salt provided)

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack), you just need to find an output of the hash function that is equal to the hash of a valid password (thus "collision"). Finding a collision using a birthday attack takes O(2^(n/2)) time, where n is the output length of the hash function in bits.

SHA-2 has an output size of 512 bits, so finding a collision would take O(2^256) time. Given there are no clever attacks on the algorithm itself (currently none are known for the SHA-2 hash family) this is what it takes to break the algorithm.

To get a feeling for what 2^256 actually means: currently it is believed that the number of atoms in the (entire!!!) universe is roughly 10^80 which is roughly 2^266. Assuming 32 byte input (which is reasonable for your case - 20 bytes salt + 12 bytes password) my machine takes ~0,22s (~2^-2s) for 65536 (=2^16) computations. So 2^256 computations would be done in 2^240 * 2^16 computations which would take

2^240 * 2^-2 = 2^238 ~ 10^72s ~ 3,17 * 10^64 years

Even calling this millions of years is ridiculous. And it doesn't get much better with the fastest hardware on the planet computing thousands of hashes in parallel. No human technology will be able to crunch this number into something acceptable.

So forget brute-forcing SHA-256 here. Your next question was about dictionary words. To retrieve such weak passwords rainbow tables were used traditionally. A rainbow table is generally just a table of precomputed hash values, the idea is if you were able to precompute and store every possible hash along with its input, then it would take you O(1) to look up a given hash and retrieve a valid preimage for it. Of course this is not possible in practice since there's no storage device that could store such enormous amounts of data. This dilemma is known as memory-time tradeoff. As you are only able to store so many values typical rainbow tables include some form of hash chaining with intermediary reduction functions (this is explained in detail in the Wikipedia article) to save on space by giving up a bit of savings in time.

Salts were a countermeasure to make such rainbow tables infeasible. To discourage attackers from precomputing a table for a specific salt it is recommended to apply per-user salt values. However, since users do not use secure, completely random passwords, it is still surprising how successful you can get if the salt is known and you just iterate over a large dictionary of common passwords in a simple trial and error scheme. The relationship between natural language and randomness is expressed as entropy. Typical password choices are generally of low entropy, whereas completely random values would contain a maximum of entropy.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords. If you google for them, you will end up finding torrent links for such password databases, often in the gigabyte size category. Being successful with such a tool is usually in the range of minutes to days if the attacker is not restricted in any way.

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5 and you should enforce a waiting period for a given user before they may retry entering their password. A good scheme is to start with 0.5s and then doubling that time for each failed attempt. In most cases users don't notice this and don't fail much more often than three times on average. But it will significantly slow down any malicious outsider trying to attack your application.

Groovy String to Date

Below is the way we are going within our developing application.

import java.text.SimpleDateFormat

String newDateAdded = "2018-11-11T09:30:31"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
Date dateAdded = dateFormat.parse(newDateAdded)

println(dateAdded)

The output looks like

Sun Nov 11 09:30:31 GMT 2018

In your example, we could adjust a bit to meet your need. If I were you, I will do:

String datePattern = "d/M/yyyy H:m:s"
String theDate = "28/09/2010 16:02:43"
SimpleDateFormat df = new SimpleDateFormat(datePattern)
println df.parse(theDate)

I hope this would help you much.

JavaScript: replace last occurrence of text in a string

A simple answer without any regex would be:

str = str.substr(0, str.lastIndexOf(list[i])) + 'finish'

Printing an array in C++?

It certainly is! You'll have to loop through the array and print out each item individually.

How can I pad a String in Java?

Apache StringUtils has several methods: leftPad, rightPad, center and repeat.

But please note that — as others have mentioned and demonstrated in this answerString.format() and the Formatter classes in the JDK are better options. Use them over the commons code.

Regular Expressions and negating a whole character group

Simplest way is to pull the negation out of the regular expression entirely:

if (!userName.matches("^([Ss]ys)?admin$")) { ... }

How do I copy to the clipboard in JavaScript?

In browsers other than Internet Explorer you need to use a small Flash object to manipulate the clipboard, e.g.

C++ style cast from unsigned char * to const char *

char * and const unsigned char * are considered unrelated types. So you want to use reinterpret_cast.

But if you were going from const unsigned char* to a non const type you'd need to use const_cast first. reinterpret_cast cannot cast away a const or volatile qualification.

Drawing an SVG file on a HTML5 canvas

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

Firefox 'Cross-Origin Request Blocked' despite headers

In my case CORS error was happening only in POST requests with file attachments other than small files.

After many wasted hours we found out request was blocked for users who were using Kaspersky Total Control.

It's possible that other antivirus or firewall software may cause similar problems. Kaspersky run some security tests for requests, but omits them for websites with SSL EV certificate, so obtaining such certificate should resolve this issue properly.

Disabling protection for your domain is a bit tricky, so here are required steps (as for December 2020): Settings -> Network Settings -> Manage exclusions -> Add -> your domain -> Save

The good thing is you can detect such blocked request. The error is empty – it doesn't have status and response. This way you can assume it was blocked by third party software and show some info.

How to create composite primary key in SQL Server 2008

Via Enterprise Manager (SSMS)...

  • Right Click on the Table you wish to create the composite key on and select Design.
  • Highlight the columns you wish to form as a composite key
  • Right Click over those columns and Set Primary Key

To see the SQL you can then right click on the Table > Script Table As > Create To

JavaScript - get the first day of the week from current date

I'm using this

function get_next_week_start() {
   var now = new Date();
   var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
   return next_week_start;
}

What exactly is the 'react-scripts start' command?

"start" is a name of a script, in npm you run scripts like this npm run scriptName, npm start is also a short for npm run start

As for "react-scripts" this is a script related specifically to create-react-app

Is there a way to make numbers in an ordered list bold?

I had a similar issue while writing a newsletter. So I had to inline the style this way:

<ol>
    <li style="font-weight:bold"><span style="font-weight:normal">something</span></li>
    <li style="font-weight:bold"><span style="font-weight:normal">something</span></li>
    <li style="font-weight:bold"><span style="font-weight:normal">something</span></li>
</ol>

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

I was successful with this method today. It's similar to the other answers in that it also converts the contents to XML, just using a different method. As I didn't see FOR XML PATH mentioned amongst the answers, I thought I'd add it for completeness:

SELECT [COL_NVARCHAR_MAX]
  FROM [SOME_TABLE]
  FOR XML PATH(''), ROOT('ROOT')

This will deliver a valid XML containing the contents of all rows, nested in an outer <ROOT></ROOT> element. The contents of the individual rows will each be contained within an element that, for this example, is called <COL_NVARCHAR_MAX>. The name of that can be changed using an alias via AS.

Special characters like &, < or > or similar will be converted to their respective entities. So you may have to convert &lt;, &gt; and &amp; back to their original character, depending on what you need to do with the result.

EDIT

I just realized that CDATA can be specified using FOR XML too. I find it a bit cumbersome though. This would do it:

SELECT 1 as tag, 0 as parent, [COL_NVARCHAR_MAX] as [COL_NVARCHAR_MAX!1!!CDATA]
  FROM [SOME_TABLE]
  FOR XML EXPLICIT, ROOT('ROOT')

Replace \n with actual new line in Sublime Text

the easiest way, you can copy the newline (copy empty 2 line in text editor) then paste on replace with.

View content of H2 or HSQLDB in-memory database

You can expose it as a JMX feature, startable via JConsole:

@ManagedResource
@Named
public class DbManager {

    @ManagedOperation(description = "Start HSQL DatabaseManagerSwing.")
    public void dbManager() {
        String[] args = {"--url", "jdbc:hsqldb:mem:embeddedDataSource", "--noexit"};
        DatabaseManagerSwing.main(args);
    }
}

XML context:

<context:component-scan base-package="your.package.root" scoped-proxy="targetClass"/>
<context:annotation-config />
<context:mbean-server />
<context:mbean-export />

Unsuccessful append to an empty NumPy array

numpy.append always copies the array before appending the new values. Your code is equivalent to the following:

import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)

Perhaps you mean to do this?

import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])

How to submit a form using PhantomJS

As it was mentioned above CasperJS is the best tool to fill and send forms. Simplest possible example of how to fill & submit form using fill() function:

casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
  this.fill('form#loginForm', {
    'login':    'admin',
    'password':    '12345678'
   }, true);
  this.evaluate(function(){
    //trigger click event on submit button
    document.querySelector('input[type="submit"]').click();
  });
});

Export MySQL database using PHP only

I would Suggest that you do the folllowing,

<?php

function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false)
{
    $mysqli      = new mysqli($host, $user, $pass, $name);
    $mysqli->select_db($name);
    $mysqli->query("SET NAMES 'utf8'");
    $queryTables = $mysqli->query('SHOW TABLES');
    while ($row         = $queryTables->fetch_row())
    {
        $target_tables[] = $row[0];
    }
    if ($tables !== false)
    {
        $target_tables = array_intersect($target_tables, $tables);
    }
    $content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--Database: `" . $name . "`\r\n\r\n\r\n";
    foreach ($target_tables as $table)
    {
        $result        = $mysqli->query('SELECT * FROM ' . $table);
        $fields_amount = $result->field_count;
        $rows_num      = $mysqli->affected_rows;
        $res           = $mysqli->query('SHOW CREATE TABLE ' . $table);
        $TableMLine    = $res->fetch_row();
        $content .= "\n\n" . $TableMLine[1] . ";\n\n";
        for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0)
        {
            while ($row = $result->fetch_row())
            { //when started (and every after 100 command cycle):
                if ($st_counter % 100 == 0 || $st_counter == 0)
                {
                    $content .= "\nINSERT INTO " . $table . " VALUES";
                }
                $content .= "\n(";
                for ($j = 0; $j < $fields_amount; $j++)
                {
                    $row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
                    if (isset($row[$j]))
                    {
                        $content .= '"' . $row[$j] . '"';
                    }
                    else
                    {
                        $content .= '""';
                    } if ($j < ($fields_amount - 1))
                    {
                        $content.= ',';
                    }
                }
                $content .=")";
                //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num)
                {
                    $content .= ";";
                }
                else
                {
                    $content .= ",";
                } $st_counter = $st_counter + 1;
            }
        } $content .="\n\n\n";
    }
    $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
    $backup_name = $backup_name ? $backup_name : $name . "___(" . date('H-i-s') . "_" . date('d-m-Y') . ")__rand" . rand(1, 11111111) . ".sql";
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary");
    header("Content-disposition: attachment; filename=\"" . $backup_name . "\"");
    echo $content;
    exit;
}
?>

The enitre project for export and import can be found at https://github.com/tazotodua/useful-php-scripts.

What is the maximum number of characters that nvarchar(MAX) will hold?

2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).

nchar and nvarchar

CodeIgniter - How to return Json response from controller

This is not your answer and this is an alternate way to process the form submission

$('.signinform').click(function(e) { 
      e.preventDefault();
      $.ajax({
      type: "POST",
      url: 'index.php/user/signin', // target element(s) to be updated with server response 
      dataType:'json',
      success : function(response){ console.log(response); alert(response)}
     });
}); 

Call method when home button pressed

use onPause() method to do what you want to do on home button.

Python: Making a beep noise

The cross-platform way:

import time
import sys
for i in range(1,6):
    sys.stdout.write('\r\a{i}'.format(i=i))
    sys.stdout.flush()
    time.sleep(1)
sys.stdout.write('\n')

How to downgrade Node version

 curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
 sudo npm install -g n
 sudo n 10.15
 npm install
 npm audit fix
 npm start

jQuery: If this HREF contains

use this

$("a").each(function () {
    var href=$(this).prop('href');
    if (href.indexOf('?') > -1) {
        alert("Contains questionmark");
    }
});

Invoke a second script with arguments from a script

Much simpler actually:

Method 1:

Invoke-Expression $scriptPath $argumentList

Method 2:

& $scriptPath $argumentList

Method 3:

$scriptPath $argumentList

If you have spaces in your scriptPath, don't forget to escape them `"$scriptPath`"

Open a URL in a new tab (and not a new window)

I think that you can't control this. If the user had setup their browser to open links in a new window, you can't force this to open links in a new tab.

JavaScript open in a new window, not tab

How to open an existing project in Eclipse?

Maybe you have closed the project and configured the project explorer view to filter closed projects.

In that case, have a look at Filters in the Project Explorer view. Make sure that closed projects are disabled in the "Filters" view.

Find something in column A then show the value of B for that row in Excel 2010

I figured out such data design:

Main sheet: Column A: Pump codes (numbers)

Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'

=ROW(Pump_codes)+MATCH(A2;Ruhrpumpen!$I$5:$I$100;0)

Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.

Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B

=INDIRECT("Ruhrpumpen!A"&$B2)

Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:

=INDIRECT("Ruhrpumpen!B"&$B2)

Sheet 'Ruhrpumpen':

Column A: some data about a certain pump

Column B: some more data

Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.

Spreadsheet example: http://www.bumpclub.ee/~jyri_r/Excel/Data_from_other_sheet_by_code_row.xls

IndentationError: unexpected unindent WHY?

This error could actually be in the code preceding where the error is reported. See the For example, if you have a syntax error as below, you'll get the indentation error. The syntax error is actually next to the "except" because it should contain a ":" right after it.

try:
    #do something
except
    print 'error/exception'


def printError(e):
    print e

If you change "except" above to "except:", the error will go away.

Good luck.

Can you force Vue.js to reload/re-render?

Use vm.$set('varName', value). Look for details into Change_Detection_Caveats.

How do I collapse a table row in Bootstrap?

Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.

In 2.3.2 the collapse class wasn't getting replaced by the in class. The in class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse class correctly is removed, and the <tr> collapses.

Use @Chad's solution for the html, and try using these links for referencing Bootstrap:

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>

How to get height of <div> in px dimension

Use height():

var result = $("#myDiv").height();
alert(result);

This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.

If you want to do it without jQuery, you can use plain JavaScript:

var result = document.getElementById("myDiv").offsetHeight;

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Understanding inplace=True

In pandas, is inplace = True considered harmful, or not?

TLDR; Yes, yes it is.

  • inplace, contrary to what the name implies, often does not prevent copies from being created, and (almost) never offers any performance benefits
  • inplace does not work with method chaining
  • inplace can lead to SettingWithCopyWarning if used on a DataFrame column, and may prevent the operation from going though, leading to hard-to-debug errors in code

The pain points above are common pitfalls for beginners, so removing this option will simplify the API.


I don't advise setting this parameter as it serves little purpose. See this GitHub issue which proposes the inplace argument be deprecated api-wide.

It is a common misconception that using inplace=True will lead to more efficient or optimized code. In reality, there are absolutely no performance benefits to using inplace=True. Both the in-place and out-of-place versions create a copy of the data anyway, with the in-place version automatically assigning the copy back.

inplace=True is a common pitfall for beginners. For example, it can trigger the SettingWithCopyWarning:

df = pd.DataFrame({'a': [3, 2, 1], 'b': ['x', 'y', 'z']})

df2 = df[df['a'] > 1]
df2['b'].replace({'x': 'abc'}, inplace=True)
# SettingWithCopyWarning: 
# A value is trying to be set on a copy of a slice from a DataFrame

Calling a function on a DataFrame column with inplace=True may or may not work. This is especially true when chained indexing is involved.

As if the problems described above aren't enough, inplace=True also hinders method chaining. Contrast the working of

result = df.some_function1().reset_index().some_function2()

As opposed to

temp = df.some_function1()
temp.reset_index(inplace=True)
result = temp.some_function2()

The former lends itself to better code organization and readability.


Another supporting claim is that the API for set_axis was recently changed such that inplace default value was switched from True to False. See GH27600. Great job devs!

Adding a new entry to the PATH variable in ZSH

You can append to your PATH in a minimal fashion. No need for parentheses unless you're appending more than one element. It also usually doesn't need quotes. So the simple, short way to append is:

path+=/some/new/bin/dir

This lower-case syntax is using path as an array, yet also affects its upper-case partner equivalent, PATH (to which it is "bound" via typeset).

(Notice that no : is needed/wanted as a separator.)

Common interactive usage

Then the common pattern for testing a new script/executable becomes:

path+=$PWD/.
# or
path+=$PWD/bin

Common config usage

You can sprinkle path settings around your .zshrc (as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)).

Related tidbits

Treating path this way (as an array) also means: no need to do a rehash to get the newly pathed commands to be found.

Also take a look at vared path as a dynamic way to edit path (and other things).

You may only be interested in path for this question, but since we're talking about exports and arrays, note that arrays generally cannot be exported.

You can even prevent PATH from taking on duplicate entries (refer to this and this):

typeset -U path

Change value of input placeholder via model?

As Wagner Francisco said, (in JADE)

input(type="text", ng-model="someModel", placeholder="{{someScopeVariable}}")`

And in your controller :

$scope.someScopeVariable = 'somevalue'

How can I remove non-ASCII characters but leave periods and spaces using Python?

Working my way through Fluent Python (Ramalho) - highly recommended. List comprehension one-ish-liners inspired by Chapter 2:

onlyascii = ''.join([s for s in data if ord(s) < 127])
onlymatch = ''.join([s for s in data if s in
              'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'])

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

[Original answer]: You can still use launchctl setenv variablename value to set a variable so that is picked up by all applications (graphical applications started via the Dock or Spotlight, in addition to those started via the terminal).

Obviously you will not want to do this every time you login.

[Edit]: To avoid this, launch AppleScript Editor, enter a command like this:

do shell script "launchctl setenv variablename value"

(Use multiple lines if you want to set multiple variables)

Now save (?+s) as File format: Application. Finally open System Settings ? Users & Groups ? Login Items and add your new application.

[Original answer]: To work around this place all the variables you wish to define in a short shell script, then have a look at this previous answer about how to run a script on MacOS login. That way the the script will be invoked when the user logs in.

[Edit]: Neither solution is perfect as the variables will only be set for that specific user but I am hoping/guessing that may be all you require.

If you do have multiple users you could either manually set a Login Item for each of them or place a copy of com.user.loginscript.plist in each of their local Library/LaunchAgents directories, pointing at the same shell script.

Granted, neither of these workarounds is as convenient as /etc/launchd.conf.

[Further Edit]: A user below mentions that this did not work for him. However I have tested on multiple Yosemite machines and it does work for me. If you are having a problem, remember that you will need to restart applications for this to take effect. Additionally if you set variables in the terminal via ~/.profile or ~/.bash_profile, they will override things set via launchctl setenv for applications started from the shell.

Execute JavaScript code stored as a string

Try this:

  var script = "<script type='text/javascript'> content </script>";
  //using jquery next
  $('body').append(script);//incorporates and executes inmediatelly

Personally, I didn't test it but seems to work.

Finding the max value of an attribute in an array of objects

Well, first you should parse the JSON string, so that you can easily access it's members:

var arr = $.parseJSON(str);

Use the map method to extract the values:

arr = $.map(arr, function(o){ return o.y; });

Then you can use the array in the max method:

var highest = Math.max.apply(this,arr);

Or as a one-liner:

var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

Since the above answers clearly explains how to play safely with Optionals. I will try explain what Optionals are really in swift.

Another way to declare an optional variable is

var i : Optional<Int>

And Optional type is nothing but an enumeration with two cases, i.e

 enum Optional<Wrapped> : ExpressibleByNilLiteral {
    case none 
    case some(Wrapped)
    .
    .
    .
}

So to assign a nil to our variable 'i'. We can do var i = Optional<Int>.none or to assign a value, we will pass some value var i = Optional<Int>.some(28)

According to swift, 'nil' is the absence of value. And to create an instance initialized with nil We have to conform to a protocol called ExpressibleByNilLiteral and great if you guessed it, only Optionals conform to ExpressibleByNilLiteral and conforming to other types is discouraged.

ExpressibleByNilLiteral has a single method called init(nilLiteral:) which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil literal.

Even myself has to wrap (no pun intended) my head around Optionals :D Happy Swfting All.

Fix columns in horizontal scrolling

Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/

HTML

<h2>TableHeadFixer Fix Left Column</h2>

<div id="parent">
    <table id="fixTable" class="table">
        <thead>
            <tr>
                <th>Ano</th>
                <th>Jan</th>
                <th>Fev</th>
                <th>Mar</th>
                <th>Abr</th>
                <th>Maio</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
        </tbody>
    </table>
</div>

JS

    $(document).ready(function() {
        $("#fixTable").tableHeadFixer({"head" : false, "right" : 1}); 
    });

CSS

    #parent {
        height: 300px;
    }

    #fixTable {
        width: 1800px !important;
    }

https://jsfiddle.net/5gfuqqc4/

How to use boolean datatype in C?

C99 has a bool type. To use it,

#include <stdbool.h>

Inserting values into tables Oracle SQL

INSERT
INTO    Employee 
        (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT  '001', 'John Doe', '1 River Walk, Green Street', state_id, position_id, manager_id
FROM    dual
JOIN    state s
ON      s.state_name = 'New York'
JOIN    positions p
ON      p.position_name = 'Sales Executive'
JOIN    manager m
ON      m.manager_name = 'Barry Green'

Note that but a single spelling mistake (or an extra space) will result in a non-match and nothing will be inserted.

How do you connect to a MySQL database using Oracle SQL Developer?

My experience with windows client and linux/mysql server:

When sqldev is used in a windows client and mysql is installed in a linux server meaning, sqldev network access to mysql.

Assuming mysql is already up and running and the databases to be accessed are up and functional:

• Ensure the version of sqldev (32 or 64). If 64 and to avoid dealing with path access copy a valid 64 version of msvcr100.dll into directory ~\sqldeveloper\jdev\bin.

a. Open the file msvcr100.dll in notepad and search for first occurrence of “PE “

 i. “PE  d” it is 64.

ii. “PE  L” it is 32.

b. Note: if sqldev is 64 and msvcr100.dll is 32, the application gets stuck at startup.

• For sqldev to work with mysql there is need of the JDBC jar driver. Download it from mysql site.

a. Driver name = mysql-connector-java-x.x.xx

b. Copy it into someplace related to your sqldeveloper directory.

c. Set it up in menu sqldev Tools/Preferences/Database/Third Party JDBC Driver (add entry)

• In Linux/mysql server change file /etc/mysql/mysql.conf.d/mysqld.cnf look for

bind-address = 127.0.0.1 (this linux localhost)

and change to

bind-address = xxx.xxx.xxx.xxx (this linux server real IP or machine name if DNS is up)

• Enter to linux mysql and grant needed access for example

# mysql –u root -p

GRANT ALL ON . to root@'yourWindowsClientComputerName' IDENTIFIED BY 'mysqlPasswd';

flush privileges;

restart mysql - sudo /etc/init.d/mysql restart

• Start sqldev and create a new connection

a. user = root

b. pass = (your mysql pass)

c. Choose MySql tab

 i.   Hostname = the linux IP hostname

 ii.  Port     = 3306 (default for mysql)

 iii. Choose Database = (from pull down the mysql database you want to use)

 iv.  save and connect

That is all I had to do in my case.

Thank you,

Ale

How to add a browser tab icon (favicon) for a website?

Kindly use below code in header section your index file.

<link rel="icon" href="yourfevicon.ico" />

How can I find the link URL by link text with XPath?

if you are using html agility pack use getattributeValue:

$doc2.DocumentNode.SelectNodes("//div[@class='className']/div[@class='InternalClass']/a[@class='InternalClass']").GetAttributeValue("href","")

Get path to execution directory of Windows Forms application

This could help;

Path.GetDirectoryName(Application.ExecutablePath);

also here is the reference

If Cell Starts with Text String... Formula

I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size

Try =IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))

Now incorporate your left argument

=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))

Also note your usage of left, your argument doesn't specify the number of characters, but a set.


7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet, but I rather link to official sources.

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

  1. Uninstall all JDKs installed on your computer from the Java Control Panel
  2. Search for C:\ProgramData\Oracle\Java and delete that directory and all files contained within. You can do this from the command line using rmdir /S C:\ProgramData\Oracle\Java
  3. Then search for C:\ProgramData\Oracle and delete the oracle folder. You can do this using rmdir /S C:\ProgramData\Oracle
  4. Now install JDK and set the path.

  5. Run the program.You won't find the same problem anymore.

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

Just if someone is having this issue and hadn't done list[index, sub-index], you could be having the problem because you're missing a comma between two arrays in an array of arrays (It happened to me).

How to delete a specific file from folder using asp.net

Delete any or specific file type(for example ".bak") from a path. See demo code below -

class Program
        {
        static void Main(string[] args)
            {

            // Specify the starting folder on the command line, or in 
            TraverseTree(ConfigurationManager.AppSettings["folderPath"]);

            // Specify the starting folder on the command line, or in 
            // Visual Studio in the Project > Properties > Debug pane.
            //TraverseTree(args[0]);

            Console.WriteLine("Press any key");
            Console.ReadKey();
            }

        public static void TraverseTree(string root)
            {

            if (string.IsNullOrWhiteSpace(root))
                return;

            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack<string> dirs = new Stack<string>(20);

            if (!System.IO.Directory.Exists(root))
                {
                return;
                }

            dirs.Push(root);

            while (dirs.Count > 0)
                {
                string currentDir = dirs.Pop();
                string[] subDirs;
                try
                    {
                    subDirs = System.IO.Directory.GetDirectories(currentDir);
                    }

                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file. It may or may not be acceptable 
                // to ignore the exception and continue enumerating the remaining files and 
                // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
                // will be raised. This will happen if currentDir has been deleted by
                // another application or thread after our call to Directory.Exists. The 
                // choice of which exceptions to catch depends entirely on the specific task 
                // you are intending to perform and also on how much you know with certainty 
                // about the systems on which this code will run.
                catch (UnauthorizedAccessException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }
                catch (System.IO.DirectoryNotFoundException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }

                IEnumerable<FileInfo> files = null;
                try
                    {
                    //get only .bak file
                    var directory = new DirectoryInfo(currentDir);
                    DateTime date = DateTime.Now.AddDays(-15);
                    files = directory.GetFiles("*.bak").Where(file => file.CreationTime <= date);
                    }
                catch (UnauthorizedAccessException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }
                catch (System.IO.DirectoryNotFoundException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }

                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (FileInfo file in files)
                    {
                    try
                        {
                        // Perform whatever action is required in your scenario.
                        file.Delete();
                        Console.WriteLine("{0}: {1}, {2} was successfully deleted.", file.Name, file.Length, file.CreationTime);
                        }
                    catch (System.IO.FileNotFoundException e)
                        {
                        // If file was deleted by a separate application
                        //  or thread since the call to TraverseTree()
                        // then just continue.
                        Console.WriteLine(e.Message);
                        continue;
                        }
                    }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string str in subDirs)
                    dirs.Push(str);
                }
            }
        }

for more reference - https://msdn.microsoft.com/en-us/library/bb513869.aspx

How to export MySQL database with triggers and procedures?

mysqldump will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:

  • --routines – FALSE by default
  • --triggers – TRUE by default

so in mysqldump command , add --routines like :

mysqldump <other mysqldump options> --routines > outputfile.sql

See the MySQL documentation about mysqldump arguments.

Is it possible to specify the schema when connecting to postgres with JDBC?

I don't believe there is a way to specify the schema in the connection string. It appears you have to execute

set search_path to 'schema'

after the connection is made to specify the schema.

Implement Validation for WPF TextBoxes

To get it done only with XAML you need to add Validation Rules for individual properties. But i would recommend you to go with code behind approach. In your code, define your specifications in properties setters and throw exceptions when ever it doesn't compliance to your specifications. And use error template to display your errors to user in UI. Your XAML will look like this

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <Style x:Key="CustomTextBoxTextStyle" TargetType="TextBox">
        <Setter Property="Foreground" Value="Green" />
        <Setter Property="MaxLength" Value="40" />
        <Setter Property="Width" Value="392" />
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="True">
                <Trigger.Setters>
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
                    <Setter Property="Background" Value="Red"/>
                </Trigger.Setters>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<Grid>
    <TextBox Name="tb2" Height="30" Width="400"
             Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}" 
             Style="{StaticResource CustomTextBoxTextStyle}"/>
</Grid>

Code Behind:

public partial class MainWindow : Window
{
    private ExampleViewModel m_ViewModel;
    public MainWindow()
    {
        InitializeComponent();
        m_ViewModel = new ExampleViewModel();
        DataContext = m_ViewModel;
    }
}


public class ExampleViewModel : INotifyPropertyChanged
{
    private string m_Name = "Type Here";
    public ExampleViewModel()
    {

    }

    public string Name
    {
        get
        {
            return m_Name;
        }
        set
        {
            if (String.IsNullOrEmpty(value))
            {
                throw new Exception("Name can not be empty.");
            }
            if (value.Length > 12)
            {
                throw new Exception("name can not be longer than 12 charectors");
            }
            if (m_Name != value)
            {
                m_Name = value;
                OnPropertyChanged("Name");
            }
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}

Factorial using Recursion in Java

public class Factorial {
public static void main(String[] args) {
   int n = 7;
   int result = 1;
   for (int i = 1; i <= n; i++) {
       result = result * i;
   }
   System.out.println("The factorial of 7 is " + result);
}
}

Is there an embeddable Webkit component for Windows / C# development?

I've just release a pre-alpha version of CefSharp my .Net bindings for the Chromium Embedded Framework.

Check it out and give me your thoughts: https://github.com/chillitom/CefSharp (binary libs and example available in the downloads page)

update: Released a new version, includes the ability to bind C# objects into the DOM and more.

update 2: no-longer alpha, lib is used in real world projects including Facebook Messenger for Windows, Rdio's Windows client and Github for Windows

How to recover corrupted Eclipse workspace?

In my case only removing org.eclipse.e4.workbench directory (under .metadata/.plugins) and restarting Eclipse solved the problem.

Change icons of checked and unchecked for Checkbox for Android

One alternative would be to use a drawable/textview instead of a checkbox and manipulate it accordingly. I have used this method to have my own checked and unchecked images for a task application.

querying WHERE condition to character length?

I think you want this:

select *
from dbo.table
where DATALENGTH(column_name) = 3

How to convert all tables from MyISAM into InnoDB?

for mysqli connect;

<?php

$host       = "host";
$user       = "user";
$pass       = "pss";
$database   = "db_name";


$connect = new mysqli($host, $user, $pass, $database);  

// Actual code starts here Dont forget to change db_name !!
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'db_name' 
    AND ENGINE = 'MyISAM'";

$rs = $connect->query($sql);

while($row = $rs->fetch_array())
{
    $tbl = $row[0];
    $sql = "ALTER TABLE `$tbl` ENGINE=INNODB";
    $connect->query($sql);
} ?>

How to trigger SIGUSR1 and SIGUSR2?

They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:

#include <signal.h>

kill(pid, SIGUSR1);

where pid is the process id of the receiving process. At the receiving end, you can register a signal handler for them:

#include <signal.h>

void my_handler(int signum)
{
    if (signum == SIGUSR1)
    {
        printf("Received SIGUSR1!\n");
    }
}

signal(SIGUSR1, my_handler);

Div 100% height works on Firefox but not in IE

I'm not sure what problem you are solving, but when I have two side by side containers that need to be the same height, I run a little javascript on page load that finds the maximum height of the two and explicitly sets the other to the same height. It seems to me that height: 100% might just mean "make it the size needed to fully contain the content" when what you really want is "make both the size of the largest content."

Note: you'll need to resize them again if anything happens on the page to change their height -- like a validation summary being made visible or a collapsible menu opening.

jQuery - Create hidden form element on the fly

function addHidden(theForm, key, value) {
    // Create a hidden input element, and append it to the form:
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key; //name-as-seen-at-the-server
    input.value = value;
    theForm.appendChild(input);
}

// Form reference:
var theForm = document.forms['detParameterForm'];

// Add data:
addHidden(theForm, 'key-one', 'value');

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

There is another question which duplicates this one. I posted an answer how I solved this problem. Maybe it helps someone else too:

Anyone else's build for iTunes Connect taking longer times to process?

In a nutshell: Build and upload with XCode 6.4 instead of XCode 7.

What is the meaning of "this" in Java?

Instance variables are common to every object that you creating. say, there is two instance variables

class ExpThisKeyWord{
int x;
int y;

public void setMyInstanceValues(int a, int b) {
    x= a;
    y=b;

    System.out.println("x is ="+x);
    System.out.println("y is ="+y);
}

}




class Demo{
public static void main(String[] args){

ExpThisKeyWord obj1 = new ExpThisKeyWord();
ExpThisKeyWord obj2 = new ExpThisKeyWord();
ExpThisKeyWord obj3 = new ExpThisKeyWord();

obj1.setMyInstanceValues(1, 2);
obj2.setMyInstanceValues(11, 22);
obj3.setMyInstanceValues(111, 222);



}
}

if you noticed above code, we have initiated three objects and three objects are calling SetMyInstanceValues method. How do you think JVM correctly assign the values for every object? there is the trick, JVM will not see this code how it is showed above. instead of that, it will see like below code;

public void setMyInstanceValues(int a, int b) {
    this.x= a; //Answer: this keyword denotes the current object that is handled by JVM.
    this.y=b;

    System.out.println("x is ="+x);
    System.out.println("y is ="+y);
}

Changing navigation title programmatically

Normally, the best-practice is to set the title on the UIViewController. By doing this, the UINavigationItem is also set. Generally, this is better than programmatically allocating and initializing a UINavigationBar that's not linked to anything.

You miss out on some of the benefits and functionality that the UINavigationBar was designed for. Here is a link to the documentation that may help you. It discusses the different properties you can set on the actual bar and on a UINavigationItem.

Just keep in mind:

  1. You lose back button functionality (unless you wire it yourself)
  2. The built-in "drag from the left-hand side to swipe back" gesture is forfeited

UINavigationController's are your friends.

Style child element when hover on parent

Yes, you can do this use this below code it may help you.

_x000D_
_x000D_
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
  display : block;_x000D_
  padding : 10px;_x000D_
  text-align : center;_x000D_
  border: 5px solid #000;_x000D_
  margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
  <div class="childDiv1">_x000D_
    First Div Child_x000D_
  </div>_x000D_
  <div class="childDiv2">_x000D_
    Second Div Child_x000D_
  </div>_x000D_
  <div class="childDiv3">_x000D_
    Third Div Child_x000D_
  </div>_x000D_
  <div class="childDiv4">_x000D_
    Fourth Div Child_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

First off, your code is a bit off. aes() is an argument in ggplot(), you don't use ggplot(...) + aes(...) + layers

Second, from the help file ?geom_bar:

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

You want the second case, where the height of the bar is equal to the conversion_rate So what you want is...

data_country <- data.frame(country = c("China", "Germany", "UK", "US"), 
            conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")

Result:

enter image description here

How to Remove the last char of String in C#?

If you are using string datatype, below code works:

string str = str.Remove(str.Length - 1);

But when you have StringBuilder, you have to specify second parameter length as well.

SB

That is,

string newStr = sb.Remove(sb.Length - 1, 1).ToString();

To avoid below error:

SB2

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

If your are working in a web service and the v2.0 assembly is a dependency that has been loaded by WcfSvcHost.exe then you must include

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" />
</startup>

in ..\Microsoft Visual Studio 10.0\Common7\IDE\ WcfSvcHost.exe.config file

This way, Visual Studio will be able to send the right information through the loader at runtime.

Pivoting rows into columns dynamically in Oracle

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from: http://orafaq.com/wiki/PIVOT

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

Printing a char with printf

%d prints an integer: it will print the ascii representation of your character. What you need is %c:

printf("%c", ch);

printf("%d", '\0'); prints the ascii representation of '\0', which is 0 (by escaping 0 you tell the compiler to use the ascii value 0.

printf("%d", sizeof('\n')); prints 4 because a character literal is an int, in C, and not a char.

django order_by query set, ascending and descending

If for some reason you have null values you can use the F function like this:

from django.db.models import F

Reserved.objects.all().filter(client=client_id).order_by(F('check_in').desc(nulls_last=True))

So it will put last the null values. Documentation by Django: https://docs.djangoproject.com/en/stable/ref/models/expressions/#using-f-to-sort-null-values

Mime type for WOFF fonts?

For me, the next has beeen working in an .htaccess file.

AddType font/ttf .ttf
AddType font/eot .eot
AddType font/otf .otf
AddType font/woff .woff
AddType font/woff2 .woff2   

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

Select Tag Helper in ASP.NET Core MVC

You can use below code for multiple select:

<select asp-for="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

You can also use:

<select id="EmployeeId" name="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

SQL Call Stored Procedure for each Row without using a cursor

DECLARE @SQL varchar(max)=''

-- MyTable has fields fld1 & fld2

Select @SQL = @SQL + 'exec myproc ' + convert(varchar(10),fld1) + ',' 
                   + convert(varchar(10),fld2) + ';'
From MyTable

EXEC (@SQL)

Ok, so I would never put such code into production, but it does satisfy your requirements.

Store boolean value in SQLite

SQLite Boolean Datatype:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).

You can convert boolean to int in this way:

int flag = (boolValue)? 1 : 0;

You can convert int back to boolean as follows:

 // Select COLUMN_NAME  values from db. 
 // This will be integer value, you can convert this int value back to Boolean as follows
Boolean flag2 = (intValue == 1)? true : false;

If you want to explore sqlite, here is a tutorial.
I have given one answer here. It is working for them.

Bootstrap 4 - Glyphicons migration?

Overview:

I am using bootstrap 4 without glyphicons. I found a problem with bootstrap treeview that depends upon glyphicons. I am using treeview as is, and I am using scss @extend to translate the icon class styles to font awesome class styles. I think this is quite slick (if you ask me)!

Details:

I used scss @extend to handle it for me.

I previously decided to use font-awesome for no better reason than I have used it in the past.

When I went to try bootstrap treeview, I found that the icons were missing, because I didn't have glyphicons installed.

I decided to use the scss @extend feature, to have the glyphicon classes use the font-awesome classes as so:

.treeview {
  .glyphicon {
    @extend .fa;
  }
  .glyphicon-minus {
    @extend .fa-minus;
  }
  .glyphicon-plus {
    @extend .fa-plus;
  }
}

Regex matching beginning AND end strings

If you're searching for hits within a larger text, you don't want to use ^ and $ as some other responders have said; those match the beginning and end of the text. Try this instead:

\bdbo\.\w+_fn\b

\b is a word boundary: it matches a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. This regex will find what you're looking for in any of these strings:

dbo.functionName_fn
foo dbo.functionName_fn bar
(dbo.functionName_fn)

...but not in this one:

foodbo.functionName_fnbar

\w+ matches one or more "word characters" (letters, digits, or _). If you need something more inclusive, you can try \S+ (one or more non-whitespace characters) or .+? (one or more of any characters except linefeeds, non-greedily). The non-greedy +? prevents it from accidentally matching something like dbo.func1_fn dbo.func2_fn as if it were just one hit.

Vertical rulers in Visual Studio Code

With Visual Studio Code 1.27.2:

  1. When I go to File > Preference > Settings, I get the following tab

    Screenshot

  2. I type rulers in Search settings and I get the following list of settings

    screenshot

  3. Clicking on the first Edit in settings.json, I can edit the user settings

    screenshot

  4. Clicking on the pen icon that appears to the left of the setting in Default user settings I can copy it on the user settings and edit it

With Visual Studio Code 1.38.1, the screenshot shown on the third point changes to the following one.

enter image description here

The panel for selecting the default user setting values isn't shown anymore.

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

You can give dialog box which given by the JavaFX UI Controls Project. I think it will help you

Dialogs.showErrorDialog(Stage object, errorMessage,  "Main line", "Name of Dialog box");
Dialogs.showWarningDialog(Stage object, errorMessage,  "Main line", "Name of Dialog box");

Using $setValidity inside a Controller

A better and optimised solution to display multiple validation messages for a single element would be like this.

<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
 <span class="error" ng-message="required"> <your message> </span>
 <span class="error" ng-message="size"> <your message> </span>
 <span class="error" ng-message="filetype"> <your message> </span>
</div>

Controller Code should be the one suggested by @ Ben Lesh

Mockito How to mock only the call of a method of the superclass

Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.

 public Childservice extends BaseService {
    public void save(){
        //some code
        superSave();
    }

    void superSave(){
        super.save();
    }
}

Unsupported major.minor version 52.0 in my app

Initially I had downgraded buildToolsVersion from 24.0.0 rc3 to 23.0.3, as specified in Rudy Kurniawan's answer. Then I have noticed that I have jdk 7 specified in my project settings. I have changed it to jdk 8 and now build tools 24.0.0 rc3 work.

enter image description here

It's also important to have compile options set to java7:

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Plotting lines connecting points

I think you're going to need separate lines for each segment:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random(size=(2,10))

for i in range(0, len(x), 2):
    plt.plot(x[i:i+2], y[i:i+2], 'ro-')

plt.show()

(The numpy import is just to set up some random 2x10 sample data)

enter image description here

Could not resolve this reference. Could not locate the assembly

Maybe it will help someone, but sometimes Name tag might be missing for a reference and it leads that assembly cannot be found when building with MSBuild. Make sure that Name tag is available for particular reference csproj file, for example,

    <ProjectReference Include="..\MyDependency1.csproj">
      <Project>{9A2D95B3-63B0-4D53-91F1-5EFB99B22FE8}</Project>
      <Name>MyDependency1</Name>
    </ProjectReference>

Cron and virtualenv

If you're on python and using a Conda Virtual Environment where your python script contains the shebang #!/usr/bin/env python the following works:

* * * * * cd /home/user/project && /home/user/anaconda3/envs/envname/bin/python script.py 2>&1

Additionally, if you want to capture any outputs in your script (e.g. print, errors, etc) you can use the following:

* * * * * cd /home/user/project && /home/user/anaconda3/envs/envname/bin/python script.py >> /home/user/folder/script_name.log 2>&1

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Compilation error: stray ‘\302’ in program etc

Codo was exactly right on Oct. 5 that &current[i] is the intended text (with the currency symbol inadvertently introduced when the source was put into HTML (see original): http://downloads.securityfocus.com/vulnerabilities/exploits/59846-1.c

Codo's change makes this exploit code compile without error. I did that and was able to use the exploit on Ubuntu 12.04 to escalate to root privilege.

How to remove space from string?

Try doing this in a shell:

var="  3918912k"
echo ${var//[[:blank:]]/}

That uses parameter expansion (it's a non feature)

[[:blank:]] is a POSIX regex class (remove spaces, tabs...), see http://www.regular-expressions.info/posixbrackets.html

HTML-encoding lost when attribute read from input field

Here's a little bit that emulates the Server.HTMLEncode function from Microsoft's ASP, written in pure JavaScript:

_x000D_
_x000D_
function htmlEncode(s) {_x000D_
  var ntable = {_x000D_
    "&": "amp",_x000D_
    "<": "lt",_x000D_
    ">": "gt",_x000D_
    "\"": "quot"_x000D_
  };_x000D_
  s = s.replace(/[&<>"]/g, function(ch) {_x000D_
    return "&" + ntable[ch] + ";";_x000D_
  })_x000D_
  s = s.replace(/[^ -\x7e]/g, function(ch) {_x000D_
    return "&#" + ch.charCodeAt(0).toString() + ";";_x000D_
  });_x000D_
  return s;_x000D_
}
_x000D_
_x000D_
_x000D_

The result does not encode apostrophes, but encodes the other HTML specials and any character outside the 0x20-0x7e range.

Android ADB stop application command like "force-stop" for non rooted device

If you have a rooted device you can use kill command

Connect to your device with adb:

adb shell

Once the session is established, you have to escalade privileges:

su

Then

ps

will list running processes. Note down the PID of the process you want to terminate. Then get rid of it

kill PID

How to print out a variable in makefile

You could create a vars rule in your make file, like this:

dispvar = echo $(1)=$($(1)) ; echo

.PHONY: vars
vars:
    @$(call dispvar,SOMEVAR1)
    @$(call dispvar,SOMEVAR2)

There are some more robust ways to dump all variables here: gnu make: list the values of all variables (or "macros") in a particular run.

Laravel 5.1 API Enable Cors

For me i put this codes in public\index.php file. and it worked just fine for all CRUD operations.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");

"Fade" borders in CSS

How to fade borders with CSS:

<div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>

Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.

Source: Gradient Borders

What is middleware exactly?

Lets say your company makes 4 different products, your client has another 3 different products from another 3 different companies.

Someday the client thought, why don't we integrate all our systems into one huge system. Ten minutes later their IT department said that will take 2 years.

You (the wise developer) said, why don't we just integrate all the different systems and make them work together in a homogeneous environment? The client manager staring at you... You continued, we will use a Middleware, we will study the Inputs/Outputs of all different systems, the resources they use and then choose an appropriate Middleware framework.

Still explaining to the non tech manager
With Middleware framework in the middle, the first system will produce X stuff, the system Y and Z would consume those outputs and so on.

How to create a HashMap with two keys (Key-Pair, Value)?

You can download it from the below link: https://github.com/VVS279/DoubleKeyHashMap/blob/master/src/com/virtualMark/doubleKeyHashMap/DoubleKeyHashMap.java

https://github.com/VVS279/DoubleKeyHashMap

You can use double key: value hashmap,

   DoubleKeyHashMap<Integer, Integer, String> doubleKeyHashMap1 = new 
   DoubleKeyHashMap<Integer, Integer, String>();

   DoubleKeyHashMap<String, String, String> doubleKeyHashMap2 = new 
   DoubleKeyHashMap<String, String, String>();

Run java jar file on a server as background process

You can try this:

#!/bin/sh
nohup java -jar /web/server.jar &

The & symbol, switches the program to run in the background.

The nohup utility makes the command passed as an argument run in the background even after you log out.

Using Jquery Ajax to retrieve data from Mysql


You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.

AjaxGet = function (url) {
    var result = $.ajax({
        type: "POST",
        url: url,
       param: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
       async: false,
        success: function (data) {
            // nothing needed here
      }
    }) .responseText ;
    return  result;
}

How to get the width and height of an android.widget.ImageView?

I think you can let the Android OS take care of this for you. Set the scale type on the ImageView to fitXY and the image it displays will be sized to fit the current size of the view.

<ImageView 
    android:layout_width="90px" 
    android:layout_height="60px"
    android:scaleType="fitXY" />

Deleting rows with MySQL LEFT JOIN

DELETE FROM deadline where ID IN (
    SELECT d.ID FROM `deadline` d LEFT JOIN `job` ON deadline.job_id = job.job_id WHERE `status` =  'szamlazva' OR `status` = 'szamlazhato' OR `status` = 'fizetve' OR `status` = 'szallitva' OR `status` = 'storno');

I am not sure if that kind of sub query works in MySQL, but try it. I am assuming you have an ID column in your deadline table.

What is the standard naming convention for html/css ids and classes?

There isn't one.

I use underscores all the time, due to hyphens messing up the syntax highlighting of my text editor (Gedit), but that's personal preference.

I've seen all these conventions used all over the place. Use the one that you think is best - the one that looks nicest/easiest to read for you, as well as easiest to type because you'll be using it a lot. For example, if you've got your underscore key on the underside of the keyboard (unlikely, but entirely possible), then stick to hyphens. Just go with what is best for yourself. Additionally, all 3 of these conventions are easily readable. If you're working in a team, remember to keep with the team-specified convention (if any).

Update 2012

I've changed how I program over time. I now use camel case (thisIsASelector) instead of hyphens now; I find the latter rather ugly. Use whatever you prefer, which may easily change over time.

Update 2013

It looks like I like to mix things up yearly... After switching to Sublime Text and using Bootstrap for a while, I've gone back to dashes. To me now they look a lot cleaner than un_der_scores or camelCase. My original point still stands though: there isn't a standard.

Update 2015

An interesting corner case with conventions here is Rust. I really like the language, but the compiler will warn you if you define stuff using anything other than underscore_case. You can turn the warning off, but it's interesting the compiler strongly suggests a convention by default. I imagine in larger projects it leads to cleaner code which is no bad thing.

Update 2016 (you asked for it)

I've adopted the BEM standard for my projects going forward. The class names end up being quite verbose, but I think it gives good structure and reusability to the classes and CSS that goes with them. I suppose BEM is actually a standard (so my no becomes a yes perhaps) but it's still up to you what you decide to use in a project. Most importantly: be consistent with what you choose.

Update 2019 (you asked for it)

After writing no CSS for quite a while, I started working at a place that uses OOCSS in one of their products. I personally find it pretty unpleasant to litter classes everywhere, but not having to jump between HTML and CSS all the time feels quite productive.

I'm still settled on BEM, though. It's verbose, but the namespacing makes working with it in React components very natural. It's also great for selecting specific elements when browser testing.

OOCSS and BEM are just some of the CSS standards out there. Pick one that works for you - they're all full of compromises because CSS just isn't that good.

Update 2020

A boring update this year. I'm still using BEM. My position hasn't really changed from the 2019 update for the reasons listed above. Use what works for you that scales with your team size and hides as much or as little of CSS' poor featureset as you like.

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

This can be achieved by assigning the header view manually in the UITableViewController's viewDidLoad method instead of using the delegate's viewForHeaderInSection and heightForHeaderInSection. For example in your subclass of UITableViewController, you can do something like this:

- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
    [headerView setBackgroundColor:[UIColor magentaColor]];
    [headerView setTextAlignment:NSTextAlignmentCenter];
    [headerView setText:@"Hello World"];
    [[self tableView] setTableHeaderView:headerView];
}

The header view will then disappear when the user scrolls. I don't know why this works like this, but it seems to achieve what you're looking to do.