Programs & Examples On #Iunknown

How can I check if an array contains a specific value in php?

From http://php.net/manual/en/function.in-array.php

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Searches haystack for needle using loose comparison unless strict is set.

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

It's an encoding problem. You have to set the correct encoding in the HTML head via meta tag:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

Replace "ISO-8859-1" with whatever your encoding is (e.g. 'UTF-8'). You must find out what encoding your HTML files are. If you're on an Unix system, just type file file.html and it should show you the encoding. If this is not possible, you should be able to find out somewhere what encoding your editor produces.

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

To answer the original question on how to get the index as an integer for the desired selection, the following will work :

df[df['A']==5].index.item()

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

Computing cross-correlation function?

I just finished writing my own optimised implementation of normalized cross-correlation for N-dimensional arrays. You can get it from here.

It will calculate cross-correlation either directly, using scipy.ndimage.correlate, or in the frequency domain, using scipy.fftpack.fftn/ifftn depending on whichever will be quickest.

Display SQL query results in php

You need to do a while loop to get the result from the SQL query, like this:

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )    
FROM modul1open) ORDER BY idM1O LIMIT 1";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    // If you want to display all results from the query at once:
    print_r($row);

    // If you want to display the results one by one
    echo $row['column1'];
    echo $row['column2']; // etc..

}

Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli or PDO extension. You can read more about that here.

How do I "select Android SDK" in Android Studio?

My problem solved by setting NDK path in Android Studio.

File-> Project Structure->NDK Location.

JavaScript load a page on button click

Simple code to redirect page

<!-- html button designing and calling the event in javascript -->
<input id="btntest" type="button" value="Check" 
       onclick="window.location.href = 'http://www.google.com'" />

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;
            dataGridView1.BeginEdit(true);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

Sorry with my English, When you create a new android project, you should choose api of high level, for example: from api 17 to api 21, It will not have appcompat and very easy to share project. If you did it with lower API, you just edit in Android Manifest to have upper API :), after that, you can delete Appcompat V7.

Python list iterator behavior and next(iterator)

Something is wrong with your Python/Computer.

a = iter(list(range(10)))
for i in a:
   print(i)
   next(a)

>>> 
0
2
4
6
8

Works like expected.

Tested in Python 2.7 and in Python 3+ . Works properly in both

SmartGit Installation and Usage on Ubuntu

Seems a bit too late, but there is a PPA repository with SmartGit, enjoy! =)

c# search string in txt file

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

Excluding directory when creating a .tar.gz file

You can also exclude more than one using only one --exclude. Like this example:

tar -pczf MyBackup.tar.gz --exclude={"/home/user/public_html/tmp","/home/user/public_html/data"} /home/user/public_html/

In --exclude= you must finish the directory name without / and must in between MyBackup.tar.gz and /home/user/public_html/

The syntax is:

tar <OPTIONS> <TARBALL_WILL_CREATE> <ARGS> <PATH_TO_COMPRESS>

How to set the image from drawable dynamically in android?

This works for me (dont use the extension of the image, just the name):

String imagename = "myImage";
int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

How to randomly select rows in SQL?

SELECT TOP 5 Id, Name FROM customerNames
ORDER BY NEWID()

That said, everybody seems to come to this page for the more general answer to your question:

Selecting a random row in SQL

Select a random row with MySQL:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

Select a random row with PostgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

Select a random row with Microsoft SQL Server:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

Select a random row with IBM DB2

SELECT column, RAND() as IDX 
FROM table 
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Select a random record with Oracle:

SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

Select a random row with sqlite:

SELECT column FROM table 
ORDER BY RANDOM() LIMIT 1

Peak-finding algorithm for Python/SciPy

I'm looking at a similar problem, and I've found some of the best references come from chemistry (from peaks finding in mass-spec data). For a good thorough review of peaking finding algorithms read this. This is one of the best clearest reviews of peak finding techniques that I've run across. (Wavelets are the best for finding peaks of this sort in noisy data.).

It looks like your peaks are clearly defined and aren't hidden in the noise. That being the case I'd recommend using smooth savtizky-golay derivatives to find the peaks (If you just differentiate the data above you'll have a mess of false positives.). This is a very effective technique and is pretty easy to implemented (you do need a matrix class w/ basic operations). If you simply find the zero crossing of the first S-G derivative I think you'll be happy.

how to get current datetime in SQL?

Complete answer:

1. Is there a function available in SQL?
Yes, the SQL 92 spec, Oct 97, pg. 171, section 6.16 specifies this functions:

CURRENT_TIME       Time of day at moment of evaluation
CURRENT_DATE       Date at moment of evaluation
CURRENT_TIMESTAMP  Date & Time at moment of evaluation

2. It is implementation depended so each database has its own function for this?
Each database has its own implementations, but they have to implement the three function above if they comply with the SQL 92 specification (but depends on the version of the spec)

3. What is the function available in MySQL?

NOW() returns 2009-08-05 15:13:00  
CURDATE() returns 2009-08-05  
CURTIME() returns 15:13:00  

Why can't I reference my class library?

Unfortunately the only thing that worked for me was completely deleting and recreating the class library project, after having temporarily copied the class files in it elsewhere. Only then would the ASP.Net web project recognise the using statements that referred to the class library project. This was with Visual Studio 2010, not using ReSharper.

Vertically align an image inside a div with responsive height

Make another div and add both 'dummy' and 'img-container' inside the div

Do HTML and CSS like follows

_x000D_
_x000D_
html , body {height:100%;}_x000D_
.responsive-container { height:100%; display:table; text-align:center; width:100%;}_x000D_
.inner-container {display:table-cell; vertical-align:middle;}
_x000D_
<div class="responsive-container">_x000D_
    <div class="inner-container">_x000D_
  <div class="dummy">Sample</div>_x000D_
  <div class="img-container">_x000D_
   Image tag_x000D_
  </div>_x000D_
 </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Instead of 100% for the 'responsive-container' you can give the height that you want.,

php form action php self

You can use an echo shortcut also instead of typing out "echo blah;" as shown below:

<form method="POST" action="<?=($_SERVER['PHP_SELF'])?>">

convert double to int

label8.Text = "" + years.ToString("00") + " years";

when you want to send it to a label, or something, and you don't want any fractional component, this is the best way

label8.Text = "" + years.ToString("00.00") + " years";

if you want with only 2, and it's always like that

WPF Add a Border to a TextBlock

No, you need to wrap your TextBlock in a Border. Example:

<Border BorderThickness="1" BorderBrush="Black">
    <TextBlock ... />
</Border>

Of course, you can set these properties (BorderThickness, BorderBrush) through styles as well:

<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="Black" />
</Style>

<Border Style="{StaticResource notCalledBorder}">
    <TextBlock ... />
</Border>

Twitter Bootstrap Form File Element Upload Button

I have the same problem, and i try it like this.

<div>
<button type='button' class='btn btn-info btn-file'>Browse</button>
<input type='file' name='image'/>
</div>

The CSS

<style>
.btn-file {
    position:absolute;
}
</style>

The JS

<script>
$(document).ready(function(){
    $('.btn-file').click(function(){
        $('input[name="image"]').click();
    });
});
</script>

Note : The button .btn-file must in the same tag as the input file

Hope you found the best solution...

How should I use try-with-resources with JDBC?

There's no need for the outer try in your example, so you can at least go down from 3 to 2, and also you don't need closing ; at the end of the resource list. The advantage of using two try blocks is that all of your code is present up front so you don't have to refer to a separate method:

public List<User> getUser(int userId) {
    String sql = "SELECT id, username FROM users WHERE id = ?";
    List<User> users = new ArrayList<>();
    try (Connection con = DriverManager.getConnection(myConnectionURL);
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setInt(1, userId);
        try (ResultSet rs = ps.executeQuery()) {
            while(rs.next()) {
                users.add(new User(rs.getInt("id"), rs.getString("name")));
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}

How do I create a readable diff of two spreadsheets using git diff?

I found an openoffice macro here that will invoke openoffice's compare documents function on two files. Unfortunately, openoffice's spreadsheet compare seems a little flaky; I just had the 'Reject All' button insert a superfluous column in my document.

How to show first commit by 'git log'?

Short answer

git rev-list --max-parents=0 HEAD

(from tiho's comment. As Chris Johnsen notices, --max-parents was introduced after this answer was posted.)

Explanation

Technically, there may be more than one root commit. This happens when multiple previously independent histories are merged together. It is common when a project is integrated via a subtree merge.

The git.git repository has six root commits in its history graph (one each for Linus’s initial commit, gitk, some initially separate tools, git-gui, gitweb, and git-p4). In this case, we know that e83c516 is the one we are probably interested in. It is both the earliest commit and a root commit.

It is not so simple in the general case.

Imagine that libfoo has been in development for a while and keeps its history in a Git repository (libfoo.git). Independently, the “bar” project has also been under development (in bar.git), but not for as long libfoo (the commit with the earliest date in libfoo.git has a date that precedes the commit with the earliest date in bar.git). At some point the developers of “bar” decide to incorporate libfoo into their project by using a subtree merge. Prior to this merge it might have been trivial to determine the “first” commit in bar.git (there was probably only one root commit). After the merge, however, there are multiple root commits and the earliest root commit actually comes from the history of libfoo, not “bar”.

You can find all the root commits of the history DAG like this:

git rev-list --max-parents=0 HEAD

For the record, if --max-parents weren't available, this does also work:

git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$"

If you have useful tags in place, then git name-rev might give you a quick overview of the history:

git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$" | git name-rev --stdin

Bonus

Use this often? Hard to remember? Add a git alias for quick access

git config --global alias.first "rev-list --max-parents=0 HEAD"

Now you can simply do

git first

See whether an item appears more than once in a database column

To expand on Solomon Rutzky's answer, if you are looking for a piece of data that shows up in a range (i.e. more than once but less than 5x), you can use

having count(*) > 1 and count(*) < 5

And you can use whatever qualifiers you desire in there - they don't have to match, it's all just included in the 'having' statement. https://webcheatsheet.com/sql/interactive_sql_tutorial/sql_having.php

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

If you are enabled minifyEnabled and shrinkResources to true in your app gradle file. You need to add the following line in proguard-rules.pro file

-keep class com.yourpackage_name.** { *; }

because minification is removed some important classes in our apk file.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

I haven't worked much with Appcelerator Titanium, but I'll put my understanding of it at the end.

I can speak a bit more to the differences between PhoneGap and Xamarin, as I work with these two 5 (or more) days a week.

If you are already familiar with C# and JavaScript, then the question I guess is, does the business logic lie in an area more suited to JavaScript or C#?

PhoneGap

PhoneGap is designed to allow you to write your applications using JavaScript and HTML, and much of the functionality that they do provide is designed to mimic the current proposed specifications for the functionality that will eventually be available with HTML5. The big benefit of PhoneGap in my opinion is that since you are doing the UI with HTML, it can easily be ported between platforms. The downside is, because you are porting the same UI between platforms, it won't feel quite as at home in any of them. Meaning that, without further tweaking, you can't have an application that feels fully at home in iOS and Android, meaning that it has the iOS and Android styling. The majority of your logic can be written using JavaScript, which means it too can be ported between platforms. If the current PhoneGap API does most of what you want, then it's pretty easy to get up and running. If however, there are things you need from the device that are not in the API, then you get into the fun of Plugin Development, which will be in the native device's development language of choice (with one caveat, but I'll get to that), which means you would likely need to get up to speed quickly in Objective-C, Java, etc. The good thing about this model, is you can usually adapt many different native libraries to serve your purpose, and many libraries already have PhoneGap Plugins. Although you might not have much experience with these languages, there will at least be a plethora of examples to work from.

Xamarin

Xamarin.iOS and Xamarin.Android (also known as MonoTouch and MonoDroid), are designed to allow you to have one library of business logic, and use this within your application, and hook it into your UI. Because it's based on .NET 4.5, you get some awesome lambda notations, LINQ, and a whole bunch of other C# awesomeness, which can make writing your business logic less painful. The downside here is that Xamarin expects that you want to make your applications truly feel native on the device, which means that you will likely end up rewriting your UI for each platform, before hooking it together with the business logic. I have heard about MvvmCross, which is designed to make this easier for you, but I haven't really had an opportunity to look into it yet. If you are familiar with the MVVM system in C#, you may want to have a look at this. When it comes to native libraries, MonoTouch becomes interesting. MonoTouch requires a Binding library to tell your C# code how to link into the underlying Objective-C and Java code. Some of these libraries will already have bindings, but if yours doesn't, creating one can be, interesting. Xamarin has made a tool called Objective Sharpie to help with this process, and for the most part, it will get you 95% of the way there. The remaining 5% will probably take 80% of your time attempting to bind a library.

Update

As noted in the comments below, Xamarin has released Xamarin Forms which is a cross platform abstraction around the platform specific UI components. Definitely worth the look.

PhoneGap / Xamarin Hybrid

Now because I said I would get to it, the caveat mentioned in PhoneGap above, is a Hybrid approach, where you can use PhoneGap for part, and Xamarin for part. I have quite a bit of experience with this, and I would caution you against it. Highly. The problem with this, is it is such a no mans' land that if you ever run into issues, almost no one will have come close to what you're doing, and will question what you're trying to do greatly. It is doable, but it's definitely not fun.

Appcelerator Titanium

As I mentioned before, I haven't worked much with Appcelerator Titanium, So for the differences between them, I will suggest you look at Comparing Titanium and Phonegap or Comparison between Corona, Phonegap, Titanium as it has a very thorough description of the differences. Basically, it appears that though they both use JavaScript, how that JavaScript is interpreted is slightly different. With Titanium, you will be writing your JavaScript to the Titanium SDK, whereas with PhoneGap, you will write your application using the PhoneGap API. As PhoneGap is very HTML5 and JavaScript standards compliant, you can use pretty much any JavaScript libraries you want, such as JQuery. With PhoneGap your user interface will be composed of HTML and CSS. With Titanium, you will benefit from their Cross-platform XML which appears to generate Native components. This means it will definitely have a better native look and feel.

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Sorry, no reputation to add this as a comment. So it goes as an complementary answer.

Depending on how often you will call clock_gettime(), you should keep in mind that only some of the "clocks" are provided by Linux in the VDSO (i.e. do not require a syscall with all the overhead of one -- which only got worse when Linux added the defenses to protect against Spectre-like attacks).

While clock_gettime(CLOCK_MONOTONIC,...), clock_gettime(CLOCK_REALTIME,...), and gettimeofday() are always going to be extremely fast (accelerated by the VDSO), this is not true for, e.g. CLOCK_MONOTONIC_RAW or any of the other POSIX clocks.

This can change with kernel version, and architecture.

Although most programs don't need to pay attention to this, there can be latency spikes in clocks accelerated by the VDSO: if you hit them right when the kernel is updating the shared memory area with the clock counters, it has to wait for the kernel to finish.

Here's the "proof" (GitHub, to keep bots away from kernel.org): https://github.com/torvalds/linux/commit/2aae950b21e4bc789d1fc6668faf67e8748300b7

nodejs - first argument must be a string or Buffer - when using response.write with http.request

response.statusCode is a number, e.g. response.statusCode === 200, not '200'. As the error message says, write expects a string or Buffer object, so you must convert it.

res.write(response.statusCode.toString());

You are also correct about your callback comment though. res.end(); should be inside the callback, just below your write calls.

How can I set the opacity or transparency of a Panel in WinForms?

Based on information found at http://www.windows-tech.info/3/53ee08e46d9cb138.php, I was able to achieve a translucent panel control using the following code.

public class TransparentPanel : Panel
{
    protected override CreateParams CreateParams
    {
        get
        {
            var cp = base.CreateParams;
            cp.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT

            return cp;
        }
    }

    protected override void OnPaint(PaintEventArgs e) =>
        e.Graphics.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
}

The caveat is that any controls that are added to the panel have an opaque background. Nonetheless, the translucent panel was useful for me to block off parts of my WinForms application so that users focus was shifted to the appropriate area of the application.

Double Iteration in List Comprehension

This memory technic helps me a lot:

[ <RETURNED_VALUE> <OUTER_LOOP1> <INNER_LOOP2> <INNER_LOOP3> ... <OPTIONAL_IF> ]

And now you can think about Return + Outer-loop as the only Right Order

Knowing above, the order in list comprehensive even for 3 loops seem easy:


c=[111, 222, 333]
b=[11, 22, 33]
a=[1, 2, 3]

print(
  [
    (i, j, k)                            # <RETURNED_VALUE> 
    for i in a for j in b for k in c     # in order: loop1, loop2, loop3
    if i < 2 and j < 20 and k < 200      # <OPTIONAL_IF>
  ]
)
[(1, 11, 111)]

because the above is just a:

for i in a:                         # outer loop1 GOES SECOND
  for j in b:                       # inner loop2 GOES THIRD
    for k in c:                     # inner loop3 GOES FOURTH
      if i < 2 and j < 20 and k < 200:
        print((i, j, k))            # returned value GOES FIRST

for iterating one nested list/structure, technic is the same: for a from the question:

a = [[1,2],[3,4]]
[i2    for i1 in a      for i2 in i1]
which return [1, 2, 3, 4]

for one another nested level

a = [[[1, 2], [3, 4]], [[5, 6], [7, 8, 9]], [[10]]]
[i3    for i1 in a      for i2 in i1     for i3 in i2]
which return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

and so on

Is it possible to center text in select box?

try this :

select {
    padding-left: 50% !important;
    width: 100%;
}

How to define partitioning of DataFrame?

So to start with some kind of answer : ) - You can't

I am not an expert, but as far as I understand DataFrames, they are not equal to rdd and DataFrame has no such thing as Partitioner.

Generally DataFrame's idea is to provide another level of abstraction that handles such problems itself. The queries on DataFrame are translated into logical plan that is further translated to operations on RDDs. The partitioning you suggested will probably be applied automatically or at least should be.

If you don't trust SparkSQL that it will provide some kind of optimal job, you can always transform DataFrame to RDD[Row] as suggested in of the comments.

Replace comma with newline in sed on MacOS?

The sed on macOS Mojave was released in 2005, so one solution is to install the gnu-sed,

brew install gnu-sed

then use gsed will do as you wish,

gsed 's/,/\n/g' file

If you prefer sed, just sudo sh -c 'echo /usr/local/opt/gnu-sed/libexec/gnubin > /etc/paths.d/brew', which is suggested by brew info gnu-sed. Restart your term, then your sed in command line is gsed.

Java ArrayList - how can I tell if two lists are equal, order not mattering?

I'd say these answers miss a trick.

Bloch, in his essential, wonderful, concise Effective Java, says, in item 47, title "Know and use the libraries", "To summarize, don't reinvent the wheel". And he gives several very clear reasons why not.

There are a few answers here which suggest methods from CollectionUtils in the Apache Commons Collections library but none has spotted the most beautiful, elegant way of answering this question:

Collection<Object> culprits = CollectionUtils.disjunction( list1, list2 );
if( ! culprits.isEmpty() ){
  // ... do something with the culprits, i.e. elements which are not common

}

Culprits: i.e. the elements which are not common to both Lists. Determining which culprits belong to list1 and which to list2 is relatively straightforward using CollectionUtils.intersection( list1, culprits ) and CollectionUtils.intersection( list2, culprits ).
However it tends to fall apart in cases like { "a", "a", "b" } disjunction with { "a", "b", "b" } ... except this is not a failing of the software, but inherent to the nature of the subtleties/ambiguities of the desired task.

You can always examine the source code (l. 287) for a task like this, as produced by the Apache engineers. One benefit of using their code is that it will have been thoroughly tried and tested, with many edge cases and gotchas anticipated and dealt with. You can copy and tweak this code to your heart's content if need be.


NB I was at first disappointed that none of the CollectionUtils methods provides an overloaded version enabling you to impose your own Comparator (so you can redefine equals to suit your purposes).

But from collections4 4.0 there is a new class, Equator which "determines equality between objects of type T". On examination of the source code of collections4 CollectionUtils.java they seem to be using this with some methods, but as far as I can make out this is not applicable to the methods at the top of the file, using the CardinalityHelper class... which include disjunction and intersection.

I surmise that the Apache people haven't got around to this yet because it is non-trivial: you would have to create something like an "AbstractEquatingCollection" class, which instead of using its elements' inherent equals and hashCode methods would instead have to use those of Equator for all the basic methods, such as add, contains, etc. NB in fact when you look at the source code, AbstractCollection does not implement add, nor do its abstract subclasses such as AbstractSet... you have to wait till the concrete classes such as HashSet and ArrayList before add is implemented. Quite a headache.

In the mean time watch this space, I suppose. The obvious interim solution would be to wrap all your elements in a bespoke wrapper class which uses equals and hashCode to implement the kind of equality you want... then manipulate Collections of these wrapper objects.

Spring MVC: Complex object as GET @RequestParam

While answers that refer to @ModelAttribute, @RequestParam, @PathParam and the likes are valid, there is a small gotcha I ran into. The resulting method parameter is a proxy that Spring wraps around your DTO. So, if you attempt to use it in a context that requires your own custom type, you may get some unexpected results.

The following will not work:

@GetMapping(produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CustomDto> request(@ModelAttribute CustomDto dto) {
    return ResponseEntity.ok(dto);
}

In my case, attempting to use it in Jackson binding resulted in a com.fasterxml.jackson.databind.exc.InvalidDefinitionException.

You will need to create a new object from the dto.

google-services.json for different productFlavors

According to Firebase docs you can also use string resources instead of google-services.json.

Because this provider is just reading resources with known names, another option is to add the string resources directly to your app instead of using the Google Services gradle plugin. You can do this by:

  • Removing the google-services plugin from your root build.gradle
  • Deleting the google-services.json from your project
  • Adding the string resources directly
  • Deleting apply plugin: 'com.google.gms.google-services' from your app build.gradle

Example strings.xml:

<string name="google_client_id">XXXXXXXXX.apps.googleusercontent.com</string>
<string name="default_web_client_id">XXXX-XXXXXX.apps.googleusercontent.com</string>
<string name="gcm_defaultSenderId">XXXXXX</string>
<string name="google_api_key">AIzaXXXXXX</string>
<string name="google_app_id">1:XXXXXX:android:XXXXX</string>
<string name="google_crash_reporting_api_key">AIzaXXXXXXX</string>
<string name="project_id">XXXXXXX</string>

How can I get a list of repositories 'apt-get' is checking?

As far as I know, you can't ask apt for what their current sources are. However, you can do what you want using shell tools.

Getting a list of repositories:

grep -h ^deb /etc/apt/sources.list /etc/apt/sources.list.d/* >> current.repos.list

Applying the list:

apt-add-repository << current.repos.list

Regarding getting the repository from a package (installed or available), this will do the trick:

apt-cache policy package_name | grep -m1 http | awk '{ print $2 " " $3 }'

However, that will show you the repository of the latest version available of that package, and you may have more repositories for the same package with older versions. Remove all the grep/awk stuff if you want to see the full list.

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

Ruby - test for array

Are you sure it needs to be an array? You may be able to use respond_to?(method) so your code would work for similar things that aren't necessarily arrays (maybe some other enumberable thing). If you do actually need an array, then the post describing the Array#kind\_of? method is best.

['hello'].respond_to?('each')

How to generate a random string of 20 characters

public String randomString(String chars, int length) {
  Random rand = new Random();
  StringBuilder buf = new StringBuilder();
  for (int i=0; i<length; i++) {
    buf.append(chars.charAt(rand.nextInt(chars.length())));
  }
  return buf.toString();
}

document.getelementbyId will return null if element is not defined?

Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

Demo

Html

<div id="xx"></div>

Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');

   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');

Returning pointer from a function

Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:

int *fun()
{
    int *point;
    *point=12;  <<<<<<  your program crashed here.
    return point;
}

The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.

Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.

int *fun()
{
    int point;
    point = 12;
    return (&point);
}

or almost identically:

int *fun()
{
    int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:

int *fun()
{
    static int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

or

int *fun()
{
    static int point;
    point = 12;
    return (&point);
}

As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.

Check number of arguments passed to a Bash script

Here a simple one liners to check if only one parameter is given otherwise exit the script:

[ "$#" -ne 1 ] && echo "USAGE $0 <PARAMETER>" && exit

Python Pandas replicate rows in dataframe

Appending and concatenating is usually slow in Pandas so I recommend just making a new list of the rows and turning that into a dataframe (unless appending a single row or concatenating a few dataframes).

import pandas as pd

df = pd.DataFrame([
[1,1,'2010-02-05',24924.5,False],
[1,1,'2010-02-12',46039.49,True],
[1,1,'2010-02-19',41595.55,False],
[1,1,'2010-02-26',19403.54,False],
[1,1,'2010-03-05',21827.9,False],
[1,1,'2010-03-12',21043.39,False],
[1,1,'2010-03-19',22136.64,False],
[1,1,'2010-03-26',26229.21,False],
[1,1,'2010-04-02',57258.43,False]
], columns=['Store','Dept','Date','Weekly_Sales','IsHoliday'])

temp_df = []
for row in df.itertuples(index=False):
    if row.IsHoliday:
        temp_df.extend([list(row)]*5)
    else:
        temp_df.append(list(row))

df = pd.DataFrame(temp_df, columns=df.columns)

Angular2 - Focusing a textbox on component load

The original question asked for a way to set focus initially, OR to set focus later, in response to an event. It seems like the correct way to approach this is to make an attribute directive which can be set for any input element, and then to use a custom event to safely trigger the focus method on this input element. To to so, first create the directive:

import { Directive, Input, EventEmitter, ElementRef, Renderer, Inject } from '@angular/core';

@Directive({
    selector: '[focus]'
})
export class FocusDirective {
    @Input('focus') focusEvent: EventEmitter<boolean>;

    constructor(@Inject(ElementRef) private element: ElementRef, private renderer: Renderer) {
    }

    ngOnInit() {
        this.focusEvent.subscribe(event => {
            this.renderer.invokeElementMethod(this.element.nativeElement, 'focus', []);
        });
    }
}

Note that it uses renderer.invokeElementMethod on the nativeElement, which is web worker safe. Notice also that focusEvent is declared as an input.

Then add the following declarations to the Angular 2 component which has the template where you wish to use the new directive to set focus to an input element:

public focusSettingEventEmitter = new EventEmitter<boolean>();

ngAfterViewInit() { // ngOnInit is NOT the right lifecycle event for this.
    this.focusSettingEventEmitter.emit(true);
}
setFocus(): void {
  this.focusSettingEventEmitter.emit(true);
}

Don't forget to import EventEmitter above the component like this:

import { Component, EventEmitter } from '@angular/core';

and in the template for this component, set the new [focus] attribute like this:

<input id="name" type="text" name="name" 
    [(ngModel)]="person.Name" class="form-control"
    [focus]="focusSettingEventEmitter">

Finally, in your module, import and declare the new directive like this:

import { FocusDirective } from './focus.directive';

@NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [AppComponent, AnotherComponent, FocusDirective ],
    bootstrap: [ AppComponent ]
})

To recap: the ngAfterViewInit function will cause the new EventEmitter to emit, and since we assigned this emitter to the [focus] attribute in the input element in our template, and we declared this EventEmitter as an input to the new directive and invoked the focus method in the arrow function that we passed to the subscription to this event, the input element will receive focus after the component is initialized, and whenever setFocus is called.

I had the same need in my own app, and this worked as advertised. Thank you very much to the following: http://blog.thecodecampus.de/angular-2-set-focus-element/

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

This could also happen when your app doesn't actually compile, yet it's still launched in Tomcat. When I saw this happen, it wasn't compiling because the project had a "project specific" JDK specified, and the code was checked out on a machine that didn't have that specific JDK. Eclipse defaulted to a JRE instead, not a JDK, and then the app wasn't compiled.

To fix it in our specific case, we just turned off "Project Specific Settings" here:

"Project | Properties | Java Compiler"

Here's more detailed info on how to do this: https://stackoverflow.com/a/2540730/26510

How to find out if a Python object is a string?

Python 2

Use isinstance(obj, basestring) for an object-to-test obj.

Docs.

HTML embedded PDF iframe

It's downloaded probably because there is not Adobe Reader plug-in installed. In this case, IE (it doesn't matter which version) doesn't know how to render it, and it'll simply download the file (Chrome, for example, has its own embedded PDF renderer).

That said. <iframe> is not best way to display a PDF (do not forget compatibility with mobile browsers, for example Safari). Some browsers will always open that file inside an external application (or in another browser window). Best and most compatible way I found is a little bit tricky but works on all browsers I tried (even pretty outdated):

Keep your <iframe> but do not display a PDF inside it, it'll be filled with an HTML page that consists of an <object> tag. Create an HTML wrapping page for your PDF, it should look like this:

<html>
<body>
    <object data="your_url_to_pdf" type="application/pdf">
        <embed src="your_url_to_pdf" type="application/pdf" />
    </object>
</body>
</html>

Of course, you still need the appropriate plug-in installed in the browser. Also, look at this post if you need to support Safari on mobile devices.

1st. Why nesting <embed> inside <object>? You'll find the answer here on SO. Instead of a nested <embed> tag, you may (should!) provide a custom message for your users (or a built-in viewer, see next paragraph). Nowadays, <object> can be used without worries, and <embed> is useless.

2nd. Why an HTML page? So you can provide a fallback if PDF viewer isn't supported. Internal viewer, plain HTML error messages/options, and so on...

It's tricky to check PDF support so that you may provide an alternate viewer for your customers, take a look at PDF.JS project; it's pretty good but rendering quality - for desktop browsers - isn't as good as a native PDF renderer (I didn't see any difference in mobile browsers because of screen size, I suppose).

PHP - get base64 img string decode and save as jpg (resulting empty image )

Decode and save image as PNG

header('content-type: image/png');

           ob_start();

        $ret = fopen($fullurl, 'r', true, $context);
        $contents = stream_get_contents($ret);
        $base64 = 'data:image/PNG;base64,' . base64_encode($contents);
        echo "<img src=$base64 />" ;


        ob_end_flush();

Search and replace part of string in database

I think 2 update calls should do

update VersionedFields
set Value = replace(value,'<iframe','<a><iframe')

update VersionedFields
set Value = replace(value,'> </iframe>','</a>')

How to clear/remove observable bindings in Knockout.js?

I had a memory leak problem recently and ko.cleanNode(element); wouldn't do it for me -ko.removeNode(element); did. Javascript + Knockout.js memory leak - How to make sure object is being destroyed?

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

No Application Encryption Key Has Been Specified

  1. Copy .env.example to .env:

    cp -a .env.example .env

  2. Generate a key:

    php artisan key:generate

  3. Only then run:

    php artisan serve

Platform.runLater and Task in JavaFX

Use Platform.runLater(...) for quick and simple operations and Task for complex and big operations .

Example: Why Can't we use Platform.runLater(...) for long calculations (Taken from below reference).

Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.

Code using Platform.runLater(...):

final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
    @Override public void run() {
    for (int i = 1; i <= 1000000; i++) {
        final int counter = i;
        Platform.runLater(new Runnable() {
            @Override public void run() {
                bar.setProgress(counter / 1000000.0);
            }
        });
    }
}).start();

This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.

Code using Task :

Task task = new Task<Void>() {
    @Override public Void call() {
        static final int max = 1000000;
        for (int i = 1; i <= max; i++) {
            updateProgress(i, max);
        }
        return null;
    }
};

ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();

it suffers from none of the flaws exhibited in the previous code

Reference : Worker Threading in JavaFX 2.0

Passing parameters to addTarget:action:forControlEvents

Target-Action allows three different forms of action selector:

- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event

How can I escape double quotes in XML attributes values?

From the XML specification:

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "&apos;", and the double-quote character (") as "&quot;".

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

I have got the same issue when tried to get users information without auth.

Check if you have loggen in before any request.

 $uid = $facebook->getUser();

 if ($uid){
      $me = $facebook->api('/me');
 }

The code above should solve your issue.

Angular 4: How to include Bootstrap?

first install bootstrap in your project using npm npm i bootstrap after that open ur style.css file in your project and add this line

@import "~bootstrap/dist/css/bootstrap.css";

and that's it bootstrap added in your project

Find a row in dataGridView based on column and value

If you just want to check if that item exists:

IEnumerable<DataGridViewRow> rows = grdPdfs.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue));
if (rows.Count() == 0) 
{
    // Not Found
} 
else 
{
    // Found
}

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

On Windows 10,

I just solved this issue by doing the following.

  1. Goto my.ini and add these 2 lines under [mysqld]

    skip-log-bin
    log_bin_trust_function_creators = 1
    
  2. restart MySQL service

NoClassDefFoundError on Maven dependency

By default, Maven doesn't bundle dependencies in the JAR file it builds, and you're not providing them on the classpath when you're trying to execute your JAR file at the command-line. This is why the Java VM can't find the library class files when trying to execute your code.

You could manually specify the libraries on the classpath with the -cp parameter, but that quickly becomes tiresome.

A better solution is to "shade" the library code into your output JAR file. There is a Maven plugin called the maven-shade-plugin to do this. You need to register it in your POM, and it will automatically build an "uber-JAR" containing your classes and the classes for your library code too when you run mvn package.

To simply bundle all required libraries, add the following to your POM:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.4</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

Once this is done, you can rerun the commands you used above:

$ mvn package
$ java -cp target/bil138_4-0.0.1-SNAPSHOT.jar tr.edu.hacettepe.cs.b21127113.bil138_4.App

If you want to do further configuration of the shade plugin in terms of what JARs should be included, specifying a Main-Class for an executable JAR file, and so on, see the "Examples" section on the maven-shade-plugin site.

Get controller and action name from within controller?

string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();

How to undo a SQL Server UPDATE query?

If you can catch this in time and you don't have the ability to ROLLBACK or use the transaction log, you can take a backup immediately and use a tool like Redgate's SQL Data Compare to generate a script to "restore" the affected data. This worked like a charm for me. :)

Bash checking if string does not contain other string

Use !=.

if [[ ${testmystring} != *"c0"* ]];then
    # testmystring does not contain c0
fi

See help [[ for more information.

Matplotlib - How to plot a high resolution graph?

For future readers who found this question while trying to save high resolution images from matplotlib as I am, I have tried some of the answers above and elsewhere, and summed them up here.

Best result: plt.savefig('filename.pdf')

and then converting this pdf to a png on the command line so you can use it in powerpoint:

pdftoppm -png -r 300 filename.pdf filename

OR simply opening the pdf and cropping to the image you need in adobe, saving as a png and importing the picture to powerpoint

Less successful test #1: plt.savefig('filename.png', dpi=300)

This does save the image at a bit higher than the normal resolution, but it isn't high enough for publication or some presentations. Using a dpi value of up to 2000 still produced blurry images when viewed close up.

Less successful test #2: plt.savefig('filename.pdf')

This cannot be opened in Microsoft Office Professional Plus 2016 (so no powerpoint), same with Google Slides.

Less successful test #3: plt.savefig('filename.svg')

This also cannot be opened in powerpoint or Google Slides, with the same issue as above.

Less successful test #4: plt.savefig('filename.pdf')

and then converting to png on the command line:

convert -density 300 filename.pdf filename.png

but this is still too blurry when viewed close up.

Less successful test #5: plt.savefig('filename.pdf')

and opening in GIMP, and exporting as a high quality png (increased the file size from ~100 KB to ~75 MB)

Less successful test #6: plt.savefig('filename.pdf')

and then converting to jpeg on the command line:

pdfimages -j filename.pdf filename

This did not produce any errors but did not produce an output on Ubuntu even after changing around several parameters.

jQuery Clone table row

Here you go:

$( table ).delegate( '.tr_clone_add', 'click', function () {
    var thisRow = $( this ).closest( 'tr' )[0];
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});

Live demo: http://jsfiddle.net/RhjxK/4/


Update: The new way of delegating events in jQuery is

$(table).on('click', '.tr_clone_add', function () { … });

Nginx: Job for nginx.service failed because the control process exited

Just write this your work get done

sudo rm /etc/nginx/sites-enabled/default

sudo service nginx restart

systemctl status nginx

Happy Learning

wget: unable to resolve host address `http'

The DNS server seems out of order. You can use another DNS server such as 8.8.8.8. Put nameserver 8.8.8.8 to the first line of /etc/resolv.conf.

Preferred way to create a Scala list

just an example that uses collection.breakOut

scala> val a : List[Int] = (for( x <- 1 to 10 ) yield x * 3)(collection.breakOut)
a: List[Int] = List(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)

scala> val b : List[Int] = (1 to 10).map(_ * 3)(collection.breakOut)
b: List[Int] = List(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)

Change string color with NSAttributedString?

With Swift 4, NSAttributedStringKey has a static property called foregroundColor. foregroundColor has the following declaration:

static let foregroundColor: NSAttributedStringKey

The value of this attribute is a UIColor object. Use this attribute to specify the color of the text during rendering. If you do not specify this attribute, the text is rendered in black.

The following Playground code shows how to set the text color of an NSAttributedString instance with foregroundColor:

import UIKit

let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)

The code below shows a possible UIViewController implementation that relies on NSAttributedString in order to update the text and text color of a UILabel from a UISlider:

import UIKit

enum Status: Int {
    case veryBad = 0, bad, okay, good, veryGood

    var display: (text: String, color: UIColor) {
        switch self {
        case .veryBad:  return ("Very bad", .red)
        case .bad:      return ("Bad", .orange)
        case .okay:     return ("Okay", .yellow)
        case .good:     return ("Good", .green)
        case .veryGood: return ("Very good", .blue)
        }
    }

    static let minimumValue = Status.veryBad.rawValue
    static let maximumValue = Status.veryGood.rawValue
}
final class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var slider: UISlider!
    var currentStatus: Status = Status.veryBad {
        didSet {
            // currentStatus is our model. Observe its changes to update our display
            updateDisplay()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Prepare slider
        slider.minimumValue = Float(Status.minimumValue)
        slider.maximumValue = Float(Status.maximumValue)

        // Set display
        updateDisplay()
    }

    func updateDisplay() {
        let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
        let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
        label.attributedText = attributedString
        slider.value = Float(currentStatus.rawValue)
    }

    @IBAction func updateCurrentStatus(_ sender: UISlider) {
        let value = Int(sender.value.rounded())
        guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
        currentStatus = status
    }

}

Note however that you don't really need to use NSAttributedString for such an example and can simply rely on UILabel's text and textColor properties. Therefore, you can replace your updateDisplay() implementation with the following code:

func updateDisplay() {
    label.text = currentStatus.display.text
    label.textColor = currentStatus.display.color
    slider.value = Float(currentStatus.rawValue)
}

jQuery hover and class selector

On a side note this is more efficient:

$(".menuItem").hover(function(){
    this.style.backgroundColor = "#F00";
}, function() {
    this.style.backgroundColor = "#000";
});

How do I convert array of Objects into one Object in JavaScript?

_x000D_
_x000D_
// original_x000D_
var arr = [{_x000D_
    key: '11',_x000D_
    value: '1100',_x000D_
    $$hashKey: '00X'_x000D_
  },_x000D_
  {_x000D_
    key: '22',_x000D_
    value: '2200',_x000D_
    $$hashKey: '018'_x000D_
  }_x000D_
];_x000D_
_x000D_
// My solution_x000D_
var obj = {};_x000D_
for (let i = 0; i < arr.length; i++) {_x000D_
  obj[arr[i].key] = arr[i].value;_x000D_
}_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

Egit rejected non-fast-forward

  1. Go in Github an create a repo for your new code.
  2. Use the new https or ssh url in Eclise when you are doing the push to upstream;

Understanding the results of Execute Explain Plan in Oracle SQL Developer

FULL is probably referring to a full table scan, which means that no indexes are in use. This is usually indicating that something is wrong, unless the query is supposed to use all the rows in a table.

Cost is a number that signals the sum of the different loads, processor, memory, disk, IO, and high numbers are typically bad. The numbers are added up when moving to the root of the plan, and each branch should be examined to locate the bottlenecks.

You may also want to query v$sql and v$session to get statistics about SQL statements, and this will have detailed metrics for all kind of resources, timings and executions.

Sending arrays with Intent.putExtra

You are setting the extra with an array. You are then trying to get a single int.

Your code should be:

int[] arrayB = extras.getIntArray("numbers");

How to get function parameter names/values dynamically?

I've tried doing this before, but never found a praticial way to get it done. I ended up passing in an object instead and then looping through it.

//define like
function test(args) {
    for(var item in args) {
        alert(item);
        alert(args[item]);
    }
}

//then used like
test({
    name:"Joe",
    age:40,
    admin:bool
});

How to call a Python function from Node.js

Example for people who are from Python background and want to integrate their machine learning model in the Node.js application:

It uses the child_process core module:

const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('python', ['./../pypy.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

It doesn't require sys module in your Python script.

Below is a more modular way of performing the task using Promise:

const express = require('express')
const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./../pypy.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(fromRunpy) {
        console.log(fromRunpy.toString());
        res.end(fromRunpy);
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

Attributes / member variables in interfaces?

Something important has been said by Tom:

if you use the has-a concept, you avoid the issue.

Indeed, if instead of using extends and implements you define two attributes, one of type rectangle, one of type JLabel in your Tile class, then you can define a Rectangle to be either an interface or a class.

Furthermore, I would normally encourage the use of interfaces in connection with has-a, but I guess it would be an overkill in your situation. However, you are the only one that can decide on this point (tradeoff flexibility/over-engineering).

How do I create a simple Qt console application in C++?

You could fire an event into the quit() slot of your application even without connect(). This way, the event-loop does at least one turn and should process the events within your main()-logic:

#include <QCoreApplication>
#include <QTimer>

int main(int argc, char *argv[])
{
    QCoreApplication app( argc, argv );

    // do your thing, once

    QTimer::singleShot( 0, &app, &QCoreApplication::quit );
    return app.exec();
}

Don't forget to place CONFIG += console in your .pro-file, or set consoleApplication: true in your .qbs Project.CppApplication.

CSS Selector "(A or B) and C"?

I found success using the :is() selector:

*:is(.a, .b).c{...}

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");

use hh in place of HH

How to change the project in GCP using CLI commands

Check the available projects by running: gcloud projects list. This will give you a list of projects which you can access. To switch between projects: gcloud config set project <project-id>.

Also, I recommend checking the active config before making any change to gcloud config. You can do so by running: gcloud config list

RSpec: how to test if a method was called?

it "should call 'bar' with appropriate arguments" do
  expect(subject).to receive(:bar).with("an argument I want")
  subject.foo
end

How can I convert string to datetime with format specification in JavaScript?

Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.

How do I check for null values in JavaScript?

You can use lodash module to check value is null or undefined

_.isNil(value)
Example 

 country= "Abc"
    _.isNil(country)
    //false

   state= null
    _.isNil(state)
    //true

city= undefined
    _.isNil(state)
    //true

   pin= true
    _.isNil(pin)
    // false   

Reference link: https://lodash.com/docs/#isNil

How to get config parameters in Symfony2 Twig Templates

In confing.yml

# app/config/config.yml
twig:
  globals:
    version: '%app.version%'

In Twig view

# twig view
{{ version }}

Why are interface variables static and final by default?

static - because Interface cannot have any instance. and final - because we do not need to change it.

How to get html to print return value of javascript function?

<script type="text/javascript">
    document.write("<p>" + Date() + "</p>");
</script>

Is a good example.

Want to upgrade project from Angular v5 to Angular v6

Please run the below comments to update to Angular 6 from Angular 5

  1. ng update @angular/cli
  2. ng update @angular/core
  3. npm install rxjs-compat (In order to support older version rxjs 5.6 )
  4. npm install -g rxjs-tslint (To change from rxjs 5 to rxjs 6 format in code. Install globally then only will work)
  5. rxjs-5-to-6-migrate -p src/tsconfig.app.json (After installing we have to change it in our source code to rxjs6 format)
  6. npm uninstall rxjs-compat (Remove this finally)

Resize jqGrid when browser is resized?

Borrowing from the code at your link you could try something like this:

$(window).bind('resize', function() { 
    // resize the datagrid to fit the page properly:
    $('div.subject').children('div').each(function() {
        $(this).width('auto');
        $(this).find('table').width('100%');
    });
});

This way you're binding directly to the window.onresize event, which actually looks like what you want from your question.

If your grid is set to 100% width though it should automatically expand when its container expands, unless there are some intricacies to the plugin you're using that I don't know about.

Export to xls using angularjs

One starting point could be to use this directive (ng-csv) just download the file as csv and that's something excel can understand

http://ngmodules.org/modules/ng-csv

Maybe you can adapt this code (updated link):

http://jsfiddle.net/Sourabh_/5ups6z84/2/

Altough it seems XMLSS (it warns you before opening the file, if you choose to open the file it will open correctly)

var tableToExcel = (function() {

  var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }

  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))
  }
})()

Bootstrap 3 and Youtube in Modal

Found this in another thread, and it works great on desktop and mobile - which is something that didn't seem true with some of the other solutions. Add this script to the end of your page:

<!--Script stops video from playing when modal is closed-->
<script>
    $("#myModal").on('hidden.bs.modal', function (e) {
        $("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
    });
</script>   

Completely cancel a rebase

Use git rebase --abort. From the official Linux kernel documentation for git rebase:

git rebase --continue | --skip | --abort | --edit-todo

JavaScript backslash (\) in variables is causing an error

You may want to try the following, which is more or less the standard way to escape user input:

function stringEscape(s) {
    return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
    function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }
}

This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.

jQuery bind to Paste Event, how to get the content of the paste

It would appear as though this event has some clipboardData property attached to it (it may be nested within the originalEvent property). The clipboardData contains an array of items and each one of those items has a getAsString() function that you can call. This returns the string representation of what is in the item.

Those items also have a getAsFile() function, as well as some others which are browser specific (e.g. in webkit browsers, there is a webkitGetAsEntry() function).

For my purposes, I needed the string value of what is being pasted. So, I did something similar to this:

$(element).bind("paste", function (e) {
    e.originalEvent.clipboardData.items[0].getAsString(function (pStringRepresentation) {
        debugger; 
        // pStringRepresentation now contains the string representation of what was pasted.
        // This does not include HTML or any markup. Essentially jQuery's $(element).text()
        // function result.
    });
});

You'll want to perform an iteration through the items, keeping a string concatenation result.

The fact that there is an array of items makes me think more work will need to be done, analyzing each item. You'll also want to do some null/value checks.

How do I import other TypeScript files?

Quick Easy Process in Visual Studio

Drag and Drop the file with .ts extension from solution window to editor, it will generate inline reference code like..

/// <reference path="../../components/someclass.ts"/>

PostgreSQL: how to convert from Unix epoch to date?

select to_timestamp(cast(epoch_ms/1000 as bigint))::date

worked for me

PHP Get Site URL Protocol - http vs https

It is not automatic. Your top function looks ok.

How to wait for a number of threads to complete?

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class DoSomethingInAThread implements Runnable
{
   public static void main(String[] args) throws ExecutionException, InterruptedException
   {
      //limit the number of actual threads
      int poolSize = 10;
      ExecutorService service = Executors.newFixedThreadPool(poolSize);
      List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>();

      for (int n = 0; n < 1000; n++)
      {
         Future f = service.submit(new DoSomethingInAThread());
         futures.add(f);
      }

      // wait for all tasks to complete before continuing
      for (Future<Runnable> f : futures)
      {
         f.get();
      }

      //shut down the executor service so that this thread can exit
      service.shutdownNow();
   }

   public void run()
   {
      // do something here
   }
}

Regular expression include and exclude special characters

For the allowed characters you can use

^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$

to validate a complete string that should consist of only allowed characters. Note that - is at the end (because otherwise it'd be a range) and a few characters are escaped.

For the invalid characters you can use

[<>'"/;`%]

to check for them.

To combine both into a single regex you can use

^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])

but you'd need a regex engine that allows lookahead.

Get the height and width of the browser viewport without scrollbars using jquery?

$(document).ready(function() {

  //calculate the window height & add css properties for height 100%

  wh = $( window ).height();

  ww = $( window ).width();

  $(".targeted-div").css({"height": wh, "width": ww});

});

In SQL, how can you "group by" in ranges?

Because the column being sorted on (Range) is a string, string/word sorting is used instead of numeric sorting.

As long as the strings have zeros to pad out the number lengths the sorting should still be semantically correct:

SELECT t.range AS ScoreRange,
       COUNT(*) AS NumberOfOccurrences
  FROM (SELECT CASE
                    WHEN score BETWEEN 0 AND 9 THEN '00-09'
                    WHEN score BETWEEN 10 AND 19 THEN '10-19'
                    ELSE '20-99'
               END AS Range
          FROM Scores) t
 GROUP BY t.Range

If the range is mixed, simply pad an extra zero:

SELECT t.range AS ScoreRange,
       COUNT(*) AS NumberOfOccurrences
  FROM (SELECT CASE
                    WHEN score BETWEEN 0 AND 9 THEN '000-009'
                    WHEN score BETWEEN 10 AND 19 THEN '010-019'
                    WHEN score BETWEEN 20 AND 99 THEN '020-099'
                    ELSE '100-999'
               END AS Range
          FROM Scores) t
 GROUP BY t.Range

"unrecognized selector sent to instance" error in Objective-C

This was the top Google answer for this issue, but I had a different cause/result - I thought I'd add in my two cents in case others stumble across this problem.

I had a similar issue just this morning. I found that if you right click the UI item giving you the issue, you can see what connections have been created. In my case I had a button wired up to two actions. I deleted the actions from the right-click menu and rewired them up and my problem was fixed.

So make sure you actions are wired up right.

Javascript setInterval not working

A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.

Your code, for reference:

function funcName() {
    alert("test");
}

var func = funcName();
var run = setInterval("func",10000)

Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.

When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.

So, when you say:

var func = funcName();

You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.

Then you have this line:

var run = setInterval("func",10000)

The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.

However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:

func
// 10 seconds later....
func
// and so on

However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.

The solution is to give setInterval a function to run instead of a string. So, in this case:

var run = setInterval(funcName, 10000);

Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.

So, another solution for your code would be:

var func = funcName;
var run = setInterval(func, 10000);

However, that's a bit redundant: why use func instead of funcName?

Or you can stay as true as possible to the original code by modifying two bits:

var func = funcName;
var run = setInterval("func()", 10000);

In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.

Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.

setInterval(function () {
    alert("test");
}, 10000);

In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.

Is it possible to ignore one single specific line with Pylint?

I believe you're looking for...

import config.logging_settings  # @UnusedImport

Note the double space before the comment to avoid hitting other formatting warnings.

Also, depending on your IDE (if you're using one), there's probably an option to add the correct ignore rule (e.g., in Eclipse, pressing Ctrl + 1, while the cursor is over the warning, will auto-suggest @UnusedImport).

In plain English, what does "git reset" do?

In general, git reset's function is to take the current branch and reset it to point somewhere else, and possibly bring the index and work tree along. More concretely, if your master branch (currently checked out) is like this:

- A - B - C (HEAD, master)

and you realize you want master to point to B, not C, you will use git reset B to move it there:

- A - B (HEAD, master)      # - C is still here, but there's no branch pointing to it anymore

Digression: This is different from a checkout. If you'd run git checkout B, you'd get this:

- A - B (HEAD) - C (master)

You've ended up in a detached HEAD state. HEAD, work tree, index all match B, but the master branch was left behind at C. If you make a new commit D at this point, you'll get this, which is probably not what you want:

- A - B - C (master)
       \
        D (HEAD)

Remember, reset doesn't make commits, it just updates a branch (which is a pointer to a commit) to point to a different commit. The rest is just details of what happens to your index and work tree.

Use cases

I cover many of the main use cases for git reset within my descriptions of the various options in the next section. It can really be used for a wide variety of things; the common thread is that all of them involve resetting the branch, index, and/or work tree to point to/match a given commit.

Things to be careful of

  • --hard can cause you to really lose work. It modifies your work tree.

  • git reset [options] commit can cause you to (sort of) lose commits. In the toy example above, we lost commit C. It's still in the repo, and you can find it by looking at git reflog show HEAD or git reflog show master, but it's not actually accessible from any branch anymore.

  • Git permanently deletes such commits after 30 days, but until then you can recover C by pointing a branch at it again (git checkout C; git branch <new branch name>).

Arguments

Paraphrasing the man page, most common usage is of the form git reset [<commit>] [paths...], which will reset the given paths to their state from the given commit. If the paths aren't provided, the entire tree is reset, and if the commit isn't provided, it's taken to be HEAD (the current commit). This is a common pattern across git commands (e.g. checkout, diff, log, though the exact semantics vary), so it shouldn't be too surprising.

For example, git reset other-branch path/to/foo resets everything in path/to/foo to its state in other-branch, git reset -- . resets the current directory to its state in HEAD, and a simple git reset resets everything to its state in HEAD.

The main work tree and index options

There are four main options to control what happens to your work tree and index during the reset.

Remember, the index is git's "staging area" - it's where things go when you say git add in preparation to commit.

  • --hard makes everything match the commit you've reset to. This is the easiest to understand, probably. All of your local changes get clobbered. One primary use is blowing away your work but not switching commits: git reset --hard means git reset --hard HEAD, i.e. don't change the branch but get rid of all local changes. The other is simply moving a branch from one place to another, and keeping index/work tree in sync. This is the one that can really make you lose work, because it modifies your work tree. Be very very sure you want to throw away local work before you run any reset --hard.

  • --mixed is the default, i.e. git reset means git reset --mixed. It resets the index, but not the work tree. This means all your files are intact, but any differences between the original commit and the one you reset to will show up as local modifications (or untracked files) with git status. Use this when you realize you made some bad commits, but you want to keep all the work you've done so you can fix it up and recommit. In order to commit, you'll have to add files to the index again (git add ...).

  • --soft doesn't touch the index or work tree. All your files are intact as with --mixed, but all the changes show up as changes to be committed with git status (i.e. checked in in preparation for committing). Use this when you realize you've made some bad commits, but the work's all good - all you need to do is recommit it differently. The index is untouched, so you can commit immediately if you want - the resulting commit will have all the same content as where you were before you reset.

  • --merge was added recently, and is intended to help you abort a failed merge. This is necessary because git merge will actually let you attempt a merge with a dirty work tree (one with local modifications) as long as those modifications are in files unaffected by the merge. git reset --merge resets the index (like --mixed - all changes show up as local modifications), and resets the files affected by the merge, but leaves the others alone. This will hopefully restore everything to how it was before the bad merge. You'll usually use it as git reset --merge (meaning git reset --merge HEAD) because you only want to reset away the merge, not actually move the branch. (HEAD hasn't been updated yet, since the merge failed)

    To be more concrete, suppose you've modified files A and B, and you attempt to merge in a branch which modified files C and D. The merge fails for some reason, and you decide to abort it. You use git reset --merge. It brings C and D back to how they were in HEAD, but leaves your modifications to A and B alone, since they weren't part of the attempted merge.

Want to know more?

I do think man git reset is really quite good for this - perhaps you do need a bit of a sense of the way git works for them to really sink in though. In particular, if you take the time to carefully read them, those tables detailing states of files in index and work tree for all the various options and cases are very very helpful. (But yes, they're very dense - they're conveying an awful lot of the above information in a very concise form.)

Strange notation

The "strange notation" (HEAD^ and HEAD~1) you mention is simply a shorthand for specifying commits, without having to use a hash name like 3ebe3f6. It's fully documented in the "specifying revisions" section of the man page for git-rev-parse, with lots of examples and related syntax. The caret and the tilde actually mean different things:

  • HEAD~ is short for HEAD~1 and means the commit's first parent. HEAD~2 means the commit's first parent's first parent. Think of HEAD~n as "n commits before HEAD" or "the nth generation ancestor of HEAD".
  • HEAD^ (or HEAD^1) also means the commit's first parent. HEAD^2 means the commit's second parent. Remember, a normal merge commit has two parents - the first parent is the merged-into commit, and the second parent is the commit that was merged. In general, merges can actually have arbitrarily many parents (octopus merges).
  • The ^ and ~ operators can be strung together, as in HEAD~3^2, the second parent of the third-generation ancestor of HEAD, HEAD^^2, the second parent of the first parent of HEAD, or even HEAD^^^, which is equivalent to HEAD~3.

caret and tilde

Why does Oracle not find oci.dll?

I was also looking for solving this issue. Maybe this answer will help someone.

In my case similar issue have appeared when I used Oracle Instant Client 18.5 for connecting to DB using Toad 13.1.1.5

To solve it I've downloaded more recent version of OIC - Oracle Instant Client 19.3 and Toad connected to Oracle's DB without issues.

Maybe there was version incompatibility issue. New version of Toad require a new version of oci library.

Both OICs were 64 bit and folders of both of them I've added into the user's Path variable.

Client OS: Win10

Server: OL7.7,

DB: 18c

How to debug an apache virtual host configuration?

I had a new VirtualHost configuration file that was not showing when using the apachectl -S command. After much head scratching I realised that my file did not have suffix ".conf". Once I renamed the file with that suffix my Vhost started showing and working!

bash script use cut command at variable and store result at another variable

You can avoid the loop and cut etc by using:

awk -F ':' '{system("ping " $1);}' config.txt

However it would be better if you post a snippet of your config.txt

Refresh page after form submitting

LOL, I'm just wondering why no one had idea about the PHP header function:

header("Refresh: 0"); // here 0 is in seconds

I use this, so user is not prompt to resubmit data if he refresh the page.

See Refresh a page using PHP for more details

Reliable way to convert a file to a byte[]

byte[] bytes = System.IO.File.ReadAllBytes(filename);

That should do the trick. ReadAllBytes opens the file, reads its contents into a new byte array, then closes it. Here's the MSDN page for that method.

Hide/Show components in react native

You can use the conditions for show and hide the components

constructor(){

    super();

    this.state ={

      isVisible:true

    }
  }

  ToggleFunction = () => {

    this.setState(state => ({

      isVisible: !state.isVisible

    }));

  };

  render() {
  
    return (

      <View style={styles.MainContainer}>

      {

        this.state.isVisible ? <Text style= {{ fontSize: 20, color: "red", textAlign: 'center' }}> Hello World! </Text> : null
      }

      <Button title="Toggle Visibility" onPress={this.ToggleFunction} />

      </View>
    );
  }

Is there StartsWith or Contains in t sql with variables?

StartsWith

a) left(@edition, 15) = 'Express Edition'
b) charindex('Express Edition', @edition) = 1

Contains

charindex('Express Edition', @edition) >= 1

Examples

left function

set @isExpress = case when left(@edition, 15) = 'Express Edition' then 1 else 0 end

iif function (starting with SQL Server 2012)

set @isExpress = iif(left(@edition, 15) = 'Express Edition', 1, 0);

charindex function

set @isExpress = iif(charindex('Express Edition', @edition) = 1, 1, 0);

How to download a file over HTTP?

use wget module:

import wget
wget.download('url')

SqlDataAdapter vs SqlDataReader

DataReader:

  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database

On the other hand, it:

  • Only has one record in memory at a time rather than an entire result set (this can be HUGE)
  • Is about as fast as you can get for that one iteration
  • Allows you start processing results sooner (once the first record is available). For some query types this can also be a very big deal.

DataAdapter/DataSet

  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database

At the cost of:

  • Much higher memory use
  • You wait until all the data is loaded before using any of it

So really it depends on what you're doing, but I tend to prefer a DataReader until I need something that's only supported by a dataset. SqlDataReader is perfect for the common data access case of binding to a read-only grid.

For more info, see the official Microsoft documentation.

Download file inside WebView

webView.setDownloadListener(new DownloadListener()
        {
            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimeType,
                                        long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));
                request.setMimeType(mimeType);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading File...");
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(
                        Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
                                url, contentDisposition, mimeType));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
            }});

Multiple values in single-value context

Yes, there is.

Surprising, huh? You can get a specific value from a multiple return using a simple mute function:

package main

import "fmt"
import "strings"

func µ(a ...interface{}) []interface{} {
    return a
}

type A struct {
    B string
    C func()(string)
}

func main() {
    a := A {
        B:strings.TrimSpace(µ(E())[1].(string)),
        C:µ(G())[0].(func()(string)),
    }

    fmt.Printf ("%s says %s\n", a.B, a.C())
}

func E() (bool, string) {
    return false, "F"
}

func G() (func()(string), bool) {
    return func() string { return "Hello" }, true
}

https://play.golang.org/p/IwqmoKwVm-

Notice how you select the value number just like you would from a slice/array and then the type to get the actual value.

You can read more about the science behind that from this article. Credits to the author.

Extract code country from phone number [libphonenumber]

I have got kept a handy helper method to take care of this based on one answer posted above:

Imports:

import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil

Function:

    fun parseCountryCode( phoneNumberStr: String?): String {
        val phoneUtil = PhoneNumberUtil.getInstance()
        return try {
            // phone must begin with '+'
            val numberProto = phoneUtil.parse(phoneNumberStr, "")
            numberProto.countryCode.toString()
        } catch (e: NumberParseException) {
            ""
        }
    }

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

The best and simple way:

Convert(varchar, {EndTime} - {StartTime}, 108)

Just like Anri noted.

What's the canonical way to check for type in Python?

For more complex type validations I like typeguard's approach of validating based on python type hint annotations:

from typeguard import check_type
from typing import List

try:
    check_type('mylist', [1, 2], List[int])
except TypeError as e:
    print(e)

You can perform very complex validations in very clean and readable fashion.

check_type('foo', [1, 3.14], List[Union[int, float]])
# vs
isinstance(foo, list) and all(isinstance(a, (int, float)) for a in foo) 

Truncate a SQLite table if it exists?

Just do delete. This is from the SQLite documentation:

The Truncate Optimization

"When the WHERE is omitted from a DELETE statement and the table being deleted has no triggers, SQLite uses an optimization to erase the entire table content without having to visit each row of the table individually. This "truncate" optimization makes the delete run much faster. Prior to SQLite version 3.6.5, the truncate optimization also meant that the sqlite3_changes() and sqlite3_total_changes() interfaces and the count_changes pragma will not actually return the number of deleted rows. That problem has been fixed as of version 3.6.5."

How to select a radio button by default?

They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:

<input type="radio" checked="checked">

...and you got it.

Cheers!

Youtube autoplay not working on mobile devices with embedded HTML5 player

As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.

See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512

How to hide "Showing 1 of N Entries" with the dataTables.js library

You can remove it with the bInfo option (http://datatables.net/usage/features#bInfo)

   $('#example').dataTable({
       "bInfo" : false
   });

Update: Since Datatables 1.10.* this option can be used as info, bInfo still works in current nightly build (1.10.10).

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

For CentOS users (at least), one will also get a 404 error trying to access the server on port 8080 on a fresh install if the tomcat-webapps package is not installed.

SELECT DISTINCT on one column

Assuming that you're on SQL Server 2005 or greater, you can use a CTE with ROW_NUMBER():

SELECT  *
FROM    (SELECT ID, SKU, Product,
                ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowNumber
         FROM   MyTable
         WHERE  SKU LIKE 'FOO%') AS a
WHERE   a.RowNumber = 1

How to get cookie expiration date / creation date from javascript?

It's now possible with new chrome update for version 47 for 2016 , you can see it through developer tools on the resources tabenter image description here, select cookies and look for your cookie expiration date under "Expires/Max-age"

2D arrays in Python

Please consider the follwing codes:

from numpy import zeros
scores = zeros((len(chain1),len(chain2)), float)

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

This is an old question, but none of the answers here provide enough context for a beginner to choose which one to pick.

What is make?

make is a traditional Unix utility which reads a Makefile to decide what programs to run to reach a particular goal. Typically, that goal is to build a single piece of software; but make is general enough to be used for various other tasks, too, like assembling a PDF from a collection of TeX source files, or retrieving the newest versions of each of a set of web pages.

Besides encapsulating the steps to reach an individual target, make reduces processing time by avoiding to re-execute steps which are already complete. It does this by comparing time stamps between dependencies; if A depends on B but A is newer than B, there is no need to make A. Of course, in order for this to work properly, the Makefile needs to document all such dependencies.

A: B
    commands to produce A from B

Notice that the indentation needs to consist of a literal tab character. This is a common beginner mistake.

Common Versions of make

The original make was rather pedestrian. Its lineage continues to this day into BSD make, from which nmake is derived. Roughly speaking, this version provides the make functionality defined by POSIX, with a few minor enhancements and variations.

GNU make, by contrast, significantly extends the formalism, to the point where a GNU Makefile is unlikely to work with other versions (or occasionally even older versions of GNU make). There is a convention to call such files GNUmakefile instead of Makefile, but this convention is widely ignored, especially on platforms like Linux where GNU make is the de facto standard make.

Telltale signs that a Makefile uses GNU make conventions are the use of := instead of = for variable assignments (though this is not exclusively a GNU feature) and a plethora of functions like $(shell ...), $(foreach ...), $(patsubst ...) etc.

So Which Do I Need?

Well, it really depends on what you are hoping to accomplish.

If the software you are hoping to build has a vcproj file or similar, you probably want to use that instead, and not try to use make at all.

In the general case, MinGW make is a Windows port of GNU make for Windows, It should generally cope with any Makefile you throw at it.

If you know the software was written to use nmake and you already have it installed, or it is easy for you to obtain, maybe go with that.

You should understand that if the software was not written for, or explicitly ported to, Windows, it is unlikely to compile without significant modifications. In this scenario, getting make to run is the least of your problems, and you will need a good understanding of the differences between the original platform and Windows to have a chance of pulling it off yourself.

In some more detail, if the Makefile contains Unix commands like grep or curl or yacc then your system needs to have those commands installed, too. But quite apart from that, C or C++ (or more generally, source code in any language) which was written for a different platform might simply not work - at all, or as expected (which is often worse) - on Windows.

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

How to style readonly attribute with CSS?

Note that textarea[readonly="readonly"] works if you set readonly="readonly" in HTML but it does NOT work if you set the readOnly-attribute to true or "readonly" via JavaScript.

For the CSS selector to work if you set readOnly with JavaScript you have to use the selector textarea[readonly].

Same behavior in Firefox 14 and Chrome 20.

To be on the safe side, i use both selectors.

textarea[readonly="readonly"], textarea[readonly] {
...
}

Better way to Format Currency Input editText?

I used the implementation Nathan Leigh referenced and Kayvan N's and user2582318's suggested regex to remove all chars except digits to create the following version:

fun EditText.addCurrencyFormatter() {

    // Reference: https://stackoverflow.com/questions/5107901/better-way-to-format-currency-input-edittext/29993290#29993290
    this.addTextChangedListener(object: TextWatcher {

        private var current = ""

        override fun afterTextChanged(s: Editable?) {
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            if (s.toString() != current) {
                [email protected](this)
                // strip off the currency symbol

                // Reference for this replace regex: https://stackoverflow.com/questions/5107901/better-way-to-format-currency-input-edittext/28005836#28005836
                val cleanString = s.toString().replace("\\D".toRegex(), "")
                val parsed = if (cleanString.isBlank()) 0.0 else cleanString.toDouble()
                // format the double into a currency format
                val formated = NumberFormat.getCurrencyInstance()
                        .format(parsed / 100)

                current = formated
                [email protected](formated)
                [email protected](formated.length)

                [email protected](this)
            }
        }
    })

}

This is an extension function in Kotlin which adds the TextWatcher to the TextChangedListener of the EditText.

In order to use it, just:

yourEditText = (EditText) findViewById(R.id.edit_text_your_id);
yourEditText.addCurrencyFormatter()

I hope it helps.

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

Commenting out code blocks in Atom

According to this, cmd + / should do it.

And for Windows and Linux, it is ctrl + /.

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

What is difference between Axios and Fetch?

Fetch and Axios are very similar in functionality, but for more backwards compatibility Axios seems to work better (fetch doesn't work in IE 11 for example, check this post)

Also, if you work with JSON requests, the following are some differences I stumbled upon with.

Fetch JSON post request

let url = 'https://someurl.com';
let options = {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            body: JSON.stringify({
                property_one: value_one,
                property_two: value_two
            })
        };
let response = await fetch(url, options);
let responseOK = response && response.ok;
if (responseOK) {
    let data = await response.json();
    // do something with data
}

Axios JSON post request

let url = 'https://someurl.com';
let options = {
            method: 'POST',
            url: url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data: {
                property_one: value_one,
                property_two: value_two
            }
        };
let response = await axios(options);
let responseOK = response && response.status === 200 && response.statusText === 'OK';
if (responseOK) {
    let data = await response.data;
    // do something with data
}

So:

  • Fetch's body = Axios' data
  • Fetch's body has to be stringified, Axios' data contains the object
  • Fetch has no url in request object, Axios has url in request object
  • Fetch request function includes the url as parameter, Axios request function does not include the url as parameter.
  • Fetch request is ok when response object contains the ok property, Axios request is ok when status is 200 and statusText is 'OK'
  • To get the json object response: in fetch call the json() function on the response object, in Axios get data property of the response object.

Hope this helps.

how does Request.QueryString work?

Request.QueryString["pID"];

Here Request is a object that retrieves the values that the client browser passed to the server during an HTTP request and QueryString is a collection is used to retrieve the variable values in the HTTP query string.

READ MORE@ http://msdn.microsoft.com/en-us/library/ms524784(v=vs.90).aspx

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5 

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

How to add jQuery to an HTML page?

You need this code wrap in tags and put on the end of page. Or create JS file (for example test.js), write this code on it and put on the end of page this tag

Offset a background image from the right using CSS

If you have proportioned elements, you could use:

.valid {
    background-position: 98% center;
}

.half .valid {
    background-position: 96% center;
}

In this example, .valid would be the class with the picture and .half would be a row with half the size of the standard one.

Dirty, but works as a charm and it's reasonably manageable.

Unzip files (7-zip) via cmd command

Doing the following in a command prompt works for me, also adding to my User environment variables worked fine as well:

set PATH=%PATH%;C:\Program Files\7-Zip\
echo %PATH%
7z

You should see as output (or something similar - as this is on my laptop running Windows 7):

C:\Users\Phillip>set PATH=%PATH%;C:\Program Files\7-Zip\

C:\Users\Phillip>echo %PATH%
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Wi
ndows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\
WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\To
ols\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Fil
es (x86)\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Notepad+
+;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\7-Zip\

C:\Users\Phillip>7z

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18

Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]
       [<@listfiles...>]

<Commands>
  a: Add files to archive
  b: Benchmark
  d: Delete files from archive
  e: Extract files from archive (without using directory names)
  l: List contents of archive
  t: Test integrity of archive
  u: Update files to archive
  x: eXtract files with full paths
<Switches>
  -ai[r[-|0]]{@listfile|!wildcard}: Include archives
  -ax[r[-|0]]{@listfile|!wildcard}: eXclude archives
  -bd: Disable percentage indicator
  -i[r[-|0]]{@listfile|!wildcard}: Include filenames
  -m{Parameters}: set compression Method
  -o{Directory}: set Output directory
  -p{Password}: set Password
  -r[-|0]: Recurse subdirectories
  -scs{UTF-8 | WIN | DOS}: set charset for list files
  -sfx[{name}]: Create SFX archive
  -si[{name}]: read data from stdin
  -slt: show technical information for l (List) command
  -so: write data to stdout
  -ssc[-]: set sensitive case mode
  -ssw: compress shared files
  -t{Type}: Set type of archive
  -u[-][p#][q#][r#][x#][y#][z#][!newArchiveName]: Update options
  -v{Size}[b|k|m|g]: Create volumes
  -w[{path}]: assign Work directory. Empty path means a temporary directory
  -x[r[-|0]]]{@listfile|!wildcard}: eXclude filenames
  -y: assume Yes on all queries

How to move or copy files listed by 'find' command in unix?

Actually, you can process the find command output in a copy command in two ways:

  1. If the find command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:

    Syntax:
        find <Path> <Conditions> | xargs cp -t <copy file path>
    Example:
        find -mtime -1 -type f | xargs cp -t inner/
    
  2. But our production data files might contain spaces, so most of time this command is effective:

    Syntax:
       find <path> <condition> -exec cp '{}' <copy path> \;
    
    Example 
       find -mtime -1 -type f -exec cp '{}' inner/ \;
    

In the second example, the last part, the semi-colon is also considered as part of the find command, and should be escaped before pressing Enter. Otherwise you will get an error something like:

find: missing argument to `-exec'

mongodb how to get max value from collections

what about using aggregate framework:

db.collection.aggregate({ $group : { _id: null, max: { $max : "$age" }}});

make an ID in a mysql table auto_increment (after the fact)

I'm guessing that you don't need to re-increment the existing data so, why can't you just run a simple ALTER TABLE command to change the PK's attributes?

Something like:

ALTER TABLE `content` CHANGE `id` `id` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT 

I've tested this code on my own MySQL database and it works but I have not tried it with any meaningful number of records. Once you've altered the row then you need to reset the increment to a number guaranteed not to interfere with any other records.

ALTER TABLE `content` auto_increment = MAX(`id`) + 1

Again, untested but I believe it will work.

DataGridView - how to set column width?

DataGridView1.Columns.Item("Adress").Width = 60
    DataGridView1.Columns.Item("Phone").Width = 30
    DataGridView1.Columns.Item("Name").Width = 40
    DataGridView1.Columns.Item("Etc.").Width = 30

How to get All input of POST in Laravel

It should be at least this:

public function login(Request $loginCredentials){
     $data = $loginCredentials->all();
     return $data['username'];
}

How to set the locale inside a Debian/Ubuntu Docker container?

Just add

ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8

into your Dockerfile. (You may need to make sure the locales package is installed.) Nothing else is needed for the basic operation. Meanwhile, outside of Ubuntu, locale-gen doesn’t accept any arguments, that’s why none of the ‘fixes’ using it work e.g. on Debian. Ubuntu have patched locale-gen to accept a list of locales to generate but the patch at the moment has not been accepted in Debian of anywhere else.

How to read existing text files without defining path

This will load a file in working directory:

        static void Main(string[] args)
        {
            string fileName = System.IO.Path.GetFullPath(Directory.GetCurrentDirectory() + @"\Yourfile.txt");

            Console.WriteLine("Your file content is:");
            using (StreamReader sr = File.OpenText(fileName))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }

            Console.ReadKey();
        }

If your using console you can also do this.It will prompt the user to write the path of the file(including filename with extension).

        static void Main(string[] args)
        {

            Console.WriteLine("****please enter path to your file****");
            Console.Write("Path: ");
            string pth = Console.ReadLine();
            Console.WriteLine();
            Console.WriteLine("Your file content is:");
            using (StreamReader sr = File.OpenText(pth))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }

            Console.ReadKey();
        }

If you use winforms for example try this simple example:

        private void button1_Click(object sender, EventArgs e)
        {
            string pth = "";
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                pth = ofd.FileName;
                textBox1.Text = File.ReadAllText(pth);
            }
        }

How to print a percentage value in python?

You are dividing integers then converting to float. Divide by floats instead.

As a bonus, use the awesome string formatting methods described here: http://docs.python.org/library/string.html#format-specification-mini-language

To specify a percent conversion and precision.

>>> float(1) / float(3)
[Out] 0.33333333333333331

>>> 1.0/3.0
[Out] 0.33333333333333331

>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'

>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'

A great gem!

Get 2 Digit Number For The Month

For me the quickest solution was

DATE_FORMAT(CURDATE(),'%m')

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Custom thread pool in Java 8 parallel stream

There actually is a trick how to execute a parallel operation in a specific fork-join pool. If you execute it as a task in a fork-join pool, it stays there and does not use the common one.

final int parallelism = 4;
ForkJoinPool forkJoinPool = null;
try {
    forkJoinPool = new ForkJoinPool(parallelism);
    final List<Integer> primes = forkJoinPool.submit(() ->
        // Parallel task here, for example
        IntStream.range(1, 1_000_000).parallel()
                .filter(PrimesPrint::isPrime)
                .boxed().collect(Collectors.toList())
    ).get();
    System.out.println(primes);
} catch (InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
} finally {
    if (forkJoinPool != null) {
        forkJoinPool.shutdown();
    }
}

The trick is based on ForkJoinTask.fork which specifies: "Arranges to asynchronously execute this task in the pool the current task is running in, if applicable, or using the ForkJoinPool.commonPool() if not inForkJoinPool()"

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

How to adjust gutter in Bootstrap 3 grid system?

To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.

To learn more about the grid and the columns / gutter widths, please also read:

In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px. When setting @grid-columns:3; and setting @grid-gutter-width:15px; in variables.less you will get:

15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px

Show diff between commits

I always love using the command line and have user friendly tools (with GUI) at my hand. Best of both worlds. Here is how I do it to compare two commits in Git.

You can show the diff between two commits like the following.

Edit your git config file in a TEXT EDITOR:

git config --global -e 

Set up a proper diff tool (user friendly) like Meld like this in Windows in the Git config file:

[difftool "meld"]
cmd = "C:/Program Files (x86)/Meld/Meld.exe" "LOCAL\" \"REMOTE" --label "DIFF (ORIGINAL MY)"
prompt = false
path = C:\Program Files (x86)\Meld\Meld.exe

Meld can be installed using Chocolatey like this from the COMMAND LINE:

choco install meld

Let's define a shell function to help us compare two sha-s (commits) under [alias] in the TEXT EDITOR:

[alias]
showchangesbetween = "!w() { git difftool \"$1\" \"$2\" --dir-diff --ignore-all-space; }; w"

To compare the commits with the help of Meld (or your other favorite diff tool, just type at the COMMAND LINE:

git showchangesbetween somesha123 somesha456

The commit sha-s are easily visible typing

 git log 

for example.

'float' vs. 'double' precision

Do doubles always have 16 significant figures while floats always have 7 significant figures?

No. Doubles always have 53 significant bits and floats always have 24 significant bits (except for denormals, infinities, and NaN values, but those are subjects for a different question). These are binary formats, and you can only speak clearly about the precision of their representations in terms of binary digits (bits).

This is analogous to the question of how many digits can be stored in a binary integer: an unsigned 32 bit integer can store integers with up to 32 bits, which doesn't precisely map to any number of decimal digits: all integers of up to 9 decimal digits can be stored, but a lot of 10-digit numbers can be stored as well.

Why don't doubles have 14 significant figures?

The encoding of a double uses 64 bits (1 bit for the sign, 11 bits for the exponent, 52 explicit significant bits and one implicit bit), which is double the number of bits used to represent a float (32 bits).

How best to determine if an argument is not sent to the JavaScript function

This is one of the few cases where I find the test:

if(! argument2) {  

}

works quite nicely and carries the correct implication syntactically.

(With the simultaneous restriction that I wouldn't allow a legitimate null value for argument2 which has some other meaning; but that would be really confusing.)

EDIT:

This is a really good example of a stylistic difference between loosely-typed and strongly-typed languages; and a stylistic option that javascript affords in spades.

My personal preference (with no criticism meant for other preferences) is minimalism. The less the code has to say, as long as I'm consistent and concise, the less someone else has to comprehend to correctly infer my meaning.

One implication of that preference is that I don't want to - don't find it useful to - pile up a bunch of type-dependency tests. Instead, I try to make the code mean what it looks like it means; and test only for what I really will need to test for.

One of the aggravations I find in some other peoples' code is needing to figure out whether or not they expect, in the larger context, to actually run into the cases they are testing for. Or if they are trying to test for everything possible, on the chance that they don't anticipate the context completely enough. Which means I end up needing to track them down exhaustively in both directions before I can confidently refactor or modify anything. I figure that there's a good chance they might have put those various tests in place because they foresaw circumstances where they would be needed (and which usually aren't apparent to me).

(I consider that a serious downside in the way these folks use dynamic languages. Too often people don't want to give up all the static tests, and end up faking it.)

I've seen this most glaringly in comparing comprehensive ActionScript 3 code with elegant javascript code. The AS3 can be 3 or 4 times the bulk of the js, and the reliability I suspect is at least no better, just because of the number (3-4X) of coding decisions that were made.

As you say, Shog9, YMMV. :D

Consistency of hashCode() on a Java string

I found something about JDK 1.0 and 1.1 and >= 1.2:

In JDK 1.0.x and 1.1.x the hashCode function for long Strings worked by sampling every nth character. This pretty well guaranteed you would have many Strings hashing to the same value, thus slowing down Hashtable lookup. In JDK 1.2 the function has been improved to multiply the result so far by 31 then add the next character in sequence. This is a little slower, but is much better at avoiding collisions. Source: http://mindprod.com/jgloss/hashcode.html

Something different, because you seem to need a number: How about using CRC32 or MD5 instead of hashcode and you are good to go - no discussions and no worries at all...

How to convert integers to characters in C?

In C, int, char, long, etc. are all integers.

They typically have different memory sizes and thus different ranges as in INT_MIN to INT_MAX. char and arrays of char are often used to store characters and strings. Integers are stored in many types: int being the most popular for a balance of speed, size and range.

ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.

int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;

To convert an int to a char, simple assign:

int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4; 

This warning comes up because int typically has a greater range than char and so some loss-of-information may occur. By using the cast (char), the potential loss of info is explicitly directed.

To print the value of an integer:

printf("<%c>\n", c3); // prints <b>

// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>

// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>

printf("<%d>\n", i3); // prints <98>

There are additional issues about printing such as using %hhu or casting when printing an unsigned char, but leave that for later. There is a lot to printf().

How do I resize an image using PIL and maintain its aspect ratio?

A simple method for keeping constrained ratios and passing a max width / height. Not the prettiest but gets the job done and is easy to understand:

def resize(img_path, max_px_size, output_folder):
    with Image.open(img_path) as img:
        width_0, height_0 = img.size
        out_f_name = os.path.split(img_path)[-1]
        out_f_path = os.path.join(output_folder, out_f_name)

        if max((width_0, height_0)) <= max_px_size:
            print('writing {} to disk (no change from original)'.format(out_f_path))
            img.save(out_f_path)
            return

        if width_0 > height_0:
            wpercent = max_px_size / float(width_0)
            hsize = int(float(height_0) * float(wpercent))
            img = img.resize((max_px_size, hsize), Image.ANTIALIAS)
            print('writing {} to disk'.format(out_f_path))
            img.save(out_f_path)
            return

        if width_0 < height_0:
            hpercent = max_px_size / float(height_0)
            wsize = int(float(width_0) * float(hpercent))
            img = img.resize((max_px_size, wsize), Image.ANTIALIAS)
            print('writing {} to disk'.format(out_f_path))
            img.save(out_f_path)
            return

Here's a python script that uses this function to run batch image resizing.

Excel: replace part of cell's string value

What you need to do is as follows:

  1. List item
  2. Select the entire column by clicking once on the corresponding letter or by simply selecting the cells with your mouse.
  3. Press Ctrl+H.
  4. You are now in the "Find and Replace" dialog. Write "Author" in the "Find what" text box.
  5. Write "Authoring" in the "Replace with" text box.
  6. Click the "Replace All" button.

That's it!

Excel compare two columns and highlight duplicates

Suppose you want to compare a column A and column H in a same spreadsheet .

You need to go another column next to these 2 columns and paste this formula : =(Sheet1!A:A=Sheet1!H:H) this will display FALSE or TRUE in the column . So you can use this new column to color the non matching values using conditional color formatting feature .

Python - How to cut a string in Python?

You need to split the string:

>>> s = 'http://www.domain.com/?s=some&two=20'
>>> s.split('&')
['http://www.domain.com/?s=some', 'two=20']

That will return a list as you can see so you can do:

>>> s2 = s.split('&')[0]
>>> print s2
http://www.domain.com/?s=some

CSS scale height to match width - possibly with a formfactor

You can set its before and after to force a constant width-to-height ratio

HTML:

<div class="squared"></div>

CSS:

.squared {
  background: #333;
  width: 300px; 
}
.squared::before {
  content: '';
  padding-top: 100%;
  float: left;
}
.squared::after {
  content: '';
  display: block;
  clear: both;
}

One liner for If string is not null or empty else

Old question, but thought I'd add this to help out,

#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif

WCF timeout exception detailed investigation

I'm having a very similar problem. In the past, this has been related to serialization problems. If you are still having this problem, can you verify that you can correctly serialize the objects you are returning. Specifically, if you are using Linq-To-Sql objects that have relationships, there are known serialization problems if you put a back reference on a child object to the parent object and mark that back reference as a DataMember.

You can verify serialization by writing a console app that serializes and deserializes your objects using the DataContractSerializer on the server side and whatever serialization methods your client uses. For example, in our current application, we have both WPF and Compact Framework clients. I wrote a console app to verify that I can serialize using a DataContractSerializer and deserialize using an XmlDesserializer. You might try that.

Also, if you are returning Linq-To-Sql objects that have child collections, you might try to ensure that you have eagerly loaded them on the server side. Sometimes, because of lazy loading, the objects being returned are not populated and may cause the behavior you are seeing where the request is sent to the service method multiple times.

If you have solved this problem, I'd love to hear how because I'm stuck with it too. I have verified that my issue is not serialization so I'm at a loss.

UPDATE: I'm not sure if it will help you any but the Service Trace Viewer Tool just solved my problem after 5 days of very similar experience to yours. By setting up tracing and then looking at the raw XML, I found the exceptions that were causing my serialization problems. It was related to Linq-to-SQL objects that occasionally had more child objects than could be successfully serialized. Adding the following to your web.config file should enable tracing:

<sharedListeners>
    <add name="sharedListener"
         type="System.Diagnostics.XmlWriterTraceListener"
         initializeData="c:\Temp\servicetrace.svclog" />
  </sharedListeners>
  <sources>
    <source name="System.ServiceModel" switchValue="Verbose, ActivityTracing" >
      <listeners>
        <add name="sharedListener" />
      </listeners>
    </source>
    <source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
      <listeners>
        <add name="sharedListener" />
      </listeners>
    </source>
  </sources>

The resulting file can be opened with the Service Trace Viewer Tool or just in IE to examine the results.

How to decode encrypted wordpress admin password?

MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.

  1. Using compare methods like so:

    <?php
      $db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
      $my_pass = "mypass";
      if ($db_pass === md5($my_pass)) {
        // password is matched
      } else {
        // password didn't match
      }
    
  2. Only for WordPress users. If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass is not only MD5 format it also uses utf8_mb4_cli charset so what to do?

    That's why I use another Approach if I forget my WordPress password I use

    I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )

    EASY is use this :

    1. password = "ARJUNsingh@123"
    2. password_hasing = " $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1 "
    3. Replace your $P$BX5675uhhghfhgfhfhfgftut/0 with my $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1

I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS

WORDPRESS USE THIS

https://developer.wordpress.org/reference/functions/wp_hash_password/

Android offline documentation and sample codes

here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.

https://dl-ssl.google.com/android/repository/docs-17_r02.zip   (129 MB)

Flexbox not working in Internet Explorer 11

According to Flexbugs:

In IE 10-11, min-height declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.

Here are a couple of workarounds:

1. Always fill the viewport + scrollable <aside> and <section>:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1;
  display: flex;
}

aside, section {
  overflow: auto;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

2. Fill the viewport initially + normal page scroll with more content:

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

header,
footer {
  background: #7092bf;
}

main {
  flex: 1 0 auto;
  display: flex;
}

aside {
  flex: 0 0 150px;
  background: #3e48cc;
}

section {
  flex: 1;
  background: #9ad9ea;
}
_x000D_
<header>
  <p>header</p>
</header>

<main>
  <aside>
    <p>aside</p>
  </aside>
  <section>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
    <p>content</p>
  </section>
</main>

<footer>
  <p>footer</p>
</footer>
_x000D_
_x000D_
_x000D_

Passing parameters to a JQuery function

Do you want to pass parameters to another page or to the function only?

If only the function, you don't need to add the $.ajax() tvanfosson added. Just add your function content instead. Like:

function DoAction (id, name ) {
    // ...
    // do anything you want here
    alert ("id: "+id+" - name: "+name);
    //...
}

This will return an alert box with the id and name values.

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx


To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

Interface/enum listing standard mime-type constants

From https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/MediaType.html :

staticjava.lang.String APPLICATION_ATOM_XML             "application/atom+xml"
staticMediaType        APPLICATION_ATOM_XML_TYPE        "application/atom+xml"
staticjava.lang.String APPLICATION_FORM_URLENCODED      "application/x-www-form-urlencoded"
staticMediaType        APPLICATION_FORM_URLENCODED_TYPE "application/x-www-form-urlencoded"
staticjava.lang.String APPLICATION_JSON                 "application/json"
staticMediaType        APPLICATION_JSON_TYPE            "application/json"
staticjava.lang.String APPLICATION_OCTET_STREAM         "application/octet-stream"
staticMediaType        APPLICATION_OCTET_STREAM_TYPE    "application/octet-stream"
staticjava.lang.String APPLICATION_SVG_XML              "application/svg+xml"
staticMediaType        APPLICATION_SVG_XML_TYPE         "application/svg+xml"
staticjava.lang.String APPLICATION_XHTML_XML            "application/xhtml+xml"
staticMediaType        APPLICATION_XHTML_XML_TYPE       "application/xhtml+xml"
staticjava.lang.String APPLICATION_XML                  "application/xml"
staticMediaType        APPLICATION_XML_TYPE             "application/xml"
staticjava.lang.String MEDIA_TYPE_WILDCARD              The value of a type or subtype wildcard: "*"
staticjava.lang.String MULTIPART_FORM_DATA              "multipart/form-data"
staticMediaType        MULTIPART_FORM_DATA_TYPE         "multipart/form-data"
staticjava.lang.String TEXT_HTML                        "text/html"
staticMediaType        TEXT_HTML_TYPE                   "text/html"
staticjava.lang.String TEXT_PLAIN                       "text/plain"
staticMediaType        TEXT_PLAIN_TYPE                  "text/plain"
staticjava.lang.String TEXT_XML                         "text/xml"
staticMediaType        TEXT_XML_TYPE                    "text/xml"
staticjava.lang.String WILDCARD                         "*/*"
staticMediaType        WILDCARD_TYPE                    "*/*"

How to use componentWillMount() in React Hooks?

You cannot use any of the existing lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount etc.) in a hook. They can only be used in class components. And with Hooks you can only use in functional components. The line below comes from the React doc:

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

suggest is, you can mimic these lifecycle method from class component in a functional components.

Code inside componentDidMount run once when the component is mounted. useEffect hook equivalent for this behaviour is

useEffect(() => {
  // Your code here
}, []);

Notice the second parameter here (empty array). This will run only once.

Without the second parameter the useEffect hook will be called on every render of the component which can be dangerous.

useEffect(() => {
  // Your code here
});

componentWillUnmount is use for cleanup (like removing event listeners, cancel the timer etc). Say you are adding a event listener in componentDidMount and removing it in componentWillUnmount as below.

componentDidMount() {
  window.addEventListener('mousemove', () => {})
}

componentWillUnmount() {
  window.removeEventListener('mousemove', () => {})
}

Hook equivalent of above code will be as follows

useEffect(() => {
  window.addEventListener('mousemove', () => {});

  // returned function will be called on component unmount 
  return () => {
    window.removeEventListener('mousemove', () => {})
  }
}, [])

How do you redirect to a page using the POST verb?

HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page. You'll probably have to just write the code for your page to accept GET requests as well as POST requests.

How to make a submit out of a <a href...>...</a> link?

Something like this page ?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>BSO Communication</title>

<style type="text/css">
.submit {
    border : 0;
    background : url(ok.gif) left top no-repeat;
    height : 24px;
    width : 24px;
    cursor : pointer;
    text-indent : -9999px;
}
html:first-child .submit {
    padding-left : 1000px;
}
</style>
<!--[if IE]>
<style type="text/css">
.submit {
    text-indent : 0;
    color : expression(this.value = '');
}
</style>
<![endif]-->
</head>

<body>
    <h1>Display input submit as image with CSS</h1>

    <p>Take a look at <a href="/2007/07/26/afficher-un-input-submit-comme-une-image/">the related article</a> (in french).</p>
    <form action="" method="get">
        <fieldset>
            <legend>Some form</legend>
            <p class="field">
                <label for="input">Some value</label>

                <input type="text" id="input" name="value" />
                <input type="submit" class="submit" />
            </p>
        </fieldset>
    </form>

    <hr />
    <p>This page is part of the <a href="http://www.bsohq.fr">BSO Communication blog</a>.</p>

</body>
</html>

How do I get the information from a meta tag with JavaScript?

There is an easier way:

document.getElementsByName('name of metatag')[0].getAttribute('content')

How to change the font color of a disabled TextBox?

NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor of the TextBox.


I think what you really want to do is enable the TextBox and set the ReadOnly property to true.

It's a bit tricky to change the color of the text in a disabled TextBox. I think you'd probably have to subclass and override the OnPaint event.

ReadOnly though should give you the same result as !Enabled and allow you to maintain control of the color and formatting of the TextBox. I think it will also still support selecting and copying text from the TextBox which is not possible with a disabled TextBox.

Another simple alternative is to use a Label instead of a TextBox.

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

if you get an error as Parameter 'element' implicitly has an 'any' type.Vetur(7006) in vueJs

with the error:

 exportColumns.forEach(element=> {
      if (element.command !== undefined) {
        let d = element.command.findIndex(x => x.name === "destroy");

you can fixed it by defining thoes variables as any as follow.

corrected code:

exportColumns.forEach((element: any) => {
      if (element.command !== undefined) {
        let d = element.command.findIndex((x: any) => x.name === "destroy");

proper way to sudo over ssh

Sudo over SSH passing a password, no tty required:

You can use sudo over ssh without forcing ssh to have a pseudo-tty (without the use of the ssh "-t" switch) by telling sudo not to require an interactive password and to just grab the password off stdin. You do this by using the "-S" switch on sudo. This makes sudo listen for the password on stdin, and stop listening when it sees a newline.

Example 1 - Simple Remote Command

In this example, we send a simple whoami command:

$ ssh user@server cat \| sudo --prompt="" -S -- whoami << EOF
> <remote_sudo_password>
root

We're telling sudo not to issue a prompt, and to take its input from stdin. This makes the sudo password passing completely silent so the only response you get back is the output from whoami.

This technique has the benefit of allowing you to run programs through sudo over ssh that themselves require stdin input. This is because sudo is consuming the password over the first line of stdin, then letting whatever program it runs continue to grab stdin.

Example 2 - Remote Command That Requires Its Own stdin

In the following example, the remote command "cat" is executed through sudo, and we are providing some extra lines through stdin for the remote cat to display.

$ ssh user@server cat \| sudo --prompt="" -S -- "cat" << EOF
> <remote_sudo_password>
> Extra line1
> Extra line2
> EOF
Extra line1
Extra line2

The output demonstrates that the <remote_sudo_password> line is being consumed by sudo, and that the remotely executed cat is then displaying the extra lines.

An example of where this would be beneficial is if you want to use ssh to pass a password to a privileged command without using the command line. Say, if you want to mount a remote encrypted container over ssh.

Example 3 - Mounting a Remote VeraCrypt Container

In this example script, we are remotely mounting a VeraCrypt container through sudo without any extra prompting text:

#!/bin/sh
ssh user@server cat \| sudo --prompt="" -S -- "veracrypt --non-interactive --stdin --keyfiles=/path/to/test.key /path/to/test.img /mnt/mountpoint" << EOF
SudoPassword
VeraCryptContainerPassword
EOF

It should be noted that in all the command-line examples above (everything except the script) the << EOF construct on the command line will cause the everything typed, including the password, to be recorded in the local machine's .bash_history. It is therefore highly recommended that for real-world use you either use do it entirely through a script, like the veracrypt example above, or, if on the command line then put the password in a file and redirect that file through ssh.

Example 1a - Example 1 Without Local Command-Line Password

The first example would thus become:

$ cat text_file_with_sudo_password | ssh user@server cat \| sudo --prompt="" -S -- whoami
root

Example 2a - Example 2 Without Local Command-Line Password

and the second example would become:

$ cat text_file_with_sudo_password - << EOF | ssh va1der.net cat \| sudo --prompt="" -S -- cat
> Extra line1
> Extra line2
> EOF
Extra line1
Extra line2

Putting the password in a separate file is unnecessary if you are putting the whole thing in a script, since the contents of scripts do not end up in your history. It still may be useful, though, in case you want to allow users who should not see the password to execute the script.

How to zip a whole folder using PHP

For anyone reading this post and looking for a why to zip the files using addFile instead of addFromString, that does not zip the files with their absolute path (just zips the files and nothing else), see my question and answer here

Laravel Password & Password_Confirmation Validation

You can use the confirmed validation rule.

$this->validate($request, [
    'name' => 'required|min:3|max:50',
    'email' => 'email',
    'vat_number' => 'max:13',
    'password' => 'required|confirmed|min:6',
]);

What does .pack() do?

The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

I had the same issue when using an .exe to install a Python package (because I use Anaconda and it didn't add Python to the registry). I fixed the problem by running this script:

#
# script to register Python 2.0 or later for use with 
# Python extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/[email protected]/msg10512.html

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_CURRENT_USER, regpath)
    except EnvironmentError as e:
        try:
            reg = CreateKey(HKEY_CURRENT_USER, regpath)
            SetValue(reg, installkey, REG_SZ, installpath)
            SetValue(reg, pythonkey, REG_SZ, pythonpath)
            CloseKey(reg)
        except:
            print "*** Unable to register!"
            return
        print "--- Python", version, "is now registered!"
        return
    if (QueryValue(reg, installkey) == installpath and
        QueryValue(reg, pythonkey) == pythonpath):
        CloseKey(reg)
        print "=== Python", version, "is already registered!"
        return
    CloseKey(reg)
    print "*** Unable to register!"
    print "*** You probably have another Python installation!"

if __name__ == "__main__":
    RegisterPy()

How to force ViewPager to re-instantiate its items

public class DayFlipper extends ViewPager {

private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return DayFlipper.DAY_HISTORY;
    }

    @Override
    public void startUpdate(View container) {
    }

    @Override
    public Object instantiateItem(View container, int position) {
        Log.d(TAG, "instantiateItem(): " + position);

        Date d = DateHelper.getBot();
        for (int i = 0; i < position; i++) {
            d = DateHelper.getTomorrow(d);
        }

        d = DateHelper.normalize(d);

        CubbiesView cv = new CubbiesView(mContext);
        cv.setLifeDate(d);
        ((ViewPager) container).addView(cv, 0);
        // add map
        cv.setCubbieMap(mMap);
        cv.initEntries(d);
adpter = FlipperAdapter.this;
        return cv;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((CubbiesView) object);
    }

    @Override
    public void finishUpdate(View container) {

    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((CubbiesView) object);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {

    }

}

    ...

    public void refresh() {
    adapter().notifyDataSetChanged();
}
}

try this.

how to hide a vertical scroll bar when not needed

overflow: auto (or overflow-y: auto) is the correct way to go.

The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.

Try this: http://jsfiddle.net/G9rfq/1/

I set overflow:auto on the text box, and made the textbox the same size as the div.

Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen. Also your div isn't closed.

How to detect window.print() finish

It works for me with $(window).focus().

var w;
var src = 'http://pagetoprint';
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
    w = $('<iframe></iframe>');
    w.attr('src', src);
    w.css('display', 'none');
    $('body').append(w);
    w.load(function() {
        w[0].focus();
        w[0].contentWindow.print();
    });
    $(window).focus(function() {
        console.log('After print');
    });
}
else {
    w = window.open(src);
    $(w).unload(function() {
        console.log('After print');
    });
}

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

This also includes the last date

$begin = new DateTime( "2015-07-03" );
$end   = new DateTime( "2015-07-09" );

for($i = $begin; $i <= $end; $i->modify('+1 day')){
    echo $i->format("Y-m-d");
}

If you dont need the last date just remove = from the condition.

How can I update a row in a DataTable in VB.NET?

The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.

To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse

dtResult.Rows(i)("Foo") = strVerse

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

Up to Android 7.1 (SDK 25)

Until Android 7.1 you will get it with:

Build.SERIAL

From Android 8 (SDK 26)

On Android 8 (SDK 26) and above, this field will return UNKNOWN and must be accessed with:

Build.getSerial()

which requires the dangerous permission android.permission.READ_PHONE_STATE.

From Android Q (SDK 29)

Since Android Q using Build.getSerial() gets a bit more complicated by requiring:

android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE (which can only be acquired by system apps), or for the calling package to be the device or profile owner and have the READ_PHONE_STATE permission. This means most apps won't be able to uses this feature. See the Android Q announcement from Google.

See Android SDK reference


Best Practice for Unique Device Identifier

If you just require a unique identifier, it's best to avoid using hardware identifiers as Google continuously tries to make it harder to access them for privacy reasons. You could just generate a UUID.randomUUID().toString(); and save it the first time it needs to be accessed in e.g. shared preferences. Alternatively you could use ANDROID_ID which is a 8 byte long hex string unique to the device, user and (only Android 8+) app installation. For more info on that topic, see Best practices for unique identifiers.

How to create a floating action button (FAB) in android, using AppCompat v21?

Here is one aditional free Floating Action Button library for Android It has many customizations and requires SDK version 9 and higher

enter image description here

Full Demo Video