Programs & Examples On #Sunstudio

Reading file contents on the client-side in javascript in various browsers

Edited to add information about the File API

Since I originally wrote this answer, the File API has been proposed as a standard and implemented in most browsers (as of IE 10, which added support for FileReader API described here, though not yet the File API). The API is a bit more complicated than the older Mozilla API, as it is designed to support asynchronous reading of files, better support for binary files and decoding of different text encodings. There is some documentation available on the Mozilla Developer Network as well as various examples online. You would use it as follows:

var file = document.getElementById("fileForUpload").files[0];
if (file) {
    var reader = new FileReader();
    reader.readAsText(file, "UTF-8");
    reader.onload = function (evt) {
        document.getElementById("fileContents").innerHTML = evt.target.result;
    }
    reader.onerror = function (evt) {
        document.getElementById("fileContents").innerHTML = "error reading file";
    }
}

Original answer

There does not appear to be a way to do this in WebKit (thus, Safari and Chrome). The only keys that a File object has are fileName and fileSize. According to the commit message for the File and FileList support, these are inspired by Mozilla's File object, but they appear to support only a subset of the features.

If you would like to change this, you could always send a patch to the WebKit project. Another possibility would be to propose the Mozilla API for inclusion in HTML 5; the WHATWG mailing list is probably the best place to do that. If you do that, then it is much more likely that there will be a cross-browser way to do this, at least in a couple years time. Of course, submitting either a patch or a proposal for inclusion to HTML 5 does mean some work defending the idea, but the fact that Firefox already implements it gives you something to start with.

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Try to open Services Window, by writing services.msc into Start->Run and hit Enter.

When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.

How do I redirect a user when a button is clicked?

If, like me, you don't like to rely on JavaScript for links on buttons. You can also use a anchor and style it like your buttons using CSS.

<a href="/Controller/View" class="Button">Text</a>

C# - Making a Process.Start wait until the process has start-up

I agree with Tom. In addition, to check the processes while performing Thread.Sleep, check the running processes. Something like:

bool found = 0;
while (!found)
{
    foreach (Process clsProcess in Process.GetProcesses())
        if (clsProcess.Name == Name)
            found = true;

    Thread.CurrentThread.Sleep(1000);
}

Sort array of objects by single key with date value

As for today, answers of @knowbody (https://stackoverflow.com/a/42418963/6778546) and @Rocket Hazmat (https://stackoverflow.com/a/8837511/6778546) can be combined to provide for ES2015 support and correct date handling:

arr.sort((a, b) => {
   const dateA = new Date(a.updated_at);
   const dateB = new Date(b.updated_at);
   return dateA - dateB;
});

Handling the TAB character in Java

Or you could just perform a trim() on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We faced the same problem:

ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log

In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.

How to use onClick() or onSelect() on option tag in a JSP page?

<html>
<head>
<title>Cars</title>
</head>
<body >

<h1>Cars</h1>
    <p>Name </p>
        <select id="selectBox" onchange="myFunction(value);">
            <option value="volvo" >Volvo</option>
            <option value="saab"  >Saab</option>
            <option value="mercedes">Mercedes</option>
        </select>        
<p id="result"> Price : </p>
<script>
function myFunction($value)
{       
    if($value=="volvo")
    {document.getElementById("result").innerHTML = "30L";}
    else if($value=="saab")
    {document.getElementById("result").innerHTML = "40L";}
     else if($value=="mercedes")
    {document.getElementById("result").innerHTML = "50L";}
}
</script>
</body>
</html>```

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

laravel 5.3 new Auth::routes()

Here's Laravel 5.7, Laravel 5.8, Laravel 6.0, Laravel 7.0, and Laravel 8.0 (note a minor bc change in 6.0 to the email verification route).

// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update');

// Confirm Password (added in v6.2)
Route::get('password/confirm', 'Auth\ConfirmPasswordController@showConfirmForm')->name('password.confirm');
Route::post('password/confirm', 'Auth\ConfirmPasswordController@confirm');

// Email Verification Routes...
Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}/{hash}', 'Auth\VerificationController@verify')->name('verification.verify'); // v6.x
/* Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify'); // v5.x */
Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');

You can verify these routes here:

Adding days to a date in Java

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 5); // Adding 5 days
String output = sdf.format(c.getTime());
System.out.println(output);

How to uncheck checkbox using jQuery Uniform library

Just do this:

$('#checkbox').prop('checked',true).uniform('refresh');

is inaccessible due to its protection level

In your Main method, you're trying to access, for instance, club (which is protected), when you should be accessing myclub which is the public property that you created.

How to select into a variable in PL/SQL when the result might be null?

I would recommend using a cursor. A cursor fetch is always a single row (unless you use a bulk collection), and cursors do not automatically throw no_data_found or too_many_rows exceptions; although you may inspect the cursor attribute once opened to determine if you have a row and how many.

declare
v_column my_table.column%type;
l_count pls_integer;
cursor my_cursor is
  select count(*) from my_table where ...;

begin
  open my_cursor;
    fetch my_cursor into l_count;
  close my_cursor;

  if l_count = 1 then
    select whse_code into v_column from my_table where ...;
  else
    v_column := null;
  end if;
end;

Or, even more simple:

    declare
    v_column my_table.column%type;
    cursor my_cursor is
      select column from my_table where ...;

    begin
      open my_cursor;
        fetch my_cursor into v_column;
        -- Optional IF .. THEN based on FOUND or NOTFOUND
        -- Not really needed if v_column is not set
        if my_cursor%notfound then
          v_column := null;
        end if;
      close my_cursor;
    end;

How can I check if a program exists from a Bash script?

In case you want to check if a program exists and is really a program, not a Bash built-in command, then command, type and hash are not appropriate for testing as they all return 0 exit status for built-in commands.

For example, there is the time program which offers more features than the time built-in command. To check if the program exists, I would suggest using which as in the following example:

# First check if the time program exists
timeProg=`which time`
if [ "$timeProg" = "" ]
then
  echo "The time program does not exist on this system."
  exit 1
fi

# Invoke the time program
$timeProg --quiet -o result.txt -f "%S %U + p" du -sk ~
echo "Total CPU time: `dc -f result.txt` seconds"
rm result.txt

javascript how to create a validation error message without using alert

You need to stop the submission if an error occured:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}

How can I define fieldset border color?

I added it for all fieldsets with

fieldset {
        border: 1px solid lightgray;
    }

I didnt work if I set it separately using for example

border-color : red

. Then a black line was drawn next to the red line.

What is FCM token in Firebase?

Here is simple steps add this gradle:

dependencies {
  compile "com.google.firebase:firebase-messaging:9.0.0"
}

No extra permission are needed in manifest like GCM. No receiver is needed to manifest like GCM. With FCM, com.google.android.gms.gcm.GcmReceiver is added automatically.

Migrate your listener service

A service extending InstanceIDListenerService is now required only if you want to access the FCM token.

This is needed if you want to

  • Manage device tokens to send a messages to single device directly, or Send messages to device group, or
  • Send messages to device group, or
  • Subscribe devices to topics with the server subscription management API.

Add Service in manifest

<service
    android:name=".MyInstanceIDListenerService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>

<service
    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

Change MyInstanceIDListenerService to extend FirebaseInstanceIdService, and update code to listen for token updates and get the token whenever a new token is generated.

public class MyInstanceIDListenerService extends FirebaseInstanceIdService {

  ...

  /**
   * Called if InstanceID token is updated. This may occur if the security of
   * the previous token had been compromised. Note that this is also called
   * when the InstanceID token is initially generated, so this is where
   * you retrieve the token.
   */
  // [START refresh_token]
  @Override
  public void onTokenRefresh() {
      // Get updated InstanceID token.
      String refreshedToken = FirebaseInstanceId.getInstance().getToken();
      Log.d(TAG, "Refreshed token: " + refreshedToken);
      // TODO: Implement this method to send any registration to your app's servers.
      sendRegistrationToServer(refreshedToken);
  }

}

For more information visit

  1. How to import former GCM Projects into Firebase
  2. How to force a token refresh
  3. How to access the token
  4. How to set up firebase

Add swipe to delete UITableViewCell

In Swift 4 tableview add, swipe to delete UITableViewCell

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "delete") { (action, indexPath) in
        // delete item at indexPath

    }
    return [delete]
}

Why does sed not replace all occurrences?

You should add the g modifier so that sed performs a global substitution of the contents of the pattern buffer:

echo dog dog dos | sed -e 's:dog:log:g'

For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6

The official documentation for GNU sed is available at http://www.gnu.org/software/sed/manual/

SQL Server 2008 can't login with newly created user

Login to Server as Admin

Go To Security > Logins > New Login

Step 1:

Login Name : SomeName

Step 2:

Select  SQL Server / Windows Authentication.

More Info on, what is the differences between sql server authentication and windows authentication..?

Choose Default DB and Language of your choice

Click OK

Try to connect with the New User Credentials, It will prompt you to change the password. Change and login

OR

Try with query :

USE [master] -- Default DB
GO

CREATE LOGIN [Username] WITH PASSWORD=N'123456', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO

--123456 is the Password And Username is Login User 
ALTER LOGIN [Username] enable -- Enable or to Disable User
GO

Rebasing a Git merge commit

  • From your merge commit
  • Cherry-pick the new change which should be easy
  • copy your stuff
  • redo the merge and resolve the conflicts by just copying the files from your local copy ;)

SSH Key - Still asking for password and passphrase

Generally, here are the steps to allow you make a remote connection to your server using ssh without password:

  • Create a pair of rsa private and public key

    $ ssh-keygen -t rsa -b 4096 -C "your comments"
    
  • Copy your public key and login to your remote server

  • Add your public key to .ssh/authorized_keys

  • If you have multiple ssh keys in your computer you might to add your key using ssh-add

    $ ssh-add /path/to/private/key

  • Then try ssh to your server

    $ ssh username@your_ip_address

Source: http://diary-of-programmer.blogspot.com/2018/08/tips-how-to-ssh-to-your-digitalocean.html

How to enter a series of numbers automatically in Excel

I have a very simple answer. Just put this formula in cell A2:

=Max($A$1:A1)+1

and fill down.

This sets row number automatically, even if you remove some rows or sort rows.

Autosorting numbers of row

Play audio file from the assets directory

enter image description here

start sound

startSound("mp3/ba.mp3");

method

private void startSound(String filename) {
    AssetFileDescriptor afd = null;
    try {
        afd = getResources().getAssets().openFd(filename);
    } catch (IOException e) {
        e.printStackTrace();
    }
    MediaPlayer player = new MediaPlayer();
    try {
        assert afd != null;
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        player.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    player.start();
}

How to compress a String in Java?

Compression algorithms almost always have some form of space overhead, which means that they are only effective when compressing data which is sufficiently large that the overhead is smaller than the amount of saved space.

Compressing a string which is only 20 characters long is not too easy, and it is not always possible. If you have repetition, Huffman Coding or simple run-length encoding might be able to compress, but probably not by very much.

getActionBar() returns null

Try extending your Activity class from ActionBarActivity. This solved it for me. Do something like the following:

public class MyActivity extends ActionBarActivity
{
  . . .

In my case the class was extending only from Activity.

HTML Text with tags to formatted text in an Excel cell

I ran into the same error that BornToCode first identified in the comments of the original solution. Being unfamiliar with Excel and VBA it took me a second to figure out how to implement tiQU's solution. So I'm posting it as a "For Dummies" solution below

  1. First enable developer mode in Excel: Link
  2. Select the Developer Tab > Visual Basic
  3. Click View > Code
  4. Paste the code below updating the lines that require cell references to be correct.
  5. Click the Green Run Arrow or press F5
Sub Sample()
    Dim Ie As Object
    Set Ie = CreateObject("InternetExplorer.Application")
    With Ie
        .Visible = False
        .Navigate "about:blank"
        .document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
             'update to the cell that contains HTML you want converted
        .ExecWB 17, 0
             'Select all contents in browser
        .ExecWB 12, 2
             'Copy them
        ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
             'update to cell you want converted HTML pasted in
        .Quit
    End With
End Sub

Simplest way to merge ES6 Maps/Sets?

Edit:

I benchmarked my original solution against other solutions suggests here and found that it is very inefficient.

The benchmark itself is very interesting (link) It compares 3 solutions (higher is better):

  • @fregante (formerly called @bfred.it) solution, which adds values one by one (14,955 op/sec)
  • @jameslk's solution, which uses a self invoking generator (5,089 op/sec)
  • my own, which uses reduce & spread (3,434 op/sec)

As you can see, @fregante's solution is definitely the winner.

Performance + Immutability

With that in mind, here's a slightly modified version which doesn't mutates the original set and excepts a variable number of iterables to combine as arguments:

function union(...iterables) {
  const set = new Set();

  for (const iterable of iterables) {
    for (const item of iterable) {
      set.add(item);
    }
  }

  return set;
}

Usage:

const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 5]);
const c = new Set([4, 5, 6]);

union(a,b,c) // {1, 2, 3, 4, 5, 6}

Original Answer

I would like to suggest another approach, using reduce and the spread operator:

Implementation

function union (sets) {
  return sets.reduce((combined, list) => {
    return new Set([...combined, ...list]);
  }, new Set());
}

Usage:

const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 5]);
const c = new Set([4, 5, 6]);

union([a, b, c]) // {1, 2, 3, 4, 5, 6}

Tip:

We can also make use of the rest operator to make the interface a bit nicer:

function union (...sets) {
  return sets.reduce((combined, list) => {
    return new Set([...combined, ...list]);
  }, new Set());
}

Now, instead of passing an array of sets, we can pass an arbitrary number of arguments of sets:

union(a, b, c) // {1, 2, 3, 4, 5, 6}

Hide particular div onload and then show div after click

The second time you're referring to div2, you're not using the # id selector.

There's no element named div2.

how to use sqltransaction in c#

Well, I don't understand why are you used transaction in case when you make a select.

Transaction is useful when you make changes (add, edit or delete) data from database.

Remove transaction unless you use insert, update or delete statements

The cause of "bad magic number" error when loading a workspace and how to avoid it?

I got the error when building an R package (using roxygen2)

The cause in my case was that I had saved data/mydata.RData with saveRDS() rather than save(). E.g. save(iris, file="data/iris.RData")

This fixed the issue for me. I found this info here

Also note that with save() / load() the object is loaded in with the same name it is initially saved with (i.e you can't rename it until it's already loaded into the R environment under the name it had when you initially saved it).

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

If you are using create-react-app on C9 just run this command to start

npm run start --public $C9_HOSTNAME

And access the app from whatever your hostname is (eg type $C_HOSTNAME in the terminal to get the hostname)

HTTP Error 404.3-Not Found in IIS 7.5

I was having trouble accessing wcf service hosted locally in IIS. Running aspnet_regiis.exe -i wasn't working.

However, I fortunately came across the following:

Rahul's blog

which informs that servicemodelreg also needs to be run:

Run Visual Studio 2008 Command Prompt as “Administrator”. Navigate to C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation. Run this command servicemodelreg –i.

Winforms TableLayoutPanel adding rows programmatically

I just had a related problem (which is how I found this thread), where my dynamically added row and column styles were not taking effect. I usually consider SuspendLayout()/ResumeLayout() as optimizations, but in this case, wrapping my code in them made the rows and columns behave correctly.

What is the right way to POST multipart/form-data using curl?

This is what worked for me

curl --form file='@filename' URL

It seems when I gave this answer (4+ years ago), I didn't really understand the question, or how form fields worked. I was just answering based on what I had tried in a difference scenario, and it worked for me.

So firstly, the only mistake the OP made was in not using the @ symbol before the file name. Secondly, my answer which uses file=... only worked for me because the form field I was trying to do the upload for was called file. If your form field is called something else, use that name instead.

Explanation

From the curl manpages; under the description for the option --form it says:

This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.

Chances are that if you are trying to do a form upload, you will most likely want to use the @ prefix to upload the file rather than < which uploads the contents of the file.

Addendum

Now I must also add that one must be careful with using the < symbol because in most unix shells, < is the input redirection symbol [which coincidentally will also supply the contents of the given file to the command standard input of the program before <]. This means that if you do not properly escape that symbol or wrap it in quotes, you may find that your curl command does not behave the way you expect.

On that same note, I will also recommend quoting the @ symbol.


You may also be interested in this other question titled: application/x-www-form-urlencoded or multipart/form-data?

I say this because curl offers other ways of uploading a file, but they differ in the content-type set in the header. For example the --data option offers a similar mechanism for uploading files as data, but uses a different content-type for the upload.

Anyways that's all I wanted to say about this answer since it started to get more upvotes. I hope this helps erase any confusions such as the difference between this answer and the accepted answer. There is really none, except for this explanation.

How to convert string into float in JavaScript?

Replace the comma with a dot.

This will only return 554:

var value = parseFloat("554,20")

This will return 554.20:

var value = parseFloat("554.20")

So in the end, you can simply use:

var fValue = parseFloat(document.getElementById("textfield").value.replace(",","."))

Don't forget that parseInt() should only be used to parse integers (no floating points). In your case it will only return 554. Additionally, calling parseInt() on a float will not round the number: it will take its floor (closest lower integer).


Extended example to answer Pedro Ferreira's question from the comments:

If the textfield contains thousands separator dots like in 1.234.567,99 those could be eliminated beforehand with another replace:

var fValue = parseFloat(document.getElementById("textfield").value.replace(/\./g,"").replace(",","."))

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

I think you can also use BufferedWriter :

BufferedWriter writer = new BufferedWriter(new FileWriter(new File("note.txt")));

String stuffToWrite = info;

writer.write(stuffToWrite);

writer.close();

and before that remember too add

import java.io.BufferedWriter;

php_network_getaddresses: getaddrinfo failed: Name or service not known

I was getting the same error of fsocket() and I just updated my hosts files

  1. I logged via SSH in CentOS server. USERNAME and PASSWORD type
  2. cd /etc/
  3. ls                                     //"just to watch list"
  4. vi hosts                                   //"edit the host file"
  5. i                                    //" to put the file into insert mode"
  6. 95.183.24.10                 [mail_server_name] in my case ("mail.kingologic.com")
  7. Press ESC Key
  8. press ZZ

hope it will solve your problem

for any further query please ping me at http://kingologic.com

How do I convert datetime.timedelta to minutes, hours in Python?

datetime.timedelta(hours=1, minutes=10)
#python 2.7

Finding the handle to a WPF window

Well, instead of passing Application.Current.MainWindow, just pass a reference to whichever window it is you want: new WindowInteropHelper(this).Handle and so on.

How do I implement IEnumerable<T>

If you choose to use a generic collection, such as List<MyObject> instead of ArrayList, you'll find that the List<MyObject> will provide both generic and non-generic enumerators that you can use.

using System.Collections;

class MyObjects : IEnumerable<MyObject>
{
    List<MyObject> mylist = new List<MyObject>();

    public MyObject this[int index]  
    {  
        get { return mylist[index]; }  
        set { mylist.Insert(index, value); }  
    } 

    public IEnumerator<MyObject> GetEnumerator()
    {
        return mylist.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

Convert JSON String to Pretty Print JSON output using Jackson

To indent any old JSON, just bind it as Object, like:

Object json = mapper.readValue(input, Object.class);

and then write it out with indentation:

String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

this avoids your having to define actual POJO to map data to.

Or you can use JsonNode (JSON Tree) as well.

Django model "doesn't declare an explicit app_label"

O...M...G I was getting this error too and I spent almost 2 days on it and now I finally managed to solve it. Honestly...the error had nothing to do with what the problem was. In my case it was a simple matter of syntax. I was trying to run a python module standalone that used some django models in a django context, but the module itself wasn't a django model. But I was declaring the class wrong

instead of having

class Scrapper:
    name = ""
    main_link= ""
    ...

I was doing

class Scrapper(Website):
    name = ""
    main_link= ""
    ...

which is obviously wrong. The message is so misleading that I couldn't help myself but think it was some issue with configuration or just using django in a wrong way since I'm very new to it.

I'll share this here for someone newbie as me going through the same silliness can hopefully solve their issue.

Saving data to a file in C#

One liner:

System.IO.File.WriteAllText(@"D:\file.txt", content);

It creates the file if it doesn't exist and overwrites it if it exists. Make sure you have appropriate privileges to write to the location, otherwise you will get an exception.

https://msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Write string to text file and ensure it always overwrites the existing content.

Why do multiple-table joins produce duplicate rows?

When you have related tables you often have one-to-many or many-to-many relationships. So when you join to TableB each record in TableA many have multiple records in TableB. This is normal and expected.

Now at times you only need certain columns and those are all the same for all the records, then you would need to do some sort of group by or distinct to remove the duplicates. Let's look at an example:

TableA
Id Field1
1  test
2  another test

TableB
ID Field2 field3
1  Test1  something
1  test1  More something
2  Test2  Anything

So when you join them and select all the files you get:

select * 
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1        b.id   b.field2  b.field3
1    test            1      Test1     something
1    test            1      Test1     More something
2    another test 2  2      Test2     Anything

These are not duplicates because the values of Field3 are different even though there are repeated values in the earlier fields. Now when you only select certain columns the same number of records are being joined together but since the columns with the different information is not being displayed they look like duplicates.

select a.Id, a.Field1,  b.field2
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1       b.field2  
1    test           Test1     
1    test           Test1 
2    another test   Test2

This appears to be duplicates but it is not because of the multiple records in TableB.

You normally fix this by using aggregates and group by, by using distinct or by filtering in the where clause to remove duplicates. How you solve this depends on exactly what your business rule is and how your database is designed and what kind of data is in there.

react native get TextInput value

If you are like me and doesn't want to use or pollute state for one-off components here's what I did:

export default class Registartion extends Component {
  _register = () => {
    const payload = {
      firstName: this.firstName,
      /* other values */
    }

    console.log(payload)
  }

  render() {
    return (
      <RegisterLayout>
        <Text style={styles.welcome}>
          Register
        </Text>

        <InputText
          placeholder="First Name"
          onChangeText={(text) => this.firstName = text} />
        // More components...
        <CustomButton
          backgroundColor="steelblue"
          handlePress={this._register}>
          Submit
        </CustomButton>
     </RegisterLayout>
    )
  }
}

size of uint8, uint16 and uint32?

It's quite unclear how you are computing the size ("the size in debug mode"?").

Use printf():

printf("the size of c is %u\n", (unsigned int) sizeof c);

Normally you'd print a size_t value (which is the type sizeof returns) with %zu, but if you're using a pre-C99 compiler like Visual Studio that won't work.

You need to find the typedef statements in your code that define the custom names like uint8 and so on; those are not standard so nobody here can know how they're defined in your code.

New C code should use <stdint.h> which gives you uint8_t and so on.

convert double to int

The best way is to simply use Convert.ToInt32. It is fast and also rounds correctly.

Why make it more complicated?

How can I get the timezone name in JavaScript?

In javascript , the Date.getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.

var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;

Moment'timezone will be a useful tool. http://momentjs.com/timezone/

Convert Dates Between Timezones

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

Get the value of checked checkbox?

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var ckbox = $("input[name='ips']");_x000D_
  var chkId = '';_x000D_
  $('input').on('click', function() {_x000D_
    _x000D_
    if (ckbox.is(':checked')) {_x000D_
      $("input[name='ips']:checked").each ( function() {_x000D_
      chkId = $(this).val() + ",";_x000D_
        chkId = chkId.slice(0, -1);_x000D_
    });_x000D_
       _x000D_
       alert ( $(this).val() ); // return all values of checkboxes checked_x000D_
       alert(chkId); // return value of checkbox checked_x000D_
    }     _x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="ips" value="12520">_x000D_
<input type="checkbox" name="ips" value="12521">_x000D_
<input type="checkbox" name="ips" value="12522">
_x000D_
_x000D_
_x000D_

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

Cannot make file java.io.IOException: No such file or directory

i fixed my problem by this code on linux file system

if (!file.exists())
    Files.createFile(file.toPath());

When to use std::size_t?

size_t is an unsigned type that can hold maximum integer value for your architecture, so it is protected from integer overflows due to sign (signed int 0x7FFFFFFF incremented by 1 will give you -1) or short size (unsigned short int 0xFFFF incremented by 1 will give you 0).

It is mainly used in array indexing/loops/address arithmetic and so on. Functions like memset() and alike accept size_t only, because theoretically you may have a block of memory of size 2^32-1 (on 32bit platform).

For such simple loops don't bother and use just int.

How do I capitalize first letter of first name and last name in C#?

The most direct option is going to be to use the ToTitleCase function that is available in .NET which should take care of the name most of the time. As edg pointed out there are some names that it will not work for, but these are fairly rare so unless you are targeting a culture where such names are common it is not necessary something that you have to worry too much about.

However if you are not working with a .NET langauge, then it depends on what the input looks like - if you have two separate fields for the first name and the last name then you can just capitalize the first letter lower the rest of it using substrings.

firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();
lastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();

However, if you are provided multiple names as part of the same string then you need to know how you are getting the information and split it accordingly. So if you are getting a name like "John Doe" you an split the string based upon the space character. If it is in a format such as "Doe, John" you are going to need to split it based upon the comma. However, once you have it split apart you just apply the code shown previously.

How to get value of selected radio button?

https://codepen.io/anon/pen/YQxbZJ

The HTML

<div id="rates">
<input type="radio" id="x1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="x2" name="rate" value="Variable Rate" 
checked="checked"> Variable Rate
<input type="radio" id="x3" name="rate" value="Multi Rate" > Multi Rate
</div>

<button id="rdio"> Check Radio </button>
<div id="check">

</div>

The JS

var x ,y;
var x = document.getElementById("check");
function boom()
{
if (document.getElementById("x1").checked)
  y = document.getElementById("x1").value;

else if(document.getElementById("x2").checked)
  y = document.getElementById("x2").value;

else if (document.getElementById("x3").checked)
  y = document.getElementById("x3").value;
else
  y = "kuch nhi;"
x.innerHTML = y;
}

var z = document.getElementById('rdio');
z.addEventListener("click", boom);`

/usr/bin/ld: cannot find

@Alwin Doss You should provide the -L option before -l. You would have done the other way round probably. Try this :)

git repo says it's up-to-date after pull but files are not updated

Try this:

 git fetch --all
 git reset --hard origin/master

Explanation:

git fetch downloads the latest from remote without trying to merge or rebase anything.

Please let me know if you have any questions!

Storing a file in a database as opposed to the file system?

If you can move to SQL Server 2008, you can take advantage of the FILESTREAM support which gives you the best of both - the files are stored in the filesystem, but the database integration is much better than just storing a filepath in a varchar field. Your query can return a standard .NET file stream, which makes the integration a lot simpler.

Getting Started with FILESTREAM Storage

What is the difference between persist() and merge() in JPA and Hibernate?

This is coming from JPA. In a very simple way:

  • persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).

  • merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.

How to identify object types in java

You want instanceof:

if (value instanceof Integer)

This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do

if (value.getClass() == Integer.class)

or

if (Integer.class.equals(value.getClass())

Can Android Studio be used to run standard Java projects?

on Android Studio 4.0 and above, you will get an option readily on the IDE,a green run icon to run the related main() class.

enter image description here

how to check which version of nltk, scikit learn installed?

You can find NLTK version simply by doing:

In [1]: import nltk

In [2]: nltk.__version__
Out[2]: '3.2.5'

And similarly for scikit-learn,

In [3]: import sklearn

In [4]: sklearn.__version__
Out[4]: '0.19.0'

I'm using python3 here.

How to Check byte array empty or not?

You must swap the order of your test:

From:

if (Attachment.Length > 0 && Attachment != null)

To:

if (Attachment != null && Attachment.Length > 0 )

The first version attempts to dereference Attachment first and therefore throws if it's null. The second version will check for nullness first and only go on to check the length if it's not null (due to "boolean short-circuiting").


[EDIT] I come from the future to tell you that with later versions of C# you can use a "null conditional operator" to simplify the code above to:

if (Attachment?.Length > 0)
        

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

This works for me:

android {
   packagingOptions {
       exclude 'LICENSE.txt'
   }
}

Eclipse error ... cannot be resolved to a type

Solved the problem by dropping the jar into WEB_INF/lib.

Log all queries in mysql

Besides what I came across here, running the following was the simplest way to dump queries to a log file without restarting

SET global log_output = 'FILE';
SET global general_log_file='/Applications/MAMP/logs/mysql_general.log';
SET global general_log = 1;

can be turned off with

SET global general_log = 0;

How to check that an element is in a std::set?

I use

if(!my_set.count(that_element)) //Element is present...
;

But it is not as efficient as

if(my_set.find(that_element)!=my_set.end()) ....;

My version only saves my time in writing the code. I prefer it this way for competitive coding.

Export tables to an excel spreadsheet in same directory

You can use VBA to export an Access database table as a Worksheet in an Excel Workbook.

To obtain the path of the Access database, use the CurrentProject.Path property.

To name the Excel Workbook file with the current date, use the Format(Date, "yyyyMMdd") method.

Finally, to export the table as a Worksheet, use the DoCmd.TransferSpreadsheet method.

Example:

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True

This will output both Table1 and Table2 into the same Workbook.

HTH

How to recover just deleted rows in mysql?

If you use MyISAM tables, then you can recover any data you deleted, just

open file: mysql/data/[your_db]/[your_table].MYD

with any text editor

SCRIPT438: Object doesn't support property or method IE

We were able to solve this problem by adding in the Object.Assign polyfill to the files being imported and throwing the error. We would make it the highest import, that way it would be available to the other code to be called in the stack.

import "mdn-polyfills/Object.assign";

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

In c# 9.0 you can try to use records for this. They have default copy constructor that copy all fields - no need to use reflection / constructor with all fields.

public record BaseR
{
   public string Prop1 { get; set; }
}

public record DerivedR : BaseR
{
   public DerivedR(BaseR baseR) : base(baseR) { }
   public string Prop2 { get; set; }
}

var baseR = new BaseR { Prop1 = "base prob" };
var derivedR = new DerivedR(baseR) { Prop2 = "new prop" };

enter image description here

Correct way to quit a Qt program?

While searching this very question I discovered this example in the documentation.

QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection);

Mutatis mutandis for your particular action of course.

Along with this note.

It's good practice to always connect signals to this slot using a QueuedConnection. If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec()), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.

It's common to connect the QGuiApplication::lastWindowClosed() signal to quit()

What is the difference between an abstract function and a virtual function?

Abstract method: When a class contains an abstract method, that class must be declared as abstract. The abstract method has no implementation and thus, classes that derive from that abstract class, must provide an implementation for this abstract method.

Virtual method: A class can have a virtual method. The virtual method has an implementation. When you inherit from a class that has a virtual method, you can override the virtual method and provide additional logic, or replace the logic with your own implementation.

When to use what: In some cases, you know that certain types should have a specific method, but, you don't know what implementation this method should have.
In such cases, you can create an interface which contains a method with this signature. However, if you have such a case, but you know that implementors of that interface will also have another common method (for which you can already provide the implementation), you can create an abstract class. This abstract class then contains the abstract method (which must be overriden), and another method which contains the 'common' logic.

A virtual method should be used if you have a class which can be used directly, but for which you want inheritors to be able to change certain behaviour, although it is not mandatory.

How do I move an existing Git submodule within a Git repository?

The most modern answer, taken from Valloric's comment above:

  1. Upgrade to Git 1.9.3 (or 2.18 if the submodule contains nested submodules)
  2. git mv old/submod new/submod
  3. Afterwards the .gitmodules and the submodule directory are already staged for a commit (you can verify this with git status.)
  4. Commit the changes with git commitand you're good to go!

Done!

Splitting a Java String by the pipe symbol using split("|")

test.split("\\|",999);

Specifing a limit or max will be accurate for examples like: "boo|||a" or "||boo|" or " |||"

But test.split("\\|"); will return different length strings arrays for the same examples.

use reference: link

creating a table in ionic

You should consider using an angular plug-in to handle the heavy lifting for you, unless you particularly enjoy typing hundreds of lines of knarly error prone ion-grid code. Simon Grimm has a cracking step by step tutorial that anyone can follow: https://devdactic.com/ionic-datatable-ngx-datatable/. This shows how to use ngx-datatable. But there are many other options (ng2-table is good).

The dead simple example goes like this:

<ion-content>
  <ngx-datatable class="fullscreen" [ngClass]="tablestyle" [rows]="rows" [columnMode]="'force'" [sortType]="'multi'" [reorderable]="false">
    <ngx-datatable-column name="Name"></ngx-datatable-column>
    <ngx-datatable-column name="Gender"></ngx-datatable-column>
    <ngx-datatable-column name="Age"></ngx-datatable-column>
  </ngx-datatable>
</ion-content>

And the ts:

rows = [
    {
      "name": "Ethel Price",
      "gender": "female",
      "age": 22
    },
    {
      "name": "Claudine Neal",
      "gender": "female",
      "age": 55
    },
    {
      "name": "Beryl Rice",
      "gender": "female",
      "age": 67
    },
    {
      "name": "Simon Grimm",
      "gender": "male",
      "age": 28
    }
  ];

Since the original poster expressed their frustration of how difficult it is to achieve this with ion-grid, I think the correct answer should not be constrained by this as a prerequisite. You would be nuts to roll your own, given how good this is!

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Somewhere in that mess, the non-breaking spaces from the HTML template (the  s) are encoding as ISO-8859-1 so that they show up incorrectly as an "Â" character

That'd be encoding to UTF-8 then, not ISO-8859-1. The non-breaking space character is byte 0xA0 in ISO-8859-1; when encoded to UTF-8 it'd be 0xC2,0xA0, which, if you (incorrectly) view it as ISO-8859-1 comes out as " ". That includes a trailing nbsp which you might not be noticing; if that byte isn't there, then something else has mauled your document and we need to see further up to find out what.

What's the regexp, how does the templating work? There would seem to be a proper HTML parser involved somewhere if your &nbsp; strings are (correctly) being turned into U+00A0 NON-BREAKING SPACE characters. If so, you could just process your template natively in the DOM, and ask it to serialise using the ASCII encoding to keep non-ASCII characters as character references. That would also stop you having to do regex post-processing on the HTML itself, which is always a highly dodgy business.

Well anyway, for now you can add one of the following to your document's <head> and see if that makes it look right in the browser:

  • for HTML4: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  • for HTML5: <meta charset="utf-8">

If you've done that, then any remaining problem is ActivePDF's fault.

Easy login script without database

FacebookConnect or OpenID are two great options.

Basically, your users login to other sites they are already members of (Facebook, or Google), and then you get confirmation from that site telling you the user is trustworthy - start a session, and they're logged in. No database needed (unless you want to associate more data to their account).

Java get String CompareTo as a comparator object

Also, if you want case-insensitive comparison, in recent versions of Java the String class contains a public static final field called CASE_INSENSITIVE_ORDER which is of type Comparator<String>, as I just recently found out. So, you can get your job done using String.CASE_INSENSITIVE_ORDER.

How can I detect keydown or keypress event in angular.js?

Update:

ngKeypress, ngKeydown and ngKeyup are now part of AngularJS.

<!-- you can, for example, specify an expression to evaluate -->
<input ng-keypress="count = count + 1" ng-init="count=0">

<!-- or call a controller/directive method and pass $event as parameter.
     With access to $event you can now do stuff like 
     finding which key was pressed -->
<input ng-keypress="changed($event)">

Read more here:

https://docs.angularjs.org/api/ng/directive/ngKeypress https://docs.angularjs.org/api/ng/directive/ngKeydown https://docs.angularjs.org/api/ng/directive/ngKeyup

Earlier solutions:

Solution 1: Use ng-change with ng-model

<input type="text" placeholder="+639178983214" ng-model="mobileNumber" 
ng-controller="RegisterDataController" ng-change="keydown()">

JS:

function RegisterDataController($scope) {       
   $scope.keydown = function() {
        /* validate $scope.mobileNumber here*/
   };
}

Solution 2. Use $watch

<input type="text" placeholder="+639178983214" ng-model="mobileNumber" 
ng-controller="RegisterDataController">
    

JS:

$scope.$watch("mobileNumber", function(newValue, oldValue) {
    /* change noticed */
});

WPF Databinding: How do I access the "parent" data context?

This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"

Does Android support near real time push notification?

I cannot find where I read it at, but I believe gmail utilizes an open TCP connection to do the e-mail push.

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }

Get Memory Usage in Android

Based on the previous answers and personnal experience, here is the code I use to monitor CPU use. The code of this class is written in pure Java.

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Utilities available only on Linux Operating System.
 * 
 * <p>
 * A typical use is to assign a thread to CPU monitoring:
 * </p>
 * 
 * <pre>
 * &#064;Override
 * public void run() {
 *  while (CpuUtil.monitorCpu) {
 * 
 *      LinuxUtils linuxUtils = new LinuxUtils();
 * 
 *      int pid = android.os.Process.myPid();
 *      String cpuStat1 = linuxUtils.readSystemStat();
 *      String pidStat1 = linuxUtils.readProcessStat(pid);
 * 
 *      try {
 *          Thread.sleep(CPU_WINDOW);
 *      } catch (Exception e) {
 *      }
 * 
 *      String cpuStat2 = linuxUtils.readSystemStat();
 *      String pidStat2 = linuxUtils.readProcessStat(pid);
 * 
 *      float cpu = linuxUtils.getSystemCpuUsage(cpuStat1, cpuStat2);
 *      if (cpu &gt;= 0.0f) {
 *          _printLine(mOutput, &quot;total&quot;, Float.toString(cpu));
 *      }
 * 
 *      String[] toks = cpuStat1.split(&quot; &quot;);
 *      long cpu1 = linuxUtils.getSystemUptime(toks);
 * 
 *      toks = cpuStat2.split(&quot; &quot;);
 *      long cpu2 = linuxUtils.getSystemUptime(toks);
 * 
 *      cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
 *      if (cpu &gt;= 0.0f) {
 *          _printLine(mOutput, &quot;&quot; + pid, Float.toString(cpu));
 *      }
 * 
 *      try {
 *          synchronized (this) {
 *              wait(CPU_REFRESH_RATE);
 *          }
 *      } catch (InterruptedException e) {
 *          e.printStackTrace();
 *          return;
 *      }
 *  }
 * 
 *  Log.i(&quot;THREAD CPU&quot;, &quot;Finishing&quot;);
 * }
 * </pre>
 */
public final class LinuxUtils {

    // Warning: there appears to be an issue with the column index with android linux:
    // it was observed that on most present devices there are actually
    // two spaces between the 'cpu' of the first column and the value of 
    // the next column with data. The thing is the index of the idle 
    // column should have been 4 and the first column with data should have index 1. 
    // The indexes defined below are coping with the double space situation.
    // If your file contains only one space then use index 1 and 4 instead of 2 and 5.
    // A better way to deal with this problem may be to use a split method 
    // not preserving blanks or compute an offset and add it to the indexes 1 and 4.

    private static final int FIRST_SYS_CPU_COLUMN_INDEX = 2;

    private static final int IDLE_SYS_CPU_COLUMN_INDEX = 5;

    /** Return the first line of /proc/stat or null if failed. */
    public String readSystemStat() {

        RandomAccessFile reader = null;
        String load = null;

        try {
            reader = new RandomAccessFile("/proc/stat", "r");
            load = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            Streams.close(reader);
        }

        return load;
    }

    /**
     * Compute and return the total CPU usage, in percent.
     * 
     * @param start
     *            first content of /proc/stat. Not null.
     * @param end
     *            second content of /proc/stat. Not null.
     * @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
     *         available.
     * @see {@link #readSystemStat()}
     */
    public float getSystemCpuUsage(String start, String end) {
        String[] stat = start.split("\\s");
        long idle1 = getSystemIdleTime(stat);
        long up1 = getSystemUptime(stat);

        stat = end.split("\\s");
        long idle2 = getSystemIdleTime(stat);
        long up2 = getSystemUptime(stat);

        // don't know how it is possible but we should care about zero and
        // negative values.
        float cpu = -1f;
        if (idle1 >= 0 && up1 >= 0 && idle2 >= 0 && up2 >= 0) {
            if ((up2 + idle2) > (up1 + idle1) && up2 >= up1) {
                cpu = (up2 - up1) / (float) ((up2 + idle2) - (up1 + idle1));
                cpu *= 100.0f;
            }
        }

        return cpu;
    }

    /**
     * Return the sum of uptimes read from /proc/stat.
     * 
     * @param stat
     *            see {@link #readSystemStat()}
     */
    public long getSystemUptime(String[] stat) {
        /*
         * (from man/5/proc) /proc/stat kernel/system statistics. Varies with
         * architecture. Common entries include: cpu 3357 0 4313 1362393
         * 
         * The amount of time, measured in units of USER_HZ (1/100ths of a
         * second on most architectures, use sysconf(_SC_CLK_TCK) to obtain the
         * right value), that the system spent in user mode, user mode with low
         * priority (nice), system mode, and the idle task, respectively. The
         * last value should be USER_HZ times the second entry in the uptime
         * pseudo-file.
         * 
         * In Linux 2.6 this line includes three additional columns: iowait -
         * time waiting for I/O to complete (since 2.5.41); irq - time servicing
         * interrupts (since 2.6.0-test4); softirq - time servicing softirqs
         * (since 2.6.0-test4).
         * 
         * Since Linux 2.6.11, there is an eighth column, steal - stolen time,
         * which is the time spent in other operating systems when running in a
         * virtualized environment
         * 
         * Since Linux 2.6.24, there is a ninth column, guest, which is the time
         * spent running a virtual CPU for guest operating systems under the
         * control of the Linux kernel.
         */

        // with the following algorithm, we should cope with all versions and
        // probably new ones.
        long l = 0L;

        for (int i = FIRST_SYS_CPU_COLUMN_INDEX; i < stat.length; i++) {
            if (i != IDLE_SYS_CPU_COLUMN_INDEX ) { // bypass any idle mode. There is currently only one.
                try {
                    l += Long.parseLong(stat[i]);
                } catch (NumberFormatException ex) {
                    ex.printStackTrace();
                    return -1L;
                }
            }
        }

        return l;
    }

    /**
     * Return the sum of idle times read from /proc/stat.
     * 
     * @param stat
     *            see {@link #readSystemStat()}
     */
    public long getSystemIdleTime(String[] stat) {
        try {
            return Long.parseLong(stat[IDLE_SYS_CPU_COLUMN_INDEX]);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }

        return -1L;
    }

    /** Return the first line of /proc/pid/stat or null if failed. */
    public String readProcessStat(int pid) {

        RandomAccessFile reader = null;
        String line = null;

        try {
            reader = new RandomAccessFile("/proc/" + pid + "/stat", "r");
            line = reader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            Streams.close(reader);
        }

        return line;
    }

    /**
     * Compute and return the CPU usage for a process, in percent.
     * 
     * <p>
     * The parameters {@code totalCpuTime} is to be the one for the same period
     * of time delimited by {@code statStart} and {@code statEnd}.
     * </p>
     * 
     * @param start
     *            first content of /proc/pid/stat. Not null.
     * @param end
     *            second content of /proc/pid/stat. Not null.
     * @return the CPU use in percent or -1f if the stats are inverted or on
     *         error
     * @param uptime
     *            sum of user and kernel times for the entire system for the
     *            same period of time.
     * @return 12.7 for a cpu usage of 12.7% or -1 if the value is not available
     *         or an error occurred.
     * @see {@link #readProcessStat(int)}
     */
    public float getProcessCpuUsage(String start, String end, long uptime) {

        String[] stat = start.split("\\s");
        long up1 = getProcessUptime(stat);

        stat = end.split("\\s");
        long up2 = getProcessUptime(stat);

        float ret = -1f;
        if (up1 >= 0 && up2 >= up1 && uptime > 0.) {
            ret = 100.f * (up2 - up1) / (float) uptime;
        }

        return ret;
    }

    /**
     * Decode the fields of the file {@code /proc/pid/stat} and return (utime +
     * stime)
     * 
     * @param stat
     *            obtained with {@link #readProcessStat(int)}
     */
    public long getProcessUptime(String[] stat) {
        return Long.parseLong(stat[14]) + Long.parseLong(stat[15]);
    }

    /**
     * Decode the fields of the file {@code /proc/pid/stat} and return (cutime +
     * cstime)
     * 
     * @param stat
     *            obtained with {@link #readProcessStat(int)}
     */
    public long getProcessIdleTime(String[] stat) {
        return Long.parseLong(stat[16]) + Long.parseLong(stat[17]);
    }

    /**
     * Return the total CPU usage, in percent.
     * <p>
     * The call is blocking for the time specified by elapse.
     * </p>
     * 
     * @param elapse
     *            the time in milliseconds between reads.
     * @return 12.7 for a CPU usage of 12.7% or -1 if the value is not
     *         available.
     */
    public float syncGetSystemCpuUsage(long elapse) {

        String stat1 = readSystemStat();
        if (stat1 == null) {
            return -1.f;
        }

        try {
            Thread.sleep(elapse);
        } catch (Exception e) {
        }

        String stat2 = readSystemStat();
        if (stat2 == null) {
            return -1.f;
        }

        return getSystemCpuUsage(stat1, stat2);
    }

    /**
     * Return the CPU usage of a process, in percent.
     * <p>
     * The call is blocking for the time specified by elapse.
     * </p>
     * 
     * @param pid
     * @param elapse
     *            the time in milliseconds between reads.
     * @return 6.32 for a CPU usage of 6.32% or -1 if the value is not
     *         available.
     */
    public float syncGetProcessCpuUsage(int pid, long elapse) {

        String pidStat1 = readProcessStat(pid);
        String totalStat1 = readSystemStat();
        if (pidStat1 == null || totalStat1 == null) {
            return -1.f;
        }

        try {
            Thread.sleep(elapse);
        } catch (Exception e) {
            e.printStackTrace();
            return -1.f;
        }

        String pidStat2 = readProcessStat(pid);
        String totalStat2 = readSystemStat();
        if (pidStat2 == null || totalStat2 == null) {
            return -1.f;
        }

        String[] toks = totalStat1.split("\\s");
        long cpu1 = getSystemUptime(toks);

        toks = totalStat2.split("\\s");
        long cpu2 = getSystemUptime(toks);

        return getProcessCpuUsage(pidStat1, pidStat2, cpu2 - cpu1);
    }

}

There are several ways of exploiting this class. You can call either syncGetSystemCpuUsage or syncGetProcessCpuUsage but each is blocking the calling thread. Since a common issue is to monitor the total CPU usage and the CPU use of the current process at the same time, I have designed a class computing both of them. That class contains a dedicated thread. The output management is implementation specific and you need to code your own.

The class can be customized by a few means. The constant CPU_WINDOW defines the depth of a read, i.e. the number of milliseconds between readings and computing of the corresponding CPU load. CPU_REFRESH_RATE is the time between each CPU load measurement. Do not set CPU_REFRESH_RATE to 0 because it will suspend the thread after the first read.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import android.app.Application;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import my.app.LinuxUtils;
import my.app.Streams;
import my.app.TestReport;
import my.app.Utils;

public final class CpuUtil {

    private static final int CPU_WINDOW = 1000;

    private static final int CPU_REFRESH_RATE = 100; // Warning: anything but > 0

    private static HandlerThread handlerThread;

    private static TestReport output;

    static {
        output = new TestReport();
        output.setDateFormat(Utils.getDateFormat(Utils.DATE_FORMAT_ENGLISH));
    }

    private static boolean monitorCpu;

    /**
     * Construct the class singleton. This method should be called in
     * {@link Application#onCreate()}
     * 
     * @param dir
     *            the parent directory
     * @param append
     *            mode
     */
    public static void setOutput(File dir, boolean append) {
        try {
            File file = new File(dir, "cpu.txt");
            output.setOutputStream(new FileOutputStream(file, append));
            if (!append) {
                output.println(file.getAbsolutePath());
                output.newLine(1);

                // print header
                _printLine(output, "Process", "CPU%");

                output.flush();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /** Start CPU monitoring */
    public static boolean startCpuMonitoring() {
        CpuUtil.monitorCpu = true;

        handlerThread = new HandlerThread("CPU monitoring"); //$NON-NLS-1$
        handlerThread.start();

        Handler handler = new Handler(handlerThread.getLooper());
        handler.post(new Runnable() {

            @Override
            public void run() {
                while (CpuUtil.monitorCpu) {

                    LinuxUtils linuxUtils = new LinuxUtils();

                    int pid = android.os.Process.myPid();
                    String cpuStat1 = linuxUtils.readSystemStat();
                    String pidStat1 = linuxUtils.readProcessStat(pid);

                    try {
                        Thread.sleep(CPU_WINDOW);
                    } catch (Exception e) {
                    }

                    String cpuStat2 = linuxUtils.readSystemStat();
                    String pidStat2 = linuxUtils.readProcessStat(pid);

                    float cpu = linuxUtils
                            .getSystemCpuUsage(cpuStat1, cpuStat2);
                    if (cpu >= 0.0f) {
                        _printLine(output, "total", Float.toString(cpu));
                    }

                    String[] toks = cpuStat1.split(" ");
                    long cpu1 = linuxUtils.getSystemUptime(toks);

                    toks = cpuStat2.split(" ");
                    long cpu2 = linuxUtils.getSystemUptime(toks);

                    cpu = linuxUtils.getProcessCpuUsage(pidStat1, pidStat2,
                            cpu2 - cpu1);
                    if (cpu >= 0.0f) {
                        _printLine(output, "" + pid, Float.toString(cpu));
                    }

                    try {
                        synchronized (this) {
                            wait(CPU_REFRESH_RATE);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        return;
                    }
                }

                Log.i("THREAD CPU", "Finishing");
            }

        });

        return CpuUtil.monitorCpu;
    }

    /** Stop CPU monitoring */
    public static void stopCpuMonitoring() {
        if (handlerThread != null) {
            monitorCpu = false;
            handlerThread.quit();
            handlerThread = null;
        }
    }

    /** Dispose of the object and release the resources allocated for it */
    public void dispose() {

        monitorCpu = false;

        if (output != null) {
            OutputStream os = output.getOutputStream();
            if (os != null) {
                Streams.close(os);
                output.setOutputStream(null);
            }

            output = null;
        }
    }

    private static void _printLine(TestReport output, String process, String cpu) {
        output.stampln(process + ";" + cpu);
    }

}

Which comes first in a 2D array, rows or columns?

In java the rows are done first, because a 2 dimension array is considered two separate arrays. Starts with the first row 1 dimension array.

How to give a Blob uploaded as FormData a file name?

Adding this here as it doesn't seem to be here.

Aside from the excellent solution of form.append("blob",blob, filename); you can also turn the blob into a File instance:

var blob = new Blob([JSON.stringify([0,1,2])], {type : 'application/json'});
var fileOfBlob = new File([blob], 'aFileName.json');
form.append("upload", fileOfBlob);

How to calculate the number of occurrence of a given character in each row of a column of strings?

nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))
[1] 2 1 0

Notice that I coerce the factor variable to character, before passing to nchar. The regex functions appear to do that internally.

Here's benchmark results (with a scaled up size of the test to 3000 rows)

 q.data<-q.data[rep(1:NROW(q.data), 1000),]
 str(q.data)
'data.frame':   3000 obs. of  3 variables:
 $ number     : int  1 2 3 1 2 3 1 2 3 1 ...
 $ string     : Factor w/ 3 levels "greatgreat","magic",..: 1 2 3 1 2 3 1 2 3 1 ...
 $ number.of.a: int  2 1 0 2 1 0 2 1 0 2 ...

 benchmark( Dason = { q.data$number.of.a <- str_count(as.character(q.data$string), "a") },
 Tim = {resT <- sapply(as.character(q.data$string), function(x, letter = "a"){
                            sum(unlist(strsplit(x, split = "")) == letter) }) }, 

 DWin = {resW <- nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))},
 Josh = {x <- sapply(regmatches(q.data$string, gregexpr("g",q.data$string )), length)}, replications=100)
#-----------------------
   test replications elapsed  relative user.self sys.self user.child sys.child
1 Dason          100   4.173  9.959427     2.985    1.204          0         0
3  DWin          100   0.419  1.000000     0.417    0.003          0         0
4  Josh          100  18.635 44.474940    17.883    0.827          0         0
2   Tim          100   3.705  8.842482     3.646    0.072          0         0

How to get the current TimeStamp?

In Qt 4.7, there is the QDateTime::currentMSecsSinceEpoch() static function, which does exactly what you need, without any intermediary steps. Hence I'd recommend that for projects using Qt 4.7 or newer.

How to reformat JSON in Notepad++?

I'm using the JSON Viewer plug-in with NPP 5.9 and it seems to work well.

Clear Application's Data Programmatically

I'm just putting the tutorial from the link ihrupin posted here in this post.

package com.hrupin.cleaner;

import java.io.File;

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {

    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance() {
        return instance;
    }

    public void clearApplicationData() {
        File cacheDirectory = getCacheDir();
        File applicationDirectory = new File(cacheDirectory.getParent());
        if (applicationDirectory.exists()) {
            String[] fileNames = applicationDirectory.list();
            for (String fileName : fileNames) {
                if (!fileName.equals("lib")) {
                    deleteFile(new File(applicationDirectory, fileName));
                }
            }
        }
    }

    public static boolean deleteFile(File file) {
        boolean deletedAll = true;
        if (file != null) {
            if (file.isDirectory()) {
                String[] children = file.list();
                for (int i = 0; i < children.length; i++) {
                    deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
                }
            } else {
                deletedAll = file.delete();
            }
        }

        return deletedAll;
    }
}

So if you want a button to do this you need to call MyApplication.getInstance(). clearApplicationData() from within an onClickListener

Update: Your SharedPreferences instance might hold onto your data and recreate the preferences file after you delete it. So your going to want to get your SharedPreferences object and

prefs.edit().clear().commit();

Update:

You need to add android:name="your.package.MyApplication" to the application tag inside AndroidManifest.xml if you had not done so. Else, MyApplication.getInstance() returns null, resulting a NullPointerException.

Break when a value changes using the Visual Studio debugger

As Peter Mortensen wrote:

In the Visual Studio 2005 menu:

Debug -> New Breakpoint -> New Data Breakpoint

Enter: &myVariable

Additional information:

Obviously, the system must know which address in memory to watch. So - set a normal breakpoint to the initialisation of myVariable (or myClass.m_Variable) - run the system and wait till it stops at that breakpoint. - Now the Menu entry is enabled, and you can watch the variable by entering &myVariable, or the instance by entering &myClass.m_Variable. Now the addresses are well defined.

Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this.

Round a floating-point number down to the nearest integer?

Just make round(x-0.5) this will always return the next rounded down Integer value of your Float. You can also easily round up by do round(x+0.5)

How to dynamically change a web page's title?

Update: as per the comments and reference on SearchEngineLand most web crawlers will index the updated title. Below answer is obsolete, but the code is still applicable.

You can just do something like, document.title = "This is the new page title.";, but that would totally defeat the purpose of SEO. Most crawlers aren't going to support javascript in the first place, so they will take whatever is in the element as the page title.

If you want this to be compatible with most of the important crawlers, you're going to need to actually change the title tag itself, which would involve reloading the page (PHP, or the like). You're not going to be able to get around that, if you want to change the page title in a way that a crawler can see.

Anaconda Navigator won't launch (windows 10)

I was also facing same problem. Running below command from conda command prompt solved my problem

pip install pyqt5

How to read response headers in angularjs?

According the MDN custom headers are not exposed by default. The server admin need to expose them using "Access-Control-Expose-Headers" in the same fashion they deal with "access-control-allow-origin"

See this MDN link for confirmation [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers]

Download files from server php

Here is the code that will not download courpt files

$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;

header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
    ob_end_clean();
}
readfile($file);

I have included mime_content_type which will return content type of file .

To prevent from corrupt file download i have added ob_get_level() and ob_end_clean();

How do I print the content of httprequest request?

In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.

static private String dumpResponse(HttpServletResponse resp){
    StringBuilder sb = new StringBuilder();

    sb.append("Response Status = [" + resp.getStatus() + "], ");
    String headers = resp.getHeaderNames().stream()
                    .map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
                    .collect(Collectors.joining(", "));

    if (headers.isEmpty()) {
        sb.append("Response headers: NONE,");
    } else {
        sb.append("Response headers: "+headers+",");
    }

    return sb.toString();
}

Spring JSON request getting 406 (not Acceptable)

check this thread. spring mvc restcontroller return json string p/s: you should add jack son mapping config to your WebMvcConfig class

@Override protected void configureMessageConverters( List<HttpMessageConverter<?>> converters) { // put the jackson converter to the front of the list so that application/json content-type strings will be treated as JSON converters.add(new MappingJackson2HttpMessageConverter()); // and probably needs a string converter too for text/plain content-type strings to be properly handled converters.add(new StringHttpMessageConverter()); }

How to recursively find the latest modified file in a directory?

The following command worked on Solaris :

find . -name "*zip" -type f | xargs ls -ltr | tail -1 

Get Hours and Minutes (HH:MM) from date

Following code shows current hour and minutes in 'Hour:Minutes' column for us.

SELECT  CONVERT(VARCHAR(5), GETDATE(), 108) + 
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
    ELSE ' AM'
END) 'Hour:Minutes'

or

SELECT  Format(GETDATE(), 'hh:mm') + 
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
    ELSE ' AM'
END) 'Hour:Minutes'

Ansible - Use default if a variable is not defined

In case you using lookup to set default read from environment you have also set the second parameter of default to true:

- set_facts:
    ansible_ssh_user: "{{ lookup('env', 'SSH_USER') | default('foo', true) }}"

You can also concatenate multiple default definitions:

- set_facts:
    ansible_ssh_user: "{{ some_var.split('-')[1] | default(lookup('env','USER'), true) | default('foo') }}"

How to print exact sql query in zend framework ?

from >= 2.1.4

echo $select->getSqlString()

How do you generate a random double uniformly distributed between 0 and 1 from C++?

If speed is your primary concern, then I'd simply go with

double r = (double)rand() / (double)RAND_MAX;

Jenkins could not run git

Please install git in your Jenkins server. For example, if you are using Red Hat Enterprise Linux where you are hosting Jenkins, then install git in that server using the following command: sudo yum install git This should solve the problem as git executable will be available in /usr/bin/git then and this will be recognized automatically by jenkins and this you can verify by navigating to Manage Jenkins --> Global Tool Configuration. Then under Git installations, there will not be any warning and now you should be able to clone your git project in jenkins. Hope this help the users.

How disable / remove android activity label and label bar?

There is a code here that does it.

The trick is at this line:

 title.setVisibility(View.GONE);

No Activity found to handle Intent : android.intent.action.VIEW

Url addresses must be preceded by http://

Uri uri = Uri.parse("www.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);

throws an ActivityNotFoundException. If you prepend "http://", problem solved.

Uri uri = Uri.parse("http://www.google.com");

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Try to import

java.util.List;

instead of

java.awt.List;

How to print to console using swift playground?

In Xcode 6.3 and later (including Xcode 7 and 8), console output appears in the Debug area at the bottom of the playground window (similar to where it appears in a project). To show it:

  • Menu: View > Debug Area > Show Debug Area (??Y)

  • Click the middle button of the workspace-layout widget in the toolbar

    workspace layout widget

  • Click the triangle next to the timeline at the bottom of the window

    triangle for console

Anything that writes to the console, including Swift's print statement (renamed from println in Swift 2 beta) shows up there.


In earlier Xcode 6 versions (which by now you probably should be upgrading from anyway), show the Assistant editor (e.g. by clicking the little circle next to a bit in the output area). Console output appears there.

versionCode vs versionName in Android Manifest

versionCode

A positive integer used as an internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName setting, below. The Android system uses the versionCode value to protect against downgrades by preventing users from installing an APK with a lower versionCode than the version currently installed on their device.

The value is a positive integer so that other apps can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any positive integer you want, however you should make sure that each successive release of your app uses a greater value. You cannot upload an APK to the Play Store with a versionCode you have already used for a previous version.

versionName

A string used as the version number shown to users. This setting can be specified as a raw string or as a reference to a string resource.

The value is a string so that you can describe the app version as a .. string, or as any other type of absolute or relative version identifier. The versionName has no purpose other than to be displayed to users.

Pass by Reference / Value in C++

I'm not sure if I understand your question correctly. It is a bit unclear. However, what might be confusing you is the following:

  1. When passing by reference, a reference to the same object is passed to the function being called. Any changes to the object will be reflected in the original object and hence the caller will see it.

  2. When passing by value, the copy constructor will be called. The default copy constructor will only do a shallow copy, hence, if the called function modifies an integer in the object, this will not be seen by the calling function, but if the function changes a data structure pointed to by a pointer within the object, then this will be seen by the caller due to the shallow copy.

I might have mis-understood your question, but I thought I would give it a stab anyway.

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

How can two strings be concatenated?

> tmp = paste("GAD", "AB", sep = ",")
> tmp
[1] "GAD,AB"

I found this from Google by searching for R concatenate strings: http://stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html

How do I modify a MySQL column to allow NULL?

Your syntax error is caused by a missing "table" in the query

ALTER TABLE mytable MODIFY mycolumn varchar(255) null;

Calling a javascript function recursively

Here's one very simple example:

var counter = 0;

function getSlug(tokens) {
    var slug = '';

    if (!!tokens.length) {
        slug = tokens.shift();
        slug = slug.toLowerCase();
        slug += getSlug(tokens);

        counter += 1;
        console.log('THE SLUG ELEMENT IS: %s, counter is: %s', slug, counter);
    }

    return slug;
}

var mySlug = getSlug(['This', 'Is', 'My', 'Slug']);
console.log('THE SLUG IS: %s', mySlug);

Notice that the counter counts "backwards" in regards to what slug's value is. This is because of the position at which we are logging these values, as the function recurs before logging -- so, we essentially keep nesting deeper and deeper into the call-stack before logging takes place.

Once the recursion meets the final call-stack item, it trampolines "out" of the function calls, whereas, the first increment of counter occurs inside of the last nested call.

I know this is not a "fix" on the Questioner's code, but given the title I thought I'd generically exemplify Recursion for a better understanding of recursion, outright.

.NET 4.0 has a new GAC, why?

Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.

In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.

To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.

Source

Why?

It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.

See the following information in MSDN about the GAC changes in 4.0.

For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. As a result of this, there was no need in the previous two framework releases to split the GAC. The problem of breaking older (in this case, .NET 2.0) applications resurfaces in Net Framework 4.0 at which point CLR 4.0 released. Hence, to avoid interference issues between CLR 2.0 and CLR 4.0, the GAC is now split into private GACs for each runtime.

As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

Catch an exception thrown by an async void method

It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await or Wait() the call to Foo.

public async Task Foo()
{
    var x = await DoSomethingAsync();
}

public async void DoFoo()
{
    try
    {
        await Foo();
    }
    catch (ProtocolException ex)
    {
          // The exception will be caught because you've awaited
          // the call in an async method.
    }
}

//or//

public void DoFoo()
{
    try
    {
        Foo().Wait();
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught because you've
             waited for the completion of the call. */
    }
} 

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. - https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.

This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.

How to replace a hash key with another key

you can do

hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}

This should work for your case!

How merge two objects array in angularjs?

This works for me :

$scope.array1 = $scope.array1.concat(array2)

In your case it would be :

$scope.actions.data = $scope.actions.data.concat(data)

How to square or raise to a power (elementwise) a 2D numpy array?

>>> import numpy
>>> print numpy.power.__doc__

power(x1, x2[, out])

First array elements raised to powers from second array, element-wise.

Raise each base in `x1` to the positionally-corresponding power in
`x2`.  `x1` and `x2` must be broadcastable to the same shape.

Parameters
----------
x1 : array_like
    The bases.
x2 : array_like
    The exponents.

Returns
-------
y : ndarray
    The bases in `x1` raised to the exponents in `x2`.

Examples
--------
Cube each element in a list.

>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([  0,   1,   8,  27,  64, 125])

Raise the bases to different exponents.

>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])

The effect of broadcasting.

>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
       [1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0,  1,  8, 27, 16,  5],
       [ 0,  1,  8, 27, 16,  5]])
>>>

Precision

As per the discussed observation on numerical precision as per @GarethRees objection in comments:

>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027,  1.0,  1.0],
       [ 1.0,  1.0,  1.0],
       [ 1.0,  1.0,  1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484,  1.0,  1.0],
       [ 1.0,  1.0,  1.0],
       [ 1.0,  1.0,  1.0]], dtype=float96)

>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677

>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241

Performance

>>> c    = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )

>>> import zmq
>>> aClk = zmq.Stopwatch()

>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L)                #   5 663 [usec]

>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L)                #   6 395 [usec]

>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L)                #   6 930 [usec]

>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L)                #   6 285 [usec]

>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L)             # 384 515 [usec]

How to split a data frame?

You may also want to cut the data frame into an arbitrary number of smaller dataframes. Here, we cut into two dataframes.

x = data.frame(num = 1:26, let = letters, LET = LETTERS)
set.seed(10)
split(x, sample(rep(1:2, 13)))

gives

$`1`
   num let LET
3    3   c   C
6    6   f   F
10  10   j   J
12  12   l   L
14  14   n   N
15  15   o   O
17  17   q   Q
18  18   r   R
20  20   t   T
21  21   u   U
22  22   v   V
23  23   w   W
26  26   z   Z

$`2`
   num let LET
1    1   a   A
2    2   b   B
4    4   d   D
5    5   e   E
7    7   g   G
8    8   h   H
9    9   i   I
11  11   k   K
13  13   m   M
16  16   p   P
19  19   s   S
24  24   x   X
25  25   y   Y

You can also split a data frame based upon an existing column. For example, to create three data frames based on the cyl column in mtcars:

split(mtcars,mtcars$cyl)

The operation cannot be completed because the DbContext has been disposed error

This can be as simple as adding ToList() in your repository. For example:

public IEnumerable<MyObject> GetMyObjectsForId(string id)
{
    using (var ctxt = new RcContext())
    {
        // causes an error
        return ctxt.MyObjects.Where(x => x.MyObjects.Id == id);
    }
}

Will yield the Db Context disposed error in the calling class but this can be resolved by explicitly exercising the enumeration by adding ToList() on the LINQ operation:

public IEnumerable<MyObject> GetMyObjectsForId(string id)
{
    using (var ctxt = new RcContext())
    {
        return ctxt.MyObjects.Where(x => x.MyObjects.Id == id).ToList();
    }
}

How to change the background color of a UIButton while it's highlighted?

Try tintColor:

_button.tintColor = [UIColor redColor];

Double precision - decimal places

It is actually 53 binary places, which translates to 15 stable decimal places, meaning that if you round a start out with a number with 15 decimal places, convert it to a double, and then round the double back to 15 decimal places you'll get the same number. To uniquely represent a double you need 17 decimal places (meaning that for every number with 17 decimal places, there's a unique closest double) which is why 17 places are showing up, but not all 17-decimal numbers map to different double values (like in the examples in the other answers).

Better way to find last used row

I use the following function extensively. As pointed out above, using other methods can sometimes give inaccurate results due to used range updates, gaps in the data, or different columns having different row counts.

Example of use:

lastRow=FindRange("Sheet1","A1:A1000")

would return the last occupied row number of the entire range. You can specify any range you want from single columns to random rows, eg FindRange("Sheet1","A100:A150")

Public Function FindRange(inSheet As String, inRange As String) As Long
    Set fr = ThisWorkbook.Sheets(inSheet).Range(inRange).find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
    If Not fr Is Nothing Then FindRange = fr.row Else FindRange = 0
End Function

Priority queue in .Net

The following implementation of a PriorityQueue uses SortedSet from the System library.

using System;
using System.Collections.Generic;

namespace CDiggins
{
    interface IPriorityQueue<T, K> where K : IComparable<K>
    {
        bool Empty { get; }
        void Enqueue(T x, K key);
        void Dequeue();
        T Top { get; }
    }

    class PriorityQueue<T, K> : IPriorityQueue<T, K> where K : IComparable<K>
    {
        SortedSet<Tuple<T, K>> set;

        class Comparer : IComparer<Tuple<T, K>> {
            public int Compare(Tuple<T, K> x, Tuple<T, K> y) {
                return x.Item2.CompareTo(y.Item2);
            }
        }

        PriorityQueue() { set = new SortedSet<Tuple<T, K>>(new Comparer()); }
        public bool Empty { get { return set.Count == 0;  } }
        public void Enqueue(T x, K key) { set.Add(Tuple.Create(x, key)); }
        public void Dequeue() { set.Remove(set.Max); }
        public T Top { get { return set.Max.Item1; } }
    }
}

How do I pass named parameters with Invoke-Command?

I needed something to call scripts with named parameters. We have a policy of not using ordinal positioning of parameters and requiring the parameter name.

My approach is similar to the ones above but gets the content of the script file that you want to call and sends a parameter block containing the parameters and values.

One of the advantages of this is that you can optionally choose which parameters to send to the script file allowing for non-mandatory parameters with defaults.

Assuming there is a script called "MyScript.ps1" in the temporary path that has the following parameter block:

[CmdletBinding(PositionalBinding = $False)]
param
(
    [Parameter(Mandatory = $True)] [String] $MyNamedParameter1,
    [Parameter(Mandatory = $True)] [String] $MyNamedParameter2,
    [Parameter(Mandatory = $False)] [String] $MyNamedParameter3 = "some default value"
)

This is how I would call this script from another script:

$params = @{
    MyNamedParameter1 = $SomeValue
    MyNamedParameter2 = $SomeOtherValue
}

If ($SomeCondition)
{
    $params['MyNamedParameter3'] = $YetAnotherValue
}

$pathToScript = Join-Path -Path $env:Temp -ChildPath MyScript.ps1

$sb = [scriptblock]::create(".{$(Get-Content -Path $pathToScript -Raw)} $(&{
        $args
} @params)")
Invoke-Command -ScriptBlock $sb

I have used this in lots of scenarios and it works really well. One thing that you occasionally need to do is put quotes around the parameter value assignment block. This is always the case when there are spaces in the value.

e.g. This param block is used to call a script that copies various modules into the standard location used by PowerShell C:\Program Files\WindowsPowerShell\Modules which contains a space character.

$params = @{
        SourcePath      = "$WorkingDirectory\Modules"
        DestinationPath = "'$(Join-Path -Path $([System.Environment]::GetFolderPath('ProgramFiles')) -ChildPath 'WindowsPowershell\Modules')'"
    }

Hope this helps!

How to create a stopwatch using JavaScript?

well after a few modification of the code provided by mace,i ended up building a stopwatch. https://codepen.io/truestbyheart/pen/EGELmv

  <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Stopwatch</title>
    <style>
    #center {
     margin: 30%  30%;
     font-family: tahoma;
     }
    .stopwatch {
         border:1px solid #000;
         background-color: #eee;
         text-align: center;
         width:656px;
         height: 230px;
         overflow: hidden;
     }
     .stopwatch span{
         display: block;
         font-size: 100px;
     }
     .stopwatch p{
         display: inline-block;
         font-size: 40px;
     }
     .stopwatch a{
       font-size:45px;
     }
     a:link,
     a:visited{
         color :#000;
         text-decoration: none;
         padding: 12px 14px;
         border: 1px solid #000;
     }
    </style>
  </head>
  <body>
      <div id="center">
            <div class="timer stopwatch"></div>
      </div>

    <script>
      const Stopwatch = function(elem, options) {
        let timer = createTimer(),
          startButton = createButton("start", start),
          stopButton = createButton("stop", stop),
          resetButton = createButton("reset", reset),
          offset,
          clock,
          interval,
          hrs = 0,
          min = 0;

        // default options
        options = options || {};
        options.delay = options.delay || 1;

        // append elements
        elem.appendChild(timer);
        elem.appendChild(startButton);
        elem.appendChild(stopButton);
        elem.appendChild(resetButton);

        // initialize
        reset();

        // private functions
        function createTimer() {
          return document.createElement("span");
        }

        function createButton(action, handler) {
          if (action !== "reset") {
            let a = document.createElement("a");
            a.href = "#" + action;
            a.innerHTML = action;
            a.addEventListener("click", function(event) {
              handler();
              event.preventDefault();
            });
            return a;
          } else if (action === "reset") {
            let a = document.createElement("a");
            a.href = "#" + action;
            a.innerHTML = action;
            a.addEventListener("click", function(event) {
              clean();
              event.preventDefault();
            });
            return a;
          }
        }

        function start() {
          if (!interval) {
            offset = Date.now();
            interval = setInterval(update, options.delay);
          }
        }

        function stop() {
          if (interval) {
            clearInterval(interval);
            interval = null;
          }
        }

        function reset() {
          clock = 0;
          render(0);
        }

        function clean() {
          min = 0;
          hrs = 0;
          clock = 0;
          render(0);
        }

        function update() {
          clock += delta();
          render();
        }

        function render() {
          if (Math.floor(clock / 1000) === 60) {
            min++;
            reset();
            if (min === 60) {
              min = 0;
              hrs++;
            }
          }
          timer.innerHTML =
            hrs + "<p>hrs</p>" + min + "<p>min</p>" + Math.floor(clock / 1000)+ "<p>sec</p>";
        }

        function delta() {
          var now = Date.now(),
            d = now - offset;

          offset = now;
          return d;
        }
      };

      // Initiating the Stopwatch
      var elems = document.getElementsByClassName("timer");

      for (var i = 0, len = elems.length; i < len; i++) {
        new Stopwatch(elems[i]);
      }
    </script>
  </body>
</html>

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.

Replace non-ASCII characters with a single space

For you the get the most alike representation of your original string I recommend the unidecode module:

from unidecode import unidecode
def remove_non_ascii(text):
    return unidecode(unicode(text, encoding = "utf-8"))

Then you can use it in a string:

remove_non_ascii("Ceñía")
Cenia

How to reference image resources in XAML?

If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:

<Image Source="/Icons/play_small.png" />

That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:

var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;

var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;

var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();

this.image1.Source = bitmapImage;

Changing the action of a form with JavaScript/jQuery

You can actually just use

$("#form").attr("target", "NewAction");

As far as I know, this will NOT fail silently.

If the page is opening in a new target, you may need to make sure the URL is unique each time because Webkit (chrome/safari) will cache the fact you have visited that URL and won't perform the post.

For example

$("form").attr("action", "/Pages/GeneratePreview?" + new Date().getMilliseconds());

Deleting row from datatable in C#

Try using Delete method:

    DataRow[] drr = dt.Select("Student=' " + id + " ' "); 
    for (int i = 0; i < drr.Length; i++)
        drr[i].Delete();
    dt.AcceptChanges();

How to run a script file remotely using SSH

You can do:

ssh user@host 'bash -s' < /path/script.sh

How to sort a data frame by alphabetic order of a character variable in R?

The order() function fails when the column has levels or factor. It works properly when stringsAsFactors=FALSE is used in data.frame creation.

css 'pointer-events' property alternative for IE

I faced similar issues:

  1. I faced this issue in a directive, i fixed it adding a as its parent element and making pointer-events:none for that

  2. The above fix did not work for select tag, then i added cursor:text (which was what i wanted) and it worked for me

If a normal cursor is needed you could add cursor:default

Can PHP cURL retrieve response headers AND body in a single request?

Here is my contribution to the debate ... This returns a single array with the data separated and the headers listed. This works on the basis that CURL will return a headers chunk [ blank line ] data

curl_setopt($ch, CURLOPT_HEADER, 1); // we need this to get headers back
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);

// $output contains the output string
$output = curl_exec($ch);

$lines = explode("\n",$output);

$out = array();
$headers = true;

foreach ($lines as $l){
    $l = trim($l);

    if ($headers && !empty($l)){
        if (strpos($l,'HTTP') !== false){
            $p = explode(' ',$l);
            $out['Headers']['Status'] = trim($p[1]);
        } else {
            $p = explode(':',$l);
            $out['Headers'][$p[0]] = trim($p[1]);
        }
    } elseif (!empty($l)) {
        $out['Data'] = $l;
    }

    if (empty($l)){
        $headers = false;
    }
}

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

How to measure time taken by a function to execute

var StopWatch = function (performance) {
    this.startTime = 0;
    this.stopTime = 0;
    this.running = false;
    this.performance = performance === false ? false : !!window.performance;
};

StopWatch.prototype.currentTime = function () {
    return this.performance ? window.performance.now() : new Date().getTime();
};

StopWatch.prototype.start = function () {
    this.startTime = this.currentTime();
    this.running = true;
};

StopWatch.prototype.stop = function () {
    this.stopTime = this.currentTime();
    this.running = false;
};

StopWatch.prototype.getElapsedMilliseconds = function () {
    if (this.running) {
        this.stopTime = this.currentTime();
    }

    return this.stopTime - this.startTime;
};

StopWatch.prototype.getElapsedSeconds = function () {
    return this.getElapsedMilliseconds() / 1000;
};

StopWatch.prototype.printElapsed = function (name) {
    var currentName = name || 'Elapsed:';

    console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};

Benchmark

var stopwatch = new StopWatch();
stopwatch.start();

for (var index = 0; index < 100; index++) {
    stopwatch.printElapsed('Instance[' + index + ']');
}

stopwatch.stop();

stopwatch.printElapsed();

Output

Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]

performance.now() is optional - just pass false into StopWatch constructor function.

Responsive web design is working on desktop but not on mobile device

Though it is answered above and it is right to use

<meta name="viewport" content="width=device-width, initial-scale=1">

but if you are using React and webpack then don't forget to close the element tag

<meta name="viewport" content="width=device-width, initial-scale=1" />

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

Check if there is any conflict in your IIS authentication. i.e. you enable the anonymous authentication and ASP.NET impersonation both might cause the error also.

SUM of grouped COUNT in SQL Query

You can try group by on name and count the ids in that group.

SELECT name, count(id) as COUNT FROM table group by name

How do I clear all variables in the middle of a Python script?

In the idle IDE there is Shell/Restart Shell. Cntrl-F6 will do it.

How to get the innerHTML of selectable jquery element?

The parameter ui has a property called selected which is a reference to the selected dom element, you can call innerHTML on that element.

Your code $('.ui-selected').innerHTML tries to return the innerHTML property of a jQuery wrapper element for a dom element with class ui-selected

$(function () {
    $("#select-image").selectable({
        selected: function (event, ui) {
            var $variable = ui.selected.innerHTML; // or $(ui.selected).html()
            console.log($variable);
        }
    });
});

Demo: Fiddle

JTable How to refresh table model after insert delete or update the data.

The faster way for your case is:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.

Show SOME invisible/whitespace characters in Eclipse

Unfortunately, you can only turn on all invisible (whitespace) characters at the same time. I suggest you file an enhancement request but I doubt they will pick it up.

The text component in Eclipse is very complicated as it is and they are not keen on making them even worse.

[UPDATE] This has been fixed in Eclipse 3.7: Go to Window > Preferences > General > Editors > Text Editors

Click on the link "whitespace characters" to fine tune what should be shown.

Kudos go to John Isaacks

Pass parameter from a batch file to a PowerShell script

The answer from @Emiliano is excellent. You can also pass named parameters like so:

powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"

Note the parameters are outside the command call, and you'll use:

[parameter(Mandatory=$false)]
  [string]$NamedParam1,
[parameter(Mandatory=$false)]
  [string]$NamedParam2

What does <a href="#" class="view"> mean?

Javascript may be hooking up to the click-event of the anchor, rather than injecting any href.

For example, jQuery:

$('a.view').click(function() { Alert('anchor without a href was clicked');});

Of course, the javascript can do anything it wants with the click event--such as navigate to some other page (in which case the href is never set, but the anchor still behaves as though it were)

How to download and save a file from Internet using Java?

To summarize (and somehow polish and update) previous answers. The three following methods are practically equivalent. (I added explicit timeouts because I think they are a must, nobody wants a download to freeze forever when the connection is lost.)

public static void saveUrl1(final Path file, final URL url,
   int secsConnectTimeout, int secsReadTimeout)) 
    throws MalformedURLException, IOException {
    // Files.createDirectories(file.getParent()); // optional, make sure parent dir exists
    try (BufferedInputStream in = new BufferedInputStream(
       streamFromUrl(url, secsConnectTimeout,secsReadTimeout)  );
        OutputStream fout = Files.newOutputStream(file)) {
        final byte data[] = new byte[8192];
        int count;
        while((count = in.read(data)) > 0)
            fout.write(data, 0, count);
    }
}

public static void saveUrl2(final Path file, final URL url,
   int secsConnectTimeout, int secsReadTimeout))  
    throws MalformedURLException, IOException {
    // Files.createDirectories(file.getParent()); // optional, make sure parent dir exists
    try (ReadableByteChannel rbc = Channels.newChannel(
      streamFromUrl(url, secsConnectTimeout,secsReadTimeout) 
        );
        FileChannel channel = FileChannel.open(file,
             StandardOpenOption.CREATE, 
             StandardOpenOption.TRUNCATE_EXISTING,
             StandardOpenOption.WRITE) 
        ) {
        channel.transferFrom(rbc, 0, Long.MAX_VALUE);
    }
}

public static void saveUrl3(final Path file, final URL url, 
   int secsConnectTimeout, int secsReadTimeout))  
    throws MalformedURLException, IOException {
    // Files.createDirectories(file.getParent()); // optional, make sure parent dir exists
    try (InputStream in = streamFromUrl(url, secsConnectTimeout,secsReadTimeout) ) {
        Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING);
    }
}

public static InputStream streamFromUrl(URL url,int secsConnectTimeout,int secsReadTimeout) throws IOException {
    URLConnection conn = url.openConnection();
    if(secsConnectTimeout>0) conn.setConnectTimeout(secsConnectTimeout*1000);
    if(secsReadTimeout>0) conn.setReadTimeout(secsReadTimeout*1000);
    return conn.getInputStream();
}

I don't find significant differences, all seem right to me. They are safe and efficient. (Differences in speed seem hardly relevant - I write 180Mb from local server to a SSD disk in times that fluctuate around 1.2 to 1.5 segs). They don't require external libraries. All work with arbitrary sizes and (to my experience) HTTP redirections.

Additionally, all throw FileNotFoundException if the resource is not found (error 404, typically), and java.net.UnknownHostException if the DNS resolution failed; other IOException correspond to errors during transmission.

(Marked as community wiki, feel free to add info or corrections)

Click button copy to clipboard using jQuery

As of 2020, you should use the Clipboard Api.

navigator.clipboard.writeText('text here you want to copy').then(function () {
    alert('It worked! Do a CTRL - V to paste')
}, function () {
    alert('Failure to copy. Check permissions for clipboard')
});

Here is more info about interacting with the clipboard

CSS @media print issues with background-color;

Tested and Working over Chrome, Firefox, Opera and Edge by 2016/10. Should work on any browser and should always look as expected.

Ok, I did a little cross-browser experiment for printing background colors. Just copy, paste & enjoy!

Here it is a full printable HTML page for bootstrap:

<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">

    /* Both z-index are resolving recursive element containment */
    [background-color] {
        z-index: 0;
        position: relative;
        -webkit-print-color-adjust: exact !important;
    }

    [background-color] canvas {
        display: block;
        position:absolute;
        z-index: -1;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

</style>
</head>

<!-- CONTENT -->
<body>

    <!-- PRINT ROW BLOCK -->
    <div class="container">

    <div class="row">
        <div class="col-xs-6">
            <div background-color="#A400C1">
                <h4>
                Hey... this works !
                </h4>
                <div background-color="#0068C1">
                    <p>
                    Ohh... this works recursive too !!
                    <div background-color="green" style="width: 80px; height: 60px">
                        Any size !!
                    </div>
                    </p>
                </div>
            </div>
        </div>

        <div class="col-xs-6">
            <div background-color="#FFCB83" style="height: 200px">
                Some content...
            </div>
        </div>

    </div>


<script>
    var containers = document.querySelectorAll("[background-color]");

    for (i = 0; i < containers.length; i++)
    {
        // Element
        var container = containers[i];
        container.insertAdjacentHTML('beforeend', '<canvas id="canvas-' + i + '"></canvas>');

        // Color
        var color = container.getAttribute("background-color");
        container.style.backgroundColor = color;

        // Inner Canvas
        var canvas = document.getElementById("canvas-" + i);
        canvas.width = container.offsetWidth;
        canvas.height = container.offsetHeight;
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = color;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    }

    window.print();
</script>


</body>

</html>

App.Config change value

That worked for me in WPF application:

string configPath = Path.Combine(System.Environment.CurrentDirectory, "YourApplication.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
config.AppSettings.Settings["currentLanguage"].Value = "En";
config.Save();

SQL (MySQL) vs NoSQL (CouchDB)

One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use

IntelliJ does not show 'Class' when we right click and select 'New'

The directory or one of the parent directories must be marked as Source Root (In this case, it appears in blue).

If this is not the case, right click your root source directory -> Mark As -> Source Root.

Adding Permissions in AndroidManifest.xml in Android Studio?

It's quite simple.

All you need to do is:

  • Right click above application tag and click on Generate
  • Click on XML tag
  • Click on user-permission
  • Enter the name of your permission.

PHP validation/regex for URL

I used this on a few projects, I don't believe I've run into issues, but I'm sure it's not exhaustive:

$text = preg_replace(
  '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i',
  "'<a href=\"$1\" target=\"_blank\">$3</a>$4'",
  $text
);

Most of the random junk at the end is to deal with situations like http://domain.com. in a sentence (to avoid matching the trailing period). I'm sure it could be cleaned up but since it worked. I've more or less just copied it over from project to project.

Android: Proper Way to use onBackPressed() with Toast

additionally, you need to dissmis dialog before calling activity.super.onBackPressed(), otherwise you'll get "Activity has leaked.." error.

Example in my case with sweetalerdialog library:

 @Override
    public void onBackPressed() {
        //super.onBackPressed();
        SweetAlertDialog progressDialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
        progressDialog.setCancelable(false);
        progressDialog.setTitleText("Are you sure you want to exit?");
        progressDialog.setCancelText("No");
        progressDialog.setConfirmText("Yes");
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
                MainActivity.super.onBackPressed();
            }
        });
        progressDialog.show();
    }

Select current element in jQuery

Fortunately, jQuery selectors allow you much more freedom:

$("div a").click( function(event)
{
   var clicked = $(this); // jQuery wrapper for clicked element
   // ... click-specific code goes here ...
});

...will attach the specified callback to each <a> contained in a <div>.

Import an existing git project into GitLab?

I was able to fully export my project along with all commits, branches and tags to gitlab via following commands run locally on my computer:

To illustrate my example, I will be using https://github.com/raveren/kint as the source repository that I want to import into gitlab. I created an empty project named Kint (under namespace raveren) in gitlab beforehand and it told me the http git url of the newly created project there is http://gitlab.example.com/raveren/kint.git

The commands are OS agnostic.

In a new directory:

git clone --mirror https://github.com/raveren/kint
cd kint.git
git remote add gitlab http://gitlab.example.com/raveren/kint.git
git push gitlab --mirror

Now if you have a locally cloned repository that you want to keep using with the new remote, just run the following commands* there:

git remote remove origin
git remote add origin http://gitlab.example.com/raveren/kint.git
git fetch --all

*This assumes that you did not rename your remote master from origin, otherwise, change the first two lines to reflect it.

PHP Regex to check date is in YYYY-MM-DD format

preg_match needs a / or another char as delimiter.

preg_match("/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/",$date)

you also should check for validity of that date so you wouldn't end up with something like 9999-19-38

bool checkdate ( int $month , int $day , int $year )

What is the minimum I have to do to create an RPM file?

RPMs are usually built from source, not the binaries.

You need to write the spec file that covers how to configure and compile your application; also, which files to include in your RPM.

A quick glance at the manual shows that most of what you need is covered in Chapter 8 -- also, as most RPM-based distributions have sources available, there's literally a zillion of examples of different approaches you could look at.

Removing duplicates from a list of lists

a_list = [
          [1,2],
          [1,2],
          [2,3],
          [3,4]
]

print (list(map(list,set(map(tuple,a_list)))))

outputs: [[1, 2], [3, 4], [2, 3]]

How to select following sibling/xml tag using xpath

How would I accomplish the nextsibling and is there an easier way of doing this?

You may use:

tr/td[@class='name']/following-sibling::td

but I'd rather use directly:

tr[td[@class='name'] ='Brand']/td[@class='desc']

This assumes that:

  1. The context node, against which the XPath expression is evaluated is the parent of all tr elements -- not shown in your question.

  2. Each tr element has only one td with class attribute valued 'name' and only one td with class attribute valued 'desc'.

How to sign in kubernetes dashboard?

TL;DR

To get the token in a single oneliner:

kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | awk '/^deployment-controller-token-/{print $1}') | awk '$1=="token:"{print $2}'

This assumes that your ~/.kube/config is present and valid. And also that kubectl config get-contexts indicates that you are using the correct context (cluster and namespace) for the dashboard you are logging into.

Explanation

I derived this answer from what I learned from @silverfox's answer. That is a very informative write up. Unfortunately it falls short of telling you how to actually put the information into practice. Maybe I've been doing DevOps too long, but I think in shell. It's much more difficult for me to learn or teach in English.

Here is that oneliner with line breaks and indents for readability:

kubectl -n kube-system describe secret $(
  kubectl -n kube-system get secret | \
  awk '/^deployment-controller-token-/{print $1}'
) | \
awk '$1=="token:"{print $2}'

There are 4 distinct commands and they get called in this order:

  • Line 2 - This is the first command from @silverfox's Token section.
  • Line 3 - Print only the first field of the line beginning with deployment-controller-token- (which is the pod name)
  • Line 1 - This is the second command from @silverfox's Token section.
  • Line 5 - Print only the second field of the line whose first field is "token:"

How do I print bold text in Python?

You can use termcolor for this:

 sudo pip install termcolor

To print a colored bold:

 from termcolor import colored
 print(colored('Hello', 'green', attrs=['bold']))

For more information, see termcolor on PyPi.

simple-colors is another package with similar syntax:

 from simple_colors import *
 print(green('Hello', ['bold'])

The equivalent in colorama may be Style.BRIGHT.

Edit seaborn legend

Took me a while to read through the above. This was the answer for me:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=False
)

plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)

Reference this for more arguments: matplotlib.pyplot.legend

enter image description here

How to add bootstrap to an angular-cli project

angular-cli now has a dedicated wiki page where you can find everything you need. TLDR, install bootstrap via npm and add the styles link to "styles" section in your .angular-cli.json file

SOAP or REST for Web Services?

I know this is an old question but I have to post my answer - maybe someone will find it useful. I can't believe how many people are recommending REST over SOAP. I can only assume these people are not developers or have never actually implemented a REST service of any reasonable size. Implementing a REST service takes a LOT longer than implementing a SOAP service. And in the end it comes out a lot messier, too. Here are the reasons I would choose SOAP 99% of the time:

1) Implementing a REST service takes infinitely longer than implementing a SOAP service. Tools exist for all modern languages/frameworks/platforms to read in a WSDL and output proxy classes and clients. Implementing a REST service is done by hand and - get this - by reading documentation. Furthermore, while implementing these two services, you have to make "guesses" as to what will come back across the pipe as there is no real schema or reference document.

2) Why write a REST service that returns XML anyway? The only difference is that with REST you don't know the types each element/attribute represents - you are on your own to implement it and hope that one day a string doesn't come across in a field you thought was always an int. SOAP defines the data structure using the WSDL so this is a no-brainer.

3) I've heard the complaint that with SOAP you have the "overhead" of the SOAP Envelope. In this day and age, do we really need to worry about a handful of bytes?

4) I've heard the argument that with REST you can just pop the URL into the browser and see the data. Sure, if your REST service is using simple or no authentication. The Netflix service, for instance, uses OAuth which requires you to sign things and encode things before you can even submit your request.

5) Why do we need a "readable" URL for each resource? If we were using a tool to implement the service, do we really care about the actual URL?

Need I go on?

PHP get dropdown value and text

you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown

$("#dropdownid").val();   for value
$("#dropdownid").text(); for selected value

catch these into two variables and take it as inputs to ajax call for a php file

$.ajax 
   ({
     url:"callingphpfile.php",//url of fetching php  
     method:"POST", //type 
     data:"val1="+value+"&val2="+selectedtext,
     success:function(data) //return the data     
     {

}

and in php you can get it as

    if (isset($_POST["val1"])) {
    $val1= $_POST["val1"] ;
}

if (isset($_POST["val2"])) {
  $selectedtext= $_POST["val1"];
}

Vue.js img src concatenate variable and text

if you handel this from dataBase try :

<img :src="baseUrl + 'path/path' + obj.key +'.png'">

How to activate JMX on my JVM for access with jconsole?

I had this exact issue, and created a GitHub project for testing and figuring out the correct settings.

It contains a working Dockerfile with supporting scripts, and a simple docker-compose.yml for quick testing.

How to get multiple selected values from select box in JSP?

Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.

Update: save the file as test.jsp and run it on any web/app server

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>

check if variable is dataframe

Use the built-in isinstance() function.

import pandas as pd

def f(var):
    if isinstance(var, pd.DataFrame):
        print("do stuff")

Linux shell sort file according to the second column?

If this is UNIX:

sort -k 2 file.txt

You can use multiple -k flags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:

sort -k 2,2 -k 1,1 file.txt

Relevant options from "man sort":

-k, --key=POS1[,POS2]

start a key at POS1, end it at POS2 (origin 1)

POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

-t, --field-separator=SEP

use SEP instead of non-blank to blank transition

Fetching data from MySQL database using PHP, Displaying it in a form for editing

Play around this piece of code. Focus on the concept, edit where necessary so that it can

<html>
<head>
    <title> Delegate edit form</title>
</head>
<body>
    Delegate update form  </p>

    <meta name="viewport" content="width=device-width; initial-scale=1.0">

    <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />


    <link href='http://fonts.googleapis.com/css?family=Droid+Serif|Ubuntu' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="js/flexslider/flexslider.css" />
    <link rel="stylesheet" href="css/basic-style.css">




    <script src="js/libs/modernizr-2.6.2.min.js"></script>

    </head>

    <body id="home">

        <header class="wrapper clearfix">



            <nav id="topnav" role="navigation">
                <div class="menu-toggle">Menu</div>
                <ul class="srt-menu" id="menu-main-navigation">
                    <li><a href="Swift_Landing.html">Home page</a></li>

        </header>
        </section>

        <style>
            form label {
                display: inline-block;
                width: 100px;
                font-weight: bold;
            }
        </style>
        </ul>

        <?php
        session_start();
        $usernm="root";
        $passwd="";
        $host="localhost";
        $database="swift";

        $Username=$_SESSION['myssession'];



        mysql_connect($host,$usernm,$passwd);

        mysql_select_db($database);

        $sql = "SELECT * FROM usermaster WHERE User_name='$Username'";
        $result = mysql_query ($sql) or die (mysql_error ());
        while ($row = mysql_fetch_array ($result)){

        ?>

        <form action="Delegate_update.php" method="post">
            Name
            <input type="text" name="Namex" value="<?php echo $row ['Name']; ?> " size=10>
            Username
            <input type="text" name="Username" value="<?php echo $row ['User_name']; ?> " size=10>
            Password
            <input type="text" name="Password" value="<?php echo $row ['User_password']; ?>" size=17>
            <input type="submit" name="submit" value="Update">
        </form>
        <?php
        }
        ?>
        </p>
    </body>
</html>

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call Stored Procedure like this inside Stored Procedure B.

CREATE PROCEDURE spA
@myDate DATETIME
AS
    EXEC spB @myDate

RETURN 0

`ui-router` $stateParams vs. $state.params

I have a root state which resolves sth. Passing $state as a resolve parameter won't guarantee the availability for $state.params. But using $stateParams will.

var rootState = {
    name: 'root',
    url: '/:stubCompanyId',
    abstract: true,
    ...
};

// case 1:
rootState.resolve = {
    authInit: ['AuthenticationService', '$state', function (AuthenticationService, $state) {
        console.log('rootState.resolve', $state.params);
        return AuthenticationService.init($state.params);
    }]
};
// output:
// rootState.resolve Object {}

// case 2:
rootState.resolve = {
    authInit: ['AuthenticationService', '$stateParams', function (AuthenticationService, $stateParams) {
        console.log('rootState.resolve', $stateParams);
        return AuthenticationService.init($stateParams);
    }]
};
// output:
// rootState.resolve Object {stubCompanyId:...}

Using "angular": "~1.4.0", "angular-ui-router": "~0.2.15"

Undefined symbols for architecture armv7

I use to face that issue when the module (file .m) is not in the target that I am working with.

Using a dictionary to count the items in a list

>>> L = ['apple','red','apple','red','red','pear']
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in L:
...   d[i] += 1
>>> d
defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3})

How to read from stdin with fgets()?

Exits the loop if the line is empty(Improving code).

#include <stdio.h>
#include <string.h>

// The value BUFFERSIZE can be changed to customer's taste . Changes the
// size of the base array (string buffer )    
#define BUFFERSIZE 10

int main(void)
{
    char buffer[BUFFERSIZE];
    char cChar;
    printf("Enter a message: \n");
    while(*(fgets(buffer, BUFFERSIZE, stdin)) != '\n')
    {
        // For concatenation
        // fgets reads and adds '\n' in the string , replace '\n' by '\0' to 
        // remove the line break .
/*      if(buffer[strlen(buffer) - 1] == '\n')
            buffer[strlen(buffer) - 1] = '\0'; */
        printf("%s", buffer);
        // Corrects the error mentioned by Alain BECKER.       
        // Checks if the string buffer is full to check and prevent the 
        // next character read by fgets is '\n' .
        if(strlen(buffer) == (BUFFERSIZE - 1) && (buffer[strlen(buffer) - 1] != '\n'))
        {
            // Prevents end of the line '\n' to be read in the first 
            // character (Loop Exit) in the next loop. Reads
            // the next char in stdin buffer , if '\n' is read and removed, if
            // different is returned to stdin 
            cChar = fgetc(stdin);
            if(cChar != '\n')
                ungetc(cChar, stdin);
            // To print correctly if '\n' is removed.
            else
                printf("\n");
        }
    }
    return 0;
}

Exit when Enter is pressed.

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>

#define BUFFERSIZE 16

int main(void)
{
    char buffer[BUFFERSIZE];
    printf("Enter a message: \n");
    while(true)
    {
        assert(fgets(buffer, BUFFERSIZE, stdin) != NULL);
        // Verifies that the previous character to the last character in the
        // buffer array is '\n' (The last character is '\0') if the
        // character is '\n' leaves loop.
        if(buffer[strlen(buffer) - 1] == '\n')
        {
            // fgets reads and adds '\n' in the string, replace '\n' by '\0' to 
            // remove the line break .
            buffer[strlen(buffer) - 1] = '\0';
            printf("%s", buffer);
            break;
        }
        printf("%s", buffer);   
    }
    return 0;
}

Concatenation and dinamic allocation(linked list) to a single string.

/* Autor : Tiago Portela
   Email : [email protected]
   Sobre : Compilado com TDM-GCC 5.10 64-bit e LCC-Win32 64-bit;
   Obs : Apenas tentando aprender algoritimos, sozinho, por hobby. */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>

#define BUFFERSIZE 8

typedef struct _Node {
    char *lpBuffer;
    struct _Node *LpProxNode;
} Node_t, *LpNode_t;

int main(void)
{
    char acBuffer[BUFFERSIZE] = {0};
    LpNode_t lpNode = (LpNode_t)malloc(sizeof(Node_t));
    assert(lpNode!=NULL);
    LpNode_t lpHeadNode = lpNode;
    char* lpBuffer = (char*)calloc(1,sizeof(char));
    assert(lpBuffer!=NULL);
    char cChar;


    printf("Enter a message: \n");
    // Exit when Enter is pressed
/*  while(true)
    {
        assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
        lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
        assert(lpNode->lpBuffer!=NULL);
        strcpy(lpNode->lpBuffer, acBuffer);
        if(lpNode->lpBuffer[strlen(acBuffer) - 1] == '\n')
        {
            lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
            lpNode->LpProxNode = NULL;
            break;
        }
        lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
        lpNode = lpNode->LpProxNode;
        assert(lpNode!=NULL);
    }*/

    // Exits the loop if the line is empty(Improving code).
    while(true)
    {
        assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
        lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
        assert(lpNode->lpBuffer!=NULL);
        strcpy(lpNode->lpBuffer, acBuffer);
        if(acBuffer[strlen(acBuffer) - 1] == '\n')
            lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
        if(strlen(acBuffer) == (BUFFERSIZE - 1) && (acBuffer[strlen(acBuffer) - 1] != '\n'))
        {
            cChar = fgetc(stdin);
            if(cChar != '\n')
                ungetc(cChar, stdin);
        }
        if(acBuffer[0] == '\n')
        {
            lpNode->LpProxNode = NULL;
            break;
        }
        lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
        lpNode = lpNode->LpProxNode;
        assert(lpNode!=NULL);
    }


    printf("\nPseudo String :\n");
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        printf("%s", lpNode->lpBuffer);
        lpNode = lpNode->LpProxNode;
    }


    printf("\n\nMemory blocks:\n");
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        printf("Block \"%7s\" size = %lu\n", lpNode->lpBuffer, (long unsigned)(strlen(lpNode->lpBuffer) + 1));
        lpNode = lpNode->LpProxNode;
    }


    printf("\nConcatenated string:\n");
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        lpBuffer = (char*)realloc(lpBuffer, (strlen(lpBuffer) + strlen(lpNode->lpBuffer)) + 1);
        strcat(lpBuffer, lpNode->lpBuffer);
        lpNode = lpNode->LpProxNode;
    }
    printf("%s", lpBuffer);
    printf("\n\n");

    // Deallocate memory
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        lpHeadNode = lpNode->LpProxNode;
        free(lpNode->lpBuffer);
        free(lpNode);
        lpNode = lpHeadNode;
    }
    lpBuffer = (char*)realloc(lpBuffer, 0);
    lpBuffer = NULL;
    if((lpNode == NULL) && (lpBuffer == NULL))
    {

        printf("Deallocate memory = %s", (char*)lpNode);
    }
    printf("\n\n");

    return 0;
}

How to test abstract class in Java with JUnit?

Create a concrete class that inherits the abstract class and then test the functions the concrete class inherits from the abstract class.

How Should I Set Default Python Version In Windows?

Nothing above worked, this is what worked for me:

ftype Python.File=C:\Path\to\python.exe "%1" %*

This command should be run in Command prompt launched as administrator

Warning: even if the path in this command is set to python35, if you have python36 installed it's going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36 to xxPython36, run the command and then remove the change to the Python 36 folder.

How to indent a few lines in Markdown markup?

Another alternative is to use a markdown editor like StackEdit. It converts html (or text) into markdown in a WYSIWYG editor. You can create indents, titles, lists in the editor, and it will show you the corresponding text in markdown format. You can then save, publish, share, or download the file. You can access it on their website - no downloads required!

How to make a simple modal pop up form using jquery and html?

I have placed here complete bins for above query. you can check demo link too.

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

HTML

<div id="panel">
  <input type="button" class="button" value="1" id="btn1">
  <input type="button" class="button" value="2" id="btn2">
  <input type="button" class="button" value="3" id="btn3">
  <br>
  <input type="text" id="valueFromMyModal">
  <!-- Dialog Box-->
  <div class="dialog" id="myform">
    <form>
      <label id="valueFromMyButton">
      </label>
      <input type="text" id="name">
      <div align="center">
        <input type="button" value="Ok" id="btnOK">
      </div>
    </form>
  </div>
</div>

JQuery

$(function() {
    $(".button").click(function() {
        $("#myform #valueFromMyButton").text($(this).val().trim());
        $("#myform input[type=text]").val('');
        $("#myform").show(500);
    });
    $("#btnOK").click(function() {
        $("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
        $("#myform").hide(400);
    });
});

CSS

.button{
  border:1px solid #333;
  background:#6479fd;
}
.button:hover{
  background:#a4a9fd;
}
.dialog{
  border:5px solid #666;
  padding:10px;
  background:#3A3A3A;
  position:absolute;
  display:none;
}
.dialog label{
  display:inline-block;
  color:#cecece;
}
input[type=text]{
  border:1px solid #333;
  display:inline-block;
  margin:5px;
}
#btnOK{
  border:1px solid #000;
  background:#ff9999;
  margin:5px;
}

#btnOK:hover{
  border:1px solid #000;
  background:#ffacac;
}

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

How do I check if a string is unicode or ascii?

use:

import six
if isinstance(obj, six.text_type)

inside the six library it is represented as:

if PY3:
    string_types = str,
else:
    string_types = basestring,

Can we open pdf file using UIWebView on iOS?

UIWebView *pdfWebView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

NSURL *targetURL = [NSURL URLWithString:@"http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf"];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [pdfWebView loadRequest:request];
    [self.view addSubview:pdfWebView];

How to find prime numbers between 0 - 100?

I recently came up with a one-line solution that accomplishes exactly this for a JS challenge on Scrimba (below).

ES6+

const getPrimes=num=>Array(num-1).fill().map((e,i)=>2+i).filter((e,i,a)=>a.slice(0,i).every(x=>e%x!==0));

< ES6

function getPrimes(num){return ",".repeat(num).slice(0,-1).split(',').map(function(e,i){return i+1}).filter(function(e){return e>1}).filter(function(x){return ",".repeat(x).slice(0,-1).split(',').map(function(f,j){return j}).filter(function(e){return e>1}).every(function(e){return x%e!==0})})};

This is the logic explained:

  1. First, the function builds an array of all numbers leading up to the desired number (in this case, 100) via the .repeat() function using the desired number (100) as the repeater argument and then mapping the array to the indexes+1 to get the range of numbers from 0 to that number (0-100). A bit of string splitting and joining magic going on here. I'm happy to explain this step further if you like.

  2. We exclude 0 and 1 from the array as they should not be tested for prime, lest they give a false positive. Neither are prime. We do this using .filter() for only numbers > 1 (= 2).

  3. Now, we filter our new array of all integers between 2 and the desired number (100) for only prime numbers. To filter for prime numbers only, we use some of the same magic from our first step. We use .filter() and .repeat() once again to create a new array from 2 to each value from our new array of numbers. For each value's new array, we check to see if any of the numbers = 2 and < that number are factors of the number. We can do this using the .every() method paired with the modulo operator % to check if that number has any remainders when divided by any of those values between 2 and itself. If each value has remainders (x%e!==0), the condition is met for all values from 2 to that number (but not including that number, i.e.: [2,99]) and we can say that number is prime. The filter functions returns all prime numbers to the uppermost return, thereby returning the list of prime values between 2 and the passed value.

As an example, using one of these functions I've added above, returns the following:

getPrimes(100);
// => [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]

Datagrid binding in WPF

try to do this in the behind code

   public diagboxclass()
   {
         List<object> list = new List<object>();
         list = GetObjectList();
         Imported.ItemsSource = null;
         Imported.ItemsSource = list;
   }

Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.

Return an empty Observable

RxJS 6

you can use also from function like below:

return from<string>([""]);

after import:

import {from} from 'rxjs';

How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".force_encoding('ASCII-8BIT')
puts CGI.escape str


=> "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

Saving a text file on server using JavaScript

It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.

However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:

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

And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!

File uploading (most of this applies if sending plain text too if javascript can choose the name of the file) http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security https://www.owasp.org/index.php/Unrestricted_File_Upload

How to convert string to integer in C#

int i;

string result = Something;

i = Convert.ToInt32(result);

Clone contents of a GitHub repository (without the folder itself)

You can specify the destination directory as second parameter of the git clone command, so you can do:

git clone <remote> .

This will clone the repository directly in the current local directory.

How to ORDER BY a SUM() in MySQL?

Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.

Try this:

SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname

OR this:

SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2

And you can always do a derived query like this:

SELECT
   f1, f2
FROM
    (
        SELECT SUM(x+y) as f1, foo as F2
        FROM tablename 
        GROUP BY f2
    ) as table1
ORDER BY 
    f1

Many possibilities!

Summarizing multiple columns with dplyr?

You can simply pass more arguments to summarise:

df %>% group_by(grp) %>% summarise(mean(a), mean(b), mean(c), mean(d))

Source: local data frame [3 x 5]

  grp  mean(a)  mean(b)  mean(c) mean(d)
1   1 2.500000 3.500000 2.000000     3.0
2   2 3.800000 3.200000 3.200000     2.8
3   3 3.666667 3.333333 2.333333     3.0