Programs & Examples On #Flash media server

Version 4 and below of what is now called Adobe Media Server, a server that uses the RTMP protocol to receive and deliver streaming audio and video.

Why use static_cast<int>(x) instead of (int)x?

static_cast, aside from manipulating pointers to classes, can also be used to perform conversions explicitly defined in classes, as well as to perform standard conversions between fundamental types:

double d = 3.14159265;
int    i = static_cast<int>(d);

How to center text vertically with a large font-awesome icon?

For those using Bootstrap 4 is simple:

<span class="align-middle"><i class="fas fa-camera"></i></span>

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

Crystal Reports - Adding a parameter to a 'Command' query

The solution I came up with was as follows:

  1. Create the SQL query in your favorite query dev tool
  2. In Crystal Reports, within the main report, create parameter to pass to the subreport
  3. Create sub report, using the 'Add Command' option in the 'Data' portion of the 'Report Creation Wizard' and the SQL query from #1.
  4. Once the subreport is added to the main report, right click on the subreport, choose 'Change Subreport Links...', select the link field, and uncheck 'Select data in subreport based on field:'

    NOTE: You may have to initially add the parameter with the 'Select data in subreport based on field:' checked, then go back to 'Change Subreport Links ' and uncheck it after the subreport has been created.

  5. In the subreport, click the 'Report' menu, 'Select Expert', use the 'Formula Editor', set the SQL column from #1 either equal to or like the parameter(s) selected in #4.

                    (Subreport SQL Column)  (Parameter from Main Report)
            Example:  {Command.Project} like {?Pm-?Proj_Name}
    

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

Google officially suggests to developers to use Volley library for networking related stuff Here, so Its time to switch to Volley, Happy coding

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

Best practice to run Linux service as a different user

After looking at all the suggestions here, I've discovered a few things which I hope will be useful to others in my position:

  1. hop is right to point me back at /etc/init.d/functions: the daemon function already allows you to set an alternate user:

    daemon --user=my_user my_cmd &>/dev/null &
    

    This is implemented by wrapping the process invocation with runuser - more on this later.

  2. Jonathan Leffler is right: there is setuid in Python:

    import os
    os.setuid(501) # UID of my_user is 501
    

    I still don't think you can setuid from inside a JVM, however.

  3. Neither su nor runuser gracefully handle the case where you ask to run a command as the user you already are. E.g.:

    [my_user@my_host]$ id
    uid=500(my_user) gid=500(my_user) groups=500(my_user)
    [my_user@my_host]$ su my_user -c "id"
    Password: # don't want to be prompted!
    uid=500(my_user) gid=500(my_user) groups=500(my_user)
    

To workaround that behaviour of su and runuser, I've changed my init script to something like:

if [[ "$USER" == "my_user" ]]
then
    daemon my_cmd &>/dev/null &
else
    daemon --user=my_user my_cmd &>/dev/null &
fi

Thanks all for your help!

How to resolve this System.IO.FileNotFoundException

I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.

To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:

Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.

Can't find/install libXtst.so.6?

This worked for me in Luna elementary OS

sudo apt-get install libxtst6:i386

Could not instantiate mail function. Why this error occurring

To revisit an old thread, my issue was that one of the "AddressTo" email addresses was not valid. Removing that email address removed the error.

Avoid trailing zeroes in printf()

Here is my first try at an answer:

void
xprintfloat(char *format, float f)
{
  char s[50];
  char *p;

  sprintf(s, format, f);
  for(p=s; *p; ++p)
    if('.' == *p) {
      while(*++p);
      while('0'==*--p) *p = '\0';
    }
  printf("%s", s);
}

Known bugs: Possible buffer overflow depending on format. If "." is present for other reason than %f wrong result might happen.

Using File.listFiles with FileNameExtensionFilter

Is there a specific reason you want to use FileNameExtensionFilter? I know this works..

private File[] getNewTextFiles() {
    return dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".txt");
        }
    });
}

How to choose multiple files using File Upload Control?

The FileUpload.AllowMultiple property in .NET 4.5 and higher will allow you the control to select multiple files.

<asp:FileUpload ID="fileImages" AllowMultiple="true" runat="server" />

.NET 4 and below

 <asp:FileUpload ID="fileImages" Multiple="Multiple" runat="server" />

On the post-back, you can then:

 Dim flImages As HttpFileCollection = Request.Files                   
 For Each key As String In flImages.Keys
    Dim flfile As HttpPostedFile = flImages(key)
    flfile.SaveAs(yourpath & flfile.FileName)
 Next

Multi-character constant warnings

Even if you're willing to look up what behavior your implementation defines, multi-character constants will still vary with endianness.

Better to use a (POD) struct { char[4] }; ... and then use a UDL like "WAVE"_4cc to easily construct instances of that class

Selecting last element in JavaScript array

This worked:

array.reverse()[0]

How do I install g++ for Fedora?

Run the command bellow in a terminal emulator:

sudo dnf install gcc-c++

Enter password and that's it...

Python function to convert seconds into minutes, hours, and days

This will convert n seconds into d days, h hours, m minutes, and s seconds.

from datetime import datetime, timedelta

def GetTime():
    sec = timedelta(seconds=int(input('Enter the number of seconds: ')))
    d = datetime(1,1,1) + sec

    print("DAYS:HOURS:MIN:SEC")
    print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache' http://www.example.com

This curl command servers in its header request to return non-cached data from the web server.

Regex: ignore case sensitivity

You also can lead your initial string, which you are going to check for pattern matching, to lower case. And using in your pattern lower case symbols respectively .

How to reset or change the passphrase for a GitHub SSH key?

Passphrases can be added to an existing key or changed without regenerating the key pair:
Note This will work if keys doesn't had a passphrase, otherwise you'll get this: Enter old passphrase: then Bad passphrase

$ ssh-keygen -p
Enter file in which the key is (/Users/tekkub/.ssh/id_rsa):
Key has comment '/Users/tekkub/.ssh/id_rsa'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.

If your key had passphrase then, There's no way to recover the passphrase for a pair of SSH keys. In that case you have to create a new pair of SSH keys.

  1. Generating SSH keys

Cycles in family tree software

Your family tree should use directed relations. This way you won't have a cycle.

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

If you know what types your stack will be used with, you can instantiate them expicitly in the cpp file, and keep all relevant code there.

It is also possible to export these across DLLs (!) but it's pretty tricky to get the syntax right (MS-specific combinations of __declspec(dllexport) and the export keyword).

We've used that in a math/geom lib that templated double/float, but had quite a lot of code. (I googled around for it at the time, don't have that code today though.)

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

How to write an ArrayList of Strings into a text file?

If you want to serialize the ArrayList object to a file so you can read it back in again later use ObjectOuputStream/ObjectInputStream writeObject()/readObject() since ArrayList implements Serializable. It's not clear to me from your question if you want to do this or just write each individual item. If so then Andrey's answer will do that.

java.lang.Exception: No runnable methods exception in running JUnits

I got this error because I didn't create my own test suite correctly:

Here is how I did it correctly:

Put this in Foobar.java:

public class Foobar{
    public int getfifteen(){
        return 15;
    }
}

Put this in FoobarTest.java:

import static org.junit.Assert.*;
import junit.framework.JUnit4TestAdapter;
import org.junit.Test;
public class FoobarTest {
    @Test
    public void mytest() {
        Foobar f = new Foobar();

        assert(15==f.getfifteen());
    }
    public static junit.framework.Test suite(){
       return new JUnit4TestAdapter(FoobarTest.class);
    }
}

Download junit4-4.8.2.jar I used the one from here:

http://www.java2s.com/Code/Jar/j/Downloadjunit4jar.htm

Compile it:

javac -cp .:./libs/junit4-4.8.2.jar Foobar.java FoobarTest.java

Run it:

el@failbox /home/el $ java -cp .:./libs/* org.junit.runner.JUnitCore FoobarTest
JUnit version 4.8.2
.
Time: 0.009    
OK (1 test)

One test passed.

Why is a ConcurrentModificationException thrown and how to debug it

This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.

Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
   Entry item = it.next();
   map.remove(item.getKey());
}

This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.

The correct approach would be

   Iterator it = map.entrySet().iterator();
   while (it.hasNext())
   {
      Entry item = it.next();
      it.remove();
   }

Assuming this iterator supports the remove() operation.

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

I had similar problems because of .gitignore for the /storage folder on first machine, then cloned repository on second machine and laravel was revision to write down sessions cache

So, manually creating folder /storage/sessions might be an solution..

Get MIME type from filename extension

You can find that information in the registry. For instance, the MIME type for .pdf file can be found in the key HKEY_CLASSES_ROOT\.pdf, in the value "Content Type" :

string mimeType = Registry.GetValue(@"HKEY_CLASSES_ROOT\.pdf", "Content Type", null) as string;

Is JavaScript guaranteed to be single-threaded?

I'd say yes - because virtually all existing (at least all non-trivial) javascript code would break if a browser's javascript engine were to run it asynchronously.

Add to that the fact that HTML5 already specifies Web Workers (an explicit, standardized API for multi-threading javascript code) introducing multi-threading into the basic Javascript would be mostly pointless.

(Note to others commenters: Even though setTimeout/setInterval, HTTP-request onload events (XHR), and UI events (click, focus, etc.) provide a crude impression of multi-threadedness - they are still all executed along a single timeline - one at a time - so even if we don't know their execution order beforehand, there's no need to worry about external conditions changing during the execution of an event handler, timed function or XHR callback.)

git pull while not in a git directory

Edit:

There's either a bug with git pull, or you can't do what you're trying to do with that command. You can however, do it with fetch and merge:

cd /X
git --git-dir=/X/Y/.git fetch
git --git-dir=/X/Y/.git --work-tree=/X/Y merge origin/master

Original answer:

Assuming you're running bash or similar, you can do (cd /X/Y; git pull).

The git man page specifies some variables (see "The git Repository") that seem like they should help, but I can't make them work right (with my repository in /tmp/ggg2):

GIT_WORK_TREE=/tmp/ggg2 GIT_DIR=/tmp/ggg2/.git git pull
fatal: /usr/lib/git-core/git-pull cannot be used without a working tree.

Running the command below while my cwd is /tmp updates that repo, but the updated file appears in /tmp instead of the working tree /tmp/ggg2:

GIT_DIR=/tmp/ggg2/.git git pull

See also this answer to a similar question, which demonstrates the --git-dir and --work-tree flags.

Test if a variable is a list or tuple

On Python 2.8 type(list) is list returns false
I would suggest comparing the type in this horrible way:

if type(a) == type([]) :
  print "variable a is a list"

(well at least on my system, using anaconda on Mac OS X Yosemite)

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

SQL Server CTE and recursion example

Would like to outline a brief semantic parallel to an already correct answer.

In 'simple' terms, a recursive CTE can be semantically defined as the following parts:

1: The CTE query. Also known as ANCHOR.

2: The recursive CTE query on the CTE in (1) with UNION ALL (or UNION or EXCEPT or INTERSECT) so the ultimate result is accordingly returned.

3: The corner/termination condition. Which is by default when there are no more rows/tuples returned by the recursive query.

A short example that will make the picture clear:

;WITH SupplierChain_CTE(supplier_id, supplier_name, supplies_to, level)
AS
(
SELECT S.supplier_id, S.supplier_name, S.supplies_to, 0 as level
FROM Supplier S
WHERE supplies_to = -1    -- Return the roots where a supplier supplies to no other supplier directly

UNION ALL

-- The recursive CTE query on the SupplierChain_CTE
SELECT S.supplier_id, S.supplier_name, S.supplies_to, level + 1
FROM Supplier S
INNER JOIN SupplierChain_CTE SC
ON S.supplies_to = SC.supplier_id
)
-- Use the CTE to get all suppliers in a supply chain with levels
SELECT * FROM SupplierChain_CTE

Explanation: The first CTE query returns the base suppliers (like leaves) who do not supply to any other supplier directly (-1)

The recursive query in the first iteration gets all the suppliers who supply to the suppliers returned by the ANCHOR. This process continues till the condition returns tuples.

UNION ALL returns all the tuples over the total recursive calls.

Another good example can be found here.

PS: For a recursive CTE to work, the relations must have a hierarchical (recursive) condition to work on. Ex: elementId = elementParentId.. you get the point.

How do I launch a program from command line without opening a new cmd window?

1-Open you folder that contains your application in the File Explorer. 2-Press SHIFT and Right Click in White Space. 3-Click on "Open command window here". 4-Run your application. (you can type some of the first characters of application name and press Up Arrow Key OR Down Arrow Key)

Getting full JS autocompletion under Sublime Text

There are three approaches

  • Use SublimeCodeIntel plug-in

  • Use CTags plug-in

  • Generate .sublime-completion file manually

Approaches are described in detail in this blog post (of mine): http://opensourcehacker.com/2013/03/04/javascript-autocompletions-and-having-one-for-sublime-text-2/

How to calculate UILabel height dynamically?

To make UILabel fit the dynamic content you can use lines property in property inspector and set that as 0.

And you don't require to do any coding for this.

For more details you can check below demonstration video

https://www.youtube.com/watch?v=rVeDS_OGslU

Django - limiting query results

Looks like the solution in the question doesn't work with Django 1.7 anymore and raises an error: "Cannot reorder a query once a slice has been taken"

According to the documentation https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets forcing the “step” parameter of Python slice syntax evaluates the Query. It works this way:

Model.objects.all().order_by('-id')[:10:1]

Still I wonder if the limit is executed in SQL or Python slices the whole result array returned. There is no good to retrieve huge lists to application memory.

WooCommerce - get category for product page

I literally striped out this line of code from content-single-popup.php located in woocommerce folder in my theme directory.

global $product; 
echo $product->get_categories( ', ', ' ' . _n( ' ', '  ', $cat_count, 'woocommerce' ) . ' ', ' ' );

Since my theme that I am working on has integrated woocommerce in it, this was my solution.

adding line break

C# 6+

In addition, since c#6 you can also use a static using statement for System.Environment.

So instead of Environment.NewLine, you can just write NewLine.

Concise and much easier on the eye, particularly when there are multiple instances ...

using static System.Environment;
   
FirmNames = "";
foreach (var item in FirmNameList)
{
    if (FirmNames != "")
    {
       FirmNames += ", " + NewLine;
    }
    FirmNames += item;
}

jQuery - Disable Form Fields

$('input, select').attr('disabled', 'disabled');

How to center-justify the last line of text in CSS?

its working with this code

text-align: justify; text-align-last: center;

Using BeautifulSoup to search HTML for string

text='Python' searches for elements that have the exact text you provided:

import re
from BeautifulSoup import BeautifulSoup

html = """<p>exact text</p>
   <p>almost exact text</p>"""
soup = BeautifulSoup(html)
print soup(text='exact text')
print soup(text=re.compile('exact text'))

Output

[u'exact text']
[u'exact text', u'almost exact text']

"To see if the string 'Python' is located on the page http://python.org":

import urllib2
html = urllib2.urlopen('http://python.org').read()
print 'Python' in html # -> True

If you need to find a position of substring within a string you could do html.find('Python').

Determine if JavaScript value is an "integer"?

Use jQuery's IsNumeric method.

http://api.jquery.com/jQuery.isNumeric/

if ($.isNumeric(id)) {
   //it's numeric
}

CORRECTION: that would not ensure an integer. This would:

if ( (id+"").match(/^\d+$/) ) {
   //it's all digits
}

That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works

WPF checkbox binding

Hello this is my first time posting so please be patient: my answer was to create a simple property:

public bool Checked { get; set; }

Then to set the data context of the Checkbox (called cb1):

cb1.DataContext = this;

Then to bind the IsChecked proerty of it in the xaml

IsChecked="{Binding Checked}"

The code is like this:

XAML

<CheckBox x:Name="cb1"
          HorizontalAlignment="Left"
          Margin="439,81,0,0"
          VerticalAlignment="Top"
          Height="35" Width="96"
          IsChecked="{Binding Checked}"/>

Code behind

public partial class MainWindow : Window
{
    public bool Checked { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        cb1.DataContext = this;
    }

    private void myyButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(Checked.ToString());
    }
}

Pie chart with jQuery

Flot

Limitations: lines, points, filled areas, bars, pie and combinations of these

From an interaction perspective, Flot by far will get you as close as possible to Flash graphing as you can get with jQuery. Whilst the graph output is pretty slick, and great looking, you can also interact with data points. What I mean by this is you can have the ability to hover over a data point and get visual feedback on the value of that point in the graph.

The trunk version of flot supports pie charts.

Flot Zoom capability.

On top of this, you also have the ability to select a chunk of the graph to get data back for a particular “zone”. As a secondary feature to this “zoning”, you can also select an area on a graph and zoom in to see the data points a little more closely. Very cool.


Sparklines

Limitations: Pie, Line, Bar, Combination

Sparklines is my favourite mini graphing tool out there. Really great for dashboard style graphs (think Google Analytics dashboard next time you login). Because they’re so tiny, they can be included in line (as in the example above). Another nice idea which can be used in all graphing plugins is the self-refresh capabilities. Their Mouse-Speed demo shows you the power of live charting at its best.


Query Chart 0.21

Limitations: Area, Line, Bar and combinations of these

jQuery Chart 0.21 isn’t the nicest looking charting plugin out there it has to be said. It’s pretty basic in functionality when it comes to the charts it can handle, however it can be flexible if you can put in some time and effort into it.

Adding values into a chart is relatively simple:

.chartAdd({

    "label"  : "Leads",
    "type"   : "Line",
    "color"  : "#008800",
    "values" : ["100","124","222","44","123","23","99"]
});

jQchart

Limitations: Bar, Line

jQchart is an odd one, they’ve built in animation transistions and drag/drop functionality into the chart, however it’s a little clunky – and seemingly pointless. It does generate nice looking charts if you get the CSS setup right, but there are better out there.


TufteGraph

Limitations: Bar and Stacked Bar

Tuftegraph sells itself as “pretty bar graphs that you would show your mother”. It comes close, Flot is prettier, but Tufte does lend itself to be very lightweight. Although with that comes restrictions – there are few options to choose from, so you get what you’re given. Check it out for a quick win bar chart.

PHP, MySQL error: Column count doesn't match value count at row 1

The number of column parameters in your insert query is 9, but you've only provided 8 values.

INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

The query should omit the "id" parameter, because it is auto-generated (or should be anyway):

INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

Does Python have an ordered set?

In case you're already using pandas in your code, its Index object behaves pretty like an ordered set, as shown in this article.

Examples from the article:

indA = pd.Index([1, 3, 5, 7, 9])
indB = pd.Index([2, 3, 5, 7, 11])

indA & indB  # intersection
indA | indB  # union
indA - indB  # difference
indA ^ indB  # symmetric difference

Trigger standard HTML5 validation (form) without using submit button?

You have to submit the form to get the html5 validation to work. There's a way around it to get what you want. Se the code:

<body>
    <h1>Validation Example</h1><br />
    <h2>Insert just 1 digit<h2>
    <form id="form" onsubmit="return false">
        <label>Input<input type="text" pattern="[0-9]" id="input" /></label> 
        <input type="submit" class="hide" id="inputButton">         
    </form>
</body>

See an example here

Note: using form.submit() didn't work for me. So i created a hidden submit button, that triggers on keyup. Don't ask me why. Maybe someone could clarify it.

Killing a process created with Python's subprocess.Popen()

process.terminate() doesn't work when using shell=True. This answer will help you.

Printing variables in Python 3.4

You can also format the string like so:

>>> print ("{index}. {word} appears {count} times".format(index=1, word='Hello', count=42))

Which outputs

1. Hello appears 42 times.

Because the values are named, their order does not matter. Making the example below output the same as the above example.

>>> print ("{index}. {word} appears {count} times".format(count=42, index=1, word='Hello'))

Formatting string this way allows you to do this.

>>> data = {'count':42, 'index':1, 'word':'Hello'}
>>> print ("{index}. {word} appears {count} times.".format(**data))
1. Hello appears 42 times.

How to change the Text color of Menu item in Android?

Simply just go to Values - styles and inside styles and type your color

View a file in a different Git branch without changing branches

If you're using Emacs, you can type C-x v ~ to see a different revision of the file you're currently editing (tags, branches and hashes all work).

Integer value comparison

Integers are autounboxed, so you can just do

if (count > 0) {
    .... 
}

How to convert array to a string using methods other than JSON?

You are looking for serialize(). Here is an example:

$array = array('foo', 'bar');

//Array to String
$string = serialize($array);

//String to array
$array = unserialize($string);

Confirm deletion using Bootstrap 3 modal box

You can use Bootbox dialog boxes

$(document).ready(function() {

  $('#btnDelete').click(function() {
    bootbox.confirm("Are you sure want to delete?", function(result) {
      alert("Confirm result: " + result);
    });
  });
});

Plunker Demo

What is the best way to paginate results in SQL Server

You didn't specify the language nor which driver you are using. Therefore I'm describing it abstractly.

  • Create a scrollable resultset / dataset. This required a primary on the table(s)
  • jump to the end
  • request the row count
  • jump to the start of the page
  • scroll through the rows until the end of the page

add controls vertically instead of horizontally using flow layout

As I stated in comment i would use a box layout for this.

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout());

JButton button = new JButton("Button1");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);

button = new JButton("Button2");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);

button = new JButton("Button3");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);

add(panel);

How to generate keyboard events?

    def keyboardevent():
         keyboard.press_and_release('a')
         keyboard.press_and_release('shift + b')
         
    keyboardevent()

How to replace multiple patterns at once with sed?

Here is an awk based on oogas sed

echo 'abbc' | awk '{gsub(/ab/,"xy");gsub(/bc/,"ab");gsub(/xy/,"bc")}1'
bcab

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

If you are just testing your PL/SQL in SQL Plus you can direct it to a file like this:

spool output.txt
set serveroutput on

begin
  SELECT systimestamp FROM dual INTO time_db;
  DBMS_OUTPUT.PUT_LINE('time before procedure ' || time_db);
end;
/

spool off

IDEs like Toad and SQL Developer can capture the output in other ways, but I'm not familiar with how.

Spring Boot - inject map from application.yml

Solution for pulling Map using @Value from application.yml property coded as multiline

application.yml

other-prop: just for demo 

my-map-property-name: "{\
         key1: \"ANY String Value here\", \  
         key2: \"any number of items\" , \ 
         key3: \"Note the Last item does not have comma\" \
         }"

other-prop2: just for demo 2 

Here the value for our map property "my-map-property-name" is stored in JSON format inside a string and we have achived multiline using \ at end of line

myJavaClass.java

import org.springframework.beans.factory.annotation.Value;

public class myJavaClass {

@Value("#{${my-map-property-name}}") 
private Map<String,String> myMap;

public void someRandomMethod (){
    if(myMap.containsKey("key1")) {
            //todo...
    } }

}

More explanation

  • \ in yaml it is Used to break string into multiline

  • \" is escape charater for "(quote) in yaml string

  • {key:value} JSON in yaml which will be converted to Map by @Value

  • #{ } it is SpEL expresion and can be used in @Value to convert json int Map or Array / list Reference

Tested in a spring boot project

Accept server's self-signed ssl certificate in Java client

I had the issue that I was passing a URL into a library which was calling url.openConnection(); I adapted jon-daniel's answer,

public class TrustHostUrlStreamHandler extends URLStreamHandler {

    private static final Logger LOG = LoggerFactory.getLogger(TrustHostUrlStreamHandler.class);

    @Override
    protected URLConnection openConnection(final URL url) throws IOException {

        final URLConnection urlConnection = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).openConnection();

        // adapated from
        // https://stackoverflow.com/questions/2893819/accept-servers-self-signed-ssl-certificate-in-java-client
        if (urlConnection instanceof HttpsURLConnection) {
            final HttpsURLConnection conHttps = (HttpsURLConnection) urlConnection;

            try {
                // Set up a Trust all manager
                final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
                    }

                    @Override
                    public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
                    }
                } };

                // Get a new SSL context
                final SSLContext sc = SSLContext.getInstance("TLSv1.2");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                // Set our connection to use this SSL context, with the "Trust all" manager in place.
                conHttps.setSSLSocketFactory(sc.getSocketFactory());
                // Also force it to trust all hosts
                final HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(final String hostname, final SSLSession session) {
                        return true;
                    }
                };

                // and set the hostname verifier.
                conHttps.setHostnameVerifier(allHostsValid);

            } catch (final NoSuchAlgorithmException e) {
                LOG.warn("Failed to override URLConnection.", e);
            } catch (final KeyManagementException e) {
                LOG.warn("Failed to override URLConnection.", e);
            }

        } else {
            LOG.warn("Failed to override URLConnection. Incorrect type: {}", urlConnection.getClass().getName());
        }

        return urlConnection;
    }

}

Using this class it is possible to create a new URL with:

trustedUrl = new URL(new URL(originalUrl), "", new TrustHostUrlStreamHandler());
trustedUrl.openConnection();

This has the advantage that it is localized and not replacing the default URL.openConnection.

How do I enumerate through a JObject?

The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.

This is the answer that worked for me:

foreach (var x in jobj)
{
    var key = ((JProperty) (x)).Name;
    var jvalue = ((JProperty)(x)).Value ;
}

Download all stock symbol list of a market

You can download a list of symbols from here. You have an option to download the whole list directly into excel file. You will have to register though.

What is the best way to modify a list in a 'foreach' loop?

I have written one easy step, but because of this performance will be degraded

Here is my code snippet:-

for (int tempReg = 0; tempReg < reg.Matches(lines).Count; tempReg++)
                            {
                                foreach (Match match in reg.Matches(lines))
                                {
                                    var aStringBuilder = new StringBuilder(lines);
                                    aStringBuilder.Insert(startIndex, match.ToString().Replace(",", " ");
                                    lines[k] = aStringBuilder.ToString();
                                    tempReg = 0;
                                    break;
                                }
                            }

How do I print a double value without scientific notation using Java?

This will work as long as your number is a whole number:

double dnexp = 12345678;
System.out.println("dexp: " + (long)dexp);

If the double variable has precision after the decimal point it will truncate it.

how to remove untracked files in Git?

Those are untracked files. This means git isn't tracking them. It's only listing them because they're not in the git ignore file. Since they're not being tracked by git, git reset won't touch them.

If you want to blow away all untracked files, the simplest way is git clean -f (use git clean -n instead if you want to see what it would destroy without actually deleting anything). Otherwise, you can just delete the files you don't want by hand.

Why is printing "B" dramatically slower than printing "#"?

Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # = 6.03 seconds
  2. Second Matrix: O and B = 50.97 seconds

Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B");
        }
        if(j%100==0){               //Adding a line break in second loop      
            System.out.println();
        }                    
    }
    System.out.println("");                
}

Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings

SQL: Alias Column Name for Use in CASE Statement

I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.

With localView1 as (
 select c1,
        c2,
        c3,
        c4,
        ((c2-c4)*(3))+c1 as "complex"
   from realTable1) 
   , localView2 as (
 select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
        complex * complex as formula2    
   from localView1)
select *
from localView2

Put Excel-VBA code in module or sheet?

Definitely in Modules.

  • Sheets can be deleted, copied and moved with surprising results.
  • You can't call code in sheet "code-behind" from other modules without fully qualifying the reference. This will lead to coupling of the sheet and the code in other modules/sheets.
  • Modules can be exported and imported into other workbooks, and put under version control
  • Code in split logically into modules (data access, utilities, spreadsheet formatting etc.) can be reused as units, and are easier to manage if your macros get large.

Since the tooling is so poor in primitive systems such as Excel VBA, best practices, obsessive code hygiene and religious following of conventions are important, especially if you're trying to do anything remotely complex with it.

This article explains the intended usages of different types of code containers. It doesn't qualify why these distinctions should be made, but I believe most developers trying to develop serious applications on the Excel platform follow them.

There's also a list of VBA coding conventions I've found helpful, although they're not directly related to Excel VBA. Please ignore the crazy naming conventions they have on that site, it's all crazy hungarian.

Saving an image in OpenCV

I had the same problem on Windows Vista, I just added this code before cvQueryFrame:

cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 720);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 480);

Auto margins don't center image in page

add display:block; and it'll work. Images are inline by default

To clarify, the default width for a block element is auto, which of course fills the entire available width of the containing element.

By setting the margin to auto, the browser assigns half the remaining space to margin-left and the other half to margin-right.

How to multiply all integers inside list

The most pythonic way would be to use a list comprehension:

l = [2*x for x in l]

If you need to do this for a large number of integers, use numpy arrays:

l = numpy.array(l, dtype=int)*2

A final alternative is to use map

l = list(map(lambda x:2*x, l))

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

This tutorial is very useful. To give a quick summary:

  1. Use the CORS package available on Nuget: Install-Package Microsoft.AspNet.WebApi.Cors

  2. In your WebApiConfig.cs file, add config.EnableCors() to the Register() method.

  3. Add an attribute to the controllers you need to handle cors:

[EnableCors(origins: "<origin address in here>", headers: "*", methods: "*")]

What is stability in sorting algorithms and why is it important?

Some more examples of the reason for wanting stable sorts. Databases are a common example. Take the case of a transaction data base than includes last|first name, date|time of purchase, item number, price. Say the data base is normally sorted by date|time. Then a query is made to make a sorted copy of the data base by last|first name, since a stable sort preserves the original order, even though the inquiry compare only involves last|first name, the transactions for each last|first name will be in data|time order.

A similar example is classic Excel, which limited sorts to 3 columns at a time. To sort 6 columns, a sort is done with the least significant 3 columns, followed by a sort with the most significant 3 columns.

A classic example of a stable radix sort is a card sorter, used to sort by a field of base 10 numeric columns. The cards are sorted from least significant digit to most significant digit. On each pass, a deck of cards is read and separated into 10 different bins according to the digit in that column. Then the 10 bins of cards are put back into the input hopper in order ("0" cards first, "9" cards last). Then another pass is done by the next column, until all columns are sorted. Actual card sorters have more than 10 bins since there are 12 zones on a card, a column can be blank, and there is a mis-read bin. To sort letters, 2 passes per column are needed, 1st pass for digit, 2nd pass for the 12 11 zone.

Later (1937) there were card collating (merging) machines that could merge two decks of cards by comparing fields. The input was two already sorted decks of cards, a master deck and an update deck. The collator merged the two decks into a a new mater bin and an archive bin, which was optionally used for master duplicates so that the new master bin would only have update cards in case of duplicates. This was probably the basis for the idea behind the original (bottom up) merge sort.

Is there a way to know your current username in mysql?

to print the current user who is using the database

select user();

or

select current_user();

What are the applications of binary trees?

The main application is binary search trees. These are a data structure in which searching, insertion, and removal are all very fast (about log(n) operations)

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

Reassigning the path Xcode is configured with worked for me.

sudo xcode-select -switch /Applications/Xcode.app

You'll then likely be prompted (after trying a command) to agree to the license agreement.

Aligning a button to the center

Add width:100px, margin:50%. Now the left side of the button is set to the center.
Finally add half of the width of the button in our case 50px.
The middle of the button is in the center.

<input type='submit' style='width:100px;margin:0 50%;position:relative;left:-50px;'>

Import Maven dependencies in IntelliJ IDEA

Open IntelliJ Idea, Go to File > Other Settings > Default Settings... > Maven (Preferences) > Importing or| Preferences > Maven > Importing

enter image description here

Click on Enable Auto-import in the console.

enter image description here

How to check if a date is greater than another in Java?

You need to use a SimpleDateFormat (dd-MM-yyyy will be the format) to parse the 2 input strings to Date objects and then use the Date#before(otherDate) (or) Date#after(otherDate) to compare them.

Try to implement the code yourself.

Calculate difference between two datetimes in MySQL

If your start and end datetimes are on different days use TIMEDIFF.

SELECT TIMEDIFF(datetime1,datetime2)

if datetime1 > datetime2 then

SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")

gives: 24:01:00

and datetime1 < datetime2

SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")

gives: -24:01:00

How to Solve Max Connection Pool Error

Here's what u can also try....

run your application....while it is still running launch your command prompt

while your application is running type netstat -n on the command prompt. You should see a list of TCP/IP connections. Check if your list is not very long. Ideally you should have less than 5 connections in the list. Check the status of the connections.
If you have too many connections with a TIME_WAIT status it means the connection has been closed and is waiting for the OS to release the resources. If you are running on Windows, the default ephemeral port rang is between 1024 and 5000 and the default time it takes Windows to release the resource from TIME_WAIT status is 4 minutes. So if your application used more then 3976 connections in less then 4 minutes, you will get the exception you got.

Suggestions to fix it:

  1. Add a connection pool to your connection string.

If you continue to receive the same error message (which is highly unlikely) you can then try the following: (Please don't do it if you are not familiar with the Windows registry)

  1. Run regedit from your run command. In the registry editor look for this registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters:

Modify the settings so they read:

MaxUserPort = dword:00004e20 (10,000 decimal) TcpTimedWaitDelay = dword:0000001e (30 decimal)

This will increase the number of ports to 10,000 and reduce the time to release freed tcp/ip connections.

Only use suggestion 2 if 1 fails.

Thank you.

Indexes of all occurrences of character in a string

Also, if u want to find all indexes of a String in a String.

int index = word.indexOf(guess);
while (index >= 0) {
    System.out.println(index);
    index = word.indexOf(guess, index + guess.length());
}

How to fix 'sudo: no tty present and no askpass program specified' error?

I was getting this error because I had limited my user to only a single executable 'systemctl' and had misconfigured the visudo file.

Here's what I had:

jenkins ALL=NOPASSWD: systemctl

However, you need to include the full path to the executable, even if it is on your path by default, for example:

jenkins ALL=NOPASSWD: /bin/systemctl

This allows my jenkins user to restart services but not have full root access

How can I see CakePHP's SQL dump in the controller?

for cakephp 2.0 Write this function in AppModel.php

function getLastQuery()
{
    $dbo = $this->getDatasource();
    $logs = $dbo->getLog();
    $lastLog = end($logs['log']);
    return $lastLog['query'];
}

To use this in Controller Write : echo $this->YourModelName->getLastQuery();

How to convert a private key to an RSA private key?

Newer versions of OpenSSL say BEGIN PRIVATE KEY because they contain the private key + an OID that identifies the key type (this is known as PKCS8 format). To get the old style key (known as either PKCS1 or traditional OpenSSL format) you can do this:

openssl rsa -in server.key -out server_new.key

Alternately, if you have a PKCS1 key and want PKCS8:

openssl pkcs8 -topk8 -nocrypt -in privkey.pem

Visual Studio Code Tab Key does not insert a tab

Try CTR + M it will work like before.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

For me the cause of the issue was that the format of username was incorrect. It was earlierly specified as "mydomain\user". I removed the domain part and the error was gone.

PS I was using ServerBind authentication.

How to set a parameter in a HttpServletRequest?

You can't, not using the standard API. HttpServletRequest represent a request received by the server, and so adding new parameters is not a valid option (as far as the API is concerned).

You could in principle implement a subclass of HttpServletRequestWrapper which wraps the original request, and intercepts the getParameter() methods, and pass the wrapped request on when you forward.

If you go this route, you should use a Filter to replace your HttpServletRequest with a HttpServletRequestWrapper:

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    if (servletRequest instanceof HttpServletRequest) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // Check wether the current request needs to be able to support the body to be read multiple times
        if (MULTI_READ_HTTP_METHODS.contains(request.getMethod())) {
            // Override current HttpServletRequest with custom implementation
            filterChain.doFilter(new HttpServletRequestWrapper(request), servletResponse);
            return;
        }
    }
    filterChain.doFilter(servletRequest, servletResponse);
}

Max tcp/ip connections on Windows Server 2008

There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:

It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.

Is there a command for formatting HTML in the Atom editor?

Atom does not have a built-in command for formatting html. However, you can install the atom-beautify package to get this behavior.

  1. Press CTRL + SHFT + P to bring up the command palette (CMD + SHFT + P on a Mac).
  2. Type Install Packages to bring up the package manager.
  3. Type beautify into the search box.
  4. Choose atom-beautify or one of the other packages and click Install.
  5. Now you can use the default keybinding for atom-beautify CTRL + ALT + B to beautify your HTML (CTRL + OPTION + B on a Mac).

How to scale a BufferedImage

AffineTransformOp offers the additional flexibility of choosing the interpolation type.

BufferedImage before = getBufferedImage(encoded);
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0);
AffineTransformOp scaleOp = 
   new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);

The fragment shown illustrates resampling, not cropping; this related answer addresses the issue; some related examples are examined here.

MongoDB: update every document on one field

Regardless of the version, for your example, the <update> is:

{  $set: { lastLookedAt: Date.now() / 1000 }  }

However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB client:

$version >= 3.2:

db.foo.updateMany( {}, <update> )
  • {} is the condition (the empty condition matches any document)

3.2 > $version >= 2.2:

db.foo.update( {}, <update>, { multi: true } )
  • {} is the condition (the empty condition matches any document)
  • {multi: true} is the "update multiple documents" option

$version < 2.2:

db.foo.update( {}, <update>, false, true )
  • {} is the condition (the empty condition matches any document)
  • false is for the "upsert" parameter
  • true is for the "multi" parameter (update multiple records)

Undoing a git rebase

Resetting the branch to the dangling commit object of its old tip is of course the best solution, because it restores the previous state without expending any effort. But if you happen to have lost those commits (f.ex. because you garbage-collected your repository in the meantime, or this is a fresh clone), you can always rebase the branch again. The key to this is the --onto switch.

Let’s say you had a topic branch imaginatively called topic, that you branched off master when the tip of master was the 0deadbeef commit. At some point while on the topic branch, you did git rebase master. Now you want to undo this. Here’s how:

git rebase --onto 0deadbeef master topic

This will take all commits on topic that aren’t on master and replay them on top of 0deadbeef.

With --onto, you can rearrange your history into pretty much any shape whatsoever.

Have fun. :-)

Setting up a JavaScript variable from Spring model by using Thymeleaf

var message =/*[[${message}]]*/ 'defaultanyvalue';

Add two textbox values and display the sum in a third textbox automatically

Try this: Open given fiddle in CHROME

function sum() {
      var txtFirstNumberValue = document.getElementById('txt1').value;
      var txtSecondNumberValue = document.getElementById('txt2').value;
      var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
      if (!isNaN(result)) {
         document.getElementById('txt3').value = result;
      }
}

HTML

<input type="text" id="txt1"  onkeyup="sum();" />
<input type="text" id="txt2"  onkeyup="sum();" />
<input type="text" id="txt3" />

DEMO HERE

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

Use RSA private key to generate public key?

People looking for SSH public key...

If you're looking to extract the public key for use with OpenSSH, you will need to get the public key a bit differently

$ ssh-keygen -y -f mykey.pem > mykey.pub

This public key format is compatible with OpenSSH. Append the public key to remote:~/.ssh/authorized_keys and you'll be good to go


docs from SSH-KEYGEN(1)

ssh-keygen -y [-f input_keyfile]  

-y This option will read a private OpenSSH format file and print an OpenSSH public key to stdout.

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

What Java ORM do you prefer, and why?

Hibernate, because it's basically the defacto standard in Java and was one of the driving forces in the creation of the JPA. It's got excellent support in Spring, and almost every Java framework supports it. Finally, GORM is a really cool wrapper around it doing dynamic finders and so on using Groovy.

It's even been ported to .NET (NHibernate) so you can use it there too.

Angular redirect to login page

1. Create a guard as seen below. 2. Install ngx-cookie-service to get cookies returned by external SSO. 3. Create ssoPath in environment.ts (SSO Login redirection). 4. Get the state.url and use encodeURIComponent.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from 
  '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { environment } from '../../../environments/environment.prod';

@Injectable()
export class AuthGuardService implements CanActivate {
  private returnUrl: string;
  constructor(private _router: Router, private cookie: CookieService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.cookie.get('MasterSignOn')) {
      return true;
    } else {
      let uri = window.location.origin + '/#' + state.url;
      this.returnUrl = encodeURIComponent(uri);      
      window.location.href = environment.ssoPath +  this.returnUrl ;   
      return false;      
    }
  }
}

How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

How to find out what character key is pressed?

"Clear" JavaScript:

_x000D_
_x000D_
function myKeyPress(e){
  var keynum;

  if(window.event) { // IE                  
    keynum = e.keyCode;
  } else if(e.which){ // Netscape/Firefox/Opera                 
    keynum = e.which;
  }

  alert(String.fromCharCode(keynum));
}
_x000D_
<input type="text" onkeypress="return myKeyPress(event)" />
_x000D_
_x000D_
_x000D_

JQuery:

_x000D_
_x000D_
$("input").keypress(function(event){
  alert(String.fromCharCode(event.which)); 
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
_x000D_
_x000D_
_x000D_

Python extract pattern matches

It seems like you're actually trying to extract a name vice simply find a match. If this is the case, having span indexes for your match is helpful and I'd recommend using re.finditer. As a shortcut, you know the name part of your regex is length 5 and the is valid is length 9, so you can slice the matching text to extract the name.

Note - In your example, it looks like s is string with line breaks, so that's what's assumed below.

## covert s to list of strings separated by line:
s2 = s.splitlines()

## find matches by line: 
for i, j in enumerate(s2):
    matches = re.finditer("name (.*) is valid", j)
    ## ignore lines without a match
    if matches:
        ## loop through match group elements
        for k in matches:
            ## get text
            match_txt = k.group(0)
            ## get line span
            match_span = k.span(0)
            ## extract username
            my_user_name = match_txt[5:-9]
            ## compare with original text
            print(f'Extracted Username: {my_user_name} - found on line {i}')
            print('Match Text:', match_txt)

How to set editable true/false EditText in Android programmatically?

Once focus of edit text is removed, it would not allow you to type even if you set it to focusable again.

Here is a way around it

if (someCondition)
   editTextField.setFocusable(false);
else
   editTextField.setFocusableInTouchMode(true);

Setting it true in setFocusableInTouchMode() seems to do the trick.

How do I run Google Chrome as root?

Chrome can run as root (remember to use gksu when doing so) so long as you provide it with a profile directory.

Rather than type in the profile directory every time you want to run it, create a new bash file (I'd name it something like start-chrome.sh)

#/bin/bash
google-chrome --user-data-dir="/root/chrome-profile/"

Rember to call that script with root privelages!

$ gksu /root/start-chrome.sh

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

Remove stubborn underline from link

set text-decoration: none; for anchor tag.

Example html.

<body>
    <ul class="nav-tabs">
        <li><a href="#"><i class="fas fa-th"></i>Business</a></li>
        <li><a href="#"><i class="fas fa-th"></i>Expertise</a></li>
        <li><a href="#"><i class="fas fa-th"></i>Quality</a></li>
    </ul>
</body>

Example CSS:

.nav-tabs li a{
  text-decoration: none;
}

Executing Javascript code "on the spot" in Chrome?

If you mean you want to execute the function inputted, yes, that is simple:

Use this JS code:

eval(document.getElementById( -- el ID -- ).value);

Copy mysql database from remote server to local computer

Copy mysql database from remote server to local computer

I ran into the same problem. And I could not get it done with the other answers. So here is how I finally did it (yes, a beginner tutorial):

Step 1: Create a new database in your local phpmyadmin.

Step 2: Dump the database on the remote server into a sql file (here I used Putty/SSH):

mysqldump --host="mysql5.domain.com" --user="db231231" --password="DBPASSWORD" databasename > dbdump.sql

Step 3: Download the dbdump.sql file via FTP client (should be located in the root folder)

Step 4: Move the sql file to the folder of your localhost installation, where mysql.exe is located. I am using uniform-server, this would be at C:\uniserver\core\mysql\bin\, with XAMPP it would be C:\xampp\mysql\bin

Step 5: Execute the mysql.exe as follows:

 mysql.exe -u root -pYOURPASSWORD YOURLOCALDBNAME < dbdump.sql

Step 6: Wait... depending on the file size. You can check the progress in phpmyadmin, seeing newly created tables.

Step 7: Done. Go to your local phpmyadmin to check if the database has been filled with the entire data.

Hope that helps. Good luck!


Note 1: When starting the uniformer-server you can specify a password for mysql. This is the one you have to use above for YOURPASSWORD.

Note 2: If the login does not work and you run into password problems, check your password if it contains special characters like !. If so, then you probably need to escape them \!.

Note 3: In case not all mysql data can be found in the local db after the import, it could be that there is a problem with the mysql directives of your dbdump.sql

Converting HTML element to string in JavaScript / JQuery

You can do this:

_x000D_
_x000D_
var $html = $('<iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>');    _x000D_
var str = $html.prop('outerHTML');_x000D_
console.log(str);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

FIDDLE DEMO

Regex for quoted string with escaping quotes

/"(?:[^"\\]|\\.)*"/

Works in The Regex Coach and PCRE Workbench.

Example of test in JavaScript:

_x000D_
_x000D_
    var s = ' function(){ return " Is big \\"problem\\", \\no? "; }';_x000D_
    var m = s.match(/"(?:[^"\\]|\\.)*"/);_x000D_
    if (m != null)_x000D_
        alert(m);
_x000D_
_x000D_
_x000D_

PHP multidimensional array search by value

Try this

<?php
 function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && 
            recursive_array_search($needle,$value) !== false)) {
             return $current_key;
        }
    }
    return false;
 }
 ?>

TypeError: Object of type 'bytes' is not JSON serializable

You are creating those bytes objects yourself:

item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)

Each of those t.encode(), l.encode() and d.encode() calls creates a bytes string. Do not do this, leave it to the JSON format to serialise these.

Next, you are making several other errors; you are encoding too much where there is no need to. Leave it to the json module and the standard file object returned by the open() call to handle encoding.

You also don't need to convert your items list to a dictionary; it'll already be an object that can be JSON encoded directly:

class W3SchoolPipeline(object):    
    def __init__(self):
        self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(item) + '\n'
        self.file.write(line)
        return item

I'm guessing you followed a tutorial that assumed Python 2, you are using Python 3 instead. I strongly suggest you find a different tutorial; not only is it written for an outdated version of Python, if it is advocating line.decode('unicode_escape') it is teaching some extremely bad habits that'll lead to hard-to-track bugs. I can recommend you look at Think Python, 2nd edition for a good, free, book on learning Python 3.

How to convert a python numpy array to an RGB image with Opencv 2.4?

This is due to the fact that cv2 uses the type "uint8" from numpy. Therefore, you should define the type when creating the array.

Something like the following:

import numpy
import cv2

b = numpy.zeros([5,5,3], dtype=numpy.uint8)
b[:,:,0] = numpy.ones([5,5])*64
b[:,:,1] = numpy.ones([5,5])*128
b[:,:,2] = numpy.ones([5,5])*192

How do I subtract minutes from a date in javascript?

Everything is just ticks, no need to memorize methods...

var aMinuteAgo = new Date( Date.now() - 1000 * 60 );

or

var aMinuteLess = new Date( someDate.getTime() - 1000 * 60 );

update

After working with momentjs, I have to say this is an amazing library you should check out. It is true that ticks work in many cases making your code very tiny and you should try to make your code as small as possible for what you need to do. But for anything complicated, use momentjs.

How can I insert data into Database Laravel?

make sure you use the POST to insert the data. Actually you were using GET.

open read and close a file in 1 line of code

with open('pagehead.section.htm')as f:contents=f.read()

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['AllowNoPassword'] = false;

Checking if type == list in python

Python 3.7.7

import typing
if isinstance([1, 2, 3, 4, 5] , typing.List):
    print("It is a list")

Looking for a short & simple example of getters/setters in C#

Most languages do it this way, and you can do it in C# too.

    public void setRAM(int RAM)
    {
        this.RAM = RAM;
    }
    public int getRAM()
    {
        return this.RAM;
    }

But C# also gives a more elegant solution to this :

    public class Computer
    {
        int ram;
        public int RAM 
        { 
             get 
             {
                  return ram;
             }
             set 
             {
                  ram = value; // value is a reserved word and it is a variable that holds the input that is given to ram ( like in the example below )
             }
        }
     }

And later access it with.

    Computer comp = new Computer();
    comp.RAM = 1024;
    int var = comp.RAM;

For newer versions of C# it's even better :

public class Computer
{
    public int RAM { get; set; }
}

and later :

Computer comp = new Computer();
comp.RAM = 1024;
int var = comp.RAM;

How do I get a list of files in a directory in C++?

Solving this will require a platform specific solution. Look for opendir() on unix/linux or FindFirstFile() on Windows. Or, there are many libraries that will handle the platform specific part for you.

Chrome, Javascript, window.open in new tab

It is sometimes useful to force the use of a tab, if the user likes that. As Prakash stated above, this is sometimes dictated by the use of a non-user-initiated event, but there are ways around that.

For example:

$("#theButton").button().click( function(event) {
   $.post( url, data )
   .always( function( response ) {
      window.open( newurl + response, '_blank' );
   } );
} );

will always open "newurl" in a new browser window since the "always" function is not considered user-initiated. However, if we do this:

$("#theButton").button().click( function(event) {
   var newtab = window.open( '', '_blank' );
   $.post( url, data )
   .always( function( response ) {
      newtab.location = newurl + response;
   } );
} );

we open the new browser window or create the new tab, as determined by the user preference in the button click which IS user-initiated. Then we just set the location to the desired URL after returning from the AJAX post. Voila, we force the use of a tab if the user likes that.

Convert List<String> to List<Integer> directly

No, you need to loop over the array

for(String s : strList) intList.add(Integer.valueOf(s));

How do I create an array of strings in C?

If the strings are static, you're best off with:

const char *my_array[] = {"eenie","meenie","miney"};

While not part of basic ANSI C, chances are your environment supports the syntax. These strings are immutable (read-only), and thus in many environments use less overhead than dynamically building a string array.

For example in small micro-controller projects, this syntax uses program memory rather than (usually) more precious ram memory. AVR-C is an example environment supporting this syntax, but so do most of the other ones.

Inline for loop

q  = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1,1,2,3,1]

p = []
for v in vm:
    if v in q:
        p.append(q.index(v))
    else:
        p.append(99999)

print p
p = [q.index(v) if v in q else 99999 for v in vm]
print p

Output:

[99999, 99999, 99999, 99999, 0, 1, 2, 0]
[99999, 99999, 99999, 99999, 0, 1, 2, 0]

Instead of using append() in the list comprehension you can reference the p as direct output, and use q.index(v) and 99999 in the LC.

Not sure if this is intentional but note that q.index(v) will find just the first occurrence of v, even tho you have several in q. If you want to get the index of all v in q, consider using a enumerator and a list of already visited indexes

Something in those lines(pseudo-code):

visited = []
for i, v in enumerator(vm):
   if i not in visited:
       p.append(q.index(v))
   else:
       p.append(q.index(v,max(visited))) # this line should only check for v in q after the index of max(visited)
   visited.append(i)

Difference between map and collect in Ruby?

#collect is actually an alias for #map. That means the two methods can be used interchangeably, and effect the same behavior.

Export result set on Dbeaver to CSV

You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :

  1. Execute your query
  2. Right click any anywhere in the results
  3. click "Export resultset..." to open the export wizard
  4. Choose the format you want (CSV according to your question)
  5. Review the settings in the next panes when clicking "Next".
  6. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.


In newer versions of DBeaver you can just :

  1. right click the SQL of the query you want to export
  2. Execute > Export from query
  3. Choose the format you want (CSV according to your question)
  4. Review the settings in the next panes when clicking "Next".
  5. Set the folder where the file will be created, and "Finish"

The export runs in the background, a popup will appear when it's done.

Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.

How to right-align and justify-align in Markdown?

In a generic Markdown document, use:

<style>body {text-align: right}</style>

or

<style>body {text-align: justify}</style>

Does not seem to work with Jupyter though.

How can I get the line number which threw exception?

Extension Method

static class ExceptionHelpers
{
    public static int LineNumber(this Exception ex)
    {
        int n;
        int i = ex.StackTrace.LastIndexOf(" ");
        if (i > -1)
        {
            string s = ex.StackTrace.Substring(i + 1);
            if (int.TryParse(s, out n))
                return n;
        }
        return -1;
    }
}

Usage

try
{
    throw new Exception("A new error happened");
}
catch (Exception ex)
{
    //If error in exception LineNumber() will be -1
    System.Diagnostics.Debug.WriteLine("[" + ex.LineNumber() + "] " + ex.Message);
}

How to get multiple counts with one SQL query?

I do something like this where I just give each table a string name to identify it in column A, and a count for column. Then I union them all so they stack. The result is pretty in my opinion - not sure how efficient it is compared to other options but it got me what I needed.

select 'table1', count (*) from table1
union select 'table2', count (*) from table2
union select 'table3', count (*) from table3
union select 'table4', count (*) from table4
union select 'table5', count (*) from table5
union select 'table6', count (*) from table6
union select 'table7', count (*) from table7;

Result:

-------------------
| String  | Count |
-------------------
| table1  | 123   |
| table2  | 234   |
| table3  | 345   |
| table4  | 456   |
| table5  | 567   |
-------------------

Troubleshooting misplaced .git directory (nothing to commit)

I have faced the same issue with git while working with angular CLI 6.1.2. Angular CLI 6.1.2 automatically initializes .git folder when you create a new angular project using Angular CLI. So when I tried git status - it was not detecting the whole working directory.

I have just deleted the hidden .git folder from my angular working directory and then initialized git repository again with git init. And now, I can see all my files with git status.

jQuery Scroll To bottom of the page

$('html,body').animate({ scrollTop: 9999 }, 'slow');

As simple as this , 9999 page height ... big range so it can reach to bottom .

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

This is a known bug on Linux Debian. I solved using the create_tables.sql in the official package and changing pma_ with pma__ inside /etc/phpmyadmin/config.inc.php

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

I believe that you can omit updating the "non-desired" columns by adjusting the other answers as follows:

update table set
    columnx = (case when condition1 then 25 end),
    columny = (case when condition2 then 25 end)`

As I understand it, this will update only when the condition is met.

After reading all the comments, this is the most efficient:

Update table set ColumnX = 25 where Condition1
 Update table set ColumnY = 25 where Condition1`

Sample Table:

CREATE TABLE [dbo].[tblTest](
    [ColX] [int] NULL,
    [ColY] [int] NULL,
    [ColConditional] [bit] NULL,
    [id] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]

Sample Data:

Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1)
Insert into tblTest (ColX, ColY, ColConditional) values (1, null, null)
Insert into tblTest (ColX, ColY, ColConditional) values (2, null, null)
Insert into tblTest (ColX, ColY, ColConditional) values (null, 1, null)
Insert into tblTest (ColX, ColY, ColConditional) values (null, 2, null)

Now I assume you can write a conditional that handles nulls. For my example, I am assuming you have written such a conditional that evaluates to True, False or Null. If you need help with this, let me know and I will do my best.

Now running these two lines of code does infact change X to 25 if and only if ColConditional is True(1) and Y to 25 if and only if ColConditional is False(0)

Update tblTest set ColX = 25 where ColConditional = 1
Update tblTest set ColY = 25 where ColConditional = 0

P.S. The null case was never mentioned in the original question or any updates to the question, but as you can see, this very simple answer handles them anyway.

Write / add data in JSON file using Node.js

try

var fs = require("fs");
var sampleObject = { your data };

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {  console.error(err);  return; };
    console.log("File has been created");
});

How do I convert a TimeSpan to a formatted string?

Would TimeSpan.ToString() do the trick for you? If not, it looks like the code sample on that page describes how to do custom formatting of a TimeSpan object.

How to get the first line of a file in a bash script?

line=$(head -1 file)

Will work fine. (As previous answer). But

line=$(read -r FIRSTLINE < filename)

will be marginally faster as read is a built-in bash command.

Import regular CSS file in SCSS file?

If you have a .css file which you don't wish to modify, neither change its extension to .scss (e.g. this file is from a forked project you don't maintain), you can always create a symlink and then import it into your .scss.

Creates a symlink:

ln -s path/to/css/file.css path/to/sass/files/_file.scss


Imports symlink file into a target .scss:

@import "path/to/sass/files/file";


Your target output .css file is going to hold contents from imported symlink .scss file, not a CSS import rule (mentioned by @yaz with highest comment votes). And you don't have duplicated files with different extensions, what means any update made inside initial .css file immediately gets imported into your target output.

Symbolic link (also symlink or soft link) is a special type of file that contains a reference to another file in the form of an absolute or relative path and that affects pathname resolution.
http://en.wikipedia.org/wiki/Symbolic_link

How to center an iframe horizontally?

You can put iframe inside a <div>

<div>
    <iframe></iframe>
</div>

It works because it is now inside a block element.

Adding elements to object

If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:

var element = { quantity: quantity };
cart[id] = element;

This allows you to add multiple items to the cart like so:

cart["1"] = { quantity: 5};
cart["2"] = { quantity: 10};

// Cart is now:
// { "1": { quantity: 5 }, "2": { quantity: 10 } }

Is there a 'box-shadow-color' property?

You could use a CSS pre-processor to do your skinning. With Sass you can do something similar to this:

_theme1.scss:

$theme-primary-color: #a00;
$theme-secondary-color: #d00;
// etc.

_theme2.scss:

$theme-primary-color: #666;
$theme-secondary-color: #ccc;
// etc.

styles.scss:

// import whichever theme you want to use
@import 'theme2';

-webkit-box-shadow: inset 0px 0px 2px $theme-primary-color;
-moz-box-shadow: inset 0px 0px 2px $theme-primary-color;

If it's not site wide theming but class based theming you need, then you can do this: http://codepen.io/jjenzz/pen/EaAzo

How to send multiple data fields via Ajax?

I am a beginner at ajax but I think to use this "data: {status: status, name: name}" method datatype must be set to JSON i.e

$.ajax({
type: "POST",
dataType: "json",
url: "ajax/activity_save.php",
data: {status: status, name: name},

Adding background image to div using CSS

You need to add a width and a height of the background image for it to display properly.

For instance,

.header-shadow{
    background-image: url('../images/header-shade.jpg');
    width: XXpx;
    height: XXpx;
}

As you mentioned that you are using it as a shadow, you can remove the width and add a background-repeat (either vertically or horizontally if required).

For instance,

.header-shadow{
    background-image: url('../images/header-shade.jpg');
    background-repeat: repeat-y; /* for vertical repeat */
    background-repeat: repeat-x; /* for horizontal repeat */
    height: XXpx;
}

PS: XX is a dummy value. You need to replace it with your actual values of your image.

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

If at any point you return Promise.reject('something') you will be thrown in the catch block to the promise.

promiseOne
  .then((result) => {
    if (!result) {
      return Promise.reject('No result');
    }
    return;
  })
  .catch((err) => {
    console.log(err);
  });

If the first promise does not return any result you will only get 'No result' in the console.

How to add column if not exists on PostgreSQL?

You can do it by following way.

ALTER TABLE tableName drop column if exists columnName; 
ALTER TABLE tableName ADD COLUMN columnName character varying(8);

So it will drop the column if it is already exists. And then add the column to particular table.

Force download a pdf link using javascript/ajax/jquery

In javascript use the preventDefault() method of the event args parameter.

<a href="no-script.html">Download now!</a>

$('a').click(function(e) {
    e.preventDefault(); // stop the browser from following
    window.location.href = 'downloads/file.pdf';
});

Ant is using wrong java version

Just had this issue, it happened because I'd first added the build file to the ant-view when the default JRE was 1.6.

There was no project-specific JRE and I changed the default to 1.5, even eclipse was running in 1.5, and JAVA_HOME was 1.5 too. Running the ant target from the command line used JRE 1.5, but within eclipse it still used 1.6.

I had to right-click the ant target, select Run As... and change the JRE under the JRE tab. This setting is remembered for subsequent runs.

Uncaught TypeError: Cannot assign to read only property

I tried changing year to a different term, and it worked.

public_methods : {
    get: function() {
        return this._year;
    },

    set: function(newValue) {
        if(newValue > this.originYear) {
            this._year = newValue;
            this.edition += newValue - this.originYear;
        }
    }
}

Expression ___ has changed after it was checked

I switched from AfterViewInit to AfterContentChecked and It worked for me.

Here is the process

  1. Add dependency in your constructor:

    constructor (private cdr: ChangeDetectorRef) {}

  2. and call your login in implemented method code here:

     ngAfterContentChecked() {
         this.cdr.detectChanges();
      // call or add here your code
     }
    

Git, How to reset origin/master to a commit?

Since I had a similar situation, I thought I'd share my situation and how these answers helped me (thanks everyone).

So I decided to work locally by amending my last commit every time I wanted to save my progress on the main branch (I know, I should've branched out, committed on that, kept pushing and later merge back to master).

One late night, in paranoid fear of loosing my progress to hardware failure or something out of the ether, I decided to push master to origin. Later I kept amending my local master branch and when I decided it's time to push again, I was faced with different master branches and found out I can't amend origin/upstream (duh!) like I can local development branches.

So I didn't checkout master locally because I already was after a commit. Master was unchanged. I didn't even need to reset --hard, my current commit was OK.

I just forced push to origin, without even specifying what commit I wanted to force on master since in this case it's whatever HEAD is at. Checked git diff master..origin/master so there weren't any differences and that's it. All fixed. Thanks! (I know, I'm a git newbie, please forgive!).

So if you're already OK with your master branch locally, just:

git push --force origin master
git diff master..origin/master

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

Datatables Select All Checkbox

I made a simple implementation of this functionality using fontawesome, also taking advantage of the Select Extension, this covers select all, deselect some items, deselect all. https://codepen.io/pakogn/pen/jJryLo

HTML:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>
                <button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">
                <i class="far fa-square"></i>  
                </button>
            </th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td></td>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>$170,750</td>
        </tr>
        <tr>
            <td></td>
            <td>Ashton Cox</td>
            <td>Junior Technical Author</td>
            <td>San Francisco</td>
            <td>66</td>
            <td>$86,000</td>
        </tr>
        <tr>
            <td></td>
            <td>Cedric Kelly</td>
            <td>Senior Javascript Developer</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>$433,060</td>
        </tr>
        <tr>
            <td></td>
            <td>Airi Satou</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>33</td>
            <td>$162,700</td>
        </tr>
        <tr>
            <td></td>
            <td>Brielle Williamson</td>
            <td>Integration Specialist</td>
            <td>New York</td>
            <td>61</td>
            <td>$372,000</td>
        </tr>
        <tr>
            <td></td>
            <td>Herrod Chandler</td>
            <td>Sales Assistant</td>
            <td>San Francisco</td>
            <td>59</td>
            <td>$137,500</td>
        </tr>
        <tr>
            <td></td>
            <td>Rhona Davidson</td>
            <td>Integration Specialist</td>
            <td>Tokyo</td>
            <td>55</td>
            <td>$327,900</td>
        </tr>
        <tr>
            <td></td>
            <td>Colleen Hurst</td>
            <td>Javascript Developer</td>
            <td>San Francisco</td>
            <td>39</td>
            <td>$205,500</td>
        </tr>
        <tr>
            <td></td>
            <td>Sonya Frost</td>
            <td>Software Engineer</td>
            <td>Edinburgh</td>
            <td>23</td>
            <td>$103,600</td>
        </tr>
        <tr>
            <td></td>
            <td>Jena Gaines</td>
            <td>Office Manager</td>
            <td>London</td>
            <td>30</td>
            <td>$90,560</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </tfoot>
</table>

Javascript:

$(document).ready(function() {
    let myTable = $('#example').DataTable({
        columnDefs: [{
            orderable: false,
            className: 'select-checkbox',
            targets: 0,
        }],
        select: {
            style: 'os', // 'single', 'multi', 'os', 'multi+shift'
            selector: 'td:first-child',
        },
        order: [
            [1, 'asc'],
        ],
    });

    $('#MyTableCheckAllButton').click(function() {
        if (myTable.rows({
                selected: true
            }).count() > 0) {
            myTable.rows().deselect();
            return;
        }

        myTable.rows().select();
    });

    myTable.on('select deselect', function(e, dt, type, indexes) {
        if (type === 'row') {
            // We may use dt instead of myTable to have the freshest data.
            if (dt.rows().count() === dt.rows({
                    selected: true
                }).count()) {
                // Deselect all items button.
                $('#MyTableCheckAllButton i').attr('class', 'far fa-check-square');
                return;
            }

            if (dt.rows({
                    selected: true
                }).count() === 0) {
                // Select all items button.
                $('#MyTableCheckAllButton i').attr('class', 'far fa-square');
                return;
            }

            // Deselect some items button.
            $('#MyTableCheckAllButton i').attr('class', 'far fa-minus-square');
        }
    });
});

Error: "setFile(null,false) call failed" when using log4j

I had the exact same problem. Here is the solution that worked for me: simply put your properties file path in the cmd line this way :

-Dlog4j.configuration=<FILE_PATH>  (ex: log4j.properties)

Hope this will help you

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

If you already have all dependencies in your pom, try:
1. Remove all downloaded jars form your maven repository folder for 'org->springframework'
2. Make a maven clean build.

Returning the product of a list

I remember some long discussions on comp.lang.python (sorry, too lazy to produce pointers now) which concluded that your original product() definition is the most Pythonic.

Note that the proposal is not to write a for loop every time you want to do it, but to write a function once (per type of reduction) and call it as needed! Calling reduction functions is very Pythonic - it works sweetly with generator expressions, and since the sucessful introduction of sum(), Python keeps growing more and more builtin reduction functions - any() and all() are the latest additions...

This conclusion is kinda official - reduce() was removed from builtins in Python 3.0, saying:

"Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable."

See also The fate of reduce() in Python 3000 for a supporting quote from Guido (and some less supporting comments by Lispers that read that blog).

P.S. if by chance you need product() for combinatorics, see math.factorial() (new 2.6).

How to uninstall pip on OSX?

Since pip is a package, pip uninstall pip Will do it.
EDIT: If that does not work, try sudo -H pip uninstall pip.

Prepare for Segue in Swift

Change the segue identifier in the right panel in the section with an id. icon to match the string you used in your conditional.

Laravel Pagination links not including other GET parameters

I think you should use this code in Laravel version 5+. Also this will work not only with parameter page but also with any other parameter(s):

$users->appends(request()->input())->links();

Personally, I try to avoid using Facades as much as I can. Using global helper functions is less code and much elegant.

UPDATE:

Do not use Input Facade as it is deprecated in Laravel v6+

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

What is the use of the square brackets [] in sql statements?

They're handy if your columns have the same names as SQL keywords, or have spaces in them.

Example:

create table test ( id int, user varchar(20) )

Oh no! Incorrect syntax near the keyword 'user'. But this:

create table test ( id int, [user] varchar(20) )

Works fine.

Setting a Sheet and cell as variable

Yes. For that ensure that you declare the worksheet

For example

Previous Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet3")

    Debug.Print ws.Cells(23, 4).Value
End Sub

New Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet4")

    Debug.Print ws.Cells(23, 4).Value
End Sub

Use jQuery to change value of a label

.text is correct, the following code works for me:

$('#lb'+(n+1)).text(a[i].attributes[n].name+": "+ a[i].attributes[n].value);

ToList()-- does it create a new list?

I don't see anywhere in the documentation that ToList() is always guaranteed to return a new list. If an IEnumerable is a List, it may be more efficient to check for this and simply return the same List.

The worry is that sometimes you may want to be absolutely sure that the returned List is != to the original List. Because Microsoft doesn't document that ToList will return a new List, we can't be sure (unless someone found that documentation). It could also change in the future, even if it works now.

new List(IEnumerable enumerablestuff) is guaranteed to return a new List. I would use this instead.

In Angular, What is 'pathmatch: full' and what effect does it have?

RouterModule.forRoot([
      { path: 'welcome', component: WelcomeComponent },
      { path: '', redirectTo: 'welcome', pathMatch: 'full' },
      { path: '**', component: 'pageNotFoundComponent' }
    ])

Case 1 pathMatch:'full': In this case, when app is launched on localhost:4200 (or some server) the default page will be welcome screen, since the url will be https://localhost:4200/

If https://localhost:4200/gibberish this will redirect to pageNotFound screen because of path:'**' wildcard

Case 2 pathMatch:'prefix':

If the routes have { path: '', redirectTo: 'welcome', pathMatch: 'prefix' }, now this will never reach the wildcard route since every url would match path:'' defined.

Hash Map in Python

class HashMap:
    def __init__(self):
        self.size = 64
        self.map = [None] * self.size

    def _get_hash(self, key):
        hash = 0

        for char in str(key):
            hash += ord(char)
        return hash % self.size

    def add(self, key, value):
        key_hash = self._get_hash(key)
        key_value = [key, value]

        if self.map[key_hash] is None:
            self.map[key_hash] = list([key_value])
            return True
        else:
            for pair in self.map[key_hash]:
                if pair[0] == key:
                    pair[1] = value
                    return True
                else:
                    self.map[key_hash].append(list([key_value]))
                    return True

    def get(self, key):
        key_hash = self._get_hash(key)
        if self.map[key_hash] is not None:
            for pair in self.map[key_hash]: 
                if pair[0] == key:
                    return pair[1]
        return None

    def delete(self, key):
        key_hash = self._get_hash(key)

        if self.map[key_hash] is None :
            return False
        for i in range(0, len(self.map[key_hash])):
            if self.map[key_hash][i][0] == key:
                self.map[key_hash].pop(i)
                return True

    def print(self):

        print('---Phonebook---')
        for item in self.map:
            if item is not None:
                print(str(item))

h = HashMap()

TCPDF output without saving file

I've been using the Output("doc.pdf", "I"); and it doesn't work, I'm always asked for saving the file.

I took a look in documentation and found that

I send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF. http://www.tcpdf.org/doc/classTCPDF.html#a3d6dcb62298ec9d42e9125ee2f5b23a1

Then I think you have to use a plugin to print it, otherwise it is going to be downloaded.

How do you implement a Stack and a Queue in JavaScript?

Javascript array shift() is slow especially when holding many elements. I know two ways to implement queue with amortized O(1) complexity.

First is by using circular buffer and table doubling. I have implemented this before. You can see my source code here https://github.com/kevyuu/rapid-queue

The second way is by using two stack. This is the code for queue with two stack

function createDoubleStackQueue() {
var that = {};
var pushContainer = [];
var popContainer = [];

function moveElementToPopContainer() {
    while (pushContainer.length !==0 ) {
        var element = pushContainer.pop();
        popContainer.push(element);
    }
}

that.push = function(element) {
    pushContainer.push(element);
};

that.shift = function() {
    if (popContainer.length === 0) {
        moveElementToPopContainer();
    }
    if (popContainer.length === 0) {
        return null;
    } else {
        return popContainer.pop();
    }
};

that.front = function() {
    if (popContainer.length === 0) {
        moveElementToPopContainer();
    }
    if (popContainer.length === 0) {
        return null;
    }
    return popContainer[popContainer.length - 1];
};

that.length = function() {
    return pushContainer.length + popContainer.length;
};

that.isEmpty = function() {
    return (pushContainer.length + popContainer.length) === 0;
};

return that;}

This is performance comparison using jsPerf

CircularQueue.shift() vs Array.shift()

http://jsperf.com/rapidqueue-shift-vs-array-shift

As you can see it is significantly faster with large dataset

What's the HTML to have a horizontal space between two objects?

Another way you can add horizontal space between elements is to set up labels to preserve spaces in css:

label {
   white-space: pre;
}

..and then add a label with as many spaces as you want:

<label>  </label>

How can I use Html.Action?

first, create a class to hold your parameters:

public class PkRk {
    public int pk { get; set; }
    public int rk { get; set; }
}

then, use the Html.Action passing the parameters:

Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })

and use in Controller:

public ActionResult PkRkAction(PkRk pkrk) {
    return PartialView(pkrk);
}

What's wrong with overridable method calls in constructors?

Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.

class A {

    protected int minWeeklySalary;
    protected int maxWeeklySalary;

    protected static final int MIN = 1000;
    protected static final int MAX = 2000;

    public A() {
        setSalaryRange();
    }

    protected void setSalaryRange() {
        throw new RuntimeException("not implemented");
    }

    public void pr() {
        System.out.println("minWeeklySalary: " + minWeeklySalary);
        System.out.println("maxWeeklySalary: " + maxWeeklySalary);
    }
}

class B extends A {

    private int factor = 1;

    public B(int _factor) {
        this.factor = _factor;
    }

    @Override
    protected void setSalaryRange() {
        this.minWeeklySalary = MIN * this.factor;
        this.maxWeeklySalary = MAX * this.factor;
    }
}

public static void main(String[] args) {
    B b = new B(2);
    b.pr();
}

The result would actually be:

minWeeklySalary: 0

maxWeeklySalary: 0

This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.

I hope that would help someone.

How to do a recursive find/replace of a string with awk or sed?

find /home/www \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

-print0 tells find to print each of the results separated by a null character, rather than a new line. In the unlikely event that your directory has files with newlines in the names, this still lets xargs work on the correct filenames.

\( -type d -name .git -prune \) is an expression which completely skips over all directories named .git. You could easily expand it, if you use SVN or have other folders you want to preserve -- just match against more names. It's roughly equivalent to -not -path .git, but more efficient, because rather than checking every file in the directory, it skips it entirely. The -o after it is required because of how -prune actually works.

For more information, see man find.

how to resolve DTS_E_OLEDBERROR. in ssis

I faced the similar issue.

Deselect the check box ("In wizard deselect the checkbox stating "First row has columns names") and before running the wizard make sure you have opened your excel sheet.

Then run the wizard by deselecting the checkbox.

This resolved my issue.

Twitter Bootstrap carousel different height images cause bouncing arrows

The solution given earlier leads to a situation where images may be too small for the carousel box. A proper solution to the problem of bumping controls is to override Bootstraps CSS.

Original code:

.carousel-control {
top: 40%;
}

Override the variable with a fixed value inside your own stylesheet (300px worked in my design):

.carousel-control {
top: 300px;
}

Hopefully this will solve your problem.

Extension exists but uuid_generate_v4 fails

The extension is available but not installed in this database.

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

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

I was also facing the same issue, tried all the solutions mentioned in the answer but none seemed to work. Turned out that during the checkin of code to TFS. TFS did not checkin the Resx file it only checked in the designer file. So all other developers were facing this issue while running on their machines. Checking in the resx file manually did the trick

C# Numeric Only TextBox Control

You can check the Ascii value by e.keychar on KeyPress event of TextBox.

By checking the AscII value you can check for number or character.

Similarly you can write logic to check the Email ID.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

Please do following steps:

  1. Open service link in IE.

  2. Click on the certificate error mention in address bar and click on View certificates.

  3. Check issued to: name.

  4. Take the issued name and replace localhost mention in service and client endpoint base address name with A fully qualified domain name (FQDN).

For Example: https://localhost:203/SampleService.svc To https://INL-126166-.groupinfra.com:203/SampleService.svc

RSA: Get exponent and modulus given a public key

Mostly for my own reference, here's how you get it from a private key generated by ssh-keygen

openssl rsa -text -noout -in ~/.ssh/id_rsa

Of course, this only works with the private key.

how to use a like with a join in sql?

In MySQL you could try:

SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');

Of course this would be a massively inefficient query because it would do a full table scan.

Update: Here's a proof


create table A (MYCOL varchar(255));
create table B (MYCOL varchar(255));
insert into A (MYCOL) values ('foo'), ('bar'), ('baz');
insert into B (MYCOL) values ('fooblah'), ('somethingfooblah'), ('foo');
insert into B (MYCOL) values ('barblah'), ('somethingbarblah'), ('bar');
SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');
+-------+------------------+
| MYCOL | MYCOL            |
+-------+------------------+
| foo   | fooblah          |
| foo   | somethingfooblah |
| foo   | foo              |
| bar   | barblah          |
| bar   | somethingbarblah |
| bar   | bar              |
+-------+------------------+
6 rows in set (0.38 sec)

How to close an iframe within iframe itself

function closeWin()   // Tested Code
{
var someIframe = window.parent.document.getElementById('iframe_callback');
someIframe.parentNode.removeChild(window.parent.document.getElementById('iframe_callback'));
}


<input class="question" name="Close" type="button" value="Close" onClick="closeWin()" tabindex="10" /> 

Angular 4 setting selected option in Dropdown

If you want to select a value based on true / false use

[selected]="opt.selected == true"

 <option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected == true">{{opt.selected+opt.value}}</option>

checkit out

Angular 2 - Setting selected value on dropdown list

Android and setting alpha for (image) view alpha

It's easier than the other response. There is an xml value alpha that takes double values.

android:alpha="0.0" thats invisible

android:alpha="0.5" see-through

android:alpha="1.0" full visible

That's how it works.

Connecting to a network folder with username/password in Powershell

At first glance one really wants to use New-PSDrive supplying it credentials.

> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user

Fails!

New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.

The documentation states that you can provide a PSCredential object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.

Therefore you can either use net use or the WScript.Network object, calling the MapNetworkDrive function:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")

Edit for New-PSDrive in PowerShell 3.0

Apparently with newer versions of PowerShell, the New-PSDrive cmdlet works to map network shares with credentials!

New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist

Static extension methods

In short, no, you can't.

Long answer, extension methods are just syntactic sugar. IE:

If you have an extension method on string let's say:

public static string SomeStringExtension(this string s)
{
   //whatever..
}

When you then call it:

myString.SomeStringExtension();

The compiler just turns it into:

ExtensionClass.SomeStringExtension(myString);

So as you can see, there's no way to do that for static methods.

And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:

Bool.Parse(..)

vs.

Helper.ParseBool(..);

Doesn't really bring much to the table...

jQuery: How to get the HTTP status code from within the $.ajax.error method?

If you're using jQuery 1.5, then statusCode will work.

If you're using jQuery 1.4, try this:

error: function(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.status);
    alert(textStatus);
    alert(errorThrown);
}

You should see the status code from the first alert.

Unable to execute dex: Multiple dex files define

This is a build path issue.

  • Make sure your bin folder is not included in your build path.

  • Right click on your project -> go to properties -> Build Path.

  • Make sure that Honeycomb library is in your libs/ folder and not in your source folder.

  • Include the libraries in libs/ individually in the build path.

    BTW, you may want to bring in the android-support-v4 library to get Ice Cream Sandwich support instead of the Honeycomb support library.

What is the difference between a strongly typed language and a statically typed language?

One does not imply the other. For a language to be statically typed it means that the types of all variables are known or inferred at compile time.

A strongly typed language does not allow you to use one type as another. C is a weakly typed language and is a good example of what strongly typed languages don't allow. In C you can pass a data element of the wrong type and it will not complain. In strongly typed languages you cannot.

Difference between View and ViewGroup in Android

A View object is a component of the user interface (UI) like a button or a text box, and it's also called widget.

A ViewGroup object is a layout, that is, a container of other ViewGroup objects (layouts) and View objects (widgets). It's possible to have a layout inside another layout. It's called nested layout but it can increase the time needed to draw the user interface.

The user interface for an app is built using a hierarchy of ViewGroup and View objects. In Android Studio it is possible to use the Component Tree window to visualise this hierarchy.

The Layout Editor in Android Studio can be used to drag and drop View objects (widgets) in the layout. It simplifies the creation of a layout.

What is class="mb-0" in Bootstrap 4?

Bootstrap has predefined classes that we use for styling. If you are familiar with CSS, you'd know what padding, margin and spacing etc. are.

mb-0 = margin-bottom:0;

OK now moving a little further in knowledge, bootstrap has more classes for margin including:

mt- = margin-top
mb- = margin-bottom
ml- = margin-left
mr- = margin-right
my- = it sets margin-left and margin-right at the same time on y axes
mX- = it sets margin-bottom and margin-top at the same time on X axes

This and much more is explained here https://getbootstrap.com/docs/5.0/utilities/spacing/ The best way to learn is through https://getbootstrap.com site itself. It explains a lot obout its built in classes.

What is the Java equivalent of PHP var_dump?

I like to use GSON because it's often already a dependency of the type of projects I'm working on:

public static String getDump(Object o) {
    return new GsonBuilder().setPrettyPrinting().create().toJson(o);
}

Or substitute GSON for any other JSON library you use.

Why can't I see the "Report Data" window when creating reports?

It is in visual studio. In the designer page, it is on in the menu bar, there is XTRAREPORTS field. You can show up panels using it

Sort a Custom Class List<T>

You can use linq:

var q = from tag in Week orderby Convert.ToDateTime(tag.date) select tag;
List<cTag> Sorted = q.ToList()

How to have comments in IntelliSense for function in Visual Studio?

To generate an area where you can specify a description for the function and each parameter for the function, type the following on the line before your function and hit Enter:

  • C#: ///

  • VB: '''

See Recommended Tags for Documentation Comments (C# Programming Guide) for more info on the structured content you can include in these comments.