Programs & Examples On #Largenumber

Very large numbers often occur in fields such as mathematics, cosmology, cryptography and statistical mechanics. That numbers are significantly larger than those ordinarily used in everyday life, for instance in simple counting or in monetary transactions. The term typically refers to large positive integers, or more generally, large positive real numbers, but it may also be used in other contexts.

Handling very large numbers in Python

You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.

  • Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.

  • Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.

  • The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 < h2 for such hands means nothing.

Print Pdf in C#

It is also possible to do it with an embedded web browser, note however that since this might be a local file, and also because it is not actually the browser directly and there is no DOM so there is no ready state.

Here is the code for the approach I worked out on a win form web browser control:

    private void button1_Click(object sender, EventArgs e)
    {
        webBrowser1.Navigate(@"path\to\file");
    }  

    private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {   
        //Progress Changed fires multiple times, however after the Navigated event it is fired only once,
        //and at this point it is ready to print
        webBrowser1.ProgressChanged += (o, args) => 
        {
            webBrowser1.Print();//Note this does not print only brings up the print preview dialog
            //Should be on a separate task to ensure the main thread 
            //can fully initialize the print dialog 
            Task.Factory.StartNew(() => 
            {
                Thread.Sleep(1000);//We need to wait before we can send enter
                //This assumes that the print preview is still in focus
                Action g = () =>
                {
                    SendKeys.SendWait("{ENTER}");
                };
                this.Invoke(g);
            });
        };
    }

Git says local branch is behind remote branch, but it's not

You probably did some history rewriting? Your local branch diverged from the one on the server. Run this command to get a better understanding of what happened:

gitk HEAD @{u}

I would strongly recommend you try to understand where this error is coming from. To fix it, simply run:

git push -f

The -f makes this a “forced push” and overwrites the branch on the server. That is very dangerous when you are working in team. But since you are on your own and sure that your local state is correct this should be fine. You risk losing commit history if that is not the case.

What does the question mark in Java generics' type parameter mean?

? extends HasWord

means "A class/interface that extends HasWord." In other words, HasWord itself or any of its children... basically anything that would work with instanceof HasWord plus null.

In more technical terms, ? extends HasWord is a bounded wildcard, covered in Item 31 of Effective Java 3rd Edition, starting on page 139. The same chapter from the 2nd Edition is available online as a PDF; the part on bounded wildcards is Item 28 starting on page 134.

Update: PDF link was updated since Oracle removed it a while back. It now points to the copy hosted by the Queen Mary University of London's School of Electronic Engineering and Computer Science.

Update 2: Lets go into a bit more detail as to why you'd want to use wildcards.

If you declare a method whose signature expect you to pass in List<HasWord>, then the only thing you can pass in is a List<HasWord>.

However, if said signature was List<? extends HasWord> then you could pass in a List<ChildOfHasWord> instead.

Note that there is a subtle difference between List<? extends HasWord> and List<? super HasWord>. As Joshua Bloch put it: PECS = producer-extends, consumer-super.

What this means is that if you are passing in a collection that your method pulls data out from (i.e. the collection is producing elements for your method to use), you should use extends. If you're passing in a collection that your method adds data to (i.e. the collection is consuming elements your method creates), it should use super.

This may sound confusing. However, you can see it in List's sort command (which is just a shortcut to the two-arg version of Collections.sort). Instead of taking a Comparator<T>, it actually takes a Comparator<? super T>. In this case, the Comparator is consuming the elements of the List in order to reorder the List itself.

Create instance of generic type whose constructor requires a parameter?

It is still possible, with high performance, by doing the following:

    //
    public List<R> GetAllItems<R>() where R : IBaseRO, new() {
        var list = new List<R>();
        using ( var wl = new ReaderLock<T>( this ) ) {
            foreach ( var bo in this.items ) {
                T t = bo.Value.Data as T;
                R r = new R();
                r.Initialize( t );
                list.Add( r );
            }
        }
        return list;
    }

and

    //
///<summary>Base class for read-only objects</summary>
public partial interface IBaseRO  {
    void Initialize( IDTO dto );
    void Initialize( object value );
}

The relevant classes then have to derive from this interface and initialize accordingly. Please note, that in my case, this code is part of a surrounding class, which already has <T> as generic parameter. R, in my case, also is a read-only class. IMO, the public availability of Initialize() functions has no negative effect on the immutability. The user of this class could put another object in, but this would not modify the underlying collection.

How to save a list to a file and read it as a list type?

If you don't want to use pickle, you can store the list as text and then evaluate it:

data = [0,1,2,3,4,5]
with open("test.txt", "w") as file:
    file.write(str(data))

with open("test.txt", "r") as file:
    data2 = eval(file.readline())

# Let's see if data and types are same.
print(data, type(data), type(data[0]))
print(data2, type(data2), type(data2[0]))

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

How to update core-js to core-js@3 dependency?

How about reinstalling the node module? Go to the root directory of the project and remove the current node modules and install again.

These are the commands : rm -rf node_modules npm install

OR

npm uninstall -g react-native-cli and

npm install -g react-native-cli

Frequency table for a single variable

The answer provided by @DSM is simple and straightforward, but I thought I'd add my own input to this question. If you look at the code for pandas.value_counts, you'll see that there is a lot going on.

If you need to calculate the frequency of many series, this could take a while. A faster implementation would be to use numpy.unique with return_counts = True

Here is an example:

import pandas as pd
import numpy as np

my_series = pd.Series([1,2,2,3,3,3])

print(my_series.value_counts())
3    3
2    2
1    1
dtype: int64

Notice here that the item returned is a pandas.Series

In comparison, numpy.unique returns a tuple with two items, the unique values and the counts.

vals, counts = np.unique(my_series, return_counts=True)
print(vals, counts)
[1 2 3] [1 2 3]

You can then combine these into a dictionary:

results = dict(zip(vals, counts))
print(results)
{1: 1, 2: 2, 3: 3}

And then into a pandas.Series

print(pd.Series(results))
1    1
2    2
3    3
dtype: int64

Sending a notification from a service in Android

This type of Notification is deprecated as seen from documents:

@java.lang.Deprecated
public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }

public Notification(android.os.Parcel parcel) { /* compiled code */ }

@java.lang.Deprecated
public void setLatestEventInfo(android.content.Context context, java.lang.CharSequence contentTitle, java.lang.CharSequence contentText, android.app.PendingIntent contentIntent) { /* compiled code */ }

Better way
You can send a notification like this:

// prepare intent which is triggered if the
// notification is selected

Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// build notification
// the addAction re-use the same intent to keep the example short
Notification n  = new Notification.Builder(this)
        .setContentTitle("New mail from " + "[email protected]")
        .setContentText("Subject")
        .setSmallIcon(R.drawable.icon)
        .setContentIntent(pIntent)
        .setAutoCancel(true)
        .addAction(R.drawable.icon, "Call", pIntent)
        .addAction(R.drawable.icon, "More", pIntent)
        .addAction(R.drawable.icon, "And more", pIntent).build();


NotificationManager notificationManager = 
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(0, n); 

Best way
Code above needs minimum API level 11 (Android 3.0).
If your minimum API level is lower than 11, you should you use support library's NotificationCompat class like this.

So if your minimum target API level is 4+ (Android 1.6+) use this:

    import android.support.v4.app.NotificationCompat;
    -------------
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.mylogo)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");
    int NOTIFICATION_ID = 12345;

    Intent targetIntent = new Intent(this, MyFavoriteActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nManager.notify(NOTIFICATION_ID, builder.build());

How do I pass a datetime value as a URI parameter in asp.net mvc?

Typical format of a URI for ASP .NET MVC is Controller/Action/Id where Id is an integer

I would suggest sending the date value as a parameter rather than as part of the route:

 mysite/Controller/Action?date=21-9-2009 10:20

If it's still giving you problems the date may contain characters that are not allowed in a URI and need to be encoded. Check out:

 encodeURIComponent(yourstring)

It is a method within Javascript.

On the Server Side:

public ActionResult ActionName(string date)
{
     DateTime mydate;
     DateTime.Tryparse(date, out mydate);
}

FYI, any url parameter can be mapped to an action method parameter as long as the names are the same.

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

When creating a service with sc.exe how to pass in context parameters?

I couldn't handle the issue with your proposals, at the end with the x86 folder it only worked in power shell (windows server 2012) using environment variables:

{sc.exe create svnserve binpath= "${env:programfiles(x86)}/subversion/bin/svnserve.exe --service -r C:/svnrepositories/"   displayname= "Subversion Server" depend= Tcpip start= auto}

jQuery limit to 2 decimal places

Here is a working example in both Javascript and jQuery:

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
?

Ternary operator (?:) in Bash

A string-oriented alternative, that uses an array:

spec=(IGNORE REPLACE)
for p in {13..15}; do
  echo "$p: ${spec[p==14]}";
done

which outputs:

13: IGNORE
14: REPLACE
15: IGNORE

Rolling back bad changes with svn in Eclipse

I have same problem but CleanUp eclipse option doesn't work for me.

1) install TortoiseSVN
2) Go to windows explorer and right click on your project directory
3 Choice CleanUp option (by checking break lock option)

It's works.

Hope this helps someone.

Multiprocessing vs Threading Python

As I learnd in university most of the answers above are right. In PRACTISE on different platforms (always using python) spawning multiple threads ends up like spawning one process. The difference is the multiple cores share the load instead of only 1 core processing everything at 100%. So if you spawn for example 10 threads on a 4 core pc, you will end up getting only the 25% of the cpus power!! And if u spawn 10 processes u will end up with the cpu processing at 100% (if u dont have other limitations). Im not a expert in all the new technologies. Im answering with own real experience background

How can I check if a string contains ANY letters from the alphabet?

You can use islower() on your string to see if it contains some lowercase letters (amongst other characters). or it with isupper() to also check if contains some uppercase letters:

below: letters in the string: test yields true

>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True

below: no letters in the string: test yields false.

>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>> 

Not to be mixed up with isalpha() which returns True only if all characters are letters, which isn't what you want.

Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.

MySQL Stored procedure variables from SELECT statements

You simply need to enclose your SELECT statements in parentheses to indicate that they are subqueries:

SET cityLat = (SELECT cities.lat FROM cities WHERE cities.id = cityID);

Alternatively, you can use MySQL's SELECT ... INTO syntax. One advantage of this approach is that both cityLat and cityLng can be assigned from a single table-access:

SELECT lat, lng INTO cityLat, cityLng FROM cities WHERE id = cityID;

However, the entire procedure can be replaced with a single self-joined SELECT statement:

SELECT   b.*, HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM     cities AS a, cities AS b
WHERE    a.id = cityID
ORDER BY dist
LIMIT    10;

Ignore Duplicates and Create New List of Unique Values in Excel

Another approach, since Excel 2016, is to use Power Query.

Howto:

  • select the data (including the field name),
  • use menu Data > From a table or a range,
  • (Excel will change your sheet into an Excel Table, which is very convenient),
  • in the Power Query Editor, right-click on ColumnA (the column header), and Remove duplicates,
  • in the menu, choose Close and load, choose where you want the result, and you're done, like this.
  • Whenever you want the result table to update, right-click it and choose Refresh.

Benefits :

  • it uses the CPU only when manually updated, which is very convenient for long lists,
  • if you're curious, this offers many other powerful options.

Drawbacks :

  • it doesn't update on the fly (you have to right-click and refresh the result table),
  • people with old version of Excel won't be able to refresh the results table.

Difference between "process.stdout.write" and "console.log" in node.js?


Console.log implement process.sdout.write, process.sdout.write is a buffer/stream that will directly output in your console.

According to my puglin serverline : console = new Console(consoleOptions) you can rewrite Console class with your own readline system.

You can see code source of console.log:


See more :

Conversion failed when converting the nvarchar value ... to data type int

I was using a KEY word for one of my columns and I solved it with brackets []

What is the maximum possible length of a .NET string?

For anyone coming to this topic late, I could see that hitscan's "you probably shouldn't do that" might cause someone to ask what they should do…

The StringBuilder class is often an easy replacement. Consider one of the stream-based classes especially, if your data is coming from a file.

The problem with s += "stuff" is that it has to allocate a completely new area to hold the data and then copy all of the old data to it plus the new stuff - EACH AND EVERY LOOP ITERATION. So, adding five bytes to 1,000,000 with s += "stuff" is extremely costly. If what you want is to just write five bytes to the end and proceed with your program, you have to pick a class that leaves some room for growth:

StringBuilder sb = new StringBuilder(5000);
for (; ; )
    {
        sb.Append("stuff");
    }

StringBuilder will auto-grow by doubling when it's limit is hit. So, you will see the growth pain once at start, once at 5,000 bytes, again at 10,000, again at 20,000. Appending strings will incur the pain every loop iteration.

How to get selected value from Dropdown list in JavaScript

Direct value should work just fine:

var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout
layout?.minimumLineSpacing = 8

How to get the xml node value in string

These posts helped me get past a couple of issues I had creating a CLR Stored Procedure with Restful API call against Infor M3 API.

The XML Result from these API's look like this for my code below:

miResult xmlns="http://lawson.com/m3/miaccess">
    <Program>MMS200MI</Program>
    <Transaction>Get</Transaction>
    <Metadata>...</Metadata>
    <MIRecord>
        <RowIndex>0</RowIndex>
        <NameValue>
            <Name>STAT</Name>
            <Value>20</Value>
        </NameValue>
        <NameValue>
            <Name>ITNO</Name>
            <Value>ITEM123</Value>
        </NameValue>
        <NameValue>
            <Name>ITDS</Name>
            <Value>ITEM DESCRIPTION 123 </Value>
        </NameValue>
...

The CLR C# Code to accomplish listing out the Resultset from the API works as shown below:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using Microsoft.SqlServer.Server;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void CallM3API_Test1()
    {
        SqlPipe pipe_msg = SqlContext.Pipe;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://M3Server.domain.com:12345/m3api-rest/execute/MMS200MI/Get?ITNO=ITEM123");

            request.Method = "Get";
            request.ContentLength = 0;

            request.Credentials = new NetworkCredential("[email protected]", "MyPassword");
            request.ContentType = "application/xml";
            request.Accept = "application/xml";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                    using (Stream receiveStream = response.GetResponseStream())
                    {
                        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                        {
                            string strContent = readStream.ReadToEnd();
                            XmlDocument xdoc = new XmlDocument();
                            xdoc.LoadXml(strContent);
                            try
                            {
                                SqlPipe pipe = SqlContext.Pipe;

                                //Define Output Columns and Max Length of each Column in the Resultset    
                                SqlMetaData[] cols = new SqlMetaData[2];
                                cols[0] = new SqlMetaData("Name", SqlDbType.NVarChar, 50);
                                cols[1] = new SqlMetaData("Value", SqlDbType.NVarChar, 120);
                                SqlDataRecord record = new SqlDataRecord(cols);

                                pipe.SendResultsStart(record);

                                XmlNodeList nodeList = xdoc.GetElementsByTagName("NameValue");
                                //List ALL Output Names + Values
                                foreach (XmlNode nodeRes in nodeList)
                                {
                                    record.SetSqlString(0, nodeRes["Name"].InnerText);
                                    record.SetSqlString(1, nodeRes["Value"].InnerText);

                                    pipe.SendResultsRow(record);
                                }

                                pipe.SendResultsEnd();
                            }
                            catch (Exception ex)
                            {
                                SqlContext.Pipe.Send("Error (readStream): " + ex.Message);
                            }
                        }
                    }
            }
        }
        catch (Exception ex)
        {
            SqlContext.Pipe.Send("Error (CallM3API_Test1): " + ex.Message);

        }
    }
}

Hopefully this provides helpful.

Webdriver and proxy server for firefox

According to the latest documentation

from selenium import webdriver

PROXY = "<HOST:PORT>"
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
    "httpProxy": PROXY,
    "ftpProxy": PROXY,
    "sslProxy": PROXY,
    "proxyType": "MANUAL",

}

with webdriver.Firefox() as driver:
    # Open URL
    driver.get("https://selenium.dev")

How to sum digits of an integer in java?

Java 8 Solution:

int n= 29;    
String.valueOf(n).chars().map(Character::getNumericValue).sum()

Is there a way to do repetitive tasks at intervals?

The function time.NewTicker makes a channel that sends a periodic message, and provides a way to stop it. Use it something like this (untested):

ticker := time.NewTicker(5 * time.Second)
quit := make(chan struct{})
go func() {
    for {
       select {
        case <- ticker.C:
            // do stuff
        case <- quit:
            ticker.Stop()
            return
        }
    }
 }()

You can stop the worker by closing the quit channel: close(quit).

Font size of TextView in Android application changes on changing font size from native settings

It is not a good thing to have to specify DIP or SP again by code when already defined in a dimen.xml file.

I think that the best option is to use PX when using a dimen.xml value :

tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.txt_size));

This way, you can switch from DP to SP if needed in dimen.xml file without having to change any code.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

No you can't use bind variables that way. In your second example :into_bind in v_query_str is just a placeholder for value of variable v_num_of_employees. Your select into statement will turn into something like:

SELECT COUNT(*) INTO  FROM emp_...

because the value of v_num_of_employees is null at EXECUTE IMMEDIATE.

Your first example presents the correct way to bind the return value to a variable.

Edit

The original poster has edited the second code block that I'm referring in my answer to use OUT parameter mode for v_num_of_employees instead of the default IN mode. This modification makes the both examples functionally equivalent.

Date format Mapping to JSON Jackson

Of course there is an automated way called serialization and deserialization and you can define it with specific annotations (@JsonSerialize,@JsonDeserialize) as mentioned by pb2q as well.

You can use both java.util.Date and java.util.Calendar ... and probably JodaTime as well.

The @JsonFormat annotations not worked for me as I wanted (it has adjusted the timezone to different value) during deserialization (the serialization worked perfect):

@JsonFormat(locale = "hu", shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm", timezone = "CET")

@JsonFormat(locale = "hu", shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm", timezone = "Europe/Budapest")

You need to use custom serializer and custom deserializer instead of the @JsonFormat annotation if you want predicted result. I have found real good tutorial and solution here http://www.baeldung.com/jackson-serialize-dates

There are examples for Date fields but I needed for Calendar fields so here is my implementation:

The serializer class:

public class CustomCalendarSerializer extends JsonSerializer<Calendar> {

    public static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public static final Locale LOCALE_HUNGARIAN = new Locale("hu", "HU");
    public static final TimeZone LOCAL_TIME_ZONE = TimeZone.getTimeZone("Europe/Budapest");

    @Override
    public void serialize(Calendar value, JsonGenerator gen, SerializerProvider arg2)
            throws IOException, JsonProcessingException {
        if (value == null) {
            gen.writeNull();
        } else {
            gen.writeString(FORMATTER.format(value.getTime()));
        }
    }
}

The deserializer class:

public class CustomCalendarDeserializer extends JsonDeserializer<Calendar> {

    @Override
    public Calendar deserialize(JsonParser jsonparser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        String dateAsString = jsonparser.getText();
        try {
            Date date = CustomCalendarSerializer.FORMATTER.parse(dateAsString);
            Calendar calendar = Calendar.getInstance(
                CustomCalendarSerializer.LOCAL_TIME_ZONE, 
                CustomCalendarSerializer.LOCALE_HUNGARIAN
            );
            calendar.setTime(date);
            return calendar;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

and the usage of the above classes:

public class CalendarEntry {

    @JsonSerialize(using = CustomCalendarSerializer.class)
    @JsonDeserialize(using = CustomCalendarDeserializer.class)
    private Calendar calendar;

    // ... additional things ...
}

Using this implementation the execution of the serialization and deserialization process consecutively results the origin value.

Only using the @JsonFormat annotation the deserialization gives different result I think because of the library internal timezone default setup what you can not change with annotation parameters (that was my experience with Jackson library 2.5.3 and 2.6.3 version as well).

Difference between the Apache HTTP Server and Apache Tomcat?

  1. Apache is a general-purpose http server, which supports a number of advanced options that Tomcat doesn't.
  2. Although Tomcat can be used as a general purpose http server, you can also set up Apache and Tomcat to work together with Apache serving static content and forwarding the requests for dynamic content to Tomcat.

How to change the color of winform DataGridview header?

dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

How to cancel a pull request on github?

If you sent a pull request on a repository where you don't have the rights to close it, you can delete the branch from where the pull request originated. That will cancel the pull request.

Should we pass a shared_ptr by reference or by value?

There was a recent blog post: https://medium.com/@vgasparyan1995/pass-by-value-vs-pass-by-reference-to-const-c-f8944171e3ce

So the answer to this is: Do (almost) never pass by const shared_ptr<T>&.
Simply pass the underlying class instead.

Basically the only reasonable parameters types are:

  • shared_ptr<T> - Modify and take ownership
  • shared_ptr<const T> - Don't modify, take ownership
  • T& - Modify, no ownership
  • const T& - Don't modify, no ownership
  • T - Don't modify, no ownership, Cheap to copy

As @accel pointed out in https://stackoverflow.com/a/26197326/1930508 the advice from Herb Sutter is:

Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership

But in how many cases are you not sure? So this is a rare situation

How do I execute multiple SQL Statements in Access' Query Editor?

You might find it better to use a 3rd party program to enter the queries into Access such as WinSQL I think from memory WinSQL supports multiple queries via it's batch feature.

I ultimately found it easier to just write a program in perl to do bulk INSERTS into an Access via ODBC. You could use vbscript or any language that supports ODBC though.

You can then do anything you like and have your own complicated logic to handle the importing.

Unable to read repository at http://download.eclipse.org/releases/indigo

In Windows 7 32-bit version, I started the eclipse with as an administrator. This worked for me.

Delete all Duplicate Rows except for One in MySQL?

Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.

NB - You need to do this first on a test copy of your table!

When I did it, I found that unless I also included AND n1.id <> n2.id, it deleted every row in the table.

  1. If you want to keep the row with the lowest id value:

    DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
    
  2. If you want to keep the row with the highest id value:

    DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
    

I used this method in MySQL 5.1

Not sure about other versions.


Update: Since people Googling for removing duplicates end up here
Although the OP's question is about DELETE, please be advised that using INSERT and DISTINCT is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE, it took more than 2 hours and yet didn't complete.

INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
    SELECT DISTINCT cellId,attributeId,entityRowId,value
    FROM tableName;

How to remove decimal values from a value of type 'double' in Java

You can use DecimalFormat, but please also note that it is not a good idea to use double in these situations, rather use BigDecimal

How to Customize a Progress Bar In Android

Customizing the color of progressbar namely in case of spinner type needs an xml file and initiating codes in their respective java files.

Create an xml file and name it as progressbar.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    tools:context=".Radio_Activity" >

    <LinearLayout
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ProgressBar
            android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </ProgressBar>
    </LinearLayout>

</LinearLayout>

Use the following code to get the spinner in various expected color.Here we use the hexcode to display spinner in blue color.

Progressbar spinner = (ProgressBar) progrees.findViewById(R.id.spinner);
spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#80DAEB"),
                android.graphics.PorterDuff.Mode.MULTIPLY);

Trying to fire the onload event on script tag

You should set the src attribute after the onload event, f.ex:

el.onload = function() { //...
el.src = script;

You should also append the script to the DOM before attaching the onload event:

$body.append(el);
el.onload = function() { //...
el.src = script;

Remember that you need to check readystate for IE support. If you are using jQuery, you can also try the getScript() method: http://api.jquery.com/jQuery.getScript/

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

For each conflicted file you get, you can specify

git checkout --ours -- <paths>
# or
git checkout --theirs -- <paths>

From the git checkout docs

git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>...

--ours
--theirs
When checking out paths from the index, check out stage #2 (ours) or #3 (theirs) for unmerged paths.

The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using -f will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using --ours or --theirs. With -m, changes made to the working tree file can be discarded to re-create the original conflicted merge result.

Selecting an element in iFrame jQuery

Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html

$("#iframeID").contents().find("[tokenid=" + token + "]").html();

Place your selector in the find method.

This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.

jQuery/JavaScript: accessing contents of an iframe

How to git commit a single file/directory

you try if You are in Master branch git commit -m "Commit message" -- filename.ext

'python' is not recognized as an internal or external command

I have found the answer... click on the installer and check the box "Add python to environment variables" DO NOT uninstall the old one rather click on modify....Click on link for picture...

enter image description here

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

Can I get a patch-compatible output from git-diff?

  1. I save the diff of the current directory (including uncommitted files) against the current HEAD.
  2. Then you can transport the save.patch file to wherever (including binary files).
  3. On your target machine, apply the patch using git apply <file>

Note: it diff's the currently staged files too.

$ git diff --binary --staged HEAD > save.patch
$ git reset --hard
$ <transport it>
$ git apply save.patch

Parsing JSON from URL

Here is a easy method.

First parse the JSON from url -

public String readJSONFeed(String URL) {
    StringBuilder stringBuilder = new StringBuilder();
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(URL);

    try {

        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == 200) {

            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            inputStream.close();

        } else {
            Log.d("JSON", "Failed to download file");
        }
    } catch (Exception e) {
        Log.d("readJSONFeed", e.getLocalizedMessage());
    }
    return stringBuilder.toString();
}

Then place a task and then read the desired value from JSON -

private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {

        return readJSONFeed(urls[0]);
    }

    protected void onPostExecute(String result) {

        JSONObject json;
        try {
            json = new JSONObject(result);

        ////CREATE A JSON OBJECT////

        JSONObject data = json.getJSONObject("JSON OBJECT NAME");

        ////GET A STRING////

        String title = data.getString("");

        //Similarly you can get other types of data
        //Replace String to the desired data type like int or boolean etc.

        } catch (JSONException e1) {
            e1.printStackTrace();

        }

        //GETTINGS DATA FROM JSON ARRAY//

        try {

            JSONObject jsonObject = new JSONObject(result);
            JSONArray postalCodesItems = new JSONArray(
                    jsonObject.getString("postalCodes"));

                JSONObject postalCodesItem = postalCodesItems
                        .getJSONObject(1);

        } catch (Exception e) {
            Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
        }
    }
}

You can then place a task like this -

new ReadPlacesFeedTask()
    .execute("JSON URL");

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

Percentage calculation

You can hold onto the percentage as decimal (value \ total) and then when you want to render to a human you can make use of Habeeb's answer or using string interpolation you could have something even cleaner:

var displayPercentage = $"{(decimal)value / total:P}";

or

//Calculate percentage earlier in code
decimal percentage = (decimal)value / total;
...
//Now render percentage
var displayPercentage = $"{percentage:P}";

An Iframe I need to refresh every 30 seconds (but not the whole page)

I have a simpler solution. In your destination page (irc_online.php) add an auto-refresh tag in the header.

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

You are checking Parent properties for null in your delegate. The same should work with lambda expressions too.

List<AnalysisObject> analysisObjects = analysisObjectRepository
        .FindAll()
        .Where(x => 
            (x.ID == packageId) || 
            (x.Parent != null &&
                (x.Parent.ID == packageId || 
                (x.Parent.Parent != null && x.Parent.Parent.ID == packageId)))
        .ToList();

ESLint Parsing error: Unexpected token

If you have got a pre-commit task with husky running eslint, please continue reading. I tried most of the answers about parserOptions and parser values where my actual issue was about the node version I was using.

My current node version was 12.0.0, but husky was using my nvm default version somehow (even though I didn't have nvm in my system). This seems to be an issue with husky itself. So:

  1. I deleted $HOME/.nvm folder which was not deleted when I removed nvm earlier.
  2. Verified node is the latest and did proper parser options.
  3. It started working!

sql try/catch rollback/commit - preventing erroneous commit after rollback

Transaction counter

--@@TRANCOUNT = 0
begin try
--@@TRANCOUNT = 0
BEGIN TRANSACTION tran1
 --@@TRANCOUNT = 1

        --your code
        -- if failed  @@TRANCOUNT = 1
        -- if success @@TRANCOUNT = 0

COMMIT TRANSACTION tran1

end try

begin catch
    print 'FAILED'
end catch

Add image in pdf using jspdf

maybe a little bit late, but I come to this situation recently and found a simple solution, 2 functions are needed.

  1. load the image.

    function getImgFromUrl(logo_url, callback) {
        var img = new Image();
        img.src = logo_url;
        img.onload = function () {
            callback(img);
        };
    } 
    
  2. in onload event on first step, make a callback to use the jspdf doc.

    function generatePDF(img){
        var options = {orientation: 'p', unit: 'mm', format: custom};
        var doc = new jsPDF(options);
        doc.addImage(img, 'JPEG', 0, 0, 100, 50);}
    
  3. use the above functions.

    var logo_url = "/images/logo.jpg";
    getImgFromUrl(logo_url, function (img) {
        generatePDF(img);
    });
    

round() doesn't seem to be rounding properly

Code:

x1 = 5.63
x2 = 5.65
print(float('%.2f' % round(x1,1)))  # gives you '5.6'
print(float('%.2f' % round(x2,1)))  # gives you '5.7'

Output:

5.6
5.7

HTML5 Canvas: Zooming

If you have a source image or canvas element and your 400x400 canvas you want to draw into you can use the drawImage method to achieve zooming.

So for example, the full view might be like this

ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);

And a zoomed view might be like this

ctx.drawImage(img, img.width / 4, img.height / 4, img.width / 2, img.height / 2, 0, 0, canvas.width, canvas.height);

The first parameter to drawImage is the image element or canvas element to draw, the next 4 are the x, y, width and height to sample from the source and the last 4 parameters are the x, y, width and height of the region to draw in the canvas. It will then handle the scaling for you.

You would just need to pick the width and height for the source sample based on the zoom level and the x and y based on where the mouse is clicked minus half the calculated width and height (but you will need to ensure the rectangle isn't out of bounds).

Laravel check if collection is empty

I prefer

(!$mentor)

Is more effective and accurate

Error: Module not specified (IntelliJ IDEA)

Faced the same issue. To solve it,

Sorting objects by property values

Example.

This runs on cscript.exe, on windows.

// define the Car class
(function() {
    // makeClass - By John Resig (MIT Licensed)
    // Allows either new User() or User() to be employed for construction.
    function makeClass(){
        return function(args){
            if ( this instanceof arguments.callee ) {
                if ( typeof this.init == "function" )
                    this.init.apply( this, (args && args.callee) ? args : arguments );
            } else
                return new arguments.callee( arguments );
        };
    }

    Car = makeClass();

    Car.prototype.init = function(make, model, price, topSpeed, weight) {
        this.make = make;
        this.model = model;
        this.price = price;
        this.weight = weight;
        this.topSpeed = topSpeed;
    };
})();


// create a list of cars
var autos = [
    new Car("Chevy", "Corvair", 1800, 88, 2900),
    new Car("Buick", "LeSabre", 31000, 138, 3700),
    new Car("Toyota", "Prius", 24000, 103, 3200),
    new Car("Porsche", "911", 92000, 155, 3100),
    new Car("Mercedes", "E500", 67000, 145, 3800),
    new Car("VW", "Passat", 31000, 135, 3700)
];

// a list of sorting functions
var sorters = {
    byWeight : function(a,b) {
        return (a.weight - b.weight);
    },
    bySpeed : function(a,b) {
        return (a.topSpeed - b.topSpeed);
    },
    byPrice : function(a,b) {
        return (a.price - b.price);
    },
    byModelName : function(a,b) {
        return ((a.model < b.model) ? -1 : ((a.model > b.model) ? 1 : 0));
    },
    byMake : function(a,b) {
        return ((a.make < b.make) ? -1 : ((a.make > b.make) ? 1 : 0));
    }
};

function say(s) {WScript.Echo(s);}

function show(title)
{
    say ("sorted by: "+title);
    for (var i=0; i < autos.length; i++) {
        say("  " + autos[i].model);
    }
    say(" ");
}

autos.sort(sorters.byWeight);
show("Weight");

autos.sort(sorters.byModelName);
show("Name");

autos.sort(sorters.byPrice);
show("Price");

You can also make a general sorter.

var byProperty = function(prop) {
    return function(a,b) {
        if (typeof a[prop] == "number") {
            return (a[prop] - b[prop]);
        } else {
            return ((a[prop] < b[prop]) ? -1 : ((a[prop] > b[prop]) ? 1 : 0));
        }
    };
};

autos.sort(byProperty("topSpeed"));
show("Top Speed");

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

Iterating through a JSON object

After deserializing the JSON, you have a python object. Use the regular object methods.

In this case you have a list made of dictionaries:

json_object[0].items()

json_object[0]["title"]

etc.

Java Reflection: How to get the name of a variable?

All you need to do is make an array of fields and then set it to the class you want like shown below.

Field fld[] = (class name).class.getDeclaredFields();   
for(Field x : fld)
{System.out.println(x);}

For example if you did

Field fld[] = Integer.class.getDeclaredFields();
          for(Field x : fld)
          {System.out.println(x);}

you would get

public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
static final char[] java.lang.Integer.digits
static final char[] java.lang.Integer.DigitTens
static final char[] java.lang.Integer.DigitOnes
static final int[] java.lang.Integer.sizeTable
private static java.lang.String java.lang.Integer.integerCacheHighPropValue
private final int java.lang.Integer.value
public static final int java.lang.Integer.SIZE
private static final long java.lang.Integer.serialVersionUID

Which is faster: multiple single INSERTs or one multiple-row INSERT?

It's ridiculous how bad Mysql and MariaDB are optimized when it comes to inserts. I tested mysql 5.7 and mariadb 10.3, no real difference on those.

I've tested this on a server with NVME disks, 70,000 IOPS, 1.1 GB/sec seq throughput and that's possible full duplex (read and write).
The server is a high performance server as well.
Gave it 20 GB of ram.
The database completely empty.

The speed I receive was 5000 inserts per second when doing multi row inserts (tried it with 1MB up to 10MB chunks of data)

Now the clue:
If I add another thread and insert into the SAME tables I suddenly have 2x5000 /sec. One more thread and I have 15000 total /sec

Consider this: When doing ONE thread inserts it means you can sequentially write to the disk (with exceptions to indexes). When using threads you actually degrade the possible performance because it now needs to do a lot more random accesses. But reality check shows mysql is so badly optimized that threads help a lot.

The real performance possible with such a server is probably millions per second, the CPU is idle the disk is idle.
The reason is quite clearly that mariadb just as mysql has internal delays.

Emulate/Simulate iOS in Linux

You might want to try screenfly. It worked great for me.

"SSL certificate verify failed" using pip to install packages

It seems that Scrapy fails because installing Twisted fails, which fails because incremental fails. Running pip install --upgrade pip && pip install --upgrade incremental fixed this for me.

How does java do modulus calculations with negative numbers?

In Java latest versions you get -13%64 = -13. The answer will always have sign of numerator.

How to get hex color value rather than RGB value?

Try

// c - color str e.g."rgb(12,233,43)", result color hex e.g. "#0ce92b"
let rgb2hex= c=> '#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``

_x000D_
_x000D_
// rgb - color str e.g."rgb(12,233,43)", result color hex e.g. "#0ce92b"_x000D_
let rgb2hex= c=> '#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``_x000D_
_x000D_
console.log(rgb2hex("rgb(12,233,43"));
_x000D_
_x000D_
_x000D_

How to add dividers and spaces between items in RecyclerView?

Here's my lazy approach but it works: wrap the CardView in a layout and set a padding/margin on the parent layout to mimic the divider, and force the normal divider to null

list_item.xml

<LinearLayout
    android:id="@+id/entry_item_layout_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="<divider_size>" > // this is the divider
    <CardView
        android:layout_width="<width_size>"
        android:layout_height="<height_size>">
        ...
    </CardView>
</LinearLayout

list.xml

<RecyclerView
 android:divider="@null"
 android:layout_width="<width_size>"
 android:layout_height="<height_size>"
 ...
/>

Why is Git better than Subversion?

This is the wrong question to be asking. It's all too easy to focus on git's warts and formulate an argument about why subversion is ostensibly better, at least for some use cases. The fact that git was originally designed as a low-level version control construction set and has a baroque linux-developer-oriented interface makes it easier for the holy wars to gain traction and perceived legitimacy. Git proponents bang the drum with millions of workflow advantages, which svn guys proclaim unnecessary. Pretty soon the whole debate is framed as centralized vs distributed, which serves the interests of the enterprise svn tool community. These companies, which typically put out the most convincing articles about subversion's superiority in the enterprise, are dependent on the perceived insecurity of git and the enterprise-readiness of svn for the long-term success of their products.

But here's the problem: Subversion is an architectural dead-end.

Whereas you can take git and build a centralized subversion replacement quite easily, despite being around for more than twice as long svn has never been able to get even basic merge-tracking working anywhere near as well as it does in git. One basic reason for this is the design decision to make branches the same as directories. I don't know why they went this way originally, it certainly makes partial checkouts very simple. Unfortunately it also makes it impossible to track history properly. Now obviously you are supposed to use subversion repository layout conventions to separate branches from regular directories, and svn uses some heuristics to make things work for the daily use cases. But all this is just papering over a very poor and limiting low-level design decision. Being able to a do a repository-wise diff (rather than directory-wise diff) is basic and critical functionality for a version control system, and greatly simplifies the internals, making it possible to build smarter and useful features on top of it. You can see in the amount of effort that has been put into extending subversion, and yet how far behind it is from the current crop of modern VCSes in terms of fundamental operations like merge resolution.

Now here's my heart-felt and agnostic advice for anyone who still believes Subversion is good enough for the foreseeable future:

Subversion will never catch up to the newer breeds of VCSes that have learned from the mistakes of RCS and CVS; it is a technical impossibility unless they retool the repository model from the ground up, but then it wouldn't really be svn would it? Regardless of how much you think you don't the capabilities of a modern VCS, your ignorance will not protect you from the Subversion's pitfalls, many of which are situations that are impossible or easily resolved in other systems.

It is extremely rare that the technical inferiority of a solution is so clear-cut as it is with svn, certainly I would never state such an opinion about win-vs-linux or emacs-vs-vi, but in this case it is so clearcut, and source control is such a fundamental tool in the developer's arsenal, that I feel it must be stated unequivocally. Regardless of the requirement to use svn for organizational reasons, I implore all svn users not to let their logical mind construct a false belief that more modern VCSes are only useful for large open-source projects. Regardless of the nature of your development work, if you are a programmer, you will be a more effective programmer if you learn how to use better-designed VCSes, whether it be Git, Mercurial, Darcs, or many others.

Getting a timestamp for today at midnight?

Today at midnight. Easy.

$stamp = mktime(0, 0, 0);

Reading *.wav files in Python

Using the struct module, you can take the wave frames (which are in 2's complementary binary between -32768 and 32767 (i.e. 0x8000 and 0x7FFF). This reads a MONO, 16-BIT, WAVE file. I found this webpage quite useful in formulating this:

import wave, struct

wavefile = wave.open('sine.wav', 'r')

length = wavefile.getnframes()
for i in range(0, length):
    wavedata = wavefile.readframes(1)
    data = struct.unpack("<h", wavedata)
    print(int(data[0]))

This snippet reads 1 frame. To read more than one frame (e.g., 13), use

wavedata = wavefile.readframes(13)
data = struct.unpack("<13h", wavedata)

How do I get the path of the Python script I am running in?

import os
print os.path.abspath(__file__)

Rethrowing exceptions in Java without losing the stack trace

public int read(byte[] a) throws IOException {
    try {
        return in.read(a);
    } catch (final Throwable t) {
        /* can do something here, like  in=null;  */
        throw t;
    }
}

This is a concrete example where the method throws an IOException. The final means t can only hold an exception thrown from the try block. Additional reading material can be found here and here.

How do I get a plist as a Dictionary in Swift?

I use swift dictionaries but convert them to and from NSDictionaries in my file manager class like so:

    func writePlist(fileName:String, myDict:Dictionary<String, AnyObject>){
        let docsDir:String = dirPaths[0] as String
        let docPath = docsDir + "/" + fileName
        let thisDict = myDict as NSDictionary
        if(thisDict.writeToFile(docPath, atomically: true)){
            NSLog("success")
        } else {
            NSLog("failure")
        }

    }
    func getPlist(fileName:String)->Dictionary<String, AnyObject>{
        let docsDir:String = dirPaths[0] as String
        let docPath = docsDir + "/" + fileName
        let thisDict = NSDictionary(contentsOfFile: docPath)
        return thisDict! as! Dictionary<String, AnyObject>
    }

This seems the least troubling way to read and write but let's the rest of my code stay as swift as possible.

Animation fade in and out

FOR FADE add this first line with your animation's object.

.animate().alpha(1).setDuration(2000);

FOR EXAMPLEI USED LottieAnimation

Print debugging info from stored procedure in MySQL

Option 1: Put this in your procedure to print 'comment' to stdout when it runs.

SELECT 'Comment';

Option 2: Put this in your procedure to print a variable with it to stdout:

declare myvar INT default 0;
SET myvar = 5;
SELECT concat('myvar is ', myvar);

This prints myvar is 5 to stdout when the procedure runs.

Option 3, Create a table with one text column called tmptable, and push messages to it:

declare myvar INT default 0;
SET myvar = 5;
insert into tmptable select concat('myvar is ', myvar);

You could put the above in a stored procedure, so all you would have to write is this:

CALL log(concat('the value is', myvar));

Which saves a few keystrokes.

Option 4, Log messages to file

select "penguin" as log into outfile '/tmp/result.txt';

There is very heavy restrictions on this command. You can only write the outfile to areas on disk that give the 'others' group create and write permissions. It should work saving it out to /tmp directory.

Also once you write the outfile, you can't overwrite it. This is to prevent crackers from rooting your box just because they have SQL injected your website and can run arbitrary commands in MySQL.

JPA Query.getResultList() - use in a generic way

Here is the sample on what worked for me. I think that put method is needed in entity class to map sql columns to java class attributes.

    //simpleExample
    Query query = em.createNativeQuery(
"SELECT u.name,s.something FROM user u,  someTable s WHERE s.user_id = u.id", 
NameSomething.class);
    List list = (List<NameSomething.class>) query.getResultList();

Entity class:

    @Entity
    public class NameSomething {

        @Id
        private String name;

        private String something;

        // getters/setters



        /**
         * Generic put method to map JPA native Query to this object.
         *
         * @param column
         * @param value
         */
        public void put(Object column, Object value) {
            if (((String) column).equals("name")) {
                setName(String) value);
            } else if (((String) column).equals("something")) {
                setSomething((String) value);
            }
        }
    }

SQL Server: Get table primary key using sql query

SELECT COLUMN_NAME FROM {DATABASENAME}.INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME LIKE '{TABLENAME}' AND CONSTRAINT_NAME LIKE 'PK%'

WHERE
{DATABASENAME} = your database from your server AND
{TABLENAME} = your table name from which you want to see the primary key.

NOTE : enter your database name and table name without brackets.

How to create multidimensional array

I know this is an old question but here is something to try: Make your multidimensional array, and place it inside an html tag. This way you can precisely aim your array'd input:

//Your Holding tag for your inputs!
<div id='input-container' class='funky'></div>

<script>
    //With VAR: you can seperate each variable with a comma instead of:
    //creating var at the beginning and a semicolon at the end.
    //Creates a cleaner layout of your variables
    var
        arr=[['input1-1','input1-2'],['input2-1','input2-2']],
        //globall calls these letters var so you dont have to recreate variable below
        i,j
    ;

    //Instead of the general 'i<array.length' you can go even further
    //by creating array[i] in place of 'i<array.length'
    for(i=0;arr[i];i++){
    for(j=0;arr[i][j];j++){
        document.getElementById('input-container').innerHTML+=
            "<input class='inner-funky'>"+arr[i][j]+"</input>"
        ;
    }}
</script>

Its simply a neater way to write your code and easier to invoke. You can check my demo here!

How does RewriteBase work in .htaccess

The clearest explanation I found was not in the current 2.4 apache docs, but in version 2.0.

#  /abc/def/.htaccess -- per-dir config file for directory /abc/def
#  Remember: /abc/def is the physical path of /xyz, i.e., the server
#            has a 'Alias /xyz /abc/def' directive e.g.

RewriteEngine On

#  let the server know that we were reached via /xyz and not
#  via the physical path prefix /abc/def
RewriteBase   /xyz

How does it work? For you apache hackers, this 2.0 doc goes on to give "detailed information about the internal processing steps."

Lesson learned: While we need to be familiar with "current," gems can be found in the annals.

Convert HTML5 into standalone Android App

Create an Android app using Eclipse.

Create a layout that has a <WebView> control.

Move your HTML code to /assets folder.

Load webview with your file:///android_asset/ file.

And you have an android app!

Fade In Fade Out Android Animation in Java

viewToAnimate.animate().alpha(1).setDuration(1000).setInterpolator(new DecelerateInterpolator()).withEndAction(new Runnable() {
    @Override
    public void run() {
        viewToAnimate.animate().alpha(0).setDuration(1000).setInterpolator(new AccelerateInterpolator()).start();
    }
}).start();

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

When this happened to me (out of nowhere) I was about to dive into the top answer above, and then I figured I'd close the project, close Visual Studio, and then re-open everything. Problem solved. VS bug?

Play infinitely looping video on-load in HTML5

As of April 2018, Chrome (along with several other major browsers) now require the muted attribute too.

Therefore, you should use

<video width="320" height="240" autoplay loop muted>
  <source src="movie.mp4" type="video/mp4" />
</video>

I'm getting Key error in python

For dict, just use

if key in dict

and don't use searching in key list

if key in dict.keys()

The latter will be more time-consuming.

Module is not available, misspelled or forgot to load (but I didn't)

I got this error when my service declaration was inside a non-invoked function (IIFE). The last line below did NOT have the extra () to run and define the service.

(function() {
    "use strict";

    angular.module("reviewService", [])
        .service("reviewService", reviewService);

    function reviewService($http, $q, $log) {
        //
    }
}());

Understanding SQL Server LOCKS on SELECT queries

The SELECT WITH (NOLOCK) allows reads of uncommitted data, which is equivalent to having the READ UNCOMMITTED isolation level set on your database. The NOLOCK keyword allows finer grained control than setting the isolation level on the entire database.

Wikipedia has a useful article: Wikipedia: Isolation (database systems)

It is also discussed at length in other stackoverflow articles.

How to remove any URL within a string in Python

You could also look at it from the other way around...

from urlparse import urlparse
[el for el in ['text1', 'FTP://somewhere.com', 'text2', 'http://blah.com:8080/foo/bar#header'] if not urlparse(el).scheme]

Convert form data to JavaScript object with jQuery

const formData = new FormData(form);

let formDataJSON = {};

for (const [key, value] of formData.entries()) {

    formDataJSON[key] = value;
}

How to read strings from a Scanner in a Java console application?

What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));

Hope this helps.

How to compare timestamp dates with date-only parameter in MySQL?

In case you are using SQL parameters to run the query then this would be helpful

SELECT * FROM table WHERE timestamp between concat(date(?), ' ', '00:00:00') and concat(date(?), ' ', '23:59:59')

Pretty printing XML with javascript

From the text of the question I get the impression that a string result is expected, as opposed to an HTML-formatted result.

If this is so, the simplest way to achieve this is to process the XML document with the identity transformation and with an <xsl:output indent="yes"/> instruction:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

When applying this transformation on the provided XML document:

<root><node/></root>

most XSLT processors (.NET XslCompiledTransform, Saxon 6.5.4 and Saxon 9.0.0.2, AltovaXML) produce the wanted result:

<root>
  <node />
</root>

Return from a promise then()

I prefer to use "await" command and async functions to get rid of confusions of promises,

In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :

async function SubFunction(output){

   // Call to database , returns a promise, like an Ajax call etc :

   const response = await axios.get( GetApiHost() + '/api/some_endpoint')

   // Return :
   return response;

}

and then I would call this function from main function :

async function justTesting() {
   const lv_result = await SubFunction(output);

   return lv_result + 1;
}

Noting that I returned both main function and sub function to async functions here.

byte[] to hex string

private static string GuidToRaw(Guid guid)
{
    byte[] bytes = guid.ToByteArray();

    int ?harCount = bytes.Length * 2;
    char[] chars = new char[?harCount];

    int index = 0;
    for (int i = 0; i < ?harCount; i += 2)
    {
        byte b = bytes[index++];
        chars[i] = GetHexValue((int)(b / 16));
        chars[i + 1] = GetHexValue((int)(b % 16));
    }
    return new string(chars, 0, chars.Length);
}

private static char GetHexValue(int i)
{
    return (char)(i < 10 ? i + 48 : i + 55);
}

disable Bootstrap's Collapse open/close animation

For Bootstrap 3 and 4 it's

.collapsing {
    -webkit-transition: none;
    transition: none;
    display: none;
}

Printing an int list in a single line python3

Maybe this code will help you.

>>> def sort(lists):
...     lists.sort()
...     return lists
...
>>> datalist = [6,3,4,1,3,2,9]
>>> print(*sort(datalist), end=" ")
1 2 3 3 4 6 9

you can use an empty list variable to collect the user input, with method append(). and if you want to print list in one line you can use print(*list)

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

PHP file_get_contents() and setting request headers

You can use this variable to retrieve response headers after file_get_contents() function.

Code:

  file_get_contents("http://example.com");
  var_dump($http_response_header);

Output:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}

Using jq to parse and display multiple fields in a json serially

You can use addition to concatenate strings.

Strings are added by being joined into a larger string.

jq '.users[] | .first + " " + .last'

The above works when both first and last are string. If you are extracting different datatypes(number and string), then we need to convert to equivalent types. Referring to solution on this question. For example.

jq '.users[] | .first + " " + (.number|tostring)'

What size do you use for varchar(MAX) in your parameter declaration?

The maximum SqlDbType.VarChar size is 2147483647.

If you would use a generic oledb connection instead of sql, I found here there is also a LongVarChar datatype. Its max size is 2147483647.

cmd.Parameters.Add("@blah", OleDbType.LongVarChar, -1).Value = "very big string";

git stash changes apply to new branch?

If you have some changes on your workspace and you want to stash them into a new branch use this command:

git stash branch branchName

It will make:

  1. a new branch
  2. move changes to this branch
  3. and remove latest stash (Like: git stash pop)

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

Expanding on retrography's answer..: I had this same problem even when using LocalDate and not LocalDateTime. The issue was that I had created my DateTimeFormatter using .withResolverStyle(ResolverStyle.STRICT);, so I had to use date pattern uuuuMMdd instead of yyyyMMdd (i.e. "year" instead of "year-of-era")!

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .parseStrict()
  .appendPattern("uuuuMMdd")
  .toFormatter()
  .withResolverStyle(ResolverStyle.STRICT);
LocalDate dt = LocalDate.parse("20140218", formatter);

(This solution was originally a comment to retrography's answer, but I was encouraged to post it as a stand-alone answer because it apparently works really well for many people.)

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

How to uncompress a tar.gz in another directory

gzip -dc archive.tar.gz | tar -xf - -C /destination

or, with GNU tar

tar xzf archive.tar.gz -C /destination

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

Run the below command to create a migration file:

rails g migration ChangeHasedPasswordToHashedPassword

Then in the file generated in the db/migrate folder, write rename_column as below:

class ChangeOldCoulmnToNewColumn < ActiveRecord::Migration
  def change
     rename_column :table_name, :hased_password, :hashed_password
  end
end

How to find index of list item in Swift?

Swift 4. If your array contains elements of type [String: AnyObject]. So to find the index of element use the below code

var array = [[String: AnyObject]]()// Save your data in array
let objectAtZero = array[0] // get first object
let index = (self.array as NSArray).index(of: objectAtZero)

Or If you want to found index on the basis of key from Dictionary. Here array contains Objects of Model class and I am matching id property.

   let userId = 20
    if let index = array.index(where: { (dict) -> Bool in
           return dict.id == userId // Will found index of matched id
    }) {
    print("Index found")
    }
OR
      let storeId = Int(surveyCurrent.store_id) // Accessing model key value
      indexArrUpTo = self.arrEarnUpTo.index { Int($0.store_id) == storeId }! // Array contains models and finding specific one

How do you write multiline strings in Go?

According to the language specification you can use a raw string literal, where the string is delimited by backticks instead of double quotes.

`line 1
line 2
line 3`

How to configure log4j to only keep log files for the last seven days?

My script based on @dogbane's answer

/etc/cron.daily/hbase

#!/bin/sh
find /var/log/hbase -type f -name "phoenix-hbase-server.log.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]" -exec bzip2 {} ";"
find /var/log/hbase -type f -regex ".*.out.[0-9][0-9]?" -exec bzip2 {} ";"
find /var/log/hbase -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

/etc/cron.daily/tomcat

#!/bin/sh
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*log" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].txt" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

because Tomcat rotate needs one day delay.

How to calculate the IP range when the IP address and the netmask is given?

Input: 192.168.0.1/25

The mask is this part: /25

To find the network address do the following:

  • Subtract the mask from the ip length (32 - mask) = 32 - 25 = 7 and take those bits from the right

  • In the given ip address I.e: 192.168.0.1 in binary is: 11111111 11111111 00000000 00000001 Now, taking 7 bits from right '0' 1111111 11111111 00000000 00000000 Which in decimal is: 192.168.0.0 (this is the network address)

To find first valid/usable ip address add +1 to network address I.e: 192.168.0.1

To find the last/broadcast address the procedure is same as that of finding network address but here you have to make (32-mask) bits from right to '1'

I.e: 11111111 11111111 00000000 01111111 Which in decimal is 192.168.0.127

To find the last valid/usable ip address subtract 1 from the broadcast address I.e: 192.168.0.126

What is the best way to repeatedly execute a function every x seconds?

The easier way I believe to be:

import time

def executeSomething():
    #code here
    time.sleep(60)

while True:
    executeSomething()

This way your code is executed, then it waits 60 seconds then it executes again, waits, execute, etc... No need to complicate things :D

In PHP with PDO, how to check the final SQL parametrized query?

So I think I'll finally answer my own question in order to have a full solution for the record. But have to thank Ben James and Kailash Badu which provided the clues for this.

Short Answer
As mentioned by Ben James: NO.
The full SQL query does not exist on the PHP side, because the query-with-tokens and the parameters are sent separately to the database. Only on the database side the full query exists.

Even trying to create a function to replace tokens on the PHP side would not guarantee the replacement process is the same as the SQL one (tricky stuff like token-type, bindValue vs bindParam, ...)

Workaround
This is where I elaborate on Kailash Badu's answer. By logging all SQL queries, we can see what is really run on the server. With mySQL, this can be done by updating the my.cnf (or my.ini in my case with Wamp server), and adding a line like:

log=[REPLACE_BY_PATH]/[REPLACE_BY_FILE_NAME]

Just do not run this in production!!!

Given a view, how do I get its viewController?

If you are not familiar with the code and you want to find ViewController coresponding to given view, then you can try:

  1. Run app in debug
  2. Navigate to screen
  3. Start View inspector
  4. Grab the View you want to find (or a child view even better)
  5. From the right pane get the address (e.g. 0x7fe523bd3000)
  6. In debug console start writing commands:
    po (UIView *)0x7fe523bd3000
    po [(UIView *)0x7fe523bd3000 nextResponder]
    po [[(UIView *)0x7fe523bd3000 nextResponder] nextResponder]
    po [[[(UIView *)0x7fe523bd3000 nextResponder] nextResponder] nextResponder]
    ...

In most cases you will get UIView, but from time to time there will be UIViewController based class.

Proper usage of .net MVC Html.CheckBoxFor

I was looking for the solution to show the label dynamically from database like this:

checkbox1 : Option 1 text from database
checkbox2 : Option 2 text from database
checkbox3 : Option 3 text from database
checkbox4 : Option 4 text from database

So none of the above solution worked for me so I used like this:

 @Html.CheckBoxFor(m => m.Option1, new { @class = "options" }) 
 <label for="Option1">@Model.Option1Text</label>

 @Html.CheckBoxFor(m => m.Option2, new { @class = "options" }) 
 <label for="Option2">@Mode2.Option1Text</label>

In this way when user will click on label, checkbox will be selected.

Might be it can help someone.

Which language uses .pde extension?

pde is extesion for:

  • Processing: Java derived language

  • Wiring: C/C++ derived language (Wiring is derived from Processing)

  • Early versions of Arduino: C/C++ derived (Arduino IDE is derived from Wiring)

For Arduino for example the IDE preprocessor is adding some #defines and some C/C++ files before giving all to gcc.

Android Service Stops When App Is Closed

You must add this code in your Service class so that it handles the case when your process is being killed

 @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());

        PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 1000,
                restartServicePendingIntent);

        super.onTaskRemoved(rootIntent);
    }

How to replace a substring of a string

By regex i think this is java, the method replaceAll() returns a new String with the substrings replaced, so try this:

String teste = "abcd=0; efgh=1";

String teste2 = teste.replaceAll("abcd", "dddd");

System.out.println(teste2);

Output:

dddd=0; efgh=1

How to kill a process running on particular port in Linux?

Get the PID of the task and kill it.

lsof -ti:8080 | xargs kill

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Convert ArrayList<String> to String[] array

I can see many answers showing how to solve problem, but only Stephen's answer is trying to explain why problem occurs so I will try to add something more on this subject. It is a story about possible reasons why Object[] toArray wasn't changed to T[] toArray where generics ware introduced to Java.


Why String[] stockArr = (String[]) stock_list.toArray(); wont work?

In Java, generic type exists at compile-time only. At runtime information about generic type (like in your case <String>) is removed and replaced with Object type (take a look at type erasure). That is why at runtime toArray() have no idea about what precise type to use to create new array, so it uses Object as safest type, because each class extends Object so it can safely store instance of any class.

Now the problem is that you can't cast instance of Object[] to String[].

Why? Take a look at this example (lets assume that class B extends A):

//B extends A
A a = new A();
B b = (B)a;

Although such code will compile, at runtime we will see thrown ClassCastException because instance held by reference a is not actually of type B (or its subtypes). Why is this problem (why this exception needs to be cast)? One of the reasons is that B could have new methods/fields which A doesn't, so it is possible that someone will try to use these new members via b reference even if held instance doesn't have (doesn't support) them. In other words we could end up trying to use data which doesn't exist, which could lead to many problems. So to prevent such situation JVM throws exception, and stop further potentially dangerous code.

You could ask now "So why aren't we stopped even earlier? Why code involving such casting is even compilable? Shouldn't compiler stop it?". Answer is: no because compiler can't know for sure what is the actual type of instance held by a reference, and there is a chance that it will hold instance of class B which will support interface of b reference. Take a look at this example:

A a = new B(); 
      //  ^------ Here reference "a" holds instance of type B
B b = (B)a;    // so now casting is safe, now JVM is sure that `b` reference can 
               // safely access all members of B class

Now lets go back to your arrays. As you see in question, we can't cast instance of Object[] array to more precise type String[] like

Object[] arr = new Object[] { "ab", "cd" };
String[] arr2 = (String[]) arr;//ClassCastException will be thrown

Here problem is a little different. Now we are sure that String[] array will not have additional fields or methods because every array support only:

  • [] operator,
  • length filed,
  • methods inherited from Object supertype,

So it is not arrays interface which is making it impossible. Problem is that Object[] array beside Strings can store any objects (for instance Integers) so it is possible that one beautiful day we will end up with trying to invoke method like strArray[i].substring(1,3) on instance of Integer which doesn't have such method.

So to make sure that this situation will never happen, in Java array references can hold only

  • instances of array of same type as reference (reference String[] strArr can hold String[])
  • instances of array of subtype (Object[] can hold String[] because String is subtype of Object),

but can't hold

  • array of supertype of type of array from reference (String[] can't hold Object[])
  • array of type which is not related to type from reference (Integer[] can't hold String[])

In other words something like this is OK

Object[] arr = new String[] { "ab", "cd" }; //OK - because
               //  ^^^^^^^^                  `arr` holds array of subtype of Object (String)
String[] arr2 = (String[]) arr; //OK - `arr2` reference will hold same array of same type as 
                                //     reference

You could say that one way to resolve this problem is to find at runtime most common type between all list elements and create array of that type, but this wont work in situations where all elements of list will be of one type derived from generic one. Take a look

//B extends A
List<A> elements = new ArrayList<A>();
elements.add(new B());
elements.add(new B());

now most common type is B, not A so toArray()

A[] arr = elements.toArray();

would return array of B class new B[]. Problem with this array is that while compiler would allow you to edit its content by adding new A() element to it, you would get ArrayStoreException because B[] array can hold only elements of class B or its subclass, to make sure that all elements will support interface of B, but instance of A may not have all methods/fields of B. So this solution is not perfect.


Best solution to this problem is explicitly tell what type of array toArray() should be returned by passing this type as method argument like

String[] arr = list.toArray(new String[list.size()]);

or

String[] arr = list.toArray(new String[0]); //if size of array is smaller then list it will be automatically adjusted.

How to make a GridLayout fit screen size

After many attempts I found what I was looking for in this layout. Even spaced LinearLayouts with automatically fitted ImageViews, with maintained aspect ratio. Works with landscape and portrait with any screen and image resolution.

Nexus 7 Nexus 5 Nexus 10

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffcc5d00" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">


        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_weight="1"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image1"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image2"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_weight="1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image3"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:padding="10dip"
                    android:layout_height="fill_parent">

                    <ImageView
                        android:id="@+id/image4"
                        android:layout_height="fill_parent"
                        android:adjustViewBounds="true"
                        android:scaleType="fitCenter"
                        android:src="@drawable/stackoverflow"
                        android:layout_width="fill_parent"
                        android:layout_gravity="center" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</FrameLayout>

Determine SQL Server Database Size

The best solution is maybe to calculate the size of each database file, using the sys.sysfiles view, considering a size of 8 KB for each page, as follows:

USE [myDatabase]
GO

SELECT
    [size] * 8
    , [filename]
FROM sysfiles

The [field] column represents the size of the file, in pages (MSDN Reference to sysfiles).

You would see there will be at least two files (MDF and LDF): the sum of these files will give you the correct size of the entire database...

How to manage a redirect request after a jQuery Ajax call

I resolved this issue like this:

Add a middleware to process response, if it is a redirect for an ajax request, change the response to a normal response with the redirect url.

class AjaxRedirect(object):
  def process_response(self, request, response):
    if request.is_ajax():
      if type(response) == HttpResponseRedirect:
        r = HttpResponse(json.dumps({'redirect': response['Location']}))
        return r
    return response

Then in ajaxComplete, if the response contains redirect, it must be a redirect, so change the browser's location.

$('body').ajaxComplete(function (e, xhr, settings) {
   if (xhr.status == 200) {
       var redirect = null;
       try {
           redirect = $.parseJSON(xhr.responseText).redirect;
           if (redirect) {
               window.location.href = redirect.replace(/\?.*$/, "?next=" + window.location.pathname);
           }
       } catch (e) {
           return;
       }
   }
}

Remove end of line characters from Java string

public static void main(final String[] argv) 
{
    String str;

    str = "hello\r\n\tjava\r\nbook";
    str = str.replaceAll("(\\r|\\n|\\t)", "");
    System.out.println(str);
}

It would be useful to add the tabulation in regex too.

jquery 3.0 url.indexOf error

I came across the same error after updating to the latest version of JQuery. Therefore I updated the jquery file I was working on, as stated in a previous answer, so it said .on("load") instead of .load().

This fix isn't very stable and sometimes it didn't work for me. Therefore to fix this issue you should update your code from:

    .load();

to

    .trigger("load");

I got this fix from the following source: https://github.com/stevenwanderski/bxslider-4/pull/1024

How to specify multiple conditions in an if statement in javascript

if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {

        PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

This could be one of possible solutions, so 'or' is || not !!

Excel VBA code to copy a specific string to clipboard

Add a reference to the Microsoft Forms 2.0 Object Library and try this code. It only works with text, not with other data types.

Dim DataObj As New MSForms.DataObject

'Put a string in the clipboard
DataObj.SetText "Hello!"
DataObj.PutInClipboard

'Get a string from the clipboard
DataObj.GetFromClipboard
Debug.Print DataObj.GetText

Here you can find more details about how to use the clipboard with VBA.

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5

Creating the checkbox dynamically using JavaScript?

The last line should read

cbh.appendChild(document.createTextNode(cap));

Appending the text (label?) to the same container as the checkbox, not the checkbox itself

How do I get formatted JSON in .NET using C#?

This worked for me. In case someone is looking for a VB.NET version.

@imports System
@imports System.IO
@imports Newtonsoft.Json

Public Shared Function JsonPrettify(ByVal json As String) As String
  Using stringReader = New StringReader(json)

    Using stringWriter = New StringWriter()
      Dim jsonReader = New JsonTextReader(stringReader)
      Dim jsonWriter = New JsonTextWriter(stringWriter) With {
          .Formatting = Formatting.Indented
      }
      jsonWriter.WriteToken(jsonReader)
      Return stringWriter.ToString()
    End Using
  End Using
End Function

Java System.out.print formatting

Are you sure that you want "055" as opposed to "55"? Some programs interpret a leading zero as meaning octal, so that it would read 055 as (decimal) 45 instead of (decimal) 55.

That should just mean dropping the '0' (zero-fill) flag.

e.g., change System.out.printf("%03d ", x); to the simpler System.out.printf("%3d ", x);

How to specify more spaces for the delimiter using cut?

If you want to pick columns from a ps output, any reason to not use -o?

e.g.

ps ax -o pid,vsz
ps ax -o pid,cmd

Minimum column width allocated, no padding, only single space field separator.

ps ax --no-headers -o pid:1,vsz:1,cmd

3443 24600 -bash
8419 0 [xfsalloc]
8420 0 [xfs_mru_cache]
8602 489316 /usr/sbin/apache2 -k start
12821 497240 /usr/sbin/apache2 -k start
12824 497132 /usr/sbin/apache2 -k start

Pid and vsz given 10 char width, 1 space field separator.

ps ax --no-headers -o pid:10,vsz:10,cmd

  3443      24600 -bash
  8419          0 [xfsalloc]
  8420          0 [xfs_mru_cache]
  8602     489316 /usr/sbin/apache2 -k start
 12821     497240 /usr/sbin/apache2 -k start
 12824     497132 /usr/sbin/apache2 -k start

Used in a script:-

oldpid=12824
echo "PID: ${oldpid}"
echo "Command: $(ps -ho cmd ${oldpid})"

Commenting out code blocks in Atom

Also, there are packages:

What is a Maven artifact?

In general software terms, an "artifact" is something produced by the software development process, whether it be software related documentation or an executable file.

In Maven terminology, the artifact is the resulting output of the maven build, generally a jar or war or other executable file. Artifacts in maven are identified by a coordinate system of groupId, artifactId, and version. Maven uses the groupId, artifactId, and version to identify dependencies (usually other jar files) needed to build and run your code.

How to get the jQuery $.ajax error response text?

This will allow you to see the whole response not just the "responseText" value

error: function(xhr, status, error) {
    var acc = []
    $.each(xhr, function(index, value) {
        acc.push(index + ': ' + value);
    });
    alert(JSON.stringify(acc));
}

Reactjs - setting inline styles correctly

It's not immediately obvious from the documentation why the following does not work:

<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>

But when doing it entirely inline:

  • You need double curly brackets
  • You don't need to put your values in quotes
  • React will add some default if you omit "em"
  • Remember to camelCase style names that have dashes in CSS - e.g. font-size becomes fontSize:
  • class is className

The correct way looks like this:

<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>

Why is January month 0 in Java Calendar?

Because programmers are obsessed with 0-based indexes. OK, it's a bit more complicated than that: it makes more sense when you're working with lower-level logic to use 0-based indexing. But by and large, I'll still stick with my first sentence.

How to return a value from pthread threads in C?

You are returning a reference to ret which is a variable on the stack.

How do you set autocommit in an SQL Server session?

Autocommit is SQL Server's default transaction management mode. (SQL 2000 onwards)

Ref: Autocommit Transactions

Access denied for user 'homestead'@'localhost' (using password: YES)

I had the same issue and in the end It turned out that I just had to restart the server and start again

Ctrl + c then

php artisan serve

is there a function in lodash to replace matched item

As the time passes you should embrace a more functional approach in which you should avoid data mutations and write small, single responsibility functions. With the ECMAScript 6 standard, you can enjoy functional programming paradigm in JavaScript with the provided map, filter and reduce methods. You don't need another lodash, underscore or what else to do most basic things.

Down below I have included some proposed solutions to this problem in order to show how this problem can be solved using different language features:

Using ES6 map:

_x000D_
_x000D_
const replace = predicate => replacement => element =>_x000D_
  predicate(element) ? replacement : element_x000D_
 _x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = arr.map(replace (predicate) (replacement))_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_


Recursive version - equivalent of mapping:

Requires destructuring and array spread.

_x000D_
_x000D_
const replace = predicate => replacement =>_x000D_
{_x000D_
  const traverse = ([head, ...tail]) =>_x000D_
    head_x000D_
    ? [predicate(head) ? replacement : head, ...tail]_x000D_
    : []_x000D_
  return traverse_x000D_
}_x000D_
 _x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = replace (predicate) (replacement) (arr)_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_


When the final array's order is not important you can use an object as a HashMap data structure. Very handy if you already have keyed collection as an object - otherwise you have to change your representation first.

Requires object rest spread, computed property names and Object.entries.

_x000D_
_x000D_
const replace = key => ({id, ...values}) => hashMap =>_x000D_
({_x000D_
  ...hashMap,       //original HashMap_x000D_
  [key]: undefined, //delete the replaced value_x000D_
  [id]: values      //assign replacement_x000D_
})_x000D_
_x000D_
// HashMap <-> array conversion_x000D_
const toHashMapById = array =>_x000D_
  array.reduce(_x000D_
    (acc, { id, ...values }) => _x000D_
    ({ ...acc, [id]: values })_x000D_
  , {})_x000D_
  _x000D_
const toArrayById = hashMap =>_x000D_
  Object.entries(hashMap)_x000D_
  .filter( // filter out undefined values_x000D_
    ([_, value]) => value _x000D_
  ) _x000D_
  .map(_x000D_
    ([id, values]) => ({ id, ...values })_x000D_
  )_x000D_
_x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const replaceKey = 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
// Create a HashMap from the array, treating id properties as keys_x000D_
const hashMap = toHashMapById(arr)_x000D_
console.log(hashMap)_x000D_
_x000D_
// Result of replacement - notice an undefined value for replaced key_x000D_
const resultHashMap = replace (replaceKey) (replacement) (hashMap)_x000D_
console.log(resultHashMap)_x000D_
_x000D_
// Final result of conversion from the HashMap to an array_x000D_
const result = toArrayById (resultHashMap)_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

How to create a data file for gnuplot?

I had the same issue when tried to open the file using Plot->Data filename... option provided in the version for Windows 7 (by the way, it worked fine on another computer with the same version of the OP system).

Then I tried to change directory and save the .plt file, but it didn't work either. Finally, I tried to tape manually as it was showed for Linux earlier in this queue of posts:

gnuplot > plot "./datafile.dat"

and it worked!

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

Build fails with "Command failed with a nonzero exit code"

Context: I was having a similar issue "Command CompileStoryboard failed with a nonzero exit code" after trying to build an iOS flutter app with the latest and Android studio and XCode 11.3 (new installation on Mojave). This was an existing flutter android app I had built with Android studio on Windows 10.

Tried and failed: Command+Shift+K, Command+B, Delete Derived data, SWIFT_ENABLE_BATCH_MODE = NO

Solution: - Open Finder and Navigate to project name > ios > Runner > Base.Iproj - Delete .storyboard files (main and launch) - Open terminal and run "flutter create ." - Open Xcode and run

Removing double quotes from a string in Java

String withoutQuotes_line1 = line1.replace("\"", "");

have a look here

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

Check if file is already open

Using the Apache Commons IO library...

boolean isFileUnlocked = false;
try {
    org.apache.commons.io.FileUtils.touch(yourFile);
    isFileUnlocked = true;
} catch (IOException e) {
    isFileUnlocked = false;
}

if(isFileUnlocked){
    // Do stuff you need to do with a file that is NOT locked.
} else {
    // Do stuff you need to do with a file that IS locked
}

SELECT INTO a table variable in T-SQL

First create a temp table :

Step 1:

create table #tblOm_Temp (

    Name varchar(100),
    Age Int ,
    RollNumber bigint
)

**Step 2: ** Insert Some value in Temp table .

insert into #tblom_temp values('Om Pandey',102,1347)

Step 3: Declare a table Variable to hold temp table data.

declare   @tblOm_Variable table(

    Name Varchar(100),
    Age int,
    RollNumber bigint
)

Step 4: select value from temp table and insert into table variable.

insert into @tblOm_Variable select * from #tblom_temp

Finally value is inserted from a temp table to Table variable

Step 5: Can Check inserted value in table variable.

select * from @tblOm_Variable

How to delete a row from GridView?

The default answer is to remove the item from whatever collection you're using as the GridView's DataSource.

If that option is undesirable then I recommend that you use the GridView's RowDataBound event to selectively set the row's (e.Row) Visible property to false.

Cannot checkout, file is unmerged

status tell you what to do.

Unmerged paths:
  (use "git reset HEAD <file>..." to unstage)
  (use "git add <file>..." to mark resolution)

you probably applied a stash or something else that cause a conflict.

either add, reset, or rm.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

What is Python buffer type for?

An example usage:

>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world

The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.

This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:

>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05'

This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.

Note that buffer has been replaced by the better named memoryview in Python 3, though you can use either in Python 2.7.

Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.

Use formula in custom calculated field in Pivot Table

I'll post this comment as answer, as I'm confident enough that what I asked is not possible.

I) Couple of similar questions trying to do the same, without success:

II) This article: Excel Pivot Table Calculated Field for example lists many restrictions of Calculated Field:

  • For calculated fields, the individual amounts in the other fields are summed, and then the calculation is performed on the total amount.
  • Calculated field formulas cannot refer to the pivot table totals or subtotals
  • Calculated field formulas cannot refer to worksheet cells by address or by name.
  • Sum is the only function available for a calculated field.
  • Calculated fields are not available in an OLAP-based pivot table.

III) There is tiny limited possibility to use AVERAGE() and similar function for a range of cells, but that applies only if Pivot table doesn't have grouped cells, which allows listing the cells as items in new group (right to "Fileds" listbox in above screenshot) and then user can calculate AVERAGE(), referencing explicitly every item (cell), from Items listbox, as argument. Maybe it's better explained here: Calculate values in a PivotTable report
For my Pivot table it wasn't applicable because my range wasn't small enough, this option to be sane choice.

SQL Query to fetch data from the last 30 days?

Pay attention to one aspect when doing "purchase_date>(sysdate-30)": "sysdate" is the current date, hour, minute and second. So "sysdate-30" is not exactly "30 days ago", but "30 days ago at this exact hour".

If your purchase dates have 00.00.00 in hours, minutes, seconds, better doing:

where trunc(purchase_date)>trunc(sysdate-30)

(this doesn't take hours, minutes and seconds into account).

Android eclipse DDMS - Can't access data/data/ on phone to pull files

If gives "permission denied" on adb shell -> su...

Some ROMs are running adbd daemon in secure mode (adbd has no root access and su command does not even show permission ask dialog on the device). In this case you will get "permission denied" when you try cmd -> adb shell -> su. The solution I've found is one app from the famous modder Chainfire called Adbd Insecure.

How do I analyze a .hprof file?

If you want to do a custom analysis of your heapdump then there's:

This library is fast but you will need to write your analysis code in Java.

From the docs:

  • Does not create any temporary files on disk to process heap dump
  • Can work directly GZ compressed heap dumps
  • HeapPath notation

Batch command to move files to a new directory

this will also work, if you like

 xcopy  C:\Test\Log "c:\Test\Backup-%date:~4,2%-%date:~7,2%-%date:~10,4%_%time:~0,2%%time:~3,2%" /s /i
 del C:\Test\Log

Java: recommended solution for deep cloning/copying an instance

I'd recommend the DIY way which, combined with a good hashCode() and equals() method should be easy to proof in a unit test.

Broken references in Virtualenvs

Anyone who is using pipenv (and you should!) can simply use these two commands — without having the venv activated:

rm -rf `pipenv --venv` # remove the broken venv
pipenv install --dev   # reinstall the venv from pipfile 

How do I install Composer on a shared hosting?

It depends on the host, but you probably simply can't (you can't on my shared host on Rackspace Cloud Sites - I asked them).

What you can do is set up an environment on your dev machine that roughly matches your shared host, and do all of your management through the command line locally. Then when everything is set (you've pulled in all the dependencies, updated, managed with git, etc.) you can "push" that to your shared host over (s)FTP.

Is it possible to write to the console in colour in .NET?

I've created a small plugin (available on NuGet) that allows you to add any (if supported by your terminal) color to your console output, without the limitations of the classic solutions.

It works by extending the String object and the syntax is very simple:

"colorize me".Pastel("#1E90FF");

Both foreground and background colors are supported.

enter image description here

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

The easiest way to do this in my experience is with the Cloudmersive free native PHP library, just call convertDocumentDocxToPdf:

<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');



$apiInstance = new Swagger\Client\Api\ConvertDocumentApi(


    new GuzzleHttp\Client(),
    $config
);
$input_file = "/path/to/file.txt"; // \SplFileObject | Input file to perform the operation on.

try {
    $result = $apiInstance->convertDocumentDocxToPdf($input_file);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling ConvertDocumentApi->convertDocumentDocxToPdf: ', $e->getMessage(), PHP_EOL;
}
?>

Be sure to replace $input_file with the appropriate file path. You can also configure it to use a byte array if you prefer to do it that way. The result will be the bytes of the converted PDF file.

Combine a list of data frames into one data frame by row

Here's another way this can be done (just adding it to the answers because reduce is a very effective functional tool that is often overlooked as a replacement for loops. In this particular case, neither of these are significantly faster than do.call)

using base R:

df <- Reduce(rbind, listOfDataFrames)

or, using the tidyverse:

library(tidyverse) # or, library(dplyr); library(purrr)
df <- listOfDataFrames %>% reduce(bind_rows)

How do I use InputFilter to limit characters in an EditText in Android?

InputFilters are a little complicated in Android versions that display dictionary suggestions. You sometimes get a SpannableStringBuilder, sometimes a plain String in the source parameter.

The following InputFilter should work. Feel free to improve this code!

new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {

        if (source instanceof SpannableStringBuilder) {
            SpannableStringBuilder sourceAsSpannableBuilder = (SpannableStringBuilder)source;
            for (int i = end - 1; i >= start; i--) { 
                char currentChar = source.charAt(i);
                 if (!Character.isLetterOrDigit(currentChar) && !Character.isSpaceChar(currentChar)) {    
                     sourceAsSpannableBuilder.delete(i, i+1);
                 }     
            }
            return source;
        } else {
            StringBuilder filteredStringBuilder = new StringBuilder();
            for (int i = start; i < end; i++) { 
                char currentChar = source.charAt(i);
                if (Character.isLetterOrDigit(currentChar) || Character.isSpaceChar(currentChar)) {    
                    filteredStringBuilder.append(currentChar);
                }     
            }
            return filteredStringBuilder.toString();
        }
    }
}

XAMPP Port 80 in use by "Unable to open process" with PID 4

Your port 80 is being used by the system.

  1. In Windows “World Wide Publishing" Service is using this port and it's process is system which PID is 4 maximum time and stopping this service(“World Wide Publishing") will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop.
  2. If you don't find there then Then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.
  3. If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80

enter image description here

And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.

When should I use Memcache instead of Memcached?

When using Windows, the comparison is cut short: memcache appears to be the only client available.

Why Is `Export Default Const` invalid?

If the component name is explained in the file name MyComponent.js, just don't name the component, keeps code slim.

import React from 'react'

export default (props) =>
    <div id='static-page-template'>
        {props.children}
    </div>

Update: Since this labels it as unknown in stack tracing, it isn't recommended

Change icon-bar (?) color in bootstrap

In bootstrap 4.3.1 I can change the background color of the toggler icon to white via the css code.

.navbar-toggler{
  background-color:white;
  }

And in my opinion the so changed icon looks fine as well on light as on dark background.

How to completely DISABLE any MOUSE CLICK

You can overlay a big, semi-transparent <div> that takes all the clicks. Just append a new <div> to <body> with this style:

.overlay {
    background-color: rgba(1, 1, 1, 0.7);
    bottom: 0;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
}

android : Error converting byte to dex

If you have multiple projects, make sure you are not adding a dependency multiple times, I needed to exclude the other project's dependency like this:

compile(project(':OtherProject-SDK')) {
    compile.exclude module: 'play-services-gcm'
    compile.exclude module: 'play-services-location'
    compile.exclude module: 'support-v4'
    compile.exclude module: 'okhttp'
}

Textarea Auto height

I used jQuery AutoSize. When I tried using Elastic it frequently gave me bogus heights (really tall textarea's). jQuery AutoSize has worked well and hasn't had this issue.

CSS center content inside div

You just do CSS changes for parent div

.parent-div { 
        text-align: center;
        display: block;
}

Center Oversized Image in Div

based on @Guffa answer
because I lost more than 2 hours to center a very wide image,
for me with a image dimendion of 2500x100px and viewport 1600x1200 or Full HD 1900x1200 works centered like that:

 .imageContainer {
  height: 100px;
  overflow: hidden;
  position: relative;
 }
 .imageCenter {
  width: auto;
  position: absolute;
  left: -10%;
  top: 0;
  margin-left: -500px;
 }
.imageCenter img {
 display: block;
 margin: 0 auto;
 }

I Hope this helps others to finish faster the task :)

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

adding line break

string[] abcd = obj.show(); 

Response.Write(string.join("</br>", abcd));

Are lists thread-safe?

Here's a comprehensive yet non-exhaustive list of examples of list operations and whether or not they are thread safe. Hoping to get an answer regarding the obj in a_list language construct here.

Assigning a function to a variable

lambda should be useful for this case. For example,

  1. create function y=x+1 y=lambda x:x+1

  2. call the function y(1) then return 2.

How do I add a newline to a TextView in Android?

System.getProperty("line.separator"); this work for me.

What are the differences in die() and exit() in PHP?

They are essentially the same, though this article suggest otherwise.

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

I removed old AppleWWDRCA, downloaded and installed AppleWWDRCA, but problem remained. I also, checked my distribution and development certificates from Keychain Access, and see below error;

"This certificate has an invalid issuer."

Then,

  1. I revoked both development and distribution certificates on member center.
  2. Re-created CSR file and add development and distribution certificates from zero, downloaded them, and installed.

This fixed certificate problem.

Since old certificates revoked, existing provisioning profiles become invalid. To fix this;

  1. On member center, opened provisioning profiles.
  2. Opened profile detail by clicking "Edit", checked certificate from the list, and clicked "Generate" button.
  3. Downloaded and installed both development and distribution profiles.

I hope this helps.

Maven command to determine which settings.xml file Maven is using

Quick and dirty method to determine if Maven is using desired settings.xml would be invalidate its xml and run some safe maven command that requires settings.xml.

If it reads this settings.xml then Maven reports an error: "Error reading settings.xml..."

Getting current device language in iOS?

For MonoTouch C# developers use:

NSLocale.PreferredLanguages.FirstOrDefault() ?? "en"

Note: I know this was an iOS question, but as I am a MonoTouch developer, the answer on this page led me in the right direction and I thought I'd share the results.

Creating a .p12 file

The openssl documentation says that file supplied as the -in argument must be in PEM format.

Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

In order to create my .p12, I had to first convert the certificate to PEM:

openssl pkcs7 -in myCert.cer -print_certs -out certs.pem

and then execute

openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem

Export to csv in jQuery

You can do that in the client side only, in browser that accept Data URIs:

data:application/csv;charset=utf-8,content_encoded_as_url

In your example the Data URI must be:

data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333

You can call this URI by:

  • using window.open
  • or setting the window.location
  • or by the href of an anchor
  • by adding the download attribute it will work in chrome, still have to test in IE.

To test, simply copy the URIs above and paste in your browser address bar. Or test the anchor below in a HTML page:

<a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>

To create the content, getting the values from the table, you can use table2CSV and do:

var data = $table.table2CSV({delivery:'value'});

$('<a></a>')
    .attr('id','downloadFile')
    .attr('href','data:text/csv;charset=utf8,' + encodeURIComponent(data))
    .attr('download','filename.csv')
    .appendTo('body');

$('#downloadFile').ready(function() {
    $('#downloadFile').get(0).click();
});

Most, if not all, versions of IE don't support navigation to a data link, so a hack must be implemented, often with an iframe. Using an iFrame combined with document.execCommand('SaveAs'..), you can get similar behavior on most currently used versions of IE.

Change an image with onclick()

If you don't want use js, I think, you can use <a href="javascript:void(0);"></a> instead of img and then use css like

a {
  background: url('oldImage.png');
}
a:visited {
  background: url('newImage.png');
}

EDIT: Nope. Sorry it works only for :hover

Access to the path is denied

If you get this error while uploading files in Sub domain And working correct in your localhost, then follow below steps:

Solution:

Plesk Panel

  • Login to your Plesk Panel. Select Your Sub domain which is giving error.
  • Click on Hosting settings.
  • Select Additional write/modify permissions and Apply.

CPanel

  • I am not sure about options available in CPanel. But IF you give permission to directory (In CPanel it has to be decimal number like 777, 755) will resolve the error.

For more details refer here

Reason for Error:

  • Let's Assume FileUpload.SaveAs(Server.MapPath("~/uploads/" + *YOUR_FILENAME*)) will be your code to move your files to upload path.
  • Server.MapPath will give you physical path (Real Path) of directory. But your Sub domain may don't have permission for access physical path.

  • So, If you give permission for sub domain to access write/modify permission, it will resolve the issue.

HTML Table width in percentage, table rows separated equally

You need to enter the width % for each cell. But wait, there's a better way to do that, it's called CSS:

<style>
     .equalDivide tr td { width:25%; }
</style>

<table class="equalDivide" cellpadding="0" cellspacing="0" width="100%" border="0">
   <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
   </tr>
</table>

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

Class library is shared compiled code.

Shared project is shared source code.

How to set UITextField height?

An update for iOS 6 : using auto-layout, even though you still can't set the UITextField's height from the Size Inspector in the Interface Builder (as of Xcode 4.5 DP4 at least), it is now possible to set a Height constraint on it, which you can edit from the Interface Builder.

Also, if you're setting the frame's height by code, auto-layout may reset it depending on the other constraints your view may have.

Configuring so that pip install can work from github

you can try this way in Colab

!git clone https://github.com/UKPLab/sentence-transformers.git
!pip install -e /content/sentence-transformers
import sentence_transformers

Javascript String to int conversion

The parseInt() function parses a string and returns an integer,10 is the Radix or Base [DOC]

var number = parseInt(id.substring(indexPos) , 10 ) + 1;

Save each sheet in a workbook to separate CSV files

And here's my solution should work with Excel > 2000, but tested only on 2007:

Private Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' ask the user where to save
OutputPath = InputBox("Enter a directory to save to", "Save to directory", Path)

If OutputPath <> "" Then

    ' save for each sheet
    For Each Sheet In Sheets

        OutputFile = OutputPath & "\" & Sheet.Name & ".csv"

        ' make a copy to create a new book with this sheet
        ' otherwise you will always only get the first sheet
        Sheet.Copy
        ' this copy will now become active
        ActiveWorkbook.SaveAs FileName:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
        ActiveWorkbook.Close
    Next

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
        "Source: " & Err.Source & " " & vbCrLf & _
        "Number: " & Err.Number & " " & vbCrLf & _
        "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub

(OT: I wonder if SO will replace some of my minor blogging)

Connection string using Windows Authentication

Replace the username and password with Integrated Security=SSPI;

So the connection string should be

<connectionStrings> 
<add name="NorthwindContex" 
   connectionString="data source=localhost;
   initial catalog=northwind;persist security info=True; 
   Integrated Security=SSPI;" 
   providerName="System.Data.SqlClient" /> 
</connectionStrings> 

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

Check if page gets reloaded or refreshed in JavaScript

Append the below Script in Console:

window.addEventListener("beforeunload", function(event) { 
     console.log("The page is redirecting")           
     debugger; 
});

Java escape JSON String?

Try to replace all the " and ' with a \ before them. Do this just for the msget object(String, I guess). Don't forget that \ must be escaped too.

Bootstrap: align input with button

Twitter Bootstrap 4

In Twitter Bootstrap 4, inputs and buttons can be aligned using the input-group-prepend and input-group-append classes (see https://getbootstrap.com/docs/4.0/components/input-group/#button-addons)

Group button on the left side (prepend)

<div class="input-group mb-3">
  <div class="input-group-prepend">
    <button class="btn btn-outline-secondary" type="button">Button</button>
  </div>
  <input type="text" class="form-control">
</div>

Group button on the right side (append)

<div class="input-group mb-3">
  <div class="input-group-append">
    <button class="btn btn-outline-secondary" type="button">Button</button>
  </div>
  <input type="text" class="form-control">
</div>

Twitter Bootstrap 3

As shown in the answer by @abimelex, inputs and buttons can be aligned by using the .input-group classes (see http://getbootstrap.com/components/#input-groups-buttons)

Group button on the left side

<div class="input-group">
  <span class="input-group-btn">
    <button class="btn btn-default" type="button">Go!</button>
  </span>
  <input type="text" class="form-control">
</div>

Group button on the right side

<div class="input-group">
   <input type="text" class="form-control">
   <span class="input-group-btn">
        <button class="btn btn-default" type="button">Go!</button>
   </span>
</div>

This solution has been added to keep my answer up to date, but please stick your up-vote on the answer provided by @abimelex.


Twitter Bootstrap 2

Bootstrap offers an .input-append class, which works as a wrapper element and corrects this for you:

<div class="input-append">
    <input name="search" id="search"/>
    <button class="btn">button</button>
</div>

As pointed out by @OleksiyKhilkevich in his answer, there is a second way to align input and button by using the .form-horizontal class:

<div class="form-horizontal">
    <input name="search" id="search"/>
    <button class="btn">button</button>
</div>

The Differences

The difference between these two classes is that .input-append will place the button up against the input element (so they look like they are attached), where .form-horizontal will place a space between them.

-- Note --

To allow the input and button elements to be next to each other without spacing, the font-size has been set to 0 in the .input-append class (this removes the white spacing between the inline-block elements). This may have an adverse effect on font-sizes in the input element if you want to override the defaults using em or % measurements.